Skip to content

DXGI-based VRAM detection for Windows GPU adapters - #3086

Merged
dbwiddis merged 5 commits into
oshi:masterfrom
dbwiddis:windows-vram
Mar 10, 2026
Merged

dbwiddis merged 5 commits into
oshi:masterfrom
dbwiddis:windows-vram

Conversation

@dbwiddis

@dbwiddis dbwiddis commented Mar 10, 2026 •

Copy link
Copy Markdown
Member

Full disclosure: code written by Claude Sonnet 4.6. 🤖

Problem

OSHI reported incorrect VRAM for modern discrete GPUs on Windows. For example, an Intel Arc A770
(16 GB) was reported as having ~2 GB. The root cause was that HardwareInformation.MemorySize is
a 32-bit registry value, and Windows writes the sentinel 0x7FFFF000 (~2 GiB) into it for any GPU
with more than 2 GiB of dedicated VRAM. The 64-bit HardwareInformation.qwMemorySize key is absent
on at least some Intel Arc driver installations, leaving no reliable registry fallback.

Solution

Use the DXGI API (IDXGIAdapter::GetDesc) as the primary VRAM source.
DXGI_ADAPTER_DESC.DedicatedVideoMemory is the authoritative Windows API value for dedicated GPU
memory and is not subject to any 32-bit cap.

Changes

oshi/driver/windows/DxgiAdapterInfo.java (new)
Plain immutable data class holding a DXGI adapter's description, PCI vendor ID, device ID, and
dedicatedVideoMemory. No native dependencies — fully unit-testable in isolation.

oshi/jna/platform/windows/WindowsDxgi.java (new)
Minimal JNA binding to dxgi.dll using the same vtable-based COMInvoker pattern already used
throughout OSHI. Implements:

  • queryAdapters() — calls CreateDXGIFactory then IDXGIFactory::EnumAdapters /
    IDXGIAdapter::GetDesc in a loop; fails gracefully to an empty list if dxgi.dll is unavailable
  • findMatch() — matches a DXGI adapter to a registry card by PCI vendor+device ID first, then by
    normalized adapter name as a fallback
  • registryValueToVram() — handles REG_QWORD (Long), REG_DWORD (Integer), and REG_BINARY
    (little-endian byte array)
  • normalizeName() — case-insensitive name normalization stripping (R)/(TM) and collapsing
    whitespace

oshi/hardware/platform/windows/WindowsGraphicsCard.java (modified)

  • Calls WindowsDxgi.queryAdapters() once before the registry enumeration loop
  • Reads MatchingDeviceId from each adapter's registry key and parses VEN_xxxx&DEV_xxxx to
    obtain PCI IDs for DXGI matching
  • Uses WindowsDxgi.findMatch() as the primary VRAM source
  • Falls back to HardwareInformation.qwMemorySize (64-bit) if DXGI has no match
  • Removes HardwareInformation.MemorySize (32-bit) entirely with an explanatory comment

oshi/driver/windows/WindowsDxgiTest.java (new)
13 tests covering: findMatch by vendor+device ID, multi-GPU tie-breaking, name fallback, no-match,
zero-ID fallback; normalizeName edge cases; registryValueToVram for all three registry types;
and a @EnabledOnOs(OS.WINDOWS) integration test that calls queryAdapters() against real hardware.

Fixes #2907

Summary by CodeRabbit

  • New Features

    • Windows DXGI-based GPU enumeration added for more accurate VRAM detection and PCI-ID matching.
  • Bug Fixes

    • VRAM reporting now prefers DXGI-sourced values with a 64-bit registry fallback to reduce incorrect memory reports.
  • Tests

    • Added unit and integration tests for adapter matching, name normalization, and VRAM conversions.
  • Documentation

    • Changelog updated to document the VRAM detection improvement.

@coderabbitai

coderabbitai Bot commented Mar 10, 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
  • ✅ Review completed - (🔄 Check again to review again)
📝 Walkthrough

Walkthrough

Adds DXGI-based VRAM detection on Windows: new immutable DxgiAdapterInfo, JNA binding WindowsDxgi to enumerate DXGI adapters and convert registry values, ParseUtil PCI ID extraction, updates to WindowsGraphicsCard to prefer DXGI (with registry qwMemorySize fallback), tests, and changelog entry.

Changes

Cohort / File(s) Summary
DXGI Adapter Value Class
oshi-core/src/main/java/oshi/driver/windows/DxgiAdapterInfo.java
New immutable value class storing adapter description, vendorId, deviceId, and dedicatedVideoMemory with getters and toString().
Windows DXGI Binding
oshi-core/src/main/java/oshi/jna/platform/windows/WindowsDxgi.java
New JNA wrapper to load dxgi.dll, enumerate adapters and their DXGI_ADAPTER_DESC, expose queryAdapters(), findMatch(), registryValueToVram(), and normalizeName().
Graphics Card VRAM Detection
oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java
Refactors VRAM sourcing to prefer DXGI adapter matches (adds MATCHING_DEVICE_ID constant, PCI ID parsing, prefetches DXGI adapters), delegates registry conversions to WindowsDxgi, and falls back to registry qwMemorySize or WMI when needed.
Parse Utility
oshi-core/src/main/java/oshi/util/ParseUtil.java
Adds parseDeviceIdToVendorProductIds(String) with a vendor/product ID pattern to extract VEN/DEV or VID/PID pairs and return as Pair<Integer,Integer>.
Unit & Integration Tests
oshi-core/src/test/java/oshi/driver/windows/WindowsDxgiTest.java, oshi-core/src/test/java/oshi/util/ParseUtilTest.java
New tests covering DXGI matching (ID and name), normalization, registry-to-VRAM conversions, ParseUtil PCI ID parsing, and a Windows-only integration test querying live DXGI adapters.
Changelog & Config
CHANGELOG.md, config/checkstyle-suppressions.xml
Adds changelog item for DXGI-based VRAM detection and adjusts a checkstyle suppression line range.

Sequence Diagram

sequenceDiagram
    participant WGC as WindowsGraphicsCard
    participant Parse as ParseUtil (PCI regex)
    participant WD as WindowsDxgi
    participant DXGI as dxgi.dll
    participant Reg as Windows Registry

    WGC->>WD: queryAdapters()
    WD->>DXGI: CreateDXGIFactory / EnumAdapters / GetDesc
    DXGI-->>WD: DxgiAdapterInfo(name,vendor,device, vram)
    WD-->>WGC: List<DxgiAdapterInfo>

    WGC->>Reg: Read MatchingDeviceId
    WGC->>Parse: parseDeviceIdToVendorProductIds(id)
    Parse-->>WGC: vendorId, deviceId (or null)

    WGC->>WD: findMatch(adapters, vendorId, deviceId, adapterName)
    alt DXGI match found
        WD-->>WGC: DxgiAdapterInfo with dedicatedVideoMemory
        WGC->>WGC: Use DXGI VRAM
    else No DXGI match
        WGC->>Reg: Read qwMemorySize (registry)
        WGC->>WD: registryValueToVram(registryValue)
        WD-->>WGC: vramBytes
        WGC->>WGC: Use registry VRAM or 0
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

🐇 I hopped through DXGI, sniffed vendor and device,
Matched names and PCI bits, fetched VRAM precise,
From registry bytes to DedicatedVideoMemory's light,
No more tiny surprises hiding out of sight,
Hop! — the rabbit cheers for frames tonight!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 47.22% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately and concisely describes the main change: introducing DXGI-based VRAM detection as the primary source for Windows GPU memory reporting.
Linked Issues check ✅ Passed The PR successfully implements all requirements from issue #2907: uses DXGI_ADAPTER_DESC.DedicatedVideoMemory as primary VRAM source, matches adapters by PCI IDs and normalized names, and falls back to qwMemorySize, directly addressing the incorrect 2GB reporting.
Out of Scope Changes check ✅ Passed All changes are directly related to implementing DXGI-based VRAM detection. Supporting changes (ParseUtil device ID parsing, checkstyle configuration updates) are necessary for the main objective and within scope.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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 Mar 10, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 85.38%. Comparing base (9ae3c62) to head (f65a8c0).
⚠️ Report is 1 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #3086      +/-   ##
==========================================
+ Coverage   84.82%   85.38%   +0.55%     
==========================================
  Files          33       33              
  Lines        1470     1478       +8     
  Branches      216      217       +1     
==========================================
+ Hits         1247     1262      +15     
+ Misses        124      118       -6     
+ Partials       99       98       -1     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 5

🤖 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/WindowsGraphicsCard.java`:
- Around line 190-193: WMI fallback currently ignores DXGI matches and always
uses ADAPTERRAM; update getGraphicsCardsFromWmi(...) to accept the dxgiAdapters
collection (passed from queryAdapters()), use the already-parsed PNPDEVICEID to
call WindowsDxgi.findMatch(dxgiAdapters, pnpDeviceId) and prefer that DXGI match
when present, and only fall back to WmiUtil.getUint32asLong(...,
VideoControllerProperty.ADAPTERRAM, ...) when WindowsDxgi.findMatch returns no
match.
- Around line 87-88: WindowsDxgi.findMatch() currently reuses the same
dxgiAdapters list for every registry entry, causing multiple GPUs with identical
PCI IDs to all reference the same DxgiAdapterInfo; modify the matching logic in
WindowsGraphicsCard so after locating a match via WindowsDxgi.findMatch(...) on
the dxgiAdapters list you remove or mark that DxgiAdapterInfo as consumed (e.g.,
remove by index or use an iterator) so each DxgiAdapterInfo is assigned at most
once; update any repeated lookup sites (the dxgiAdapters variable use around
WindowsGraphicsCard and the matching block referenced in lines ~123-125) to
consume the matched entry instead of leaving it available for subsequent
matches.
- Around line 129-131: The registry fallback currently treats vram == 0 as a
miss and overwrites a valid DXGI result; change the conditional in
WindowsGraphicsCard so the registry fallback only runs when there was no DXGI
match (i.e., vram is negative/not set) rather than when vram <= 0. Concretely,
replace the check using vram <= 0 with vram < 0 (or the sentinel used to
indicate "no match") around the Advapi32Util.registryValueExists/getValue block
that calls registryValueToVram, so legitimate DedicatedVideoMemory == 0 values
are preserved.

In `@oshi-core/src/test/java/oshi/driver/windows/WindowsDxgiTest.java`:
- Around line 56-65: The test currently passes using the exact adapter
description so it doesn't verify normalization; update the test in
WindowsDxgiTest to call WindowsDxgi.findMatch(...) with a variant of the adapter
name that only matches after normalization (for example remove "(R)" and "(TM)"
and/or collapse extra whitespace or use unicode ®/™), keeping the created
DxgiAdapterInfo("Intel(R) Arc(TM) A770 Graphics", ...) unchanged; ensure the
assertions still check that the returned DxgiAdapterInfo (from
WindowsDxgi.findMatch) is non-null and has the expected dedicated memory to
confirm normalization logic in findMatch is exercised.
- Around line 148-156: The test testQueryAdaptersOnWindows currently requires at
least one DXGI adapter and that VendorId > 0 which fails in DXGI-unavailable or
virtual environments; change the test in
WindowsDxgiTest.testQueryAdaptersOnWindows to accept an empty adapters list (do
not fail if adapters.isEmpty()), and only perform per-adapter assertions when
adapters are present: check a.getDescription() is not null and relax the vendor
check to allow non-negative IDs (vendorId >= 0) instead of strictly > 0; leave
the dedicated video memory assertion (>= 0) as-is. Ensure you reference
WindowsDxgi.queryAdapters() and DxgiAdapterInfo getters (getDescription,
getVendorId, getDedicatedVideoMemory) when locating the code to modify.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: d8b6eea2-ea8d-469b-a912-25c774435e86

📥 Commits

Reviewing files that changed from the base of the PR and between 9ae3c62 and e6f3db3.

📒 Files selected for processing (4)
  • oshi-core/src/main/java/oshi/driver/windows/DxgiAdapterInfo.java
  • oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java
  • oshi-core/src/main/java/oshi/jna/platform/windows/WindowsDxgi.java
  • oshi-core/src/test/java/oshi/driver/windows/WindowsDxgiTest.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: Analyze (java)
  • GitHub Check: Test JDK 25, macos-latest
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: Test JDK 25, windows-latest
🔇 Additional comments (2)
oshi-core/src/main/java/oshi/driver/windows/DxgiAdapterInfo.java (1)

17-77: Nice lightweight carrier type.

The immutable shape keeps the DXGI-to-hardware handoff simple and avoids accidental mutation during adapter matching.

oshi-core/src/main/java/oshi/jna/platform/windows/WindowsDxgi.java (1)

208-263: COM lifetime handling looks solid.

Releasing both adapter and factory pointers in finally blocks keeps the DXGI enumeration path safe even when EnumAdapters() or GetDesc() fail partway through.

@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

♻️ Duplicate comments (5)
oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java (3)

87-88: ⚠️ Potential issue | 🟡 Minor

Consume matched DXGI adapters once they're assigned.

WindowsDxgi.findMatch() returns the first vendor/device hit. Reusing the same dxgiAdapters list for every registry card lets multiple same-ID adapters bind to that one DxgiAdapterInfo, so one card's VRAM can be reused for its siblings.

Simple one-to-one matching
-        List<DxgiAdapterInfo> dxgiAdapters = WindowsDxgi.queryAdapters();
+        List<DxgiAdapterInfo> dxgiAdapters = new ArrayList<>(WindowsDxgi.queryAdapters());
...
                 DxgiAdapterInfo dxgiMatch = WindowsDxgi.findMatch(dxgiAdapters, pciVendorId, pciDeviceId, name);
                 if (dxgiMatch != null) {
                     vram = dxgiMatch.getDedicatedVideoMemory();
+                    dxgiAdapters.remove(dxgiMatch);
                 }

Also applies to: 123-125

🤖 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/WindowsGraphicsCard.java`
around lines 87 - 88, The code queries DXGI adapters once into dxgiAdapters
(WindowsDxgi.queryAdapters()) and then uses WindowsDxgi.findMatch() repeatedly,
which allows the same DxgiAdapterInfo to be matched to multiple registry cards;
change the matching loop in WindowsGraphicsCard so after a successful match (a
returned DxgiAdapterInfo) you consume it (e.g., remove it from the dxgiAdapters
list or mark it consumed) so each DxgiAdapterInfo is used one-to-one with a
registry card (refer to WindowsDxgi.findMatch(), DxgiAdapterInfo, and the loop
that constructs WindowsGraphicsCard objects).

190-193: ⚠️ Potential issue | 🟠 Major

This fallback path can still use DXGI.

This method already has NAME and parsed PNPDEVICEID, so dropping straight to ADAPTERRAM reintroduces the same 32-bit-capped VRAM source the PR is trying to avoid when registry enumeration fails. Pass the DXGI adapter list into getGraphicsCardsFromWmi() and only use AdapterRAM when WindowsDxgi.findMatch() cannot identify a match.

🤖 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/WindowsGraphicsCard.java`
around lines 190 - 193, The WMI fallback should prefer DXGI-derived VRAM when
possible: change getGraphicsCardsFromWmi(...) to accept the DXGI adapter list
(pass the list from the caller where NAME and parsed PNPDEVICEID are available),
call WindowsDxgi.findMatch(NAME, parsedPnpDeviceId, dxgiAdapters) and, if it
returns a match, use the DXGI VRAM values from that match instead of falling
straight to VideoControllerProperty.ADAPTERRAM; only call
WmiUtil.getUint32asLong(cards, VideoControllerProperty.ADAPTERRAM, index) when
WindowsDxgi.findMatch(...) yields no match.

121-131: ⚠️ Potential issue | 🟠 Major

Don't treat a matched 0 as a miss.

DedicatedVideoMemory == 0 is a valid DXGI result for UMA/integrated adapters. The vram <= 0 check overwrites that authoritative match with qwMemorySize.

Restrict the registry fallback to the no-match case
                 long vram = 0L;
                 DxgiAdapterInfo dxgiMatch = WindowsDxgi.findMatch(dxgiAdapters, pciVendorId, pciDeviceId, name);
                 if (dxgiMatch != null) {
                     vram = dxgiMatch.getDedicatedVideoMemory();
-                }
-
-                // Fallback: 64-bit registry value qwMemorySize
-                if (vram <= 0 && Advapi32Util.registryValueExists(WinReg.HKEY_LOCAL_MACHINE, fullKey, QW_MEMORY_SIZE)) {
+                } else if (Advapi32Util.registryValueExists(WinReg.HKEY_LOCAL_MACHINE, fullKey, QW_MEMORY_SIZE)) {
                     Object regValue = Advapi32Util.registryGetValue(WinReg.HKEY_LOCAL_MACHINE, fullKey, QW_MEMORY_SIZE);
                     vram = registryValueToVram(regValue);
                 }
🤖 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/WindowsGraphicsCard.java`
around lines 121 - 131, The code currently treats a DXGI match with
getDedicatedVideoMemory() == 0 as a miss and falls back to the registry; change
this so the registry fallback only runs when WindowsDxgi.findMatch(...) returns
null. In WindowsGraphicsCard, after calling WindowsDxgi.findMatch(dxgiAdapters,
pciVendorId, pciDeviceId, name) and assigning vram =
dxgiMatch.getDedicatedVideoMemory(), do not enter the
Advapi32Util.registryValueExists / registryGetValue path when dxgiMatch != null
(even if vram == 0); only call Advapi32Util.registryValueExists and
registryValueToVram when dxgiMatch == null to preserve authoritative 0 values
from DxgiAdapterInfo.
oshi-core/src/test/java/oshi/driver/windows/WindowsDxgiTest.java (2)

56-65: ⚠️ Potential issue | 🟡 Minor

Use an input that only matches after normalization.

Line 63 still passes the exact adapter description, so this test would pass even if findMatch() stopped calling normalizeName(). Feed it a variant that only matches after stripping (R)/(TM) or collapsing whitespace.

Minimal change
-        DxgiAdapterInfo match = WindowsDxgi.findMatch(adapters, 0, 0, "Intel(R) Arc(TM) A770 Graphics");
+        DxgiAdapterInfo match = WindowsDxgi.findMatch(adapters, 0, 0, "Intel Arc A770   Graphics");
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@oshi-core/src/test/java/oshi/driver/windows/WindowsDxgiTest.java` around
lines 56 - 65, The test testFindMatchByNormalizedName currently passes the exact
adapter description so it doesn't verify normalization; update the input passed
to WindowsDxgi.findMatch to a variant that only matches after normalization
(e.g., remove or alter the "(R)" and "(TM)" markers or change spacing) while
keeping the expected DxgiAdapterInfo with name "Intel(R) Arc(TM) A770 Graphics"
and its dedicatedVideoMemory; this ensures WindowsDxgi.findMatch (and any
normalizeName logic) is actually exercised when matching the DxgiAdapterInfo
instance.

146-156: ⚠️ Potential issue | 🟠 Major

Make the Windows integration test tolerate valid empty DXGI results.

WindowsDxgi.queryAdapters() is explicitly allowed to return an empty list, so asserting size() > 0 makes this test fail on valid Windows environments. VendorId > 0 is also too strict for software or virtual adapters.

One way to keep the test stable
-        // On any Windows system with a display, there should be at least one adapter
-        assertThat("Should find at least one DXGI adapter", adapters.size(), is(greaterThan(0)));
         for (DxgiAdapterInfo a : adapters) {
             assertThat("Description should not be null", a.getDescription(), is(notNullValue()));
-            assertThat("VendorId should be positive", a.getVendorId(), is(greaterThan(0)));
+            assertThat("VendorId should be non-negative", a.getVendorId(), is(greaterThanOrEqualTo(0)));
             assertThat("DedicatedVideoMemory should be non-negative", a.getDedicatedVideoMemory(),
                     is(greaterThanOrEqualTo(0L)));
         }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@oshi-core/src/test/java/oshi/driver/windows/WindowsDxgiTest.java` around
lines 146 - 156, Remove the hard failure for empty results in
testQueryAdaptersOnWindows by deleting the assert that adapters.size() > 0
(allow WindowsDxgi.queryAdapters() to return an empty list), and relax the
vendor ID check in the per-adapter assertions: change the VendorId expectation
in the DxgiAdapterInfo assertions from greaterThan(0) to
greaterThanOrEqualTo(0). Keep the existing checks for description not null and
dedicatedVideoMemory >= 0; the for-loop over adapters can remain as-is (it will
simply not execute if the list is empty).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@CHANGELOG.md`:
- Around line 7-8: The changelog entry currently splits the PR/title and the
author attribution into two list items; merge them into a single bullet by
folding the attribution line into the same bullet as the PR entry (i.e., change
the two lines "* [`#3086`](https://github.com/oshi/oshi/pull/3086): DXGI-based
VRAM detection for Windows GPU adapters" and " -
[`@claude`](https://github.com/claude), [`@dbwiddis`](https://github.com/dbwiddis)."
into one bullet such as "* [`#3086`](https://github.com/oshi/oshi/pull/3086):
DXGI-based VRAM detection for Windows GPU adapters —
[`@claude`](https://github.com/claude),
[`@dbwiddis`](https://github.com/dbwiddis).")

In `@oshi-core/src/main/java/oshi/jna/platform/windows/WindowsDxgi.java`:
- Around line 70-71: The static DxgiLib.INSTANCE (in interface DxgiLib) can
cause NoClassDefFoundError after a failed Native.load; update the code paths
that access DxgiLib.INSTANCE (notably in queryAdapters() and the similar block
around lines 213–217) to catch NoClassDefFoundError in addition to
UnsatisfiedLinkError so the method returns the documented empty list fallback;
locate uses of DxgiLib.INSTANCE in WindowsDxgi (and any helper methods that
touch it) and wrap the access in a try-catch that handles both
UnsatisfiedLinkError and NoClassDefFoundError, logging as before and returning
the empty list.

---

Duplicate comments:
In
`@oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java`:
- Around line 87-88: The code queries DXGI adapters once into dxgiAdapters
(WindowsDxgi.queryAdapters()) and then uses WindowsDxgi.findMatch() repeatedly,
which allows the same DxgiAdapterInfo to be matched to multiple registry cards;
change the matching loop in WindowsGraphicsCard so after a successful match (a
returned DxgiAdapterInfo) you consume it (e.g., remove it from the dxgiAdapters
list or mark it consumed) so each DxgiAdapterInfo is used one-to-one with a
registry card (refer to WindowsDxgi.findMatch(), DxgiAdapterInfo, and the loop
that constructs WindowsGraphicsCard objects).
- Around line 190-193: The WMI fallback should prefer DXGI-derived VRAM when
possible: change getGraphicsCardsFromWmi(...) to accept the DXGI adapter list
(pass the list from the caller where NAME and parsed PNPDEVICEID are available),
call WindowsDxgi.findMatch(NAME, parsedPnpDeviceId, dxgiAdapters) and, if it
returns a match, use the DXGI VRAM values from that match instead of falling
straight to VideoControllerProperty.ADAPTERRAM; only call
WmiUtil.getUint32asLong(cards, VideoControllerProperty.ADAPTERRAM, index) when
WindowsDxgi.findMatch(...) yields no match.
- Around line 121-131: The code currently treats a DXGI match with
getDedicatedVideoMemory() == 0 as a miss and falls back to the registry; change
this so the registry fallback only runs when WindowsDxgi.findMatch(...) returns
null. In WindowsGraphicsCard, after calling WindowsDxgi.findMatch(dxgiAdapters,
pciVendorId, pciDeviceId, name) and assigning vram =
dxgiMatch.getDedicatedVideoMemory(), do not enter the
Advapi32Util.registryValueExists / registryGetValue path when dxgiMatch != null
(even if vram == 0); only call Advapi32Util.registryValueExists and
registryValueToVram when dxgiMatch == null to preserve authoritative 0 values
from DxgiAdapterInfo.

In `@oshi-core/src/test/java/oshi/driver/windows/WindowsDxgiTest.java`:
- Around line 56-65: The test testFindMatchByNormalizedName currently passes the
exact adapter description so it doesn't verify normalization; update the input
passed to WindowsDxgi.findMatch to a variant that only matches after
normalization (e.g., remove or alter the "(R)" and "(TM)" markers or change
spacing) while keeping the expected DxgiAdapterInfo with name "Intel(R) Arc(TM)
A770 Graphics" and its dedicatedVideoMemory; this ensures WindowsDxgi.findMatch
(and any normalizeName logic) is actually exercised when matching the
DxgiAdapterInfo instance.
- Around line 146-156: Remove the hard failure for empty results in
testQueryAdaptersOnWindows by deleting the assert that adapters.size() > 0
(allow WindowsDxgi.queryAdapters() to return an empty list), and relax the
vendor ID check in the per-adapter assertions: change the VendorId expectation
in the DxgiAdapterInfo assertions from greaterThan(0) to
greaterThanOrEqualTo(0). Keep the existing checks for description not null and
dedicatedVideoMemory >= 0; the for-loop over adapters can remain as-is (it will
simply not execute if the list is empty).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 1642ed1f-c4e4-4ebd-a7e0-e6bd54e7b817

📥 Commits

Reviewing files that changed from the base of the PR and between e6f3db3 and 6d20b92.

📒 Files selected for processing (5)
  • CHANGELOG.md
  • oshi-core/src/main/java/oshi/driver/windows/DxgiAdapterInfo.java
  • oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java
  • oshi-core/src/main/java/oshi/jna/platform/windows/WindowsDxgi.java
  • oshi-core/src/test/java/oshi/driver/windows/WindowsDxgiTest.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

Comment thread CHANGELOG.md Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

297-317: Consider adding defensive null check for adapters parameter.

If findMatch is called with a null list, the for-each loops will throw NullPointerException. While queryAdapters() never returns null, as a public API method, a defensive check would make the contract clearer.

💡 Suggested defensive check
 public static DxgiAdapterInfo findMatch(List<DxgiAdapterInfo> adapters, int vendorId, int deviceId,
         String adapterName) {
+    if (adapters == null || adapters.isEmpty()) {
+        return null;
+    }
     // Priority 1: vendor + device ID
     if (vendorId != 0 && deviceId != 0) {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@oshi-core/src/main/java/oshi/jna/platform/windows/WindowsDxgi.java` around
lines 297 - 317, The method findMatch(List<DxgiAdapterInfo> adapters, int
vendorId, int deviceId, String adapterName) can NPE if adapters is null; add a
defensive null check at the top (e.g., if adapters == null || adapters.isEmpty()
return null) so the for-each loops over adapters never throw; update only
findMatch and keep behavior otherwise (still prefer vendor/device match first,
then normalized name using normalizeName); this makes the public API robust even
if callers (outside queryAdapters()) pass null.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@oshi-core/src/main/java/oshi/jna/platform/windows/WindowsDxgi.java`:
- Around line 297-317: The method findMatch(List<DxgiAdapterInfo> adapters, int
vendorId, int deviceId, String adapterName) can NPE if adapters is null; add a
defensive null check at the top (e.g., if adapters == null || adapters.isEmpty()
return null) so the for-each loops over adapters never throw; update only
findMatch and keep behavior otherwise (still prefer vendor/device match first,
then normalized name using normalizeName); this makes the public API robust even
if callers (outside queryAdapters()) pass null.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: e3f225f6-28d2-4241-aab1-7606cf7aac12

📥 Commits

Reviewing files that changed from the base of the PR and between 2f3b236 and 61ac741.

📒 Files selected for processing (4)
  • CHANGELOG.md
  • oshi-core/src/main/java/oshi/driver/windows/DxgiAdapterInfo.java
  • oshi-core/src/main/java/oshi/jna/platform/windows/WindowsDxgi.java
  • oshi-core/src/test/java/oshi/driver/windows/WindowsDxgiTest.java
🚧 Files skipped from review as they are similar to previous changes (2)
  • oshi-core/src/main/java/oshi/driver/windows/DxgiAdapterInfo.java
  • oshi-core/src/test/java/oshi/driver/windows/WindowsDxgiTest.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, windows-latest
  • GitHub Check: Test JDK 25, macos-latest
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: Analyze (java)
🔇 Additional comments (8)
CHANGELOG.md (1)

6-8: Looks good.

This now uses a single bullet and matches the surrounding changelog style.

oshi-core/src/main/java/oshi/jna/platform/windows/WindowsDxgi.java (7)

27-61: Well-documented utility class with clear DXGI API explanation.

The vtable layout documentation (lines 38-44) is valuable for maintainers unfamiliar with DXGI COM interfaces. Good use of private constructor for the utility class pattern.


83-96: Past review concern properly addressed with static initialization guard.

The static initializer catches both UnsatisfiedLinkError (first failure) and NoClassDefFoundError (subsequent references to erroneous class), setting DXGI_AVAILABLE accordingly. The flag check in queryAdapters() (line 224) prevents further access attempts to DxgiLib.INSTANCE when the library is unavailable.

This is a cleaner solution than catching at every call site.


119-133: LGTM!

The structure mapping correctly uses SIZE_T for pointer-sized memory fields and properly decomposes LUID into two 32-bit parts to match the Windows definition.


158-208: COM vtable wrappers are correctly implemented.

The vtable slot indices match the documented inheritance chain (IUnknown → IDXGIObject → IDXGIFactory/IDXGIAdapter). The use of COMInvoker._invokeNativeObject and _invokeNativeInt follows standard JNA COM patterns.


223-275: Solid resource management and error handling in queryAdapters().

The nested try-finally blocks (lines 254-269 for adapter, lines 239-273 for factory) ensure COM objects are released even when exceptions occur. The explicit desc.read() call on line 258 is essential since JNA doesn't automatically sync structure fields from native memory after the call.


329-345: LGTM!

The registryValueToVram correctly handles all three registry types:

  • Long (REG_QWORD) returned as-is
  • Integer (REG_DWORD) converted using Integer.toUnsignedLong() to preserve unsigned semantics
  • byte[] (REG_BINARY) interpreted as little-endian, correctly limited to 8 bytes

The little-endian conversion loop reads from highest to lowest index, placing each byte progressively into more significant positions.


353-359: LGTM!

The normalization using Locale.ROOT ensures consistent lowercase behavior regardless of the JVM's default locale—important for fuzzy matching of adapter names that may contain locale-sensitive characters.

@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/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java (1)

171-173: Reuse the first DXGI enumeration in the WMI fallback.

This overload does a second WindowsDxgi.queryAdapters() even though getGraphicsCards() already fetched adapters. On the fallback path, that can produce a different match set than the registry pass and needlessly throws away the first DXGI enumeration. Prefer passing the existing dxgiAdapters list through instead of re-querying here.

🤖 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/WindowsGraphicsCard.java`
around lines 171 - 173, The no-arg getGraphicsCardsFromWmi() currently re-calls
WindowsDxgi.queryAdapters(), discarding the initial DXGI enumeration; change
callers to pass the existing dxgiAdapters list into
getGraphicsCardsFromWmi(List<...>) and implement/keep an overload that accepts a
List parameter so the method uses the provided dxgiAdapters instead of calling
WindowsDxgi.queryAdapters() again (update places that currently call the no-arg
getGraphicsCardsFromWmi() to pass the dxgiAdapters variable, and remove the
internal new ArrayList<>(WindowsDxgi.queryAdapters()) re-query).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@config/checkstyle-suppressions.xml`:
- Line 9: The suppression range in config/checkstyle-suppressions.xml currently
only covers lines 115-135 for ParseUtil.java, which misses the mixed-case
constants HZ, KHZ, MHZ, GHZ, THZ, PHZ defined at lines 108-113; update the
<suppress> entry for files="ParseUtil\.java" to cover the earlier lines (e.g.,
change lines="115-135" to lines="108-135") or add a second <suppress> for
files="ParseUtil\.java" with lines="108-113" so the ConstantName check is
suppressed for those constants HZ/KHZ/MHZ/GHZ/THZ/PHZ as well.

---

Nitpick comments:
In
`@oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java`:
- Around line 171-173: The no-arg getGraphicsCardsFromWmi() currently re-calls
WindowsDxgi.queryAdapters(), discarding the initial DXGI enumeration; change
callers to pass the existing dxgiAdapters list into
getGraphicsCardsFromWmi(List<...>) and implement/keep an overload that accepts a
List parameter so the method uses the provided dxgiAdapters instead of calling
WindowsDxgi.queryAdapters() again (update places that currently call the no-arg
getGraphicsCardsFromWmi() to pass the dxgiAdapters variable, and remove the
internal new ArrayList<>(WindowsDxgi.queryAdapters()) re-query).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: a96c9f02-6691-48ff-a4f2-4a688383c6f9

📥 Commits

Reviewing files that changed from the base of the PR and between 61ac741 and 91317f2.

📒 Files selected for processing (5)
  • CHANGELOG.md
  • config/checkstyle-suppressions.xml
  • oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java
  • oshi-core/src/main/java/oshi/util/ParseUtil.java
  • oshi-core/src/test/java/oshi/util/ParseUtilTest.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). (4)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 25, windows-latest
  • GitHub Check: Test JDK 25, macos-latest
  • GitHub Check: Analyze (java)
🔇 Additional comments (3)
oshi-core/src/main/java/oshi/util/ParseUtil.java (1)

87-93: The new DeviceID parser looks solid.

It cleanly covers both full PNPDeviceID strings and bare MatchingDeviceId / VID_xxxx&PID_xxxx inputs while keeping the existing null-on-no-match behavior consistent with the rest of ParseUtil.

Also applies to: 1032-1053

oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java (1)

83-140: DXGI-first matching and fallback flow looks correct now.

The one-to-one adapter consumption, the separate “matched vs. VRAM value” handling, and the WMI-side DXGI reuse all line up well with the Arc A770 regression this PR is fixing.

Also applies to: 198-212

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

545-573: Good coverage for the new parser.

These cases exercise the exact Windows identifier shapes this PR depends on, especially the bare MatchingDeviceId path that the existing serial parser could not handle.

Comment thread config/checkstyle-suppressions.xml Resolved
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.

Reported VRAM for an Arc A770 on Windows comes back as 2GB instead of 16GB.

1 participant