Skip to content

Share the Mac USB IOKit walk behind backend-neutral registry views - #3449

Merged
dbwiddis merged 3 commits into
oshi:masterfrom
dbwiddis:dedup-mac-usb-iokit
Jul 12, 2026
Merged

dbwiddis merged 3 commits into
oshi:masterfrom
dbwiddis:dedup-mac-usb-iokit

Conversation

@dbwiddis

@dbwiddis dbwiddis commented Jul 12, 2026 •

Copy link
Copy Markdown
Member

Summary

Part of the cross-OS USB consistency/dedup audit (follows the Linux udev PR #3448). MacUsbDeviceJNA and MacUsbDeviceFFM each carried a verbatim copy of the IORegistry walk — enumerate the root's IOUSB-plane children, resolve each device's controller via the IOService plane, look up the controller's vendor/product IDs by location-matching, and recurse the device subtree into lookup maps. The two differed only in the IOKit binding types (com.sun.jna.platform.mac.IOKit vs oshi.ffm.platform.mac.IOKit) and release style.

Changes

  • MacUsbDevice (oshi-common) gains two nested backend-neutral view interfaces, RegistryEntry / RegistryIterator, and now holds the entire walk once (getUsbDevices(RegistryEntry root) + addDeviceAndChildrenToMaps + the tree build), operating only on those views. The class is now final; the old no-arg "so subclasses compile" constructor is gone.
  • MacUsbDeviceJNA / MacUsbDeviceFFM shrink to thin adapters over their native IORegistryEntry/IOIterator, plus the one genuinely backend-specific piece — lookupControllerVidPid(), which encapsulates the CoreFoundation dictionary matching. Neither extends MacUsbDevice anymore.
  • HALs untouched — the getUsbDevices() entry point is unchanged.

The ~90 lines of identical walk/map-building that were duplicated across the two backends are now single-source; the only per-backend code left is native-binding delegation and the CF-matching hook, which can't be shared.

Behavior

No user-facing change. Validated on Apple Silicon: NativeComparisonTest.usbDevices() — a recursive deep-equal of the JNA and FFM device trees — passes.

Design note

Mac's IOKit is a tree-walk API (parent/children are live handles), so a view interface that lets the shared code drive the traversal is the right fit. This intentionally differs from the Linux udev PR (#3448), whose flat-enumeration API is better served by a carrier record. A follow-up will hoist the shared map/tree builder into AbstractUsbDevice so all platforms — regardless of producer shape — feed one tree-building consumer.

Testing

  • spotless / checkstyle / forbiddenapis / javadoc: clean
  • Clean full-reactor install: BUILD SUCCESS, 0 tests failed
  • NativeComparisonTest.usbDevices() (JNA vs FFM deep-equal): passes on macOS/Apple Silicon

Summary by CodeRabbit

  • Bug Fixes
    • Improved macOS USB device discovery and enumeration reliability.
    • Enhanced USB topology results with better hub/parent/controller relationships.
    • More consistent vendor/product and serial identification (including improved formatting and fallbacks).
    • Improved cleanup of native registry resources during enumeration.
  • Refactor
    • Unified macOS USB enumeration behavior across runtime implementations for more consistent output.

MacUsbDeviceJNA and MacUsbDeviceFFM each carried a verbatim copy of the
IORegistry walk (enumerate root's IOUSB children, resolve each device's
controller, recurse the subtree into lookup maps) — differing only in the
IOKit binding types and release style.

Introduce RegistryEntry/RegistryIterator view interfaces (nested in
MacUsbDevice); the base now holds the entire walk once, operating only on
those views. Each backend is reduced to a thin adapter over its native
IORegistryEntry/IOIterator plus lookupControllerVidPid(), which
encapsulates the backend-specific CoreFoundation dictionary matching.
MacUsbDevice is now final; the backends no longer extend it.

No user-facing change: NativeComparisonTest.usbDevices() (JNA vs FFM
recursive deep-equal) passes on Apple Silicon.
@coderabbitai

coderabbitai Bot commented Jul 12, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 2f20d375-34ac-4028-a99d-74591ecbf87b

📥 Commits

Reviewing files that changed from the base of the PR and between 80e4f6f and a204ade.

📒 Files selected for processing (1)
  • oshi-common/src/main/java/oshi/hardware/common/platform/mac/MacUsbDevice.java
🚧 Files skipped from review as they are similar to previous changes (1)
  • oshi-common/src/main/java/oshi/hardware/common/platform/mac/MacUsbDevice.java
📜 Recent review details
⏰ Context from checks skipped due to timeout. (15)
  • GitHub Check: CodeRabbit
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 26, windows-latest
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 26, macos-latest
  • GitHub Check: Test JDK 25, ubuntu-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 26, ubuntu-latest
  • GitHub Check: Test JDK 25, OpenBSD (+ JNA==FFM)
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: Test JDK 25, FreeBSD (+ JNA==FFM)
  • GitHub Check: Test JDK 25, OpenIndiana (+ JNA==FFM)
  • GitHub Check: Analyze (java)

📝 Walkthrough

Walkthrough

macOS USB enumeration is centralized in MacUsbDevice, which now exposes backend-neutral registry interfaces. JNA and FFM implementations provide adapters for registry access, iteration, controller identification, and native resource release.

Changes

macOS USB enumeration

Layer / File(s) Summary
Shared registry traversal and tree construction
oshi-common/src/main/java/oshi/hardware/common/platform/mac/MacUsbDevice.java
MacUsbDevice is finalized, defines registry interfaces, traverses USB and service planes, builds controller-scoped maps, recursively assembles device trees, and releases registry resources.
FFM registry adapter
oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacUsbDeviceFFM.java
FFM enumeration delegates to shared traversal through registry-entry and iterator adapters, including controller VID/PID lookup.
JNA registry adapter
oshi-core/src/main/java/oshi/hardware/platform/mac/MacUsbDeviceJNA.java
JNA enumeration delegates to shared traversal through registry-entry and iterator adapters, including controller VID/PID lookup and native resource release.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant MacUsbDeviceJNA
  participant JnaRegistryEntry
  participant MacUsbDevice
  participant JnaRegistryIterator
  MacUsbDeviceJNA->>JnaRegistryEntry: wrap IOKit root entry
  MacUsbDeviceJNA->>MacUsbDevice: call getUsbDevices(root)
  MacUsbDevice->>JnaRegistryEntry: traverse USB and service registry planes
  JnaRegistryEntry->>JnaRegistryIterator: create child iterator
  JnaRegistryIterator-->>MacUsbDevice: return wrapped registry entries
  MacUsbDevice->>JnaRegistryEntry: read properties and controller VID/PID
  MacUsbDevice-->>MacUsbDeviceJNA: return USB device tree
Loading

Poem

A bunny hops through USB trees,
With adapters rustling in the breeze.
JNA and FFM share the way,
Devices bloom in maps today.
“Release those iterators!” squeaks the hare.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 36.96% 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 clearly describes the main refactor: sharing the macOS USB IOKit walk behind backend-neutral registry views.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@codecov

codecov Bot commented Jul 12, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 74.28571% with 18 lines in your changes missing coverage. Please review.
✅ Project coverage is 74.48%. Comparing base (ee5c0ca) to head (a204ade).
⚠️ Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
...shi/hardware/common/platform/mac/MacUsbDevice.java 74.28% 8 Missing and 10 partials ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master    #3449      +/-   ##
============================================
- Coverage     74.54%   74.48%   -0.06%     
  Complexity       76       76              
============================================
  Files           583      583              
  Lines         21934    22001      +67     
  Branches       3671     3686      +15     
============================================
+ Hits          16350    16387      +37     
- Misses         3555     3568      +13     
- Partials       2029     2046      +17     
Flag Coverage Δ
freebsd 26.77% <0.00%> (-0.08%) ⬇️
linux 31.40% <0.00%> (-0.10%) ⬇️
macos 31.94% <74.28%> (+0.09%) ⬆️
openbsd 26.27% <0.00%> (-0.09%) ⬇️
solaris 28.30% <0.00%> (-0.09%) ⬇️
windows 39.71% <0.00%> (-0.14%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 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: 1

🧹 Nitpick comments (1)
oshi-common/src/main/java/oshi/hardware/common/platform/mac/MacUsbDevice.java (1)

143-160: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Consider resolving controller VID/PID once per controller.

lookupControllerVidPid() performs a native CoreFoundation matching-service enumeration and is invoked for every top-level device (Line 149). If multiple root devices share a controller, this repeats the expensive lookup and re-writes identical map entries. Guarding on usbControllers before the controller work would avoid the redundancy.

♻️ Proposed guard
                 if (controller != null) {
                     id = controller.getRegistryEntryID();
-                    nameMap.put(id, controller.getName());
-                    // The only controller info in the registry is its locationID; use it to find the matching PCI
-                    // device and pull vendor/product IDs.
-                    String[] vidPid = controller.lookupControllerVidPid();
-                    if (vidPid[0] != null) {
-                        vendorIdMap.put(id, vidPid[0]);
-                    }
-                    if (vidPid[1] != null) {
-                        productIdMap.put(id, vidPid[1]);
-                    }
+                    if (!usbControllers.contains(id)) {
+                        nameMap.put(id, controller.getName());
+                        // The only controller info in the registry is its locationID; use it to find the matching
+                        // PCI device and pull vendor/product IDs.
+                        String[] vidPid = controller.lookupControllerVidPid();
+                        if (vidPid[0] != null) {
+                            vendorIdMap.put(id, vidPid[0]);
+                        }
+                        if (vidPid[1] != null) {
+                            productIdMap.put(id, vidPid[1]);
+                        }
+                    }
                     controller.release();
                 }

Please confirm whether root's IOUSB-plane children can map to the same controller before adopting this.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@oshi-common/src/main/java/oshi/hardware/common/platform/mac/MacUsbDevice.java`
around lines 143 - 160, Update the controller-processing block in MacUsbDevice
so lookupControllerVidPid(), controller name retrieval, and the
vendorIdMap/productIdMap writes occur only when the controller’s registry ID is
not already present in usbControllers. Preserve the existing anonymous id 0L
behavior for null controllers, and ensure repeated devices sharing a controller
still add their controller ID without repeating the native lookup.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@oshi-common/src/main/java/oshi/hardware/common/platform/mac/MacUsbDevice.java`:
- Around line 195-199: Update the USB name handling in MacUsbDevice’s
device-walk logic and getDeviceAndChildren so RegistryEntry.getName() and
controller.getName() are checked for null before trimming or storing. Preserve
null/empty names as appropriate so getDeviceAndChildren can use its vendorId +
":" + productId fallback, and ensure a null name cannot abort traversal before
native handles are released.

---

Nitpick comments:
In
`@oshi-common/src/main/java/oshi/hardware/common/platform/mac/MacUsbDevice.java`:
- Around line 143-160: Update the controller-processing block in MacUsbDevice so
lookupControllerVidPid(), controller name retrieval, and the
vendorIdMap/productIdMap writes occur only when the controller’s registry ID is
not already present in usbControllers. Preserve the existing anonymous id 0L
behavior for null controllers, and ensure repeated devices sharing a controller
still add their controller ID without repeating the native lookup.
🪄 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: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 07aa3d01-9977-4bf7-a1c6-43115aa3792b

📥 Commits

Reviewing files that changed from the base of the PR and between ee5c0ca and 71abb38.

📒 Files selected for processing (3)
  • oshi-common/src/main/java/oshi/hardware/common/platform/mac/MacUsbDevice.java
  • oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacUsbDeviceFFM.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacUsbDeviceJNA.java
📜 Review details
⏰ Context from checks skipped due to timeout. (15)
  • GitHub Check: CodeRabbit
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 26, macos-latest
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 26, windows-latest
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Test JDK 25, ubuntu-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 26, ubuntu-latest
  • GitHub Check: Test JDK 25, FreeBSD (+ JNA==FFM)
  • GitHub Check: Test JDK 25, OpenBSD (+ JNA==FFM)
  • GitHub Check: Test JDK 25, OpenIndiana (+ JNA==FFM)
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: Analyze (java)
🧰 Additional context used
🧠 Learnings (4)
📚 Learning: 2026-07-06T19:25:59.225Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3432
File: oshi-common/src/main/java/oshi/util/ExceptionUtil.java:26-56
Timestamp: 2026-07-06T19:25:59.225Z
Learning: In this repo’s SLF4J 1.x-compatible logging code, do not flag cases where a logger call uses SLF4J 1.6+ implicit-cause handling—e.g., `log.error("...{}", value, t)` (or similar with a single `{}` placeholder) where `t` is passed as the final/trailing argument. SLF4J will attach `t` as the log event’s cause with the full stack trace; this is equivalent to SLF4J 2.x’s fluent `atLevel(...).setCause(t).log(...)` and is intentionally used to preserve SLF4J 1.x runtime compatibility.

Applied to files:

  • oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacUsbDeviceFFM.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacUsbDeviceJNA.java
  • oshi-common/src/main/java/oshi/hardware/common/platform/mac/MacUsbDevice.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/MacUsbDeviceJNA.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`, treat `id = 0L` as an intentional sentinel when `device.getParentEntry(IOSERVICE)` returns null. This catch-all value groups devices whose controller cannot be identified (even though that edge case is expected not to occur). Do not review it as a bug, do not suggest skipping those devices, and do not propose moving them to the top level without controller context—this design explicitly avoids silently dropping orphaned devices and preserves controller-grouping behavior.

Applied to files:

  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacUsbDeviceJNA.java
📚 Learning: 2026-04-12T19:22:09.716Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3149
File: oshi-common/src/main/java/oshi/hardware/common/platform/mac/MacCentralProcessor.java:159-163
Timestamp: 2026-04-12T19:22:09.716Z
Learning: When reviewing OSHI hardware platform code that uses or implements `CentralProcessor`/`PhysicalProcessor.getEfficiency()`, remember the API’s counterintuitive semantics: a *higher* efficiency-class value indicates *greater performance* (lower efficiency). P-cores/“performance cores” should therefore have higher values (e.g., 1) than E-cores/“efficiency cores” (e.g., 0), as documented in the `CentralProcessor` Javadoc. Do not flag code as incorrect solely because ARM_P_CORES or Intel P-cores are assigned higher efficiency values.

Applied to files:

  • oshi-common/src/main/java/oshi/hardware/common/platform/mac/MacUsbDevice.java
🔇 Additional comments (3)
oshi-common/src/main/java/oshi/hardware/common/platform/mac/MacUsbDevice.java (1)

42-114: LGTM!

oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacUsbDeviceFFM.java (1)

44-182: LGTM!

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

40-179: LGTM!

dbwiddis added 2 commits July 11, 2026 19:57
A null name from getName() (e.g. a nameless FFM registry entry) would NPE on
.trim() mid-walk, aborting traversal before the native handles were released,
and storing a null controller name defeated getDeviceAndChildren's vid:pid
fallback (getOrDefault only substitutes for absent keys, not null values).
Skip null names at both sites; pre-existing, carried over from the original
per-backend walks.
A controller shared by multiple root devices was re-read once per device,
re-running the deterministic getName() and the lookupControllerVidPid()
CoreFoundation dictionary match and overwriting identical map entries. Gate
those reads on the controller id not yet being in usbControllers; the id is
still registered and the native handle still released every iteration, so the
resulting tree is unchanged.
@dbwiddis
dbwiddis merged commit aed7bfa into oshi:master Jul 12, 2026
19 checks passed
@dbwiddis
dbwiddis deleted the dedup-mac-usb-iokit branch July 12, 2026 03:53
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