Repository navigation
Share the Mac USB IOKit walk behind backend-neutral registry views - #3449
Conversation
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.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📜 Recent review details⏰ Context from checks skipped due to timeout. (15)
📝 WalkthroughWalkthroughmacOS USB enumeration is centralized in ChangesmacOS USB enumeration
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
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## master #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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
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 winConsider 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 onusbControllersbefore 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
📒 Files selected for processing (3)
oshi-common/src/main/java/oshi/hardware/common/platform/mac/MacUsbDevice.javaoshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacUsbDeviceFFM.javaoshi-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.javaoshi-core/src/main/java/oshi/hardware/platform/mac/MacUsbDeviceJNA.javaoshi-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!
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.
Summary
Part of the cross-OS USB consistency/dedup audit (follows the Linux udev PR #3448).
MacUsbDeviceJNAandMacUsbDeviceFFMeach 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.IOKitvsoshi.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 nowfinal; the old no-arg "so subclasses compile" constructor is gone.MacUsbDeviceJNA/MacUsbDeviceFFMshrink to thin adapters over their nativeIORegistryEntry/IOIterator, plus the one genuinely backend-specific piece —lookupControllerVidPid(), which encapsulates the CoreFoundation dictionary matching. Neither extendsMacUsbDeviceanymore.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
AbstractUsbDeviceso all platforms — regardless of producer shape — feed one tree-building consumer.Testing
install: BUILD SUCCESS, 0 tests failedNativeComparisonTest.usbDevices()(JNA vs FFM deep-equal): passes on macOS/Apple SiliconSummary by CodeRabbit