upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/runtime/shims/com_shim.cpp
blob: 8156b1917cb50436a611bbecf6b19ff60c70c6bc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
// COM lifecycle and helper shims for api-ms-win-core-com-l1-1-0..3.dll.
//
// game_scarlett_master.exe imports CoInitializeEx, CoUninitialize, CoCreateInstance, CoCreateGuid, CoTaskMemFree,
// PropVariantClear, and StringFromGUID2 through api-ms-win-core-com-l1-1-0.dll. CoCreateInstance of the
// MMDeviceEnumerator goes to silent_audio.cpp, which serves a silent output endpoint when the host has none. When the host (or a host library) has
// already initialized a thread as STA, a guest call to CoInitializeEx(nullptr, COINIT_MULTITHREADED) fails with
// RPC_E_CHANGED_MODE (0x80010106) and an unbalanced CoUninitialize can tear down host COM early.
//
// Per-thread guest COM depth and host init ownership are tracked via a TlsAlloc slot (constant-initialized via
// InitOnceExecuteOnce with zero _Init_thread_header TLS guards or C++ thread_local destructors).
#include <windows.h>
#include <objbase.h>
#include <propidl.h>

#include <cstdint>
#include <new>

#include "shims.h"
#include "silent_audio.h"

namespace rt::com_shim {
namespace {

struct ThreadComState {
    uint32_t guest_depth = 0;
    uint32_t host_inits_owned = 0;
    DWORD requested_coinit = COINIT_MULTITHREADED;
    DWORD host_coinit = COINIT_MULTITHREADED;
    bool mismatch_absorbed = false;
};

INIT_ONCE g_tls_once = INIT_ONCE_STATIC_INIT;
DWORD g_tls_index = TLS_OUT_OF_INDEXES;

BOOL CALLBACK init_tls_once(PINIT_ONCE, PVOID, PVOID*) {
    g_tls_index = TlsAlloc();
    return TRUE;
}

DWORD tls_slot() {
    InitOnceExecuteOnce(&g_tls_once, init_tls_once, nullptr, nullptr);
    return g_tls_index;
}

bool apartment_differs(DWORD a, DWORD b) {
    return (a & COINIT_APARTMENTTHREADED) != (b & COINIT_APARTMENTTHREADED);
}

DWORD detect_existing_host_coinit(DWORD attempted_coinit) {
    APTTYPE apt = APTTYPE_CURRENT;
    APTTYPEQUALIFIER qual = APTTYPEQUALIFIER_NONE;
    DWORD base = (attempted_coinit & COINIT_APARTMENTTHREADED) ? COINIT_MULTITHREADED : COINIT_APARTMENTTHREADED;
    if (SUCCEEDED(::CoGetApartmentType(&apt, &qual))) {
        if (apt == APTTYPE_STA || apt == APTTYPE_MAINSTA) base = COINIT_APARTMENTTHREADED;
        else if (apt == APTTYPE_MTA) base = COINIT_MULTITHREADED;
    }
    return base | (attempted_coinit & (COINIT_DISABLE_OLE1DDE | COINIT_SPEED_OVER_MEMORY));
}

HRESULT WINAPI co_initialize_ex(LPVOID reserved, DWORD coinit) {
    if (reserved != nullptr) return E_INVALIDARG;

    const DWORD slot = tls_slot();
    if (slot == TLS_OUT_OF_INDEXES) return ::CoInitializeEx(nullptr, coinit);

    auto* state = static_cast<ThreadComState*>(TlsGetValue(slot));
    if (!state) {
        const HRESULT hr = ::CoInitializeEx(nullptr, coinit);
        if (FAILED(hr) && hr != RPC_E_CHANGED_MODE) return hr;

        DWORD owned_mode = coinit;
        bool absorbed = false;
        uint32_t owned_count = 1;
        if (hr == RPC_E_CHANGED_MODE) {
            // Retain an actual host COM reference in the thread's existing apartment so guest COM stays alive even if
            // the host calls CoUninitialize() while the guest still holds an active initialization.
            owned_mode = detect_existing_host_coinit(coinit);
            const HRESULT hold_hr = ::CoInitializeEx(nullptr, owned_mode);
            if (FAILED(hold_hr)) return hold_hr;
            absorbed = true;
        }

        auto* created = new (std::nothrow) ThreadComState{};
        if (!created) {
            if (owned_count) ::CoUninitialize();
            return E_OUTOFMEMORY;
        }
        created->guest_depth = 1;
        created->host_inits_owned = owned_count;
        created->requested_coinit = coinit;
        created->host_coinit = owned_mode;
        created->mismatch_absorbed = absorbed;
        TlsSetValue(slot, created);
        return S_OK;
    }

    const bool matches_host = !apartment_differs(state->host_coinit, coinit);
    const bool matches_absorbed_guest = state->mismatch_absorbed && !apartment_differs(state->requested_coinit, coinit);
    if (!matches_host && !matches_absorbed_guest) return RPC_E_CHANGED_MODE;

    const DWORD forward_mode =
        matches_host ? coinit : (state->host_coinit | (coinit & (COINIT_DISABLE_OLE1DDE | COINIT_SPEED_OVER_MEMORY)));
    const HRESULT hr = ::CoInitializeEx(nullptr, forward_mode);
    if (FAILED(hr)) return hr;

    ++state->host_inits_owned;
    ++state->guest_depth;
    return S_FALSE;
}

void WINAPI co_uninitialize() {
    const DWORD slot = tls_slot();
    if (slot == TLS_OUT_OF_INDEXES) {
        ::CoUninitialize();
        return;
    }
    auto* state = static_cast<ThreadComState*>(TlsGetValue(slot));
    if (!state || state->guest_depth == 0) return;

    --state->guest_depth;
    if (state->guest_depth == 0) {
        for (uint32_t i = 0; i < state->host_inits_owned; ++i) {
            ::CoUninitialize();
        }
        TlsSetValue(slot, nullptr);
        delete state;
    }
}

HRESULT WINAPI co_create_instance(REFCLSID rclsid, LPUNKNOWN outer, DWORD cls_context, REFIID riid, LPVOID* ppv) {
    if (!ppv) return E_POINTER;
    *ppv = nullptr;
    // The audio device enumerator: the host's when it has an output, else (or with LEONIDA_AUDIO=silent) one that
    // also answers with the silent output endpoint (silent_audio.h).
    if (!outer && IsEqualCLSID(rclsid, rt::silent_audio::kClsidMMDeviceEnumerator))
        return rt::silent_audio::create_enumerator(cls_context, riid, ppv);
    return ::CoCreateInstance(rclsid, outer, cls_context, riid, ppv);
}

HRESULT WINAPI co_create_guid(GUID* guid) {
    if (!guid) return E_INVALIDARG;
    return ::CoCreateGuid(guid);
}

void WINAPI co_task_mem_free(LPVOID pv) { ::CoTaskMemFree(pv); }

HRESULT WINAPI prop_variant_clear(PROPVARIANT* pvar) { return ::PropVariantClear(pvar); }

int WINAPI string_from_guid2(REFGUID rguid, LPOLESTR lpsz, int cch_max) {
    if (!lpsz || cch_max <= 0) return 0;
    return ::StringFromGUID2(rguid, lpsz, cch_max);
}

}  // namespace
}  // namespace rt::com_shim

namespace {

using namespace rt::com_shim;

#define COM_L1_API(dll)                                                                  \
    {dll, "CoInitializeEx", reinterpret_cast<void*>(&co_initialize_ex)},                 \
        {dll, "CoUninitialize", reinterpret_cast<void*>(&co_uninitialize)},              \
        {dll, "CoCreateInstance", reinterpret_cast<void*>(&co_create_instance)},         \
        {dll, "CoCreateGuid", reinterpret_cast<void*>(&co_create_guid)},                 \
        {dll, "CoTaskMemFree", reinterpret_cast<void*>(&co_task_mem_free)},              \
        {dll, "PropVariantClear", reinterpret_cast<void*>(&prop_variant_clear)},         \
        {dll, "StringFromGUID2", reinterpret_cast<void*>(&string_from_guid2)}

}  // namespace

// Registered strictly on the api-ms-win-core-com API sets (not ole32.dll/combase.dll) so rt::shims::owns_dll keeps
// host COM DLLs unbound to pseudo-handles while answering all mapped api-ms-win-core-com-* imports.
SHIM_TABLE(com_shim,
    COM_L1_API("api-ms-win-core-com-l1-1-0.dll"),
    COM_L1_API("api-ms-win-core-com-l1-1-1.dll"),
    COM_L1_API("api-ms-win-core-com-l1-1-2.dll"),
    COM_L1_API("api-ms-win-core-com-l1-1-3.dll"),
);