[Questions] Attempting to Interact Device Watcher With COM

Open
#2,564 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
36/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Active
Tech stack
zig
Domain
backend

Research direction

Start by comparing the DeviceWatcher and MidiEndpointDeviceWatcher event registration behavior described in the issue, especially the TypedEventHandler vtable and QueryInterface handling for IID_INoMarshal. The crash occurs at addAdded() in the Zig experiment; determine whether the COM callback contract differs and document a working way to register the handler. Done means the cause of the crash and the required interface behavior are clear.

Written by the indexing model from the issue text.

Description

Pri3

TLDR:

Despite the complicated problem in the story, my question is simple:

  • have anyone successfully used Windows.Devices.Enumeration.DeviceWatcher with language that don't support C++/WinRT and with COM interface (For example, pure C)?
  • Is here fundamental design difference for TypedEventHandler between Windows.Devices.Enumeration.DeviceWatcher and Windows.Devices.Midi2.Enumeration.MidiEndpointDeviceWatcher?

Background:

I have a little understanding to COM interface and winrt projection, and have success on building a zig binding with the COM interface from the recent Midi Service; however, I have encounter a weird problem on adding callback with the winrt Windows.Devices.Enumeration.DeviceWatcher where it has gone segmentation fault during querying the interfaces.

Despite the use of zig, I will keep the principle as generic as possible so that it could be understood in other programming languages users for the discussion. Since my choice of language doesn't support COM, which is not C# or C++, I have to build a vtable to retrieve the functions from the winrt side.

The TypedEventHandler vtable is defined as the following:

// For someone who used C, "*?*anyopaque" is same as "**void" 

pub const VTable = struct {
    queryInterface: *const fn (self: *TypedEventHandler, riid: *const Guid, ppvObject: *?*anyopaque) callconv(.winapi) HRESULT,
    addRef: *const fn (self: *TypedEventHandler) callconv(.winapi) ULONG,
    release: *const fn (self: *TypedEventHandler) callconv(.winapi) ULONG,
    invoke: *const fn (*TypedEventHandler, *TSender, *TResult) callconv(.c) HRESULT,
};

Meanwhile, after I have successfully fetch the static interface with RoGetActivationFactory and created the watcher with the abi DeviceWatcher CreateWatcher([In] string aqsFilter)

const device_info_static = try rtype.getActivationFactory(iuwp_enum.IDeviceInformationStatics, "Windows.Devices.Enumeration.DeviceInformation");
const midi_in_static = try rtype.getActivationFactory(iuwp_midi.IMidiInPortStatics, "Windows.Devices.Midi.MidiInPort");

// this should return the interface IDeviceWatcher
var watcher = try device_info_static.createWatcherAqsFilter(try midi_in_static.getDeviceSelector()); 

This expose the interface of IDeviceWatcher, containing the following vtable definition, based on my understanding:

// "[*]" is many item pointer, but in C, it is basically just another "*". For optional pointer "?*", you may treat them as "*" in pure C too 

pub const VTable = struct {
    queryInterface: *const fn (self: *TypedEventHandler, riid: *const Guid, ppvObject: *?*anyopaque) callconv(.winapi) HRESULT,
    addRef: *const fn (self: *TypedEventHandler) callconv(.winapi) ULONG,
    release: *const fn (self: *TypedEventHandler) callconv(.winapi) ULONG,
    getIids: *const fn (self: *Self, iidCount: *ULONG, iid: *[*]Guid) callconv(.winapi) HRESULT,
    getRuntimeClassName: *const fn (self: *Self, className: *HSTRING) callconv(.winapi) HRESULT,
    getTrustLevel: *const fn (self: *Self, trustLevel: *TrustLevel) callconv(.winapi) HRESULT,
    addAdded: *const fn (
        self: *Self,
        handler: ?*TypedEventHandler(Self, IDeviceInformation),
        token: *EventRegistrationToken,
    ) callconv(.winapi) HRESULT,
    removeAdded: *const fn (self: *Self, token: EventRegistrationToken) callconv(.winapi) HRESULT,

    addUpdated: *const fn (
        self: *Self,
        handler: ?*TypedEventHandler(Self, IDeviceInformationUpdate),
        token: *EventRegistrationToken,
    ) callconv(.winapi) HRESULT,
    removeUpdated: *const fn (self: *Self, token: EventRegistrationToken) callconv(.winapi) HRESULT,

    addRemoved: *const fn (
        self: *Self,
        handler: ?*TypedEventHandler(Self, IDeviceInformationUpdate),
        token: *EventRegistrationToken,
    ) callconv(.winapi) HRESULT,
    removeRemoved: *const fn (self: *Self, token: EventRegistrationToken) callconv(.winapi) HRESULT,

    addEnumerationCompleted: *const fn (
        self: *Self,
        handler: ?*TypedEventHandler(Self, ibase.IInspectable),
        token: *EventRegistrationToken,
    ) callconv(.winapi) HRESULT,
    removeEnumerationCompleted: *const fn (self: *Self, token: EventRegistrationToken) callconv(.winapi) HRESULT,

    addStopped: *const fn (
        self: *Self,
        handler: ?*TypedEventHandler(Self, ibase.IInspectable),
        token: *EventRegistrationToken,
    ) callconv(.winapi) HRESULT,
    removeStopped: *const fn (self: *Self, token: EventRegistrationToken) callconv(.winapi) HRESULT,
    getStatus: *const fn (self: *Self, value: *DeviceWatcherStatus) callconv(.winapi) HRESULT,
    start: *const fn (self: *Self) callconv(.winapi) HRESULT,
    stop: *const fn (self: *Self) callconv(.winapi) HRESULT,
};
However, here is the problem:

I tried to add a handler with the function addAdded(). After I have supplied my own typed event handler implementation, I have put some logger in the queryInterface of my handler implementation to trace any abnormalities, and during the function trigger, I can only observed IID_INoMarshal (EC87F1E3-C1F3-4C80-855E-65F6C551AF49) being queried into my handler, and since I have bypassed the guid in the queryInterface with the following logic:

if (std.meta.eql(guid.*, ibase.IUnknown.IID) or
    std.meta.eql(guid.*, HandlerIID))
{
    output.* = this;
    _ = addRef(iunknown);
    std.debug.print("QI -> Success\n", .{});
    return @intFromEnum(std.os.windows.Win32Error.SUCCESS);
} else {
    output.* = null; // IID_INoMarshal  ends here and return a null with NOINTERFACE
    std.debug.print("QI -> Failed\n", .{}); // pay attention to this print for the following console log
    return @intFromEnum(std.os.windows.Win32Error.NOINTERFACE);
}

The queryInterface stops after that point and return a segmentation fault, stating somewhere is getting null:

QI -> .{ .Data1 = 3972557083, .Data2 = 49627, .Data3 = 19904, .Data4 = { 133, 94, 101, 246, 197, 81, 175, 73 } }, reference: winrt.ibase.IUnknown@16fd65c0340
QI -> Failed
Segmentation fault at address 0x0
???:?:?: 0x7ffba3cbc188 in ??? (combase.dll)
???:?:?: 0x7ffba3cbc413 in ??? (combase.dll)
???:?:?: 0x7ffb7069ad25 in ??? (Windows.Devices.Enumeration.dll)
...\main.zig:53:30: 0x7ff69c7a16c8 in main (winrt_experiment_zcu.obj)
    ret = watcher.vt.addAdded(watcher, @ptrCast(&addAddedRef.com.TypedEventHandler), &token);
                             ^

During the time, I have ensure that my generic iid is correct: 03c5a07b-990c-5d09-b0b8-5734eaa38222 which is identical to the one I have found in windows.devices.enumeration.h, but the Handler didn't query any id other than the IID_INoMarshal one before the crash.

The same typed event handler are used for Windows.Devices.Midi2.Enumeration.MidiEndpointDeviceWatcher; nevertheless, it works with queried the handler iid, while the IID_INoMarshal is skipped without any issue:

fromIUnknown: backends.windows.common_winrt.ibase.IUnknown@118f5f70008
QI -> .{ .Data1 = 2498374548, .Data2 = 59852, .Data3 = 18912, .Data4 = { 192, 255, 238, 100, 202, 143, 91, 144 } }, reference: backends.windows.common_winrt.ibase.IUnknown@118f5f70008
QI -> Failed
fromIUnknown: backends.windows.common_winrt.ibase.IUnknown@118f5f70008
QI -> .{ .Data1 = 546357981, .Data2 = 6935, .Data3 = 20609, .Data4 = { 168, 236, 88, 177, 32, 37, 182, 171 } }, reference: backends.windows.common_winrt.ibase.IUnknown@118f5f70008
addRef: backends.windows.common_winrt.ibase.IUnknown@118f5f70008
fromIUnknown: backends.windows.common_winrt.ibase.IUnknown@118f5f70008
QI -> Success
fromIUnknown: backends.windows.common_winrt.ibase.IUnknown@118f5f70008
QI -> .{ .Data1 = 3972557083, .Data2 = 49627, .Data3 = 19904, .Data4 = { 133, 94, 101, 246, 197, 81, 175, 73 } }, reference: backends.windows.common_winrt.ibase.IUnknown@118f5f70008
QI -> Failed // This is the same IID_INoMarshal id, but it doesn't crash and the callback works in Midi2.
release

From here, I have a few questions:

  1. Have anyone successfully interacted Windows.Devices.Enumeration.DeviceWatcher with adding your own callback, without C++/WinRT, C++ and C#?
  2. Are there difference in the design of the TypedEventHandler in between Windows.Devices.Enumeration.DeviceWatcher and Windows.Devices.Midi2.Enumeration.MidiEndpointDeviceWatcher which I need to fulfil the additional COM or WinRT requirement for the former interface?

Please let me know if anyone want more details to the problem.

Dominant language
JavaScript
Stars
266
Forks
517
Avg merge
1m
Merged PRs (30d)
1

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from MicrosoftDocs/winrt-api

All issues in MicrosoftDocs/winrt-api

Similar issues

More JavaScript issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.