compobj.c 155 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*
 * Component Object Tests
 *
 * Copyright 2005 Robert Shearman
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19 20 21
 */

#define COBJMACROS
22
#define CONST_VTABLE
23 24

#include <stdarg.h>
25
#include <stdio.h>
26 27 28

#include "windef.h"
#include "winbase.h"
29
#define USE_COM_CONTEXT_DEF
30
#include "objbase.h"
31
#include "shlguid.h"
32
#include "urlmon.h" /* for CLSID_FileProtocol */
33
#include "dde.h"
34
#include "cguid.h"
35

36 37
#include "ctxtcall.h"

38
#include "wine/test.h"
39
#include "winternl.h"
40
#include "initguid.h"
41

42
#define DEFINE_EXPECT(func) \
43
    static BOOL expect_ ## func = FALSE; static unsigned int called_ ## func = 0
44 45 46 47 48 49 50

#define SET_EXPECT(func) \
    expect_ ## func = TRUE

#define CHECK_EXPECT2(func) \
    do { \
        ok(expect_ ##func, "unexpected call " #func "\n"); \
51
        called_ ## func++; \
52 53 54 55 56 57 58 59
    }while(0)

#define CHECK_EXPECT(func) \
    do { \
        CHECK_EXPECT2(func); \
        expect_ ## func = FALSE; \
    }while(0)

60
#define CHECK_CALLED(func, n) \
61
    do { \
62 63 64
        ok(called_ ## func == n, "expected " #func " called %u times, got %u\n", n, called_ ## func); \
        expect_ ## func = FALSE; \
        called_ ## func = 0; \
65 66 67
    }while(0)

DEFINE_EXPECT(CreateStub);
68 69 70 71
DEFINE_EXPECT(PreInitialize);
DEFINE_EXPECT(PostInitialize);
DEFINE_EXPECT(PreUninitialize);
DEFINE_EXPECT(PostUninitialize);
72

73
/* functions that are not present on all versions of Windows */
74 75 76
static HRESULT (WINAPI * pCoGetObjectContext)(REFIID riid, LPVOID *ppv);
static HRESULT (WINAPI * pCoSwitchCallContext)(IUnknown *pObject, IUnknown **ppOldObject);
static HRESULT (WINAPI * pCoGetContextToken)(ULONG_PTR *token);
77
static HRESULT (WINAPI * pCoGetApartmentType)(APTTYPE *type, APTTYPEQUALIFIER *qualifier);
78 79
static HRESULT (WINAPI * pCoIncrementMTAUsage)(CO_MTA_USAGE_COOKIE *cookie);
static HRESULT (WINAPI * pCoDecrementMTAUsage)(CO_MTA_USAGE_COOKIE cookie);
80
static LONG (WINAPI * pRegDeleteKeyExA)(HKEY, LPCSTR, REGSAM, DWORD);
81
static LONG (WINAPI * pRegOverridePredefKey)(HKEY key, HKEY override);
82 83
static HRESULT (WINAPI * pCoCreateInstanceFromApp)(REFCLSID clsid, IUnknown *outer, DWORD clscontext,
        void *reserved, DWORD count, MULTI_QI *results);
84

85
static BOOL   (WINAPI *pIsWow64Process)(HANDLE, LPBOOL);
86

87
#define ok_ole_success(hr, func) ok(hr == S_OK, func " failed with error 0x%08x\n", hr)
88 89
#define ok_more_than_one_lock() ok(cLocks > 0, "Number of locks should be > 0, but actually is %d\n", cLocks)
#define ok_no_locks() ok(cLocks == 0, "Number of locks should be 0, but actually is %d\n", cLocks)
90

91
static const CLSID CLSID_non_existent =   { 0x12345678, 0x1234, 0x1234, { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0 } };
92
static const CLSID CLSID_StdFont = { 0x0be35203, 0x8f91, 0x11ce, { 0x9d, 0xe3, 0x00, 0xaa, 0x00, 0x4b, 0xb8, 0x51 } };
93 94 95 96
static const GUID IID_Testiface = { 0x22222222, 0x1234, 0x1234, { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0 } };
static const GUID IID_Testiface2 = { 0x32222222, 0x1234, 0x1234, { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0 } };
static const GUID IID_Testiface3 = { 0x42222222, 0x1234, 0x1234, { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0 } };
static const GUID IID_Testiface4 = { 0x52222222, 0x1234, 0x1234, { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0 } };
97 98
static const GUID IID_Testiface5 = { 0x62222222, 0x1234, 0x1234, { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0 } };
static const GUID IID_Testiface6 = { 0x72222222, 0x1234, 0x1234, { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0 } };
99 100
static const GUID IID_Testiface7 = { 0x82222222, 0x1234, 0x1234, { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0 } };
static const GUID IID_Testiface8 = { 0x92222222, 0x1234, 0x1234, { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0 } };
101 102
static const GUID IID_TestPS = { 0x66666666, 0x8888, 0x7777, { 0x66, 0x66, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55 } };

103
DEFINE_GUID(CLSID_testclsid, 0xacd014c7,0x9535,0x4fac,0x8b,0x53,0xa4,0x8c,0xa7,0xf4,0xd7,0x26);
104

105
static const WCHAR stdfont[] = {'S','t','d','F','o','n','t',0};
106
static const WCHAR wszNonExistent[] = {'N','o','n','E','x','i','s','t','e','n','t',0};
107
static const WCHAR wszCLSID_StdFont[] =
108
{
109 110
    '{','0','b','e','3','5','2','0','3','-','8','f','9','1','-','1','1','c','e','-',
    '9','d','e','3','-','0','0','a','a','0','0','4','b','b','8','5','1','}',0
111
};
112
static const WCHAR progidW[] = {'P','r','o','g','I','d','.','P','r','o','g','I','d',0};
113 114
static const WCHAR cf_brokenW[] = {'{','0','0','0','0','0','0','0','1','-','0','0','0','0','-','0','0','0','0','-',
                                    'c','0','0','0','-','0','0','0','0','0','0','0','0','0','0','4','6','}','a',0};
115

116 117
DEFINE_GUID(IID_IWineTest, 0x5201163f, 0x8164, 0x4fd0, 0xa1, 0xa2, 0x5d, 0x5a, 0x36, 0x54, 0xd3, 0xbd);
DEFINE_GUID(CLSID_WineOOPTest, 0x5201163f, 0x8164, 0x4fd0, 0xa1, 0xa2, 0x5d, 0x5a, 0x36, 0x54, 0xd3, 0xbd);
118

119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
static LONG cLocks;

static void LockModule(void)
{
    InterlockedIncrement(&cLocks);
}

static void UnlockModule(void)
{
    InterlockedDecrement(&cLocks);
}

static HRESULT WINAPI Test_IClassFactory_QueryInterface(
    LPCLASSFACTORY iface,
    REFIID riid,
    LPVOID *ppvObj)
{
    if (ppvObj == NULL) return E_POINTER;

    if (IsEqualGUID(riid, &IID_IUnknown) ||
        IsEqualGUID(riid, &IID_IClassFactory))
    {
141
        *ppvObj = iface;
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
        IClassFactory_AddRef(iface);
        return S_OK;
    }

    *ppvObj = NULL;
    return E_NOINTERFACE;
}

static ULONG WINAPI Test_IClassFactory_AddRef(LPCLASSFACTORY iface)
{
    LockModule();
    return 2; /* non-heap-based object */
}

static ULONG WINAPI Test_IClassFactory_Release(LPCLASSFACTORY iface)
{
    UnlockModule();
    return 1; /* non-heap-based object */
}

162
static IID create_instance_iid;
163 164
static HRESULT WINAPI Test_IClassFactory_CreateInstance(
    LPCLASSFACTORY iface,
165
    IUnknown *pUnkOuter,
166 167 168 169
    REFIID riid,
    LPVOID *ppvObj)
{
    *ppvObj = NULL;
170
    create_instance_iid = *riid;
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
    if (pUnkOuter) return CLASS_E_NOAGGREGATION;
    return E_NOINTERFACE;
}

static HRESULT WINAPI Test_IClassFactory_LockServer(
    LPCLASSFACTORY iface,
    BOOL fLock)
{
    return S_OK;
}

static const IClassFactoryVtbl TestClassFactory_Vtbl =
{
    Test_IClassFactory_QueryInterface,
    Test_IClassFactory_AddRef,
    Test_IClassFactory_Release,
    Test_IClassFactory_CreateInstance,
    Test_IClassFactory_LockServer
};

static IClassFactory Test_ClassFactory = { &TestClassFactory_Vtbl };
192

193 194 195 196 197 198 199 200 201 202
static WCHAR manifest_path[MAX_PATH];

static BOOL create_manifest_file(const char *filename, const char *manifest)
{
    int manifest_len;
    DWORD size;
    HANDLE file;
    WCHAR path[MAX_PATH];

    MultiByteToWideChar( CP_ACP, 0, filename, -1, path, MAX_PATH );
203
    GetFullPathNameW(path, ARRAY_SIZE(manifest_path), manifest_path, NULL);
204 205 206 207 208 209 210 211 212 213 214 215 216

    manifest_len = strlen(manifest);
    file = CreateFileW(path, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
                       FILE_ATTRIBUTE_NORMAL, NULL);
    ok(file != INVALID_HANDLE_VALUE, "CreateFile failed: %u\n", GetLastError());
    if(file == INVALID_HANDLE_VALUE)
        return FALSE;
    WriteFile(file, manifest, manifest_len, &size, NULL);
    CloseHandle(file);

    return TRUE;
}

217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
static void extract_resource(const char *name, const char *type, const char *path)
{
    DWORD written;
    HANDLE file;
    HRSRC res;
    void *ptr;

    file = CreateFileA(path, GENERIC_READ|GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, 0);
    ok(file != INVALID_HANDLE_VALUE, "Failed to create a file at %s, error %d.\n", path, GetLastError());

    res = FindResourceA(NULL, name, type);
    ok(res != 0, "Failed to find resource.\n");
    ptr = LockResource(LoadResource(GetModuleHandleA(NULL), res));
    WriteFile(file, ptr, SizeofResource(GetModuleHandleA(NULL), res), &written, NULL);
    ok(written == SizeofResource(GetModuleHandleA(NULL), res), "Failed to write file.\n" );
    CloseHandle(file);
}

static char testlib[MAX_PATH];

237 238 239 240 241 242 243 244 245 246 247 248 249 250
static HANDLE activate_context(const char *manifest, ULONG_PTR *cookie)
{
    WCHAR path[MAX_PATH];
    ACTCTXW actctx;
    HANDLE handle;
    BOOL ret;

    create_manifest_file("file.manifest", manifest);

    MultiByteToWideChar( CP_ACP, 0, "file.manifest", -1, path, MAX_PATH );
    memset(&actctx, 0, sizeof(ACTCTXW));
    actctx.cbSize = sizeof(ACTCTXW);
    actctx.lpSource = path;

251
    handle = CreateActCtxW(&actctx);
252 253 254 255
    ok(handle != INVALID_HANDLE_VALUE || broken(handle == INVALID_HANDLE_VALUE) /* some old XP/2k3 versions */,
        "handle == INVALID_HANDLE_VALUE, error %u\n", GetLastError());
    if (handle == INVALID_HANDLE_VALUE)
    {
256
        win_skip("activation context generation failed, some tests will be skipped. Error %d\n", GetLastError());
257 258
        handle = NULL;
    }
259 260 261 262 263 264 265 266 267 268 269 270 271

    ok(actctx.cbSize == sizeof(ACTCTXW), "actctx.cbSize=%d\n", actctx.cbSize);
    ok(actctx.dwFlags == 0, "actctx.dwFlags=%d\n", actctx.dwFlags);
    ok(actctx.lpSource == path, "actctx.lpSource=%p\n", actctx.lpSource);
    ok(actctx.wProcessorArchitecture == 0, "actctx.wProcessorArchitecture=%d\n", actctx.wProcessorArchitecture);
    ok(actctx.wLangId == 0, "actctx.wLangId=%d\n", actctx.wLangId);
    ok(actctx.lpAssemblyDirectory == NULL, "actctx.lpAssemblyDirectory=%p\n", actctx.lpAssemblyDirectory);
    ok(actctx.lpResourceName == NULL, "actctx.lpResourceName=%p\n", actctx.lpResourceName);
    ok(actctx.lpApplicationName == NULL, "actctx.lpApplicationName=%p\n", actctx.lpApplicationName);
    ok(actctx.hModule == NULL, "actctx.hModule=%p\n", actctx.hModule);

    DeleteFileA("file.manifest");

272 273
    if (handle)
    {
274
        ret = ActivateActCtx(handle, cookie);
275 276
        ok(ret, "ActivateActCtx failed: %u\n", GetLastError());
    }
277 278 279 280

    return handle;
}

281 282 283 284 285 286 287 288 289
static void deactivate_context(HANDLE handle, ULONG_PTR cookie)
{
    BOOL ret;

    ret = DeactivateActCtx(0, cookie);
    ok(ret, "Failed to deactivate context, error %d.\n", GetLastError());
    ReleaseActCtx(handle);
}

290 291 292 293 294
static const char actctx_manifest[] =
"<assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\" manifestVersion=\"1.0\">"
"<assemblyIdentity version=\"1.2.3.4\"  name=\"Wine.Test\" type=\"win32\""
" publicKeyToken=\"6595b6414666f1df\" />"
"<file name=\"testlib.dll\">"
295 296 297 298 299 300 301 302
"    <comClass"
"              clsid=\"{0000033a-0000-0000-c000-000000000046}\""
"              progid=\"FTMarshal\""
"    />"
"    <comClass"
"              clsid=\"{5201163f-8164-4fd0-a1a2-5d5a3654d3bd}\""
"              progid=\"WineOOPTest\""
"    />"
303 304 305
"    <comClass description=\"Test com class\""
"              clsid=\"{12345678-1234-1234-1234-56789abcdef0}\""
"              progid=\"ProgId.ProgId\""
306
"              miscStatusIcon=\"recomposeonresize\""
307
"    />"
308
"    <comClass description=\"CustomFont Description\" clsid=\"{0be35203-8f91-11ce-9de3-00aa004bb851}\""
309
"              progid=\"CustomFont\""
310 311
"              miscStatusIcon=\"recomposeonresize\""
"              miscStatusContent=\"insideout\""
312
"    />"
313
"    <comClass description=\"StdFont Description\" clsid=\"{0be35203-8f91-11ce-9de3-00aa004bb852}\""
314 315
"              progid=\"StdFont\""
"    />"
316 317 318
"    <comClass clsid=\"{62222222-1234-1234-1234-56789abcdef0}\" >"
"        <progid>ProgId.ProgId.1</progid>"
"    </comClass>"
319 320 321 322 323
"    <comInterfaceProxyStub "
"        name=\"Iifaceps\""
"        iid=\"{22222222-1234-1234-1234-56789abcdef0}\""
"        proxyStubClsid32=\"{66666666-8888-7777-6666-555555555555}\""
"    />"
324 325 326 327
"    <comInterfaceProxyStub "
"        name=\"Iifaceps5\""
"        iid=\"{82222222-1234-1234-1234-56789abcdef0}\""
"    />"
328
"</file>"
329 330 331 332 333 334 335 336 337 338 339 340 341 342
"    <comInterfaceExternalProxyStub "
"        name=\"Iifaceps2\""
"        iid=\"{32222222-1234-1234-1234-56789abcdef0}\""
"    />"
"    <comInterfaceExternalProxyStub "
"        name=\"Iifaceps3\""
"        iid=\"{42222222-1234-1234-1234-56789abcdef0}\""
"        proxyStubClsid32=\"{66666666-8888-7777-6666-555555555555}\""
"    />"
"    <comInterfaceExternalProxyStub "
"        name=\"Iifaceps4\""
"        iid=\"{52222222-1234-1234-1234-56789abcdef0}\""
"        proxyStubClsid32=\"{00000000-0000-0000-0000-000000000000}\""
"    />"
343 344 345 346 347 348
"    <clrClass "
"        clsid=\"{72222222-1234-1234-1234-56789abcdef0}\""
"        name=\"clrclass\""
"    >"
"        <progid>clrprogid.1</progid>"
"    </clrClass>"
349 350
"</assembly>";

351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
static const char actctx_manifest2[] =
"<assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\" manifestVersion=\"1.0\">"
"<assemblyIdentity version=\"1.2.3.4\"  name=\"Wine.Test\" type=\"win32\""
" publicKeyToken=\"6595b6414666f1df\" />"
"<file name=\"testlib.dll\">"
"    <comInterfaceProxyStub "
"        name=\"Testiface7\""
"        iid=\"{52222222-1234-1234-1234-56789abcdef0}\""
"        proxyStubClsid32=\"{82222222-1234-1234-1234-56789abcdef0}\""
"        threadingModel=\"Apartment\""
"    />"
"</file>"
"<file name=\"testlib4.dll\">"
"    <comInterfaceProxyStub "
"        name=\"Testiface8\""
"        iid=\"{92222222-1234-1234-1234-56789abcdef0}\""
"        threadingModel=\"Apartment\""
"    />"
"</file>"
"    <comInterfaceExternalProxyStub "
"        name=\"Iifaceps3\""
"        iid=\"{42222222-1234-1234-1234-56789abcdef0}\""
"        proxyStubClsid32=\"{66666666-8888-7777-6666-555555555555}\""
"    />"
"</assembly>";

377 378
DEFINE_GUID(CLSID_Testclass, 0x12345678, 0x1234, 0x1234, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0);

379 380
static void test_ProgIDFromCLSID(void)
{
381
    ULONG_PTR cookie = 0;
382
    LPWSTR progid;
383 384 385 386
    HANDLE handle;
    HRESULT hr;

    hr = ProgIDFromCLSID(&CLSID_StdFont, &progid);
387
    ok(hr == S_OK, "ProgIDFromCLSID failed with error 0x%08x\n", hr);
388 389
    if (hr == S_OK)
    {
390
        ok(!lstrcmpiW(progid, stdfont), "Didn't get expected prog ID\n");
391 392
        CoTaskMemFree(progid);
    }
393 394 395

    progid = (LPWSTR)0xdeadbeef;
    hr = ProgIDFromCLSID(&CLSID_non_existent, &progid);
396
    ok(hr == REGDB_E_CLASSNOTREG, "ProgIDFromCLSID returned %08x\n", hr);
397
    ok(progid == NULL, "ProgIDFromCLSID returns with progid %p\n", progid);
398

399
    hr = ProgIDFromCLSID(&CLSID_StdFont, NULL);
400
    ok(hr == E_INVALIDARG, "ProgIDFromCLSID should return E_INVALIDARG instead of 0x%08x\n", hr);
401 402 403

    if ((handle = activate_context(actctx_manifest, &cookie)))
    {
404 405
        static const WCHAR customfontW[] = {'C','u','s','t','o','m','F','o','n','t',0};

406 407
        hr = ProgIDFromCLSID(&CLSID_non_existent, &progid);
        ok(hr == S_OK, "got 0x%08x\n", hr);
408 409
        ok(!lstrcmpiW(progid, progidW), "got %s\n", wine_dbgstr_w(progid));
        CoTaskMemFree(progid);
410

411 412 413 414 415 416 417
        /* try something registered and redirected */
        progid = NULL;
        hr = ProgIDFromCLSID(&CLSID_StdFont, &progid);
        ok(hr == S_OK, "got 0x%08x\n", hr);
        ok(!lstrcmpiW(progid, customfontW), "got wrong progid %s\n", wine_dbgstr_w(progid));
        CoTaskMemFree(progid);

418
        /* classes without default progid, progid list is not used */
419
        progid = (void *)0xdeadbeef;
420
        hr = ProgIDFromCLSID(&IID_Testiface5, &progid);
421
        ok(hr == REGDB_E_CLASSNOTREG && progid == NULL, "got 0x%08x, progid %p\n", hr, progid);
422

423
        progid = (void *)0xdeadbeef;
424
        hr = ProgIDFromCLSID(&IID_Testiface6, &progid);
425
        ok(hr == REGDB_E_CLASSNOTREG && progid == NULL, "got 0x%08x, progid %p\n", hr, progid);
426

427
        deactivate_context(handle, cookie);
428
    }
429 430 431 432
}

static void test_CLSIDFromProgID(void)
{
433 434
    ULONG_PTR cookie = 0;
    HANDLE handle;
435
    CLSID clsid;
436
    HRESULT hr = CLSIDFromProgID(stdfont, &clsid);
437
    ok(hr == S_OK, "CLSIDFromProgID failed with error 0x%08x\n", hr);
438
    ok(IsEqualCLSID(&clsid, &CLSID_StdFont), "clsid wasn't equal to CLSID_StdFont\n");
439

440
    hr = CLSIDFromString(stdfont, &clsid);
441
    ok_ole_success(hr, "CLSIDFromString");
442
    ok(IsEqualCLSID(&clsid, &CLSID_StdFont), "clsid wasn't equal to CLSID_StdFont\n");
443 444 445

    /* test some failure cases */

446
    hr = CLSIDFromProgID(wszNonExistent, NULL);
447
    ok(hr == E_INVALIDARG, "CLSIDFromProgID should have returned E_INVALIDARG instead of 0x%08x\n", hr);
448 449

    hr = CLSIDFromProgID(NULL, &clsid);
450
    ok(hr == E_INVALIDARG, "CLSIDFromProgID should have returned E_INVALIDARG instead of 0x%08x\n", hr);
451 452

    memset(&clsid, 0xcc, sizeof(clsid));
453
    hr = CLSIDFromProgID(wszNonExistent, &clsid);
454
    ok(hr == CO_E_CLASSSTRING, "CLSIDFromProgID on nonexistent ProgID should have returned CO_E_CLASSSTRING instead of 0x%08x\n", hr);
455
    ok(IsEqualCLSID(&clsid, &CLSID_NULL), "CLSIDFromProgID should have set clsid to all-zeros on failure\n");
456 457 458 459 460 461 462 463 464

    /* fails without proper context */
    memset(&clsid, 0xcc, sizeof(clsid));
    hr = CLSIDFromProgID(progidW, &clsid);
    ok(hr == CO_E_CLASSSTRING, "got 0x%08x\n", hr);
    ok(IsEqualCLSID(&clsid, &CLSID_NULL), "wrong clsid\n");

    if ((handle = activate_context(actctx_manifest, &cookie)))
    {
465 466
        GUID clsid1;

467 468 469 470 471 472 473 474 475
        memset(&clsid, 0xcc, sizeof(clsid));
        hr = CLSIDFromProgID(wszNonExistent, &clsid);
        ok(hr == CO_E_CLASSSTRING, "got 0x%08x\n", hr);
        ok(IsEqualCLSID(&clsid, &CLSID_NULL), "should have zero CLSID on failure\n");

        /* CLSIDFromString() doesn't check activation context */
        hr = CLSIDFromString(progidW, &clsid);
        ok(hr == CO_E_CLASSSTRING, "got 0x%08x\n", hr);

476 477
        clsid = CLSID_NULL;
        hr = CLSIDFromProgID(progidW, &clsid);
478
        ok(hr == S_OK, "got 0x%08x\n", hr);
479 480
        /* it returns generated CLSID here */
        ok(!IsEqualCLSID(&clsid, &CLSID_non_existent) && !IsEqualCLSID(&clsid, &CLSID_NULL),
481
                 "got wrong clsid %s\n", wine_dbgstr_guid(&clsid));
482

483 484 485 486 487 488 489 490
        /* duplicate progid present in context - returns generated guid here too */
        clsid = CLSID_NULL;
        hr = CLSIDFromProgID(stdfont, &clsid);
        ok(hr == S_OK, "got 0x%08x\n", hr);
        clsid1 = CLSID_StdFont;
        /* that's where it differs from StdFont */
        clsid1.Data4[7] = 0x52;
        ok(!IsEqualCLSID(&clsid, &CLSID_StdFont) && !IsEqualCLSID(&clsid, &CLSID_NULL) && !IsEqualCLSID(&clsid, &clsid1),
491
            "got %s\n", wine_dbgstr_guid(&clsid));
492

493
        deactivate_context(handle, cookie);
494
    }
495 496 497 498 499
}

static void test_CLSIDFromString(void)
{
    CLSID clsid;
500 501 502
    WCHAR wszCLSID_Broken[50];
    UINT i;

503
    HRESULT hr = CLSIDFromString(wszCLSID_StdFont, &clsid);
504
    ok_ole_success(hr, "CLSIDFromString");
505
    ok(IsEqualCLSID(&clsid, &CLSID_StdFont), "clsid wasn't equal to CLSID_StdFont\n");
506

507
    memset(&clsid, 0xab, sizeof(clsid));
508
    hr = CLSIDFromString(NULL, &clsid);
509
    ok(hr == S_OK, "got 0x%08x\n", hr);
510
    ok(IsEqualCLSID(&clsid, &CLSID_NULL), "clsid wasn't equal to CLSID_NULL\n");
511

512 513 514 515 516 517
    /* string is longer, but starts with a valid CLSID */
    memset(&clsid, 0, sizeof(clsid));
    hr = CLSIDFromString(cf_brokenW, &clsid);
    ok(hr == CO_E_CLASSSTRING, "got 0x%08x\n", hr);
    ok(IsEqualCLSID(&clsid, &IID_IClassFactory), "got %s\n", wine_dbgstr_guid(&clsid));

518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
    lstrcpyW(wszCLSID_Broken, wszCLSID_StdFont);
    for(i = lstrlenW(wszCLSID_StdFont); i < 49; i++)
        wszCLSID_Broken[i] = 'A';
    wszCLSID_Broken[i] = '\0';

    memset(&clsid, 0, sizeof(CLSID));
    hr = CLSIDFromString(wszCLSID_Broken, &clsid);
    ok(hr == CO_E_CLASSSTRING, "Got %08x\n", hr);
    ok(IsEqualCLSID(&clsid, &CLSID_StdFont), "clsid wasn't equal to CLSID_StdFont\n");

    wszCLSID_Broken[lstrlenW(wszCLSID_StdFont)-1] = 'A';
    memset(&clsid, 0, sizeof(CLSID));
    hr = CLSIDFromString(wszCLSID_Broken, &clsid);
    ok(hr == CO_E_CLASSSTRING, "Got %08x\n", hr);
    ok(IsEqualCLSID(&clsid, &CLSID_StdFont), "clsid wasn't equal to CLSID_StdFont\n");

    wszCLSID_Broken[lstrlenW(wszCLSID_StdFont)] = '\0';
    memset(&clsid, 0, sizeof(CLSID));
    hr = CLSIDFromString(wszCLSID_Broken, &clsid);
    ok(hr == CO_E_CLASSSTRING, "Got %08x\n", hr);
    ok(IsEqualCLSID(&clsid, &CLSID_StdFont), "clsid wasn't equal to CLSID_StdFont\n");

    wszCLSID_Broken[lstrlenW(wszCLSID_StdFont)-1] = '\0';
    memset(&clsid, 0, sizeof(CLSID));
    hr = CLSIDFromString(wszCLSID_Broken, &clsid);
    ok(hr == CO_E_CLASSSTRING, "Got %08x\n", hr);
    ok(IsEqualCLSID(&clsid, &CLSID_StdFont), "clsid wasn't equal to CLSID_StdFont\n");

    memset(&clsid, 0xcc, sizeof(CLSID));
    hr = CLSIDFromString(wszCLSID_Broken+1, &clsid);
    ok(hr == CO_E_CLASSSTRING, "Got %08x\n", hr);
    ok(IsEqualCLSID(&clsid, &CLSID_NULL), "clsid wasn't equal to CLSID_NULL\n");

    wszCLSID_Broken[9] = '*';
    memset(&clsid, 0xcc, sizeof(CLSID));
    hr = CLSIDFromString(wszCLSID_Broken, &clsid);
    ok(hr == CO_E_CLASSSTRING, "Got %08x\n", hr);
    ok(clsid.Data1 == CLSID_StdFont.Data1, "Got %08x\n", clsid.Data1);
    ok(clsid.Data2 == 0xcccc, "Got %04x\n", clsid.Data2);

    wszCLSID_Broken[3] = '*';
    memset(&clsid, 0xcc, sizeof(CLSID));
    hr = CLSIDFromString(wszCLSID_Broken, &clsid);
    ok(hr == CO_E_CLASSSTRING, "Got %08x\n", hr);
    ok(clsid.Data1 == 0xb, "Got %08x\n", clsid.Data1);
    ok(clsid.Data2 == 0xcccc, "Got %04x\n", clsid.Data2);

    wszCLSID_Broken[3] = '\0';
    memset(&clsid, 0xcc, sizeof(CLSID));
    hr = CLSIDFromString(wszCLSID_Broken, &clsid);
    ok(hr == CO_E_CLASSSTRING, "Got %08x\n", hr);
    ok(clsid.Data1 == 0xb, "Got %08x\n", clsid.Data1);
    ok(clsid.Data2 == 0xcccc, "Got %04x\n", clsid.Data2);
571 572
}

573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
static void test_IIDFromString(void)
{
    static const WCHAR cfW[] = {'{','0','0','0','0','0','0','0','1','-','0','0','0','0','-','0','0','0','0','-',
                                    'c','0','0','0','-','0','0','0','0','0','0','0','0','0','0','4','6','}',0};
    static const WCHAR brokenW[] = {'{','0','0','0','0','0','0','0','1','-','0','0','0','0','-','0','0','0','0','-',
                                        'g','0','0','0','-','0','0','0','0','0','0','0','0','0','0','4','6','}',0};
    static const WCHAR broken2W[] = {'{','0','0','0','0','0','0','0','1','=','0','0','0','0','-','0','0','0','0','-',
                                        'g','0','0','0','-','0','0','0','0','0','0','0','0','0','0','4','6','}',0};
    static const WCHAR broken3W[] = {'b','r','o','k','e','n','0','0','1','=','0','0','0','0','-','0','0','0','0','-',
                                        'g','0','0','0','-','0','0','0','0','0','0','0','0','0','0','4','6','}',0};
    HRESULT hr;
    IID iid;

    hr = IIDFromString(wszCLSID_StdFont, &iid);
    ok(hr == S_OK, "got 0x%08x\n", hr);
    ok(IsEqualIID(&iid, &CLSID_StdFont), "got iid %s\n", wine_dbgstr_guid(&iid));

    memset(&iid, 0xab, sizeof(iid));
    hr = IIDFromString(NULL, &iid);
    ok(hr == S_OK, "got 0x%08x\n", hr);
    ok(IsEqualIID(&iid, &CLSID_NULL), "got iid %s\n", wine_dbgstr_guid(&iid));

    hr = IIDFromString(cfW, &iid);
    ok(hr == S_OK, "got 0x%08x\n", hr);
    ok(IsEqualIID(&iid, &IID_IClassFactory), "got iid %s\n", wine_dbgstr_guid(&iid));

    /* string starts with a valid IID but is longer */
    memset(&iid, 0xab, sizeof(iid));
    hr = IIDFromString(cf_brokenW, &iid);
    ok(hr == E_INVALIDARG, "got 0x%08x\n", hr);
    ok(iid.Data1 == 0xabababab, "Got %08x\n", iid.Data1);

    /* invalid IID in a valid format */
    memset(&iid, 0xab, sizeof(iid));
    hr = IIDFromString(brokenW, &iid);
    ok(hr == CO_E_IIDSTRING, "got 0x%08x\n", hr);
    ok(iid.Data1 == 0x00000001, "Got %08x\n", iid.Data1);

    memset(&iid, 0xab, sizeof(iid));
    hr = IIDFromString(broken2W, &iid);
    ok(hr == CO_E_IIDSTRING, "got 0x%08x\n", hr);
    ok(iid.Data1 == 0x00000001, "Got %08x\n", iid.Data1);

    /* format is broken, but string length is okay */
    memset(&iid, 0xab, sizeof(iid));
    hr = IIDFromString(broken3W, &iid);
    ok(hr == CO_E_IIDSTRING, "got 0x%08x\n", hr);
    ok(iid.Data1 == 0xabababab, "Got %08x\n", iid.Data1);

    /* invalid string */
    memset(&iid, 0xab, sizeof(iid));
    hr = IIDFromString(wszNonExistent, &iid);
    ok(hr == E_INVALIDARG, "got 0x%08x\n", hr);
    ok(iid.Data1 == 0xabababab, "Got %08x\n", iid.Data1);

    /* valid ProgID */
    memset(&iid, 0xab, sizeof(iid));
    hr = IIDFromString(stdfont, &iid);
    ok(hr == E_INVALIDARG, "got 0x%08x\n", hr);
    ok(iid.Data1 == 0xabababab, "Got %08x\n", iid.Data1);
}

635 636 637 638
static void test_StringFromGUID2(void)
{
  WCHAR str[50];
  int len;
639 640 641 642 643 644 645

  /* invalid pointer */
  SetLastError(0xdeadbeef);
  len = StringFromGUID2(NULL,str,50);
  ok(len == 0, "len: %d (expected 0)\n", len);
  ok(GetLastError() == 0xdeadbeef, "Expected 0xdeadbeef, got %x\n", GetLastError());

646
  /* Test corner cases for buffer size */
647
  len = StringFromGUID2(&CLSID_StdFont,str,50);
648
  ok(len == 39, "len: %d (expected 39)\n", len);
649
  ok(!lstrcmpiW(str, wszCLSID_StdFont),"string wasn't equal for CLSID_StdFont\n");
650 651

  memset(str,0,sizeof str);
652
  len = StringFromGUID2(&CLSID_StdFont,str,39);
653
  ok(len == 39, "len: %d (expected 39)\n", len);
654
  ok(!lstrcmpiW(str, wszCLSID_StdFont),"string wasn't equal for CLSID_StdFont\n");
655

656
  len = StringFromGUID2(&CLSID_StdFont,str,38);
657
  ok(len == 0, "len: %d (expected 0)\n", len);
658

659
  len = StringFromGUID2(&CLSID_StdFont,str,30);
660
  ok(len == 0, "len: %d (expected 0)\n", len);
661 662
}

663 664
#define test_apt_type(t, q) _test_apt_type(t, q, __LINE__)
static void _test_apt_type(APTTYPE expected_type, APTTYPEQUALIFIER expected_qualifier, int line)
665 666 667 668 669 670 671 672 673
{
    APTTYPEQUALIFIER qualifier = ~0u;
    APTTYPE type = ~0u;
    HRESULT hr;

    if (!pCoGetApartmentType)
        return;

    hr = pCoGetApartmentType(&type, &qualifier);
674 675
    ok_(__FILE__, line)(hr == S_OK || (type == APTTYPE_CURRENT && hr == CO_E_NOTINITIALIZED),
            "Unexpected hr %#x.\n", hr);
676 677 678 679 680
    ok_(__FILE__, line)(type == expected_type, "Wrong apartment type %d, expected %d\n", type, expected_type);
    ok_(__FILE__, line)(qualifier == expected_qualifier, "Wrong apartment qualifier %d, expected %d\n", qualifier,
        expected_qualifier);
}

681 682
static void test_CoCreateInstance(void)
{
683 684 685 686 687 688
    HRESULT hr;
    IUnknown *pUnk;
    REFCLSID rclsid = &CLSID_InternetZoneManager;

    pUnk = (IUnknown *)0xdeadbeef;
    hr = CoCreateInstance(rclsid, NULL, CLSCTX_INPROC_SERVER, &IID_IUnknown, (void **)&pUnk);
689
    ok(hr == CO_E_NOTINITIALIZED, "CoCreateInstance should have returned CO_E_NOTINITIALIZED instead of 0x%08x\n", hr);
690 691 692
    ok(pUnk == NULL, "CoCreateInstance should have changed the passed in pointer to NULL, instead of %p\n", pUnk);

    OleInitialize(NULL);
693 694 695 696 697 698 699 700 701 702 703

    /* test errors returned for non-registered clsids */
    hr = CoCreateInstance(&CLSID_non_existent, NULL, CLSCTX_INPROC_SERVER, &IID_IUnknown, (void **)&pUnk);
    ok(hr == REGDB_E_CLASSNOTREG, "CoCreateInstance for non-registered inproc server should have returned REGDB_E_CLASSNOTREG instead of 0x%08x\n", hr);
    hr = CoCreateInstance(&CLSID_non_existent, NULL, CLSCTX_INPROC_HANDLER, &IID_IUnknown, (void **)&pUnk);
    ok(hr == REGDB_E_CLASSNOTREG, "CoCreateInstance for non-registered inproc handler should have returned REGDB_E_CLASSNOTREG instead of 0x%08x\n", hr);
    hr = CoCreateInstance(&CLSID_non_existent, NULL, CLSCTX_LOCAL_SERVER, &IID_IUnknown, (void **)&pUnk);
    ok(hr == REGDB_E_CLASSNOTREG, "CoCreateInstance for non-registered local server should have returned REGDB_E_CLASSNOTREG instead of 0x%08x\n", hr);
    hr = CoCreateInstance(&CLSID_non_existent, NULL, CLSCTX_REMOTE_SERVER, &IID_IUnknown, (void **)&pUnk);
    ok(hr == REGDB_E_CLASSNOTREG, "CoCreateInstance for non-registered remote server should have returned REGDB_E_CLASSNOTREG instead of 0x%08x\n", hr);

704
    hr = CoCreateInstance(rclsid, NULL, CLSCTX_INPROC_SERVER, &IID_IUnknown, (void **)&pUnk);
705 706 707 708 709 710 711
    if(hr == REGDB_E_CLASSNOTREG)
    {
        skip("IE not installed so can't test CoCreateInstance\n");
        OleUninitialize();
        return;
    }

712
    ok_ole_success(hr, "CoCreateInstance");
713
    if(pUnk) IUnknown_Release(pUnk);
714 715 716
    OleUninitialize();

    hr = CoCreateInstance(rclsid, NULL, CLSCTX_INPROC_SERVER, &IID_IUnknown, (void **)&pUnk);
717
    ok(hr == CO_E_NOTINITIALIZED, "CoCreateInstance should have returned CO_E_NOTINITIALIZED instead of 0x%08x\n", hr);
718

719
    test_apt_type(APTTYPE_CURRENT, APTTYPEQUALIFIER_NONE);
720 721
}

722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743
struct comclassredirect_data
{
    ULONG size;
    ULONG flags;
    DWORD model;
    GUID  clsid;
    GUID  alias;
    GUID  clsid2;
    GUID  tlid;
    ULONG name_len;
    ULONG name_offset;
    ULONG progid_len;
    ULONG progid_offset;
    ULONG clrdata_len;
    ULONG clrdata_offset;
    DWORD miscstatus;
    DWORD miscstatuscontent;
    DWORD miscstatusthumbnail;
    DWORD miscstatusicon;
    DWORD miscstatusdocprint;
};

744 745
static void test_CoGetClassObject(void)
{
746
    HRESULT hr;
747
    HANDLE handle;
748
    ULONG_PTR cookie;
749 750
    IUnknown *pUnk;
    REFCLSID rclsid = &CLSID_InternetZoneManager;
751 752
    HKEY hkey;
    LONG res;
753 754

    hr = CoGetClassObject(rclsid, CLSCTX_INPROC_SERVER, NULL, &IID_IUnknown, (void **)&pUnk);
755
    ok(hr == CO_E_NOTINITIALIZED, "CoGetClassObject should have returned CO_E_NOTINITIALIZED instead of 0x%08x\n", hr);
756 757
    ok(pUnk == NULL, "CoGetClassObject should have changed the passed in pointer to NULL, instead of %p\n", pUnk);

758
    hr = CoGetClassObject(rclsid, CLSCTX_INPROC_SERVER, NULL, &IID_IUnknown, NULL);
759 760 761
    ok(hr == E_INVALIDARG ||
       broken(hr == CO_E_NOTINITIALIZED), /* win9x */
       "CoGetClassObject should have returned E_INVALIDARG instead of 0x%08x\n", hr);
762

763
    test_apt_type(APTTYPE_CURRENT, APTTYPEQUALIFIER_NONE);
764

765 766 767 768 769 770
    if (!pRegOverridePredefKey)
    {
        win_skip("RegOverridePredefKey not available\n");
        return;
    }

771
    CoInitializeEx(NULL, COINIT_MULTITHREADED);
772 773 774 775 776 777

    hr = CoGetClassObject(rclsid, CLSCTX_INPROC_SERVER, NULL, &IID_IUnknown, (void **)&pUnk);
    if (hr == S_OK)
    {
        IUnknown_Release(pUnk);

778
        res = RegCreateKeyExA(HKEY_CURRENT_USER, "Software\\Classes", 0, NULL, 0,
779 780
                             KEY_ALL_ACCESS, NULL, &hkey, NULL);
        ok(!res, "RegCreateKeyEx returned %d\n", res);
781 782 783 784 785 786 787 788 789 790 791 792 793

        res = pRegOverridePredefKey(HKEY_CLASSES_ROOT, hkey);
        ok(!res, "RegOverridePredefKey returned %d\n", res);

        hr = CoGetClassObject(rclsid, CLSCTX_INPROC_SERVER, NULL, &IID_IUnknown, (void **)&pUnk);
        ok(hr == S_OK, "CoGetClassObject should have returned S_OK instead of 0x%08x\n", hr);

        res = pRegOverridePredefKey(HKEY_CLASSES_ROOT, NULL);
        ok(!res, "RegOverridePredefKey returned %d\n", res);

        if (hr == S_OK) IUnknown_Release(pUnk);
        RegCloseKey(hkey);
    }
794 795 796 797 798 799 800 801 802 803 804 805

    hr = CoGetClassObject(&CLSID_InProcFreeMarshaler, CLSCTX_INPROC_SERVER, NULL, &IID_IUnknown, (void **)&pUnk);
    ok(hr == S_OK, "got 0x%08x\n", hr);
    IUnknown_Release(pUnk);

    /* context redefines FreeMarshaler CLSID */
    if ((handle = activate_context(actctx_manifest, &cookie)))
    {
        hr = CoGetClassObject(&CLSID_InProcFreeMarshaler, CLSCTX_INPROC_SERVER, NULL, &IID_IUnknown, (void **)&pUnk);
        ok(hr == S_OK, "got 0x%08x\n", hr);
        IUnknown_Release(pUnk);

806
        hr = CoGetClassObject(&IID_Testiface7, CLSCTX_INPROC_SERVER, NULL, &IID_IUnknown, (void **)&pUnk);
807
        ok(hr == 0x80001235 || broken(hr == HRESULT_FROM_WIN32(ERROR_MOD_NOT_FOUND)) /* winxp */, "Unexpected hr %#x.\n", hr);
808 809 810 811 812

        hr = CoGetClassObject(&IID_Testiface8, CLSCTX_INPROC_SERVER, NULL, &IID_IUnknown, (void **)&pUnk);
        ok(hr == REGDB_E_CLASSNOTREG, "Unexpected hr %#x.\n", hr);

        deactivate_context(handle, cookie);
813 814
    }

815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
    if ((handle = activate_context(actctx_manifest2, &cookie)))
    {
        struct comclassredirect_data *comclass;
        ACTCTX_SECTION_KEYED_DATA data;
        BOOL ret;

        /* This one will load test dll and get back specific error code. */
        hr = CoGetClassObject(&IID_Testiface7, CLSCTX_INPROC_SERVER, NULL, &IID_IUnknown, (void **)&pUnk);
        ok(hr == 0x80001235 || broken(hr == HRESULT_FROM_WIN32(ERROR_MOD_NOT_FOUND)) /* winxp */, "Unexpected hr %#x.\n", hr);

        hr = CoGetClassObject(&IID_Testiface8, CLSCTX_INPROC_SERVER, NULL, &IID_IUnknown, (void **)&pUnk);
        ok(FAILED(hr), "Unexpected hr %#x.\n", hr);

        memset(&data, 0, sizeof(data));
        data.cbSize = sizeof(data);
        ret = FindActCtxSectionGuid(0, NULL, ACTIVATION_CONTEXT_SECTION_COM_INTERFACE_REDIRECTION, &IID_Testiface8, &data);
        ok(ret, "Section not found.\n");

        memset(&data, 0, sizeof(data));
        data.cbSize = sizeof(data);

        /* External proxy-stubs are not accessible. */
        ret = FindActCtxSectionGuid(0, NULL, ACTIVATION_CONTEXT_SECTION_COM_SERVER_REDIRECTION, &IID_Testiface3, &data);
        ok(!ret, "Unexpected return value.\n");

        ret = FindActCtxSectionGuid(0, NULL, ACTIVATION_CONTEXT_SECTION_COM_SERVER_REDIRECTION, &IID_TestPS, &data);
        ok(!ret, "Unexpected return value.\n");

        ret = FindActCtxSectionGuid(0, NULL, ACTIVATION_CONTEXT_SECTION_COM_SERVER_REDIRECTION, &IID_Testiface7, &data);
        ok(ret, "Unexpected return value.\n");

        ret = FindActCtxSectionGuid(0, NULL, ACTIVATION_CONTEXT_SECTION_COM_SERVER_REDIRECTION, &IID_Testiface4, &data);
        ok(!ret, "Unexpected return value.\n");

        ret = FindActCtxSectionGuid(0, NULL, ACTIVATION_CONTEXT_SECTION_COM_SERVER_REDIRECTION, &IID_Testiface8, &data);
        ok(ret, "Unexpected return value.\n");

        comclass = data.lpData;
        if (comclass)
        {
            WCHAR *name = (WCHAR *)((char *)data.lpSectionBase + comclass->name_offset);
            ok(!lstrcmpW(name, L"testlib4.dll"), "Unexpected module name %s.\n", wine_dbgstr_w(name));
        }

        deactivate_context(handle, cookie);
    }

862
    CoUninitialize();
863 864
}

865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
static void test_CoCreateInstanceEx(void)
{
    MULTI_QI qi_res = { &IID_IMoniker };
    DWORD cookie;
    HRESULT hr;

    CoInitialize(NULL);

    hr = CoRegisterClassObject(&CLSID_WineOOPTest, (IUnknown *)&Test_ClassFactory,
                               CLSCTX_INPROC_SERVER, REGCLS_MULTIPLEUSE, &cookie);
    ok_ole_success(hr, "CoRegisterClassObject");

    create_instance_iid = IID_NULL;
    hr = CoCreateInstanceEx(&CLSID_WineOOPTest, NULL, CLSCTX_INPROC_SERVER, NULL, 1, &qi_res);
    ok(hr == E_NOINTERFACE, "CoCreateInstanceEx failed: %08x\n", hr);
    ok(IsEqualGUID(&create_instance_iid, qi_res.pIID), "Unexpected CreateInstance iid %s\n",
       wine_dbgstr_guid(&create_instance_iid));

    hr = CoRevokeClassObject(cookie);
    ok_ole_success(hr, "CoRevokeClassObject");

    CoUninitialize();
}

889 890
static ATOM register_dummy_class(void)
{
891
    WNDCLASSA wc =
892 893
    {
        0,
894
        DefWindowProcA,
895 896
        0,
        0,
897
        GetModuleHandleA(NULL),
898
        NULL,
899
        LoadCursorA(NULL, (LPSTR)IDC_ARROW),
900 901
        (HBRUSH)(COLOR_BTNFACE+1),
        NULL,
902
        "WineOleTestClass",
903
    };
904

905
    return RegisterClassA(&wc);
906 907 908 909 910 911 912
}

static void test_ole_menu(void)
{
	HWND hwndFrame;
	HRESULT hr;

913
	hwndFrame = CreateWindowA((LPCSTR)MAKEINTATOM(register_dummy_class()), "Test", 0, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, NULL, NULL);
914 915 916 917 918 919
	hr = OleSetMenuDescriptor(NULL, hwndFrame, NULL, NULL, NULL);
	todo_wine ok_ole_success(hr, "OleSetMenuDescriptor");

	DestroyWindow(hwndFrame);
}

920 921 922 923 924 925

static HRESULT WINAPI MessageFilter_QueryInterface(IMessageFilter *iface, REFIID riid, void ** ppvObj)
{
    if (ppvObj == NULL) return E_POINTER;

    if (IsEqualGUID(riid, &IID_IUnknown) ||
926
        IsEqualGUID(riid, &IID_IMessageFilter))
927
    {
928
        *ppvObj = iface;
929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973
        IMessageFilter_AddRef(iface);
        return S_OK;
    }

    return E_NOINTERFACE;
}

static ULONG WINAPI MessageFilter_AddRef(IMessageFilter *iface)
{
    return 2; /* non-heap object */
}

static ULONG WINAPI MessageFilter_Release(IMessageFilter *iface)
{
    return 1; /* non-heap object */
}

static DWORD WINAPI MessageFilter_HandleInComingCall(
  IMessageFilter *iface,
  DWORD dwCallType,
  HTASK threadIDCaller,
  DWORD dwTickCount,
  LPINTERFACEINFO lpInterfaceInfo)
{
    trace("HandleInComingCall\n");
    return SERVERCALL_ISHANDLED;
}

static DWORD WINAPI MessageFilter_RetryRejectedCall(
  IMessageFilter *iface,
  HTASK threadIDCallee,
  DWORD dwTickCount,
  DWORD dwRejectType)
{
    trace("RetryRejectedCall\n");
    return 0;
}

static DWORD WINAPI MessageFilter_MessagePending(
  IMessageFilter *iface,
  HTASK threadIDCallee,
  DWORD dwTickCount,
  DWORD dwPendingType)
{
    trace("MessagePending\n");
974
    todo_wine ok(0, "unexpected call\n");
975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995
    return PENDINGMSG_WAITNOPROCESS;
}

static const IMessageFilterVtbl MessageFilter_Vtbl =
{
    MessageFilter_QueryInterface,
    MessageFilter_AddRef,
    MessageFilter_Release,
    MessageFilter_HandleInComingCall,
    MessageFilter_RetryRejectedCall,
    MessageFilter_MessagePending
};

static IMessageFilter MessageFilter = { &MessageFilter_Vtbl };

static void test_CoRegisterMessageFilter(void)
{
    HRESULT hr;
    IMessageFilter *prev_filter;

    hr = CoRegisterMessageFilter(&MessageFilter, &prev_filter);
996 997 998
    ok(hr == CO_E_NOT_SUPPORTED,
        "CoRegisterMessageFilter should have failed with CO_E_NOT_SUPPORTED instead of 0x%08x\n",
        hr);
999

1000
    CoInitializeEx(NULL, COINIT_MULTITHREADED);
1001 1002 1003
    prev_filter = (IMessageFilter *)0xdeadbeef;
    hr = CoRegisterMessageFilter(&MessageFilter, &prev_filter);
    ok(hr == CO_E_NOT_SUPPORTED,
1004
        "CoRegisterMessageFilter should have failed with CO_E_NOT_SUPPORTED instead of 0x%08x\n",
1005 1006 1007 1008 1009
        hr);
    ok(prev_filter == (IMessageFilter *)0xdeadbeef,
        "prev_filter should have been set to %p\n", prev_filter);
    CoUninitialize();

1010
    CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029

    hr = CoRegisterMessageFilter(NULL, NULL);
    ok_ole_success(hr, "CoRegisterMessageFilter");

    prev_filter = (IMessageFilter *)0xdeadbeef;
    hr = CoRegisterMessageFilter(NULL, &prev_filter);
    ok_ole_success(hr, "CoRegisterMessageFilter");
    ok(prev_filter == NULL, "prev_filter should have been set to NULL instead of %p\n", prev_filter);

    hr = CoRegisterMessageFilter(&MessageFilter, &prev_filter);
    ok_ole_success(hr, "CoRegisterMessageFilter");
    ok(prev_filter == NULL, "prev_filter should have been set to NULL instead of %p\n", prev_filter);

    hr = CoRegisterMessageFilter(NULL, NULL);
    ok_ole_success(hr, "CoRegisterMessageFilter");

    CoUninitialize();
}

1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
static IUnknown Test_Unknown;

static HRESULT WINAPI EnumOLEVERB_QueryInterface(IEnumOLEVERB *iface, REFIID riid, void **ppv)
{
    return IUnknown_QueryInterface(&Test_Unknown, riid, ppv);
}

static ULONG WINAPI EnumOLEVERB_AddRef(IEnumOLEVERB *iface)
{
    return 2;
}

static ULONG WINAPI EnumOLEVERB_Release(IEnumOLEVERB *iface)
{
    return 1;
}

static HRESULT WINAPI EnumOLEVERB_Next(IEnumOLEVERB *iface, ULONG celt, OLEVERB *rgelt, ULONG *fetched)
{
    ok(0, "unexpected call\n");
    return E_NOTIMPL;
}

static HRESULT WINAPI EnumOLEVERB_Skip(IEnumOLEVERB *iface, ULONG celt)
{
    ok(0, "unexpected call\n");
    return E_NOTIMPL;
}

static HRESULT WINAPI EnumOLEVERB_Reset(IEnumOLEVERB *iface)
{
    ok(0, "unexpected call\n");
    return E_NOTIMPL;
}

static HRESULT WINAPI EnumOLEVERB_Clone(IEnumOLEVERB *iface, IEnumOLEVERB **ppenum)
{
    ok(0, "unexpected call\n");
    return E_NOTIMPL;
}

static const IEnumOLEVERBVtbl EnumOLEVERBVtbl = {
    EnumOLEVERB_QueryInterface,
    EnumOLEVERB_AddRef,
    EnumOLEVERB_Release,
    EnumOLEVERB_Next,
    EnumOLEVERB_Skip,
    EnumOLEVERB_Reset,
    EnumOLEVERB_Clone
};

static IEnumOLEVERB EnumOLEVERB = { &EnumOLEVERBVtbl };

1083
static HRESULT WINAPI Test_IUnknown_QueryInterface(
1084
    IUnknown *iface,
1085 1086 1087 1088 1089
    REFIID riid,
    LPVOID *ppvObj)
{
    if (ppvObj == NULL) return E_POINTER;

1090
    if (IsEqualIID(riid, &IID_IUnknown) || IsEqualIID(riid, &IID_IWineTest)) {
1091
        *ppvObj = iface;
1092 1093 1094 1095 1096
    }else if(IsEqualIID(riid, &IID_IEnumOLEVERB)) {
        *ppvObj = &EnumOLEVERB;
    }else {
        *ppvObj = NULL;
        return E_NOINTERFACE;
1097 1098
    }

1099 1100
    IUnknown_AddRef((IUnknown*)*ppvObj);
    return S_OK;
1101 1102
}

1103
static ULONG WINAPI Test_IUnknown_AddRef(IUnknown *iface)
1104 1105 1106 1107
{
    return 2; /* non-heap-based object */
}

1108
static ULONG WINAPI Test_IUnknown_Release(IUnknown *iface)
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
{
    return 1; /* non-heap-based object */
}

static const IUnknownVtbl TestUnknown_Vtbl =
{
    Test_IUnknown_QueryInterface,
    Test_IUnknown_AddRef,
    Test_IUnknown_Release,
};

static IUnknown Test_Unknown = { &TestUnknown_Vtbl };

1122 1123
static IPSFactoryBuffer *ps_factory_buffer;

1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
static HRESULT WINAPI PSFactoryBuffer_QueryInterface(
    IPSFactoryBuffer * This,
    /* [in] */ REFIID riid,
    /* [iid_is][out] */ void **ppvObject)
{
    if (IsEqualIID(riid, &IID_IUnknown) ||
        IsEqualIID(riid, &IID_IPSFactoryBuffer))
    {
        *ppvObject = This;
        IPSFactoryBuffer_AddRef(This);
        return S_OK;
    }
    return E_NOINTERFACE;
}
1138

1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
static ULONG WINAPI PSFactoryBuffer_AddRef(
    IPSFactoryBuffer * This)
{
    return 2;
}

static ULONG WINAPI PSFactoryBuffer_Release(
    IPSFactoryBuffer * This)
{
    return 1;
}

static HRESULT WINAPI PSFactoryBuffer_CreateProxy(
    IPSFactoryBuffer * This,
    /* [in] */ IUnknown *pUnkOuter,
    /* [in] */ REFIID riid,
    /* [out] */ IRpcProxyBuffer **ppProxy,
    /* [out] */ void **ppv)
{
    return E_NOTIMPL;
}
1160

1161 1162 1163 1164 1165 1166
static HRESULT WINAPI PSFactoryBuffer_CreateStub(
    IPSFactoryBuffer * This,
    /* [in] */ REFIID riid,
    /* [unique][in] */ IUnknown *pUnkServer,
    /* [out] */ IRpcStubBuffer **ppStub)
{
1167 1168
    CHECK_EXPECT(CreateStub);

1169
    ok(pUnkServer == &Test_Unknown, "unexpected pUnkServer %p\n", pUnkServer);
1170 1171 1172 1173
    if(!ps_factory_buffer)
        return E_NOTIMPL;

    return IPSFactoryBuffer_CreateStub(ps_factory_buffer, &IID_IEnumOLEVERB, pUnkServer, ppStub);
1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
}

static IPSFactoryBufferVtbl PSFactoryBufferVtbl =
{
    PSFactoryBuffer_QueryInterface,
    PSFactoryBuffer_AddRef,
    PSFactoryBuffer_Release,
    PSFactoryBuffer_CreateProxy,
    PSFactoryBuffer_CreateStub
};

static IPSFactoryBuffer PSFactoryBuffer = { &PSFactoryBufferVtbl };

static const CLSID CLSID_WineTestPSFactoryBuffer =
{
    0x52011640,
    0x8164,
    0x4fd0,
    {0xa1, 0xa2, 0x5d, 0x5a, 0x36, 0x54, 0xd3, 0xbd}
}; /* 52011640-8164-4fd0-a1a2-5d5a3654d3bd */

1195 1196 1197 1198 1199
static DWORD CALLBACK register_ps_clsid_thread(void *context)
{
    HRESULT hr;
    CLSID clsid = {0};

1200
    CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215

    hr = CoGetPSClsid(&IID_IWineTest, &clsid);
    ok_ole_success(hr, "CoGetPSClsid");
    ok(IsEqualGUID(&clsid, &CLSID_WineTestPSFactoryBuffer), "expected %s, got %s\n",
                   wine_dbgstr_guid(&CLSID_WineTestPSFactoryBuffer), wine_dbgstr_guid(&clsid));

    /* test registering a PSClsid in an apartment which is then destroyed */
    hr = CoRegisterPSClsid(&IID_TestPS, &clsid);
    ok_ole_success(hr, "CoRegisterPSClsid");

    CoUninitialize();

    return hr;
}

1216 1217 1218 1219 1220 1221
static void test_CoRegisterPSClsid(void)
{
    HRESULT hr;
    DWORD dwRegistrationKey;
    IStream *stream;
    CLSID clsid;
1222 1223
    HANDLE thread;
    DWORD tid;
1224 1225

    hr = CoRegisterPSClsid(&IID_IWineTest, &CLSID_WineTestPSFactoryBuffer);
1226
    ok(hr == CO_E_NOTINITIALIZED, "CoRegisterPSClsid should have returned CO_E_NOTINITIALIZED instead of 0x%08x\n", hr);
1227

1228
    CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
1229 1230 1231 1232 1233 1234 1235 1236

    hr = CoRegisterClassObject(&CLSID_WineTestPSFactoryBuffer, (IUnknown *)&PSFactoryBuffer,
        CLSCTX_INPROC_SERVER, REGCLS_MULTIPLEUSE, &dwRegistrationKey);
    ok_ole_success(hr, "CoRegisterClassObject");

    hr = CoRegisterPSClsid(&IID_IWineTest, &CLSID_WineTestPSFactoryBuffer);
    ok_ole_success(hr, "CoRegisterPSClsid");

1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
    hr = CoGetPSClsid(&IID_IWineTest, &clsid);
    ok_ole_success(hr, "CoGetPSClsid");
    ok(IsEqualGUID(&clsid, &CLSID_WineTestPSFactoryBuffer), "expected %s, got %s\n",
                   wine_dbgstr_guid(&CLSID_WineTestPSFactoryBuffer), wine_dbgstr_guid(&clsid));

    thread = CreateThread(NULL, 0, register_ps_clsid_thread, NULL, 0, &tid);
    ok(thread != NULL, "CreateThread failed with error %d\n", GetLastError());
    ok(!WaitForSingleObject(thread, 10000), "wait timed out\n");
    CloseHandle(thread);

    hr = CoGetPSClsid(&IID_TestPS, &clsid);
    ok_ole_success(hr, "CoGetPSClsid");
    ok(IsEqualGUID(&clsid, &CLSID_WineTestPSFactoryBuffer), "expected %s, got %s\n",
                   wine_dbgstr_guid(&CLSID_WineTestPSFactoryBuffer), wine_dbgstr_guid(&clsid));

1252 1253 1254
    hr = CreateStreamOnHGlobal(NULL, TRUE, &stream);
    ok_ole_success(hr, "CreateStreamOnHGlobal");

1255
    SET_EXPECT(CreateStub);
1256
    hr = CoMarshalInterface(stream, &IID_IWineTest, &Test_Unknown, MSHCTX_INPROC, NULL, MSHLFLAGS_NORMAL);
1257
    ok(hr == E_NOTIMPL, "CoMarshalInterface should have returned E_NOTIMPL instead of 0x%08x\n", hr);
1258
    CHECK_CALLED(CreateStub, 1);
1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270

    hr = CoGetPSClsid(&IID_IEnumOLEVERB, &clsid);
    ok_ole_success(hr, "CoGetPSClsid");

    hr = CoGetClassObject(&clsid, CLSCTX_INPROC_SERVER, NULL, &IID_IPSFactoryBuffer, (void **)&ps_factory_buffer);
    ok_ole_success(hr, "CoGetClassObject");

    hr = CoRegisterPSClsid(&IID_IEnumOLEVERB, &CLSID_WineTestPSFactoryBuffer);
    ok_ole_success(hr, "CoRegisterPSClsid");

    SET_EXPECT(CreateStub);
    hr = CoMarshalInterface(stream, &IID_IEnumOLEVERB, (IUnknown*)&EnumOLEVERB, MSHCTX_INPROC, NULL, MSHLFLAGS_NORMAL);
1271
    ok(hr == S_OK, "CoMarshalInterface should have returned S_OK instead of 0x%08x\n", hr);
1272
    CHECK_CALLED(CreateStub, 1);
1273 1274

    hr = CoMarshalInterface(stream, &IID_IEnumOLEVERB, &Test_Unknown, MSHCTX_INPROC, NULL, MSHLFLAGS_NORMAL);
1275
    ok(hr == S_OK, "CoMarshalInterface should have returned S_OK instead of 0x%08x\n", hr);
1276

1277
    IStream_Release(stream);
1278 1279
    IPSFactoryBuffer_Release(ps_factory_buffer);
    ps_factory_buffer = NULL;
1280 1281 1282 1283 1284 1285

    hr = CoRevokeClassObject(dwRegistrationKey);
    ok_ole_success(hr, "CoRevokeClassObject");

    CoUninitialize();

1286
    CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
1287 1288

    hr = CoGetPSClsid(&IID_IWineTest, &clsid);
1289
    ok(hr == REGDB_E_IIDNOTREG, "CoGetPSClsid should have returned REGDB_E_IIDNOTREG instead of 0x%08x\n", hr);
1290

1291 1292 1293 1294 1295
    hr = CoGetPSClsid(&IID_TestPS, &clsid);
    ok(hr == REGDB_E_IIDNOTREG, "CoGetPSClsid should have returned REGDB_E_IIDNOTREG instead of 0x%08x\n", hr);

    CoUninitialize();

1296
    CoInitializeEx(NULL, COINIT_MULTITHREADED);
1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315

    hr = CoRegisterPSClsid(&IID_IWineTest, &CLSID_WineTestPSFactoryBuffer);
    ok_ole_success(hr, "CoRegisterPSClsid");

    hr = CoGetPSClsid(&IID_IWineTest, &clsid);
    ok_ole_success(hr, "CoGetPSClsid");
    ok(IsEqualGUID(&clsid, &CLSID_WineTestPSFactoryBuffer), "expected %s, got %s\n",
                   wine_dbgstr_guid(&CLSID_WineTestPSFactoryBuffer), wine_dbgstr_guid(&clsid));

    thread = CreateThread(NULL, 0, register_ps_clsid_thread, NULL, 0, &tid);
    ok(thread != NULL, "CreateThread failed with error %d\n", GetLastError());
    ok(!WaitForSingleObject(thread, 10000), "wait timed out\n");
    CloseHandle(thread);

    hr = CoGetPSClsid(&IID_TestPS, &clsid);
    ok_ole_success(hr, "CoGetPSClsid");
    ok(IsEqualGUID(&clsid, &CLSID_WineTestPSFactoryBuffer), "expected %s, got %s\n",
                   wine_dbgstr_guid(&CLSID_WineTestPSFactoryBuffer), wine_dbgstr_guid(&clsid));

1316 1317 1318
    CoUninitialize();
}

1319 1320
static void test_CoGetPSClsid(void)
{
1321 1322
    ULONG_PTR cookie;
    HANDLE handle;
1323 1324
    HRESULT hr;
    CLSID clsid;
1325 1326
    HKEY hkey;
    LONG res;
1327 1328
    const BOOL is_win64 = (sizeof(void*) != sizeof(int));
    BOOL is_wow64 = FALSE;
1329 1330 1331

    hr = CoGetPSClsid(&IID_IClassFactory, &clsid);
    ok(hr == CO_E_NOTINITIALIZED,
1332
       "CoGetPSClsid should have returned CO_E_NOTINITIALIZED instead of 0x%08x\n",
1333 1334
       hr);

1335
    CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
1336 1337 1338 1339 1340 1341

    hr = CoGetPSClsid(&IID_IClassFactory, &clsid);
    ok_ole_success(hr, "CoGetPSClsid");

    hr = CoGetPSClsid(&IID_IWineTest, &clsid);
    ok(hr == REGDB_E_IIDNOTREG,
1342
       "CoGetPSClsid for random IID returned 0x%08x instead of REGDB_E_IIDNOTREG\n",
1343 1344 1345 1346
       hr);

    hr = CoGetPSClsid(&IID_IClassFactory, NULL);
    ok(hr == E_INVALIDARG,
1347
       "CoGetPSClsid for null clsid returned 0x%08x instead of E_INVALIDARG\n",
1348 1349
       hr);

1350 1351 1352 1353 1354 1355 1356 1357 1358
    if (!pRegOverridePredefKey)
    {
        win_skip("RegOverridePredefKey not available\n");
        CoUninitialize();
        return;
    }
    hr = CoGetPSClsid(&IID_IClassFactory, &clsid);
    ok_ole_success(hr, "CoGetPSClsid");

1359 1360
    res = RegCreateKeyExA(HKEY_CURRENT_USER, "Software\\Classes", 0, NULL, 0,
                          KEY_ALL_ACCESS, NULL, &hkey, NULL);
1361
    ok(!res, "RegCreateKeyEx returned %d\n", res);
1362 1363 1364 1365 1366

    res = pRegOverridePredefKey(HKEY_CLASSES_ROOT, hkey);
    ok(!res, "RegOverridePredefKey returned %d\n", res);

    hr = CoGetPSClsid(&IID_IClassFactory, &clsid);
1367
    ok_ole_success(hr, "CoGetPSClsid");
1368 1369 1370 1371 1372

    res = pRegOverridePredefKey(HKEY_CLASSES_ROOT, NULL);
    ok(!res, "RegOverridePredefKey returned %d\n", res);

    RegCloseKey(hkey);
1373 1374 1375 1376 1377 1378 1379 1380 1381 1382

    /* not registered CLSID */
    hr = CoGetPSClsid(&IID_Testiface, &clsid);
    ok(hr == REGDB_E_IIDNOTREG, "got 0x%08x\n", hr);

    if ((handle = activate_context(actctx_manifest, &cookie)))
    {
        memset(&clsid, 0, sizeof(clsid));
        hr = CoGetPSClsid(&IID_Testiface, &clsid);
        ok(hr == S_OK, "got 0x%08x\n", hr);
1383
        ok(IsEqualGUID(&clsid, &IID_Testiface), "got clsid %s\n", wine_dbgstr_guid(&clsid));
1384 1385 1386 1387

        memset(&clsid, 0, sizeof(clsid));
        hr = CoGetPSClsid(&IID_Testiface2, &clsid);
        ok(hr == S_OK, "got 0x%08x\n", hr);
1388
        ok(IsEqualGUID(&clsid, &IID_Testiface2), "got clsid %s\n", wine_dbgstr_guid(&clsid));
1389 1390 1391 1392

        memset(&clsid, 0, sizeof(clsid));
        hr = CoGetPSClsid(&IID_Testiface3, &clsid);
        ok(hr == S_OK, "got 0x%08x\n", hr);
1393
        ok(IsEqualGUID(&clsid, &IID_TestPS), "got clsid %s\n", wine_dbgstr_guid(&clsid));
1394 1395 1396 1397

        memset(&clsid, 0xaa, sizeof(clsid));
        hr = CoGetPSClsid(&IID_Testiface4, &clsid);
        ok(hr == S_OK, "got 0x%08x\n", hr);
1398
        ok(IsEqualGUID(&clsid, &GUID_NULL), "got clsid %s\n", wine_dbgstr_guid(&clsid));
1399

1400 1401 1402 1403 1404
        memset(&clsid, 0xaa, sizeof(clsid));
        hr = CoGetPSClsid(&IID_Testiface7, &clsid);
        ok(hr == S_OK, "Failed to get PS CLSID, hr %#x.\n", hr);
        ok(IsEqualGUID(&clsid, &IID_Testiface7), "Unexpected CLSID %s.\n", wine_dbgstr_guid(&clsid));

1405 1406 1407 1408 1409 1410
        /* register same interface and try to get CLSID back */
        hr = CoRegisterPSClsid(&IID_Testiface, &IID_Testiface4);
        ok(hr == S_OK, "got 0x%08x\n", hr);
        memset(&clsid, 0, sizeof(clsid));
        hr = CoGetPSClsid(&IID_Testiface, &clsid);
        ok(hr == S_OK, "got 0x%08x\n", hr);
1411
        ok(IsEqualGUID(&clsid, &IID_Testiface4), "got clsid %s\n", wine_dbgstr_guid(&clsid));
1412

1413
        deactivate_context(handle, cookie);
1414 1415
    }

1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433
    if (pRegDeleteKeyExA &&
        (is_win64 ||
         (pIsWow64Process && pIsWow64Process(GetCurrentProcess(), &is_wow64) && is_wow64)))
    {
        static GUID IID_DeadBeef = {0xdeadbeef,0xdead,0xbeef,{0xde,0xad,0xbe,0xef,0xde,0xad,0xbe,0xef}};
        static const char clsidDeadBeef[] = "{deadbeef-dead-beef-dead-beefdeadbeef}";
        static const char clsidA[] = "{66666666-8888-7777-6666-555555555555}";
        HKEY hkey_iface, hkey_psclsid;
        REGSAM opposite = is_win64 ? KEY_WOW64_32KEY : KEY_WOW64_64KEY;

        hr = CoGetPSClsid(&IID_DeadBeef, &clsid);
        ok(hr == REGDB_E_IIDNOTREG, "got 0x%08x\n", hr);

        res = RegCreateKeyExA(HKEY_CLASSES_ROOT, "Interface",
                              0, NULL, 0, KEY_ALL_ACCESS | opposite, NULL, &hkey_iface, NULL);
        ok(!res, "RegCreateKeyEx returned %d\n", res);
        res = RegCreateKeyExA(hkey_iface, clsidDeadBeef,
                              0, NULL, 0, KEY_ALL_ACCESS | opposite, NULL, &hkey, NULL);
1434 1435 1436 1437 1438 1439
        if (res == ERROR_ACCESS_DENIED)
        {
            win_skip("Failed to create a key, skipping some of CoGetPSClsid() tests\n");
            goto cleanup;
        }

1440 1441 1442
        ok(!res, "RegCreateKeyEx returned %d\n", res);
        res = RegCreateKeyExA(hkey, "ProxyStubClsid32",
                              0, NULL, 0, KEY_ALL_ACCESS | opposite, NULL, &hkey_psclsid, NULL);
1443
        ok(!res, "RegCreateKeyEx returned %d\n", res);
1444 1445 1446 1447 1448
        res = RegSetValueExA(hkey_psclsid, NULL, 0, REG_SZ, (const BYTE *)clsidA, strlen(clsidA)+1);
        ok(!res, "RegSetValueEx returned %d\n", res);
        RegCloseKey(hkey_psclsid);

        hr = CoGetPSClsid(&IID_DeadBeef, &clsid);
1449 1450
        ok_ole_success(hr, "CoGetPSClsid");
        ok(IsEqualGUID(&clsid, &IID_TestPS), "got clsid %s\n", wine_dbgstr_guid(&clsid));
1451 1452 1453 1454 1455 1456

        res = pRegDeleteKeyExA(hkey, "ProxyStubClsid32", opposite, 0);
        ok(!res, "RegDeleteKeyEx returned %d\n", res);
        RegCloseKey(hkey);
        res = pRegDeleteKeyExA(hkey_iface, clsidDeadBeef, opposite, 0);
        ok(!res, "RegDeleteKeyEx returned %d\n", res);
1457 1458

    cleanup:
1459 1460 1461
        RegCloseKey(hkey_iface);
    }

1462 1463 1464
    CoUninitialize();
}

1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477
/* basic test, mainly for invalid arguments. see marshal.c for more */
static void test_CoUnmarshalInterface(void)
{
    IUnknown *pProxy;
    IStream *pStream;
    HRESULT hr;

    hr = CoUnmarshalInterface(NULL, &IID_IUnknown, (void **)&pProxy);
    ok(hr == E_INVALIDARG, "CoUnmarshalInterface should have returned E_INVALIDARG instead of 0x%08x\n", hr);

    hr = CreateStreamOnHGlobal(NULL, TRUE, &pStream);
    ok_ole_success(hr, "CreateStreamOnHGlobal");

1478 1479 1480 1481
    hr = CoUnmarshalInterface(pStream, &IID_IUnknown, (void **)&pProxy);
    todo_wine
    ok(hr == CO_E_NOTINITIALIZED, "CoUnmarshalInterface should have returned CO_E_NOTINITIALIZED instead of 0x%08x\n", hr);

1482
    CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
1483

1484 1485 1486
    hr = CoUnmarshalInterface(pStream, &IID_IUnknown, (void **)&pProxy);
    ok(hr == STG_E_READFAULT, "CoUnmarshalInterface should have returned STG_E_READFAULT instead of 0x%08x\n", hr);

1487 1488
    CoUninitialize();

1489 1490 1491 1492 1493 1494
    hr = CoUnmarshalInterface(pStream, &IID_IUnknown, NULL);
    ok(hr == E_INVALIDARG, "CoUnmarshalInterface should have returned E_INVALIDARG instead of 0x%08x\n", hr);

    IStream_Release(pStream);
}

1495 1496 1497 1498 1499
static void test_CoGetInterfaceAndReleaseStream(void)
{
    HRESULT hr;
    IUnknown *pUnk;

1500
    CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
1501 1502 1503 1504 1505 1506

    hr = CoGetInterfaceAndReleaseStream(NULL, &IID_IUnknown, (void**)&pUnk);
    ok(hr == E_INVALIDARG, "hr %08x\n", hr);

    CoUninitialize();
}
1507

1508
/* basic test, mainly for invalid arguments. see marshal.c for more */
1509 1510 1511 1512 1513 1514
static void test_CoMarshalInterface(void)
{
    IStream *pStream;
    HRESULT hr;
    static const LARGE_INTEGER llZero;

1515
    CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549

    hr = CreateStreamOnHGlobal(NULL, TRUE, &pStream);
    ok_ole_success(hr, "CreateStreamOnHGlobal");

    hr = CoMarshalInterface(pStream, &IID_IUnknown, NULL, MSHCTX_INPROC, NULL, MSHLFLAGS_NORMAL);
    ok(hr == E_INVALIDARG, "CoMarshalInterface should have returned E_INVALIDARG instead of 0x%08x\n", hr);

    hr = CoMarshalInterface(NULL, &IID_IUnknown, (IUnknown *)&Test_ClassFactory, MSHCTX_INPROC, NULL, MSHLFLAGS_NORMAL);
    ok(hr == E_INVALIDARG, "CoMarshalInterface should have returned E_INVALIDARG instead of 0x%08x\n", hr);

    hr = CoMarshalInterface(pStream, &IID_IUnknown, (IUnknown *)&Test_ClassFactory, MSHCTX_INPROC, NULL, MSHLFLAGS_NORMAL);
    ok_ole_success(hr, "CoMarshalInterface");

    /* stream not rewound */
    hr = CoReleaseMarshalData(pStream);
    ok(hr == STG_E_READFAULT, "CoReleaseMarshalData should have returned STG_E_READFAULT instead of 0x%08x\n", hr);

    hr = IStream_Seek(pStream, llZero, STREAM_SEEK_SET, NULL);
    ok_ole_success(hr, "IStream_Seek");

    hr = CoReleaseMarshalData(pStream);
    ok_ole_success(hr, "CoReleaseMarshalData");

    IStream_Release(pStream);

    CoUninitialize();
}

static void test_CoMarshalInterThreadInterfaceInStream(void)
{
    IStream *pStream;
    HRESULT hr;
    IClassFactory *pProxy;

1550
    CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570

    cLocks = 0;

    hr = CoMarshalInterThreadInterfaceInStream(&IID_IUnknown, (IUnknown *)&Test_ClassFactory, NULL);
    ok(hr == E_INVALIDARG, "CoMarshalInterThreadInterfaceInStream should have returned E_INVALIDARG instead of 0x%08x\n", hr);

    hr = CoMarshalInterThreadInterfaceInStream(&IID_IUnknown, NULL, &pStream);
    ok(hr == E_INVALIDARG, "CoMarshalInterThreadInterfaceInStream should have returned E_INVALIDARG instead of 0x%08x\n", hr);

    ok_no_locks();

    hr = CoMarshalInterThreadInterfaceInStream(&IID_IUnknown, (IUnknown *)&Test_ClassFactory, &pStream);
    ok_ole_success(hr, "CoMarshalInterThreadInterfaceInStream");

    ok_more_than_one_lock();

    hr = CoUnmarshalInterface(pStream, &IID_IClassFactory, (void **)&pProxy);
    ok_ole_success(hr, "CoUnmarshalInterface");

    IClassFactory_Release(pProxy);
1571
    IStream_Release(pStream);
1572 1573 1574 1575 1576 1577

    ok_no_locks();

    CoUninitialize();
}

1578 1579
static void test_CoRegisterClassObject(void)
{
1580 1581
    ULONG_PTR ctxcookie;
    HANDLE handle;
1582 1583
    DWORD cookie;
    HRESULT hr;
1584
    IClassFactory *pcf;
1585

1586
    CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631

    /* CLSCTX_INPROC_SERVER */
    hr = CoRegisterClassObject(&CLSID_WineOOPTest, (IUnknown *)&Test_ClassFactory,
                               CLSCTX_INPROC_SERVER, REGCLS_SINGLEUSE, &cookie);
    ok_ole_success(hr, "CoRegisterClassObject");
    hr = CoRevokeClassObject(cookie);
    ok_ole_success(hr, "CoRevokeClassObject");

    hr = CoRegisterClassObject(&CLSID_WineOOPTest, (IUnknown *)&Test_ClassFactory,
                               CLSCTX_INPROC_SERVER, REGCLS_MULTIPLEUSE, &cookie);
    ok_ole_success(hr, "CoRegisterClassObject");
    hr = CoRevokeClassObject(cookie);
    ok_ole_success(hr, "CoRevokeClassObject");

    hr = CoRegisterClassObject(&CLSID_WineOOPTest, (IUnknown *)&Test_ClassFactory,
                               CLSCTX_INPROC_SERVER, REGCLS_MULTI_SEPARATE, &cookie);
    ok_ole_success(hr, "CoRegisterClassObject");
    hr = CoRevokeClassObject(cookie);
    ok_ole_success(hr, "CoRevokeClassObject");

    /* CLSCTX_LOCAL_SERVER */
    hr = CoRegisterClassObject(&CLSID_WineOOPTest, (IUnknown *)&Test_ClassFactory,
                               CLSCTX_LOCAL_SERVER, REGCLS_SINGLEUSE, &cookie);
    ok_ole_success(hr, "CoRegisterClassObject");
    hr = CoRevokeClassObject(cookie);
    ok_ole_success(hr, "CoRevokeClassObject");

    hr = CoRegisterClassObject(&CLSID_WineOOPTest, (IUnknown *)&Test_ClassFactory,
                               CLSCTX_LOCAL_SERVER, REGCLS_MULTIPLEUSE, &cookie);
    ok_ole_success(hr, "CoRegisterClassObject");
    hr = CoRevokeClassObject(cookie);
    ok_ole_success(hr, "CoRevokeClassObject");

    hr = CoRegisterClassObject(&CLSID_WineOOPTest, (IUnknown *)&Test_ClassFactory,
                               CLSCTX_LOCAL_SERVER, REGCLS_MULTI_SEPARATE, &cookie);
    ok_ole_success(hr, "CoRegisterClassObject");
    hr = CoRevokeClassObject(cookie);
    ok_ole_success(hr, "CoRevokeClassObject");

    /* CLSCTX_INPROC_SERVER|CLSCTX_LOCAL_SERVER */
    hr = CoRegisterClassObject(&CLSID_WineOOPTest, (IUnknown *)&Test_ClassFactory,
                               CLSCTX_INPROC_SERVER|CLSCTX_LOCAL_SERVER, REGCLS_SINGLEUSE, &cookie);
    ok_ole_success(hr, "CoRegisterClassObject");
    hr = CoRevokeClassObject(cookie);
    ok_ole_success(hr, "CoRevokeClassObject");
1632 1633 1634 1635 1636 1637 1638 1639

    /* test whether an object that doesn't support IClassFactory can be
     * registered for CLSCTX_LOCAL_SERVER */
    hr = CoRegisterClassObject(&CLSID_WineOOPTest, &Test_Unknown,
                               CLSCTX_LOCAL_SERVER, REGCLS_SINGLEUSE, &cookie);
    ok_ole_success(hr, "CoRegisterClassObject");
    hr = CoRevokeClassObject(cookie);
    ok_ole_success(hr, "CoRevokeClassObject");
1640

1641 1642 1643 1644 1645 1646
    /* test whether registered class becomes invalid when apartment is destroyed */
    hr = CoRegisterClassObject(&CLSID_WineOOPTest, (IUnknown *)&Test_ClassFactory,
                               CLSCTX_INPROC_SERVER, REGCLS_SINGLEUSE, &cookie);
    ok_ole_success(hr, "CoRegisterClassObject");

    CoUninitialize();
1647
    CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
1648 1649 1650 1651 1652 1653 1654

    hr = CoGetClassObject(&CLSID_WineOOPTest, CLSCTX_INPROC_SERVER, NULL,
                          &IID_IClassFactory, (void **)&pcf);
    ok(hr == REGDB_E_CLASSNOTREG, "object registered in an apartment shouldn't accessible after it is destroyed\n");

    /* crashes with at least win9x DCOM! */
    if (0)
1655
        CoRevokeClassObject(cookie);
1656

1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669
    /* test that object is accessible */
    hr = CoRegisterClassObject(&CLSID_WineOOPTest, (IUnknown *)&Test_ClassFactory, CLSCTX_INPROC_SERVER,
        REGCLS_MULTIPLEUSE, &cookie);
    ok(hr == S_OK, "got 0x%08x\n", hr);

    hr = CoGetClassObject(&CLSID_WineOOPTest, CLSCTX_INPROC_SERVER, NULL, &IID_IClassFactory, (void**)&pcf);
    ok(hr == S_OK, "got 0x%08x\n", hr);
    IClassFactory_Release(pcf);

    /* context now contains CLSID_WineOOPTest, test if registered one could still be used */
    if ((handle = activate_context(actctx_manifest, &ctxcookie)))
    {
        hr = CoGetClassObject(&CLSID_WineOOPTest, CLSCTX_INPROC_SERVER, NULL, &IID_IClassFactory, (void**)&pcf);
1670
        ok(hr == 0x80001234 || broken(hr == HRESULT_FROM_WIN32(ERROR_MOD_NOT_FOUND)) /* winxp */, "Unexpected hr %#x.\n", hr);
1671

1672
        deactivate_context(handle, ctxcookie);
1673 1674 1675 1676 1677 1678 1679 1680 1681
    }

    hr = CoGetClassObject(&CLSID_WineOOPTest, CLSCTX_INPROC_SERVER, NULL, &IID_IClassFactory, (void**)&pcf);
    ok(hr == S_OK, "got 0x%08x\n", hr);
    IClassFactory_Release(pcf);

    hr = CoRevokeClassObject(cookie);
    ok(hr == S_OK, "got 0x%08x\n", hr);

1682 1683 1684
    CoUninitialize();
}

1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703
static HRESULT get_class_object(CLSCTX clsctx)
{
    HRESULT hr;
    IClassFactory *pcf;

    hr = CoGetClassObject(&CLSID_WineOOPTest, clsctx, NULL, &IID_IClassFactory,
                          (void **)&pcf);

    if (SUCCEEDED(hr))
        IClassFactory_Release(pcf);

    return hr;
}

static DWORD CALLBACK get_class_object_thread(LPVOID pv)
{
    CLSCTX clsctx = (CLSCTX)(DWORD_PTR)pv;
    HRESULT hr;

1704
    CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
1705 1706 1707 1708 1709 1710 1711 1712

    hr = get_class_object(clsctx);

    CoUninitialize();

    return hr;
}

1713 1714 1715 1716 1717 1718 1719
static DWORD CALLBACK get_class_object_proxy_thread(LPVOID pv)
{
    CLSCTX clsctx = (CLSCTX)(DWORD_PTR)pv;
    HRESULT hr;
    IClassFactory *pcf;
    IMultiQI *pMQI;

1720
    CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737

    hr = CoGetClassObject(&CLSID_WineOOPTest, clsctx, NULL, &IID_IClassFactory,
                          (void **)&pcf);

    if (SUCCEEDED(hr))
    {
        hr = IClassFactory_QueryInterface(pcf, &IID_IMultiQI, (void **)&pMQI);
        if (SUCCEEDED(hr))
            IMultiQI_Release(pMQI);
        IClassFactory_Release(pcf);
    }

    CoUninitialize();

    return hr;
}

1738 1739 1740 1741 1742
static DWORD CALLBACK register_class_object_thread(LPVOID pv)
{
    HRESULT hr;
    DWORD cookie;

1743
    CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757

    hr = CoRegisterClassObject(&CLSID_WineOOPTest, (IUnknown *)&Test_ClassFactory,
                               CLSCTX_INPROC_SERVER, REGCLS_SINGLEUSE, &cookie);

    CoUninitialize();

    return hr;
}

static DWORD CALLBACK revoke_class_object_thread(LPVOID pv)
{
    DWORD cookie = (DWORD_PTR)pv;
    HRESULT hr;

1758
    CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774

    hr = CoRevokeClassObject(cookie);

    CoUninitialize();

    return hr;
}

static void test_registered_object_thread_affinity(void)
{
    HRESULT hr;
    DWORD cookie;
    HANDLE thread;
    DWORD tid;
    DWORD exitcode;

1775
    CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
1776 1777 1778 1779 1780 1781 1782 1783 1784

    /* CLSCTX_INPROC_SERVER */

    hr = CoRegisterClassObject(&CLSID_WineOOPTest, (IUnknown *)&Test_ClassFactory,
                               CLSCTX_INPROC_SERVER, REGCLS_SINGLEUSE, &cookie);
    ok_ole_success(hr, "CoRegisterClassObject");

    thread = CreateThread(NULL, 0, get_class_object_thread, (LPVOID)CLSCTX_INPROC_SERVER, 0, &tid);
    ok(thread != NULL, "CreateThread failed with error %d\n", GetLastError());
1785
    ok( !WaitForSingleObject(thread, 10000), "wait timed out\n" );
1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797
    GetExitCodeThread(thread, &exitcode);
    hr = exitcode;
    ok(hr == REGDB_E_CLASSNOTREG, "CoGetClassObject on inproc object "
       "registered in different thread should return REGDB_E_CLASSNOTREG "
       "instead of 0x%08x\n", hr);

    hr = get_class_object(CLSCTX_INPROC_SERVER);
    ok(hr == S_OK, "CoGetClassObject on inproc object registered in same "
       "thread should return S_OK instead of 0x%08x\n", hr);

    thread = CreateThread(NULL, 0, register_class_object_thread, NULL, 0, &tid);
    ok(thread != NULL, "CreateThread failed with error %d\n", GetLastError());
1798
    ok ( !WaitForSingleObject(thread, 10000), "wait timed out\n" );
1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811
    GetExitCodeThread(thread, &exitcode);
    hr = exitcode;
    ok(hr == S_OK, "CoRegisterClassObject with same CLSID but in different thread should return S_OK instead of 0x%08x\n", hr);

    hr = CoRevokeClassObject(cookie);
    ok_ole_success(hr, "CoRevokeClassObject");

    /* CLSCTX_LOCAL_SERVER */

    hr = CoRegisterClassObject(&CLSID_WineOOPTest, (IUnknown *)&Test_ClassFactory,
                               CLSCTX_LOCAL_SERVER, REGCLS_MULTIPLEUSE, &cookie);
    ok_ole_success(hr, "CoRegisterClassObject");

1812
    thread = CreateThread(NULL, 0, get_class_object_proxy_thread, (LPVOID)CLSCTX_LOCAL_SERVER, 0, &tid);
1813
    ok(thread != NULL, "CreateThread failed with error %d\n", GetLastError());
1814
    while (MsgWaitForMultipleObjects(1, &thread, FALSE, 10000, QS_ALLINPUT) == WAIT_OBJECT_0 + 1)
1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832
    {
        MSG msg;
        while (PeekMessageA(&msg, NULL, 0, 0, PM_REMOVE))
        {
            TranslateMessage(&msg);
            DispatchMessageA(&msg);
        }
    }
    GetExitCodeThread(thread, &exitcode);
    hr = exitcode;
    ok(hr == S_OK, "CoGetClassObject on local server object "
       "registered in different thread should return S_OK "
       "instead of 0x%08x\n", hr);

    hr = get_class_object(CLSCTX_LOCAL_SERVER);
    ok(hr == S_OK, "CoGetClassObject on local server object registered in same "
       "thread should return S_OK instead of 0x%08x\n", hr);

1833
    thread = CreateThread(NULL, 0, revoke_class_object_thread, (LPVOID)(DWORD_PTR)cookie, 0, &tid);
1834
    ok(thread != NULL, "CreateThread failed with error %d\n", GetLastError());
1835
    ok( !WaitForSingleObject(thread, 10000), "wait timed out\n" );
1836 1837
    GetExitCodeThread(thread, &exitcode);
    hr = exitcode;
1838
    ok(hr == RPC_E_WRONG_THREAD || broken(hr == S_OK) /* win8 */, "CoRevokeClassObject called from different "
1839 1840 1841 1842
       "thread to where registered should return RPC_E_WRONG_THREAD instead of 0x%08x\n", hr);

    thread = CreateThread(NULL, 0, register_class_object_thread, NULL, 0, &tid);
    ok(thread != NULL, "CreateThread failed with error %d\n", GetLastError());
1843
    ok( !WaitForSingleObject(thread, 10000), "wait timed out\n" );
1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854
    GetExitCodeThread(thread, &exitcode);
    hr = exitcode;
    ok(hr == S_OK, "CoRegisterClassObject with same CLSID but in different "
        "thread should return S_OK instead of 0x%08x\n", hr);

    hr = CoRevokeClassObject(cookie);
    ok_ole_success(hr, "CoRevokeClassObject");

    CoUninitialize();
}

1855 1856 1857 1858 1859 1860 1861 1862
static DWORD CALLBACK free_libraries_thread(LPVOID p)
{
    CoFreeUnusedLibraries();
    return 0;
}

static inline BOOL is_module_loaded(const char *module)
{
1863
    return GetModuleHandleA(module) != 0;
1864 1865 1866 1867 1868 1869 1870 1871 1872
}

static void test_CoFreeUnusedLibraries(void)
{
    HRESULT hr;
    IUnknown *pUnk;
    DWORD tid;
    HANDLE thread;

1873
    CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
1874 1875 1876

    ok(!is_module_loaded("urlmon.dll"), "urlmon.dll shouldn't be loaded\n");

1877
    hr = CoCreateInstance(&CLSID_FileProtocol, NULL, CLSCTX_INPROC_SERVER, &IID_IInternetProtocol, (void **)&pUnk);
1878 1879
    if (hr == REGDB_E_CLASSNOTREG)
    {
1880
        skip("IE not installed so can't run CoFreeUnusedLibraries test\n");
1881
        CoUninitialize();
1882 1883 1884 1885 1886 1887
        return;
    }
    ok_ole_success(hr, "CoCreateInstance");

    ok(is_module_loaded("urlmon.dll"), "urlmon.dll should be loaded\n");

1888 1889 1890
    ok(pUnk != NULL ||
       broken(pUnk == NULL), /* win9x */
       "Expected a valid pointer\n");
1891 1892
    if (pUnk)
        IUnknown_Release(pUnk);
1893 1894 1895 1896

    ok(is_module_loaded("urlmon.dll"), "urlmon.dll should be loaded\n");

    thread = CreateThread(NULL, 0, free_libraries_thread, NULL, 0, &tid);
1897
    ok( !WaitForSingleObject(thread, 10000), "wait timed out\n" );
1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908
    CloseHandle(thread);

    ok(is_module_loaded("urlmon.dll"), "urlmon.dll should be loaded\n");

    CoFreeUnusedLibraries();

    ok(!is_module_loaded("urlmon.dll"), "urlmon.dll shouldn't be loaded\n");

    CoUninitialize();
}

1909 1910 1911 1912
static void test_CoGetObjectContext(void)
{
    HRESULT hr;
    ULONG refs;
1913
    IComThreadingInfo *pComThreadingInfo, *threadinginfo2;
1914
    IContextCallback *pContextCallback;
1915
    IObjContext *pObjContext;
1916 1917
    APTTYPE apttype;
    THDTYPE thdtype;
1918
    GUID id, id2;
1919 1920 1921

    if (!pCoGetObjectContext)
    {
1922
        win_skip("CoGetObjectContext not present\n");
1923 1924 1925 1926 1927 1928 1929
        return;
    }

    hr = pCoGetObjectContext(&IID_IComThreadingInfo, (void **)&pComThreadingInfo);
    ok(hr == CO_E_NOTINITIALIZED, "CoGetObjectContext should have returned CO_E_NOTINITIALIZED instead of 0x%08x\n", hr);
    ok(pComThreadingInfo == NULL, "pComThreadingInfo should have been set to NULL\n");

1930
    CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
1931

1932
    test_apt_type(APTTYPE_MAINSTA, APTTYPEQUALIFIER_NONE);
1933

1934
    hr = pCoGetObjectContext(&IID_IComThreadingInfo, (void **)&pComThreadingInfo);
1935
    ok_ole_success(hr, "CoGetObjectContext");
1936

1937 1938 1939 1940 1941 1942
    threadinginfo2 = NULL;
    hr = pCoGetObjectContext(&IID_IComThreadingInfo, (void **)&threadinginfo2);
    ok(hr == S_OK, "Expected S_OK, got 0x%08x\n", hr);
    ok(pComThreadingInfo == threadinginfo2, "got different instance\n");
    IComThreadingInfo_Release(threadinginfo2);

1943 1944 1945 1946 1947 1948 1949 1950 1951 1952
    hr = IComThreadingInfo_GetCurrentLogicalThreadId(pComThreadingInfo, NULL);
    ok(hr == E_INVALIDARG, "got 0x%08x\n", hr);

    id = id2 = GUID_NULL;
    hr = IComThreadingInfo_GetCurrentLogicalThreadId(pComThreadingInfo, &id);
    ok(hr == S_OK, "got 0x%08x\n", hr);

    hr = CoGetCurrentLogicalThreadId(&id2);
    ok(IsEqualGUID(&id, &id2), "got %s, expected %s\n", wine_dbgstr_guid(&id), wine_dbgstr_guid(&id2));

1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963
    hr = IComThreadingInfo_GetCurrentApartmentType(pComThreadingInfo, &apttype);
    ok_ole_success(hr, "IComThreadingInfo_GetCurrentApartmentType");
    ok(apttype == APTTYPE_MAINSTA, "apartment type should be APTTYPE_MAINSTA instead of %d\n", apttype);

    hr = IComThreadingInfo_GetCurrentThreadType(pComThreadingInfo, &thdtype);
    ok_ole_success(hr, "IComThreadingInfo_GetCurrentThreadType");
    ok(thdtype == THDTYPE_PROCESSMESSAGES, "thread type should be THDTYPE_PROCESSMESSAGES instead of %d\n", thdtype);

    refs = IComThreadingInfo_Release(pComThreadingInfo);
    ok(refs == 0, "pComThreadingInfo should have 0 refs instead of %d refs\n", refs);

1964 1965 1966
    hr = pCoGetObjectContext(&IID_IContextCallback, (void **)&pContextCallback);
    ok_ole_success(hr, "CoGetObjectContext(ContextCallback)");

1967 1968
    refs = IContextCallback_Release(pContextCallback);
    ok(refs == 0, "pContextCallback should have 0 refs instead of %d refs\n", refs);
1969

1970 1971
    CoUninitialize();

1972
    CoInitializeEx(NULL, COINIT_MULTITHREADED);
1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987

    hr = pCoGetObjectContext(&IID_IComThreadingInfo, (void **)&pComThreadingInfo);
    ok_ole_success(hr, "CoGetObjectContext");

    hr = IComThreadingInfo_GetCurrentApartmentType(pComThreadingInfo, &apttype);
    ok_ole_success(hr, "IComThreadingInfo_GetCurrentApartmentType");
    ok(apttype == APTTYPE_MTA, "apartment type should be APTTYPE_MTA instead of %d\n", apttype);

    hr = IComThreadingInfo_GetCurrentThreadType(pComThreadingInfo, &thdtype);
    ok_ole_success(hr, "IComThreadingInfo_GetCurrentThreadType");
    ok(thdtype == THDTYPE_BLOCKMESSAGES, "thread type should be THDTYPE_BLOCKMESSAGES instead of %d\n", thdtype);

    refs = IComThreadingInfo_Release(pComThreadingInfo);
    ok(refs == 0, "pComThreadingInfo should have 0 refs instead of %d refs\n", refs);

1988 1989 1990
    hr = pCoGetObjectContext(&IID_IContextCallback, (void **)&pContextCallback);
    ok_ole_success(hr, "CoGetObjectContext(ContextCallback)");

1991 1992
    refs = IContextCallback_Release(pContextCallback);
    ok(refs == 0, "pContextCallback should have 0 refs instead of %d refs\n", refs);
1993

1994 1995 1996 1997 1998 1999
    hr = pCoGetObjectContext(&IID_IObjContext, (void **)&pObjContext);
    ok_ole_success(hr, "CoGetObjectContext");

    refs = IObjContext_Release(pObjContext);
    ok(refs == 0, "pObjContext should have 0 refs instead of %d refs\n", refs);

2000 2001
    CoUninitialize();
}
2002

2003
typedef struct {
2004
    IUnknown IUnknown_iface;
2005 2006 2007
    LONG refs;
} Test_CallContext;

2008 2009 2010 2011 2012
static inline Test_CallContext *impl_from_IUnknown(IUnknown *iface)
{
    return CONTAINING_RECORD(iface, Test_CallContext, IUnknown_iface);
}

2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032
static HRESULT WINAPI Test_CallContext_QueryInterface(
    IUnknown *iface,
    REFIID riid,
    LPVOID *ppvObj)
{
    if (ppvObj == NULL) return E_POINTER;

    if (IsEqualGUID(riid, &IID_IUnknown))
    {
        *ppvObj = iface;
        IUnknown_AddRef(iface);
        return S_OK;
    }

    *ppvObj = NULL;
    return E_NOINTERFACE;
}

static ULONG WINAPI Test_CallContext_AddRef(IUnknown *iface)
{
2033
    Test_CallContext *This = impl_from_IUnknown(iface);
2034 2035 2036 2037 2038
    return InterlockedIncrement(&This->refs);
}

static ULONG WINAPI Test_CallContext_Release(IUnknown *iface)
{
2039
    Test_CallContext *This = impl_from_IUnknown(iface);
2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057
    ULONG refs = InterlockedDecrement(&This->refs);
    if (!refs)
        HeapFree(GetProcessHeap(), 0, This);
    return refs;
}

static const IUnknownVtbl TestCallContext_Vtbl =
{
    Test_CallContext_QueryInterface,
    Test_CallContext_AddRef,
    Test_CallContext_Release
};

static void test_CoGetCallContext(void)
{
    HRESULT hr;
    ULONG refs;
    IUnknown *pUnk;
2058
    Test_CallContext *test_object;
2059 2060 2061 2062 2063 2064 2065 2066 2067 2068

    if (!pCoSwitchCallContext)
    {
        skip("CoSwitchCallContext not present\n");
        return;
    }

    CoInitialize(NULL);

    test_object = HeapAlloc(GetProcessHeap(), 0, sizeof(Test_CallContext));
2069 2070
    test_object->IUnknown_iface.lpVtbl = &TestCallContext_Vtbl;
    test_object->refs = 1;
2071 2072 2073 2074 2075

    hr = CoGetCallContext(&IID_IUnknown, (void**)&pUnk);
    ok(hr == RPC_E_CALL_COMPLETE, "Expected RPC_E_CALL_COMPLETE, got 0x%08x\n", hr);

    pUnk = (IUnknown*)0xdeadbeef;
2076
    hr = pCoSwitchCallContext(&test_object->IUnknown_iface, &pUnk);
2077 2078
    ok_ole_success(hr, "CoSwitchCallContext");
    ok(pUnk == NULL, "expected NULL, got %p\n", pUnk);
2079
    refs = IUnknown_AddRef(&test_object->IUnknown_iface);
2080
    ok(refs == 2, "Expected refcount 2, got %d\n", refs);
2081
    IUnknown_Release(&test_object->IUnknown_iface);
2082 2083 2084 2085

    pUnk = (IUnknown*)0xdeadbeef;
    hr = CoGetCallContext(&IID_IUnknown, (void**)&pUnk);
    ok_ole_success(hr, "CoGetCallContext");
2086 2087 2088
    ok(pUnk == &test_object->IUnknown_iface, "expected %p, got %p\n",
       &test_object->IUnknown_iface, pUnk);
    refs = IUnknown_AddRef(&test_object->IUnknown_iface);
2089
    ok(refs == 3, "Expected refcount 3, got %d\n", refs);
2090
    IUnknown_Release(&test_object->IUnknown_iface);
2091 2092 2093 2094 2095
    IUnknown_Release(pUnk);

    pUnk = (IUnknown*)0xdeadbeef;
    hr = pCoSwitchCallContext(NULL, &pUnk);
    ok_ole_success(hr, "CoSwitchCallContext");
2096 2097 2098
    ok(pUnk == &test_object->IUnknown_iface, "expected %p, got %p\n",
       &test_object->IUnknown_iface, pUnk);
    refs = IUnknown_AddRef(&test_object->IUnknown_iface);
2099
    ok(refs == 2, "Expected refcount 2, got %d\n", refs);
2100
    IUnknown_Release(&test_object->IUnknown_iface);
2101 2102 2103 2104

    hr = CoGetCallContext(&IID_IUnknown, (void**)&pUnk);
    ok(hr == RPC_E_CALL_COMPLETE, "Expected RPC_E_CALL_COMPLETE, got 0x%08x\n", hr);

2105
    IUnknown_Release(&test_object->IUnknown_iface);
2106 2107 2108 2109

    CoUninitialize();
}

2110 2111 2112 2113
static void test_CoGetContextToken(void)
{
    HRESULT hr;
    ULONG refs;
2114
    ULONG_PTR token, token2;
2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127
    IObjContext *ctx;

    if (!pCoGetContextToken)
    {
        win_skip("CoGetContextToken not present\n");
        return;
    }

    token = 0xdeadbeef;
    hr = pCoGetContextToken(&token);
    ok(hr == CO_E_NOTINITIALIZED, "Expected CO_E_NOTINITIALIZED, got 0x%08x\n", hr);
    ok(token == 0xdeadbeef, "Expected 0, got 0x%lx\n", token);

2128
    test_apt_type(APTTYPE_CURRENT, APTTYPEQUALIFIER_NONE);
2129

2130 2131
    CoInitialize(NULL);

2132
    test_apt_type(APTTYPE_MAINSTA, APTTYPEQUALIFIER_NONE);
2133

2134 2135 2136 2137 2138 2139 2140 2141
    hr = pCoGetContextToken(NULL);
    ok(hr == E_POINTER, "Expected E_POINTER, got 0x%08x\n", hr);

    token = 0;
    hr = pCoGetContextToken(&token);
    ok(hr == S_OK, "Expected S_OK, got 0x%08x\n", hr);
    ok(token, "Expected token != 0\n");

2142 2143 2144 2145 2146
    token2 = 0;
    hr = pCoGetContextToken(&token2);
    ok(hr == S_OK, "Expected S_OK, got 0x%08x\n", hr);
    ok(token2 == token, "got different token\n");

2147
    refs = IUnknown_AddRef((IUnknown *)token);
2148
    ok(refs == 1, "Expected 1, got %u\n", refs);
2149 2150 2151

    hr = pCoGetObjectContext(&IID_IObjContext, (void **)&ctx);
    ok(hr == S_OK, "Expected S_OK, got 0x%08x\n", hr);
2152
    ok(ctx == (IObjContext *)token, "Expected interface pointers to be the same\n");
2153

2154
    refs = IObjContext_AddRef(ctx);
2155
    ok(refs == 3, "Expected 3, got %u\n", refs);
2156

2157
    refs = IObjContext_Release(ctx);
2158
    ok(refs == 2, "Expected 2, got %u\n", refs);
2159 2160

    refs = IUnknown_Release((IUnknown *)token);
2161
    ok(refs == 1, "Expected 1, got %u\n", refs);
2162 2163 2164 2165 2166 2167

    /* CoGetContextToken does not add a reference */
    token = 0;
    hr = pCoGetContextToken(&token);
    ok(hr == S_OK, "Expected S_OK, got 0x%08x\n", hr);
    ok(token, "Expected token != 0\n");
2168
    ok(ctx == (IObjContext *)token, "Expected interface pointers to be the same\n");
2169

2170
    refs = IObjContext_AddRef(ctx);
2171 2172
    ok(refs == 2, "Expected 1, got %u\n", refs);

2173
    refs = IObjContext_Release(ctx);
2174 2175
    ok(refs == 1, "Expected 0, got %u\n", refs);

2176
    refs = IObjContext_Release(ctx);
2177 2178
    ok(refs == 0, "Expected 0, got %u\n", refs);

2179 2180 2181
    CoUninitialize();
}

2182
static void test_TreatAsClass(void)
2183 2184 2185 2186
{
    HRESULT hr;
    CLSID out;
    static GUID deadbeef = {0xdeadbeef,0xdead,0xbeef,{0xde,0xad,0xbe,0xef,0xde,0xad,0xbe,0xef}};
2187
    static const char deadbeefA[] = "{DEADBEEF-DEAD-BEEF-DEAD-BEEFDEADBEEF}";
2188
    IInternetProtocol *pIP = NULL;
2189 2190
    HKEY clsidkey, deadbeefkey;
    LONG lr;
2191

2192
    hr = CoGetTreatAsClass(&deadbeef,&out);
2193 2194
    ok (hr == S_FALSE, "expected S_FALSE got %x\n",hr);
    ok (IsEqualGUID(&out,&deadbeef), "expected to get same clsid back\n");
2195

2196
    hr = CoGetTreatAsClass(NULL, &out);
2197 2198 2199
    ok(hr == E_INVALIDARG, "expected E_INVALIDARG got %08x\n", hr);
    ok(IsEqualGUID(&out, &deadbeef), "expected no change to the clsid\n");

2200
    hr = CoGetTreatAsClass(&deadbeef, NULL);
2201 2202
    ok(hr == E_INVALIDARG, "expected E_INVALIDARG got %08x\n", hr);

2203
    lr = RegOpenKeyExA(HKEY_CLASSES_ROOT, "CLSID", 0, KEY_READ, &clsidkey);
2204
    ok(!lr, "Couldn't open CLSID key, error %d\n", lr);
2205 2206

    lr = RegCreateKeyExA(clsidkey, deadbeefA, 0, NULL, 0, KEY_WRITE, NULL, &deadbeefkey, NULL);
2207
    if (lr) {
2208
        win_skip("CoGetTreatAsClass() tests will be skipped (failed to create a test key, error %d)\n", lr);
2209 2210 2211
        RegCloseKey(clsidkey);
        return;
    }
2212

2213
    hr = CoTreatAsClass(&deadbeef, &deadbeef);
2214 2215
    ok(hr == REGDB_E_WRITEREGDB, "CoTreatAsClass gave wrong error: %08x\n", hr);

2216
    hr = CoTreatAsClass(&deadbeef, &CLSID_FileProtocol);
2217 2218 2219 2220 2221 2222
    if(hr == REGDB_E_WRITEREGDB){
        win_skip("Insufficient privileges to use CoTreatAsClass\n");
        goto exit;
    }
    ok(hr == S_OK, "CoTreatAsClass failed: %08x\n", hr);

2223
    hr = CoGetTreatAsClass(&deadbeef, &out);
2224 2225 2226
    ok(hr == S_OK, "CoGetTreatAsClass failed: %08x\n",hr);
    ok(IsEqualGUID(&out, &CLSID_FileProtocol), "expected to get substituted clsid\n");

2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241
    OleInitialize(NULL);

    hr = CoCreateInstance(&deadbeef, NULL, CLSCTX_INPROC_SERVER, &IID_IInternetProtocol, (void **)&pIP);
    if(hr == REGDB_E_CLASSNOTREG)
    {
        win_skip("IE not installed so can't test CoCreateInstance\n");
        goto exit;
    }

    ok(hr == S_OK, "CoCreateInstance failed: %08x\n", hr);
    if(pIP){
        IInternetProtocol_Release(pIP);
        pIP = NULL;
    }

2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258
    if (pCoCreateInstanceFromApp)
    {
        MULTI_QI mqi = { 0 };

        mqi.pIID = &IID_IInternetProtocol;
        hr = pCoCreateInstanceFromApp(&deadbeef, NULL, CLSCTX_INPROC_SERVER, NULL, 1, &mqi);
        ok(hr == REGDB_E_CLASSNOTREG, "Unexpected hr %#x.\n", hr);

        hr = CoCreateInstance(&deadbeef, NULL, CLSCTX_INPROC_SERVER | CLSCTX_APPCONTAINER, &IID_IInternetProtocol,
                (void **)&pIP);
        ok(hr == REGDB_E_CLASSNOTREG, "Unexpected hr %#x.\n", hr);

        hr = CoCreateInstance(&deadbeef, NULL, CLSCTX_INPROC_SERVER, &IID_IInternetProtocol, (void **)&pIP);
        ok(hr == S_OK, "Unexpected hr %#x.\n", hr);
        IUnknown_Release(pIP);
    }

2259
    hr = CoTreatAsClass(&deadbeef, &CLSID_NULL);
2260 2261
    ok(hr == S_OK, "CoTreatAsClass failed: %08x\n", hr);

2262
    hr = CoGetTreatAsClass(&deadbeef, &out);
2263 2264 2265
    ok(hr == S_FALSE, "expected S_FALSE got %08x\n", hr);
    ok(IsEqualGUID(&out, &deadbeef), "expected to get same clsid back\n");

2266 2267 2268 2269 2270 2271 2272 2273 2274
    /* bizarrely, native's CoTreatAsClass takes some time to take effect in CoCreateInstance */
    Sleep(200);

    hr = CoCreateInstance(&deadbeef, NULL, CLSCTX_INPROC_SERVER, &IID_IInternetProtocol, (void **)&pIP);
    ok(hr == REGDB_E_CLASSNOTREG, "CoCreateInstance gave wrong error: %08x\n", hr);

    if(pIP)
        IInternetProtocol_Release(pIP);

2275
exit:
2276
    OleUninitialize();
2277 2278 2279
    RegCloseKey(deadbeefkey);
    RegDeleteKeyA(clsidkey, deadbeefA);
    RegCloseKey(clsidkey);
2280 2281
}

2282 2283 2284 2285
static void test_CoInitializeEx(void)
{
    HRESULT hr;

2286
    hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
2287 2288 2289 2290 2291
    ok(hr == S_OK, "CoInitializeEx failed with error 0x%08x\n", hr);

    /* Calling OleInitialize for the first time should yield S_OK even with
     * apartment already initialized by previous CoInitialize(Ex) calls. */
    hr = OleInitialize(NULL);
2292
    ok(hr == S_OK, "OleInitialize failed with error 0x%08x\n", hr);
2293 2294 2295 2296 2297 2298 2299 2300

    /* Subsequent calls to OleInitialize should return S_FALSE */
    hr = OleInitialize(NULL);
    ok(hr == S_FALSE, "Expected S_FALSE, hr = 0x%08x\n", hr);

    /* Cleanup */
    CoUninitialize();
    OleUninitialize();
2301
    OleUninitialize();
2302 2303
}

2304 2305 2306 2307 2308 2309
static void test_OleInitialize_InitCounting(void)
{
    HRESULT hr;
    IUnknown *pUnk;
    REFCLSID rclsid = &CLSID_InternetZoneManager;

2310
    /* 1. OleInitialize fails but OleUninitialize is still called: apartment stays initialized */
2311
    hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324
    ok(hr == S_OK, "CoInitializeEx(COINIT_MULTITHREADED) failed with error 0x%08x\n", hr);

    hr = OleInitialize(NULL);
    ok(hr == RPC_E_CHANGED_MODE, "OleInitialize should have returned 0x%08x instead of 0x%08x\n", RPC_E_CHANGED_MODE, hr);
    OleUninitialize();

    pUnk = (IUnknown *)0xdeadbeef;
    hr = CoCreateInstance(rclsid, NULL, 0x17, &IID_IUnknown, (void **)&pUnk);
    ok(hr == S_OK, "CoCreateInstance should have returned 0x%08x instead of 0x%08x\n", S_OK, hr);
    if (pUnk) IUnknown_Release(pUnk);

    CoUninitialize();

2325
    /* 2. Extra multiple OleUninitialize: apartment stays initialized until CoUninitialize */
2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370
    hr = CoInitialize(NULL);
    ok(hr == S_OK, "CoInitialize() failed with error 0x%08x\n", hr);

    hr = OleInitialize(NULL);
    ok(hr == S_OK, "OleInitialize should have returned 0x%08x instead of 0x%08x\n", S_OK, hr);
    OleUninitialize();
    OleUninitialize();
    OleUninitialize();

    pUnk = (IUnknown *)0xdeadbeef;
    hr = CoCreateInstance(rclsid, NULL, 0x17, &IID_IUnknown, (void **)&pUnk);
    ok(hr == S_OK, "CoCreateInstance should have returned 0x%08x instead of 0x%08x\n", S_OK, hr);
    if (pUnk) IUnknown_Release(pUnk);

    CoUninitialize();

    pUnk = (IUnknown *)0xdeadbeef;
    hr = CoCreateInstance(rclsid, NULL, 0x17, &IID_IUnknown, (void **)&pUnk);
    ok(hr == CO_E_NOTINITIALIZED, "CoCreateInstance should have returned 0x%08x instead of 0x%08x\n", CO_E_NOTINITIALIZED, hr);
    if (pUnk) IUnknown_Release(pUnk);

    /* 3. CoUninitialize does not formally deinit Ole */
    hr = CoInitialize(NULL);
    ok(hr == S_OK, "CoInitialize() failed with error 0x%08x\n", hr);

    hr = OleInitialize(NULL);
    ok(hr == S_OK, "OleInitialize should have returned 0x%08x instead of 0x%08x\n", S_OK, hr);

    CoUninitialize();
    CoUninitialize();

    pUnk = (IUnknown *)0xdeadbeef;
    hr = CoCreateInstance(rclsid, NULL, 0x17, &IID_IUnknown, (void **)&pUnk);
    ok(hr == CO_E_NOTINITIALIZED, "CoCreateInstance should have returned 0x%08x instead of 0x%08x\n", CO_E_NOTINITIALIZED, hr);
      /* COM is not initialized anymore */
    if (pUnk) IUnknown_Release(pUnk);

    hr = OleInitialize(NULL);
    ok(hr == S_FALSE, "OleInitialize should have returned 0x%08x instead of 0x%08x\n", S_FALSE, hr);
      /* ... but native OleInit returns S_FALSE as if Ole is considered initialized */

    OleUninitialize();

}

2371 2372 2373 2374 2375 2376 2377
static void test_OleRegGetMiscStatus(void)
{
    ULONG_PTR cookie;
    HANDLE handle;
    DWORD status;
    HRESULT hr;

2378 2379 2380 2381
    hr = OleRegGetMiscStatus(&CLSID_Testclass, DVASPECT_ICON, NULL);
    ok(hr == E_INVALIDARG, "got 0x%08x\n", hr);

    status = 0xdeadbeef;
2382 2383
    hr = OleRegGetMiscStatus(&CLSID_Testclass, DVASPECT_ICON, &status);
    ok(hr == REGDB_E_CLASSNOTREG, "got 0x%08x\n", hr);
2384 2385 2386 2387 2388 2389
    ok(status == 0, "got 0x%08x\n", status);

    status = -1;
    hr = OleRegGetMiscStatus(&CLSID_StdFont, DVASPECT_ICON, &status);
    ok(hr == S_OK, "got 0x%08x\n", hr);
    ok(status == 0, "got 0x%08x\n", status);
2390 2391 2392 2393 2394 2395 2396

    if ((handle = activate_context(actctx_manifest, &cookie)))
    {
        status = 0;
        hr = OleRegGetMiscStatus(&CLSID_Testclass, DVASPECT_ICON, &status);
        ok(hr == S_OK, "got 0x%08x\n", hr);
        ok(status == OLEMISC_RECOMPOSEONRESIZE, "got 0x%08x\n", status);
2397

2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409
        /* context data takes precedence over registration info */
        status = 0;
        hr = OleRegGetMiscStatus(&CLSID_StdFont, DVASPECT_ICON, &status);
        ok(hr == S_OK, "got 0x%08x\n", hr);
        ok(status == OLEMISC_RECOMPOSEONRESIZE, "got 0x%08x\n", status);

        /* there's no such attribute in context */
        status = -1;
        hr = OleRegGetMiscStatus(&CLSID_Testclass, DVASPECT_DOCPRINT, &status);
        ok(hr == S_OK, "got 0x%08x\n", hr);
        ok(status == 0, "got 0x%08x\n", status);

2410
        deactivate_context(handle, cookie);
2411 2412 2413
    }
}

2414 2415 2416 2417
static void test_OleRegGetUserType(void)
{
    static const WCHAR stdfont_usertypeW[] = {'S','t','a','n','d','a','r','d',' ','F','o','n','t',0};
    static const WCHAR stdfont2_usertypeW[] = {'C','L','S','I','D','_','S','t','d','F','o','n','t',0};
2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435
    static const WCHAR clsidkeyW[] = {'C','L','S','I','D',0};
    static const WCHAR defvalueW[] = {'D','e','f','a','u','l','t',' ','N','a','m','e',0};
    static const WCHAR auxvalue0W[] = {'A','u','x',' ','N','a','m','e',' ','0',0};
    static const WCHAR auxvalue2W[] = {'A','u','x',' ','N','a','m','e',' ','2',0};
    static const WCHAR auxvalue3W[] = {'A','u','x',' ','N','a','m','e',' ','3',0};
    static const WCHAR auxvalue4W[] = {'A','u','x',' ','N','a','m','e',' ','4',0};

    static const char auxvalues[][16] = {
        "Aux Name 0",
        "Aux Name 1",
        "Aux Name 2",
        "Aux Name 3",
        "Aux Name 4"
    };

    HKEY clsidhkey, hkey, auxhkey, classkey;
    DWORD form, ret, disposition;
    WCHAR clsidW[39];
2436 2437 2438 2439
    ULONG_PTR cookie;
    HANDLE handle;
    HRESULT hr;
    WCHAR *str;
2440
    int i;
2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476

    for (form = 0; form <= USERCLASSTYPE_APPNAME+1; form++) {
        hr = OleRegGetUserType(&CLSID_Testclass, form, NULL);
        ok(hr == E_INVALIDARG, "form %u: got 0x%08x\n", form, hr);

        str = (void*)0xdeadbeef;
        hr = OleRegGetUserType(&CLSID_Testclass, form, &str);
        ok(hr == REGDB_E_CLASSNOTREG, "form %u: got 0x%08x\n", form, hr);
        ok(str == NULL, "form %u: got %p\n", form, str);

        /* same string returned for StdFont for all form types */
        str = NULL;
        hr = OleRegGetUserType(&CLSID_StdFont, form, &str);
        ok(hr == S_OK, "form %u: got 0x%08x\n", form, hr);
        ok(!lstrcmpW(str, stdfont_usertypeW) || !lstrcmpW(str, stdfont2_usertypeW) /* winxp */,
            "form %u, got %s\n", form, wine_dbgstr_w(str));
        CoTaskMemFree(str);
    }

    if ((handle = activate_context(actctx_manifest, &cookie)))
    {
        for (form = 0; form <= USERCLASSTYPE_APPNAME+1; form++) {
            str = (void*)0xdeadbeef;
            hr = OleRegGetUserType(&CLSID_Testclass, form, &str);
            ok(hr == REGDB_E_CLASSNOTREG, "form %u: got 0x%08x\n", form, hr);
            ok(str == NULL, "form %u: got %s\n", form, wine_dbgstr_w(str));

            /* same string returned for StdFont for all form types */
            str = NULL;
            hr = OleRegGetUserType(&CLSID_StdFont, form, &str);
            ok(hr == S_OK, "form %u: got 0x%08x\n", form, hr);
            ok(!lstrcmpW(str, stdfont_usertypeW) || !lstrcmpW(str, stdfont2_usertypeW) /* winxp */,
                "form %u, got %s\n", form, wine_dbgstr_w(str));
            CoTaskMemFree(str);
        }

2477
        deactivate_context(handle, cookie);
2478
    }
2479 2480

    /* test using registered CLSID */
2481
    StringFromGUID2(&CLSID_non_existent, clsidW, ARRAY_SIZE(clsidW));
2482 2483

    ret = RegCreateKeyExW(HKEY_CLASSES_ROOT, clsidkeyW, 0, NULL, 0, KEY_ALL_ACCESS, NULL, &clsidhkey, &disposition);
2484 2485 2486 2487 2488 2489 2490
    if (!ret)
    {
        ret = RegCreateKeyExW(clsidhkey, clsidW, 0, NULL, 0, KEY_ALL_ACCESS, NULL, &classkey, NULL);
        if (ret)
            RegCloseKey(clsidhkey);
    }

2491 2492
    if (ret == ERROR_ACCESS_DENIED)
    {
2493
        win_skip("Failed to create test key, skipping some of OleRegGetUserType() tests.\n");
2494 2495 2496
        return;
    }

2497
    ok(!ret, "failed to create a key, error %d\n", ret);
2498 2499

    ret = RegSetValueExW(classkey, NULL, 0, REG_SZ, (const BYTE*)defvalueW, sizeof(defvalueW));
2500
    ok(!ret, "got error %d\n", ret);
2501 2502

    ret = RegCreateKeyExA(classkey, "AuxUserType", 0, NULL, 0, KEY_ALL_ACCESS, NULL, &auxhkey, NULL);
2503
    ok(!ret, "got error %d\n", ret);
2504 2505 2506 2507 2508 2509 2510

    /* populate AuxUserType */
    for (i = 0; i <= 4; i++) {
        char name[16];

        sprintf(name, "AuxUserType\\%d", i);
        ret = RegCreateKeyExA(classkey, name, 0, NULL, 0, KEY_ALL_ACCESS, NULL, &hkey, NULL);
2511
        ok(!ret, "got error %d\n", ret);
2512 2513

        ret = RegSetValueExA(hkey, NULL, 0, REG_SZ, (const BYTE*)auxvalues[i], strlen(auxvalues[i]));
2514
        ok(!ret, "got error %d\n", ret);
2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567
        RegCloseKey(hkey);
    }

    str = NULL;
    hr = OleRegGetUserType(&CLSID_non_existent, 0, &str);
    ok(hr == S_OK, "got 0x%08x\n", hr);
    ok(!lstrcmpW(str, auxvalue0W), "got %s\n", wine_dbgstr_w(str));
    CoTaskMemFree(str);

    str = NULL;
    hr = OleRegGetUserType(&CLSID_non_existent, USERCLASSTYPE_FULL, &str);
    ok(hr == S_OK, "got 0x%08x\n", hr);
    ok(!lstrcmpW(str, defvalueW), "got %s\n", wine_dbgstr_w(str));
    CoTaskMemFree(str);

    str = NULL;
    hr = OleRegGetUserType(&CLSID_non_existent, USERCLASSTYPE_SHORT, &str);
    ok(hr == S_OK, "got 0x%08x\n", hr);
    ok(!lstrcmpW(str, auxvalue2W), "got %s\n", wine_dbgstr_w(str));
    CoTaskMemFree(str);

    str = NULL;
    hr = OleRegGetUserType(&CLSID_non_existent, USERCLASSTYPE_APPNAME, &str);
    ok(hr == S_OK, "got 0x%08x\n", hr);
    ok(!lstrcmpW(str, auxvalue3W), "got %s\n", wine_dbgstr_w(str));
    CoTaskMemFree(str);

    str = NULL;
    hr = OleRegGetUserType(&CLSID_non_existent, USERCLASSTYPE_APPNAME+1, &str);
    ok(hr == S_OK, "got 0x%08x\n", hr);
    ok(!lstrcmpW(str, auxvalue4W), "got %s\n", wine_dbgstr_w(str));
    CoTaskMemFree(str);

    str = NULL;
    hr = OleRegGetUserType(&CLSID_non_existent, USERCLASSTYPE_APPNAME+2, &str);
    ok(hr == S_OK, "got 0x%08x\n", hr);
    ok(!lstrcmpW(str, defvalueW), "got %s\n", wine_dbgstr_w(str));
    CoTaskMemFree(str);

    /* registry cleanup */
    for (i = 0; i <= 4; i++)
    {
        char name[2];
        sprintf(name, "%d", i);
        RegDeleteKeyA(auxhkey, name);
    }
    RegCloseKey(auxhkey);
    RegDeleteKeyA(classkey, "AuxUserType");
    RegCloseKey(classkey);
    RegDeleteKeyW(clsidhkey, clsidW);
    RegCloseKey(clsidhkey);
    if (disposition == REG_CREATED_NEW_KEY)
        RegDeleteKeyA(HKEY_CLASSES_ROOT, "CLSID");
2568
}
2569

2570 2571 2572 2573 2574 2575 2576 2577
static void test_CoCreateGuid(void)
{
    HRESULT hr;

    hr = CoCreateGuid(NULL);
    ok(hr == E_INVALIDARG, "got 0x%08x\n", hr);
}

2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590
static void CALLBACK apc_test_proc(ULONG_PTR param)
{
    /* nothing */
}

static DWORD CALLBACK release_semaphore_thread( LPVOID arg )
{
    HANDLE handle = arg;
    if (WaitForSingleObject(handle, 200) == WAIT_TIMEOUT)
        ReleaseSemaphore(handle, 1, NULL);
    return 0;
}

2591 2592 2593 2594 2595 2596 2597
static DWORD CALLBACK send_message_thread(LPVOID arg)
{
    HWND hWnd = arg;
    SendMessageA(hWnd, WM_DDE_FIRST, 0, 0);
    return 0;
}

2598 2599 2600 2601 2602 2603 2604 2605 2606
static DWORD CALLBACK send_and_post_user_message_thread(void *arg)
{
    HWND hwnd = arg;
    Sleep(30);
    SendMessageA(hwnd, WM_USER, 0, 0);
    PostMessageA(hwnd, WM_USER, 0, 0);
    return 0;
}

2607 2608 2609 2610 2611 2612 2613
static DWORD CALLBACK post_message_thread(LPVOID arg)
{
    HWND hWnd = arg;
    PostMessageA(hWnd, WM_DDE_FIRST, 0, 0);
    return 0;
}

2614
static const char cls_name[] = "cowait_test_class";
2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666

static UINT cowait_msgs[100], cowait_msgs_first, cowait_msgs_last;

static void cowait_msgs_reset(void)
{
    cowait_msgs_first = cowait_msgs_last = 0;
}

#define cowait_msgs_expect_empty() _cowait_msgs_expect_empty(__LINE__)
static void _cowait_msgs_expect_empty(unsigned line)
{
    while(cowait_msgs_first < cowait_msgs_last) {
        ok_(__FILE__,line)(0, "unexpected message %u\n", cowait_msgs[cowait_msgs_first]);
        cowait_msgs_first++;
    }
    cowait_msgs_reset();
}

#define cowait_msgs_expect_notified(a) _cowait_msgs_expect_notified(__LINE__,a)
static void _cowait_msgs_expect_notified(unsigned line, UINT expected_msg)
{
    if(cowait_msgs_first == cowait_msgs_last) {
        ok_(__FILE__,line)(0, "expected message %u, received none\n", expected_msg);
    }else {
        ok_(__FILE__,line)(cowait_msgs[cowait_msgs_first] == expected_msg,
                           "expected message %u, received %u \n",
                           expected_msg, cowait_msgs[cowait_msgs_first]);
        cowait_msgs_first++;
    }
}

#define cowait_msgs_expect_queued(a,b) _cowait_msgs_expect_queued(__LINE__,a,b)
static void _cowait_msgs_expect_queued(unsigned line, HWND hwnd, UINT expected_msg)
{
    MSG msg;
    BOOL success;

    success = PeekMessageA(&msg, hwnd, expected_msg, expected_msg, PM_REMOVE);
    ok_(__FILE__,line)(success, "PeekMessageA failed: %u\n", GetLastError());
    if(success)
        ok_(__FILE__,line)(msg.message == expected_msg, "unexpected message %u, expected %u\n",
                           msg.message, expected_msg);
}

static void flush_messages(void)
{
    MSG msg;
    while (PeekMessageA( &msg, 0, 0, 0, PM_REMOVE ));
}

static LRESULT CALLBACK cowait_window_proc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
2667
    if(cowait_msgs_last < ARRAY_SIZE(cowait_msgs))
2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700
        cowait_msgs[cowait_msgs_last++] = msg;
    if(msg == WM_DDE_FIRST)
        return 6;
    return DefWindowProcA(hwnd, msg, wparam, lparam);
}

static DWORD CALLBACK cowait_unmarshal_thread(void *arg)
{
    IStream *stream = arg;
    IEnumOLEVERB *enum_verb;
    LARGE_INTEGER zero;
    IUnknown *unk;
    HRESULT hr;

    CoInitialize(NULL);

    zero.QuadPart = 0;
    hr = IStream_Seek(stream, zero, STREAM_SEEK_SET, NULL);
    ok(hr == S_OK, "Seek failed: %08x\n", hr);

    hr = CoUnmarshalInterface(stream, &IID_IUnknown, (void**)&unk);
    ok(hr == S_OK, "CoUnmarshalInterface failed: %08x\n", hr);

    hr = IUnknown_QueryInterface(unk, &IID_IEnumOLEVERB, (void**)&enum_verb);
    ok(hr == S_OK, "QueryInterface failed: %08x\n", hr);

    IEnumOLEVERB_Release(enum_verb);
    IUnknown_Release(unk);

    CoUninitialize();
    return 0;
}

2701 2702
static DWORD CALLBACK test_CoWaitForMultipleHandles_thread(LPVOID arg)
{
2703 2704
    HANDLE *handles = arg, event, thread;
    IStream *stream;
2705
    BOOL success;
2706
    DWORD index, tid;
2707 2708
    HRESULT hr;
    HWND hWnd;
2709
    UINT uMSG = 0xc065;
2710
    MSG msg;
2711
    int ret;
2712

2713
    hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
2714 2715 2716 2717 2718 2719 2720 2721
    ok(hr == S_OK, "CoInitializeEx failed with error 0x%08x\n", hr);

    hWnd = CreateWindowExA(0, cls_name, "Test (thread)", WS_TILEDWINDOW, 0, 0, 640, 480, 0, 0, 0, 0);
    ok(hWnd != 0, "CreateWindowExA failed %u\n", GetLastError());

    index = 0xdeadbeef;
    PostMessageA(hWnd, WM_DDE_FIRST, 0, 0);
    hr = CoWaitForMultipleHandles(0, 50, 2, handles, &index);
2722 2723
    ok(hr == RPC_S_CALLPENDING, "expected RPC_S_CALLPENDING, got 0x%08x\n", hr);
    ok(index==0 || index==0xdeadbeef/* Win 8 */, "expected index 0, got %u\n", index);
2724 2725 2726 2727 2728 2729
    success = PeekMessageA(&msg, hWnd, WM_DDE_FIRST, WM_DDE_FIRST, PM_REMOVE);
    ok(!success, "CoWaitForMultipleHandles didn't pump any messages\n");

    index = 0xdeadbeef;
    PostMessageA(hWnd, WM_USER, 0, 0);
    hr = CoWaitForMultipleHandles(0, 50, 2, handles, &index);
2730 2731
    ok(hr == RPC_S_CALLPENDING, "expected RPC_S_CALLPENDING, got 0x%08x\n", hr);
    ok(index==0 || index==0xdeadbeef/* Win 8 */, "expected index 0, got %u\n", index);
2732 2733 2734
    success = PeekMessageA(&msg, hWnd, WM_USER, WM_USER, PM_REMOVE);
    ok(success, "CoWaitForMultipleHandles unexpectedly pumped messages\n");

2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751
    /* Even if CoWaitForMultipleHandles does not pump a message it peeks
     * at ALL of them */
    index = 0xdeadbeef;
    PostMessageA(NULL, uMSG, 0, 0);

    hr = CoWaitForMultipleHandles(COWAIT_ALERTABLE, 50, 2, handles, &index);
    ok(hr == RPC_S_CALLPENDING, "expected RPC_S_CALLPENDING, got 0x%08x\n", hr);
    ok(index == 0 || broken(index == 0xdeadbeef) /* Win 8 */, "expected index 0, got %u\n", index);

    /* Make sure message was peeked at */
    ret = MsgWaitForMultipleObjectsEx(0, NULL, 2, QS_ALLPOSTMESSAGE, MWMO_ALERTABLE);
    ok(ret == WAIT_TIMEOUT, "MsgWaitForMultipleObjects returned %x\n", ret);

    /* But not pumped */
    success = PeekMessageA(&msg, NULL, uMSG, uMSG, PM_REMOVE);
    ok(success, "CoWaitForMultipleHandles unexpectedly pumped messages\n");

2752 2753
    DestroyWindow(hWnd);
    CoUninitialize();
2754

2755
    hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
2756 2757 2758
    ok(hr == S_OK, "CoInitializeEx failed with error 0x%08x\n", hr);

    hr = CreateStreamOnHGlobal(NULL, TRUE, &stream);
2759
    ok(hr == S_OK, "CreateStreamOnHGlobal failed: %08x\n", hr);
2760 2761 2762 2763 2764 2765 2766 2767 2768 2769

    hr = CoMarshalInterface(stream, &IID_IUnknown, &Test_Unknown, MSHCTX_INPROC, NULL, MSHLFLAGS_NORMAL);
    ok(hr == S_OK, "CoMarshalInterface should have returned S_OK instead of 0x%08x\n", hr);

    event = CreateEventW(NULL, TRUE, FALSE, NULL);

    PostQuitMessage(66);
    PostThreadMessageW(GetCurrentThreadId(), WM_QUIT, 0, 0);

    hr = CoRegisterMessageFilter(&MessageFilter, NULL);
2770
    ok(hr == S_OK, "CoRegisterMessageFilter failed: %08x\n", hr);
2771 2772 2773 2774 2775

    thread = CreateThread(NULL, 0, cowait_unmarshal_thread, stream, 0, &tid);
    ok(thread != NULL, "CreateThread failed, error %u\n", GetLastError());
    hr = CoWaitForMultipleHandles(0, 50, 1, &event, &index);
    ok(hr == RPC_S_CALLPENDING, "expected RPC_S_CALLPENDING, got 0x%08x\n", hr);
2776 2777
    hr = CoWaitForMultipleHandles(0, 200, 1, &thread, &index);
    ok(hr == S_OK, "expected S_OK, got 0x%08x\n", hr);
2778
    ok(index == WAIT_OBJECT_0, "cowait_unmarshal_thread didn't finish\n");
2779 2780 2781
    CloseHandle(thread);

    hr = CoRegisterMessageFilter(NULL, NULL);
2782
    ok(hr == S_OK, "CoRegisterMessageFilter failed: %08x\n", hr);
2783 2784 2785 2786 2787

    IStream_Release(stream);

    CloseHandle(event);
    CoUninitialize();
2788 2789 2790
    return 0;
}

2791 2792 2793 2794 2795 2796 2797 2798 2799 2800
static void test_CoWaitForMultipleHandles(void)
{
    HANDLE handles[2], thread;
    DWORD index, tid;
    WNDCLASSEXA wc;
    BOOL success;
    HRESULT hr;
    HWND hWnd;
    MSG msg;

2801
    hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
2802 2803 2804 2805 2806 2807 2808 2809 2810
    ok(hr == S_OK, "CoInitializeEx failed with error 0x%08x\n", hr);

    memset(&wc, 0, sizeof(wc));
    wc.cbSize        = sizeof(wc);
    wc.style         = CS_VREDRAW | CS_HREDRAW;
    wc.hInstance     = GetModuleHandleA(0);
    wc.hCursor       = LoadCursorA(NULL, (LPCSTR)IDC_ARROW);
    wc.hbrBackground = NULL;
    wc.lpszClassName = cls_name;
2811
    wc.lpfnWndProc   = cowait_window_proc;
2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869
    success = RegisterClassExA(&wc) != 0;
    ok(success, "RegisterClassExA failed %u\n", GetLastError());

    hWnd = CreateWindowExA(0, cls_name, "Test", WS_TILEDWINDOW, 0, 0, 640, 480, 0, 0, 0, 0);
    ok(hWnd != 0, "CreateWindowExA failed %u\n", GetLastError());
    handles[0] = CreateSemaphoreA(NULL, 1, 1, NULL);
    ok(handles[0] != 0, "CreateSemaphoreA failed %u\n", GetLastError());
    handles[1] = CreateSemaphoreA(NULL, 1, 1, NULL);
    ok(handles[1] != 0, "CreateSemaphoreA failed %u\n", GetLastError());

    /* test without flags */

    PostMessageA(hWnd, WM_DDE_FIRST, 0, 0);
    hr = CoWaitForMultipleHandles(0, 50, 0, handles, NULL);
    ok(hr == E_INVALIDARG, "expected E_INVALIDARG, got 0x%08x\n", hr);
    success = PeekMessageA(&msg, hWnd, WM_DDE_FIRST, WM_DDE_FIRST, PM_REMOVE);
    ok(success, "CoWaitForMultipleHandles unexpectedly pumped messages\n");

    index = 0xdeadbeef;
    PostMessageA(hWnd, WM_DDE_FIRST, 0, 0);
    hr = CoWaitForMultipleHandles(0, 50, 0, NULL, &index);
    ok(hr == E_INVALIDARG, "expected E_INVALIDARG, got 0x%08x\n", hr);
    ok(index == 0, "expected index 0, got %u\n", index);
    success = PeekMessageA(&msg, hWnd, WM_DDE_FIRST, WM_DDE_FIRST, PM_REMOVE);
    ok(success, "CoWaitForMultipleHandles unexpectedly pumped messages\n");

    index = 0xdeadbeef;
    PostMessageA(hWnd, WM_DDE_FIRST, 0, 0);
    hr = CoWaitForMultipleHandles(0, 50, 0, handles, &index);
    ok(hr == RPC_E_NO_SYNC, "expected RPC_E_NO_SYNC, got 0x%08x\n", hr);
    ok(index == 0, "expected index 0, got %u\n", index);
    success = PeekMessageA(&msg, hWnd, WM_DDE_FIRST, WM_DDE_FIRST, PM_REMOVE);
    ok(success, "CoWaitForMultipleHandles unexpectedly pumped messages\n");

    index = 0xdeadbeef;
    PostMessageA(hWnd, WM_DDE_FIRST, 0, 0);
    hr = CoWaitForMultipleHandles(0, 50, 1, handles, &index);
    ok(hr == S_OK, "expected S_OK, got 0x%08x\n", hr);
    ok(index == 0, "expected index 0, got %u\n", index);
    success = PeekMessageA(&msg, hWnd, WM_DDE_FIRST, WM_DDE_FIRST, PM_REMOVE);
    ok(success, "CoWaitForMultipleHandles unexpectedly pumped messages\n");

    index = 0xdeadbeef;
    PostMessageA(hWnd, WM_DDE_FIRST, 0, 0);
    hr = CoWaitForMultipleHandles(0, 50, 2, handles, &index);
    ok(hr == S_OK, "expected S_OK, got 0x%08x\n", hr);
    ok(index == 1, "expected index 1, got %u\n", index);
    success = PeekMessageA(&msg, hWnd, WM_DDE_FIRST, WM_DDE_FIRST, PM_REMOVE);
    ok(success, "CoWaitForMultipleHandles unexpectedly pumped messages\n");

    index = 0xdeadbeef;
    PostMessageA(hWnd, WM_DDE_FIRST, 0, 0);
    hr = CoWaitForMultipleHandles(0, 50, 2, handles, &index);
    ok(hr == RPC_S_CALLPENDING, "expected RPC_S_CALLPENDING, got 0x%08x\n", hr);
    ok(index == 0 || broken(index == 0xdeadbeef) /* Win 8 */, "expected index 0, got %u\n", index);
    success = PeekMessageA(&msg, hWnd, WM_DDE_FIRST, WM_DDE_FIRST, PM_REMOVE);
    ok(!success, "CoWaitForMultipleHandles didn't pump any messages\n");

2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895
    /* test PostMessageA/SendMessageA from a different thread */

    index = 0xdeadbeef;
    thread = CreateThread(NULL, 0, post_message_thread, hWnd, 0, &tid);
    ok(thread != NULL, "CreateThread failed, error %u\n", GetLastError());
    hr = CoWaitForMultipleHandles(0, 100, 2, handles, &index);
    ok(hr == RPC_S_CALLPENDING, "expected RPC_S_CALLPENDING, got 0x%08x\n", hr);
    ok(index == 0 || broken(index == 0xdeadbeef) /* Win 8 */, "expected index 0, got %u\n", index);
    success = PeekMessageA(&msg, hWnd, WM_DDE_FIRST, WM_DDE_FIRST, PM_REMOVE);
    ok(!success, "CoWaitForMultipleHandles didn't pump any messages\n");
    index = WaitForSingleObject(thread, 200);
    ok(index == WAIT_OBJECT_0, "WaitForSingleObject failed\n");
    CloseHandle(thread);

    index = 0xdeadbeef;
    thread = CreateThread(NULL, 0, send_message_thread, hWnd, 0, &tid);
    ok(thread != NULL, "CreateThread failed, error %u\n", GetLastError());
    hr = CoWaitForMultipleHandles(0, 100, 2, handles, &index);
    ok(hr == RPC_S_CALLPENDING, "expected RPC_S_CALLPENDING, got 0x%08x\n", hr);
    ok(index == 0 || broken(index == 0xdeadbeef) /* Win 8 */, "expected index 0, got %u\n", index);
    success = PeekMessageA(&msg, hWnd, WM_DDE_FIRST, WM_DDE_FIRST, PM_REMOVE);
    ok(!success, "CoWaitForMultipleHandles didn't pump any messages\n");
    index = WaitForSingleObject(thread, 200);
    ok(index == WAIT_OBJECT_0, "WaitForSingleObject failed\n");
    CloseHandle(thread);

2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976
    ReleaseSemaphore(handles[0], 1, NULL);
    ReleaseSemaphore(handles[1], 1, NULL);

    /* test with COWAIT_WAITALL */

    index = 0xdeadbeef;
    PostMessageA(hWnd, WM_DDE_FIRST, 0, 0);
    hr = CoWaitForMultipleHandles(COWAIT_WAITALL, 50, 2, handles, &index);
    ok(hr == S_OK, "expected S_OK, got 0x%08x\n", hr);
    ok(index == 0, "expected index 0, got %u\n", index);
    success = PeekMessageA(&msg, hWnd, WM_DDE_FIRST, WM_DDE_FIRST, PM_REMOVE);
    ok(success, "CoWaitForMultipleHandles unexpectedly pumped messages\n");

    index = 0xdeadbeef;
    PostMessageA(hWnd, WM_DDE_FIRST, 0, 0);
    hr = CoWaitForMultipleHandles(0, 50, 2, handles, &index);
    ok(hr == RPC_S_CALLPENDING, "expected RPC_S_CALLPENDING, got 0x%08x\n", hr);
    ok(index == 0 || broken(index == 0xdeadbeef) /* Win 8 */, "expected index 0, got %u\n", index);
    success = PeekMessageA(&msg, hWnd, WM_DDE_FIRST, WM_DDE_FIRST, PM_REMOVE);
    ok(!success, "CoWaitForMultipleHandles didn't pump any messages\n");

    ReleaseSemaphore(handles[0], 1, NULL);
    ReleaseSemaphore(handles[1], 1, NULL);

    /* test with COWAIT_ALERTABLE */

    index = 0xdeadbeef;
    PostMessageA(hWnd, WM_DDE_FIRST, 0, 0);
    hr = CoWaitForMultipleHandles(COWAIT_ALERTABLE, 50, 1, handles, &index);
    ok(hr == S_OK, "expected S_OK, got 0x%08x\n", hr);
    ok(index == 0, "expected index 0, got %u\n", index);
    success = PeekMessageA(&msg, hWnd, WM_DDE_FIRST, WM_DDE_FIRST, PM_REMOVE);
    ok(success, "CoWaitForMultipleHandles unexpectedly pumped messages\n");

    index = 0xdeadbeef;
    PostMessageA(hWnd, WM_DDE_FIRST, 0, 0);
    hr = CoWaitForMultipleHandles(COWAIT_ALERTABLE, 50, 2, handles, &index);
    ok(hr == S_OK, "expected S_OK, got 0x%08x\n", hr);
    ok(index == 1, "expected index 1, got %u\n", index);
    success = PeekMessageA(&msg, hWnd, WM_DDE_FIRST, WM_DDE_FIRST, PM_REMOVE);
    ok(success, "CoWaitForMultipleHandles unexpectedly pumped messages\n");

    index = 0xdeadbeef;
    PostMessageA(hWnd, WM_DDE_FIRST, 0, 0);
    hr = CoWaitForMultipleHandles(COWAIT_ALERTABLE, 50, 2, handles, &index);
    ok(hr == RPC_S_CALLPENDING, "expected RPC_S_CALLPENDING, got 0x%08x\n", hr);
    ok(index == 0 || broken(index == 0xdeadbeef) /* Win 8 */, "expected index 0, got %u\n", index);
    success = PeekMessageA(&msg, hWnd, WM_DDE_FIRST, WM_DDE_FIRST, PM_REMOVE);
    ok(!success, "CoWaitForMultipleHandles didn't pump any messages\n");

    index = 0xdeadbeef;
    PostMessageA(hWnd, WM_DDE_FIRST, 0, 0);
    success = QueueUserAPC(apc_test_proc, GetCurrentThread(), 0);
    ok(success, "QueueUserAPC failed %u\n", GetLastError());
    hr = CoWaitForMultipleHandles(COWAIT_ALERTABLE, 50, 2, handles, &index);
    ok(hr == S_OK, "expected S_OK, got 0x%08x\n", hr);
    ok(index == WAIT_IO_COMPLETION, "expected index WAIT_IO_COMPLETION, got %u\n", index);
    success = PeekMessageA(&msg, hWnd, WM_DDE_FIRST, WM_DDE_FIRST, PM_REMOVE);
    ok(success, "CoWaitForMultipleHandles unexpectedly pumped messages\n");

    /* test with COWAIT_INPUTAVAILABLE (semaphores are still locked) */

    index = 0xdeadbeef;
    PostMessageA(hWnd, WM_DDE_FIRST, 0, 0);
    success = PeekMessageA(&msg, hWnd, WM_DDE_FIRST, WM_DDE_FIRST, PM_NOREMOVE);
    ok(success, "PeekMessageA returned FALSE\n");
    hr = CoWaitForMultipleHandles(0, 50, 2, handles, &index);
    ok(hr == RPC_S_CALLPENDING, "expected RPC_S_CALLPENDING, got 0x%08x\n", hr);
    ok(index == 0 || broken(index == 0xdeadbeef) /* Win 8 */, "expected index 0, got %u\n", index);
    success = PeekMessageA(&msg, hWnd, WM_DDE_FIRST, WM_DDE_FIRST, PM_REMOVE);
    ok(!success, "CoWaitForMultipleHandles didn't pump any messages\n");

    index = 0xdeadbeef;
    PostMessageA(hWnd, WM_DDE_FIRST, 0, 0);
    success = PeekMessageA(&msg, hWnd, WM_DDE_FIRST, WM_DDE_FIRST, PM_NOREMOVE);
    ok(success, "PeekMessageA returned FALSE\n");
    thread = CreateThread(NULL, 0, release_semaphore_thread, handles[1], 0, &tid);
    ok(thread != NULL, "CreateThread failed, error %u\n", GetLastError());
    hr = CoWaitForMultipleHandles(COWAIT_INPUTAVAILABLE, 50, 2, handles, &index);
    ok(hr == RPC_S_CALLPENDING || broken(hr == E_INVALIDARG) || broken(hr == S_OK) /* Win 8 */,
       "expected RPC_S_CALLPENDING, got 0x%08x\n", hr);
2977
    if (hr != S_OK) ReleaseSemaphore(handles[1], 1, NULL);
2978 2979 2980 2981 2982 2983 2984 2985
    ok(index == 0 || broken(index == 1) /* Win 8 */, "expected index 0, got %u\n", index);
    success = PeekMessageA(&msg, hWnd, WM_DDE_FIRST, WM_DDE_FIRST, PM_REMOVE);
    ok(!success || broken(success && hr == E_INVALIDARG),
       "CoWaitForMultipleHandles didn't pump any messages\n");
    index = WaitForSingleObject(thread, 200);
    ok(index == WAIT_OBJECT_0, "WaitForSingleObject failed\n");
    CloseHandle(thread);

2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008
    cowait_msgs_reset();
    PostMessageA(hWnd, 0, 0, 0);
    PostMessageA(hWnd, WM_DDE_FIRST, 0, 0);
    PostMessageA(hWnd, WM_USER+1, 0, 0);
    PostMessageA(hWnd, WM_DDE_FIRST+1, 0, 0);
    thread = CreateThread(NULL, 0, send_and_post_user_message_thread, hWnd, 0, &tid);
    ok(thread != NULL, "CreateThread failed, error %u\n", GetLastError());

    hr = CoWaitForMultipleHandles(0, 100, 2, handles, &index);
    ok(hr == RPC_S_CALLPENDING, "expected RPC_S_CALLPENDING, got 0x%08x\n", hr);

    cowait_msgs_expect_notified(WM_DDE_FIRST);
    cowait_msgs_expect_notified(WM_DDE_FIRST+1);
    cowait_msgs_expect_notified(WM_USER);
    cowait_msgs_expect_empty();
    cowait_msgs_expect_queued(hWnd, WM_USER);
    cowait_msgs_expect_queued(hWnd, WM_USER+1);
    flush_messages();

    index = WaitForSingleObject(thread, 200);
    ok(index == WAIT_OBJECT_0, "WaitForSingleObject failed\n");
    CloseHandle(thread);

3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019
    /* test behaviour of WM_QUIT (semaphores are still locked) */

    PostMessageA(hWnd, WM_QUIT, 40, 0);
    memset(&msg, 0, sizeof(msg));
    success = PeekMessageA(&msg, hWnd, WM_QUIT, WM_QUIT, PM_REMOVE);
    ok(success, "PeekMessageA failed, error %u\n", GetLastError());
    ok(msg.message == WM_QUIT, "expected msg.message = WM_QUIT, got %u\n", msg.message);
    ok(msg.wParam == 40, "expected msg.wParam = 40, got %lu\n", msg.wParam);
    success = PeekMessageA(&msg, hWnd, WM_QUIT, WM_QUIT, PM_REMOVE);
    ok(!success, "PeekMessageA succeeded\n");

3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042
    cowait_msgs_reset();
    PostMessageA(hWnd, WM_QUIT, 40, 0);
    PostMessageA(hWnd, 0, 0, 0);
    PostMessageA(hWnd, WM_DDE_FIRST, 0, 0);
    PostMessageA(hWnd, WM_USER+1, 0, 0);
    PostMessageA(hWnd, WM_DDE_FIRST+1, 0, 0);
    thread = CreateThread(NULL, 0, send_and_post_user_message_thread, hWnd, 0, &tid);
    ok(thread != NULL, "CreateThread failed, error %u\n", GetLastError());

    hr = CoWaitForMultipleHandles(0, 100, 2, handles, &index);
    ok(hr == RPC_S_CALLPENDING, "expected RPC_S_CALLPENDING, got 0x%08x\n", hr);

    cowait_msgs_expect_notified(WM_DDE_FIRST);
    cowait_msgs_expect_notified(WM_DDE_FIRST+1);
    cowait_msgs_expect_notified(WM_USER);
    cowait_msgs_expect_empty();
    cowait_msgs_expect_queued(hWnd, WM_USER);
    flush_messages();

    index = WaitForSingleObject(thread, 200);
    ok(index == WAIT_OBJECT_0, "WaitForSingleObject failed\n");
    CloseHandle(thread);

3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073
    index = 0xdeadbeef;
    PostMessageA(hWnd, WM_DDE_FIRST, 0, 0);
    PostMessageA(hWnd, WM_QUIT, 41, 0);
    thread = CreateThread(NULL, 0, post_message_thread, hWnd, 0, &tid);
    ok(thread != NULL, "CreateThread failed, error %u\n", GetLastError());
    hr = CoWaitForMultipleHandles(0, 100, 2, handles, &index);
    ok(hr == RPC_S_CALLPENDING, "expected RPC_S_CALLPENDING, got 0x%08x\n", hr);
    ok(index == 0 || broken(index == 0xdeadbeef) /* Win 8 */, "expected index 0, got %u\n", index);
    success = PeekMessageA(&msg, hWnd, WM_DDE_FIRST, WM_DDE_FIRST, PM_REMOVE);
    todo_wine
    ok(success || broken(!success) /* Win 2000/XP/8 */, "PeekMessageA failed, error %u\n", GetLastError());
    success = PeekMessageA(&msg, hWnd, WM_DDE_FIRST, WM_DDE_FIRST, PM_REMOVE);
    ok(!success, "PeekMessageA succeeded\n");
    memset(&msg, 0, sizeof(msg));
    success = PeekMessageA(&msg, hWnd, WM_QUIT, WM_QUIT, PM_REMOVE);
    todo_wine
    ok(!success || broken(success) /* Win 2000/XP/8 */, "PeekMessageA succeeded\n");
    if (success)
    {
        ok(msg.message == WM_QUIT, "expected msg.message = WM_QUIT, got %u\n", msg.message);
        ok(msg.wParam == 41, "expected msg.wParam = 41, got %lu\n", msg.wParam);
    }
    index = WaitForSingleObject(thread, 200);
    ok(index == WAIT_OBJECT_0, "WaitForSingleObject failed\n");
    CloseHandle(thread);

    index = 0xdeadbeef;
    PostMessageA(hWnd, WM_DDE_FIRST, 0, 0);
    PostMessageA(hWnd, WM_QUIT, 42, 0);
    thread = CreateThread(NULL, 0, send_message_thread, hWnd, 0, &tid);
    ok(thread != NULL, "CreateThread failed, error %u\n", GetLastError());
3074
    hr = CoWaitForMultipleHandles(0, 500, 2, handles, &index);
3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137
    ok(hr == RPC_S_CALLPENDING, "expected RPC_S_CALLPENDING, got 0x%08x\n", hr);
    ok(index == 0 || broken(index == 0xdeadbeef) /* Win 8 */, "expected index 0, got %u\n", index);
    success = PeekMessageA(&msg, hWnd, WM_DDE_FIRST, WM_DDE_FIRST, PM_REMOVE);
    ok(!success, "CoWaitForMultipleHandles didn't pump all WM_DDE_FIRST messages\n");
    memset(&msg, 0, sizeof(msg));
    success = PeekMessageA(&msg, hWnd, WM_QUIT, WM_QUIT, PM_REMOVE);
    ok(success, "PeekMessageA failed, error %u\n", GetLastError());
    ok(msg.message == WM_QUIT, "expected msg.message = WM_QUIT, got %u\n", msg.message);
    ok(msg.wParam == 42, "expected msg.wParam = 42, got %lu\n", msg.wParam);
    index = WaitForSingleObject(thread, 200);
    ok(index == WAIT_OBJECT_0, "WaitForSingleObject failed\n");
    CloseHandle(thread);

    PostQuitMessage(43);
    memset(&msg, 0, sizeof(msg));
    success = PeekMessageA(&msg, hWnd, WM_QUIT, WM_QUIT, PM_REMOVE);
    ok(success || broken(!success) /* Win 8 */, "PeekMessageA failed, error %u\n", GetLastError());
    if (!success)
        win_skip("PostQuitMessage didn't queue a WM_QUIT message, skipping tests\n");
    else
    {
        ok(msg.message == WM_QUIT, "expected msg.message = WM_QUIT, got %u\n", msg.message);
        ok(msg.wParam == 43, "expected msg.wParam = 43, got %lu\n", msg.wParam);
        success = PeekMessageA(&msg, hWnd, WM_QUIT, WM_QUIT, PM_REMOVE);
        ok(!success, "PeekMessageA succeeded\n");

        index = 0xdeadbeef;
        PostMessageA(hWnd, WM_DDE_FIRST, 0, 0);
        PostQuitMessage(44);
        thread = CreateThread(NULL, 0, post_message_thread, hWnd, 0, &tid);
        ok(thread != NULL, "CreateThread failed, error %u\n", GetLastError());
        hr = CoWaitForMultipleHandles(0, 100, 2, handles, &index);
        ok(hr == RPC_S_CALLPENDING, "expected RPC_S_CALLPENDING, got 0x%08x\n", hr);
        ok(index == 0 || broken(index == 0xdeadbeef) /* Win 8 */, "expected index 0, got %u\n", index);
        success = PeekMessageA(&msg, hWnd, WM_DDE_FIRST, WM_DDE_FIRST, PM_REMOVE);
        ok(success, "PeekMessageA failed, error %u\n", GetLastError());
        success = PeekMessageA(&msg, hWnd, WM_DDE_FIRST, WM_DDE_FIRST, PM_REMOVE);
        ok(!success, "PeekMessageA succeeded\n");
        success = PeekMessageA(&msg, hWnd, WM_QUIT, WM_QUIT, PM_REMOVE);
        ok(!success, "CoWaitForMultipleHandles didn't remove WM_QUIT messages\n");
        index = WaitForSingleObject(thread, 200);
        ok(index == WAIT_OBJECT_0, "WaitForSingleObject failed\n");
        CloseHandle(thread);

        index = 0xdeadbeef;
        PostMessageA(hWnd, WM_DDE_FIRST, 0, 0);
        PostQuitMessage(45);
        thread = CreateThread(NULL, 0, send_message_thread, hWnd, 0, &tid);
        ok(thread != NULL, "CreateThread failed, error %u\n", GetLastError());
        hr = CoWaitForMultipleHandles(0, 100, 2, handles, &index);
        ok(hr == RPC_S_CALLPENDING, "expected RPC_S_CALLPENDING, got 0x%08x\n", hr);
        ok(index == 0 || broken(index == 0xdeadbeef) /* Win 8 */, "expected index 0, got %u\n", index);
        success = PeekMessageA(&msg, hWnd, WM_DDE_FIRST, WM_DDE_FIRST, PM_REMOVE);
        ok(success, "PeekMessageA failed, error %u\n", GetLastError());
        success = PeekMessageA(&msg, hWnd, WM_DDE_FIRST, WM_DDE_FIRST, PM_REMOVE);
        ok(!success, "PeekMessageA succeeded\n");
        success = PeekMessageA(&msg, hWnd, WM_QUIT, WM_QUIT, PM_REMOVE);
        ok(!success, "CoWaitForMultipleHandles didn't remove WM_QUIT messages\n");
        index = WaitForSingleObject(thread, 200);
        ok(index == WAIT_OBJECT_0, "WaitForSingleObject failed\n");
        CloseHandle(thread);
    }

3138 3139
    /* test message pumping when CoWaitForMultipleHandles is called from non main apartment thread */
    thread = CreateThread(NULL, 0, test_CoWaitForMultipleHandles_thread, handles, 0, &tid);
3140
    index = WaitForSingleObject(thread, 5000);
3141 3142 3143
    ok(index == WAIT_OBJECT_0, "WaitForSingleObject failed\n");
    CloseHandle(thread);

3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167
    CoUninitialize();

    /* If COM was not initialized, messages are neither pumped nor peeked at */
    PostMessageA(hWnd, WM_DDE_FIRST, 0, 0);
    hr = CoWaitForMultipleHandles(0, 100, 2, handles, &index);
    ok(hr == RPC_S_CALLPENDING, "got %#x\n", hr);
    success = MsgWaitForMultipleObjectsEx(0, NULL, 2, QS_ALLPOSTMESSAGE, MWMO_ALERTABLE);
    ok(success == 0, "MsgWaitForMultipleObjects returned %x\n", success);
    success = PeekMessageA(&msg, hWnd, WM_DDE_FIRST, WM_DDE_FIRST, PM_REMOVE);
    ok(success, "PeekMessage failed: %u\n", GetLastError());

    /* same in an MTA */
    CoInitializeEx(NULL, COINIT_MULTITHREADED);

    PostMessageA(hWnd, WM_DDE_FIRST, 0, 0);
    hr = CoWaitForMultipleHandles(0, 100, 2, handles, &index);
    ok(hr == RPC_S_CALLPENDING, "got %#x\n", hr);
    success = MsgWaitForMultipleObjectsEx(0, NULL, 2, QS_ALLPOSTMESSAGE, MWMO_ALERTABLE);
    ok(success == 0, "MsgWaitForMultipleObjects returned %x\n", success);
    success = PeekMessageA(&msg, hWnd, WM_DDE_FIRST, WM_DDE_FIRST, PM_REMOVE);
    ok(success, "PeekMessage failed: %u\n", GetLastError());

    CoUninitialize();

3168 3169 3170 3171 3172 3173 3174 3175
    CloseHandle(handles[0]);
    CloseHandle(handles[1]);
    DestroyWindow(hWnd);

    success = UnregisterClassA(cls_name, GetModuleHandleA(0));
    ok(success, "UnregisterClass failed %u\n", GetLastError());
}

3176 3177 3178
static void test_CoGetMalloc(void)
{
    IMalloc *imalloc;
3179
    SIZE_T size;
3180
    HRESULT hr;
3181 3182
    char *ptr;
    int ret;
3183

3184 3185
    if (0) /* crashes on native */
        hr = CoGetMalloc(0, NULL);
3186 3187 3188 3189 3190

    imalloc = (void*)0xdeadbeef;
    hr = CoGetMalloc(0, &imalloc);
    ok(hr == E_INVALIDARG, "got 0x%08x\n", hr);
    ok(imalloc == NULL, "got %p\n", imalloc);
3191

3192 3193 3194 3195
    imalloc = (void*)0xdeadbeef;
    hr = CoGetMalloc(MEMCTX_SHARED, &imalloc);
    ok(hr == E_INVALIDARG, "got 0x%08x\n", hr);
    ok(imalloc == NULL, "got %p\n", imalloc);
3196

3197 3198 3199 3200
    imalloc = (void*)0xdeadbeef;
    hr = CoGetMalloc(MEMCTX_MACSYSTEM, &imalloc);
    ok(hr == E_INVALIDARG, "got 0x%08x\n", hr);
    ok(imalloc == NULL, "got %p\n", imalloc);
3201

3202 3203 3204 3205
    imalloc = (void*)0xdeadbeef;
    hr = CoGetMalloc(MEMCTX_UNKNOWN, &imalloc);
    ok(hr == E_INVALIDARG, "got 0x%08x\n", hr);
    ok(imalloc == NULL, "got %p\n", imalloc);
3206

3207 3208 3209 3210
    imalloc = (void*)0xdeadbeef;
    hr = CoGetMalloc(MEMCTX_SAME, &imalloc);
    ok(hr == E_INVALIDARG, "got 0x%08x\n", hr);
    ok(imalloc == NULL, "got %p\n", imalloc);
3211

3212 3213 3214 3215
    imalloc = NULL;
    hr = CoGetMalloc(MEMCTX_TASK, &imalloc);
    ok(hr == S_OK, "got 0x%08x\n", hr);
    ok(imalloc != NULL, "got %p\n", imalloc);
3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232

    /* DidAlloc() */
    ptr = IMalloc_Alloc(imalloc, 16);
    ok(!!ptr, "Failed to allocate block.\n");

    ret = IMalloc_DidAlloc(imalloc, ptr);
    ok(ret == 1, "Unexpected return value %d.\n", ret);

    ret = IMalloc_DidAlloc(imalloc, NULL);
    ok(ret == -1, "Unexpected return value %d.\n", ret);

    ret = IMalloc_DidAlloc(imalloc, (void *)0x1);
    ok(ret == 0, "Unexpected return value %d.\n", ret);

    ret = IMalloc_DidAlloc(imalloc, ptr + 4);
    ok(ret == 0, "Unexpected return value %d.\n", ret);

3233 3234 3235 3236 3237 3238 3239
    /* GetSize() */
    size = IMalloc_GetSize(imalloc, NULL);
    ok(size == (SIZE_T)-1, "Unexpected return value.\n");

    size = IMalloc_GetSize(imalloc, ptr);
    ok(size == 16, "Unexpected return value.\n");

3240 3241
    IMalloc_Free(imalloc, ptr);

3242 3243 3244
    IMalloc_Release(imalloc);
}

3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278
static void test_CoGetApartmentType(void)
{
    APTTYPEQUALIFIER qualifier;
    APTTYPE type;
    HRESULT hr;

    if (!pCoGetApartmentType)
    {
        win_skip("CoGetApartmentType not present\n");
        return;
    }

    hr = pCoGetApartmentType(NULL, NULL);
    ok(hr == E_INVALIDARG, "CoGetApartmentType succeeded, error: 0x%08x\n", hr);

    type = 0xdeadbeef;
    hr = pCoGetApartmentType(&type, NULL);
    ok(hr == E_INVALIDARG, "CoGetApartmentType succeeded, error: 0x%08x\n", hr);
    ok(type == 0xdeadbeef, "Expected 0xdeadbeef, got %u\n", type);

    qualifier = 0xdeadbeef;
    hr = pCoGetApartmentType(NULL, &qualifier);
    ok(hr == E_INVALIDARG, "CoGetApartmentType succeeded, error: 0x%08x\n", hr);
    ok(qualifier == 0xdeadbeef, "Expected 0xdeadbeef, got %u\n", qualifier);

    type = 0xdeadbeef;
    qualifier = 0xdeadbeef;
    hr = pCoGetApartmentType(&type, &qualifier);
    ok(hr == CO_E_NOTINITIALIZED, "CoGetApartmentType succeeded, error: 0x%08x\n", hr);
    ok(type == APTTYPE_CURRENT, "Expected APTTYPE_CURRENT, got %u\n", type);
    ok(qualifier == APTTYPEQUALIFIER_NONE, "Expected APTTYPEQUALIFIER_NONE, got %u\n", qualifier);

    type = 0xdeadbeef;
    qualifier = 0xdeadbeef;
3279
    hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
3280 3281 3282 3283 3284 3285 3286 3287 3288
    ok(hr == S_OK, "CoInitializeEx failed, error: 0x%08x\n", hr);
    hr = pCoGetApartmentType(&type, &qualifier);
    ok(hr == S_OK, "CoGetApartmentType failed, error: 0x%08x\n", hr);
    ok(type == APTTYPE_MAINSTA, "Expected APTTYPE_MAINSTA, got %u\n", type);
    ok(qualifier == APTTYPEQUALIFIER_NONE, "Expected APTTYPEQUALIFIER_NONE, got %u\n", qualifier);
    CoUninitialize();

    type = 0xdeadbeef;
    qualifier = 0xdeadbeef;
3289
    hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
3290 3291 3292 3293 3294 3295 3296 3297
    ok(hr == S_OK, "CoInitializeEx failed, error: 0x%08x\n", hr);
    hr = pCoGetApartmentType(&type, &qualifier);
    ok(hr == S_OK, "CoGetApartmentType failed, error: 0x%08x\n", hr);
    ok(type == APTTYPE_MTA, "Expected APTTYPE_MTA, got %u\n", type);
    ok(qualifier == APTTYPEQUALIFIER_NONE, "Expected APTTYPEQUALIFIER_NONE, got %u\n", qualifier);
    CoUninitialize();
}

3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414
static HRESULT WINAPI testspy_QI(IMallocSpy *iface, REFIID riid, void **obj)
{
    if (IsEqualIID(riid, &IID_IMallocSpy) || IsEqualIID(riid, &IID_IUnknown))
    {
        *obj = iface;
        IMallocSpy_AddRef(iface);
        return S_OK;
    }

    return E_NOINTERFACE;
}

static ULONG WINAPI testspy_AddRef(IMallocSpy *iface)
{
    return 2;
}

static ULONG WINAPI testspy_Release(IMallocSpy *iface)
{
    return 1;
}

static SIZE_T WINAPI testspy_PreAlloc(IMallocSpy *iface, SIZE_T cb)
{
    ok(0, "unexpected call\n");
    return 0;
}

static void* WINAPI testspy_PostAlloc(IMallocSpy *iface, void *ptr)
{
    ok(0, "unexpected call\n");
    return NULL;
}

static void* WINAPI testspy_PreFree(IMallocSpy *iface, void *ptr, BOOL spyed)
{
    ok(0, "unexpected call\n");
    return NULL;
}

static void WINAPI testspy_PostFree(IMallocSpy *iface, BOOL spyed)
{
    ok(0, "unexpected call\n");
}

static SIZE_T WINAPI testspy_PreRealloc(IMallocSpy *iface, void *ptr, SIZE_T cb, void **newptr, BOOL spyed)
{
    ok(0, "unexpected call\n");
    return 0;
}

static void* WINAPI testspy_PostRealloc(IMallocSpy *iface, void *ptr, BOOL spyed)
{
    ok(0, "unexpected call\n");
    return NULL;
}

static void* WINAPI testspy_PreGetSize(IMallocSpy *iface, void *ptr, BOOL spyed)
{
    ok(0, "unexpected call\n");
    return NULL;
}

static SIZE_T WINAPI testspy_PostGetSize(IMallocSpy *iface, SIZE_T actual, BOOL spyed)
{
    ok(0, "unexpected call\n");
    return 0;
}

static void* WINAPI testspy_PreDidAlloc(IMallocSpy *iface, void *ptr, BOOL spyed)
{
    ok(0, "unexpected call\n");
    return NULL;
}

static int WINAPI testspy_PostDidAlloc(IMallocSpy *iface, void *ptr, BOOL spyed, int actual)
{
    ok(0, "unexpected call\n");
    return 0;
}

static void WINAPI testspy_PreHeapMinimize(IMallocSpy *iface)
{
    ok(0, "unexpected call\n");
}

static void WINAPI testspy_PostHeapMinimize(IMallocSpy *iface)
{
    ok(0, "unexpected call\n");
}

static const IMallocSpyVtbl testspyvtbl =
{
    testspy_QI,
    testspy_AddRef,
    testspy_Release,
    testspy_PreAlloc,
    testspy_PostAlloc,
    testspy_PreFree,
    testspy_PostFree,
    testspy_PreRealloc,
    testspy_PostRealloc,
    testspy_PreGetSize,
    testspy_PostGetSize,
    testspy_PreDidAlloc,
    testspy_PostDidAlloc,
    testspy_PreHeapMinimize,
    testspy_PostHeapMinimize
};

static IMallocSpy testspy = { &testspyvtbl };

static void test_IMallocSpy(void)
{
    IMalloc *imalloc;
    HRESULT hr;

3415 3416 3417 3418 3419 3420
    hr = CoRegisterMallocSpy(NULL);
    ok(hr == E_INVALIDARG, "got 0x%08x\n", hr);

    hr = CoRevokeMallocSpy();
    ok(hr == CO_E_OBJNOTREG, "got 0x%08x\n", hr);

3421 3422 3423
    hr = CoRegisterMallocSpy(&testspy);
    ok(hr == S_OK, "got 0x%08x\n", hr);

3424 3425 3426 3427 3428 3429
    hr = CoRegisterMallocSpy(NULL);
    ok(hr == E_INVALIDARG, "got 0x%08x\n", hr);

    hr = CoRegisterMallocSpy(&testspy);
    ok(hr == CO_E_OBJISREG, "got 0x%08x\n", hr);

3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440
    imalloc = NULL;
    hr = CoGetMalloc(MEMCTX_TASK, &imalloc);
    ok(hr == S_OK, "got 0x%08x\n", hr);
    ok(imalloc != NULL, "got %p\n", imalloc);

    IMalloc_Free(imalloc, NULL);

    IMalloc_Release(imalloc);

    hr = CoRevokeMallocSpy();
    ok(hr == S_OK, "got 0x%08x\n", hr);
3441 3442 3443

    hr = CoRevokeMallocSpy();
    ok(hr == CO_E_OBJNOTREG, "got 0x%08x\n", hr);
3444 3445
}

3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459
static void test_CoGetCurrentLogicalThreadId(void)
{
    HRESULT hr;
    GUID id;

    hr = CoGetCurrentLogicalThreadId(NULL);
    ok(hr == E_INVALIDARG, "got 0x%08x\n", hr);

    id = GUID_NULL;
    hr = CoGetCurrentLogicalThreadId(&id);
    ok(hr == S_OK, "got 0x%08x\n", hr);
    ok(!IsEqualGUID(&id, &GUID_NULL), "got null id\n");
}

3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482
static HRESULT WINAPI testinitialize_QI(IInitializeSpy *iface, REFIID riid, void **obj)
{
    if (IsEqualIID(riid, &IID_IInitializeSpy) || IsEqualIID(riid, &IID_IUnknown))
    {
        *obj = iface;
        IInitializeSpy_AddRef(iface);
        return S_OK;
    }

    *obj = NULL;
    return E_NOINTERFACE;
}

static ULONG WINAPI testinitialize_AddRef(IInitializeSpy *iface)
{
    return 2;
}

static ULONG WINAPI testinitialize_Release(IInitializeSpy *iface)
{
    return 1;
}

3483 3484 3485 3486
static DWORD expected_coinit_flags;
static ULARGE_INTEGER init_cookies[3];
static BOOL revoke_spies_on_uninit;

3487 3488
static HRESULT WINAPI testinitialize_PreInitialize(IInitializeSpy *iface, DWORD coinit, DWORD aptrefs)
{
3489 3490
    CHECK_EXPECT2(PreInitialize);
    ok(coinit == expected_coinit_flags, "Unexpected init flags %#x, expected %#x.\n", coinit, expected_coinit_flags);
3491
    return S_OK;
3492 3493 3494 3495
}

static HRESULT WINAPI testinitialize_PostInitialize(IInitializeSpy *iface, HRESULT hr, DWORD coinit, DWORD aptrefs)
{
3496 3497
    CHECK_EXPECT2(PostInitialize);
    ok(coinit == expected_coinit_flags, "Unexpected init flags %#x, expected %#x.\n", coinit, expected_coinit_flags);
3498
    return hr;
3499 3500 3501 3502
}

static HRESULT WINAPI testinitialize_PreUninitialize(IInitializeSpy *iface, DWORD aptrefs)
{
3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518
    HRESULT hr;
    CHECK_EXPECT2(PreUninitialize);
    if (revoke_spies_on_uninit)
    {
        hr = CoRevokeInitializeSpy(init_cookies[0]);
        ok(hr == S_OK, "got 0x%08x\n", hr);

        hr = CoRevokeInitializeSpy(init_cookies[1]);
        ok(hr == S_OK, "got 0x%08x\n", hr);

        hr = CoRevokeInitializeSpy(init_cookies[2]);
        ok(hr == S_OK, "got 0x%08x\n", hr);

        revoke_spies_on_uninit = FALSE;
    }
    return S_OK;
3519 3520 3521 3522
}

static HRESULT WINAPI testinitialize_PostUninitialize(IInitializeSpy *iface, DWORD aptrefs)
{
3523
    CHECK_EXPECT2(PostUninitialize);
3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539
    return E_NOTIMPL;
}

static const IInitializeSpyVtbl testinitializevtbl =
{
    testinitialize_QI,
    testinitialize_AddRef,
    testinitialize_Release,
    testinitialize_PreInitialize,
    testinitialize_PostInitialize,
    testinitialize_PreUninitialize,
    testinitialize_PostUninitialize
};

static IInitializeSpy testinitialize = { &testinitializevtbl };

3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554
static DWORD WINAPI test_init_spies_proc(void *arg)
{
    HRESULT hr;

    hr = CoInitializeEx(NULL, COINIT_MULTITHREADED | COINIT_DISABLE_OLE1DDE);
    ok(hr == S_OK, "Failed to initialize COM, hr %#x.\n", hr);

    hr = CoRevokeInitializeSpy(init_cookies[2]);
    ok(hr == E_INVALIDARG, "got 0x%08x\n", hr);

    CoUninitialize();
    return 0;
}

static void test_IInitializeSpy(BOOL mt)
3555 3556 3557
{
    HRESULT hr;

3558 3559
    if (mt)
    {
3560
        hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
3561 3562 3563
        ok(hr == S_OK, "CoInitializeEx failed: %#x\n", hr);
    }

3564 3565 3566
    hr = CoRegisterInitializeSpy(NULL, NULL);
    ok(hr == E_INVALIDARG, "got 0x%08x\n", hr);

3567 3568
    init_cookies[0].QuadPart = 1;
    hr = CoRegisterInitializeSpy(NULL, &init_cookies[0]);
3569
    ok(hr == E_INVALIDARG, "got 0x%08x\n", hr);
3570
    ok(init_cookies[0].QuadPart == 1, "got wrong cookie\n");
3571 3572 3573 3574

    hr = CoRegisterInitializeSpy(&testinitialize, NULL);
    ok(hr == E_INVALIDARG, "got 0x%08x\n", hr);

3575 3576 3577
    init_cookies[0].HighPart = 0;
    init_cookies[0].LowPart = 1;
    hr = CoRegisterInitializeSpy(&testinitialize, &init_cookies[0]);
3578
    ok(hr == S_OK, "got 0x%08x\n", hr);
3579
    ok(init_cookies[0].HighPart == GetCurrentThreadId(), "got high part 0x%08x, expected 0x%08x\n", init_cookies[0].HighPart,
3580
        GetCurrentThreadId());
3581
    if (!mt) ok(init_cookies[0].LowPart == 0, "got wrong low part 0x%x\n", init_cookies[0].LowPart);
3582

3583
    /* register same instance one more time */
3584 3585 3586
    init_cookies[1].HighPart = 0;
    init_cookies[1].LowPart = 0;
    hr = CoRegisterInitializeSpy(&testinitialize, &init_cookies[1]);
3587
    ok(hr == S_OK, "got 0x%08x\n", hr);
3588
    ok(init_cookies[1].HighPart == GetCurrentThreadId(), "got high part 0x%08x, expected 0x%08x\n", init_cookies[1].HighPart,
3589
        GetCurrentThreadId());
3590
    if (!mt) ok(init_cookies[1].LowPart == 1, "got wrong low part 0x%x\n", init_cookies[1].LowPart);
3591

3592 3593 3594
    init_cookies[2].HighPart = 0;
    init_cookies[2].LowPart = 0;
    hr = CoRegisterInitializeSpy(&testinitialize, &init_cookies[2]);
3595
    ok(hr == S_OK, "got 0x%08x\n", hr);
3596
    ok(init_cookies[2].HighPart == GetCurrentThreadId(), "got high part 0x%08x, expected 0x%08x\n", init_cookies[2].HighPart,
3597
        GetCurrentThreadId());
3598
    if (!mt) ok(init_cookies[2].LowPart == 2, "got wrong low part 0x%x\n", init_cookies[2].LowPart);
3599

3600
    hr = CoRevokeInitializeSpy(init_cookies[1]);
3601 3602
    ok(hr == S_OK, "got 0x%08x\n", hr);

3603
    hr = CoRevokeInitializeSpy(init_cookies[1]);
3604 3605
    ok(hr == E_INVALIDARG, "got 0x%08x\n", hr);

3606 3607 3608
    init_cookies[1].HighPart = 0;
    init_cookies[1].LowPart = 0;
    hr = CoRegisterInitializeSpy(&testinitialize, &init_cookies[1]);
3609
    ok(hr == S_OK, "got 0x%08x\n", hr);
3610
    ok(init_cookies[1].HighPart == GetCurrentThreadId(), "got high part 0x%08x, expected 0x%08x\n", init_cookies[1].HighPart,
3611
        GetCurrentThreadId());
3612
    if (!mt) ok(init_cookies[1].LowPart == 1, "got wrong low part 0x%x\n", init_cookies[1].LowPart);
3613

3614 3615 3616 3617 3618 3619
    SET_EXPECT(PreInitialize);
    SET_EXPECT(PostInitialize);
    hr = CoInitializeEx(NULL, expected_coinit_flags = ((mt ? COINIT_MULTITHREADED : COINIT_APARTMENTTHREADED) | COINIT_DISABLE_OLE1DDE));
    ok(hr == (mt ? S_FALSE : S_OK), "Failed to initialize COM, hr %#x.\n", hr);
    CHECK_CALLED(PreInitialize, 3);
    CHECK_CALLED(PostInitialize, 3);
3620

3621 3622 3623 3624 3625 3626 3627
    if (mt)
    {
        HANDLE thread;
        thread = CreateThread(NULL, 0, test_init_spies_proc, NULL, 0, NULL);
        ok(thread != NULL, "CreateThread failed: %u\n", GetLastError());
        ok(!WaitForSingleObject(thread, 1000), "wait failed\n");
    }
3628

3629 3630 3631 3632 3633 3634
    SET_EXPECT(PreInitialize);
    SET_EXPECT(PostInitialize);
    hr = CoInitializeEx(NULL, expected_coinit_flags = ((mt ? COINIT_MULTITHREADED : COINIT_APARTMENTTHREADED) | COINIT_DISABLE_OLE1DDE));
    ok(hr == S_FALSE, "Failed to initialize COM, hr %#x.\n", hr);
    CHECK_CALLED(PreInitialize, 3);
    CHECK_CALLED(PostInitialize, 3);
3635

3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662
    SET_EXPECT(PreUninitialize);
    SET_EXPECT(PostUninitialize);
    CoUninitialize();
    CHECK_CALLED(PreUninitialize, 3);
    CHECK_CALLED(PostUninitialize, 3);

    SET_EXPECT(PreUninitialize);
    SET_EXPECT(PostUninitialize);
    CoUninitialize();
    CHECK_CALLED(PreUninitialize, 3);
    CHECK_CALLED(PostUninitialize, 3);

    if (mt)
    {
        SET_EXPECT(PreUninitialize);
        SET_EXPECT(PostUninitialize);
        CoUninitialize();
        CHECK_CALLED(PreUninitialize, 3);
        CHECK_CALLED(PostUninitialize, 3);
    }

    SET_EXPECT(PreInitialize);
    SET_EXPECT(PostInitialize);
    hr = CoInitializeEx(NULL, expected_coinit_flags = ((mt ? COINIT_MULTITHREADED : COINIT_APARTMENTTHREADED) | COINIT_DISABLE_OLE1DDE));
    ok(hr == S_OK, "Failed to initialize COM, hr %#x.\n", hr);
    CHECK_CALLED(PreInitialize, 3);
    CHECK_CALLED(PostInitialize, 3);
3663

3664 3665
    SET_EXPECT(PreUninitialize);
    revoke_spies_on_uninit = TRUE;
3666
    CoUninitialize();
3667
    CHECK_CALLED(PreUninitialize, 1);
3668 3669
}

3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811
static HRESULT g_persistfile_qi_ret;
static HRESULT g_persistfile_load_ret;
static HRESULT WINAPI testinstance_QI(IPersistFile *iface, REFIID riid, void **obj)
{
    if (IsEqualIID(riid, &IID_IUnknown)) {
        *obj = iface;
        IUnknown_AddRef(iface);
        return S_OK;
    }

    if (IsEqualIID(riid, &IID_IPersistFile)) {
        if (SUCCEEDED(g_persistfile_qi_ret)) {
            *obj = iface;
            IUnknown_AddRef(iface);
        }
        else
            *obj = NULL;
        return g_persistfile_qi_ret;
    }

    ok(0, "unexpected riid %s\n", wine_dbgstr_guid(riid));
    *obj = NULL;
    return E_NOINTERFACE;
}

static ULONG WINAPI testinstance_AddRef(IPersistFile *iface)
{
    return 2;
}

static ULONG WINAPI testinstance_Release(IPersistFile *iface)
{
    return 1;
}

static HRESULT WINAPI testinstance_GetClassID(IPersistFile *iface, CLSID *clsid)
{
    ok(0, "unexpected call\n");
    return E_NOTIMPL;
}

static HRESULT WINAPI testinstance_IsDirty(IPersistFile *iface)
{
    ok(0, "unexpected call\n");
    return E_NOTIMPL;
}

static HRESULT WINAPI testinstance_Load(IPersistFile *iface, LPCOLESTR filename, DWORD mode)
{
    return g_persistfile_load_ret;
}

static HRESULT WINAPI testinstance_Save(IPersistFile *iface, LPCOLESTR filename, BOOL remember)
{
    return E_NOTIMPL;
}

static HRESULT WINAPI testinstance_SaveCompleted(IPersistFile *iface, LPCOLESTR filename)
{
    ok(0, "unexpected call\n");
    return E_NOTIMPL;
}

static HRESULT WINAPI testinstance_GetCurFile(IPersistFile *iface, LPOLESTR *filename)
{
    ok(0, "unexpected call\n");
    return E_NOTIMPL;
}

static const IPersistFileVtbl testpersistfilevtbl = {
    testinstance_QI,
    testinstance_AddRef,
    testinstance_Release,
    testinstance_GetClassID,
    testinstance_IsDirty,
    testinstance_Load,
    testinstance_Save,
    testinstance_SaveCompleted,
    testinstance_GetCurFile
};

static IPersistFile testpersistfile = { &testpersistfilevtbl };

static HRESULT WINAPI getinstance_cf_QI(IClassFactory *iface, REFIID riid, void **obj)
{
    if (IsEqualIID(riid, &IID_IUnknown) || IsEqualIID(riid, &IID_IClassFactory)) {
        *obj = iface;
        IClassFactory_AddRef(iface);
        return S_OK;
    }

    *obj = NULL;
    return E_NOINTERFACE;
}

static ULONG WINAPI getinstance_cf_AddRef(IClassFactory *iface)
{
    return 2;
}

static ULONG WINAPI getinstance_cf_Release(IClassFactory *iface)
{
    return 1;
}

static HRESULT WINAPI getinstance_cf_CreateInstance(IClassFactory *iface, IUnknown *outer,
    REFIID riid, void **obj)
{
    if (IsEqualIID(riid, &IID_IUnknown)) {
        *obj = &testpersistfile;
        return S_OK;
    }

    ok(0, "unexpected call, riid %s\n", wine_dbgstr_guid(riid));
    *obj = NULL;
    return E_NOTIMPL;
}

static HRESULT WINAPI getinstance_cf_LockServer(IClassFactory *iface, BOOL lock)
{
    ok(0, "unexpected call\n");
    return E_NOTIMPL;
}

static const IClassFactoryVtbl getinstance_cf_vtbl = {
    getinstance_cf_QI,
    getinstance_cf_AddRef,
    getinstance_cf_Release,
    getinstance_cf_CreateInstance,
    getinstance_cf_LockServer
};

static IClassFactory getinstance_cf = { &getinstance_cf_vtbl  };

static void test_CoGetInstanceFromFile(void)
{
    static const WCHAR filenameW[] = {'d','u','m','m','y','p','a','t','h',0};
    CLSID *clsid = (CLSID*)&CLSID_testclsid;
    MULTI_QI mqi[2];
    DWORD cookie;
    HRESULT hr;

3812
    hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918
    ok(hr == S_OK, "got 0x%08x\n", hr);

    /* CLSID is not specified, file does not exist */
    mqi[0].pIID = &IID_IUnknown;
    mqi[0].pItf = NULL;
    mqi[0].hr = E_NOTIMPL;
    hr = CoGetInstanceFromFile(NULL, NULL, NULL, CLSCTX_INPROC_SERVER, STGM_READ, (OLECHAR*)filenameW, 1, mqi);
todo_wine
    ok(hr == MK_E_CANTOPENFILE, "got 0x%08x\n", hr);
    ok(mqi[0].pItf == NULL, "got %p\n", mqi[0].pItf);
    ok(mqi[0].hr == E_NOINTERFACE, "got 0x%08x\n", mqi[0].hr);

    /* class is not available */
    mqi[0].pIID = &IID_IUnknown;
    mqi[0].pItf = NULL;
    mqi[0].hr = E_NOTIMPL;
    hr = CoGetInstanceFromFile(NULL, clsid, NULL, CLSCTX_INPROC_SERVER, STGM_READ, (OLECHAR*)filenameW, 1, mqi);
    ok(hr == REGDB_E_CLASSNOTREG, "got 0x%08x\n", hr);
    ok(mqi[0].pItf == NULL, "got %p\n", mqi[0].pItf);
    ok(mqi[0].hr == REGDB_E_CLASSNOTREG, "got 0x%08x\n", mqi[0].hr);

    hr = CoRegisterClassObject(clsid, (IUnknown*)&getinstance_cf, CLSCTX_INPROC_SERVER, REGCLS_MULTIPLEUSE,
        &cookie);
    ok(hr == S_OK, "got 0x%08x\n", hr);

    mqi[0].pIID = &IID_IUnknown;
    mqi[0].pItf = (void*)0xdeadbeef;
    mqi[0].hr = S_OK;
    hr = CoGetInstanceFromFile(NULL, clsid, NULL, CLSCTX_INPROC_SERVER, STGM_READ, (OLECHAR*)filenameW, 1, mqi);
todo_wine {
    ok(hr == E_INVALIDARG, "got 0x%08x\n", hr);
    ok(mqi[0].pItf == (void*)0xdeadbeef, "got %p\n", mqi[0].pItf);
}
    ok(mqi[0].hr == S_OK, "got 0x%08x\n", mqi[0].hr);

    mqi[0].pIID = &IID_IUnknown;
    mqi[0].pItf = (void*)0xdeadbeef;
    mqi[0].hr = E_NOTIMPL;
    hr = CoGetInstanceFromFile(NULL, clsid, NULL, CLSCTX_INPROC_SERVER, STGM_READ, (OLECHAR*)filenameW, 1, mqi);
todo_wine {
    ok(hr == E_INVALIDARG, "got 0x%08x\n", hr);
    ok(mqi[0].pItf == (void*)0xdeadbeef, "got %p\n", mqi[0].pItf);
    ok(mqi[0].hr == E_NOTIMPL, "got 0x%08x\n", mqi[0].hr);
}
    mqi[0].pIID = &IID_IUnknown;
    mqi[0].pItf = NULL;
    mqi[0].hr = E_NOTIMPL;
    hr = CoGetInstanceFromFile(NULL, clsid, NULL, CLSCTX_INPROC_SERVER, STGM_READ, (OLECHAR*)filenameW, 1, mqi);
    ok(hr == S_OK, "got 0x%08x\n", hr);
    ok(mqi[0].pItf != NULL, "got %p\n", mqi[0].pItf);
    ok(mqi[0].hr == S_OK, "got 0x%08x\n", mqi[0].hr);

    mqi[0].pIID = &IID_IUnknown;
    mqi[0].pItf = NULL;
    mqi[0].hr = S_OK;
    hr = CoGetInstanceFromFile(NULL, clsid, NULL, CLSCTX_INPROC_SERVER, STGM_READ, (OLECHAR*)filenameW, 1, mqi);
    ok(hr == S_OK, "got 0x%08x\n", hr);
    ok(mqi[0].pItf != NULL, "got %p\n", mqi[0].pItf);
    ok(mqi[0].hr == S_OK, "got 0x%08x\n", mqi[0].hr);

    mqi[0].pIID = &IID_IUnknown;
    mqi[0].pItf = NULL;
    mqi[0].hr = S_OK;
    g_persistfile_qi_ret = S_FALSE;
    hr = CoGetInstanceFromFile(NULL, clsid, NULL, CLSCTX_INPROC_SERVER, STGM_READ, (OLECHAR*)filenameW, 1, mqi);
    ok(hr == S_OK, "got 0x%08x\n", hr);
    ok(mqi[0].pItf != NULL, "got %p\n", mqi[0].pItf);
    ok(mqi[0].hr == S_OK, "got 0x%08x\n", mqi[0].hr);
    g_persistfile_qi_ret = S_OK;

    mqi[0].pIID = &IID_IUnknown;
    mqi[0].pItf = NULL;
    mqi[0].hr = S_OK;
    mqi[1].pIID = &IID_IUnknown;
    mqi[1].pItf = NULL;
    mqi[1].hr = S_OK;
    g_persistfile_qi_ret = 0x8000efef;
    hr = CoGetInstanceFromFile(NULL, clsid, NULL, CLSCTX_INPROC_SERVER, STGM_READ, (OLECHAR*)filenameW, 2, mqi);
    ok(hr == 0x8000efef, "got 0x%08x\n", hr);
    ok(mqi[0].pItf == NULL, "got %p\n", mqi[0].pItf);
    ok(mqi[0].hr == 0x8000efef, "got 0x%08x\n", mqi[0].hr);
    ok(mqi[1].pItf == NULL, "got %p\n", mqi[1].pItf);
    ok(mqi[1].hr == 0x8000efef, "got 0x%08x\n", mqi[1].hr);
    g_persistfile_qi_ret = S_OK;

    mqi[0].pIID = &IID_IUnknown;
    mqi[0].pItf = NULL;
    mqi[0].hr = S_OK;
    mqi[1].pIID = &IID_IUnknown;
    mqi[1].pItf = NULL;
    mqi[1].hr = S_OK;
    g_persistfile_load_ret = 0x8000fefe;
    hr = CoGetInstanceFromFile(NULL, clsid, NULL, CLSCTX_INPROC_SERVER, STGM_READ, (OLECHAR*)filenameW, 2, mqi);
    ok(hr == 0x8000fefe, "got 0x%08x\n", hr);
    ok(mqi[0].pItf == NULL, "got %p\n", mqi[0].pItf);
    ok(mqi[0].hr == 0x8000fefe, "got 0x%08x\n", mqi[0].hr);
    ok(mqi[1].pItf == NULL, "got %p\n", mqi[1].pItf);
    ok(mqi[1].hr == 0x8000fefe, "got 0x%08x\n", mqi[1].hr);
    g_persistfile_load_ret = S_OK;

    hr = CoRevokeClassObject(cookie);
    ok(hr == S_OK, "got 0x%08x\n", hr);

    CoUninitialize();
}

3919 3920 3921
static void test_GlobalOptions(void)
{
    IGlobalOptions *global_options;
3922
    ULONG_PTR value;
3923 3924 3925 3926 3927 3928
    HRESULT hres;

    CoInitialize(NULL);

    hres = CoCreateInstance(&CLSID_GlobalOptions, NULL, CLSCTX_INPROC_SERVER,
            &IID_IGlobalOptions, (void**)&global_options);
3929 3930 3931 3932 3933 3934 3935
    ok(hres == S_OK || broken(hres == E_NOINTERFACE), "CoCreateInstance(CLSID_GlobalOptions) failed: %08x\n", hres);
    if(FAILED(hres))
    {
        win_skip("CLSID_GlobalOptions not available\n");
        CoUninitialize();
        return;
    }
3936

3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948
    hres = IGlobalOptions_Query(global_options, 0, &value);
    ok(FAILED(hres), "Unexpected hr %#x.\n", hres);

    hres = IGlobalOptions_Query(global_options, COMGLB_PROPERTIES_RESERVED3 + 1, &value);
    ok(FAILED(hres), "Unexpected hr %#x.\n", hres);

    value = ~0u;
    hres = IGlobalOptions_Query(global_options, COMGLB_EXCEPTION_HANDLING, &value);
    ok(hres == S_OK || broken(hres == E_FAIL) /* Vista */, "Unexpected hr %#x.\n", hres);
    if (SUCCEEDED(hres))
        ok(value == COMGLB_EXCEPTION_HANDLE, "Unexpected value %ld.\n", value);

3949 3950 3951 3952 3953 3954 3955 3956 3957
    IGlobalOptions_Release(global_options);

    hres = CoCreateInstance(&CLSID_GlobalOptions, (IUnknown*)0xdeadbeef, CLSCTX_INPROC_SERVER,
            &IID_IGlobalOptions, (void**)&global_options);
    ok(hres == E_INVALIDARG, "CoCreateInstance(CLSID_GlobalOptions) failed: %08x\n", hres);

    CoUninitialize();
}

3958
static void init_funcs(void)
3959
{
3960 3961 3962 3963
    HMODULE hOle32 = GetModuleHandleA("ole32");
    HMODULE hAdvapi32 = GetModuleHandleA("advapi32");
    HMODULE hkernel32 = GetModuleHandleA("kernel32");

3964
    pCoGetObjectContext = (void*)GetProcAddress(hOle32, "CoGetObjectContext");
3965
    pCoSwitchCallContext = (void*)GetProcAddress(hOle32, "CoSwitchCallContext");
3966
    pCoGetContextToken = (void*)GetProcAddress(hOle32, "CoGetContextToken");
3967
    pCoGetApartmentType = (void*)GetProcAddress(hOle32, "CoGetApartmentType");
3968 3969
    pCoIncrementMTAUsage = (void*)GetProcAddress(hOle32, "CoIncrementMTAUsage");
    pCoDecrementMTAUsage = (void*)GetProcAddress(hOle32, "CoDecrementMTAUsage");
3970
    pCoCreateInstanceFromApp = (void*)GetProcAddress(hOle32, "CoCreateInstanceFromApp");
3971
    pRegDeleteKeyExA = (void*)GetProcAddress(hAdvapi32, "RegDeleteKeyExA");
3972
    pRegOverridePredefKey = (void*)GetProcAddress(hAdvapi32, "RegOverridePredefKey");
3973

3974
    pIsWow64Process = (void*)GetProcAddress(hkernel32, "IsWow64Process");
3975 3976
}

3977 3978 3979 3980 3981
static DWORD CALLBACK implicit_mta_proc(void *param)
{
    IComThreadingInfo *threading_info;
    ULONG_PTR token;
    IUnknown *unk;
3982 3983
    DWORD cookie;
    CLSID clsid;
3984 3985
    HRESULT hr;

3986
    test_apt_type(APTTYPE_MTA, APTTYPEQUALIFIER_IMPLICIT_MTA);
3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002

    hr = CoCreateInstance(&CLSID_InternetZoneManager, NULL, CLSCTX_INPROC_SERVER, &IID_IUnknown, (void **)&unk);
    ok_ole_success(hr, "CoCreateInstance");
    IUnknown_Release(unk);

    hr = CoGetClassObject(&CLSID_InternetZoneManager, CLSCTX_INPROC_SERVER, NULL, &IID_IUnknown, (void **)&unk);
    ok_ole_success(hr, "CoGetClassObject");
    IUnknown_Release(unk);

    hr = CoGetObjectContext(&IID_IComThreadingInfo, (void **)&threading_info);
    ok_ole_success(hr, "CoGetObjectContext");
    IComThreadingInfo_Release(threading_info);

    hr = CoGetContextToken(&token);
    ok_ole_success(hr, "CoGetContextToken");

4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018
    hr = CoRegisterPSClsid(&IID_IWineTest, &CLSID_WineTestPSFactoryBuffer);
    ok_ole_success(hr, "CoRegisterPSClsid");

    hr = CoGetPSClsid(&IID_IClassFactory, &clsid);
    ok_ole_success(hr, "CoGetPSClsid");

    hr = CoRegisterClassObject(&CLSID_WineOOPTest, (IUnknown *)&Test_ClassFactory,
                               CLSCTX_INPROC_SERVER, REGCLS_SINGLEUSE, &cookie);
    ok_ole_success(hr, "CoRegisterClassObject");

    hr = CoRevokeClassObject(cookie);
    ok_ole_success(hr, "CoRevokeClassObject");

    hr = CoRegisterMessageFilter(NULL, NULL);
    ok(hr == CO_E_NOT_SUPPORTED, "got %#x\n", hr);

4019
    hr = CoLockObjectExternal(&Test_Unknown, TRUE, TRUE);
4020 4021
    ok_ole_success(hr, "CoLockObjectExternal");

4022
    hr = CoDisconnectObject(&Test_Unknown, 0);
4023 4024
    ok_ole_success(hr, "CoDisconnectObject");

4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041
    return 0;
}

/* Some COM functions (perhaps even all of them?) can make use of an "implicit"
 * multi-threaded apartment created by another thread in the same process. */
static void test_implicit_mta(void)
{
    HANDLE thread;

    CoInitializeEx(NULL, COINIT_MULTITHREADED);

    thread = CreateThread(NULL, 0, implicit_mta_proc, NULL, 0, NULL);
    ok(!WaitForSingleObject(thread, 1000), "wait failed\n");

    CoUninitialize();
}

4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066
static DWORD WINAPI co_get_current_process_thread(void *param)
{
    DWORD *id = param;

    *id = CoGetCurrentProcess();
    return 0;
}

static void test_CoGetCurrentProcess(void)
{
    DWORD id, id2;
    HANDLE thread;

    id = CoGetCurrentProcess();
    ok(!!id && id != GetCurrentProcessId() && id != GetCurrentThreadId(), "Unexpected result %d.\n", id);

    id2 = 0;
    thread = CreateThread(NULL, 0, co_get_current_process_thread, &id2, 0, NULL);
    ok(thread != NULL, "Failed to create test thread.\n");
    ok(!WaitForSingleObject(thread, 10000), "Wait timed out.\n");
    CloseHandle(thread);

    ok(id2 && id2 != id, "Unexpected id from another thread.\n");
}

4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100
static void test_mta_usage(void)
{
    CO_MTA_USAGE_COOKIE cookie, cookie2;
    HRESULT hr;

    if (!pCoIncrementMTAUsage)
    {
        win_skip("CoIncrementMTAUsage() is not available.\n");
        return;
    }

    test_apt_type(APTTYPE_CURRENT, APTTYPEQUALIFIER_NONE);

    cookie = 0;
    hr = pCoIncrementMTAUsage(&cookie);
    ok(hr == S_OK, "Unexpected hr %#x.\n", hr);
    ok(cookie != NULL, "Unexpected cookie %p.\n", cookie);

    cookie2 = 0;
    hr = pCoIncrementMTAUsage(&cookie2);
    ok(hr == S_OK, "Unexpected hr %#x.\n", hr);
    ok(cookie2 != NULL && cookie2 != cookie, "Unexpected cookie %p.\n", cookie2);

    test_apt_type(APTTYPE_MTA, APTTYPEQUALIFIER_IMPLICIT_MTA);

    hr = pCoDecrementMTAUsage(cookie);
    ok(hr == S_OK, "Unexpected hr %#x.\n", hr);

    test_apt_type(APTTYPE_MTA, APTTYPEQUALIFIER_IMPLICIT_MTA);

    hr = pCoDecrementMTAUsage(cookie2);
    ok(hr == S_OK, "Unexpected hr %#x.\n", hr);

    test_apt_type(APTTYPE_CURRENT, APTTYPEQUALIFIER_NONE);
4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119

    hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
    ok(hr == S_OK, "Unexpected hr %#x.\n", hr);

    test_apt_type(APTTYPE_MAINSTA, APTTYPEQUALIFIER_NONE);

    cookie = 0;
    hr = pCoIncrementMTAUsage(&cookie);
    ok(hr == S_OK, "Unexpected hr %#x.\n", hr);
    ok(cookie != NULL, "Unexpected cookie %p.\n", cookie);

    test_apt_type(APTTYPE_MAINSTA, APTTYPEQUALIFIER_NONE);

    hr = pCoDecrementMTAUsage(cookie);
    ok(hr == S_OK, "Unexpected hr %#x.\n", hr);

    CoUninitialize();

    test_apt_type(APTTYPE_CURRENT, APTTYPEQUALIFIER_NONE);
4120 4121
}

4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222
static void test_CoCreateInstanceFromApp(void)
{
    static const CLSID *supported_classes[] =
    {
        &CLSID_InProcFreeMarshaler,
        &CLSID_GlobalOptions,
        &CLSID_StdGlobalInterfaceTable,
    };
    static const CLSID *unsupported_classes[] =
    {
        &CLSID_ManualResetEvent,
    };
    unsigned int i;
    IUnknown *unk;
    DWORD cookie;
    MULTI_QI mqi;
    HRESULT hr;
    HANDLE handle;
    ULONG_PTR actctx_cookie;

    if (!pCoCreateInstanceFromApp)
    {
        win_skip("CoCreateInstanceFromApp() is not available.\n");
        return;
    }

    CoInitialize(NULL);

    for (i = 0; i < ARRAY_SIZE(supported_classes); ++i)
    {
        memset(&mqi, 0, sizeof(mqi));
        mqi.pIID = &IID_IUnknown;
        hr = pCoCreateInstanceFromApp(supported_classes[i], NULL, CLSCTX_INPROC_SERVER, NULL, 1, &mqi);
        ok(hr == S_OK, "Unexpected hr %#x.\n", hr);
        IUnknown_Release(mqi.pItf);

        hr = CoCreateInstance(supported_classes[i], NULL, CLSCTX_INPROC_SERVER, &IID_IUnknown, (void **)&unk);
        ok(hr == S_OK, "Unexpected hr %#x.\n", hr);
        IUnknown_Release(unk);
    }

    for (i = 0; i < ARRAY_SIZE(unsupported_classes); ++i)
    {
        memset(&mqi, 0, sizeof(mqi));
        mqi.pIID = &IID_IUnknown;
        hr = pCoCreateInstanceFromApp(unsupported_classes[i], NULL, CLSCTX_INPROC_SERVER, NULL, 1, &mqi);
        ok(hr == REGDB_E_CLASSNOTREG, "Unexpected hr %#x.\n", hr);

        hr = CoCreateInstance(unsupported_classes[i], NULL, CLSCTX_INPROC_SERVER | CLSCTX_APPCONTAINER,
                &IID_IUnknown, (void **)&unk);
        ok(hr == REGDB_E_CLASSNOTREG, "Unexpected hr %#x.\n", hr);

        hr = CoCreateInstance(unsupported_classes[i], NULL, CLSCTX_INPROC_SERVER, &IID_IUnknown, (void **)&unk);
        ok(hr == S_OK, "Unexpected hr %#x.\n", hr);
        IUnknown_Release(unk);
    }

    /* Locally registered classes are filtered out. */
    hr = CoRegisterClassObject(&CLSID_WineOOPTest, (IUnknown *)&Test_ClassFactory, CLSCTX_INPROC_SERVER,
            REGCLS_MULTIPLEUSE, &cookie);
    ok(hr == S_OK, "Unexpected hr %#x.\n", hr);

    hr = CoGetClassObject(&CLSID_WineOOPTest, CLSCTX_INPROC_SERVER, NULL, &IID_IClassFactory, (void **)&unk);
    ok(hr == S_OK, "Unexpected hr %#x.\n", hr);

    hr = CoGetClassObject(&CLSID_WineOOPTest, CLSCTX_INPROC_SERVER | CLSCTX_APPCONTAINER, NULL,
            &IID_IClassFactory, (void **)&unk);
todo_wine
    ok(hr == E_INVALIDARG, "Unexpected hr %#x.\n", hr);

    hr = CoCreateInstance(&CLSID_WineOOPTest, NULL, CLSCTX_INPROC_SERVER, &IID_IUnknown, (void **)&unk);
    ok(hr == E_NOINTERFACE, "Unexpected hr %#x.\n", hr);

    hr = CoCreateInstance(&CLSID_WineOOPTest, NULL, CLSCTX_INPROC_SERVER | CLSCTX_APPCONTAINER,
            &IID_IUnknown, (void **)&unk);
    ok(hr == REGDB_E_CLASSNOTREG, "Unexpected hr %#x.\n", hr);

    memset(&mqi, 0, sizeof(mqi));
    mqi.pIID = &IID_IUnknown;
    hr = pCoCreateInstanceFromApp(&CLSID_WineOOPTest, NULL, CLSCTX_INPROC_SERVER, NULL, 1, &mqi);
    ok(hr == REGDB_E_CLASSNOTREG, "Unexpected hr %#x.\n", hr);

    hr = CoRevokeClassObject(cookie);
    ok(hr == S_OK, "Unexpected hr %#x.\n", hr);

    /* Activation context */
    if ((handle = activate_context(actctx_manifest, &actctx_cookie)))
    {
        hr = CoCreateInstance(&IID_Testiface7, NULL, CLSCTX_INPROC_SERVER, &IID_IUnknown, (void **)&unk);
        ok(hr == 0x80001235, "Unexpected hr %#x.\n", hr);

        hr = CoCreateInstance(&IID_Testiface7, NULL, CLSCTX_INPROC_SERVER | CLSCTX_APPCONTAINER,
                &IID_IUnknown, (void **)&unk);
        ok(hr == 0x80001235, "Unexpected hr %#x.\n", hr);

        deactivate_context(handle, actctx_cookie);
    }

    CoUninitialize();
}

4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280
static void test_call_cancellation(void)
{
    HRESULT hr;

    /* Cancellation is disabled initially. */
    hr = CoDisableCallCancellation(NULL);
    ok(hr == CO_E_CANCEL_DISABLED, "Unexpected hr %#x.\n", hr);

    hr = CoEnableCallCancellation(NULL);
    ok(hr == S_OK, "Unexpected hr %#x.\n", hr);

    hr = CoDisableCallCancellation(NULL);
    ok(hr == S_OK, "Unexpected hr %#x.\n", hr);

    hr = CoDisableCallCancellation(NULL);
    ok(hr == CO_E_CANCEL_DISABLED, "Unexpected hr %#x.\n", hr);

    hr = CoEnableCallCancellation(NULL);
    ok(hr == S_OK, "Unexpected hr %#x.\n", hr);

    /* Counter is not affected by initialization. */
    hr = CoInitialize(NULL);
    ok(hr == S_OK, "Unexpected hr %#x.\n", hr);

    hr = CoDisableCallCancellation(NULL);
    ok(hr == S_OK, "Unexpected hr %#x.\n", hr);

    hr = CoDisableCallCancellation(NULL);
    ok(hr == CO_E_CANCEL_DISABLED, "Unexpected hr %#x.\n", hr);

    hr = CoEnableCallCancellation(NULL);
    ok(hr == S_OK, "Unexpected hr %#x.\n", hr);

    CoUninitialize();

    hr = CoDisableCallCancellation(NULL);
    ok(hr == S_OK, "Unexpected hr %#x.\n", hr);

    hr = CoDisableCallCancellation(NULL);
    ok(hr == CO_E_CANCEL_DISABLED, "Unexpected hr %#x.\n", hr);

    /* It's cumulative. */
    hr = CoEnableCallCancellation(NULL);
    ok(hr == S_OK, "Unexpected hr %#x.\n", hr);

    hr = CoEnableCallCancellation(NULL);
    ok(hr == S_OK, "Unexpected hr %#x.\n", hr);

    hr = CoDisableCallCancellation(NULL);
    ok(hr == S_OK, "Unexpected hr %#x.\n", hr);

    hr = CoDisableCallCancellation(NULL);
    ok(hr == S_OK, "Unexpected hr %#x.\n", hr);

    hr = CoDisableCallCancellation(NULL);
    ok(hr == CO_E_CANCEL_DISABLED, "Unexpected hr %#x.\n", hr);
}

4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371
enum oletlsflags
{
    OLETLS_UUIDINITIALIZED = 0x2,
    OLETLS_DISABLE_OLE1DDE = 0x40,
    OLETLS_APARTMENTTHREADED = 0x80,
    OLETLS_MULTITHREADED = 0x100,
};

struct oletlsdata
{
    void *threadbase;
    void *smallocator;
    DWORD id;
    DWORD flags;
};

static DWORD get_oletlsflags(void)
{
    struct oletlsdata *data = NtCurrentTeb()->ReservedForOle;
    return data ? data->flags : 0;
}

static DWORD CALLBACK oletlsdata_test_thread(void *arg)
{
    IUnknown *unk;
    DWORD flags;
    HRESULT hr;

    hr = CoCreateInstance(&CLSID_InternetZoneManager, NULL, CLSCTX_INPROC_SERVER, &IID_IUnknown, (void **)&unk);
    ok(hr == S_OK, "Unexpected hr %#x.\n", hr);
    IUnknown_Release(unk);

    /* Flag is not set for implicit MTA. */
    flags = get_oletlsflags();
    ok(!(flags & OLETLS_MULTITHREADED), "Unexpected flags %#x.\n", flags);

    return 0;
}

static void test_oletlsdata(void)
{
    HANDLE thread;
    DWORD flags;
    HRESULT hr;
    GUID guid;

    /* STA */
    hr = CoInitialize(NULL);
    ok(hr == S_OK, "Unexpected hr %#x.\n", hr);
    flags = get_oletlsflags();
    ok(flags & OLETLS_APARTMENTTHREADED && !(flags & OLETLS_DISABLE_OLE1DDE), "Unexpected flags %#x.\n", flags);
    CoUninitialize();
    flags = get_oletlsflags();
    ok(!(flags & (OLETLS_APARTMENTTHREADED | OLETLS_MULTITHREADED | OLETLS_DISABLE_OLE1DDE)), "Unexpected flags %#x.\n", flags);

    hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
    ok(hr == S_OK, "Unexpected hr %#x.\n", hr);
    flags = get_oletlsflags();
    ok(flags & OLETLS_APARTMENTTHREADED && flags & OLETLS_DISABLE_OLE1DDE, "Unexpected flags %#x.\n", flags);
    CoUninitialize();
    flags = get_oletlsflags();
    ok(!(flags & (OLETLS_APARTMENTTHREADED | OLETLS_MULTITHREADED | OLETLS_DISABLE_OLE1DDE)), "Unexpected flags %#x.\n", flags);

    /* MTA */
    hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
    ok(hr == S_OK, "Unexpected hr %#x.\n", hr);
    flags = get_oletlsflags();
    ok(flags & OLETLS_MULTITHREADED && flags & OLETLS_DISABLE_OLE1DDE, "Unexpected flags %#x.\n", flags);

    /* Implicit case. */
    thread = CreateThread(NULL, 0, oletlsdata_test_thread, NULL, 0, &flags);
    ok(thread != NULL, "Failed to create a test thread, error %d.\n", GetLastError());
    ok(!WaitForSingleObject(thread, 5000), "Wait timed out.\n");
    CloseHandle(thread);

    CoUninitialize();
    flags = get_oletlsflags();
    ok(!(flags & (OLETLS_APARTMENTTHREADED | OLETLS_MULTITHREADED | OLETLS_DISABLE_OLE1DDE)), "Unexpected flags %#x.\n", flags);

    /* Thread ID. */
    flags = get_oletlsflags();
    ok(!(flags & OLETLS_UUIDINITIALIZED), "Unexpected flags %#x.\n", flags);

    hr = CoGetCurrentLogicalThreadId(&guid);
    ok(hr == S_OK, "Unexpected hr %#x.\n", hr);

    flags = get_oletlsflags();
    ok(flags & OLETLS_UUIDINITIALIZED && !(flags & (OLETLS_APARTMENTTHREADED | OLETLS_MULTITHREADED)),
            "Unexpected flags %#x.\n", flags);
}

4372 4373 4374 4375
START_TEST(compobj)
{
    init_funcs();

4376 4377 4378 4379 4380
    GetTempPathA(ARRAY_SIZE(testlib), testlib);
    SetCurrentDirectoryA(testlib);
    lstrcatA(testlib, "\\testlib.dll");
    extract_resource("testlib.dll", "TESTDLL", testlib);

4381
    test_oletlsdata();
4382 4383
    test_ProgIDFromCLSID();
    test_CLSIDFromProgID();
4384
    test_CLSIDFromString();
4385
    test_IIDFromString();
4386
    test_StringFromGUID2();
4387
    test_CoCreateInstance();
4388
    test_ole_menu();
4389
    test_CoGetClassObject();
4390
    test_CoCreateInstanceEx();
4391
    test_CoRegisterMessageFilter();
4392
    test_CoRegisterPSClsid();
4393
    test_CoGetPSClsid();
4394
    test_CoUnmarshalInterface();
4395
    test_CoGetInterfaceAndReleaseStream();
4396 4397
    test_CoMarshalInterface();
    test_CoMarshalInterThreadInterfaceInStream();
4398
    test_CoRegisterClassObject();
4399
    test_registered_object_thread_affinity();
4400
    test_CoFreeUnusedLibraries();
4401
    test_CoGetObjectContext();
4402
    test_CoGetCallContext();
4403
    test_CoGetContextToken();
4404
    test_TreatAsClass();
4405
    test_CoInitializeEx();
4406
    test_OleInitialize_InitCounting();
4407
    test_OleRegGetMiscStatus();
4408
    test_CoCreateGuid();
4409
    test_CoWaitForMultipleHandles();
4410
    test_CoGetMalloc();
4411
    test_OleRegGetUserType();
4412
    test_CoGetApartmentType();
4413
    test_IMallocSpy();
4414
    test_CoGetCurrentLogicalThreadId();
4415 4416
    test_IInitializeSpy(FALSE);
    test_IInitializeSpy(TRUE);
4417
    test_CoGetInstanceFromFile();
4418
    test_GlobalOptions();
4419
    test_implicit_mta();
4420
    test_CoGetCurrentProcess();
4421
    test_mta_usage();
4422
    test_CoCreateInstanceFromApp();
4423
    test_call_cancellation();
4424

4425
    DeleteFileA( testlib );
4426
}