compobj.c 146 KB
Newer Older
Alexandre Julliard's avatar
Alexandre Julliard committed
1 2 3 4
/*
 *	COMPOBJ library
 *
 *	Copyright 1995	Martin von Loewis
5
 *	Copyright 1998	Justin Bradford
6
 *      Copyright 1999  Francis Beaudet
7 8 9
 *      Copyright 1999  Sylvain St-Germain
 *      Copyright 2002  Marcus Meissner
 *      Copyright 2004  Mike Hearn
10
 *      Copyright 2005-2006 Robert Shearman (for CodeWeavers)
11 12 13 14 15 16 17 18 19 20 21 22 23
 *
 * 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
24
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
Mike Hearn's avatar
Mike Hearn committed
25
 *
26 27 28 29
 * Note
 * 1. COINIT_MULTITHREADED is 0; it is the lack of COINIT_APARTMENTTHREADED
 *    Therefore do not test against COINIT_MULTITHREADED
 *
Mike Hearn's avatar
Mike Hearn committed
30 31 32 33
 * TODO list:           (items bunched together depend on each other)
 *
 *   - Implement the service control manager (in rpcss) to keep track
 *     of registered class objects: ISCM::ServerRegisterClsid et al
34
 *   - Implement the OXID resolver so we don't need magic endpoint names for
Mike Hearn's avatar
Mike Hearn committed
35 36
 *     clients and servers to meet up
 *
Alexandre Julliard's avatar
Alexandre Julliard committed
37 38
 */

39
#include "config.h"
40

41
#include <stdarg.h>
42
#include <stdio.h>
Alexandre Julliard's avatar
Alexandre Julliard committed
43
#include <string.h>
44
#include <assert.h>
45

46
#define COBJMACROS
47
#define NONAMELESSUNION
48

49 50
#include "ntstatus.h"
#define WIN32_NO_STATUS
51
#include "windef.h"
52
#include "winbase.h"
53 54
#include "winerror.h"
#include "winreg.h"
55
#include "winuser.h"
56
#define USE_COM_CONTEXT_DEF
57 58 59
#include "objbase.h"
#include "ole2.h"
#include "ole2ver.h"
60
#include "ctxtcall.h"
61
#include "dde.h"
62
#include "servprov.h"
63

64
#include "initguid.h"
65
#include "compobj_private.h"
66
#include "moniker.h"
67

68
#include "wine/unicode.h"
69
#include "wine/debug.h"
70

71
WINE_DEFAULT_DEBUG_CHANNEL(ole);
72

73 74
#define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))

75
/****************************************************************************
76
 * This section defines variables internal to the COM module.
77 78
 */

79
static APARTMENT *MTA; /* protected by csApartment */
80
static APARTMENT *MainApartment; /* the first STA apartment */
81
static struct list apts = LIST_INIT( apts ); /* protected by csApartment */
82 83 84 85 86 87

static CRITICAL_SECTION csApartment;
static CRITICAL_SECTION_DEBUG critsect_debug =
{
    0, 0, &csApartment,
    { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
88
      0, 0, { (DWORD_PTR)(__FILE__ ": csApartment") }
89 90
};
static CRITICAL_SECTION csApartment = { &critsect_debug, -1, 0, 0, 0, 0 };
Alexandre Julliard's avatar
Alexandre Julliard committed
91

92 93 94 95 96 97 98 99 100
enum comclass_threadingmodel
{
    ThreadingModel_Apartment = 1,
    ThreadingModel_Free      = 2,
    ThreadingModel_No        = 3,
    ThreadingModel_Both      = 4,
    ThreadingModel_Neutral   = 5
};

101 102 103 104 105 106 107 108 109
enum comclass_miscfields
{
    MiscStatus          = 1,
    MiscStatusIcon      = 2,
    MiscStatusContent   = 4,
    MiscStatusThumbnail = 8,
    MiscStatusDocPrint  = 16
};

110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
struct comclassredirect_data
{
    ULONG size;
    BYTE  res;
    BYTE  miscmask;
    BYTE  res1[2];
    DWORD model;
    GUID  clsid;
    GUID  alias;
    GUID  clsid2;
    GUID  tlbid;
    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;
};

134 135 136 137 138 139 140 141 142 143 144 145
struct ifacepsredirect_data
{
    ULONG size;
    DWORD mask;
    GUID  iid;
    ULONG nummethods;
    GUID  tlbid;
    GUID  base;
    ULONG name_len;
    ULONG name_offset;
};

146 147 148 149 150 151 152
struct progidredirect_data
{
    ULONG size;
    DWORD reserved;
    ULONG clsid_offset;
};

153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
struct class_reg_data
{
    union
    {
        struct
        {
            struct comclassredirect_data *data;
            void *section;
            HANDLE hactctx;
        } actctx;
        HKEY hkey;
    } u;
    BOOL hkey;
};

168 169 170 171 172 173 174
struct registered_psclsid
{
    struct list entry;
    IID iid;
    CLSID clsid;
};

175 176 177 178 179 180 181 182 183 184 185 186 187 188
/*
 * This is a marshallable object exposing registered local servers.
 * IServiceProvider is used only because it happens meet requirements
 * and already has proxy/stub code. If more functionality is needed,
 * a custom interface may be used instead.
 */
struct LocalServer
{
    IServiceProvider IServiceProvider_iface;
    LONG ref;
    APARTMENT *apt;
    IStream *marshal_stream;
};

189 190 191 192 193
/*
 * This lock count counts the number of times CoInitialize is called. It is
 * decreased every time CoUninitialize is called. When it hits 0, the COM
 * libraries are freed
 */
194
static LONG s_COMLockCount = 0;
195 196
/* Reference count used by CoAddRefServerProcess/CoReleaseServerProcess */
static LONG s_COMServerProcessReferences = 0;
197 198 199 200 201 202 203

/*
 * This linked list contains the list of registered class objects. These
 * are mostly used to register the factories for out-of-proc servers of OLE
 * objects.
 *
 * TODO: Make this data structure aware of inter-process communication. This
204
 *       means that parts of this will be exported to rpcss.
205 206 207
 */
typedef struct tagRegisteredClass
{
208
  struct list entry;
209
  CLSID     classIdentifier;
210
  OXID      apartment_id;
211 212 213 214
  LPUNKNOWN classObject;
  DWORD     runContext;
  DWORD     connectFlags;
  DWORD     dwCookie;
215
  void     *RpcRegistration;
216 217
} RegisteredClass;

218
static struct list RegisteredClassList = LIST_INIT(RegisteredClassList);
219

220 221 222 223 224
static CRITICAL_SECTION csRegisteredClassList;
static CRITICAL_SECTION_DEBUG class_cs_debug =
{
    0, 0, &csRegisteredClassList,
    { &class_cs_debug.ProcessLocksList, &class_cs_debug.ProcessLocksList },
225
      0, 0, { (DWORD_PTR)(__FILE__ ": csRegisteredClassList") }
226 227 228
};
static CRITICAL_SECTION csRegisteredClassList = { &class_cs_debug, -1, 0, 0, 0, 0 };

229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
static inline enum comclass_miscfields dvaspect_to_miscfields(DWORD aspect)
{
    switch (aspect)
    {
    case DVASPECT_CONTENT:
        return MiscStatusContent;
    case DVASPECT_THUMBNAIL:
        return MiscStatusThumbnail;
    case DVASPECT_ICON:
        return MiscStatusIcon;
    case DVASPECT_DOCPRINT:
        return MiscStatusDocPrint;
    default:
        return MiscStatus;
    };
}

BOOL actctx_get_miscstatus(const CLSID *clsid, DWORD aspect, DWORD *status)
{
    ACTCTX_SECTION_KEYED_DATA data;

    data.cbSize = sizeof(data);
    if (FindActCtxSectionGuid(0, NULL, ACTIVATION_CONTEXT_SECTION_COM_SERVER_REDIRECTION,
                              clsid, &data))
    {
        struct comclassredirect_data *comclass = (struct comclassredirect_data*)data.lpData;
        enum comclass_miscfields misc = dvaspect_to_miscfields(aspect);

        if (!(comclass->miscmask & misc))
        {
            if (!(comclass->miscmask & MiscStatus))
            {
                *status = 0;
                return TRUE;
            }
            misc = MiscStatus;
        }

        switch (misc)
        {
        case MiscStatus:
            *status = comclass->miscstatus;
            break;
        case MiscStatusIcon:
            *status = comclass->miscstatusicon;
            break;
        case MiscStatusContent:
            *status = comclass->miscstatuscontent;
            break;
        case MiscStatusThumbnail:
            *status = comclass->miscstatusthumbnail;
            break;
        case MiscStatusDocPrint:
            *status = comclass->miscstatusdocprint;
            break;
        default:
           ;
        };

        return TRUE;
    }
    else
        return FALSE;
}

294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
/* wrapper for NtCreateKey that creates the key recursively if necessary */
static NTSTATUS create_key( HKEY *retkey, ACCESS_MASK access, OBJECT_ATTRIBUTES *attr )
{
    NTSTATUS status = NtCreateKey( (HANDLE *)retkey, access, attr, 0, NULL, 0, NULL );

    if (status == STATUS_OBJECT_NAME_NOT_FOUND)
    {
        HANDLE subkey, root = attr->RootDirectory;
        WCHAR *buffer = attr->ObjectName->Buffer;
        DWORD attrs, pos = 0, i = 0, len = attr->ObjectName->Length / sizeof(WCHAR);
        UNICODE_STRING str;

        while (i < len && buffer[i] != '\\') i++;
        if (i == len) return status;

        attrs = attr->Attributes;
        attr->ObjectName = &str;

        while (i < len)
        {
            str.Buffer = buffer + pos;
            str.Length = (i - pos) * sizeof(WCHAR);
            status = NtCreateKey( &subkey, access, attr, 0, NULL, 0, NULL );
            if (attr->RootDirectory != root) NtClose( attr->RootDirectory );
            if (status) return status;
            attr->RootDirectory = subkey;
            while (i < len && buffer[i] == '\\') i++;
            pos = i;
            while (i < len && buffer[i] != '\\') i++;
        }
        str.Buffer = buffer + pos;
        str.Length = (i - pos) * sizeof(WCHAR);
        attr->Attributes = attrs;
        status = NtCreateKey( (PHANDLE)retkey, access, attr, 0, NULL, 0, NULL );
        if (attr->RootDirectory != root) NtClose( attr->RootDirectory );
    }
    return status;
}

static const WCHAR classes_rootW[] =
334 335
    {'\\','R','e','g','i','s','t','r','y','\\','M','a','c','h','i','n','e',
     '\\','S','o','f','t','w','a','r','e','\\','C','l','a','s','s','e','s',0};
336 337 338 339

static HKEY classes_root_hkey;

/* create the special HKEY_CLASSES_ROOT key */
340
static HKEY create_classes_root_hkey(DWORD access)
341 342 343 344 345 346 347 348 349 350 351 352
{
    HKEY hkey, ret = 0;
    OBJECT_ATTRIBUTES attr;
    UNICODE_STRING name;

    attr.Length = sizeof(attr);
    attr.RootDirectory = 0;
    attr.ObjectName = &name;
    attr.Attributes = 0;
    attr.SecurityDescriptor = NULL;
    attr.SecurityQualityOfService = NULL;
    RtlInitUnicodeString( &name, classes_rootW );
353
    if (create_key( &hkey, access, &attr )) return 0;
354 355
    TRACE( "%s -> %p\n", debugstr_w(attr.ObjectName->Buffer), hkey );

356 357 358 359 360 361 362
    if (!(access & KEY_WOW64_64KEY))
    {
        if (!(ret = InterlockedCompareExchangePointer( (void **)&classes_root_hkey, hkey, 0 )))
            ret = hkey;
        else
            NtClose( hkey );  /* somebody beat us to it */
    }
363
    else
364
        ret = hkey;
365 366 367 368
    return ret;
}

/* map the hkey from special root to normal key if necessary */
369
static inline HKEY get_classes_root_hkey( HKEY hkey, REGSAM access )
370 371
{
    HKEY ret = hkey;
372 373
    const BOOL is_win64 = sizeof(void*) > sizeof(int);
    const BOOL force_wow32 = is_win64 && (access & KEY_WOW64_32KEY);
374

375 376 377 378 379 380 381 382 383 384 385
    if (hkey == HKEY_CLASSES_ROOT &&
        ((access & KEY_WOW64_64KEY) || !(ret = classes_root_hkey)))
        ret = create_classes_root_hkey(MAXIMUM_ALLOWED | (access & KEY_WOW64_64KEY));
    if (force_wow32 && ret && ret == classes_root_hkey)
    {
        static const WCHAR wow6432nodeW[] = {'W','o','w','6','4','3','2','N','o','d','e',0};
        access &= ~KEY_WOW64_32KEY;
        if (create_classes_key(classes_root_hkey, wow6432nodeW, access, &hkey))
            return 0;
        ret = hkey;
    }
386 387 388 389 390 391 392 393 394

    return ret;
}

LSTATUS create_classes_key( HKEY hkey, const WCHAR *name, REGSAM access, HKEY *retkey )
{
    OBJECT_ATTRIBUTES attr;
    UNICODE_STRING nameW;

395
    if (!(hkey = get_classes_root_hkey( hkey, access ))) return ERROR_INVALID_HANDLE;
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412

    attr.Length = sizeof(attr);
    attr.RootDirectory = hkey;
    attr.ObjectName = &nameW;
    attr.Attributes = 0;
    attr.SecurityDescriptor = NULL;
    attr.SecurityQualityOfService = NULL;
    RtlInitUnicodeString( &nameW, name );

    return RtlNtStatusToDosError( create_key( retkey, access, &attr ) );
}

LSTATUS open_classes_key( HKEY hkey, const WCHAR *name, REGSAM access, HKEY *retkey )
{
    OBJECT_ATTRIBUTES attr;
    UNICODE_STRING nameW;

413
    if (!(hkey = get_classes_root_hkey( hkey, access ))) return ERROR_INVALID_HANDLE;
414 415 416 417 418 419 420 421 422 423 424 425

    attr.Length = sizeof(attr);
    attr.RootDirectory = hkey;
    attr.ObjectName = &nameW;
    attr.Attributes = 0;
    attr.SecurityDescriptor = NULL;
    attr.SecurityQualityOfService = NULL;
    RtlInitUnicodeString( &nameW, name );

    return RtlNtStatusToDosError( NtOpenKey( (HANDLE *)retkey, access, &attr ) );
}

426 427 428 429
/*****************************************************************************
 * This section contains OpenDllList definitions
 *
 * The OpenDllList contains only handles of dll loaded by CoGetClassObject or
430 431
 * other functions that do LoadLibrary _without_ giving back a HMODULE.
 * Without this list these handles would never be freed.
432
 *
433
 * FIXME: a DLL that says OK when asked for unloading is unloaded in the
434
 * next unload-call but not before 600 sec.
435
 */
436

437 438 439
typedef HRESULT (CALLBACK *DllGetClassObjectFunc)(REFCLSID clsid, REFIID iid, LPVOID *ppv);
typedef HRESULT (WINAPI *DllCanUnloadNowFunc)(void);

440 441 442 443 444
typedef struct tagOpenDll
{
  LONG refs;
  LPWSTR library_name;
  HANDLE library;
445 446
  DllGetClassObjectFunc DllGetClassObject;
  DllCanUnloadNowFunc DllCanUnloadNow;
447
  struct list entry;
448 449
} OpenDll;

450
static struct list openDllList = LIST_INIT(openDllList);
451

452 453 454 455 456
static CRITICAL_SECTION csOpenDllList;
static CRITICAL_SECTION_DEBUG dll_cs_debug =
{
    0, 0, &csOpenDllList,
    { &dll_cs_debug.ProcessLocksList, &dll_cs_debug.ProcessLocksList },
457
      0, 0, { (DWORD_PTR)(__FILE__ ": csOpenDllList") }
458 459 460
};
static CRITICAL_SECTION csOpenDllList = { &dll_cs_debug, -1, 0, 0, 0, 0 };

461 462 463 464
struct apartment_loaded_dll
{
    struct list entry;
    OpenDll *dll;
465
    DWORD unload_time;
466
    BOOL multi_threaded;
467 468
};

469
static const WCHAR wszAptWinClass[] = {'O','l','e','M','a','i','n','T','h','r','e','a','d','W','n','d','C','l','a','s','s',0};
470

471 472 473
/*****************************************************************************
 * This section contains OpenDllList implementation
 */
474

475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
static OpenDll *COMPOBJ_DllList_Get(LPCWSTR library_name)
{
    OpenDll *ptr;
    OpenDll *ret = NULL;
    EnterCriticalSection(&csOpenDllList);
    LIST_FOR_EACH_ENTRY(ptr, &openDllList, OpenDll, entry)
    {
        if (!strcmpiW(library_name, ptr->library_name) &&
            (InterlockedIncrement(&ptr->refs) != 1) /* entry is being destroy if == 1 */)
        {
            ret = ptr;
            break;
        }
    }
    LeaveCriticalSection(&csOpenDllList);
    return ret;
}
492

493 494
/* caller must ensure that library_name is not already in the open dll list */
static HRESULT COMPOBJ_DllList_Add(LPCWSTR library_name, OpenDll **ret)
495
{
496 497 498 499 500 501
    OpenDll *entry;
    int len;
    HRESULT hr = S_OK;
    HANDLE hLibrary;
    DllCanUnloadNowFunc DllCanUnloadNow;
    DllGetClassObjectFunc DllGetClassObject;
502

503
    TRACE("%s\n", debugstr_w(library_name));
504 505 506 507 508 509 510 511 512 513 514 515 516 517 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

    *ret = COMPOBJ_DllList_Get(library_name);
    if (*ret) return S_OK;

    /* do this outside the csOpenDllList to avoid creating a lock dependency on
     * the loader lock */
    hLibrary = LoadLibraryExW(library_name, 0, LOAD_WITH_ALTERED_SEARCH_PATH);
    if (!hLibrary)
    {
        ERR("couldn't load in-process dll %s\n", debugstr_w(library_name));
        /* failure: DLL could not be loaded */
        return E_ACCESSDENIED; /* FIXME: or should this be CO_E_DLLNOTFOUND? */
    }

    DllCanUnloadNow = (void *)GetProcAddress(hLibrary, "DllCanUnloadNow");
    /* Note: failing to find DllCanUnloadNow is not a failure */
    DllGetClassObject = (void *)GetProcAddress(hLibrary, "DllGetClassObject");
    if (!DllGetClassObject)
    {
        /* failure: the dll did not export DllGetClassObject */
        ERR("couldn't find function DllGetClassObject in %s\n", debugstr_w(library_name));
        FreeLibrary(hLibrary);
        return CO_E_DLLNOTFOUND;
    }

    EnterCriticalSection( &csOpenDllList );

    *ret = COMPOBJ_DllList_Get(library_name);
    if (*ret)
    {
        /* another caller to this function already added the dll while we
         * weren't in the critical section */
        FreeLibrary(hLibrary);
    }
    else
    {
        len = strlenW(library_name);
        entry = HeapAlloc(GetProcessHeap(),0, sizeof(OpenDll));
        if (entry)
            entry->library_name = HeapAlloc(GetProcessHeap(), 0, (len + 1)*sizeof(WCHAR));
        if (entry && entry->library_name)
        {
            memcpy(entry->library_name, library_name, (len + 1)*sizeof(WCHAR));
            entry->library = hLibrary;
            entry->refs = 1;
            entry->DllCanUnloadNow = DllCanUnloadNow;
            entry->DllGetClassObject = DllGetClassObject;
            list_add_tail(&openDllList, &entry->entry);
552
            *ret = entry;
553 554 555 556 557 558 559 560 561 562 563 564
        }
        else
        {
            HeapFree(GetProcessHeap(), 0, entry);
            hr = E_OUTOFMEMORY;
            FreeLibrary(hLibrary);
        }
    }

    LeaveCriticalSection( &csOpenDllList );

    return hr;
565 566
}

567 568 569
/* pass FALSE for free_entry to release a reference without destroying the
 * entry if it reaches zero or TRUE otherwise */
static void COMPOBJ_DllList_ReleaseRef(OpenDll *entry, BOOL free_entry)
570
{
571 572 573 574 575 576 577 578 579 580 581 582
    if (!InterlockedDecrement(&entry->refs) && free_entry)
    {
        EnterCriticalSection(&csOpenDllList);
        list_remove(&entry->entry);
        LeaveCriticalSection(&csOpenDllList);

        TRACE("freeing %p\n", entry->library);
        FreeLibrary(entry->library);

        HeapFree(GetProcessHeap(), 0, entry->library_name);
        HeapFree(GetProcessHeap(), 0, entry);
    }
583 584
}

585 586
/* frees memory associated with active dll list */
static void COMPOBJ_DllList_Free(void)
587
{
588 589 590
    OpenDll *entry, *cursor2;
    EnterCriticalSection(&csOpenDllList);
    LIST_FOR_EACH_ENTRY_SAFE(entry, cursor2, &openDllList, OpenDll, entry)
591
    {
592 593 594 595
        list_remove(&entry->entry);

        HeapFree(GetProcessHeap(), 0, entry->library_name);
        HeapFree(GetProcessHeap(), 0, entry);
596
    }
597
    LeaveCriticalSection(&csOpenDllList);
598
    DeleteCriticalSection(&csOpenDllList);
599 600
}

601 602 603
/******************************************************************************
 * Manage apartments.
 */
604

605
static DWORD apartment_addref(struct apartment *apt)
606 607 608 609 610 611
{
    DWORD refs = InterlockedIncrement(&apt->refs);
    TRACE("%s: before = %d\n", wine_dbgstr_longlong(apt->oxid), refs - 1);
    return refs;
}

612
/* allocates memory and fills in the necessary fields for a new apartment
613
 * object. must be called inside apartment cs */
614
static APARTMENT *apartment_construct(DWORD model)
615
{
616
    APARTMENT *apt;
617

618
    TRACE("creating new apartment, model=%d\n", model);
619

620 621
    apt = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*apt));
    apt->tid = GetCurrentThreadId();
622

623 624
    list_init(&apt->proxies);
    list_init(&apt->stubmgrs);
625
    list_init(&apt->psclsids);
626
    list_init(&apt->loaded_dlls);
627 628 629 630 631
    apt->ipidc = 0;
    apt->refs = 1;
    apt->remunk_exported = FALSE;
    apt->oidc = 1;
    InitializeCriticalSection(&apt->cs);
632
    DEBUG_SET_CRITSEC_NAME(&apt->cs, "apartment");
633

634
    apt->multi_threaded = !(model & COINIT_APARTMENTTHREADED);
635

636
    if (apt->multi_threaded)
637 638
    {
        /* FIXME: should be randomly generated by in an RPC call to rpcss */
639
        apt->oxid = ((OXID)GetCurrentProcessId() << 32) | 0xcafe;
640 641 642 643
    }
    else
    {
        /* FIXME: should be randomly generated by in an RPC call to rpcss */
644
        apt->oxid = ((OXID)GetCurrentProcessId() << 32) | GetCurrentThreadId();
645
    }
646

647
    TRACE("Created apartment on OXID %s\n", wine_dbgstr_longlong(apt->oxid));
648

649
    list_add_head(&apts, &apt->entry);
650

651 652
    return apt;
}
653

654 655 656
/* gets and existing apartment if one exists or otherwise creates an apartment
 * structure which stores OLE apartment-local information and stores a pointer
 * to it in the thread-local storage */
657
static APARTMENT *apartment_get_or_create(DWORD model)
658 659
{
    APARTMENT *apt = COM_CurrentApt();
660

661 662
    if (!apt)
    {
663 664
        if (model & COINIT_APARTMENTTHREADED)
        {
665 666
            EnterCriticalSection(&csApartment);

667
            apt = apartment_construct(model);
668 669 670 671 672 673 674 675
            if (!MainApartment)
            {
                MainApartment = apt;
                apt->main = TRUE;
                TRACE("Created main-threaded apartment with OXID %s\n", wine_dbgstr_longlong(apt->oxid));
            }

            LeaveCriticalSection(&csApartment);
676 677 678

            if (apt->main)
                apartment_createwindowifneeded(apt);
679
        }
680 681
        else
        {
682 683 684 685 686 687 688 689
            EnterCriticalSection(&csApartment);

            /* The multi-threaded apartment (MTA) contains zero or more threads interacting
             * with free threaded (ie thread safe) COM objects. There is only ever one MTA
             * in a process */
            if (MTA)
            {
                TRACE("entering the multithreaded apartment %s\n", wine_dbgstr_longlong(MTA->oxid));
690
                apartment_addref(MTA);
691 692 693
            }
            else
                MTA = apartment_construct(model);
694

695
            apt = MTA;
696

697 698
            LeaveCriticalSection(&csApartment);
        }
699
        COM_CurrentInfo()->apt = apt;
700
    }
701

702 703 704
    return apt;
}

705
static inline BOOL apartment_is_model(const APARTMENT *apt, DWORD model)
706 707 708 709
{
    return (apt->multi_threaded == !(model & COINIT_APARTMENTTHREADED));
}

710
static void COM_RevokeRegisteredClassObject(RegisteredClass *curClass)
711
{
712
    list_remove(&curClass->entry);
713

714 715
    if (curClass->runContext & CLSCTX_LOCAL_SERVER)
        RPC_StopLocalServer(curClass->RpcRegistration);
716

717 718 719
    IUnknown_Release(curClass->classObject);
    HeapFree(GetProcessHeap(), 0, curClass);
}
720

721 722 723
static void COM_RevokeAllClasses(const struct apartment *apt)
{
  RegisteredClass *curClass, *cursor;
724

725
  EnterCriticalSection( &csRegisteredClassList );
726

727 728 729 730 731
  LIST_FOR_EACH_ENTRY_SAFE(curClass, cursor, &RegisteredClassList, RegisteredClass, entry)
  {
    if (curClass->apartment_id == apt->oxid)
      COM_RevokeRegisteredClassObject(curClass);
  }
732

733 734
  LeaveCriticalSection( &csRegisteredClassList );
}
735

736 737 738 739 740
/******************************************************************************
 * Implementation of the manual reset event object. (CLSID_ManualResetEvent)
 */

typedef struct ManualResetEvent {
741 742
    ISynchronize        ISynchronize_iface;
    ISynchronizeHandle  ISynchronizeHandle_iface;
743 744 745 746 747 748 749 750 751 752 753 754
    LONG ref;
    HANDLE event;
} MREImpl;

static inline MREImpl *impl_from_ISynchronize(ISynchronize *iface)
{
    return CONTAINING_RECORD(iface, MREImpl, ISynchronize_iface);
}

static HRESULT WINAPI ISynchronize_fnQueryInterface(ISynchronize *iface, REFIID riid, void **ppv)
{
    MREImpl *This = impl_from_ISynchronize(iface);
755

756 757
    TRACE("%p (%s, %p)\n", This, debugstr_guid(riid), ppv);

758 759 760 761 762
    if(IsEqualGUID(riid, &IID_IUnknown) || IsEqualGUID(riid, &IID_ISynchronize)) {
        *ppv = &This->ISynchronize_iface;
    }else if(IsEqualGUID(riid, &IID_ISynchronizeHandle)) {
        *ppv = &This->ISynchronizeHandle_iface;
    }else {
763
        ERR("Unknown interface %s requested.\n", debugstr_guid(riid));
764 765
        *ppv = NULL;
        return E_NOINTERFACE;
766 767
    }

768 769
    IUnknown_AddRef((IUnknown*)*ppv);
    return S_OK;
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828
}

static ULONG WINAPI ISynchronize_fnAddRef(ISynchronize *iface)
{
    MREImpl *This = impl_from_ISynchronize(iface);
    LONG ref = InterlockedIncrement(&This->ref);
    TRACE("%p - ref %d\n", This, ref);

    return ref;
}

static ULONG WINAPI ISynchronize_fnRelease(ISynchronize *iface)
{
    MREImpl *This = impl_from_ISynchronize(iface);
    LONG ref = InterlockedDecrement(&This->ref);
    TRACE("%p - ref %d\n", This, ref);

    if(!ref)
    {
        CloseHandle(This->event);
        HeapFree(GetProcessHeap(), 0, This);
    }

    return ref;
}

static HRESULT WINAPI ISynchronize_fnWait(ISynchronize *iface, DWORD dwFlags, DWORD dwMilliseconds)
{
    MREImpl *This = impl_from_ISynchronize(iface);
    UINT index;
    TRACE("%p (%08x, %08x)\n", This, dwFlags, dwMilliseconds);
    return CoWaitForMultipleHandles(dwFlags, dwMilliseconds, 1, &This->event, &index);
}

static HRESULT WINAPI ISynchronize_fnSignal(ISynchronize *iface)
{
    MREImpl *This = impl_from_ISynchronize(iface);
    TRACE("%p\n", This);
    SetEvent(This->event);
    return S_OK;
}

static HRESULT WINAPI ISynchronize_fnReset(ISynchronize *iface)
{
    MREImpl *This = impl_from_ISynchronize(iface);
    TRACE("%p\n", This);
    ResetEvent(This->event);
    return S_OK;
}

static ISynchronizeVtbl vt_ISynchronize = {
    ISynchronize_fnQueryInterface,
    ISynchronize_fnAddRef,
    ISynchronize_fnRelease,
    ISynchronize_fnWait,
    ISynchronize_fnSignal,
    ISynchronize_fnReset
};

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 862 863 864 865 866
static inline MREImpl *impl_from_ISynchronizeHandle(ISynchronizeHandle *iface)
{
    return CONTAINING_RECORD(iface, MREImpl, ISynchronizeHandle_iface);
}

static HRESULT WINAPI SynchronizeHandle_QueryInterface(ISynchronizeHandle *iface, REFIID riid, void **ppv)
{
    MREImpl *This = impl_from_ISynchronizeHandle(iface);
    return ISynchronize_QueryInterface(&This->ISynchronize_iface, riid, ppv);
}

static ULONG WINAPI SynchronizeHandle_AddRef(ISynchronizeHandle *iface)
{
    MREImpl *This = impl_from_ISynchronizeHandle(iface);
    return ISynchronize_AddRef(&This->ISynchronize_iface);
}

static ULONG WINAPI SynchronizeHandle_Release(ISynchronizeHandle *iface)
{
    MREImpl *This = impl_from_ISynchronizeHandle(iface);
    return ISynchronize_Release(&This->ISynchronize_iface);
}

static HRESULT WINAPI SynchronizeHandle_GetHandle(ISynchronizeHandle *iface, HANDLE *ph)
{
    MREImpl *This = impl_from_ISynchronizeHandle(iface);

    *ph = This->event;
    return S_OK;
}

static const ISynchronizeHandleVtbl SynchronizeHandleVtbl = {
    SynchronizeHandle_QueryInterface,
    SynchronizeHandle_AddRef,
    SynchronizeHandle_Release,
    SynchronizeHandle_GetHandle
};

867 868 869 870 871 872 873 874 875 876
static HRESULT ManualResetEvent_Construct(IUnknown *punkouter, REFIID iid, void **ppv)
{
    MREImpl *This = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(MREImpl));
    HRESULT hr;

    if(punkouter)
        FIXME("Aggregation not implemented.\n");

    This->ref = 1;
    This->ISynchronize_iface.lpVtbl = &vt_ISynchronize;
877
    This->ISynchronizeHandle_iface.lpVtbl = &SynchronizeHandleVtbl;
878 879 880 881 882 883 884
    This->event = CreateEventW(NULL, TRUE, FALSE, NULL);

    hr = ISynchronize_QueryInterface(&This->ISynchronize_iface, iid, ppv);
    ISynchronize_Release(&This->ISynchronize_iface);
    return hr;
}

885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 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 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
static inline LocalServer *impl_from_IServiceProvider(IServiceProvider *iface)
{
    return CONTAINING_RECORD(iface, LocalServer, IServiceProvider_iface);
}

static HRESULT WINAPI LocalServer_QueryInterface(IServiceProvider *iface, REFIID riid, void **ppv)
{
    LocalServer *This = impl_from_IServiceProvider(iface);

    TRACE("(%p)->(%s %p)\n", This, debugstr_guid(riid), ppv);

    if(IsEqualGUID(riid, &IID_IUnknown) || IsEqualGUID(riid, &IID_IServiceProvider)) {
        *ppv = &This->IServiceProvider_iface;
    }else {
        *ppv = NULL;
        return E_NOINTERFACE;
    }

    IUnknown_AddRef((IUnknown*)*ppv);
    return S_OK;
}

static ULONG WINAPI LocalServer_AddRef(IServiceProvider *iface)
{
    LocalServer *This = impl_from_IServiceProvider(iface);
    LONG ref = InterlockedIncrement(&This->ref);

    TRACE("(%p) ref=%d\n", This, ref);

    return ref;
}

static ULONG WINAPI LocalServer_Release(IServiceProvider *iface)
{
    LocalServer *This = impl_from_IServiceProvider(iface);
    LONG ref = InterlockedDecrement(&This->ref);

    TRACE("(%p) ref=%d\n", This, ref);

    if(!ref) {
        assert(!This->apt);
        HeapFree(GetProcessHeap(), 0, This);
    }

    return ref;
}

static HRESULT WINAPI LocalServer_QueryService(IServiceProvider *iface, REFGUID guid, REFIID riid, void **ppv)
{
    LocalServer *This = impl_from_IServiceProvider(iface);
    APARTMENT *apt = COM_CurrentApt();
    RegisteredClass *iter;
    HRESULT hres = E_FAIL;

    TRACE("(%p)->(%s %s %p)\n", This, debugstr_guid(guid), debugstr_guid(riid), ppv);

    if(!This->apt)
        return E_UNEXPECTED;

    EnterCriticalSection(&csRegisteredClassList);

    LIST_FOR_EACH_ENTRY(iter, &RegisteredClassList, RegisteredClass, entry) {
        if(iter->apartment_id == apt->oxid
           && (iter->runContext & CLSCTX_LOCAL_SERVER)
           && IsEqualGUID(&iter->classIdentifier, guid)) {
            hres = IUnknown_QueryInterface(iter->classObject, riid, ppv);
            break;
        }
    }

    LeaveCriticalSection( &csRegisteredClassList );

    return hres;
}

static const IServiceProviderVtbl LocalServerVtbl = {
    LocalServer_QueryInterface,
    LocalServer_AddRef,
    LocalServer_Release,
    LocalServer_QueryService
};

static HRESULT get_local_server_stream(APARTMENT *apt, IStream **ret)
{
    HRESULT hres = S_OK;

    EnterCriticalSection(&apt->cs);

    if(!apt->local_server) {
        LocalServer *obj;

        obj = heap_alloc(sizeof(*obj));
        if(obj) {
            obj->IServiceProvider_iface.lpVtbl = &LocalServerVtbl;
            obj->ref = 1;
            obj->apt = apt;

            hres = CreateStreamOnHGlobal(0, TRUE, &obj->marshal_stream);
            if(SUCCEEDED(hres)) {
                hres = CoMarshalInterface(obj->marshal_stream, &IID_IServiceProvider, (IUnknown*)&obj->IServiceProvider_iface,
                        MSHCTX_LOCAL, NULL, MSHLFLAGS_TABLESTRONG);
                if(FAILED(hres))
                    IStream_Release(obj->marshal_stream);
            }

            if(SUCCEEDED(hres))
                apt->local_server = obj;
            else
                heap_free(obj);
        }else {
            hres = E_OUTOFMEMORY;
        }
    }

    if(SUCCEEDED(hres))
        hres = IStream_Clone(apt->local_server->marshal_stream, ret);

    LeaveCriticalSection(&apt->cs);

    if(FAILED(hres))
        ERR("Failed: %08x\n", hres);
    return hres;
}

1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
/***********************************************************************
 *           CoRevokeClassObject [OLE32.@]
 *
 * Removes a class object from the class registry.
 *
 * PARAMS
 *  dwRegister [I] Cookie returned from CoRegisterClassObject().
 *
 * RETURNS
 *  Success: S_OK.
 *  Failure: HRESULT code.
 *
 * NOTES
 *  Must be called from the same apartment that called CoRegisterClassObject(),
 *  otherwise it will fail with RPC_E_WRONG_THREAD.
 *
 * SEE ALSO
 *  CoRegisterClassObject
 */
1028
HRESULT WINAPI DECLSPEC_HOTPATCH CoRevokeClassObject(
1029 1030 1031 1032 1033
        DWORD dwRegister)
{
  HRESULT hr = E_INVALIDARG;
  RegisteredClass *curClass;
  APARTMENT *apt;
1034

1035
  TRACE("(%08x)\n",dwRegister);
1036

1037 1038 1039 1040 1041 1042
  apt = COM_CurrentApt();
  if (!apt)
  {
    ERR("COM was not initialized\n");
    return CO_E_NOTINITIALIZED;
  }
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 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
  EnterCriticalSection( &csRegisteredClassList );

  LIST_FOR_EACH_ENTRY(curClass, &RegisteredClassList, RegisteredClass, entry)
  {
    /*
     * Check if we have a match on the cookie.
     */
    if (curClass->dwCookie == dwRegister)
    {
      if (curClass->apartment_id == apt->oxid)
      {
          COM_RevokeRegisteredClassObject(curClass);
          hr = S_OK;
      }
      else
      {
          ERR("called from wrong apartment, should be called from %s\n",
              wine_dbgstr_longlong(curClass->apartment_id));
          hr = RPC_E_WRONG_THREAD;
      }
      break;
    }
  }

  LeaveCriticalSection( &csRegisteredClassList );

  return hr;
}

/* frees unused libraries loaded by apartment_getclassobject by calling the
 * DLL's DllCanUnloadNow entry point */
static void apartment_freeunusedlibraries(struct apartment *apt, DWORD delay)
{
    struct apartment_loaded_dll *entry, *next;
    EnterCriticalSection(&apt->cs);
    LIST_FOR_EACH_ENTRY_SAFE(entry, next, &apt->loaded_dlls, struct apartment_loaded_dll, entry)
    {
	if (entry->dll->DllCanUnloadNow && (entry->dll->DllCanUnloadNow() == S_OK))
        {
            DWORD real_delay = delay;

            if (real_delay == INFINITE)
            {
                /* DLLs that return multi-threaded objects aren't unloaded
                 * straight away to cope for programs that have races between
                 * last object destruction and threads in the DLLs that haven't
                 * finished, despite DllCanUnloadNow returning S_OK */
                if (entry->multi_threaded)
                    real_delay = 10 * 60 * 1000; /* 10 minutes */
                else
                    real_delay = 0;
            }

1097
            if (!real_delay || (entry->unload_time && ((int)(GetTickCount() - entry->unload_time) > 0)))
1098 1099 1100 1101 1102 1103
            {
                list_remove(&entry->entry);
                COMPOBJ_DllList_ReleaseRef(entry->dll, TRUE);
                HeapFree(GetProcessHeap(), 0, entry);
            }
            else
1104
            {
1105
                entry->unload_time = GetTickCount() + real_delay;
1106 1107
                if (!entry->unload_time) entry->unload_time = 1;
            }
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
        }
        else if (entry->unload_time)
            entry->unload_time = 0;
    }
    LeaveCriticalSection(&apt->cs);
}

DWORD apartment_release(struct apartment *apt)
{
    DWORD ret;

    EnterCriticalSection(&csApartment);

    ret = InterlockedDecrement(&apt->refs);
    TRACE("%s: after = %d\n", wine_dbgstr_longlong(apt->oxid), ret);
    /* destruction stuff that needs to happen under csApartment CS */
    if (ret == 0)
    {
        if (apt == MTA) MTA = NULL;
        else if (apt == MainApartment) MainApartment = NULL;
        list_remove(&apt->entry);
    }

    LeaveCriticalSection(&csApartment);

    if (ret == 0)
    {
        struct list *cursor, *cursor2;

        TRACE("destroying apartment %p, oxid %s\n", apt, wine_dbgstr_longlong(apt->oxid));

1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
        if(apt->local_server) {
            LocalServer *local_server = apt->local_server;
            LARGE_INTEGER zero;

            memset(&zero, 0, sizeof(zero));
            IStream_Seek(local_server->marshal_stream, zero, STREAM_SEEK_SET, NULL);
            CoReleaseMarshalData(local_server->marshal_stream);
            IStream_Release(local_server->marshal_stream);
            local_server->marshal_stream = NULL;

            apt->local_server = NULL;
            local_server->apt = NULL;
            IServiceProvider_Release(&local_server->IServiceProvider_iface);
        }

1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
        /* Release the references to the registered class objects */
        COM_RevokeAllClasses(apt);

        /* no locking is needed for this apartment, because no other thread
         * can access it at this point */

        apartment_disconnectproxies(apt);

        if (apt->win) DestroyWindow(apt->win);
        if (apt->host_apt_tid) PostThreadMessageW(apt->host_apt_tid, WM_QUIT, 0, 0);

        LIST_FOR_EACH_SAFE(cursor, cursor2, &apt->stubmgrs)
        {
            struct stub_manager *stubmgr = LIST_ENTRY(cursor, struct stub_manager, entry);
            /* release the implicit reference given by the fact that the
             * stub has external references (it must do since it is in the
             * stub manager list in the apartment and all non-apartment users
             * must have a ref on the apartment and so it cannot be destroyed).
             */
            stub_manager_int_release(stubmgr);
        }

        LIST_FOR_EACH_SAFE(cursor, cursor2, &apt->psclsids)
        {
            struct registered_psclsid *registered_psclsid =
                LIST_ENTRY(cursor, struct registered_psclsid, entry);
1180 1181

            list_remove(&registered_psclsid->entry);
1182
            HeapFree(GetProcessHeap(), 0, registered_psclsid);
1183 1184
        }

1185 1186 1187 1188 1189
        /* if this assert fires, then another thread took a reference to a
         * stub manager without taking a reference to the containing
         * apartment, which it must do. */
        assert(list_empty(&apt->stubmgrs));

1190
        if (apt->filter) IMessageFilter_Release(apt->filter);
1191

1192
        /* free as many unused libraries as possible... */
1193
        apartment_freeunusedlibraries(apt, 0);
1194 1195 1196 1197

        /* ... and free the memory for the apartment loaded dll entry and
         * release the dll list reference without freeing the library for the
         * rest */
1198 1199 1200
        while ((cursor = list_head(&apt->loaded_dlls)))
        {
            struct apartment_loaded_dll *apartment_loaded_dll = LIST_ENTRY(cursor, struct apartment_loaded_dll, entry);
1201
            COMPOBJ_DllList_ReleaseRef(apartment_loaded_dll->dll, FALSE);
1202 1203 1204 1205
            list_remove(cursor);
            HeapFree(GetProcessHeap(), 0, apartment_loaded_dll);
        }

1206
        DEBUG_CLEAR_CRITSEC_NAME(&apt->cs);
1207
        DeleteCriticalSection(&apt->cs);
1208

1209
        HeapFree(GetProcessHeap(), 0, apt);
1210 1211
    }

1212 1213 1214
    return ret;
}

1215
/* The given OXID must be local to this process: 
1216 1217 1218 1219
 *
 * The ref parameter is here mostly to ensure people remember that
 * they get one, you should normally take a ref for thread safety.
 */
1220
APARTMENT *apartment_findfromoxid(OXID oxid, BOOL ref)
1221
{
1222 1223
    APARTMENT *result = NULL;
    struct list *cursor;
1224 1225

    EnterCriticalSection(&csApartment);
1226 1227 1228 1229 1230 1231
    LIST_FOR_EACH( cursor, &apts )
    {
        struct apartment *apt = LIST_ENTRY( cursor, struct apartment, entry );
        if (apt->oxid == oxid)
        {
            result = apt;
1232
            if (ref) apartment_addref(result);
1233 1234 1235
            break;
        }
    }
1236
    LeaveCriticalSection(&csApartment);
1237

1238
    return result;
1239 1240
}

1241 1242 1243
/* gets the apartment which has a given creator thread ID. The caller must
 * release the reference from the apartment as soon as the apartment pointer
 * is no longer required. */
1244
APARTMENT *apartment_findfromtid(DWORD tid)
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
{
    APARTMENT *result = NULL;
    struct list *cursor;

    EnterCriticalSection(&csApartment);
    LIST_FOR_EACH( cursor, &apts )
    {
        struct apartment *apt = LIST_ENTRY( cursor, struct apartment, entry );
        if (apt->tid == tid)
        {
            result = apt;
1256
            apartment_addref(result);
1257 1258 1259 1260 1261 1262 1263 1264
            break;
        }
    }
    LeaveCriticalSection(&csApartment);

    return result;
}

1265
/* gets the main apartment if it exists. The caller must
1266 1267
 * release the reference from the apartment as soon as the apartment pointer
 * is no longer required. */
1268
static APARTMENT *apartment_findmain(void)
1269
{
1270
    APARTMENT *result;
1271 1272

    EnterCriticalSection(&csApartment);
1273

1274 1275
    result = MainApartment;
    if (result) apartment_addref(result);
1276

1277 1278 1279 1280 1281
    LeaveCriticalSection(&csApartment);

    return result;
}

1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306
/* gets the multi-threaded apartment if it exists. The caller must
 * release the reference from the apartment as soon as the apartment pointer
 * is no longer required. */
static APARTMENT *apartment_find_multi_threaded(void)
{
    APARTMENT *result = NULL;
    struct list *cursor;

    EnterCriticalSection(&csApartment);

    LIST_FOR_EACH( cursor, &apts )
    {
        struct apartment *apt = LIST_ENTRY( cursor, struct apartment, entry );
        if (apt->multi_threaded)
        {
            result = apt;
            apartment_addref(result);
            break;
        }
    }

    LeaveCriticalSection(&csApartment);
    return result;
}

1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
/* gets the specified class object by loading the appropriate DLL, if
 * necessary and calls the DllGetClassObject function for the DLL */
static HRESULT apartment_getclassobject(struct apartment *apt, LPCWSTR dllpath,
                                        BOOL apartment_threaded,
                                        REFCLSID rclsid, REFIID riid, void **ppv)
{
    static const WCHAR wszOle32[] = {'o','l','e','3','2','.','d','l','l',0};
    HRESULT hr = S_OK;
    BOOL found = FALSE;
    struct apartment_loaded_dll *apartment_loaded_dll;

    if (!strcmpiW(dllpath, wszOle32))
    {
        /* we don't need to control the lifetime of this dll, so use the local
         * implementation of DllGetClassObject directly */
        TRACE("calling ole32!DllGetClassObject\n");
        hr = DllGetClassObject(rclsid, riid, ppv);

        if (hr != S_OK)
            ERR("DllGetClassObject returned error 0x%08x\n", hr);

        return hr;
    }

    EnterCriticalSection(&apt->cs);

    LIST_FOR_EACH_ENTRY(apartment_loaded_dll, &apt->loaded_dlls, struct apartment_loaded_dll, entry)
        if (!strcmpiW(dllpath, apartment_loaded_dll->dll->library_name))
        {
            TRACE("found %s already loaded\n", debugstr_w(dllpath));
            found = TRUE;
            break;
        }

    if (!found)
    {
        apartment_loaded_dll = HeapAlloc(GetProcessHeap(), 0, sizeof(*apartment_loaded_dll));
        if (!apartment_loaded_dll)
            hr = E_OUTOFMEMORY;
        if (SUCCEEDED(hr))
        {
            apartment_loaded_dll->unload_time = 0;
            apartment_loaded_dll->multi_threaded = FALSE;
            hr = COMPOBJ_DllList_Add( dllpath, &apartment_loaded_dll->dll );
            if (FAILED(hr))
                HeapFree(GetProcessHeap(), 0, apartment_loaded_dll);
        }
        if (SUCCEEDED(hr))
        {
            TRACE("added new loaded dll %s\n", debugstr_w(dllpath));
            list_add_tail(&apt->loaded_dlls, &apartment_loaded_dll->entry);
        }
    }

    LeaveCriticalSection(&apt->cs);

    if (SUCCEEDED(hr))
    {
        /* one component being multi-threaded overrides any number of
         * apartment-threaded components */
        if (!apartment_threaded)
            apartment_loaded_dll->multi_threaded = TRUE;

        TRACE("calling DllGetClassObject %p\n", apartment_loaded_dll->dll->DllGetClassObject);
        /* OK: get the ClassObject */
        hr = apartment_loaded_dll->dll->DllGetClassObject(rclsid, riid, ppv);

        if (hr != S_OK)
            ERR("DllGetClassObject returned error 0x%08x\n", hr);
    }

    return hr;
}

/***********************************************************************
 *	COM_RegReadPath	[internal]
 *
 *	Reads a registry value and expands it when necessary
 */
1386
static DWORD COM_RegReadPath(const struct class_reg_data *regdata, WCHAR *dst, DWORD dstlen)
1387
{
1388 1389 1390 1391
    DWORD ret;

    if (regdata->hkey)
    {
1392 1393 1394 1395
	DWORD keytype;
	WCHAR src[MAX_PATH];
	DWORD dwLength = dstlen * sizeof(WCHAR);

1396
        if( (ret = RegQueryValueExW(regdata->u.hkey, NULL, NULL, &keytype, (BYTE*)src, &dwLength)) == ERROR_SUCCESS ) {
1397 1398 1399
            if (keytype == REG_EXPAND_SZ) {
              if (dstlen <= ExpandEnvironmentStringsW(src, dst, dstlen)) ret = ERROR_MORE_DATA;
            } else {
1400 1401 1402 1403 1404 1405 1406 1407 1408 1409
              const WCHAR *quote_start;
              quote_start = strchrW(src, '\"');
              if (quote_start) {
                const WCHAR *quote_end = strchrW(quote_start + 1, '\"');
                if (quote_end) {
                  memmove(src, quote_start + 1,
                          (quote_end - quote_start - 1) * sizeof(WCHAR));
                  src[quote_end - quote_start - 1] = '\0';
                }
              }
1410 1411
              lstrcpynW(dst, src, dstlen);
            }
1412
        }
1413
	return ret;
1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426
    }
    else
    {
        ULONG_PTR cookie;
        WCHAR *nameW;

        *dst = 0;
        nameW = (WCHAR*)((BYTE*)regdata->u.actctx.section + regdata->u.actctx.data->name_offset);
        ActivateActCtx(regdata->u.actctx.hactctx, &cookie);
        ret = SearchPathW(NULL, nameW, NULL, dstlen, dst, NULL);
        DeactivateActCtx(0, cookie);
        return !*dst;
    }
1427 1428
}

1429 1430
struct host_object_params
{
1431
    struct class_reg_data regdata;
1432 1433
    CLSID clsid; /* clsid of object to marshal */
    IID iid; /* interface to marshal */
1434 1435
    HANDLE event; /* event signalling when ready for multi-threaded case */
    HRESULT hr; /* result for multi-threaded case */
1436
    IStream *stream; /* stream that the object will be marshaled into */
1437
    BOOL apartment_threaded; /* is the component purely apartment-threaded? */
1438 1439
};

1440 1441
static HRESULT apartment_hostobject(struct apartment *apt,
                                    const struct host_object_params *params)
1442 1443 1444 1445
{
    IUnknown *object;
    HRESULT hr;
    static const LARGE_INTEGER llZero;
1446
    WCHAR dllpath[MAX_PATH+1];
1447

1448
    TRACE("clsid %s, iid %s\n", debugstr_guid(&params->clsid), debugstr_guid(&params->iid));
1449

1450
    if (COM_RegReadPath(&params->regdata, dllpath, ARRAYSIZE(dllpath)) != ERROR_SUCCESS)
1451 1452 1453 1454 1455 1456
    {
        /* failure: CLSID is not found in registry */
        WARN("class %s not registered inproc\n", debugstr_guid(&params->clsid));
        return REGDB_E_CLASSNOTREG;
    }

1457 1458
    hr = apartment_getclassobject(apt, dllpath, params->apartment_threaded,
                                  &params->clsid, &params->iid, (void **)&object);
1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469
    if (FAILED(hr))
        return hr;

    hr = CoMarshalInterface(params->stream, &params->iid, object, MSHCTX_INPROC, NULL, MSHLFLAGS_NORMAL);
    if (FAILED(hr))
        IUnknown_Release(object);
    IStream_Seek(params->stream, llZero, STREAM_SEEK_SET, NULL);

    return hr;
}

1470
static LRESULT CALLBACK apartment_wndproc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
1471
{
1472 1473 1474
    switch (msg)
    {
    case DM_EXECUTERPC:
1475 1476
        RPC_ExecuteCall((struct dispatch_params *)lParam);
        return 0;
1477
    case DM_HOSTOBJECT:
1478
        return apartment_hostobject(COM_CurrentApt(), (const struct host_object_params *)lParam);
1479 1480 1481
    default:
        return DefWindowProcW(hWnd, msg, wParam, lParam);
    }
1482
}
1483

1484 1485 1486 1487 1488 1489 1490
struct host_thread_params
{
    COINIT threading_model;
    HANDLE ready_event;
    HWND apartment_hwnd;
};

1491 1492
/* thread for hosting an object to allow an object to appear to be created in
 * an apartment with an incompatible threading model */
1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523
static DWORD CALLBACK apartment_hostobject_thread(LPVOID p)
{
    struct host_thread_params *params = p;
    MSG msg;
    HRESULT hr;
    struct apartment *apt;

    TRACE("\n");

    hr = CoInitializeEx(NULL, params->threading_model);
    if (FAILED(hr)) return hr;

    apt = COM_CurrentApt();
    if (params->threading_model == COINIT_APARTMENTTHREADED)
    {
        apartment_createwindowifneeded(apt);
        params->apartment_hwnd = apartment_getwindow(apt);
    }
    else
        params->apartment_hwnd = NULL;

    /* force the message queue to be created before signaling parent thread */
    PeekMessageW(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);

    SetEvent(params->ready_event);
    params = NULL; /* can't touch params after here as it may be invalid */

    while (GetMessageW(&msg, NULL, 0, 0))
    {
        if (!msg.hwnd && (msg.message == DM_HOSTOBJECT))
        {
1524 1525 1526
            struct host_object_params *obj_params = (struct host_object_params *)msg.lParam;
            obj_params->hr = apartment_hostobject(apt, obj_params);
            SetEvent(obj_params->event);
1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541
        }
        else
        {
            TranslateMessage(&msg);
            DispatchMessageW(&msg);
        }
    }

    TRACE("exiting\n");

    CoUninitialize();

    return S_OK;
}

1542 1543 1544 1545 1546
/* finds or creates a host apartment, creates the object inside it and returns
 * a proxy to it so that the object can be used in the apartment of the
 * caller of this function */
static HRESULT apartment_hostobject_in_hostapt(
    struct apartment *apt, BOOL multi_threaded, BOOL main_apartment,
1547
    const struct class_reg_data *regdata, REFCLSID rclsid, REFIID riid, void **ppv)
1548 1549 1550 1551 1552 1553 1554 1555
{
    struct host_object_params params;
    HWND apartment_hwnd = NULL;
    DWORD apartment_tid = 0;
    HRESULT hr;

    if (!multi_threaded && main_apartment)
    {
1556
        APARTMENT *host_apt = apartment_findmain();
1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608
        if (host_apt)
        {
            apartment_hwnd = apartment_getwindow(host_apt);
            apartment_release(host_apt);
        }
    }

    if (!apartment_hwnd)
    {
        EnterCriticalSection(&apt->cs);

        if (!apt->host_apt_tid)
        {
            struct host_thread_params thread_params;
            HANDLE handles[2];
            DWORD wait_value;

            thread_params.threading_model = multi_threaded ? COINIT_MULTITHREADED : COINIT_APARTMENTTHREADED;
            handles[0] = thread_params.ready_event = CreateEventW(NULL, FALSE, FALSE, NULL);
            thread_params.apartment_hwnd = NULL;
            handles[1] = CreateThread(NULL, 0, apartment_hostobject_thread, &thread_params, 0, &apt->host_apt_tid);
            if (!handles[1])
            {
                CloseHandle(handles[0]);
                LeaveCriticalSection(&apt->cs);
                return E_OUTOFMEMORY;
            }
            wait_value = WaitForMultipleObjects(2, handles, FALSE, INFINITE);
            CloseHandle(handles[0]);
            CloseHandle(handles[1]);
            if (wait_value == WAIT_OBJECT_0)
                apt->host_apt_hwnd = thread_params.apartment_hwnd;
            else
            {
                LeaveCriticalSection(&apt->cs);
                return E_OUTOFMEMORY;
            }
        }

        if (multi_threaded || !main_apartment)
        {
            apartment_hwnd = apt->host_apt_hwnd;
            apartment_tid = apt->host_apt_tid;
        }

        LeaveCriticalSection(&apt->cs);
    }

    /* another thread may have become the main apartment in the time it took
     * us to create the thread for the host apartment */
    if (!apartment_hwnd && !multi_threaded && main_apartment)
    {
1609
        APARTMENT *host_apt = apartment_findmain();
1610 1611 1612 1613 1614 1615 1616
        if (host_apt)
        {
            apartment_hwnd = apartment_getwindow(host_apt);
            apartment_release(host_apt);
        }
    }

1617
    params.regdata = *regdata;
1618 1619 1620 1621 1622
    params.clsid = *rclsid;
    params.iid = *riid;
    hr = CreateStreamOnHGlobal(NULL, TRUE, &params.stream);
    if (FAILED(hr))
        return hr;
1623
    params.apartment_threaded = !multi_threaded;
1624 1625 1626 1627 1628 1629 1630
    if (multi_threaded)
    {
        params.hr = S_OK;
        params.event = CreateEventW(NULL, FALSE, FALSE, NULL);
        if (!PostThreadMessageW(apartment_tid, DM_HOSTOBJECT, 0, (LPARAM)&params))
            hr = E_OUTOFMEMORY;
        else
1631 1632 1633 1634 1635
        {
            WaitForSingleObject(params.event, INFINITE);
            hr = params.hr;
        }
        CloseHandle(params.event);
1636 1637
    }
    else
1638
    {
1639
        if (!apartment_hwnd)
1640
        {
1641
            ERR("host apartment didn't create window\n");
1642
            hr = E_OUTOFMEMORY;
1643
        }
1644 1645
        else
            hr = SendMessageW(apartment_hwnd, DM_HOSTOBJECT, 0, (LPARAM)&params);
1646
    }
1647 1648 1649
    if (SUCCEEDED(hr))
        hr = CoUnmarshalInterface(params.stream, riid, ppv);
    IStream_Release(params.stream);
1650 1651 1652
    return hr;
}

1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673
static BOOL WINAPI register_class( INIT_ONCE *once, void *param, void **context )
{
    WNDCLASSW wclass;

    /* Dispatching to the correct thread in an apartment is done through
     * window messages rather than RPC transports. When an interface is
     * marshalled into another apartment in the same process, a window of the
     * following class is created. The *caller* of CoMarshalInterface (i.e., the
     * application) is responsible for pumping the message loop in that thread.
     * The WM_USER messages which point to the RPCs are then dispatched to
     * apartment_wndproc by the user's code from the apartment in which the
     * interface was unmarshalled.
     */
    memset(&wclass, 0, sizeof(wclass));
    wclass.lpfnWndProc = apartment_wndproc;
    wclass.hInstance = hProxyDll;
    wclass.lpszClassName = wszAptWinClass;
    RegisterClassW(&wclass);
    return TRUE;
}

1674 1675 1676
/* create a window for the apartment or return the current one if one has
 * already been created */
HRESULT apartment_createwindowifneeded(struct apartment *apt)
1677
{
1678 1679
    static INIT_ONCE class_init_once = INIT_ONCE_STATIC_INIT;

1680 1681 1682 1683
    if (apt->multi_threaded)
        return S_OK;

    if (!apt->win)
1684
    {
1685 1686 1687 1688 1689 1690
        HWND hwnd;

        InitOnceExecuteOnce( &class_init_once, register_class, NULL, NULL );

        hwnd = CreateWindowW(wszAptWinClass, NULL, 0, 0, 0, 0, 0,
                             HWND_MESSAGE, 0, hProxyDll, NULL);
1691
        if (!hwnd)
1692
        {
1693 1694
            ERR("CreateWindow failed with error %d\n", GetLastError());
            return HRESULT_FROM_WIN32(GetLastError());
1695
        }
1696 1697 1698
        if (InterlockedCompareExchangePointer((PVOID *)&apt->win, hwnd, NULL))
            /* someone beat us to it */
            DestroyWindow(hwnd);
1699
    }
1700 1701

    return S_OK;
1702 1703
}

1704 1705
/* retrieves the window for the main- or apartment-threaded apartment */
HWND apartment_getwindow(const struct apartment *apt)
1706
{
1707 1708 1709
    assert(!apt->multi_threaded);
    return apt->win;
}
1710

1711 1712 1713 1714 1715
void apartment_joinmta(void)
{
    apartment_addref(MTA);
    COM_CurrentInfo()->apt = MTA;
}
1716

1717 1718 1719 1720 1721 1722 1723 1724
static void COM_TlsDestroy(void)
{
    struct oletls *info = NtCurrentTeb()->ReservedForOle;
    if (info)
    {
        if (info->apt) apartment_release(info->apt);
        if (info->errorinfo) IErrorInfo_Release(info->errorinfo);
        if (info->state) IUnknown_Release(info->state);
1725
        if (info->spy) IInitializeSpy_Release(info->spy);
1726 1727 1728
        if (info->context_token) IObjContext_Release(info->context_token);
        HeapFree(GetProcessHeap(), 0, info);
        NtCurrentTeb()->ReservedForOle = NULL;
1729 1730 1731
    }
}

1732
/******************************************************************************
1733
 *           CoBuildVersion [OLE32.@]
1734 1735 1736 1737
 *
 * Gets the build version of the DLL.
 *
 * PARAMS
1738 1739 1740
 *
 * RETURNS
 *	Current build version, hiword is majornumber, loword is minornumber
Alexandre Julliard's avatar
Alexandre Julliard committed
1741
 */
1742 1743 1744 1745
DWORD WINAPI CoBuildVersion(void)
{
    TRACE("Returning version %d, build %d.\n", rmm, rup);
    return (rmm<<16)+rup;
Alexandre Julliard's avatar
Alexandre Julliard committed
1746 1747
}

1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783
/******************************************************************************
 *              CoRegisterInitializeSpy [OLE32.@]
 *
 * Add a Spy that watches CoInitializeEx calls
 *
 * PARAMS
 *  spy [I] Pointer to IUnknown interface that will be QueryInterface'd.
 *  cookie [II] cookie receiver
 *
 * RETURNS
 *  Success: S_OK if not already initialized, S_FALSE otherwise.
 *  Failure: HRESULT code.
 *
 * SEE ALSO
 *   CoInitializeEx
 */
HRESULT WINAPI CoRegisterInitializeSpy(IInitializeSpy *spy, ULARGE_INTEGER *cookie)
{
    struct oletls *info = COM_CurrentInfo();
    HRESULT hr;

    TRACE("(%p, %p)\n", spy, cookie);

    if (!spy || !cookie || !info)
    {
        if (!info)
            WARN("Could not allocate tls\n");
        return E_INVALIDARG;
    }

    if (info->spy)
    {
        FIXME("Already registered?\n");
        return E_UNEXPECTED;
    }

1784
    hr = IInitializeSpy_QueryInterface(spy, &IID_IInitializeSpy, (void **) &info->spy);
1785 1786 1787 1788 1789 1790 1791 1792
    if (SUCCEEDED(hr))
    {
        cookie->QuadPart = (DWORD_PTR)spy;
        return S_OK;
    }
    return hr;
}

1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807
/******************************************************************************
 *              CoRevokeInitializeSpy [OLE32.@]
 *
 * Remove a spy that previously watched CoInitializeEx calls
 *
 * PARAMS
 *  cookie [I] The cookie obtained from a previous CoRegisterInitializeSpy call
 *
 * RETURNS
 *  Success: S_OK if a spy is removed
 *  Failure: E_INVALIDARG
 *
 * SEE ALSO
 *   CoInitializeEx
 */
1808 1809 1810 1811 1812 1813 1814 1815
HRESULT WINAPI CoRevokeInitializeSpy(ULARGE_INTEGER cookie)
{
    struct oletls *info = COM_CurrentInfo();
    TRACE("(%s)\n", wine_dbgstr_longlong(cookie.QuadPart));

    if (!info || !info->spy || cookie.QuadPart != (DWORD_PTR)info->spy)
        return E_INVALIDARG;

1816
    IInitializeSpy_Release(info->spy);
1817
    info->spy = NULL;
1818 1819 1820 1821
    return S_OK;
}


1822
/******************************************************************************
1823
 *		CoInitialize	[OLE32.@]
1824
 *
1825 1826
 * Initializes the COM libraries by calling CoInitializeEx with
 * COINIT_APARTMENTTHREADED, ie it enters a STA thread.
1827
 *
1828 1829 1830 1831 1832 1833 1834
 * PARAMS
 *  lpReserved [I] Pointer to IMalloc interface (obsolete, should be NULL).
 *
 * RETURNS
 *  Success: S_OK if not already initialized, S_FALSE otherwise.
 *  Failure: HRESULT code.
 *
1835 1836
 * SEE ALSO
 *   CoInitializeEx
Alexandre Julliard's avatar
Alexandre Julliard committed
1837
 */
1838
HRESULT WINAPI CoInitialize(LPVOID lpReserved)
1839 1840 1841 1842
{
  /*
   * Just delegate to the newer method.
   */
1843
  return CoInitializeEx(lpReserved, COINIT_APARTMENTTHREADED);
Alexandre Julliard's avatar
Alexandre Julliard committed
1844 1845
}

1846
/******************************************************************************
1847
 *		CoInitializeEx	[OLE32.@]
1848
 *
1849
 * Initializes the COM libraries.
1850
 *
1851 1852 1853
 * PARAMS
 *  lpReserved [I] Pointer to IMalloc interface (obsolete, should be NULL).
 *  dwCoInit   [I] One or more flags from the COINIT enumeration. See notes.
1854 1855
 *
 * RETURNS
1856 1857
 *  S_OK               if successful,
 *  S_FALSE            if this function was called already.
1858 1859
 *  RPC_E_CHANGED_MODE if a previous call to CoInitializeEx specified another
 *                     threading model.
1860
 *
1861 1862 1863 1864
 * NOTES
 *
 * The behavior used to set the IMalloc used for memory management is
 * obsolete.
1865
 * The dwCoInit parameter must specify one of the following apartment
1866 1867 1868 1869 1870 1871 1872
 * threading models:
 *| COINIT_APARTMENTTHREADED - A single-threaded apartment (STA).
 *| COINIT_MULTITHREADED - A multi-threaded apartment (MTA).
 * The parameter may also specify zero or more of the following flags:
 *| COINIT_DISABLE_OLE1DDE - Don't use DDE for OLE1 support.
 *| COINIT_SPEED_OVER_MEMORY - Trade memory for speed.
 *
1873 1874
 * SEE ALSO
 *   CoUninitialize
1875
 */
1876
HRESULT WINAPI DECLSPEC_HOTPATCH CoInitializeEx(LPVOID lpReserved, DWORD dwCoInit)
1877
{
1878
  struct oletls *info = COM_CurrentInfo();
1879 1880
  HRESULT hr = S_OK;
  APARTMENT *apt;
1881

1882
  TRACE("(%p, %x)\n", lpReserved, (int)dwCoInit);
1883 1884 1885

  if (lpReserved!=NULL)
  {
1886
    ERR("(%p, %x) - Bad parameter passed-in %p, must be an old Windows Application\n", lpReserved, (int)dwCoInit, lpReserved);
1887 1888 1889 1890 1891
  }

  /*
   * Check the lock count. If this is the first time going through the initialize
   * process, we have to initialize the libraries.
1892 1893
   *
   * And crank-up that lock count.
1894
   */
1895
  if (InterlockedExchangeAdd(&s_COMLockCount,1)==0)
1896 1897 1898 1899
  {
    /*
     * Initialize the various COM libraries and data structures.
     */
1900
    TRACE("() - Initializing the COM libraries\n");
1901

1902
    /* we may need to defer this until after apartment initialisation */
Noomen Hamza's avatar
Noomen Hamza committed
1903
    RunningObjectTableImpl_Initialize();
1904
  }
1905

1906 1907 1908 1909
  if (info->spy)
      IInitializeSpy_PreInitialize(info->spy, dwCoInit, info->inits);

  if (!(apt = info->apt))
1910
  {
1911
    apt = apartment_get_or_create(dwCoInit);
1912
    if (!apt) return E_OUTOFMEMORY;
1913
  }
1914
  else if (!apartment_is_model(apt, dwCoInit))
1915 1916 1917
  {
    /* Changing the threading model after it's been set is illegal. If this warning is triggered by Wine
       code then we are probably using the wrong threading model to implement that API. */
1918 1919 1920
    ERR("Attempt to change threading model of this apartment from %s to %s\n",
        apt->multi_threaded ? "multi-threaded" : "apartment threaded",
        dwCoInit & COINIT_APARTMENTTHREADED ? "apartment threaded" : "multi-threaded");
1921 1922
    return RPC_E_CHANGED_MODE;
  }
1923 1924
  else
    hr = S_FALSE;
1925

1926 1927 1928 1929
  info->inits++;

  if (info->spy)
      IInitializeSpy_PostInitialize(info->spy, hr, dwCoInit, info->inits);
1930 1931

  return hr;
1932 1933
}

1934
/***********************************************************************
1935
 *           CoUninitialize   [OLE32.@]
1936
 *
1937 1938 1939 1940
 * This method will decrement the refcount on the current apartment, freeing
 * the resources associated with it if it is the last thread in the apartment.
 * If the last apartment is freed, the function will additionally release
 * any COM resources associated with the process.
1941
 *
1942 1943 1944 1945
 * PARAMS
 *
 * RETURNS
 *  Nothing.
1946 1947 1948
 *
 * SEE ALSO
 *   CoInitializeEx
1949
 */
1950
void WINAPI DECLSPEC_HOTPATCH CoUninitialize(void)
1951
{
1952
  struct oletls * info = COM_CurrentInfo();
1953
  LONG lCOMRefCnt;
1954

1955
  TRACE("()\n");
1956

1957 1958 1959
  /* will only happen on OOM */
  if (!info) return;

1960 1961 1962
  if (info->spy)
      IInitializeSpy_PreUninitialize(info->spy, info->inits);

1963 1964 1965 1966
  /* sanity check */
  if (!info->inits)
  {
    ERR("Mismatched CoUninitialize\n");
1967 1968 1969

    if (info->spy)
        IInitializeSpy_PostUninitialize(info->spy, info->inits);
1970 1971 1972 1973 1974
    return;
  }

  if (!--info->inits)
  {
1975 1976
    if (info->ole_inits)
      WARN("uninitializing apartment while Ole is still initialized\n");
1977
    apartment_release(info->apt);
1978 1979
    info->apt = NULL;
  }
1980

1981 1982 1983 1984 1985
  /*
   * Decrease the reference count.
   * If we are back to 0 locks on the COM library, make sure we free
   * all the associated data structures.
   */
1986 1987
  lCOMRefCnt = InterlockedExchangeAdd(&s_COMLockCount,-1);
  if (lCOMRefCnt==1)
1988
  {
1989
    TRACE("() - Releasing the COM libraries\n");
1990

Noomen Hamza's avatar
Noomen Hamza committed
1991
    RunningObjectTableImpl_UnInitialize();
1992 1993 1994 1995 1996
  }
  else if (lCOMRefCnt<1) {
    ERR( "CoUninitialize() - not CoInitialized.\n" );
    InterlockedExchangeAdd(&s_COMLockCount,1); /* restore the lock count. */
  }
1997 1998
  if (info->spy)
      IInitializeSpy_PostUninitialize(info->spy, info->inits);
1999
}
Alexandre Julliard's avatar
Alexandre Julliard committed
2000

2001
/******************************************************************************
2002
 *		CoDisconnectObject	[OLE32.@]
2003 2004
 *
 * Disconnects all connections to this object from remote processes. Dispatches
2005
 * pending RPCs while blocking new RPCs from occurring, and then calls
2006 2007 2008 2009
 * IMarshal::DisconnectObject on the given object.
 *
 * Typically called when the object server is forced to shut down, for instance by
 * the user.
2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020
 *
 * PARAMS
 *  lpUnk    [I] The object whose stub should be disconnected.
 *  reserved [I] Reserved. Should be set to 0.
 *
 * RETURNS
 *  Success: S_OK.
 *  Failure: HRESULT code.
 *
 * SEE ALSO
 *  CoMarshalInterface, CoReleaseMarshalData, CoLockObjectExternal
Alexandre Julliard's avatar
Alexandre Julliard committed
2021
 */
2022
HRESULT WINAPI CoDisconnectObject( LPUNKNOWN lpUnk, DWORD reserved )
Alexandre Julliard's avatar
Alexandre Julliard committed
2023
{
2024
    struct stub_manager *manager;
2025 2026 2027 2028
    HRESULT hr;
    IMarshal *marshal;
    APARTMENT *apt;

2029
    TRACE("(%p, 0x%08x)\n", lpUnk, reserved);
2030

2031 2032
    if (!lpUnk) return E_INVALIDARG;

2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044
    hr = IUnknown_QueryInterface(lpUnk, &IID_IMarshal, (void **)&marshal);
    if (hr == S_OK)
    {
        hr = IMarshal_DisconnectObject(marshal, reserved);
        IMarshal_Release(marshal);
        return hr;
    }

    apt = COM_CurrentApt();
    if (!apt)
        return CO_E_NOTINITIALIZED;

2045 2046
    manager = get_stub_manager_from_object(apt, lpUnk, FALSE);
    if (manager) {
2047
        stub_manager_disconnect(manager);
2048 2049 2050 2051
        /* Release stub manager twice, to remove the apartment reference. */
        stub_manager_int_release(manager);
        stub_manager_int_release(manager);
    }
2052 2053 2054 2055 2056 2057

    /* Note: native is pretty broken here because it just silently
     * fails, without returning an appropriate error code if the object was
     * not found, making apps think that the object was disconnected, when
     * it actually wasn't */

Alexandre Julliard's avatar
Alexandre Julliard committed
2058
    return S_OK;
Alexandre Julliard's avatar
Alexandre Julliard committed
2059 2060
}

2061
/******************************************************************************
2062
 *		CoCreateGuid [OLE32.@]
2063
 *
2064 2065
 * Simply forwards to UuidCreate in RPCRT4.
 *
2066 2067 2068 2069 2070 2071 2072
 * PARAMS
 *  pguid [O] Points to the GUID to initialize.
 *
 * RETURNS
 *  Success: S_OK.
 *  Failure: HRESULT code.
 *
2073 2074
 * SEE ALSO
 *   UuidCreate
Alexandre Julliard's avatar
Alexandre Julliard committed
2075
 */
2076 2077
HRESULT WINAPI CoCreateGuid(GUID *pguid)
{
2078 2079 2080 2081 2082
    DWORD status;

    if(!pguid) return E_INVALIDARG;

    status = UuidCreate(pguid);
2083 2084
    if (status == RPC_S_OK || status == RPC_S_UUID_LOCAL_ONLY) return S_OK;
    return HRESULT_FROM_WIN32( status );
Alexandre Julliard's avatar
Alexandre Julliard committed
2085
}
Alexandre Julliard's avatar
Alexandre Julliard committed
2086

2087 2088 2089 2090 2091 2092 2093 2094 2095
static inline BOOL is_valid_hex(WCHAR c)
{
    if (!(((c >= '0') && (c <= '9'))  ||
          ((c >= 'a') && (c <= 'f'))  ||
          ((c >= 'A') && (c <= 'F'))))
        return FALSE;
    return TRUE;
}

2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106
static const BYTE guid_conv_table[256] =
{
  0,   0,   0,   0,   0,   0,   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x00 */
  0,   0,   0,   0,   0,   0,   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x10 */
  0,   0,   0,   0,   0,   0,   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20 */
  0,   1,   2,   3,   4,   5,   6, 7, 8, 9, 0, 0, 0, 0, 0, 0, /* 0x30 */
  0, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x40 */
  0,   0,   0,   0,   0,   0,   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x50 */
  0, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf                             /* 0x60 */
};

2107 2108
/* conversion helper for CLSIDFromString/IIDFromString */
static BOOL guid_from_string(LPCWSTR s, GUID *id)
2109
{
Alexandre Julliard's avatar
Alexandre Julliard committed
2110 2111
  int	i;

2112
  if (!s || s[0]!='{') {
2113
    memset( id, 0, sizeof (CLSID) );
2114 2115
    if(!s) return TRUE;
    return FALSE;
2116
  }
2117

2118
  TRACE("%s -> %p\n", debugstr_w(s), id);
Alexandre Julliard's avatar
Alexandre Julliard committed
2119 2120 2121

  /* in form {XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX} */

2122 2123
  id->Data1 = 0;
  for (i = 1; i < 9; i++) {
2124
    if (!is_valid_hex(s[i])) return FALSE;
2125
    id->Data1 = (id->Data1 << 4) | guid_conv_table[s[i]];
2126
  }
2127
  if (s[9]!='-') return FALSE;
2128 2129 2130

  id->Data2 = 0;
  for (i = 10; i < 14; i++) {
2131
    if (!is_valid_hex(s[i])) return FALSE;
2132
    id->Data2 = (id->Data2 << 4) | guid_conv_table[s[i]];
2133
  }
2134
  if (s[14]!='-') return FALSE;
2135 2136 2137

  id->Data3 = 0;
  for (i = 15; i < 19; i++) {
2138
    if (!is_valid_hex(s[i])) return FALSE;
2139
    id->Data3 = (id->Data3 << 4) | guid_conv_table[s[i]];
2140
  }
2141
  if (s[19]!='-') return FALSE;
2142 2143 2144

  for (i = 20; i < 37; i+=2) {
    if (i == 24) {
2145
      if (s[i]!='-') return FALSE;
2146 2147
      i++;
    }
2148
    if (!is_valid_hex(s[i]) || !is_valid_hex(s[i+1])) return FALSE;
2149
    id->Data4[(i-20)/2] = guid_conv_table[s[i]] << 4 | guid_conv_table[s[i+1]];
2150 2151 2152
  }

  if (s[37] == '}' && s[38] == '\0')
2153
    return TRUE;
2154

2155
  return FALSE;
Alexandre Julliard's avatar
Alexandre Julliard committed
2156 2157
}

2158 2159
/*****************************************************************************/

2160 2161 2162 2163 2164 2165 2166 2167 2168 2169
static HRESULT clsid_from_string_reg(LPCOLESTR progid, CLSID *clsid)
{
    static const WCHAR clsidW[] = { '\\','C','L','S','I','D',0 };
    WCHAR buf2[CHARS_IN_GUID];
    LONG buf2len = sizeof(buf2);
    HKEY xhkey;
    WCHAR *buf;

    memset(clsid, 0, sizeof(*clsid));
    buf = HeapAlloc( GetProcessHeap(),0,(strlenW(progid)+8) * sizeof(WCHAR) );
2170
    if (!buf) return E_OUTOFMEMORY;
2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187
    strcpyW( buf, progid );
    strcatW( buf, clsidW );
    if (open_classes_key(HKEY_CLASSES_ROOT, buf, MAXIMUM_ALLOWED, &xhkey))
    {
        HeapFree(GetProcessHeap(),0,buf);
        WARN("couldn't open key for ProgID %s\n", debugstr_w(progid));
        return CO_E_CLASSSTRING;
    }
    HeapFree(GetProcessHeap(),0,buf);

    if (RegQueryValueW(xhkey,NULL,buf2,&buf2len))
    {
        RegCloseKey(xhkey);
        WARN("couldn't query clsid value for ProgID %s\n", debugstr_w(progid));
        return CO_E_CLASSSTRING;
    }
    RegCloseKey(xhkey);
2188
    return guid_from_string(buf2, clsid) ? S_OK : CO_E_CLASSSTRING;
2189 2190
}

2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207
/******************************************************************************
 *		CLSIDFromString	[OLE32.@]
 *
 * Converts a unique identifier from its string representation into
 * the GUID struct.
 *
 * PARAMS
 *  idstr [I] The string representation of the GUID.
 *  id    [O] GUID converted from the string.
 *
 * RETURNS
 *   S_OK on success
 *   CO_E_CLASSSTRING if idstr is not a valid CLSID
 *
 * SEE ALSO
 *  StringFromCLSID
 */
2208
HRESULT WINAPI CLSIDFromString(LPCOLESTR idstr, LPCLSID id )
2209
{
2210 2211
    HRESULT ret = CO_E_CLASSSTRING;
    CLSID tmp_id;
Alexandre Julliard's avatar
Alexandre Julliard committed
2212

2213 2214 2215
    if (!id)
        return E_INVALIDARG;

2216 2217 2218 2219 2220 2221 2222 2223
    if (guid_from_string(idstr, id))
        return S_OK;

    /* It appears a ProgID is also valid */
    ret = clsid_from_string_reg(idstr, &tmp_id);
    if(SUCCEEDED(ret))
        *id = tmp_id;

Alexandre Julliard's avatar
Alexandre Julliard committed
2224
    return ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
2225 2226
}

2227 2228 2229
/******************************************************************************
 *		IIDFromString   [OLE32.@]
 *
2230
 * Converts an interface identifier from its string representation to
2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262
 * the IID struct.
 *
 * PARAMS
 *  idstr [I] The string representation of the GUID.
 *  id    [O] IID converted from the string.
 *
 * RETURNS
 *   S_OK on success
 *   CO_E_IIDSTRING if idstr is not a valid IID
 *
 * SEE ALSO
 *  StringFromIID
 */
HRESULT WINAPI IIDFromString(LPCOLESTR s, IID *iid)
{
  TRACE("%s -> %p\n", debugstr_w(s), iid);

  if (!s)
  {
      memset(iid, 0, sizeof(*iid));
      return S_OK;
  }

  /* length mismatch is a special case */
  if (strlenW(s) + 1 != CHARS_IN_GUID)
      return E_INVALIDARG;

  if (s[0] != '{')
      return CO_E_IIDSTRING;

  return guid_from_string(s, iid) ? S_OK : CO_E_IIDSTRING;
}
Alexandre Julliard's avatar
Alexandre Julliard committed
2263

2264
/******************************************************************************
2265 2266
 *		StringFromCLSID	[OLE32.@]
 *		StringFromIID   [OLE32.@]
2267
 *
Alexandre Julliard's avatar
Alexandre Julliard committed
2268 2269
 * Converts a GUID into the respective string representation.
 * The target string is allocated using the OLE IMalloc.
2270
 *
2271 2272 2273 2274
 * PARAMS
 *  id    [I] the GUID to be converted.
 *  idstr [O] A pointer to a to-be-allocated pointer pointing to the resulting string.
 *
Alexandre Julliard's avatar
Alexandre Julliard committed
2275
 * RETURNS
2276 2277
 *   S_OK
 *   E_FAIL
2278 2279 2280
 *
 * SEE ALSO
 *  StringFromGUID2, CLSIDFromString
Alexandre Julliard's avatar
Alexandre Julliard committed
2281
 */
2282 2283
HRESULT WINAPI StringFromCLSID(REFCLSID id, LPOLESTR *idstr)
{
2284
    if (!(*idstr = CoTaskMemAlloc(CHARS_IN_GUID * sizeof(WCHAR)))) return E_OUTOFMEMORY;
2285 2286
    StringFromGUID2( id, *idstr, CHARS_IN_GUID );
    return S_OK;
Alexandre Julliard's avatar
Alexandre Julliard committed
2287 2288
}

2289
/******************************************************************************
2290
 *		StringFromGUID2	[OLE32.@]
Alexandre Julliard's avatar
Alexandre Julliard committed
2291
 *
2292 2293
 * Modified version of StringFromCLSID that allows you to specify max
 * buffer size.
Alexandre Julliard's avatar
Alexandre Julliard committed
2294
 *
2295 2296 2297 2298 2299
 * PARAMS
 *  id   [I] GUID to convert to string.
 *  str  [O] Buffer where the result will be stored.
 *  cmax [I] Size of the buffer in characters.
 *
Alexandre Julliard's avatar
Alexandre Julliard committed
2300
 * RETURNS
2301 2302
 *	Success: The length of the resulting string in characters.
 *  Failure: 0.
Alexandre Julliard's avatar
Alexandre Julliard committed
2303
 */
2304
INT WINAPI StringFromGUID2(REFGUID id, LPOLESTR str, INT cmax)
Alexandre Julliard's avatar
Alexandre Julliard committed
2305
{
2306 2307 2308 2309
    static const WCHAR formatW[] = { '{','%','0','8','X','-','%','0','4','X','-',
                                     '%','0','4','X','-','%','0','2','X','%','0','2','X','-',
                                     '%','0','2','X','%','0','2','X','%','0','2','X','%','0','2','X',
                                     '%','0','2','X','%','0','2','X','}',0 };
2310
    if (!id || cmax < CHARS_IN_GUID) return 0;
2311 2312 2313 2314
    sprintfW( str, formatW, id->Data1, id->Data2, id->Data3,
              id->Data4[0], id->Data4[1], id->Data4[2], id->Data4[3],
              id->Data4[4], id->Data4[5], id->Data4[6], id->Data4[7] );
    return CHARS_IN_GUID;
Alexandre Julliard's avatar
Alexandre Julliard committed
2315
}
Alexandre Julliard's avatar
Alexandre Julliard committed
2316

2317 2318
/* open HKCR\\CLSID\\{string form of clsid}\\{keyname} key */
HRESULT COM_OpenKeyForCLSID(REFCLSID clsid, LPCWSTR keyname, REGSAM access, HKEY *subkey)
2319 2320 2321
{
    static const WCHAR wszCLSIDSlash[] = {'C','L','S','I','D','\\',0};
    WCHAR path[CHARS_IN_GUID + ARRAYSIZE(wszCLSIDSlash) - 1];
2322 2323 2324
    LONG res;
    HKEY key;

2325 2326
    strcpyW(path, wszCLSIDSlash);
    StringFromGUID2(clsid, path + strlenW(wszCLSIDSlash), CHARS_IN_GUID);
2327
    res = open_classes_key(HKEY_CLASSES_ROOT, path, keyname ? KEY_READ : access, &key);
2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338
    if (res == ERROR_FILE_NOT_FOUND)
        return REGDB_E_CLASSNOTREG;
    else if (res != ERROR_SUCCESS)
        return REGDB_E_READREGDB;

    if (!keyname)
    {
        *subkey = key;
        return S_OK;
    }

2339
    res = open_classes_key(key, keyname, access, subkey);
2340
    RegCloseKey(key);
2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362
    if (res == ERROR_FILE_NOT_FOUND)
        return REGDB_E_KEYMISSING;
    else if (res != ERROR_SUCCESS)
        return REGDB_E_READREGDB;

    return S_OK;
}

/* open HKCR\\AppId\\{string form of appid clsid} key */
HRESULT COM_OpenKeyForAppIdFromCLSID(REFCLSID clsid, REGSAM access, HKEY *subkey)
{
    static const WCHAR szAppId[] = { 'A','p','p','I','d',0 };
    static const WCHAR szAppIdKey[] = { 'A','p','p','I','d','\\',0 };
    DWORD res;
    WCHAR buf[CHARS_IN_GUID];
    WCHAR keyname[ARRAYSIZE(szAppIdKey) + CHARS_IN_GUID];
    DWORD size;
    HKEY hkey;
    DWORD type;
    HRESULT hr;

    /* read the AppID value under the class's key */
2363
    hr = COM_OpenKeyForCLSID(clsid, NULL, KEY_READ, &hkey);
2364 2365 2366 2367
    if (FAILED(hr))
        return hr;

    size = sizeof(buf);
2368
    res = RegQueryValueExW(hkey, szAppId, NULL, &type, (LPBYTE)buf, &size);
2369 2370 2371 2372 2373 2374 2375 2376
    RegCloseKey(hkey);
    if (res == ERROR_FILE_NOT_FOUND)
        return REGDB_E_KEYMISSING;
    else if (res != ERROR_SUCCESS || type!=REG_SZ)
        return REGDB_E_READREGDB;

    strcpyW(keyname, szAppIdKey);
    strcatW(keyname, buf);
2377
    res = open_classes_key(HKEY_CLASSES_ROOT, keyname, access, subkey);
2378 2379 2380 2381 2382 2383
    if (res == ERROR_FILE_NOT_FOUND)
        return REGDB_E_KEYMISSING;
    else if (res != ERROR_SUCCESS)
        return REGDB_E_READREGDB;

    return S_OK;
2384 2385
}

2386
/******************************************************************************
2387 2388
 *               ProgIDFromCLSID [OLE32.@]
 *
2389 2390 2391 2392
 * Converts a class id into the respective program ID.
 *
 * PARAMS
 *  clsid        [I] Class ID, as found in registry.
2393
 *  ppszProgID [O] Associated ProgID.
2394 2395 2396 2397 2398
 *
 * RETURNS
 *   S_OK
 *   E_OUTOFMEMORY
 *   REGDB_E_CLASSNOTREG if the given clsid has no associated ProgID
2399
 */
2400
HRESULT WINAPI DECLSPEC_HOTPATCH ProgIDFromCLSID(REFCLSID clsid, LPOLESTR *ppszProgID)
2401
{
2402
    static const WCHAR wszProgID[] = {'P','r','o','g','I','D',0};
2403
    ACTCTX_SECTION_KEYED_DATA data;
2404 2405
    HKEY     hkey;
    HRESULT  ret;
2406
    LONG progidlen = 0;
2407

2408 2409 2410 2411
    if (!ppszProgID)
        return E_INVALIDARG;

    *ppszProgID = NULL;
2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432

    data.cbSize = sizeof(data);
    if (FindActCtxSectionGuid(0, NULL, ACTIVATION_CONTEXT_SECTION_COM_SERVER_REDIRECTION,
                              clsid, &data))
    {
        struct comclassredirect_data *comclass = (struct comclassredirect_data*)data.lpData;
        if (comclass->progid_len)
        {
            WCHAR *ptrW;

            *ppszProgID = CoTaskMemAlloc(comclass->progid_len + sizeof(WCHAR));
            if (!*ppszProgID) return E_OUTOFMEMORY;

            ptrW = (WCHAR*)((BYTE*)comclass + comclass->progid_offset);
            memcpy(*ppszProgID, ptrW, comclass->progid_len + sizeof(WCHAR));
            return S_OK;
        }
        else
            return REGDB_E_CLASSNOTREG;
    }

2433 2434 2435 2436
    ret = COM_OpenKeyForCLSID(clsid, wszProgID, KEY_READ, &hkey);
    if (FAILED(ret))
        return ret;

2437
    if (RegQueryValueW(hkey, NULL, NULL, &progidlen))
2438 2439 2440 2441
      ret = REGDB_E_CLASSNOTREG;

    if (ret == S_OK)
    {
2442 2443
      *ppszProgID = CoTaskMemAlloc(progidlen * sizeof(WCHAR));
      if (*ppszProgID)
2444
      {
2445
        if (RegQueryValueW(hkey, NULL, *ppszProgID, &progidlen)) {
2446
          ret = REGDB_E_CLASSNOTREG;
2447 2448 2449
          CoTaskMemFree(*ppszProgID);
          *ppszProgID = NULL;
        }
2450
      }
2451 2452
      else
        ret = E_OUTOFMEMORY;
2453 2454
    }

2455 2456
    RegCloseKey(hkey);
    return ret;
2457 2458
}

2459
/******************************************************************************
2460
 *		CLSIDFromProgID	[OLE32.@]
2461
 *
2462 2463 2464 2465
 * Converts a program id into the respective GUID.
 *
 * PARAMS
 *  progid [I] Unicode program ID, as found in registry.
2466
 *  clsid  [O] Associated CLSID.
2467
 *
Alexandre Julliard's avatar
Alexandre Julliard committed
2468
 * RETURNS
2469 2470
 *	Success: S_OK
 *  Failure: CO_E_CLASSSTRING - the given ProgID cannot be found.
Alexandre Julliard's avatar
Alexandre Julliard committed
2471
 */
2472
HRESULT WINAPI DECLSPEC_HOTPATCH CLSIDFromProgID(LPCOLESTR progid, LPCLSID clsid)
2473
{
2474 2475
    ACTCTX_SECTION_KEYED_DATA data;

2476 2477 2478
    if (!progid || !clsid)
        return E_INVALIDARG;

2479 2480 2481 2482 2483 2484 2485 2486 2487 2488
    data.cbSize = sizeof(data);
    if (FindActCtxSectionStringW(0, NULL, ACTIVATION_CONTEXT_SECTION_COM_PROGID_REDIRECTION,
                                 progid, &data))
    {
        struct progidredirect_data *progiddata = (struct progidredirect_data*)data.lpData;
        CLSID *alias = (CLSID*)((BYTE*)data.lpSectionBase + progiddata->clsid_offset);
        *clsid = *alias;
        return S_OK;
    }

2489
    return clsid_from_string_reg(progid, clsid);
Alexandre Julliard's avatar
Alexandre Julliard committed
2490 2491
}

2492 2493 2494 2495 2496 2497 2498 2499 2500
/******************************************************************************
 *              CLSIDFromProgIDEx [OLE32.@]
 */
HRESULT WINAPI CLSIDFromProgIDEx(LPCOLESTR progid, LPCLSID clsid)
{
    FIXME("%s,%p: semi-stub\n", debugstr_w(progid), clsid);

    return CLSIDFromProgID(progid, clsid);
}
2501

2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523
static HRESULT get_ps_clsid_from_registry(const WCHAR* path, REGSAM access, CLSID *pclsid)
{
    HKEY hkey;
    WCHAR value[CHARS_IN_GUID];
    DWORD len;

    access |= KEY_READ;

    if (open_classes_key(HKEY_CLASSES_ROOT, path, access, &hkey))
        return REGDB_E_IIDNOTREG;

    len = sizeof(value);
    if (ERROR_SUCCESS != RegQueryValueExW(hkey, NULL, NULL, NULL, (BYTE *)value, &len))
        return REGDB_E_IIDNOTREG;
    RegCloseKey(hkey);

    if (CLSIDFromString(value, pclsid) != NOERROR)
        return REGDB_E_IIDNOTREG;

    return S_OK;
}

2524
/*****************************************************************************
2525
 *             CoGetPSClsid [OLE32.@]
2526
 *
Robert Shearman's avatar
Robert Shearman committed
2527 2528
 * Retrieves the CLSID of the proxy/stub factory that implements
 * IPSFactoryBuffer for the specified interface.
2529
 *
2530 2531 2532 2533 2534 2535 2536
 * PARAMS
 *  riid   [I] Interface whose proxy/stub CLSID is to be returned.
 *  pclsid [O] Where to store returned proxy/stub CLSID.
 * 
 * RETURNS
 *   S_OK
 *   E_OUTOFMEMORY
Robert Shearman's avatar
Robert Shearman committed
2537
 *   REGDB_E_IIDNOTREG if no PSFactoryBuffer is associated with the IID, or it could not be parsed
2538 2539 2540
 *
 * NOTES
 *
2541 2542 2543 2544
 * The standard marshaller activates the object with the CLSID
 * returned and uses the CreateProxy and CreateStub methods on its
 * IPSFactoryBuffer interface to construct the proxies and stubs for a
 * given object.
2545 2546
 *
 * CoGetPSClsid determines this CLSID by searching the
2547 2548 2549
 * HKEY_CLASSES_ROOT\Interface\{string form of riid}\ProxyStubClsid32
 * in the registry and any interface id registered by
 * CoRegisterPSClsid within the current process.
2550
 *
2551
 * BUGS
2552
 *
2553
 * Native returns S_OK for interfaces with a key in HKCR\Interface, but
Robert Shearman's avatar
Robert Shearman committed
2554 2555
 * without a ProxyStubClsid32 key and leaves garbage in pclsid. This should be
 * considered a bug in native unless an application depends on this (unlikely).
2556 2557 2558
 *
 * SEE ALSO
 *  CoRegisterPSClsid.
2559
 */
2560
HRESULT WINAPI CoGetPSClsid(REFIID riid, CLSID *pclsid)
2561
{
2562 2563 2564
    static const WCHAR wszInterface[] = {'I','n','t','e','r','f','a','c','e','\\',0};
    static const WCHAR wszPSC[] = {'\\','P','r','o','x','y','S','t','u','b','C','l','s','i','d','3','2',0};
    WCHAR path[ARRAYSIZE(wszInterface) - 1 + CHARS_IN_GUID - 1 + ARRAYSIZE(wszPSC)];
2565 2566
    APARTMENT *apt = COM_CurrentApt();
    struct registered_psclsid *registered_psclsid;
2567
    ACTCTX_SECTION_KEYED_DATA data;
2568 2569 2570
    HRESULT hr;
    REGSAM opposite = (sizeof(void*) > sizeof(int)) ? KEY_WOW64_32KEY : KEY_WOW64_64KEY;
    BOOL is_wow64;
2571 2572 2573

    TRACE("() riid=%s, pclsid=%p\n", debugstr_guid(riid), pclsid);

2574 2575 2576 2577 2578 2579
    if (!apt)
    {
        ERR("apartment not initialised\n");
        return CO_E_NOTINITIALIZED;
    }

2580 2581 2582
    if (!pclsid)
        return E_INVALIDARG;

2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594
    EnterCriticalSection(&apt->cs);

    LIST_FOR_EACH_ENTRY(registered_psclsid, &apt->psclsids, struct registered_psclsid, entry)
        if (IsEqualIID(&registered_psclsid->iid, riid))
        {
            *pclsid = registered_psclsid->clsid;
            LeaveCriticalSection(&apt->cs);
            return S_OK;
        }

    LeaveCriticalSection(&apt->cs);

2595 2596 2597 2598 2599 2600 2601 2602 2603
    data.cbSize = sizeof(data);
    if (FindActCtxSectionGuid(0, NULL, ACTIVATION_CONTEXT_SECTION_COM_INTERFACE_REDIRECTION,
                              riid, &data))
    {
        struct ifacepsredirect_data *ifaceps = (struct ifacepsredirect_data*)data.lpData;
        *pclsid = ifaceps->iid;
        return S_OK;
    }

2604 2605 2606 2607
    /* Interface\\{string form of riid}\\ProxyStubClsid32 */
    strcpyW(path, wszInterface);
    StringFromGUID2(riid, path + ARRAYSIZE(wszInterface) - 1, CHARS_IN_GUID);
    strcpyW(path + ARRAYSIZE(wszInterface) - 1 + CHARS_IN_GUID - 1, wszPSC);
2608

2609 2610 2611 2612
    hr = get_ps_clsid_from_registry(path, 0, pclsid);
    if (FAILED(hr) && (opposite == KEY_WOW64_32KEY ||
                       (IsWow64Process(GetCurrentProcess(), &is_wow64) && is_wow64)))
        hr = get_ps_clsid_from_registry(path, opposite, pclsid);
2613

2614 2615 2616 2617
    if (hr == S_OK)
        TRACE ("() Returning CLSID=%s\n", debugstr_guid(pclsid));
    else
        WARN("No PSFactoryBuffer object is registered for IID %s\n", debugstr_guid(riid));
2618

2619
    return hr;
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 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682
/*****************************************************************************
 *             CoRegisterPSClsid [OLE32.@]
 *
 * Register a proxy/stub CLSID for the given interface in the current process
 * only.
 *
 * PARAMS
 *  riid   [I] Interface whose proxy/stub CLSID is to be registered.
 *  rclsid [I] CLSID of the proxy/stub.
 * 
 * RETURNS
 *   Success: S_OK
 *   Failure: E_OUTOFMEMORY
 *
 * NOTES
 *
 * This function does not add anything to the registry and the effects are
 * limited to the lifetime of the current process.
 *
 * SEE ALSO
 *  CoGetPSClsid.
 */
HRESULT WINAPI CoRegisterPSClsid(REFIID riid, REFCLSID rclsid)
{
    APARTMENT *apt = COM_CurrentApt();
    struct registered_psclsid *registered_psclsid;

    TRACE("(%s, %s)\n", debugstr_guid(riid), debugstr_guid(rclsid));

    if (!apt)
    {
        ERR("apartment not initialised\n");
        return CO_E_NOTINITIALIZED;
    }

    EnterCriticalSection(&apt->cs);

    LIST_FOR_EACH_ENTRY(registered_psclsid, &apt->psclsids, struct registered_psclsid, entry)
        if (IsEqualIID(&registered_psclsid->iid, riid))
        {
            registered_psclsid->clsid = *rclsid;
            LeaveCriticalSection(&apt->cs);
            return S_OK;
        }

    registered_psclsid = HeapAlloc(GetProcessHeap(), 0, sizeof(struct registered_psclsid));
    if (!registered_psclsid)
    {
        LeaveCriticalSection(&apt->cs);
        return E_OUTOFMEMORY;
    }

    registered_psclsid->iid = *riid;
    registered_psclsid->clsid = *rclsid;
    list_add_head(&apt->psclsids, &registered_psclsid->entry);

    LeaveCriticalSection(&apt->cs);

    return S_OK;
}

2683

2684 2685 2686
/***
 * COM_GetRegisteredClassObject
 *
2687
 * This internal method is used to scan the registered class list to
2688 2689
 * find a class object.
 *
2690
 * Params:
2691 2692 2693 2694 2695 2696
 *   rclsid        Class ID of the class to find.
 *   dwClsContext  Class context to match.
 *   ppv           [out] returns a pointer to the class object. Complying
 *                 to normal COM usage, this method will increase the
 *                 reference count on this object.
 */
2697 2698
static HRESULT COM_GetRegisteredClassObject(const struct apartment *apt, REFCLSID rclsid,
                                            DWORD dwClsContext, LPUNKNOWN* ppUnk)
2699
{
2700
  HRESULT hr = S_FALSE;
2701
  RegisteredClass *curClass;
2702

2703
  EnterCriticalSection( &csRegisteredClassList );
2704

2705
  LIST_FOR_EACH_ENTRY(curClass, &RegisteredClassList, RegisteredClass, entry)
2706 2707
  {
    /*
2708
     * Check if we have a match on the class ID and context.
2709
     */
2710 2711
    if ((apt->oxid == curClass->apartment_id) &&
        (dwClsContext & curClass->runContext) &&
2712
        IsEqualGUID(&(curClass->classIdentifier), rclsid))
2713 2714 2715 2716 2717 2718 2719 2720
    {
      /*
       * We have a match, return the pointer to the class object.
       */
      *ppUnk = curClass->classObject;

      IUnknown_AddRef(curClass->classObject);

2721
      hr = S_OK;
2722
      break;
2723 2724 2725
    }
  }

2726
  LeaveCriticalSection( &csRegisteredClassList );
2727

2728
  return hr;
2729 2730
}

2731
/******************************************************************************
2732
 *		CoRegisterClassObject	[OLE32.@]
2733
 *
2734 2735 2736
 * Registers the class object for a given class ID. Servers housed in EXE
 * files use this method instead of exporting DllGetClassObject to allow
 * other code to connect to their objects.
2737
 *
2738 2739 2740 2741 2742 2743 2744
 * PARAMS
 *  rclsid       [I] CLSID of the object to register.
 *  pUnk         [I] IUnknown of the object.
 *  dwClsContext [I] CLSCTX flags indicating the context in which to run the executable.
 *  flags        [I] REGCLS flags indicating how connections are made.
 *  lpdwRegister [I] A unique cookie that can be passed to CoRevokeClassObject.
 *
2745
 * RETURNS
2746 2747
 *   S_OK on success,
 *   E_INVALIDARG if lpdwRegister or pUnk are NULL,
2748 2749 2750 2751
 *   CO_E_OBJISREG if the object is already registered. We should not return this.
 *
 * SEE ALSO
 *   CoRevokeClassObject, CoGetClassObject
2752
 *
2753 2754 2755 2756 2757
 * NOTES
 *  In-process objects are only registered for the current apartment.
 *  CoGetClassObject() and CoCreateInstance() will not return objects registered
 *  in other apartments.
 *
2758 2759 2760
 * BUGS
 *  MSDN claims that multiple interface registrations are legal, but we
 *  can't do that with our current implementation.
Alexandre Julliard's avatar
Alexandre Julliard committed
2761
 */
2762
HRESULT WINAPI CoRegisterClassObject(
2763 2764 2765 2766 2767
    REFCLSID rclsid,
    LPUNKNOWN pUnk,
    DWORD dwClsContext,
    DWORD flags,
    LPDWORD lpdwRegister)
2768
{
2769
  static LONG next_cookie;
2770 2771 2772
  RegisteredClass* newClass;
  LPUNKNOWN        foundObject;
  HRESULT          hr;
2773
  APARTMENT *apt;
Alexandre Julliard's avatar
Alexandre Julliard committed
2774

2775
  TRACE("(%s,%p,0x%08x,0x%08x,%p)\n",
2776
	debugstr_guid(rclsid),pUnk,dwClsContext,flags,lpdwRegister);
2777 2778 2779 2780

  if ( (lpdwRegister==0) || (pUnk==0) )
    return E_INVALIDARG;

2781 2782
  apt = COM_CurrentApt();
  if (!apt)
2783 2784 2785 2786 2787
  {
      ERR("COM was not initialized\n");
      return CO_E_NOTINITIALIZED;
  }

2788 2789
  *lpdwRegister = 0;

2790 2791 2792 2793 2794
  /* REGCLS_MULTIPLEUSE implies registering as inproc server. This is what
   * differentiates the flag from REGCLS_MULTI_SEPARATE. */
  if (flags & REGCLS_MULTIPLEUSE)
    dwClsContext |= CLSCTX_INPROC_SERVER;

2795 2796 2797 2798
  /*
   * First, check if the class is already registered.
   * If it is, this should cause an error.
   */
2799
  hr = COM_GetRegisteredClassObject(apt, rclsid, dwClsContext, &foundObject);
2800
  if (hr == S_OK) {
2801 2802 2803 2804 2805 2806
    if (flags & REGCLS_MULTIPLEUSE) {
      if (dwClsContext & CLSCTX_LOCAL_SERVER)
        hr = CoLockObjectExternal(foundObject, TRUE, FALSE);
      IUnknown_Release(foundObject);
      return hr;
    }
2807
    IUnknown_Release(foundObject);
2808
    ERR("object already registered for class %s\n", debugstr_guid(rclsid));
2809 2810
    return CO_E_OBJISREG;
  }
2811

2812
  newClass = HeapAlloc(GetProcessHeap(), 0, sizeof(RegisteredClass));
2813 2814
  if ( newClass == NULL )
    return E_OUTOFMEMORY;
2815 2816

  newClass->classIdentifier = *rclsid;
2817
  newClass->apartment_id    = apt->oxid;
2818 2819
  newClass->runContext      = dwClsContext;
  newClass->connectFlags    = flags;
2820
  newClass->RpcRegistration = NULL;
2821

2822 2823
  if (!(newClass->dwCookie = InterlockedIncrement( &next_cookie )))
      newClass->dwCookie = InterlockedIncrement( &next_cookie );
2824 2825

  /*
2826
   * Since we're making a copy of the object pointer, we have to increase its
2827 2828 2829 2830 2831
   * reference count.
   */
  newClass->classObject     = pUnk;
  IUnknown_AddRef(newClass->classObject);

2832 2833
  EnterCriticalSection( &csRegisteredClassList );
  list_add_tail(&RegisteredClassList, &newClass->entry);
2834 2835
  LeaveCriticalSection( &csRegisteredClassList );

2836
  *lpdwRegister = newClass->dwCookie;
2837

2838
  if (dwClsContext & CLSCTX_LOCAL_SERVER) {
2839 2840 2841 2842
      IStream *marshal_stream;

      hr = get_local_server_stream(apt, &marshal_stream);
      if(FAILED(hr))
2843 2844
          return hr;

2845
      hr = RPC_StartLocalServer(&newClass->classIdentifier,
2846
                                marshal_stream,
2847
                                flags & (REGCLS_MULTIPLEUSE|REGCLS_MULTI_SEPARATE),
2848
                                &newClass->RpcRegistration);
2849
      IStream_Release(marshal_stream);
2850
  }
2851
  return S_OK;
Alexandre Julliard's avatar
Alexandre Julliard committed
2852 2853
}

2854
static enum comclass_threadingmodel get_threading_model(const struct class_reg_data *data)
2855
{
2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869
    if (data->hkey)
    {
        static const WCHAR wszThreadingModel[] = {'T','h','r','e','a','d','i','n','g','M','o','d','e','l',0};
        static const WCHAR wszApartment[] = {'A','p','a','r','t','m','e','n','t',0};
        static const WCHAR wszFree[] = {'F','r','e','e',0};
        static const WCHAR wszBoth[] = {'B','o','t','h',0};
        WCHAR threading_model[10 /* strlenW(L"apartment")+1 */];
        DWORD dwLength = sizeof(threading_model);
        DWORD keytype;
        DWORD ret;

        ret = RegQueryValueExW(data->u.hkey, wszThreadingModel, NULL, &keytype, (BYTE*)threading_model, &dwLength);
        if ((ret != ERROR_SUCCESS) || (keytype != REG_SZ))
            threading_model[0] = '\0';
2870

2871 2872 2873 2874 2875 2876 2877 2878 2879 2880
        if (!strcmpiW(threading_model, wszApartment)) return ThreadingModel_Apartment;
        if (!strcmpiW(threading_model, wszFree)) return ThreadingModel_Free;
        if (!strcmpiW(threading_model, wszBoth)) return ThreadingModel_Both;

        /* there's not specific handling for this case */
        if (threading_model[0]) return ThreadingModel_Neutral;
        return ThreadingModel_No;
    }
    else
        return data->u.actctx.data->model;
2881 2882
}

2883
static HRESULT get_inproc_class_object(APARTMENT *apt, const struct class_reg_data *regdata,
2884 2885
                                       REFCLSID rclsid, REFIID riid,
                                       BOOL hostifnecessary, void **ppv)
2886 2887
{
    WCHAR dllpath[MAX_PATH+1];
2888
    BOOL apartment_threaded;
2889

2890
    if (hostifnecessary)
2891
    {
2892
        enum comclass_threadingmodel model = get_threading_model(regdata);
2893

2894
        if (model == ThreadingModel_Apartment)
2895 2896 2897
        {
            apartment_threaded = TRUE;
            if (apt->multi_threaded)
2898
                return apartment_hostobject_in_hostapt(apt, FALSE, FALSE, regdata, rclsid, riid, ppv);
2899
        }
2900
        else if (model == ThreadingModel_Free)
2901 2902 2903
        {
            apartment_threaded = FALSE;
            if (!apt->multi_threaded)
2904
                return apartment_hostobject_in_hostapt(apt, TRUE, FALSE, regdata, rclsid, riid, ppv);
2905 2906
        }
        /* everything except "Apartment", "Free" and "Both" */
2907
        else if (model != ThreadingModel_Both)
2908 2909 2910
        {
            apartment_threaded = TRUE;
            /* everything else is main-threaded */
2911 2912
            if (model != ThreadingModel_No)
                FIXME("unrecognised threading model %d for object %s, should be main-threaded?\n", model, debugstr_guid(rclsid));
2913 2914

            if (apt->multi_threaded || !apt->main)
2915
                return apartment_hostobject_in_hostapt(apt, FALSE, TRUE, regdata, rclsid, riid, ppv);
2916 2917 2918
        }
        else
            apartment_threaded = FALSE;
2919
    }
2920 2921
    else
        apartment_threaded = !apt->multi_threaded;
2922

2923
    if (COM_RegReadPath(regdata, dllpath, ARRAYSIZE(dllpath)) != ERROR_SUCCESS)
2924 2925 2926 2927 2928 2929
    {
        /* failure: CLSID is not found in registry */
        WARN("class %s not registered inproc\n", debugstr_guid(rclsid));
        return REGDB_E_CLASSNOTREG;
    }

2930
    return apartment_getclassobject(apt, dllpath, apartment_threaded,
2931
                                    rclsid, riid, ppv);
2932 2933
}

Alexandre Julliard's avatar
Alexandre Julliard committed
2934
/***********************************************************************
2935
 *           CoGetClassObject [OLE32.@]
2936
 *
2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958
 * Creates an object of the specified class.
 *
 * PARAMS
 *  rclsid       [I] Class ID to create an instance of.
 *  dwClsContext [I] Flags to restrict the location of the created instance.
 *  pServerInfo  [I] Optional. Details for connecting to a remote server.
 *  iid          [I] The ID of the interface of the instance to return.
 *  ppv          [O] On returns, contains a pointer to the specified interface of the object.
 *
 * RETURNS
 *  Success: S_OK
 *  Failure: HRESULT code.
 *
 * NOTES
 *  The dwClsContext parameter can be one or more of the following:
 *| CLSCTX_INPROC_SERVER - Use an in-process server, such as from a DLL.
 *| CLSCTX_INPROC_HANDLER - Use an in-process object which handles certain functions for an object running in another process.
 *| CLSCTX_LOCAL_SERVER - Connect to an object running in another process.
 *| CLSCTX_REMOTE_SERVER - Connect to an object running on another machine.
 *
 * SEE ALSO
 *  CoCreateInstance()
Alexandre Julliard's avatar
Alexandre Julliard committed
2959
 */
2960
HRESULT WINAPI DECLSPEC_HOTPATCH CoGetClassObject(
2961
    REFCLSID rclsid, DWORD dwClsContext, COSERVERINFO *pServerInfo,
2962 2963
    REFIID iid, LPVOID *ppv)
{
2964 2965
    struct class_reg_data clsreg;
    IUnknown *regClassObject;
2966
    HRESULT	hres = E_UNEXPECTED;
2967
    APARTMENT  *apt;
2968
    BOOL release_apt = FALSE;
2969

2970
    TRACE("CLSID: %s,IID: %s\n", debugstr_guid(rclsid), debugstr_guid(iid));
Alexandre Julliard's avatar
Alexandre Julliard committed
2971

2972 2973 2974 2975 2976
    if (!ppv)
        return E_INVALIDARG;

    *ppv = NULL;

2977
    if (!(apt = COM_CurrentApt()))
2978
    {
2979 2980 2981 2982 2983 2984
        if (!(apt = apartment_find_multi_threaded()))
        {
            ERR("apartment not initialised\n");
            return CO_E_NOTINITIALIZED;
        }
        release_apt = TRUE;
2985 2986
    }

2987
    if (pServerInfo) {
2988 2989
	FIXME("pServerInfo->name=%s pAuthInfo=%p\n",
              debugstr_w(pServerInfo->pwszName), pServerInfo->pAuthInfo);
2990 2991
    }

2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010
    if (CLSCTX_INPROC_SERVER & dwClsContext)
    {
        if (IsEqualCLSID(rclsid, &CLSID_InProcFreeMarshaler))
        {
            if (release_apt) apartment_release(apt);
            return FTMarshalCF_Create(iid, ppv);
        }
    }

    if (CLSCTX_INPROC & dwClsContext)
    {
        ACTCTX_SECTION_KEYED_DATA data;

        data.cbSize = sizeof(data);
        /* search activation context first */
        if (FindActCtxSectionGuid(FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX, NULL,
                                  ACTIVATION_CONTEXT_SECTION_COM_SERVER_REDIRECTION,
                                  rclsid, &data))
        {
3011 3012
            struct comclassredirect_data *comclass = (struct comclassredirect_data*)data.lpData;

3013 3014 3015 3016 3017
            clsreg.u.actctx.hactctx = data.hActCtx;
            clsreg.u.actctx.data = data.lpData;
            clsreg.u.actctx.section = data.lpSectionBase;
            clsreg.hkey = FALSE;

3018
            hres = get_inproc_class_object(apt, &clsreg, &comclass->clsid, iid, !(dwClsContext & WINE_CLSCTX_DONT_HOST), ppv);
3019 3020 3021 3022 3023 3024
            ReleaseActCtx(data.hActCtx);
            if (release_apt) apartment_release(apt);
            return hres;
        }
    }

3025
    /*
3026
     * First, try and see if we can't match the class ID with one of the
3027 3028
     * registered classes.
     */
3029 3030
    if (S_OK == COM_GetRegisteredClassObject(apt, rclsid, dwClsContext,
                                             &regClassObject))
3031
    {
3032
      /* Get the required interface from the retrieved pointer. */
3033 3034 3035 3036 3037 3038 3039 3040
      hres = IUnknown_QueryInterface(regClassObject, iid, ppv);

      /*
       * Since QI got another reference on the pointer, we want to release the
       * one we already have. If QI was unsuccessful, this will release the object. This
       * is good since we are not returning it in the "out" parameter.
       */
      IUnknown_Release(regClassObject);
3041
      if (release_apt) apartment_release(apt);
3042 3043 3044
      return hres;
    }

3045 3046
    /* First try in-process server */
    if (CLSCTX_INPROC_SERVER & dwClsContext)
3047 3048 3049 3050
    {
        static const WCHAR wszInprocServer32[] = {'I','n','p','r','o','c','S','e','r','v','e','r','3','2',0};
        HKEY hkey;

3051 3052
        hres = COM_OpenKeyForCLSID(rclsid, wszInprocServer32, KEY_READ, &hkey);
        if (FAILED(hres))
3053
        {
3054 3055
            if (hres == REGDB_E_CLASSNOTREG)
                ERR("class %s not registered\n", debugstr_guid(rclsid));
3056 3057
            else if (hres == REGDB_E_KEYMISSING)
            {
3058
                WARN("class %s not registered as in-proc server\n", debugstr_guid(rclsid));
3059 3060
                hres = REGDB_E_CLASSNOTREG;
            }
3061 3062 3063 3064
        }

        if (SUCCEEDED(hres))
        {
3065 3066 3067 3068
            clsreg.u.hkey = hkey;
            clsreg.hkey = TRUE;

            hres = get_inproc_class_object(apt, &clsreg, rclsid, iid, !(dwClsContext & WINE_CLSCTX_DONT_HOST), ppv);
3069 3070 3071 3072 3073 3074
            RegCloseKey(hkey);
        }

        /* return if we got a class, otherwise fall through to one of the
         * other types */
        if (SUCCEEDED(hres))
3075 3076
        {
            if (release_apt) apartment_release(apt);
3077
            return hres;
3078
        }
3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091
    }

    /* Next try in-process handler */
    if (CLSCTX_INPROC_HANDLER & dwClsContext)
    {
        static const WCHAR wszInprocHandler32[] = {'I','n','p','r','o','c','H','a','n','d','l','e','r','3','2',0};
        HKEY hkey;

        hres = COM_OpenKeyForCLSID(rclsid, wszInprocHandler32, KEY_READ, &hkey);
        if (FAILED(hres))
        {
            if (hres == REGDB_E_CLASSNOTREG)
                ERR("class %s not registered\n", debugstr_guid(rclsid));
3092 3093
            else if (hres == REGDB_E_KEYMISSING)
            {
3094
                WARN("class %s not registered in-proc handler\n", debugstr_guid(rclsid));
3095 3096
                hres = REGDB_E_CLASSNOTREG;
            }
3097
        }
3098

3099
        if (SUCCEEDED(hres))
3100
        {
3101 3102 3103 3104
            clsreg.u.hkey = hkey;
            clsreg.hkey = TRUE;

            hres = get_inproc_class_object(apt, &clsreg, rclsid, iid, !(dwClsContext & WINE_CLSCTX_DONT_HOST), ppv);
3105
            RegCloseKey(hkey);
3106
        }
3107 3108 3109 3110

        /* return if we got a class, otherwise fall through to one of the
         * other types */
        if (SUCCEEDED(hres))
3111 3112
        {
            if (release_apt) apartment_release(apt);
3113
            return hres;
3114
        }
3115
    }
3116
    if (release_apt) apartment_release(apt);
3117

3118
    /* Next try out of process */
3119 3120
    if (CLSCTX_LOCAL_SERVER & dwClsContext)
    {
3121 3122 3123
        hres = RPC_GetLocalClassObject(rclsid,iid,ppv);
        if (SUCCEEDED(hres))
            return hres;
3124
    }
3125

3126
    /* Finally try remote: this requires networked DCOM (a lot of work) */
3127 3128 3129
    if (CLSCTX_REMOTE_SERVER & dwClsContext)
    {
        FIXME ("CLSCTX_REMOTE_SERVER not supported\n");
3130
        hres = REGDB_E_CLASSNOTREG;
3131 3132
    }

3133
    if (FAILED(hres))
3134
        ERR("no class object %s could be created for context 0x%x\n",
3135
            debugstr_guid(rclsid), dwClsContext);
Alexandre Julliard's avatar
Alexandre Julliard committed
3136 3137
    return hres;
}
3138

3139
/***********************************************************************
3140
 *        CoResumeClassObjects (OLE32.@)
3141
 *
3142 3143 3144 3145 3146
 * Resumes all class objects registered with REGCLS_SUSPENDED.
 *
 * RETURNS
 *  Success: S_OK.
 *  Failure: HRESULT code.
3147 3148 3149
 */
HRESULT WINAPI CoResumeClassObjects(void)
{
3150
       FIXME("stub\n");
3151 3152 3153
	return S_OK;
}

Alexandre Julliard's avatar
Alexandre Julliard committed
3154
/***********************************************************************
3155
 *           CoCreateInstance [OLE32.@]
3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183
 *
 * Creates an instance of the specified class.
 *
 * PARAMS
 *  rclsid       [I] Class ID to create an instance of.
 *  pUnkOuter    [I] Optional outer unknown to allow aggregation with another object.
 *  dwClsContext [I] Flags to restrict the location of the created instance.
 *  iid          [I] The ID of the interface of the instance to return.
 *  ppv          [O] On returns, contains a pointer to the specified interface of the instance.
 *
 * RETURNS
 *  Success: S_OK
 *  Failure: HRESULT code.
 *
 * NOTES
 *  The dwClsContext parameter can be one or more of the following:
 *| CLSCTX_INPROC_SERVER - Use an in-process server, such as from a DLL.
 *| CLSCTX_INPROC_HANDLER - Use an in-process object which handles certain functions for an object running in another process.
 *| CLSCTX_LOCAL_SERVER - Connect to an object running in another process.
 *| CLSCTX_REMOTE_SERVER - Connect to an object running on another machine.
 *
 * Aggregation is the concept of deferring the IUnknown of an object to another
 * object. This allows a separate object to behave as though it was part of
 * the object and to allow this the pUnkOuter parameter can be set. Note that
 * not all objects support having an outer of unknown.
 *
 * SEE ALSO
 *  CoGetClassObject()
Alexandre Julliard's avatar
Alexandre Julliard committed
3184
 */
3185
HRESULT WINAPI DECLSPEC_HOTPATCH CoCreateInstance(
Andrew Talbot's avatar
Andrew Talbot committed
3186 3187 3188 3189 3190 3191
    REFCLSID rclsid,
    LPUNKNOWN pUnkOuter,
    DWORD dwClsContext,
    REFIID iid,
    LPVOID *ppv)
{
3192
    MULTI_QI multi_qi = { iid };
Andrew Talbot's avatar
Andrew Talbot committed
3193
    HRESULT hres;
Alexandre Julliard's avatar
Alexandre Julliard committed
3194

Andrew Talbot's avatar
Andrew Talbot committed
3195 3196
    TRACE("(rclsid=%s, pUnkOuter=%p, dwClsContext=%08x, riid=%s, ppv=%p)\n", debugstr_guid(rclsid),
          pUnkOuter, dwClsContext, debugstr_guid(iid), ppv);
3197

Andrew Talbot's avatar
Andrew Talbot committed
3198 3199
    if (ppv==0)
        return E_POINTER;
3200

3201 3202
    hres = CoCreateInstanceEx(rclsid, pUnkOuter, dwClsContext, NULL, 1, &multi_qi);
    *ppv = multi_qi.pItf;
Andrew Talbot's avatar
Andrew Talbot committed
3203
    return hres;
Alexandre Julliard's avatar
Alexandre Julliard committed
3204 3205
}

3206
static void init_multi_qi(DWORD count, MULTI_QI *mqi, HRESULT hr)
3207 3208 3209 3210 3211 3212
{
  ULONG i;

  for (i = 0; i < count; i++)
  {
      mqi[i].pItf = NULL;
3213
      mqi[i].hr = hr;
3214 3215 3216
  }
}

3217
static HRESULT return_multi_qi(IUnknown *unk, DWORD count, MULTI_QI *mqi, BOOL include_unk)
3218
{
3219
  ULONG index = 0, fetched = 0;
3220

3221 3222 3223 3224 3225 3226 3227 3228
  if (include_unk)
  {
    mqi[0].hr = S_OK;
    mqi[0].pItf = unk;
    index = fetched = 1;
  }

  for (; index < count; index++)
3229 3230 3231 3232 3233 3234
  {
    mqi[index].hr = IUnknown_QueryInterface(unk, mqi[index].pIID, (void**)&mqi[index].pItf);
    if (mqi[index].hr == S_OK)
      fetched++;
  }

3235 3236
  if (!include_unk)
      IUnknown_Release(unk);
3237 3238 3239 3240 3241 3242 3243

  if (fetched == 0)
    return E_NOINTERFACE;

  return fetched == count ? S_OK : CO_S_NOTALLINTERFACES;
}

3244
/***********************************************************************
3245
 *           CoCreateInstanceEx [OLE32.@]
3246
 */
3247
HRESULT WINAPI DECLSPEC_HOTPATCH CoCreateInstanceEx(
3248
  REFCLSID      rclsid,
3249
  LPUNKNOWN     pUnkOuter,
3250
  DWORD         dwClsContext,
3251 3252 3253 3254
  COSERVERINFO* pServerInfo,
  ULONG         cmq,
  MULTI_QI*     pResults)
{
3255 3256 3257 3258 3259
    IUnknown *unk = NULL;
    IClassFactory *cf;
    APARTMENT *apt;
    CLSID clsid;
    HRESULT hres;
3260

3261
    TRACE("(%s %p %x %p %u %p)\n", debugstr_guid(rclsid), pUnkOuter, dwClsContext, pServerInfo, cmq, pResults);
3262

3263 3264
    if (!cmq || !pResults)
        return E_INVALIDARG;
3265

3266 3267
    if (pServerInfo)
        FIXME("() non-NULL pServerInfo not supported!\n");
3268

3269
    init_multi_qi(cmq, pResults, E_NOINTERFACE);
3270

3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 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
    hres = CoGetTreatAsClass(rclsid, &clsid);
    if(FAILED(hres))
        clsid = *rclsid;

    if (!(apt = COM_CurrentApt()))
    {
        if (!(apt = apartment_find_multi_threaded()))
        {
            ERR("apartment not initialised\n");
            return CO_E_NOTINITIALIZED;
        }
        apartment_release(apt);
    }

    /*
     * The Standard Global Interface Table (GIT) object is a process-wide singleton.
     */
    if (IsEqualIID(&clsid, &CLSID_StdGlobalInterfaceTable))
    {
        IGlobalInterfaceTable *git = get_std_git();
        TRACE("Retrieving GIT\n");
        return return_multi_qi((IUnknown*)git, cmq, pResults, FALSE);
    }

    if (IsEqualCLSID(&clsid, &CLSID_ManualResetEvent)) {
        hres = ManualResetEvent_Construct(pUnkOuter, pResults[0].pIID, (void**)&unk);
        if (FAILED(hres))
            return hres;
        return return_multi_qi(unk, cmq, pResults, TRUE);
    }

    /*
     * Get a class factory to construct the object we want.
     */
    hres = CoGetClassObject(&clsid, dwClsContext, NULL, &IID_IClassFactory, (void**)&cf);
    if (FAILED(hres))
        return hres;

    /*
     * Create the object and don't forget to release the factory
     */
    hres = IClassFactory_CreateInstance(cf, pUnkOuter, pResults[0].pIID, (void**)&unk);
    IClassFactory_Release(cf);
    if (FAILED(hres))
    {
        if (hres == CLASS_E_NOAGGREGATION && pUnkOuter)
            FIXME("Class %s does not support aggregation\n", debugstr_guid(&clsid));
        else
            FIXME("no instance created for interface %s of class %s, hres is 0x%08x\n",
                  debugstr_guid(pResults[0].pIID),
                  debugstr_guid(&clsid),hres);
        return hres;
    }
3324

3325
    return return_multi_qi(unk, cmq, pResults, TRUE);
3326 3327 3328 3329 3330
}

/***********************************************************************
 *           CoGetInstanceFromFile [OLE32.@]
 */
3331
HRESULT WINAPI DECLSPEC_HOTPATCH CoGetInstanceFromFile(
3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352
  COSERVERINFO *server_info,
  CLSID        *rclsid,
  IUnknown     *outer,
  DWORD         cls_context,
  DWORD         grfmode,
  OLECHAR      *filename,
  DWORD         count,
  MULTI_QI     *results
)
{
  IPersistFile *pf = NULL;
  IUnknown* unk = NULL;
  CLSID clsid;
  HRESULT hr;

  if (count == 0 || !results)
    return E_INVALIDARG;

  if (server_info)
    FIXME("() non-NULL server_info not supported\n");

3353
  init_multi_qi(count, results, E_NOINTERFACE);
3354

3355
  /* optionally get CLSID from a file */
3356
  if (!rclsid)
3357
  {
3358 3359 3360 3361 3362 3363
    hr = GetClassFile(filename, &clsid);
    if (FAILED(hr))
    {
      ERR("failed to get CLSID from a file\n");
      return hr;
    }
3364

3365
    rclsid = &clsid;
3366 3367
  }

3368 3369 3370 3371 3372
  hr = CoCreateInstance(rclsid,
			outer,
			cls_context,
			&IID_IUnknown,
			(void**)&unk);
3373

3374
  if (hr != S_OK)
3375 3376 3377 3378
  {
      init_multi_qi(count, results, hr);
      return hr;
  }
3379

3380 3381 3382 3383
  /* init from file */
  hr = IUnknown_QueryInterface(unk, &IID_IPersistFile, (void**)&pf);
  if (FAILED(hr))
  {
3384 3385 3386
      init_multi_qi(count, results, hr);
      IUnknown_Release(unk);
      return hr;
3387 3388
  }

3389 3390 3391 3392 3393 3394 3395 3396 3397 3398
  hr = IPersistFile_Load(pf, filename, grfmode);
  IPersistFile_Release(pf);
  if (SUCCEEDED(hr))
      return return_multi_qi(unk, count, results, FALSE);
  else
  {
      init_multi_qi(count, results, hr);
      IUnknown_Release(unk);
      return hr;
  }
3399
}
3400

3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424
/***********************************************************************
 *           CoGetInstanceFromIStorage [OLE32.@]
 */
HRESULT WINAPI CoGetInstanceFromIStorage(
  COSERVERINFO *server_info,
  CLSID        *rclsid,
  IUnknown     *outer,
  DWORD         cls_context,
  IStorage     *storage,
  DWORD         count,
  MULTI_QI     *results
)
{
  IPersistStorage *ps = NULL;
  IUnknown* unk = NULL;
  STATSTG stat;
  HRESULT hr;

  if (count == 0 || !results || !storage)
    return E_INVALIDARG;

  if (server_info)
    FIXME("() non-NULL server_info not supported\n");

3425
  init_multi_qi(count, results, E_NOINTERFACE);
3426

3427
  /* optionally get CLSID from a file */
3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460
  if (!rclsid)
  {
    memset(&stat.clsid, 0, sizeof(stat.clsid));
    hr = IStorage_Stat(storage, &stat, STATFLAG_NONAME);
    if (FAILED(hr))
    {
      ERR("failed to get CLSID from a file\n");
      return hr;
    }

    rclsid = &stat.clsid;
  }

  hr = CoCreateInstance(rclsid,
			outer,
			cls_context,
			&IID_IUnknown,
			(void**)&unk);

  if (hr != S_OK)
    return hr;

  /* init from IStorage */
  hr = IUnknown_QueryInterface(unk, &IID_IPersistStorage, (void**)&ps);
  if (FAILED(hr))
      ERR("failed to get IPersistStorage\n");

  if (ps)
  {
      IPersistStorage_Load(ps, storage);
      IPersistStorage_Release(ps);
  }

3461
  return return_multi_qi(unk, count, results, FALSE);
3462 3463
}

Ove Kaaven's avatar
Ove Kaaven committed
3464
/***********************************************************************
3465
 *           CoLoadLibrary (OLE32.@)
3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478
 *
 * Loads a library.
 *
 * PARAMS
 *  lpszLibName [I] Path to library.
 *  bAutoFree   [I] Whether the library should automatically be freed.
 *
 * RETURNS
 *  Success: Handle to loaded library.
 *  Failure: NULL.
 *
 * SEE ALSO
 *  CoFreeLibrary, CoFreeAllLibraries, CoFreeUnusedLibraries
Ove Kaaven's avatar
Ove Kaaven committed
3479
 */
3480
HINSTANCE WINAPI CoLoadLibrary(LPOLESTR lpszLibName, BOOL bAutoFree)
Ove Kaaven's avatar
Ove Kaaven committed
3481
{
3482
    TRACE("(%s, %d)\n", debugstr_w(lpszLibName), bAutoFree);
3483

3484 3485
    return LoadLibraryExW(lpszLibName, 0, LOAD_WITH_ALTERED_SEARCH_PATH);
}
3486

3487
/***********************************************************************
3488
 *           CoFreeLibrary [OLE32.@]
3489
 *
3490 3491 3492 3493 3494 3495 3496 3497 3498 3499
 * Unloads a library from memory.
 *
 * PARAMS
 *  hLibrary [I] Handle to library to unload.
 *
 * RETURNS
 *  Nothing
 *
 * SEE ALSO
 *  CoLoadLibrary, CoFreeAllLibraries, CoFreeUnusedLibraries
3500 3501 3502
 */
void WINAPI CoFreeLibrary(HINSTANCE hLibrary)
{
3503
    FreeLibrary(hLibrary);
3504 3505 3506 3507
}


/***********************************************************************
3508
 *           CoFreeAllLibraries [OLE32.@]
3509
 *
3510 3511 3512 3513 3514 3515 3516
 * Function for backwards compatibility only. Does nothing.
 *
 * RETURNS
 *  Nothing.
 *
 * SEE ALSO
 *  CoLoadLibrary, CoFreeLibrary, CoFreeUnusedLibraries
3517 3518 3519
 */
void WINAPI CoFreeAllLibraries(void)
{
3520
    /* NOP */
Ove Kaaven's avatar
Ove Kaaven committed
3521 3522
}

Alexandre Julliard's avatar
Alexandre Julliard committed
3523
/***********************************************************************
3524
 *           CoFreeUnusedLibrariesEx [OLE32.@]
3525
 *
3526 3527 3528 3529 3530 3531 3532
 * Frees any previously unused libraries whose delay has expired and marks
 * currently unused libraries for unloading. Unused are identified as those that
 * return S_OK from their DllCanUnloadNow function.
 *
 * PARAMS
 *  dwUnloadDelay [I] Unload delay in milliseconds.
 *  dwReserved    [I] Reserved. Set to 0.
3533 3534 3535
 *
 * RETURNS
 *  Nothing.
3536
 *
3537 3538
 * SEE ALSO
 *  CoLoadLibrary, CoFreeAllLibraries, CoFreeLibrary
Alexandre Julliard's avatar
Alexandre Julliard committed
3539
 */
3540
void WINAPI DECLSPEC_HOTPATCH CoFreeUnusedLibrariesEx(DWORD dwUnloadDelay, DWORD dwReserved)
Alexandre Julliard's avatar
Alexandre Julliard committed
3541
{
3542 3543 3544 3545 3546 3547 3548
    struct apartment *apt = COM_CurrentApt();
    if (!apt)
    {
        ERR("apartment not initialised\n");
        return;
    }

3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563
    apartment_freeunusedlibraries(apt, dwUnloadDelay);
}

/***********************************************************************
 *           CoFreeUnusedLibraries [OLE32.@]
 *
 * Frees any unused libraries. Unused are identified as those that return
 * S_OK from their DllCanUnloadNow function.
 *
 * RETURNS
 *  Nothing.
 *
 * SEE ALSO
 *  CoLoadLibrary, CoFreeAllLibraries, CoFreeLibrary
 */
3564
void WINAPI DECLSPEC_HOTPATCH CoFreeUnusedLibraries(void)
3565 3566
{
    CoFreeUnusedLibrariesEx(INFINITE, 0);
Alexandre Julliard's avatar
Alexandre Julliard committed
3567 3568 3569
}

/***********************************************************************
3570
 *           CoFileTimeNow [OLE32.@]
3571 3572 3573 3574 3575
 *
 * Retrieves the current time in FILETIME format.
 *
 * PARAMS
 *  lpFileTime [O] The current time.
Patrik Stridvall's avatar
Patrik Stridvall committed
3576
 *
Alexandre Julliard's avatar
Alexandre Julliard committed
3577
 * RETURNS
3578
 *	S_OK.
Alexandre Julliard's avatar
Alexandre Julliard committed
3579
 */
3580
HRESULT WINAPI CoFileTimeNow( FILETIME *lpFileTime )
3581 3582 3583
{
    GetSystemTimeAsFileTime( lpFileTime );
    return S_OK;
Alexandre Julliard's avatar
Alexandre Julliard committed
3584
}
Alexandre Julliard's avatar
Alexandre Julliard committed
3585

3586
/******************************************************************************
3587
 *		CoLockObjectExternal	[OLE32.@]
3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600
 *
 * Increments or decrements the external reference count of a stub object.
 *
 * PARAMS
 *  pUnk                [I] Stub object.
 *  fLock               [I] If TRUE then increments the external ref-count,
 *                          otherwise decrements.
 *  fLastUnlockReleases [I] If TRUE then the last unlock has the effect of
 *                          calling CoDisconnectObject.
 *
 * RETURNS
 *  Success: S_OK.
 *  Failure: HRESULT code.
3601 3602 3603 3604
 *
 * NOTES
 *  If fLock is TRUE and an object is passed in that doesn't have a stub
 *  manager then a new stub manager is created for the object.
3605
 */
3606
HRESULT WINAPI CoLockObjectExternal(
3607 3608 3609
    LPUNKNOWN pUnk,
    BOOL fLock,
    BOOL fLastUnlockReleases)
3610
{
3611 3612 3613
    struct stub_manager *stubmgr;
    struct apartment *apt;

3614 3615
    TRACE("pUnk=%p, fLock=%s, fLastUnlockReleases=%s\n",
          pUnk, fLock ? "TRUE" : "FALSE", fLastUnlockReleases ? "TRUE" : "FALSE");
3616

3617 3618 3619
    apt = COM_CurrentApt();
    if (!apt) return CO_E_NOTINITIALIZED;

3620 3621
    stubmgr = get_stub_manager_from_object(apt, pUnk, fLock);
    if (!stubmgr)
3622 3623 3624 3625 3626 3627 3628
    {
        WARN("stub object not found %p\n", pUnk);
        /* Note: native is pretty broken here because it just silently
         * fails, without returning an appropriate error code, making apps
         * think that the object was disconnected, when it actually wasn't */
        return S_OK;
    }
3629 3630 3631 3632 3633 3634 3635 3636

    if (fLock)
        stub_manager_ext_addref(stubmgr, 1, FALSE);
    else
        stub_manager_ext_release(stubmgr, 1, FALSE, fLastUnlockReleases);

    stub_manager_int_release(stubmgr);
    return S_OK;
3637 3638
}

3639
/***********************************************************************
3640
 *           CoInitializeWOW (OLE32.@)
3641 3642 3643 3644 3645 3646 3647 3648 3649
 *
 * WOW equivalent of CoInitialize?
 *
 * PARAMS
 *  x [I] Unknown.
 *  y [I] Unknown.
 *
 * RETURNS
 *  Unknown.
3650
 */
3651 3652
HRESULT WINAPI CoInitializeWOW(DWORD x,DWORD y)
{
3653
    FIXME("(0x%08x,0x%08x),stub!\n",x,y);
3654
    return 0;
3655 3656
}

3657
/***********************************************************************
3658
 *           CoGetState [OLE32.@]
3659
 *
3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675
 * Retrieves the thread state object previously stored by CoSetState().
 *
 * PARAMS
 *  ppv [I] Address where pointer to object will be stored.
 *
 * RETURNS
 *  Success: S_OK.
 *  Failure: E_OUTOFMEMORY.
 *
 * NOTES
 *  Crashes on all invalid ppv addresses, including NULL.
 *  If the function returns a non-NULL object then the caller must release its
 *  reference on the object when the object is no longer required.
 *
 * SEE ALSO
 *  CoSetState().
3676
 */
3677
HRESULT WINAPI CoGetState(IUnknown ** ppv)
3678
{
3679 3680
    struct oletls *info = COM_CurrentInfo();
    if (!info) return E_OUTOFMEMORY;
3681

3682
    *ppv = NULL;
3683

3684
    if (info->state)
3685
    {
3686 3687 3688
        IUnknown_AddRef(info->state);
        *ppv = info->state;
        TRACE("apt->state=%p\n", info->state);
3689
    }
3690

3691
    return S_OK;
3692
}
3693 3694

/***********************************************************************
3695
 *           CoSetState [OLE32.@]
3696
 *
3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707
 * Sets the thread state object.
 *
 * PARAMS
 *  pv [I] Pointer to state object to be stored.
 *
 * NOTES
 *  The system keeps a reference on the object while the object stored.
 *
 * RETURNS
 *  Success: S_OK.
 *  Failure: E_OUTOFMEMORY.
3708
 */
3709
HRESULT WINAPI CoSetState(IUnknown * pv)
3710
{
3711 3712 3713
    struct oletls *info = COM_CurrentInfo();
    if (!info) return E_OUTOFMEMORY;

3714
    if (pv) IUnknown_AddRef(pv);
3715

3716
    if (info->state)
3717
    {
3718 3719
        TRACE("-- release %p now\n", info->state);
        IUnknown_Release(info->state);
3720
    }
3721

3722
    info->state = pv;
3723

3724
    return S_OK;
3725
}
3726

3727

3728
/******************************************************************************
3729
 *              CoTreatAsClass        [OLE32.@]
3730
 *
3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742
 * Sets the TreatAs value of a class.
 *
 * PARAMS
 *  clsidOld [I] Class to set TreatAs value on.
 *  clsidNew [I] The class the clsidOld should be treated as.
 *
 * RETURNS
 *  Success: S_OK.
 *  Failure: HRESULT code.
 *
 * SEE ALSO
 *  CoGetTreatAsClass
3743 3744 3745
 */
HRESULT WINAPI CoTreatAsClass(REFCLSID clsidOld, REFCLSID clsidNew)
{
3746 3747 3748 3749
    static const WCHAR wszAutoTreatAs[] = {'A','u','t','o','T','r','e','a','t','A','s',0};
    static const WCHAR wszTreatAs[] = {'T','r','e','a','t','A','s',0};
    HKEY hkey = NULL;
    WCHAR szClsidNew[CHARS_IN_GUID];
3750
    HRESULT res = S_OK;
3751
    WCHAR auto_treat_as[CHARS_IN_GUID];
3752 3753
    LONG auto_treat_as_size = sizeof(auto_treat_as);
    CLSID id;
3754

3755 3756 3757
    res = COM_OpenKeyForCLSID(clsidOld, NULL, KEY_READ | KEY_WRITE, &hkey);
    if (FAILED(res))
        goto done;
3758 3759

    if (IsEqualGUID( clsidOld, clsidNew ))
3760
    {
3761
       if (!RegQueryValueW(hkey, wszAutoTreatAs, auto_treat_as, &auto_treat_as_size) &&
3762
           CLSIDFromString(auto_treat_as, &id) == S_OK)
3763
       {
3764
           if (RegSetValueW(hkey, wszTreatAs, REG_SZ, auto_treat_as, sizeof(auto_treat_as)))
3765 3766 3767 3768 3769 3770 3771
           {
               res = REGDB_E_WRITEREGDB;
               goto done;
           }
       }
       else
       {
3772 3773
           if(RegDeleteKeyW(hkey, wszTreatAs))
               res = REGDB_E_WRITEREGDB;
3774 3775 3776
           goto done;
       }
    }
3777
    else
3778
    {
3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793
        if(IsEqualGUID(clsidNew, &CLSID_NULL)){
           RegDeleteKeyW(hkey, wszTreatAs);
        }else{
            if(!StringFromGUID2(clsidNew, szClsidNew, ARRAYSIZE(szClsidNew))){
                WARN("StringFromGUID2 failed\n");
                res = E_FAIL;
                goto done;
            }

            if(RegSetValueW(hkey, wszTreatAs, REG_SZ, szClsidNew, sizeof(szClsidNew)) != ERROR_SUCCESS){
                WARN("RegSetValue failed\n");
                res = REGDB_E_WRITEREGDB;
                goto done;
            }
        }
3794 3795 3796 3797 3798
    }

done:
    if (hkey) RegCloseKey(hkey);
    return res;
3799
}
3800

3801
/******************************************************************************
3802
 *              CoGetTreatAsClass        [OLE32.@]
3803
 *
3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815
 * Gets the TreatAs value of a class.
 *
 * PARAMS
 *  clsidOld [I] Class to get the TreatAs value of.
 *  clsidNew [I] The class the clsidOld should be treated as.
 *
 * RETURNS
 *  Success: S_OK.
 *  Failure: HRESULT code.
 *
 * SEE ALSO
 *  CoSetTreatAsClass
3816 3817 3818
 */
HRESULT WINAPI CoGetTreatAsClass(REFCLSID clsidOld, LPCLSID clsidNew)
{
3819 3820 3821
    static const WCHAR wszTreatAs[] = {'T','r','e','a','t','A','s',0};
    HKEY hkey = NULL;
    WCHAR szClsidNew[CHARS_IN_GUID];
3822 3823 3824
    HRESULT res = S_OK;
    LONG len = sizeof(szClsidNew);

3825
    TRACE("(%s,%p)\n", debugstr_guid(clsidOld), clsidNew);
3826
    *clsidNew = *clsidOld; /* copy over old value */
3827

3828 3829
    res = COM_OpenKeyForCLSID(clsidOld, wszTreatAs, KEY_READ, &hkey);
    if (FAILED(res))
3830 3831
    {
        res = S_FALSE;
3832
        goto done;
3833
    }
3834
    if (RegQueryValueW(hkey, NULL, szClsidNew, &len))
3835 3836 3837 3838
    {
        res = S_FALSE;
	goto done;
    }
3839
    res = CLSIDFromString(szClsidNew,clsidNew);
3840
    if (FAILED(res))
3841
        ERR("Failed CLSIDFromStringA(%s), hres 0x%08x\n", debugstr_w(szClsidNew), res);
3842 3843 3844 3845
done:
    if (hkey) RegCloseKey(hkey);
    return res;
}
3846

3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862
/******************************************************************************
 *		CoGetCurrentProcess	[OLE32.@]
 *
 * Gets the current process ID.
 *
 * RETURNS
 *  The current process ID.
 *
 * NOTES
 *   Is DWORD really the correct return type for this function?
 */
DWORD WINAPI CoGetCurrentProcess(void)
{
	return GetCurrentProcessId();
}

3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876
/***********************************************************************
 *              CoGetCurrentLogicalThreadId        [OLE32.@]
 */
HRESULT WINAPI CoGetCurrentLogicalThreadId(GUID *id)
{
    TRACE("(%p)\n", id);

    if (!id)
        return E_INVALIDARG;

    *id = COM_CurrentCausalityId();
    return S_OK;
}

3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888
/******************************************************************************
 *		CoRegisterMessageFilter	[OLE32.@]
 *
 * Registers a message filter.
 *
 * PARAMS
 *  lpMessageFilter [I] Pointer to interface.
 *  lplpMessageFilter [O] Indirect pointer to prior instance if non-NULL.
 *
 * RETURNS
 *  Success: S_OK.
 *  Failure: HRESULT code.
3889 3890 3891 3892 3893 3894 3895 3896 3897 3898
 *
 * NOTES
 *  Both lpMessageFilter and lplpMessageFilter are optional. Passing in a NULL
 *  lpMessageFilter removes the message filter.
 *
 *  If lplpMessageFilter is not NULL the previous message filter will be
 *  returned in the memory pointer to this parameter and the caller is
 *  responsible for releasing the object.
 *
 *  The current thread be in an apartment otherwise the function will crash.
3899 3900 3901 3902 3903
 */
HRESULT WINAPI CoRegisterMessageFilter(
    LPMESSAGEFILTER lpMessageFilter,
    LPMESSAGEFILTER *lplpMessageFilter)
{
3904 3905 3906 3907 3908 3909 3910 3911
    struct apartment *apt;
    IMessageFilter *lpOldMessageFilter;

    TRACE("(%p, %p)\n", lpMessageFilter, lplpMessageFilter);

    apt = COM_CurrentApt();

    /* can't set a message filter in a multi-threaded apartment */
3912
    if (!apt || apt->multi_threaded)
3913
    {
3914
        WARN("can't set message filter in MTA or uninitialized apt\n");
3915
        return CO_E_NOT_SUPPORTED;
3916
    }
3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932

    if (lpMessageFilter)
        IMessageFilter_AddRef(lpMessageFilter);

    EnterCriticalSection(&apt->cs);

    lpOldMessageFilter = apt->filter;
    apt->filter = lpMessageFilter;

    LeaveCriticalSection(&apt->cs);

    if (lplpMessageFilter)
        *lplpMessageFilter = lpOldMessageFilter;
    else if (lpOldMessageFilter)
        IMessageFilter_Release(lpOldMessageFilter);

3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952
    return S_OK;
}

/***********************************************************************
 *           CoIsOle1Class [OLE32.@]
 *
 * Determines whether the specified class an OLE v1 class.
 *
 * PARAMS
 *  clsid [I] Class to test.
 *
 * RETURNS
 *  TRUE if the class is an OLE v1 class, or FALSE otherwise.
 */
BOOL WINAPI CoIsOle1Class(REFCLSID clsid)
{
  FIXME("%s\n", debugstr_guid(clsid));
  return FALSE;
}

3953
/***********************************************************************
3954
 *           IsEqualGUID [OLE32.@]
3955 3956 3957
 *
 * Compares two Unique Identifiers.
 *
3958 3959 3960 3961
 * PARAMS
 *  rguid1 [I] The first GUID to compare.
 *  rguid2 [I] The other GUID to compare.
 *
3962 3963 3964 3965 3966
 * RETURNS
 *	TRUE if equal
 */
#undef IsEqualGUID
BOOL WINAPI IsEqualGUID(
3967 3968
     REFGUID rguid1,
     REFGUID rguid2)
3969 3970 3971
{
    return !memcmp(rguid1,rguid2,sizeof(GUID));
}
3972 3973

/***********************************************************************
3974
 *           CoInitializeSecurity [OLE32.@]
3975 3976 3977 3978 3979 3980 3981
 */
HRESULT WINAPI CoInitializeSecurity(PSECURITY_DESCRIPTOR pSecDesc, LONG cAuthSvc,
                                    SOLE_AUTHENTICATION_SERVICE* asAuthSvc,
                                    void* pReserved1, DWORD dwAuthnLevel,
                                    DWORD dwImpLevel, void* pReserved2,
                                    DWORD dwCapabilities, void* pReserved3)
{
3982
  FIXME("(%p,%d,%p,%p,%d,%d,%p,%d,%p) - stub!\n", pSecDesc, cAuthSvc,
3983 3984 3985 3986
        asAuthSvc, pReserved1, dwAuthnLevel, dwImpLevel, pReserved2,
        dwCapabilities, pReserved3);
  return S_OK;
}
3987 3988 3989

/***********************************************************************
 *           CoSuspendClassObjects [OLE32.@]
3990 3991 3992 3993 3994 3995 3996
 *
 * Suspends all registered class objects to prevent further requests coming in
 * for those objects.
 *
 * RETURNS
 *  Success: S_OK.
 *  Failure: HRESULT code.
3997 3998 3999 4000 4001 4002
 */
HRESULT WINAPI CoSuspendClassObjects(void)
{
    FIXME("\n");
    return S_OK;
}
4003 4004 4005

/***********************************************************************
 *           CoAddRefServerProcess [OLE32.@]
4006 4007 4008 4009 4010 4011
 *
 * Helper function for incrementing the reference count of a local-server
 * process.
 *
 * RETURNS
 *  New reference count.
4012 4013 4014
 *
 * SEE ALSO
 *  CoReleaseServerProcess().
4015 4016 4017
 */
ULONG WINAPI CoAddRefServerProcess(void)
{
4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028
    ULONG refs;

    TRACE("\n");

    EnterCriticalSection(&csRegisteredClassList);
    refs = ++s_COMServerProcessReferences;
    LeaveCriticalSection(&csRegisteredClassList);

    TRACE("refs before: %d\n", refs - 1);

    return refs;
4029 4030 4031 4032
}

/***********************************************************************
 *           CoReleaseServerProcess [OLE32.@]
4033 4034 4035 4036 4037 4038
 *
 * Helper function for decrementing the reference count of a local-server
 * process.
 *
 * RETURNS
 *  New reference count.
4039 4040 4041 4042 4043 4044 4045
 *
 * NOTES
 *  When reference count reaches 0, this function suspends all registered
 *  classes so no new connections are accepted.
 *
 * SEE ALSO
 *  CoAddRefServerProcess(), CoSuspendClassObjects().
4046 4047 4048
 */
ULONG WINAPI CoReleaseServerProcess(void)
{
4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062
    ULONG refs;

    TRACE("\n");

    EnterCriticalSection(&csRegisteredClassList);

    refs = --s_COMServerProcessReferences;
    /* FIXME: if (!refs) COM_SuspendClassObjects(); */

    LeaveCriticalSection(&csRegisteredClassList);

    TRACE("refs after: %d\n", refs);

    return refs;
4063
}
4064

4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082
/***********************************************************************
 *           CoIsHandlerConnected [OLE32.@]
 *
 * Determines whether a proxy is connected to a remote stub.
 *
 * PARAMS
 *  pUnk [I] Pointer to object that may or may not be connected.
 *
 * RETURNS
 *  TRUE if pUnk is not a proxy or if pUnk is connected to a remote stub, or
 *  FALSE otherwise.
 */
BOOL WINAPI CoIsHandlerConnected(IUnknown *pUnk)
{
    FIXME("%p\n", pUnk);

    return TRUE;
}
4083 4084 4085 4086 4087 4088 4089 4090 4091 4092

/***********************************************************************
 *           CoAllowSetForegroundWindow [OLE32.@]
 *
 */
HRESULT WINAPI CoAllowSetForegroundWindow(IUnknown *pUnk, void *pvReserved)
{
    FIXME("(%p, %p): stub\n", pUnk, pvReserved);
    return S_OK;
}
4093
 
4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126
/***********************************************************************
 *           CoQueryProxyBlanket [OLE32.@]
 *
 * Retrieves the security settings being used by a proxy.
 *
 * PARAMS
 *  pProxy        [I] Pointer to the proxy object.
 *  pAuthnSvc     [O] The type of authentication service.
 *  pAuthzSvc     [O] The type of authorization service.
 *  ppServerPrincName [O] Optional. The server prinicple name.
 *  pAuthnLevel   [O] The authentication level.
 *  pImpLevel     [O] The impersonation level.
 *  ppAuthInfo    [O] Information specific to the authorization/authentication service.
 *  pCapabilities [O] Flags affecting the security behaviour.
 *
 * RETURNS
 *  Success: S_OK.
 *  Failure: HRESULT code.
 *
 * SEE ALSO
 *  CoCopyProxy, CoSetProxyBlanket.
 */
HRESULT WINAPI CoQueryProxyBlanket(IUnknown *pProxy, DWORD *pAuthnSvc,
    DWORD *pAuthzSvc, OLECHAR **ppServerPrincName, DWORD *pAuthnLevel,
    DWORD *pImpLevel, void **ppAuthInfo, DWORD *pCapabilities)
{
    IClientSecurity *pCliSec;
    HRESULT hr;

    TRACE("%p\n", pProxy);

    hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
    if (SUCCEEDED(hr))
4127
    {
4128 4129 4130 4131
        hr = IClientSecurity_QueryBlanket(pCliSec, pProxy, pAuthnSvc,
                                          pAuthzSvc, ppServerPrincName,
                                          pAuthnLevel, pImpLevel, ppAuthInfo,
                                          pCapabilities);
4132 4133
        IClientSecurity_Release(pCliSec);
    }
4134

4135
    if (FAILED(hr)) ERR("-- failed with 0x%08x\n", hr);
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
    return hr;
}

/***********************************************************************
 *           CoSetProxyBlanket [OLE32.@]
 *
 * Sets the security settings for a proxy.
 *
 * PARAMS
 *  pProxy       [I] Pointer to the proxy object.
 *  AuthnSvc     [I] The type of authentication service.
 *  AuthzSvc     [I] The type of authorization service.
 *  pServerPrincName [I] The server prinicple name.
 *  AuthnLevel   [I] The authentication level.
 *  ImpLevel     [I] The impersonation level.
 *  pAuthInfo    [I] Information specific to the authorization/authentication service.
 *  Capabilities [I] Flags affecting the security behaviour.
 *
 * RETURNS
 *  Success: S_OK.
 *  Failure: HRESULT code.
 *
 * SEE ALSO
 *  CoQueryProxyBlanket, CoCopyProxy.
 */
HRESULT WINAPI CoSetProxyBlanket(IUnknown *pProxy, DWORD AuthnSvc,
    DWORD AuthzSvc, OLECHAR *pServerPrincName, DWORD AuthnLevel,
    DWORD ImpLevel, void *pAuthInfo, DWORD Capabilities)
{
    IClientSecurity *pCliSec;
    HRESULT hr;

    TRACE("%p\n", pProxy);

    hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
    if (SUCCEEDED(hr))
4172
    {
4173 4174 4175 4176
        hr = IClientSecurity_SetBlanket(pCliSec, pProxy, AuthnSvc,
                                        AuthzSvc, pServerPrincName,
                                        AuthnLevel, ImpLevel, pAuthInfo,
                                        Capabilities);
4177 4178
        IClientSecurity_Release(pCliSec);
    }
4179

4180
    if (FAILED(hr)) ERR("-- failed with 0x%08x\n", hr);
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
    return hr;
}

/***********************************************************************
 *           CoCopyProxy [OLE32.@]
 *
 * Copies a proxy.
 *
 * PARAMS
 *  pProxy [I] Pointer to the proxy object.
 *  ppCopy [O] Copy of the proxy.
 *
 * RETURNS
 *  Success: S_OK.
 *  Failure: HRESULT code.
 *
 * SEE ALSO
 *  CoQueryProxyBlanket, CoSetProxyBlanket.
 */
HRESULT WINAPI CoCopyProxy(IUnknown *pProxy, IUnknown **ppCopy)
{
    IClientSecurity *pCliSec;
    HRESULT hr;

    TRACE("%p\n", pProxy);

    hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
    if (SUCCEEDED(hr))
4209
    {
4210
        hr = IClientSecurity_CopyProxy(pCliSec, pProxy, ppCopy);
4211 4212
        IClientSecurity_Release(pCliSec);
    }
4213

4214
    if (FAILED(hr)) ERR("-- failed with 0x%08x\n", hr);
4215 4216
    return hr;
}
4217 4218


4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234
/***********************************************************************
 *           CoGetCallContext [OLE32.@]
 *
 * Gets the context of the currently executing server call in the current
 * thread.
 *
 * PARAMS
 *  riid [I] Context interface to return.
 *  ppv  [O] Pointer to memory that will receive the context on return.
 *
 * RETURNS
 *  Success: S_OK.
 *  Failure: HRESULT code.
 */
HRESULT WINAPI CoGetCallContext(REFIID riid, void **ppv)
{
4235
    struct oletls *info = COM_CurrentInfo();
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
    TRACE("(%s, %p)\n", debugstr_guid(riid), ppv);

    if (!info)
        return E_OUTOFMEMORY;

    if (!info->call_state)
        return RPC_E_CALL_COMPLETE;

    return IUnknown_QueryInterface(info->call_state, riid, ppv);
}

/***********************************************************************
 *           CoSwitchCallContext [OLE32.@]
 *
 * Switches the context of the currently executing server call in the current
 * thread.
 *
 * PARAMS
 *  pObject     [I] Pointer to new context object
 *  ppOldObject [O] Pointer to memory that will receive old context object pointer
 *
 * RETURNS
 *  Success: S_OK.
 *  Failure: HRESULT code.
 */
HRESULT WINAPI CoSwitchCallContext(IUnknown *pObject, IUnknown **ppOldObject)
{
    struct oletls *info = COM_CurrentInfo();

    TRACE("(%p, %p)\n", pObject, ppOldObject);

    if (!info)
        return E_OUTOFMEMORY;

    *ppOldObject = info->call_state;
    info->call_state = pObject; /* CoSwitchCallContext does not addref nor release objects */

    return S_OK;
4275 4276 4277 4278 4279 4280 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 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397
}

/***********************************************************************
 *           CoQueryClientBlanket [OLE32.@]
 *
 * Retrieves the authentication information about the client of the currently
 * executing server call in the current thread.
 *
 * PARAMS
 *  pAuthnSvc     [O] Optional. The type of authentication service.
 *  pAuthzSvc     [O] Optional. The type of authorization service.
 *  pServerPrincName [O] Optional. The server prinicple name.
 *  pAuthnLevel   [O] Optional. The authentication level.
 *  pImpLevel     [O] Optional. The impersonation level.
 *  pPrivs        [O] Optional. Information about the privileges of the client.
 *  pCapabilities [IO] Optional. Flags affecting the security behaviour.
 *
 * RETURNS
 *  Success: S_OK.
 *  Failure: HRESULT code.
 *
 * SEE ALSO
 *  CoImpersonateClient, CoRevertToSelf, CoGetCallContext.
 */
HRESULT WINAPI CoQueryClientBlanket(
    DWORD *pAuthnSvc,
    DWORD *pAuthzSvc,
    OLECHAR **pServerPrincName,
    DWORD *pAuthnLevel,
    DWORD *pImpLevel,
    RPC_AUTHZ_HANDLE *pPrivs,
    DWORD *pCapabilities)
{
    IServerSecurity *pSrvSec;
    HRESULT hr;

    TRACE("(%p, %p, %p, %p, %p, %p, %p)\n",
        pAuthnSvc, pAuthzSvc, pServerPrincName, pAuthnLevel, pImpLevel,
        pPrivs, pCapabilities);

    hr = CoGetCallContext(&IID_IServerSecurity, (void **)&pSrvSec);
    if (SUCCEEDED(hr))
    {
        hr = IServerSecurity_QueryBlanket(
            pSrvSec, pAuthnSvc, pAuthzSvc, pServerPrincName, pAuthnLevel,
            pImpLevel, pPrivs, pCapabilities);
        IServerSecurity_Release(pSrvSec);
    }

    return hr;
}

/***********************************************************************
 *           CoImpersonateClient [OLE32.@]
 *
 * Impersonates the client of the currently executing server call in the
 * current thread.
 *
 * PARAMS
 *  None.
 *
 * RETURNS
 *  Success: S_OK.
 *  Failure: HRESULT code.
 *
 * NOTES
 *  If this function fails then the current thread will not be impersonating
 *  the client and all actions will take place on behalf of the server.
 *  Therefore, it is important to check the return value from this function.
 *
 * SEE ALSO
 *  CoRevertToSelf, CoQueryClientBlanket, CoGetCallContext.
 */
HRESULT WINAPI CoImpersonateClient(void)
{
    IServerSecurity *pSrvSec;
    HRESULT hr;

    TRACE("\n");

    hr = CoGetCallContext(&IID_IServerSecurity, (void **)&pSrvSec);
    if (SUCCEEDED(hr))
    {
        hr = IServerSecurity_ImpersonateClient(pSrvSec);
        IServerSecurity_Release(pSrvSec);
    }

    return hr;
}

/***********************************************************************
 *           CoRevertToSelf [OLE32.@]
 *
 * Ends the impersonation of the client of the currently executing server
 * call in the current thread.
 *
 * PARAMS
 *  None.
 *
 * RETURNS
 *  Success: S_OK.
 *  Failure: HRESULT code.
 *
 * SEE ALSO
 *  CoImpersonateClient, CoQueryClientBlanket, CoGetCallContext.
 */
HRESULT WINAPI CoRevertToSelf(void)
{
    IServerSecurity *pSrvSec;
    HRESULT hr;

    TRACE("\n");

    hr = CoGetCallContext(&IID_IServerSecurity, (void **)&pSrvSec);
    if (SUCCEEDED(hr))
    {
        hr = IServerSecurity_RevertToSelf(pSrvSec);
        IServerSecurity_Release(pSrvSec);
    }

    return hr;
}

4398 4399
static BOOL COM_PeekMessage(struct apartment *apt, MSG *msg)
{
4400
    /* first try to retrieve messages for incoming COM calls to the apartment window */
4401
    return (apt->win && PeekMessageW(msg, apt->win, 0, 0, PM_REMOVE|PM_NOYIELD)) ||
4402
           /* next retrieve other messages necessary for the app to remain responsive */
4403 4404
           PeekMessageW(msg, NULL, WM_DDE_FIRST, WM_DDE_LAST, PM_REMOVE|PM_NOYIELD) ||
           PeekMessageW(msg, NULL, 0, 0, PM_QS_PAINT|PM_QS_SENDMESSAGE|PM_REMOVE|PM_NOYIELD);
4405 4406
}

4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432
/***********************************************************************
 *           CoWaitForMultipleHandles [OLE32.@]
 *
 * Waits for one or more handles to become signaled.
 *
 * PARAMS
 *  dwFlags   [I] Flags. See notes.
 *  dwTimeout [I] Timeout in milliseconds.
 *  cHandles  [I] Number of handles pointed to by pHandles.
 *  pHandles  [I] Handles to wait for.
 *  lpdwindex [O] Index of handle that was signaled.
 *
 * RETURNS
 *  Success: S_OK.
 *  Failure: RPC_S_CALLPENDING on timeout.
 *
 * NOTES
 *
 * The dwFlags parameter can be zero or more of the following:
 *| COWAIT_WAITALL - Wait for all of the handles to become signaled.
 *| COWAIT_ALERTABLE - Allows a queued APC to run during the wait.
 *
 * SEE ALSO
 *  MsgWaitForMultipleObjects, WaitForMultipleObjects.
 */
HRESULT WINAPI CoWaitForMultipleHandles(DWORD dwFlags, DWORD dwTimeout,
4433
    ULONG cHandles, LPHANDLE pHandles, LPDWORD lpdwindex)
4434 4435 4436
{
    HRESULT hr = S_OK;
    DWORD start_time = GetTickCount();
4437 4438
    APARTMENT *apt = COM_CurrentApt();
    BOOL message_loop = apt && !apt->multi_threaded;
4439
    BOOL check_apc = (dwFlags & COWAIT_ALERTABLE) != 0;
4440

4441
    TRACE("(0x%08x, 0x%08x, %d, %p, %p)\n", dwFlags, dwTimeout, cHandles,
4442 4443
        pHandles, lpdwindex);

4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454
    if (!lpdwindex)
        return E_INVALIDARG;

    *lpdwindex = 0;

    if (!pHandles)
        return E_INVALIDARG;

    if (!cHandles)
        return RPC_E_NO_SYNC;

4455 4456 4457 4458
    while (TRUE)
    {
        DWORD now = GetTickCount();
        DWORD res;
4459

4460
        if (now - start_time > dwTimeout)
4461 4462 4463 4464 4465
        {
            hr = RPC_S_CALLPENDING;
            break;
        }

4466 4467
        if (message_loop)
        {
4468 4469
            DWORD wait_flags = ((dwFlags & COWAIT_WAITALL) ? MWMO_WAITALL : 0) |
                    ((dwFlags & COWAIT_ALERTABLE ) ? MWMO_ALERTABLE : 0);
4470 4471

            TRACE("waiting for rpc completion or window message\n");
4472

4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485
            res = WAIT_TIMEOUT;

            if (check_apc)
            {
                res = WaitForMultipleObjectsEx(cHandles, pHandles,
                    (dwFlags & COWAIT_WAITALL) != 0, 0, TRUE);
                check_apc = FALSE;
            }

            if (res == WAIT_TIMEOUT)
                res = MsgWaitForMultipleObjectsEx(cHandles, pHandles,
                    (dwTimeout == INFINITE) ? INFINITE : start_time + dwTimeout - now,
                    QS_SENDMESSAGE | QS_ALLPOSTMESSAGE | QS_PAINT, wait_flags);
4486

4487
            if (res == WAIT_OBJECT_0 + cHandles)  /* messages available */
4488
            {
4489
                MSG msg;
4490
                int count = 0;
4491

4492 4493 4494 4495
                /* call message filter */

                if (COM_CurrentApt()->filter)
                {
4496 4497 4498
                    PENDINGTYPE pendingtype =
                        COM_CurrentInfo()->pending_call_count_server ?
                            PENDINGTYPE_NESTED : PENDINGTYPE_TOPLEVEL;
4499 4500
                    DWORD be_handled = IMessageFilter_MessagePending(
                        COM_CurrentApt()->filter, 0 /* FIXME */,
4501
                        now - start_time, pendingtype);
4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519
                    TRACE("IMessageFilter_MessagePending returned %d\n", be_handled);
                    switch (be_handled)
                    {
                    case PENDINGMSG_CANCELCALL:
                        WARN("call canceled\n");
                        hr = RPC_E_CALL_CANCELED;
                        break;
                    case PENDINGMSG_WAITNOPROCESS:
                    case PENDINGMSG_WAITDEFPROCESS:
                    default:
                        /* FIXME: MSDN is very vague about the difference
                         * between WAITNOPROCESS and WAITDEFPROCESS - there
                         * appears to be none, so it is possibly a left-over
                         * from the 16-bit world. */
                        break;
                    }
                }

4520 4521 4522
                /* some apps (e.g. Visio 2010) don't handle WM_PAINT properly and loop forever,
                 * so after processing 100 messages we go back to checking the wait handles */
                while (count++ < 100 && COM_PeekMessage(apt, &msg))
4523
                {
4524 4525 4526 4527 4528 4529 4530 4531 4532
                    TRACE("received message whilst waiting for RPC: 0x%04x\n", msg.message);
                    TranslateMessage(&msg);
                    DispatchMessageW(&msg);
                    if (msg.message == WM_QUIT)
                    {
                        TRACE("resending WM_QUIT to outer message loop\n");
                        PostQuitMessage(msg.wParam);
                        /* no longer need to process messages */
                        message_loop = FALSE;
4533
                        break;
4534
                    }
4535
                }
4536
                continue;
4537 4538
            }
        }
4539 4540 4541 4542
        else
        {
            TRACE("waiting for rpc completion\n");

4543
            res = WaitForMultipleObjectsEx(cHandles, pHandles, (dwFlags & COWAIT_WAITALL) != 0,
4544
                (dwTimeout == INFINITE) ? INFINITE : start_time + dwTimeout - now,
4545
                (dwFlags & COWAIT_ALERTABLE) != 0);
4546 4547
        }

4548
        switch (res)
4549
        {
4550
        case WAIT_TIMEOUT:
4551 4552
            hr = RPC_S_CALLPENDING;
            break;
4553 4554
        case WAIT_FAILED:
            hr = HRESULT_FROM_WIN32( GetLastError() );
4555
            break;
4556 4557
        default:
            *lpdwindex = res;
4558 4559
            break;
        }
4560
        break;
4561
    }
4562
    TRACE("-- 0x%08x\n", hr);
4563 4564
    return hr;
}
4565

4566 4567 4568 4569

/***********************************************************************
 *           CoGetObject [OLE32.@]
 *
4570
 * Gets the object named by converting the name to a moniker and binding to it.
4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617
 *
 * PARAMS
 *  pszName      [I] String representing the object.
 *  pBindOptions [I] Parameters affecting the binding to the named object.
 *  riid         [I] Interface to bind to on the objecct.
 *  ppv          [O] On output, the interface riid of the object represented
 *                   by pszName.
 *
 * RETURNS
 *  Success: S_OK.
 *  Failure: HRESULT code.
 *
 * SEE ALSO
 *  MkParseDisplayName.
 */
HRESULT WINAPI CoGetObject(LPCWSTR pszName, BIND_OPTS *pBindOptions,
    REFIID riid, void **ppv)
{
    IBindCtx *pbc;
    HRESULT hr;

    *ppv = NULL;

    hr = CreateBindCtx(0, &pbc);
    if (SUCCEEDED(hr))
    {
        if (pBindOptions)
            hr = IBindCtx_SetBindOptions(pbc, pBindOptions);

        if (SUCCEEDED(hr))
        {
            ULONG chEaten;
            IMoniker *pmk;

            hr = MkParseDisplayName(pbc, pszName, &chEaten, &pmk);
            if (SUCCEEDED(hr))
            {
                hr = IMoniker_BindToObject(pmk, pbc, NULL, riid, ppv);
                IMoniker_Release(pmk);
            }
        }

        IBindCtx_Release(pbc);
    }
    return hr;
}

4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637
/***********************************************************************
 *           CoRegisterChannelHook [OLE32.@]
 *
 * Registers a process-wide hook that is called during ORPC calls.
 *
 * PARAMS
 *  guidExtension [I] GUID of the channel hook to register.
 *  pChannelHook  [I] Channel hook object to register.
 *
 * RETURNS
 *  Success: S_OK.
 *  Failure: HRESULT code.
 */
HRESULT WINAPI CoRegisterChannelHook(REFGUID guidExtension, IChannelHook *pChannelHook)
{
    TRACE("(%s, %p)\n", debugstr_guid(guidExtension), pChannelHook);

    return RPC_RegisterChannelHook(guidExtension, pChannelHook);
}

4638 4639
typedef struct Context
{
4640 4641 4642
    IComThreadingInfo IComThreadingInfo_iface;
    IContextCallback IContextCallback_iface;
    IObjContext IObjContext_iface;
4643 4644 4645
    LONG refs;
} Context;

4646 4647
static inline Context *impl_from_IComThreadingInfo( IComThreadingInfo *iface )
{
4648
        return CONTAINING_RECORD(iface, Context, IComThreadingInfo_iface);
4649 4650 4651 4652
}

static inline Context *impl_from_IContextCallback( IContextCallback *iface )
{
4653
        return CONTAINING_RECORD(iface, Context, IContextCallback_iface);
4654 4655
}

4656 4657
static inline Context *impl_from_IObjContext( IObjContext *iface )
{
4658
        return CONTAINING_RECORD(iface, Context, IObjContext_iface);
4659 4660
}

4661
static HRESULT Context_QueryInterface(Context *iface, REFIID riid, LPVOID *ppv)
4662 4663 4664 4665 4666 4667
{
    *ppv = NULL;

    if (IsEqualIID(riid, &IID_IComThreadingInfo) ||
        IsEqualIID(riid, &IID_IUnknown))
    {
4668
        *ppv = &iface->IComThreadingInfo_iface;
4669 4670
    }
    else if (IsEqualIID(riid, &IID_IContextCallback))
4671
    {
4672
        *ppv = &iface->IContextCallback_iface;
4673
    }
4674 4675
    else if (IsEqualIID(riid, &IID_IObjContext))
    {
4676
        *ppv = &iface->IObjContext_iface;
4677
    }
4678 4679 4680 4681

    if (*ppv)
    {
        IUnknown_AddRef((IUnknown*)*ppv);
4682 4683 4684 4685 4686 4687 4688
        return S_OK;
    }

    FIXME("interface not implemented %s\n", debugstr_guid(riid));
    return E_NOINTERFACE;
}

4689
static ULONG Context_AddRef(Context *This)
4690 4691 4692 4693
{
    return InterlockedIncrement(&This->refs);
}

4694
static ULONG Context_Release(Context *This)
4695
{
4696 4697 4698 4699
    /* Context instance is initially created with CoGetContextToken() with refcount set to 0,
       releasing context while refcount is at 0 destroys it. */
    if (!This->refs)
    {
4700
        HeapFree(GetProcessHeap(), 0, This);
4701 4702 4703 4704
        return 0;
    }

    return InterlockedDecrement(&This->refs);
4705 4706
}

4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725
static HRESULT WINAPI Context_CTI_QueryInterface(IComThreadingInfo *iface, REFIID riid, LPVOID *ppv)
{
    Context *This = impl_from_IComThreadingInfo(iface);
    return Context_QueryInterface(This, riid, ppv);
}

static ULONG WINAPI Context_CTI_AddRef(IComThreadingInfo *iface)
{
    Context *This = impl_from_IComThreadingInfo(iface);
    return Context_AddRef(This);
}

static ULONG WINAPI Context_CTI_Release(IComThreadingInfo *iface)
{
    Context *This = impl_from_IComThreadingInfo(iface);
    return Context_Release(This);
}

static HRESULT WINAPI Context_CTI_GetCurrentApartmentType(IComThreadingInfo *iface, APTTYPE *apttype)
4726
{
4727
    APTTYPEQUALIFIER qualifier;
4728 4729 4730

    TRACE("(%p)\n", apttype);

4731
    return CoGetApartmentType(apttype, &qualifier);
4732 4733
}

4734
static HRESULT WINAPI Context_CTI_GetCurrentThreadType(IComThreadingInfo *iface, THDTYPE *thdtype)
4735
{
4736 4737 4738 4739 4740 4741 4742
    APTTYPEQUALIFIER qualifier;
    APTTYPE apttype;
    HRESULT hr;

    hr = CoGetApartmentType(&apttype, &qualifier);
    if (FAILED(hr))
        return hr;
4743 4744 4745

    TRACE("(%p)\n", thdtype);

4746
    switch (apttype)
4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758
    {
    case APTTYPE_STA:
    case APTTYPE_MAINSTA:
        *thdtype = THDTYPE_PROCESSMESSAGES;
        break;
    default:
        *thdtype = THDTYPE_BLOCKMESSAGES;
        break;
    }
    return S_OK;
}

4759
static HRESULT WINAPI Context_CTI_GetCurrentLogicalThreadId(IComThreadingInfo *iface, GUID *logical_thread_id)
4760
{
4761 4762
    TRACE("(%p)\n", logical_thread_id);
    return CoGetCurrentLogicalThreadId(logical_thread_id);
4763 4764
}

4765
static HRESULT WINAPI Context_CTI_SetCurrentLogicalThreadId(IComThreadingInfo *iface, REFGUID logical_thread_id)
4766 4767 4768 4769 4770 4771 4772
{
    FIXME("(%s): stub\n", debugstr_guid(logical_thread_id));
    return E_NOTIMPL;
}

static const IComThreadingInfoVtbl Context_Threading_Vtbl =
{
4773 4774 4775 4776 4777 4778 4779
    Context_CTI_QueryInterface,
    Context_CTI_AddRef,
    Context_CTI_Release,
    Context_CTI_GetCurrentApartmentType,
    Context_CTI_GetCurrentThreadType,
    Context_CTI_GetCurrentLogicalThreadId,
    Context_CTI_SetCurrentLogicalThreadId
4780 4781
};

4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816
static HRESULT WINAPI Context_CC_QueryInterface(IContextCallback *iface, REFIID riid, LPVOID *ppv)
{
    Context *This = impl_from_IContextCallback(iface);
    return Context_QueryInterface(This, riid, ppv);
}

static ULONG WINAPI Context_CC_AddRef(IContextCallback *iface)
{
    Context *This = impl_from_IContextCallback(iface);
    return Context_AddRef(This);
}

static ULONG WINAPI Context_CC_Release(IContextCallback *iface)
{
    Context *This = impl_from_IContextCallback(iface);
    return Context_Release(This);
}

static HRESULT WINAPI Context_CC_ContextCallback(IContextCallback *iface, PFNCONTEXTCALL pCallback,
                            ComCallData *param, REFIID riid, int method, IUnknown *punk)
{
    Context *This = impl_from_IContextCallback(iface);

    FIXME("(%p/%p)->(%p, %p, %s, %d, %p)\n", This, iface, pCallback, param, debugstr_guid(riid), method, punk);
    return E_NOTIMPL;
}

static const IContextCallbackVtbl Context_Callback_Vtbl =
{
    Context_CC_QueryInterface,
    Context_CC_AddRef,
    Context_CC_Release,
    Context_CC_ContextCallback
};

4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925
static HRESULT WINAPI Context_OC_QueryInterface(IObjContext *iface, REFIID riid, LPVOID *ppv)
{
    Context *This = impl_from_IObjContext(iface);
    return Context_QueryInterface(This, riid, ppv);
}

static ULONG WINAPI Context_OC_AddRef(IObjContext *iface)
{
    Context *This = impl_from_IObjContext(iface);
    return Context_AddRef(This);
}

static ULONG WINAPI Context_OC_Release(IObjContext *iface)
{
    Context *This = impl_from_IObjContext(iface);
    return Context_Release(This);
}

static HRESULT WINAPI Context_OC_SetProperty(IObjContext *iface, REFGUID propid, CPFLAGS flags, IUnknown *punk)
{
    Context *This = impl_from_IObjContext(iface);

    FIXME("(%p/%p)->(%s, %x, %p)\n", This, iface, debugstr_guid(propid), flags, punk);
    return E_NOTIMPL;
}

static HRESULT WINAPI Context_OC_RemoveProperty(IObjContext *iface, REFGUID propid)
{
    Context *This = impl_from_IObjContext(iface);

    FIXME("(%p/%p)->(%s)\n", This, iface, debugstr_guid(propid));
    return E_NOTIMPL;
}

static HRESULT WINAPI Context_OC_GetProperty(IObjContext *iface, REFGUID propid, CPFLAGS *flags, IUnknown **punk)
{
    Context *This = impl_from_IObjContext(iface);

    FIXME("(%p/%p)->(%s, %p, %p)\n", This, iface, debugstr_guid(propid), flags, punk);
    return E_NOTIMPL;
}

static HRESULT WINAPI Context_OC_EnumContextProps(IObjContext *iface, IEnumContextProps **props)
{
    Context *This = impl_from_IObjContext(iface);

    FIXME("(%p/%p)->(%p)\n", This, iface, props);
    return E_NOTIMPL;
}

static void WINAPI Context_OC_Reserved1(IObjContext *iface)
{
    Context *This = impl_from_IObjContext(iface);
    FIXME("(%p/%p)\n", This, iface);
}

static void WINAPI Context_OC_Reserved2(IObjContext *iface)
{
    Context *This = impl_from_IObjContext(iface);
    FIXME("(%p/%p)\n", This, iface);
}

static void WINAPI Context_OC_Reserved3(IObjContext *iface)
{
    Context *This = impl_from_IObjContext(iface);
    FIXME("(%p/%p)\n", This, iface);
}

static void WINAPI Context_OC_Reserved4(IObjContext *iface)
{
    Context *This = impl_from_IObjContext(iface);
    FIXME("(%p/%p)\n", This, iface);
}

static void WINAPI Context_OC_Reserved5(IObjContext *iface)
{
    Context *This = impl_from_IObjContext(iface);
    FIXME("(%p/%p)\n", This, iface);
}

static void WINAPI Context_OC_Reserved6(IObjContext *iface)
{
    Context *This = impl_from_IObjContext(iface);
    FIXME("(%p/%p)\n", This, iface);
}

static void WINAPI Context_OC_Reserved7(IObjContext *iface)
{
    Context *This = impl_from_IObjContext(iface);
    FIXME("(%p/%p)\n", This, iface);
}

static const IObjContextVtbl Context_Object_Vtbl =
{
    Context_OC_QueryInterface,
    Context_OC_AddRef,
    Context_OC_Release,
    Context_OC_SetProperty,
    Context_OC_RemoveProperty,
    Context_OC_GetProperty,
    Context_OC_EnumContextProps,
    Context_OC_Reserved1,
    Context_OC_Reserved2,
    Context_OC_Reserved3,
    Context_OC_Reserved4,
    Context_OC_Reserved5,
    Context_OC_Reserved6,
    Context_OC_Reserved7
};
4926

4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941
/***********************************************************************
 *           CoGetObjectContext [OLE32.@]
 *
 * Retrieves an object associated with the current context (i.e. apartment).
 *
 * PARAMS
 *  riid [I] ID of the interface of the object to retrieve.
 *  ppv  [O] Address where object will be stored on return.
 *
 * RETURNS
 *  Success: S_OK.
 *  Failure: HRESULT code.
 */
HRESULT WINAPI CoGetObjectContext(REFIID riid, void **ppv)
{
4942
    IObjContext *context;
4943 4944 4945 4946 4947
    HRESULT hr;

    TRACE("(%s, %p)\n", debugstr_guid(riid), ppv);

    *ppv = NULL;
4948 4949 4950
    hr = CoGetContextToken((ULONG_PTR*)&context);
    if (FAILED(hr))
        return hr;
4951

4952
    return IObjContext_QueryInterface(context, riid, ppv);
4953 4954
}

4955 4956 4957 4958 4959
/***********************************************************************
 *           CoGetContextToken [OLE32.@]
 */
HRESULT WINAPI CoGetContextToken( ULONG_PTR *token )
{
4960
    struct oletls *info = COM_CurrentInfo();
4961 4962 4963

    TRACE("(%p)\n", token);

4964 4965
    if (!info)
        return E_OUTOFMEMORY;
4966 4967

    if (!info->apt)
4968 4969 4970 4971 4972 4973 4974 4975 4976
    {
        APARTMENT *apt;
        if (!(apt = apartment_find_multi_threaded()))
        {
            ERR("apartment not initialised\n");
            return CO_E_NOTINITIALIZED;
        }
        apartment_release(apt);
    }
4977 4978 4979 4980 4981 4982

    if (!token)
        return E_POINTER;

    if (!info->context_token)
    {
4983 4984 4985 4986 4987 4988 4989 4990 4991
        Context *context;

        context = HeapAlloc(GetProcessHeap(), 0, sizeof(*context));
        if (!context)
            return E_OUTOFMEMORY;

        context->IComThreadingInfo_iface.lpVtbl = &Context_Threading_Vtbl;
        context->IContextCallback_iface.lpVtbl = &Context_Callback_Vtbl;
        context->IObjContext_iface.lpVtbl = &Context_Object_Vtbl;
4992 4993
        /* Context token does not take a reference, it's always zero until the
           interface is explicitly requested with CoGetObjectContext(). */
4994
        context->refs = 0;
4995

4996
        info->context_token = &context->IObjContext_iface;
4997 4998 4999
    }

    *token = (ULONG_PTR)info->context_token;
5000
    TRACE("context_token=%p\n", info->context_token);
5001 5002

    return S_OK;
5003 5004
}

5005 5006 5007 5008 5009 5010 5011 5012 5013
/***********************************************************************
 *           CoGetDefaultContext [OLE32.@]
 */
HRESULT WINAPI CoGetDefaultContext(APTTYPE type, REFIID riid, LPVOID *ppv)
{
    FIXME("%d %s %p stub\n", type, debugstr_guid(riid), ppv);
    return E_NOINTERFACE;
}

5014 5015 5016 5017 5018 5019 5020 5021 5022
HRESULT Handler_DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv)
{
    static const WCHAR wszInprocHandler32[] = {'I','n','p','r','o','c','H','a','n','d','l','e','r','3','2',0};
    HKEY hkey;
    HRESULT hres;

    hres = COM_OpenKeyForCLSID(rclsid, wszInprocHandler32, KEY_READ, &hkey);
    if (SUCCEEDED(hres))
    {
5023
        struct class_reg_data regdata;
5024 5025
        WCHAR dllpath[MAX_PATH+1];

5026 5027 5028 5029
        regdata.u.hkey = hkey;
        regdata.hkey = TRUE;

        if (COM_RegReadPath(&regdata, dllpath, ARRAYSIZE(dllpath)) == ERROR_SUCCESS)
5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044
        {
            static const WCHAR wszOle32[] = {'o','l','e','3','2','.','d','l','l',0};
            if (!strcmpiW(dllpath, wszOle32))
            {
                RegCloseKey(hkey);
                return HandlerCF_Create(rclsid, riid, ppv);
            }
        }
        else
            WARN("not creating object for inproc handler path %s\n", debugstr_w(dllpath));
        RegCloseKey(hkey);
    }

    return CLASS_E_CLASSNOTAVAILABLE;
}
5045

5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074
/***********************************************************************
 *           CoGetApartmentType [OLE32.@]
 */
HRESULT WINAPI CoGetApartmentType(APTTYPE *type, APTTYPEQUALIFIER *qualifier)
{
    struct oletls *info = COM_CurrentInfo();

    FIXME("(%p, %p): semi-stub\n", type, qualifier);

    if (!type || !qualifier)
        return E_INVALIDARG;

    if (!info)
        return E_OUTOFMEMORY;

    if (!info->apt)
        *type = APTTYPE_CURRENT;
    else if (info->apt->multi_threaded)
        *type = APTTYPE_MTA;
    else if (info->apt->main)
        *type = APTTYPE_MAINSTA;
    else
        *type = APTTYPE_STA;

    *qualifier = APTTYPEQUALIFIER_NONE;

    return info->apt ? S_OK : CO_E_NOTINITIALIZED;
}

5075 5076 5077
/***********************************************************************
 *		DllMain (OLE32.@)
 */
5078
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID reserved)
5079
{
5080
    TRACE("%p 0x%x %p\n", hinstDLL, fdwReason, reserved);
5081 5082 5083

    switch(fdwReason) {
    case DLL_PROCESS_ATTACH:
5084
        hProxyDll = hinstDLL;
5085 5086 5087
	break;

    case DLL_PROCESS_DETACH:
5088
        if (reserved) break;
5089
        release_std_git();
5090
        UnregisterClassW( wszAptWinClass, hProxyDll );
5091
        RPC_UnregisterAllChannelHooks();
5092
        COMPOBJ_DllList_Free();
5093 5094
        DeleteCriticalSection(&csRegisteredClassList);
        DeleteCriticalSection(&csApartment);
5095 5096 5097 5098 5099 5100 5101 5102 5103
	break;

    case DLL_THREAD_DETACH:
        COM_TlsDestroy();
        break;
    }
    return TRUE;
}

5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118
/***********************************************************************
 *		DllRegisterServer (OLE32.@)
 */
HRESULT WINAPI DllRegisterServer(void)
{
    return OLE32_DllRegisterServer();
}

/***********************************************************************
 *		DllUnregisterServer (OLE32.@)
 */
HRESULT WINAPI DllUnregisterServer(void)
{
    return OLE32_DllUnregisterServer();
}