4 * Copyright 1995 Martin von Loewis
5 * Copyright 1998 Justin Bradford
6 * Copyright 1999 Francis Beaudet
7 * Copyright 1999 Sylvain St-Germain
8 * Copyright 2002 Marcus Meissner
9 * Copyright 2004 Mike Hearn
10 * Copyright 2005-2006 Robert Shearman (for CodeWeavers)
12 * This library is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Lesser General Public
14 * License as published by the Free Software Foundation; either
15 * version 2.1 of the License, or (at your option) any later version.
17 * This library is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * Lesser General Public License for more details.
22 * You should have received a copy of the GNU Lesser General Public
23 * 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
27 * 1. COINIT_MULTITHREADED is 0; it is the lack of COINIT_APARTMENTTHREADED
28 * Therefore do not test against COINIT_MULTITHREADED
30 * TODO list: (items bunched together depend on each other)
32 * - Implement the service control manager (in rpcss) to keep track
33 * of registered class objects: ISCM::ServerRegisterClsid et al
34 * - Implement the OXID resolver so we don't need magic endpoint names for
35 * clients and servers to meet up
47 #define NONAMELESSUNION
48 #define NONAMELESSSTRUCT
55 #define USE_COM_CONTEXT_DEF
63 #include "compobj_private.h"
66 #include "wine/unicode.h"
67 #include "wine/debug.h"
69 WINE_DEFAULT_DEBUG_CHANNEL(ole);
71 #define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))
73 /****************************************************************************
74 * This section defines variables internal to the COM module.
77 static APARTMENT *MTA; /* protected by csApartment */
78 static APARTMENT *MainApartment; /* the first STA apartment */
79 static struct list apts = LIST_INIT( apts ); /* protected by csApartment */
81 static CRITICAL_SECTION csApartment;
82 static CRITICAL_SECTION_DEBUG critsect_debug =
85 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
86 0, 0, { (DWORD_PTR)(__FILE__ ": csApartment") }
88 static CRITICAL_SECTION csApartment = { &critsect_debug, -1, 0, 0, 0, 0 };
90 struct registered_psclsid
98 * This lock count counts the number of times CoInitialize is called. It is
99 * decreased every time CoUninitialize is called. When it hits 0, the COM
100 * libraries are freed
102 static LONG s_COMLockCount = 0;
103 /* Reference count used by CoAddRefServerProcess/CoReleaseServerProcess */
104 static LONG s_COMServerProcessReferences = 0;
107 * This linked list contains the list of registered class objects. These
108 * are mostly used to register the factories for out-of-proc servers of OLE
111 * TODO: Make this data structure aware of inter-process communication. This
112 * means that parts of this will be exported to rpcss.
114 typedef struct tagRegisteredClass
117 CLSID classIdentifier;
119 LPUNKNOWN classObject;
123 LPSTREAM pMarshaledData; /* FIXME: only really need to store OXID and IPID */
124 void *RpcRegistration;
127 static struct list RegisteredClassList = LIST_INIT(RegisteredClassList);
129 static CRITICAL_SECTION csRegisteredClassList;
130 static CRITICAL_SECTION_DEBUG class_cs_debug =
132 0, 0, &csRegisteredClassList,
133 { &class_cs_debug.ProcessLocksList, &class_cs_debug.ProcessLocksList },
134 0, 0, { (DWORD_PTR)(__FILE__ ": csRegisteredClassList") }
136 static CRITICAL_SECTION csRegisteredClassList = { &class_cs_debug, -1, 0, 0, 0, 0 };
138 /*****************************************************************************
139 * This section contains OpenDllList definitions
141 * The OpenDllList contains only handles of dll loaded by CoGetClassObject or
142 * other functions that do LoadLibrary _without_ giving back a HMODULE.
143 * Without this list these handles would never be freed.
145 * FIXME: a DLL that says OK when asked for unloading is unloaded in the
146 * next unload-call but not before 600 sec.
149 typedef HRESULT (CALLBACK *DllGetClassObjectFunc)(REFCLSID clsid, REFIID iid, LPVOID *ppv);
150 typedef HRESULT (WINAPI *DllCanUnloadNowFunc)(void);
152 typedef struct tagOpenDll
157 DllGetClassObjectFunc DllGetClassObject;
158 DllCanUnloadNowFunc DllCanUnloadNow;
162 static struct list openDllList = LIST_INIT(openDllList);
164 static CRITICAL_SECTION csOpenDllList;
165 static CRITICAL_SECTION_DEBUG dll_cs_debug =
167 0, 0, &csOpenDllList,
168 { &dll_cs_debug.ProcessLocksList, &dll_cs_debug.ProcessLocksList },
169 0, 0, { (DWORD_PTR)(__FILE__ ": csOpenDllList") }
171 static CRITICAL_SECTION csOpenDllList = { &dll_cs_debug, -1, 0, 0, 0, 0 };
173 struct apartment_loaded_dll
181 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',' ',
182 '0','x','#','#','#','#','#','#','#','#',' ',0};
184 /*****************************************************************************
185 * This section contains OpenDllList implementation
188 static OpenDll *COMPOBJ_DllList_Get(LPCWSTR library_name)
192 EnterCriticalSection(&csOpenDllList);
193 LIST_FOR_EACH_ENTRY(ptr, &openDllList, OpenDll, entry)
195 if (!strcmpiW(library_name, ptr->library_name) &&
196 (InterlockedIncrement(&ptr->refs) != 1) /* entry is being destroy if == 1 */)
202 LeaveCriticalSection(&csOpenDllList);
206 /* caller must ensure that library_name is not already in the open dll list */
207 static HRESULT COMPOBJ_DllList_Add(LPCWSTR library_name, OpenDll **ret)
213 DllCanUnloadNowFunc DllCanUnloadNow;
214 DllGetClassObjectFunc DllGetClassObject;
218 *ret = COMPOBJ_DllList_Get(library_name);
219 if (*ret) return S_OK;
221 /* do this outside the csOpenDllList to avoid creating a lock dependency on
223 hLibrary = LoadLibraryExW(library_name, 0, LOAD_WITH_ALTERED_SEARCH_PATH);
226 ERR("couldn't load in-process dll %s\n", debugstr_w(library_name));
227 /* failure: DLL could not be loaded */
228 return E_ACCESSDENIED; /* FIXME: or should this be CO_E_DLLNOTFOUND? */
231 DllCanUnloadNow = (void *)GetProcAddress(hLibrary, "DllCanUnloadNow");
232 /* Note: failing to find DllCanUnloadNow is not a failure */
233 DllGetClassObject = (void *)GetProcAddress(hLibrary, "DllGetClassObject");
234 if (!DllGetClassObject)
236 /* failure: the dll did not export DllGetClassObject */
237 ERR("couldn't find function DllGetClassObject in %s\n", debugstr_w(library_name));
238 FreeLibrary(hLibrary);
239 return CO_E_DLLNOTFOUND;
242 EnterCriticalSection( &csOpenDllList );
244 *ret = COMPOBJ_DllList_Get(library_name);
247 /* another caller to this function already added the dll while we
248 * weren't in the critical section */
249 FreeLibrary(hLibrary);
253 len = strlenW(library_name);
254 entry = HeapAlloc(GetProcessHeap(),0, sizeof(OpenDll));
256 entry->library_name = HeapAlloc(GetProcessHeap(), 0, (len + 1)*sizeof(WCHAR));
257 if (entry && entry->library_name)
259 memcpy(entry->library_name, library_name, (len + 1)*sizeof(WCHAR));
260 entry->library = hLibrary;
262 entry->DllCanUnloadNow = DllCanUnloadNow;
263 entry->DllGetClassObject = DllGetClassObject;
264 list_add_tail(&openDllList, &entry->entry);
268 HeapFree(GetProcessHeap(), 0, entry);
270 FreeLibrary(hLibrary);
275 LeaveCriticalSection( &csOpenDllList );
280 /* pass FALSE for free_entry to release a reference without destroying the
281 * entry if it reaches zero or TRUE otherwise */
282 static void COMPOBJ_DllList_ReleaseRef(OpenDll *entry, BOOL free_entry)
284 if (!InterlockedDecrement(&entry->refs) && free_entry)
286 EnterCriticalSection(&csOpenDllList);
287 list_remove(&entry->entry);
288 LeaveCriticalSection(&csOpenDllList);
290 TRACE("freeing %p\n", entry->library);
291 FreeLibrary(entry->library);
293 HeapFree(GetProcessHeap(), 0, entry->library_name);
294 HeapFree(GetProcessHeap(), 0, entry);
298 /* frees memory associated with active dll list */
299 static void COMPOBJ_DllList_Free(void)
301 OpenDll *entry, *cursor2;
302 EnterCriticalSection(&csOpenDllList);
303 LIST_FOR_EACH_ENTRY_SAFE(entry, cursor2, &openDllList, OpenDll, entry)
305 list_remove(&entry->entry);
307 HeapFree(GetProcessHeap(), 0, entry->library_name);
308 HeapFree(GetProcessHeap(), 0, entry);
310 LeaveCriticalSection(&csOpenDllList);
311 DeleteCriticalSection(&csOpenDllList);
314 /******************************************************************************
318 static DWORD apartment_addref(struct apartment *apt)
320 DWORD refs = InterlockedIncrement(&apt->refs);
321 TRACE("%s: before = %d\n", wine_dbgstr_longlong(apt->oxid), refs - 1);
325 /* allocates memory and fills in the necessary fields for a new apartment
326 * object. must be called inside apartment cs */
327 static APARTMENT *apartment_construct(DWORD model)
331 TRACE("creating new apartment, model=%d\n", model);
333 apt = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*apt));
334 apt->tid = GetCurrentThreadId();
336 list_init(&apt->proxies);
337 list_init(&apt->stubmgrs);
338 list_init(&apt->psclsids);
339 list_init(&apt->loaded_dlls);
342 apt->remunk_exported = FALSE;
344 InitializeCriticalSection(&apt->cs);
345 DEBUG_SET_CRITSEC_NAME(&apt->cs, "apartment");
347 apt->multi_threaded = !(model & COINIT_APARTMENTTHREADED);
349 if (apt->multi_threaded)
351 /* FIXME: should be randomly generated by in an RPC call to rpcss */
352 apt->oxid = ((OXID)GetCurrentProcessId() << 32) | 0xcafe;
356 /* FIXME: should be randomly generated by in an RPC call to rpcss */
357 apt->oxid = ((OXID)GetCurrentProcessId() << 32) | GetCurrentThreadId();
360 TRACE("Created apartment on OXID %s\n", wine_dbgstr_longlong(apt->oxid));
362 list_add_head(&apts, &apt->entry);
367 /* gets and existing apartment if one exists or otherwise creates an apartment
368 * structure which stores OLE apartment-local information and stores a pointer
369 * to it in the thread-local storage */
370 static APARTMENT *apartment_get_or_create(DWORD model)
372 APARTMENT *apt = COM_CurrentApt();
376 if (model & COINIT_APARTMENTTHREADED)
378 EnterCriticalSection(&csApartment);
380 apt = apartment_construct(model);
385 TRACE("Created main-threaded apartment with OXID %s\n", wine_dbgstr_longlong(apt->oxid));
388 LeaveCriticalSection(&csApartment);
391 apartment_createwindowifneeded(apt);
395 EnterCriticalSection(&csApartment);
397 /* The multi-threaded apartment (MTA) contains zero or more threads interacting
398 * with free threaded (ie thread safe) COM objects. There is only ever one MTA
402 TRACE("entering the multithreaded apartment %s\n", wine_dbgstr_longlong(MTA->oxid));
403 apartment_addref(MTA);
406 MTA = apartment_construct(model);
410 LeaveCriticalSection(&csApartment);
412 COM_CurrentInfo()->apt = apt;
418 static inline BOOL apartment_is_model(const APARTMENT *apt, DWORD model)
420 return (apt->multi_threaded == !(model & COINIT_APARTMENTTHREADED));
423 static void COM_RevokeRegisteredClassObject(RegisteredClass *curClass)
425 list_remove(&curClass->entry);
427 if (curClass->runContext & CLSCTX_LOCAL_SERVER)
428 RPC_StopLocalServer(curClass->RpcRegistration);
431 * Release the reference to the class object.
433 IUnknown_Release(curClass->classObject);
435 if (curClass->pMarshaledData)
438 memset(&zero, 0, sizeof(zero));
439 IStream_Seek(curClass->pMarshaledData, zero, STREAM_SEEK_SET, NULL);
440 CoReleaseMarshalData(curClass->pMarshaledData);
441 IStream_Release(curClass->pMarshaledData);
444 HeapFree(GetProcessHeap(), 0, curClass);
447 static void COM_RevokeAllClasses(const struct apartment *apt)
449 RegisteredClass *curClass, *cursor;
451 EnterCriticalSection( &csRegisteredClassList );
453 LIST_FOR_EACH_ENTRY_SAFE(curClass, cursor, &RegisteredClassList, RegisteredClass, entry)
455 if (curClass->apartment_id == apt->oxid)
456 COM_RevokeRegisteredClassObject(curClass);
459 LeaveCriticalSection( &csRegisteredClassList );
462 /******************************************************************************
463 * Implementation of the manual reset event object. (CLSID_ManualResetEvent)
466 typedef struct ManualResetEvent {
467 ISynchronize ISynchronize_iface;
472 static inline MREImpl *impl_from_ISynchronize(ISynchronize *iface)
474 return CONTAINING_RECORD(iface, MREImpl, ISynchronize_iface);
477 static HRESULT WINAPI ISynchronize_fnQueryInterface(ISynchronize *iface, REFIID riid, void **ppv)
479 MREImpl *This = impl_from_ISynchronize(iface);
480 TRACE("%p (%s, %p)\n", This, debugstr_guid(riid), ppv);
483 if(IsEqualGUID(riid, &IID_IUnknown) ||
484 IsEqualGUID(riid, &IID_ISynchronize))
487 ERR("Unknown interface %s requested.\n", debugstr_guid(riid));
491 IUnknown_AddRef((IUnknown*)*ppv);
495 return E_NOINTERFACE;
498 static ULONG WINAPI ISynchronize_fnAddRef(ISynchronize *iface)
500 MREImpl *This = impl_from_ISynchronize(iface);
501 LONG ref = InterlockedIncrement(&This->ref);
502 TRACE("%p - ref %d\n", This, ref);
507 static ULONG WINAPI ISynchronize_fnRelease(ISynchronize *iface)
509 MREImpl *This = impl_from_ISynchronize(iface);
510 LONG ref = InterlockedDecrement(&This->ref);
511 TRACE("%p - ref %d\n", This, ref);
515 CloseHandle(This->event);
516 HeapFree(GetProcessHeap(), 0, This);
522 static HRESULT WINAPI ISynchronize_fnWait(ISynchronize *iface, DWORD dwFlags, DWORD dwMilliseconds)
524 MREImpl *This = impl_from_ISynchronize(iface);
526 TRACE("%p (%08x, %08x)\n", This, dwFlags, dwMilliseconds);
527 return CoWaitForMultipleHandles(dwFlags, dwMilliseconds, 1, &This->event, &index);
530 static HRESULT WINAPI ISynchronize_fnSignal(ISynchronize *iface)
532 MREImpl *This = impl_from_ISynchronize(iface);
534 SetEvent(This->event);
538 static HRESULT WINAPI ISynchronize_fnReset(ISynchronize *iface)
540 MREImpl *This = impl_from_ISynchronize(iface);
542 ResetEvent(This->event);
546 static ISynchronizeVtbl vt_ISynchronize = {
547 ISynchronize_fnQueryInterface,
548 ISynchronize_fnAddRef,
549 ISynchronize_fnRelease,
551 ISynchronize_fnSignal,
555 static HRESULT ManualResetEvent_Construct(IUnknown *punkouter, REFIID iid, void **ppv)
557 MREImpl *This = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(MREImpl));
561 FIXME("Aggregation not implemented.\n");
564 This->ISynchronize_iface.lpVtbl = &vt_ISynchronize;
565 This->event = CreateEventW(NULL, TRUE, FALSE, NULL);
567 hr = ISynchronize_QueryInterface(&This->ISynchronize_iface, iid, ppv);
568 ISynchronize_Release(&This->ISynchronize_iface);
572 /***********************************************************************
573 * CoRevokeClassObject [OLE32.@]
575 * Removes a class object from the class registry.
578 * dwRegister [I] Cookie returned from CoRegisterClassObject().
582 * Failure: HRESULT code.
585 * Must be called from the same apartment that called CoRegisterClassObject(),
586 * otherwise it will fail with RPC_E_WRONG_THREAD.
589 * CoRegisterClassObject
591 HRESULT WINAPI CoRevokeClassObject(
594 HRESULT hr = E_INVALIDARG;
595 RegisteredClass *curClass;
598 TRACE("(%08x)\n",dwRegister);
600 apt = COM_CurrentApt();
603 ERR("COM was not initialized\n");
604 return CO_E_NOTINITIALIZED;
607 EnterCriticalSection( &csRegisteredClassList );
609 LIST_FOR_EACH_ENTRY(curClass, &RegisteredClassList, RegisteredClass, entry)
612 * Check if we have a match on the cookie.
614 if (curClass->dwCookie == dwRegister)
616 if (curClass->apartment_id == apt->oxid)
618 COM_RevokeRegisteredClassObject(curClass);
623 ERR("called from wrong apartment, should be called from %s\n",
624 wine_dbgstr_longlong(curClass->apartment_id));
625 hr = RPC_E_WRONG_THREAD;
631 LeaveCriticalSection( &csRegisteredClassList );
636 /* frees unused libraries loaded by apartment_getclassobject by calling the
637 * DLL's DllCanUnloadNow entry point */
638 static void apartment_freeunusedlibraries(struct apartment *apt, DWORD delay)
640 struct apartment_loaded_dll *entry, *next;
641 EnterCriticalSection(&apt->cs);
642 LIST_FOR_EACH_ENTRY_SAFE(entry, next, &apt->loaded_dlls, struct apartment_loaded_dll, entry)
644 if (entry->dll->DllCanUnloadNow && (entry->dll->DllCanUnloadNow() == S_OK))
646 DWORD real_delay = delay;
648 if (real_delay == INFINITE)
650 /* DLLs that return multi-threaded objects aren't unloaded
651 * straight away to cope for programs that have races between
652 * last object destruction and threads in the DLLs that haven't
653 * finished, despite DllCanUnloadNow returning S_OK */
654 if (entry->multi_threaded)
655 real_delay = 10 * 60 * 1000; /* 10 minutes */
660 if (!real_delay || (entry->unload_time && (entry->unload_time < GetTickCount())))
662 list_remove(&entry->entry);
663 COMPOBJ_DllList_ReleaseRef(entry->dll, TRUE);
664 HeapFree(GetProcessHeap(), 0, entry);
667 entry->unload_time = GetTickCount() + real_delay;
669 else if (entry->unload_time)
670 entry->unload_time = 0;
672 LeaveCriticalSection(&apt->cs);
675 DWORD apartment_release(struct apartment *apt)
679 EnterCriticalSection(&csApartment);
681 ret = InterlockedDecrement(&apt->refs);
682 TRACE("%s: after = %d\n", wine_dbgstr_longlong(apt->oxid), ret);
683 /* destruction stuff that needs to happen under csApartment CS */
686 if (apt == MTA) MTA = NULL;
687 else if (apt == MainApartment) MainApartment = NULL;
688 list_remove(&apt->entry);
691 LeaveCriticalSection(&csApartment);
695 struct list *cursor, *cursor2;
697 TRACE("destroying apartment %p, oxid %s\n", apt, wine_dbgstr_longlong(apt->oxid));
699 /* Release the references to the registered class objects */
700 COM_RevokeAllClasses(apt);
702 /* no locking is needed for this apartment, because no other thread
703 * can access it at this point */
705 apartment_disconnectproxies(apt);
707 if (apt->win) DestroyWindow(apt->win);
708 if (apt->host_apt_tid) PostThreadMessageW(apt->host_apt_tid, WM_QUIT, 0, 0);
710 LIST_FOR_EACH_SAFE(cursor, cursor2, &apt->stubmgrs)
712 struct stub_manager *stubmgr = LIST_ENTRY(cursor, struct stub_manager, entry);
713 /* release the implicit reference given by the fact that the
714 * stub has external references (it must do since it is in the
715 * stub manager list in the apartment and all non-apartment users
716 * must have a ref on the apartment and so it cannot be destroyed).
718 stub_manager_int_release(stubmgr);
721 LIST_FOR_EACH_SAFE(cursor, cursor2, &apt->psclsids)
723 struct registered_psclsid *registered_psclsid =
724 LIST_ENTRY(cursor, struct registered_psclsid, entry);
726 list_remove(®istered_psclsid->entry);
727 HeapFree(GetProcessHeap(), 0, registered_psclsid);
730 /* if this assert fires, then another thread took a reference to a
731 * stub manager without taking a reference to the containing
732 * apartment, which it must do. */
733 assert(list_empty(&apt->stubmgrs));
735 if (apt->filter) IUnknown_Release(apt->filter);
737 /* free as many unused libraries as possible... */
738 apartment_freeunusedlibraries(apt, 0);
740 /* ... and free the memory for the apartment loaded dll entry and
741 * release the dll list reference without freeing the library for the
743 while ((cursor = list_head(&apt->loaded_dlls)))
745 struct apartment_loaded_dll *apartment_loaded_dll = LIST_ENTRY(cursor, struct apartment_loaded_dll, entry);
746 COMPOBJ_DllList_ReleaseRef(apartment_loaded_dll->dll, FALSE);
748 HeapFree(GetProcessHeap(), 0, apartment_loaded_dll);
751 DEBUG_CLEAR_CRITSEC_NAME(&apt->cs);
752 DeleteCriticalSection(&apt->cs);
754 HeapFree(GetProcessHeap(), 0, apt);
760 /* The given OXID must be local to this process:
762 * The ref parameter is here mostly to ensure people remember that
763 * they get one, you should normally take a ref for thread safety.
765 APARTMENT *apartment_findfromoxid(OXID oxid, BOOL ref)
767 APARTMENT *result = NULL;
770 EnterCriticalSection(&csApartment);
771 LIST_FOR_EACH( cursor, &apts )
773 struct apartment *apt = LIST_ENTRY( cursor, struct apartment, entry );
774 if (apt->oxid == oxid)
777 if (ref) apartment_addref(result);
781 LeaveCriticalSection(&csApartment);
786 /* gets the apartment which has a given creator thread ID. The caller must
787 * release the reference from the apartment as soon as the apartment pointer
788 * is no longer required. */
789 APARTMENT *apartment_findfromtid(DWORD tid)
791 APARTMENT *result = NULL;
794 EnterCriticalSection(&csApartment);
795 LIST_FOR_EACH( cursor, &apts )
797 struct apartment *apt = LIST_ENTRY( cursor, struct apartment, entry );
801 apartment_addref(result);
805 LeaveCriticalSection(&csApartment);
810 /* gets the main apartment if it exists. The caller must
811 * release the reference from the apartment as soon as the apartment pointer
812 * is no longer required. */
813 static APARTMENT *apartment_findmain(void)
817 EnterCriticalSection(&csApartment);
819 result = MainApartment;
820 if (result) apartment_addref(result);
822 LeaveCriticalSection(&csApartment);
827 /* gets the multi-threaded apartment if it exists. The caller must
828 * release the reference from the apartment as soon as the apartment pointer
829 * is no longer required. */
830 static APARTMENT *apartment_find_multi_threaded(void)
832 APARTMENT *result = NULL;
835 EnterCriticalSection(&csApartment);
837 LIST_FOR_EACH( cursor, &apts )
839 struct apartment *apt = LIST_ENTRY( cursor, struct apartment, entry );
840 if (apt->multi_threaded)
843 apartment_addref(result);
848 LeaveCriticalSection(&csApartment);
852 /* gets the specified class object by loading the appropriate DLL, if
853 * necessary and calls the DllGetClassObject function for the DLL */
854 static HRESULT apartment_getclassobject(struct apartment *apt, LPCWSTR dllpath,
855 BOOL apartment_threaded,
856 REFCLSID rclsid, REFIID riid, void **ppv)
858 static const WCHAR wszOle32[] = {'o','l','e','3','2','.','d','l','l',0};
861 struct apartment_loaded_dll *apartment_loaded_dll;
863 if (!strcmpiW(dllpath, wszOle32))
865 /* we don't need to control the lifetime of this dll, so use the local
866 * implementation of DllGetClassObject directly */
867 TRACE("calling ole32!DllGetClassObject\n");
868 hr = DllGetClassObject(rclsid, riid, ppv);
871 ERR("DllGetClassObject returned error 0x%08x\n", hr);
876 EnterCriticalSection(&apt->cs);
878 LIST_FOR_EACH_ENTRY(apartment_loaded_dll, &apt->loaded_dlls, struct apartment_loaded_dll, entry)
879 if (!strcmpiW(dllpath, apartment_loaded_dll->dll->library_name))
881 TRACE("found %s already loaded\n", debugstr_w(dllpath));
888 apartment_loaded_dll = HeapAlloc(GetProcessHeap(), 0, sizeof(*apartment_loaded_dll));
889 if (!apartment_loaded_dll)
893 apartment_loaded_dll->unload_time = 0;
894 apartment_loaded_dll->multi_threaded = FALSE;
895 hr = COMPOBJ_DllList_Add( dllpath, &apartment_loaded_dll->dll );
897 HeapFree(GetProcessHeap(), 0, apartment_loaded_dll);
901 TRACE("added new loaded dll %s\n", debugstr_w(dllpath));
902 list_add_tail(&apt->loaded_dlls, &apartment_loaded_dll->entry);
906 LeaveCriticalSection(&apt->cs);
910 /* one component being multi-threaded overrides any number of
911 * apartment-threaded components */
912 if (!apartment_threaded)
913 apartment_loaded_dll->multi_threaded = TRUE;
915 TRACE("calling DllGetClassObject %p\n", apartment_loaded_dll->dll->DllGetClassObject);
916 /* OK: get the ClassObject */
917 hr = apartment_loaded_dll->dll->DllGetClassObject(rclsid, riid, ppv);
920 ERR("DllGetClassObject returned error 0x%08x\n", hr);
926 /***********************************************************************
927 * COM_RegReadPath [internal]
929 * Reads a registry value and expands it when necessary
931 static DWORD COM_RegReadPath(HKEY hkeyroot, const WCHAR *keyname, const WCHAR *valuename, WCHAR * dst, DWORD dstlen)
937 DWORD dwLength = dstlen * sizeof(WCHAR);
939 if((ret = RegOpenKeyExW(hkeyroot, keyname, 0, KEY_READ, &key)) == ERROR_SUCCESS) {
940 if( (ret = RegQueryValueExW(key, NULL, NULL, &keytype, (LPBYTE)src, &dwLength)) == ERROR_SUCCESS ) {
941 if (keytype == REG_EXPAND_SZ) {
942 if (dstlen <= ExpandEnvironmentStringsW(src, dst, dstlen)) ret = ERROR_MORE_DATA;
944 const WCHAR *quote_start;
945 quote_start = strchrW(src, '\"');
947 const WCHAR *quote_end = strchrW(quote_start + 1, '\"');
949 memmove(src, quote_start + 1,
950 (quote_end - quote_start - 1) * sizeof(WCHAR));
951 src[quote_end - quote_start - 1] = '\0';
954 lstrcpynW(dst, src, dstlen);
962 struct host_object_params
965 CLSID clsid; /* clsid of object to marshal */
966 IID iid; /* interface to marshal */
967 HANDLE event; /* event signalling when ready for multi-threaded case */
968 HRESULT hr; /* result for multi-threaded case */
969 IStream *stream; /* stream that the object will be marshaled into */
970 BOOL apartment_threaded; /* is the component purely apartment-threaded? */
973 static HRESULT apartment_hostobject(struct apartment *apt,
974 const struct host_object_params *params)
978 static const LARGE_INTEGER llZero;
979 WCHAR dllpath[MAX_PATH+1];
981 TRACE("clsid %s, iid %s\n", debugstr_guid(¶ms->clsid), debugstr_guid(¶ms->iid));
983 if (COM_RegReadPath(params->hkeydll, NULL, NULL, dllpath, ARRAYSIZE(dllpath)) != ERROR_SUCCESS)
985 /* failure: CLSID is not found in registry */
986 WARN("class %s not registered inproc\n", debugstr_guid(¶ms->clsid));
987 return REGDB_E_CLASSNOTREG;
990 hr = apartment_getclassobject(apt, dllpath, params->apartment_threaded,
991 ¶ms->clsid, ¶ms->iid, (void **)&object);
995 hr = CoMarshalInterface(params->stream, ¶ms->iid, object, MSHCTX_INPROC, NULL, MSHLFLAGS_NORMAL);
997 IUnknown_Release(object);
998 IStream_Seek(params->stream, llZero, STREAM_SEEK_SET, NULL);
1003 static LRESULT CALLBACK apartment_wndproc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
1008 RPC_ExecuteCall((struct dispatch_params *)lParam);
1011 return apartment_hostobject(COM_CurrentApt(), (const struct host_object_params *)lParam);
1013 return DefWindowProcW(hWnd, msg, wParam, lParam);
1017 struct host_thread_params
1019 COINIT threading_model;
1021 HWND apartment_hwnd;
1024 /* thread for hosting an object to allow an object to appear to be created in
1025 * an apartment with an incompatible threading model */
1026 static DWORD CALLBACK apartment_hostobject_thread(LPVOID p)
1028 struct host_thread_params *params = p;
1031 struct apartment *apt;
1035 hr = CoInitializeEx(NULL, params->threading_model);
1036 if (FAILED(hr)) return hr;
1038 apt = COM_CurrentApt();
1039 if (params->threading_model == COINIT_APARTMENTTHREADED)
1041 apartment_createwindowifneeded(apt);
1042 params->apartment_hwnd = apartment_getwindow(apt);
1045 params->apartment_hwnd = NULL;
1047 /* force the message queue to be created before signaling parent thread */
1048 PeekMessageW(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
1050 SetEvent(params->ready_event);
1051 params = NULL; /* can't touch params after here as it may be invalid */
1053 while (GetMessageW(&msg, NULL, 0, 0))
1055 if (!msg.hwnd && (msg.message == DM_HOSTOBJECT))
1057 struct host_object_params *obj_params = (struct host_object_params *)msg.lParam;
1058 obj_params->hr = apartment_hostobject(apt, obj_params);
1059 SetEvent(obj_params->event);
1063 TranslateMessage(&msg);
1064 DispatchMessageW(&msg);
1075 /* finds or creates a host apartment, creates the object inside it and returns
1076 * a proxy to it so that the object can be used in the apartment of the
1077 * caller of this function */
1078 static HRESULT apartment_hostobject_in_hostapt(
1079 struct apartment *apt, BOOL multi_threaded, BOOL main_apartment,
1080 HKEY hkeydll, REFCLSID rclsid, REFIID riid, void **ppv)
1082 struct host_object_params params;
1083 HWND apartment_hwnd = NULL;
1084 DWORD apartment_tid = 0;
1087 if (!multi_threaded && main_apartment)
1089 APARTMENT *host_apt = apartment_findmain();
1092 apartment_hwnd = apartment_getwindow(host_apt);
1093 apartment_release(host_apt);
1097 if (!apartment_hwnd)
1099 EnterCriticalSection(&apt->cs);
1101 if (!apt->host_apt_tid)
1103 struct host_thread_params thread_params;
1107 thread_params.threading_model = multi_threaded ? COINIT_MULTITHREADED : COINIT_APARTMENTTHREADED;
1108 handles[0] = thread_params.ready_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1109 thread_params.apartment_hwnd = NULL;
1110 handles[1] = CreateThread(NULL, 0, apartment_hostobject_thread, &thread_params, 0, &apt->host_apt_tid);
1113 CloseHandle(handles[0]);
1114 LeaveCriticalSection(&apt->cs);
1115 return E_OUTOFMEMORY;
1117 wait_value = WaitForMultipleObjects(2, handles, FALSE, INFINITE);
1118 CloseHandle(handles[0]);
1119 CloseHandle(handles[1]);
1120 if (wait_value == WAIT_OBJECT_0)
1121 apt->host_apt_hwnd = thread_params.apartment_hwnd;
1124 LeaveCriticalSection(&apt->cs);
1125 return E_OUTOFMEMORY;
1129 if (multi_threaded || !main_apartment)
1131 apartment_hwnd = apt->host_apt_hwnd;
1132 apartment_tid = apt->host_apt_tid;
1135 LeaveCriticalSection(&apt->cs);
1138 /* another thread may have become the main apartment in the time it took
1139 * us to create the thread for the host apartment */
1140 if (!apartment_hwnd && !multi_threaded && main_apartment)
1142 APARTMENT *host_apt = apartment_findmain();
1145 apartment_hwnd = apartment_getwindow(host_apt);
1146 apartment_release(host_apt);
1150 params.hkeydll = hkeydll;
1151 params.clsid = *rclsid;
1153 hr = CreateStreamOnHGlobal(NULL, TRUE, ¶ms.stream);
1156 params.apartment_threaded = !multi_threaded;
1160 params.event = CreateEventW(NULL, FALSE, FALSE, NULL);
1161 if (!PostThreadMessageW(apartment_tid, DM_HOSTOBJECT, 0, (LPARAM)¶ms))
1165 WaitForSingleObject(params.event, INFINITE);
1168 CloseHandle(params.event);
1172 if (!apartment_hwnd)
1174 ERR("host apartment didn't create window\n");
1178 hr = SendMessageW(apartment_hwnd, DM_HOSTOBJECT, 0, (LPARAM)¶ms);
1181 hr = CoUnmarshalInterface(params.stream, riid, ppv);
1182 IStream_Release(params.stream);
1186 /* create a window for the apartment or return the current one if one has
1187 * already been created */
1188 HRESULT apartment_createwindowifneeded(struct apartment *apt)
1190 if (apt->multi_threaded)
1195 HWND hwnd = CreateWindowW(wszAptWinClass, NULL, 0,
1197 HWND_MESSAGE, 0, hProxyDll, NULL);
1200 ERR("CreateWindow failed with error %d\n", GetLastError());
1201 return HRESULT_FROM_WIN32(GetLastError());
1203 if (InterlockedCompareExchangePointer((PVOID *)&apt->win, hwnd, NULL))
1204 /* someone beat us to it */
1205 DestroyWindow(hwnd);
1211 /* retrieves the window for the main- or apartment-threaded apartment */
1212 HWND apartment_getwindow(const struct apartment *apt)
1214 assert(!apt->multi_threaded);
1218 void apartment_joinmta(void)
1220 apartment_addref(MTA);
1221 COM_CurrentInfo()->apt = MTA;
1224 static void COMPOBJ_InitProcess( void )
1228 /* Dispatching to the correct thread in an apartment is done through
1229 * window messages rather than RPC transports. When an interface is
1230 * marshalled into another apartment in the same process, a window of the
1231 * following class is created. The *caller* of CoMarshalInterface (i.e., the
1232 * application) is responsible for pumping the message loop in that thread.
1233 * The WM_USER messages which point to the RPCs are then dispatched to
1234 * apartment_wndproc by the user's code from the apartment in which the
1235 * interface was unmarshalled.
1237 memset(&wclass, 0, sizeof(wclass));
1238 wclass.lpfnWndProc = apartment_wndproc;
1239 wclass.hInstance = hProxyDll;
1240 wclass.lpszClassName = wszAptWinClass;
1241 RegisterClassW(&wclass);
1244 static void COMPOBJ_UninitProcess( void )
1246 UnregisterClassW(wszAptWinClass, hProxyDll);
1249 static void COM_TlsDestroy(void)
1251 struct oletls *info = NtCurrentTeb()->ReservedForOle;
1254 if (info->apt) apartment_release(info->apt);
1255 if (info->errorinfo) IErrorInfo_Release(info->errorinfo);
1256 if (info->state) IUnknown_Release(info->state);
1257 if (info->spy) IUnknown_Release(info->spy);
1258 if (info->context_token) IObjContext_Release(info->context_token);
1259 HeapFree(GetProcessHeap(), 0, info);
1260 NtCurrentTeb()->ReservedForOle = NULL;
1264 /******************************************************************************
1265 * CoBuildVersion [OLE32.@]
1267 * Gets the build version of the DLL.
1272 * Current build version, hiword is majornumber, loword is minornumber
1274 DWORD WINAPI CoBuildVersion(void)
1276 TRACE("Returning version %d, build %d.\n", rmm, rup);
1277 return (rmm<<16)+rup;
1280 /******************************************************************************
1281 * CoRegisterInitializeSpy [OLE32.@]
1283 * Add a Spy that watches CoInitializeEx calls
1286 * spy [I] Pointer to IUnknown interface that will be QueryInterface'd.
1287 * cookie [II] cookie receiver
1290 * Success: S_OK if not already initialized, S_FALSE otherwise.
1291 * Failure: HRESULT code.
1296 HRESULT WINAPI CoRegisterInitializeSpy(IInitializeSpy *spy, ULARGE_INTEGER *cookie)
1298 struct oletls *info = COM_CurrentInfo();
1301 TRACE("(%p, %p)\n", spy, cookie);
1303 if (!spy || !cookie || !info)
1306 WARN("Could not allocate tls\n");
1307 return E_INVALIDARG;
1312 FIXME("Already registered?\n");
1313 return E_UNEXPECTED;
1316 hr = IUnknown_QueryInterface(spy, &IID_IInitializeSpy, (void **) &info->spy);
1319 cookie->QuadPart = (DWORD_PTR)spy;
1325 /******************************************************************************
1326 * CoRevokeInitializeSpy [OLE32.@]
1328 * Remove a spy that previously watched CoInitializeEx calls
1331 * cookie [I] The cookie obtained from a previous CoRegisterInitializeSpy call
1334 * Success: S_OK if a spy is removed
1335 * Failure: E_INVALIDARG
1340 HRESULT WINAPI CoRevokeInitializeSpy(ULARGE_INTEGER cookie)
1342 struct oletls *info = COM_CurrentInfo();
1343 TRACE("(%s)\n", wine_dbgstr_longlong(cookie.QuadPart));
1345 if (!info || !info->spy || cookie.QuadPart != (DWORD_PTR)info->spy)
1346 return E_INVALIDARG;
1348 IUnknown_Release(info->spy);
1354 /******************************************************************************
1355 * CoInitialize [OLE32.@]
1357 * Initializes the COM libraries by calling CoInitializeEx with
1358 * COINIT_APARTMENTTHREADED, ie it enters a STA thread.
1361 * lpReserved [I] Pointer to IMalloc interface (obsolete, should be NULL).
1364 * Success: S_OK if not already initialized, S_FALSE otherwise.
1365 * Failure: HRESULT code.
1370 HRESULT WINAPI CoInitialize(LPVOID lpReserved)
1373 * Just delegate to the newer method.
1375 return CoInitializeEx(lpReserved, COINIT_APARTMENTTHREADED);
1378 /******************************************************************************
1379 * CoInitializeEx [OLE32.@]
1381 * Initializes the COM libraries.
1384 * lpReserved [I] Pointer to IMalloc interface (obsolete, should be NULL).
1385 * dwCoInit [I] One or more flags from the COINIT enumeration. See notes.
1388 * S_OK if successful,
1389 * S_FALSE if this function was called already.
1390 * RPC_E_CHANGED_MODE if a previous call to CoInitializeEx specified another
1395 * The behavior used to set the IMalloc used for memory management is
1397 * The dwCoInit parameter must specify one of the following apartment
1399 *| COINIT_APARTMENTTHREADED - A single-threaded apartment (STA).
1400 *| COINIT_MULTITHREADED - A multi-threaded apartment (MTA).
1401 * The parameter may also specify zero or more of the following flags:
1402 *| COINIT_DISABLE_OLE1DDE - Don't use DDE for OLE1 support.
1403 *| COINIT_SPEED_OVER_MEMORY - Trade memory for speed.
1408 HRESULT WINAPI CoInitializeEx(LPVOID lpReserved, DWORD dwCoInit)
1410 struct oletls *info = COM_CurrentInfo();
1414 TRACE("(%p, %x)\n", lpReserved, (int)dwCoInit);
1416 if (lpReserved!=NULL)
1418 ERR("(%p, %x) - Bad parameter passed-in %p, must be an old Windows Application\n", lpReserved, (int)dwCoInit, lpReserved);
1422 * Check the lock count. If this is the first time going through the initialize
1423 * process, we have to initialize the libraries.
1425 * And crank-up that lock count.
1427 if (InterlockedExchangeAdd(&s_COMLockCount,1)==0)
1430 * Initialize the various COM libraries and data structures.
1432 TRACE("() - Initializing the COM libraries\n");
1434 /* we may need to defer this until after apartment initialisation */
1435 RunningObjectTableImpl_Initialize();
1439 IInitializeSpy_PreInitialize(info->spy, dwCoInit, info->inits);
1441 if (!(apt = info->apt))
1443 apt = apartment_get_or_create(dwCoInit);
1444 if (!apt) return E_OUTOFMEMORY;
1446 else if (!apartment_is_model(apt, dwCoInit))
1448 /* Changing the threading model after it's been set is illegal. If this warning is triggered by Wine
1449 code then we are probably using the wrong threading model to implement that API. */
1450 ERR("Attempt to change threading model of this apartment from %s to %s\n",
1451 apt->multi_threaded ? "multi-threaded" : "apartment threaded",
1452 dwCoInit & COINIT_APARTMENTTHREADED ? "apartment threaded" : "multi-threaded");
1453 return RPC_E_CHANGED_MODE;
1461 IInitializeSpy_PostInitialize(info->spy, hr, dwCoInit, info->inits);
1466 /***********************************************************************
1467 * CoUninitialize [OLE32.@]
1469 * This method will decrement the refcount on the current apartment, freeing
1470 * the resources associated with it if it is the last thread in the apartment.
1471 * If the last apartment is freed, the function will additionally release
1472 * any COM resources associated with the process.
1482 void WINAPI CoUninitialize(void)
1484 struct oletls * info = COM_CurrentInfo();
1489 /* will only happen on OOM */
1493 IInitializeSpy_PreUninitialize(info->spy, info->inits);
1498 ERR("Mismatched CoUninitialize\n");
1501 IInitializeSpy_PostUninitialize(info->spy, info->inits);
1507 apartment_release(info->apt);
1512 * Decrease the reference count.
1513 * If we are back to 0 locks on the COM library, make sure we free
1514 * all the associated data structures.
1516 lCOMRefCnt = InterlockedExchangeAdd(&s_COMLockCount,-1);
1519 TRACE("() - Releasing the COM libraries\n");
1521 RunningObjectTableImpl_UnInitialize();
1523 else if (lCOMRefCnt<1) {
1524 ERR( "CoUninitialize() - not CoInitialized.\n" );
1525 InterlockedExchangeAdd(&s_COMLockCount,1); /* restore the lock count. */
1528 IInitializeSpy_PostUninitialize(info->spy, info->inits);
1531 /******************************************************************************
1532 * CoDisconnectObject [OLE32.@]
1534 * Disconnects all connections to this object from remote processes. Dispatches
1535 * pending RPCs while blocking new RPCs from occurring, and then calls
1536 * IMarshal::DisconnectObject on the given object.
1538 * Typically called when the object server is forced to shut down, for instance by
1542 * lpUnk [I] The object whose stub should be disconnected.
1543 * reserved [I] Reserved. Should be set to 0.
1547 * Failure: HRESULT code.
1550 * CoMarshalInterface, CoReleaseMarshalData, CoLockObjectExternal
1552 HRESULT WINAPI CoDisconnectObject( LPUNKNOWN lpUnk, DWORD reserved )
1558 TRACE("(%p, 0x%08x)\n", lpUnk, reserved);
1560 hr = IUnknown_QueryInterface(lpUnk, &IID_IMarshal, (void **)&marshal);
1563 hr = IMarshal_DisconnectObject(marshal, reserved);
1564 IMarshal_Release(marshal);
1568 apt = COM_CurrentApt();
1570 return CO_E_NOTINITIALIZED;
1572 apartment_disconnectobject(apt, lpUnk);
1574 /* Note: native is pretty broken here because it just silently
1575 * fails, without returning an appropriate error code if the object was
1576 * not found, making apps think that the object was disconnected, when
1577 * it actually wasn't */
1582 /******************************************************************************
1583 * CoCreateGuid [OLE32.@]
1585 * Simply forwards to UuidCreate in RPCRT4.
1588 * pguid [O] Points to the GUID to initialize.
1592 * Failure: HRESULT code.
1597 HRESULT WINAPI CoCreateGuid(GUID *pguid)
1599 DWORD status = UuidCreate(pguid);
1600 if (status == RPC_S_OK || status == RPC_S_UUID_LOCAL_ONLY) return S_OK;
1601 return HRESULT_FROM_WIN32( status );
1604 static inline BOOL is_valid_hex(WCHAR c)
1606 if (!(((c >= '0') && (c <= '9')) ||
1607 ((c >= 'a') && (c <= 'f')) ||
1608 ((c >= 'A') && (c <= 'F'))))
1613 /******************************************************************************
1614 * CLSIDFromString [OLE32.@]
1615 * IIDFromString [OLE32.@]
1617 * Converts a unique identifier from its string representation into
1621 * idstr [I] The string representation of the GUID.
1622 * id [O] GUID converted from the string.
1626 * CO_E_CLASSSTRING if idstr is not a valid CLSID
1631 static HRESULT __CLSIDFromString(LPCWSTR s, LPCLSID id)
1636 if (!s || s[0]!='{') {
1637 memset( id, 0, sizeof (CLSID) );
1639 return CO_E_CLASSSTRING;
1642 TRACE("%s -> %p\n", debugstr_w(s), id);
1644 /* quick lookup table */
1645 memset(table, 0, 256);
1647 for (i = 0; i < 10; i++) {
1650 for (i = 0; i < 6; i++) {
1651 table['A' + i] = i+10;
1652 table['a' + i] = i+10;
1655 /* in form {XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX} */
1658 for (i = 1; i < 9; i++) {
1659 if (!is_valid_hex(s[i])) return CO_E_CLASSSTRING;
1660 id->Data1 = (id->Data1 << 4) | table[s[i]];
1662 if (s[9]!='-') return CO_E_CLASSSTRING;
1665 for (i = 10; i < 14; i++) {
1666 if (!is_valid_hex(s[i])) return CO_E_CLASSSTRING;
1667 id->Data2 = (id->Data2 << 4) | table[s[i]];
1669 if (s[14]!='-') return CO_E_CLASSSTRING;
1672 for (i = 15; i < 19; i++) {
1673 if (!is_valid_hex(s[i])) return CO_E_CLASSSTRING;
1674 id->Data3 = (id->Data3 << 4) | table[s[i]];
1676 if (s[19]!='-') return CO_E_CLASSSTRING;
1678 for (i = 20; i < 37; i+=2) {
1680 if (s[i]!='-') return CO_E_CLASSSTRING;
1683 if (!is_valid_hex(s[i]) || !is_valid_hex(s[i+1])) return CO_E_CLASSSTRING;
1684 id->Data4[(i-20)/2] = table[s[i]] << 4 | table[s[i+1]];
1687 if (s[37] == '}' && s[38] == '\0')
1690 return CO_E_CLASSSTRING;
1693 /*****************************************************************************/
1695 HRESULT WINAPI CLSIDFromString(LPCOLESTR idstr, LPCLSID id )
1700 return E_INVALIDARG;
1702 ret = __CLSIDFromString(idstr, id);
1703 if(ret != S_OK) { /* It appears a ProgID is also valid */
1705 ret = CLSIDFromProgID(idstr, &tmp_id);
1713 /******************************************************************************
1714 * StringFromCLSID [OLE32.@]
1715 * StringFromIID [OLE32.@]
1717 * Converts a GUID into the respective string representation.
1718 * The target string is allocated using the OLE IMalloc.
1721 * id [I] the GUID to be converted.
1722 * idstr [O] A pointer to a to-be-allocated pointer pointing to the resulting string.
1729 * StringFromGUID2, CLSIDFromString
1731 HRESULT WINAPI StringFromCLSID(REFCLSID id, LPOLESTR *idstr)
1736 if ((ret = CoGetMalloc(0,&mllc))) return ret;
1737 if (!(*idstr = IMalloc_Alloc( mllc, CHARS_IN_GUID * sizeof(WCHAR) ))) return E_OUTOFMEMORY;
1738 StringFromGUID2( id, *idstr, CHARS_IN_GUID );
1742 /******************************************************************************
1743 * StringFromGUID2 [OLE32.@]
1745 * Modified version of StringFromCLSID that allows you to specify max
1749 * id [I] GUID to convert to string.
1750 * str [O] Buffer where the result will be stored.
1751 * cmax [I] Size of the buffer in characters.
1754 * Success: The length of the resulting string in characters.
1757 INT WINAPI StringFromGUID2(REFGUID id, LPOLESTR str, INT cmax)
1759 static const WCHAR formatW[] = { '{','%','0','8','X','-','%','0','4','X','-',
1760 '%','0','4','X','-','%','0','2','X','%','0','2','X','-',
1761 '%','0','2','X','%','0','2','X','%','0','2','X','%','0','2','X',
1762 '%','0','2','X','%','0','2','X','}',0 };
1763 if (!id || cmax < CHARS_IN_GUID) return 0;
1764 sprintfW( str, formatW, id->Data1, id->Data2, id->Data3,
1765 id->Data4[0], id->Data4[1], id->Data4[2], id->Data4[3],
1766 id->Data4[4], id->Data4[5], id->Data4[6], id->Data4[7] );
1767 return CHARS_IN_GUID;
1770 /* open HKCR\\CLSID\\{string form of clsid}\\{keyname} key */
1771 HRESULT COM_OpenKeyForCLSID(REFCLSID clsid, LPCWSTR keyname, REGSAM access, HKEY *subkey)
1773 static const WCHAR wszCLSIDSlash[] = {'C','L','S','I','D','\\',0};
1774 WCHAR path[CHARS_IN_GUID + ARRAYSIZE(wszCLSIDSlash) - 1];
1778 strcpyW(path, wszCLSIDSlash);
1779 StringFromGUID2(clsid, path + strlenW(wszCLSIDSlash), CHARS_IN_GUID);
1780 res = RegOpenKeyExW(HKEY_CLASSES_ROOT, path, 0, keyname ? KEY_READ : access, &key);
1781 if (res == ERROR_FILE_NOT_FOUND)
1782 return REGDB_E_CLASSNOTREG;
1783 else if (res != ERROR_SUCCESS)
1784 return REGDB_E_READREGDB;
1792 res = RegOpenKeyExW(key, keyname, 0, access, subkey);
1794 if (res == ERROR_FILE_NOT_FOUND)
1795 return REGDB_E_KEYMISSING;
1796 else if (res != ERROR_SUCCESS)
1797 return REGDB_E_READREGDB;
1802 /* open HKCR\\AppId\\{string form of appid clsid} key */
1803 HRESULT COM_OpenKeyForAppIdFromCLSID(REFCLSID clsid, REGSAM access, HKEY *subkey)
1805 static const WCHAR szAppId[] = { 'A','p','p','I','d',0 };
1806 static const WCHAR szAppIdKey[] = { 'A','p','p','I','d','\\',0 };
1808 WCHAR buf[CHARS_IN_GUID];
1809 WCHAR keyname[ARRAYSIZE(szAppIdKey) + CHARS_IN_GUID];
1815 /* read the AppID value under the class's key */
1816 hr = COM_OpenKeyForCLSID(clsid, NULL, KEY_READ, &hkey);
1821 res = RegQueryValueExW(hkey, szAppId, NULL, &type, (LPBYTE)buf, &size);
1823 if (res == ERROR_FILE_NOT_FOUND)
1824 return REGDB_E_KEYMISSING;
1825 else if (res != ERROR_SUCCESS || type!=REG_SZ)
1826 return REGDB_E_READREGDB;
1828 strcpyW(keyname, szAppIdKey);
1829 strcatW(keyname, buf);
1830 res = RegOpenKeyExW(HKEY_CLASSES_ROOT, keyname, 0, access, subkey);
1831 if (res == ERROR_FILE_NOT_FOUND)
1832 return REGDB_E_KEYMISSING;
1833 else if (res != ERROR_SUCCESS)
1834 return REGDB_E_READREGDB;
1839 /******************************************************************************
1840 * ProgIDFromCLSID [OLE32.@]
1842 * Converts a class id into the respective program ID.
1845 * clsid [I] Class ID, as found in registry.
1846 * ppszProgID [O] Associated ProgID.
1851 * REGDB_E_CLASSNOTREG if the given clsid has no associated ProgID
1853 HRESULT WINAPI ProgIDFromCLSID(REFCLSID clsid, LPOLESTR *ppszProgID)
1855 static const WCHAR wszProgID[] = {'P','r','o','g','I','D',0};
1862 ERR("ppszProgId isn't optional\n");
1863 return E_INVALIDARG;
1867 ret = COM_OpenKeyForCLSID(clsid, wszProgID, KEY_READ, &hkey);
1871 if (RegQueryValueW(hkey, NULL, NULL, &progidlen))
1872 ret = REGDB_E_CLASSNOTREG;
1876 *ppszProgID = CoTaskMemAlloc(progidlen * sizeof(WCHAR));
1879 if (RegQueryValueW(hkey, NULL, *ppszProgID, &progidlen))
1880 ret = REGDB_E_CLASSNOTREG;
1883 ret = E_OUTOFMEMORY;
1890 /******************************************************************************
1891 * CLSIDFromProgID [OLE32.@]
1893 * Converts a program id into the respective GUID.
1896 * progid [I] Unicode program ID, as found in registry.
1897 * clsid [O] Associated CLSID.
1901 * Failure: CO_E_CLASSSTRING - the given ProgID cannot be found.
1903 HRESULT WINAPI CLSIDFromProgID(LPCOLESTR progid, LPCLSID clsid)
1905 static const WCHAR clsidW[] = { '\\','C','L','S','I','D',0 };
1906 WCHAR buf2[CHARS_IN_GUID];
1907 LONG buf2len = sizeof(buf2);
1911 if (!progid || !clsid)
1913 ERR("neither progid (%p) nor clsid (%p) are optional\n", progid, clsid);
1914 return E_INVALIDARG;
1917 /* initialise clsid in case of failure */
1918 memset(clsid, 0, sizeof(*clsid));
1920 buf = HeapAlloc( GetProcessHeap(),0,(strlenW(progid)+8) * sizeof(WCHAR) );
1921 strcpyW( buf, progid );
1922 strcatW( buf, clsidW );
1923 if (RegOpenKeyW(HKEY_CLASSES_ROOT,buf,&xhkey))
1925 HeapFree(GetProcessHeap(),0,buf);
1926 WARN("couldn't open key for ProgID %s\n", debugstr_w(progid));
1927 return CO_E_CLASSSTRING;
1929 HeapFree(GetProcessHeap(),0,buf);
1931 if (RegQueryValueW(xhkey,NULL,buf2,&buf2len))
1934 WARN("couldn't query clsid value for ProgID %s\n", debugstr_w(progid));
1935 return CO_E_CLASSSTRING;
1938 return __CLSIDFromString(buf2,clsid);
1942 /*****************************************************************************
1943 * CoGetPSClsid [OLE32.@]
1945 * Retrieves the CLSID of the proxy/stub factory that implements
1946 * IPSFactoryBuffer for the specified interface.
1949 * riid [I] Interface whose proxy/stub CLSID is to be returned.
1950 * pclsid [O] Where to store returned proxy/stub CLSID.
1955 * REGDB_E_IIDNOTREG if no PSFactoryBuffer is associated with the IID, or it could not be parsed
1959 * The standard marshaller activates the object with the CLSID
1960 * returned and uses the CreateProxy and CreateStub methods on its
1961 * IPSFactoryBuffer interface to construct the proxies and stubs for a
1964 * CoGetPSClsid determines this CLSID by searching the
1965 * HKEY_CLASSES_ROOT\Interface\{string form of riid}\ProxyStubClsid32
1966 * in the registry and any interface id registered by
1967 * CoRegisterPSClsid within the current process.
1971 * Native returns S_OK for interfaces with a key in HKCR\Interface, but
1972 * without a ProxyStubClsid32 key and leaves garbage in pclsid. This should be
1973 * considered a bug in native unless an application depends on this (unlikely).
1976 * CoRegisterPSClsid.
1978 HRESULT WINAPI CoGetPSClsid(REFIID riid, CLSID *pclsid)
1980 static const WCHAR wszInterface[] = {'I','n','t','e','r','f','a','c','e','\\',0};
1981 static const WCHAR wszPSC[] = {'\\','P','r','o','x','y','S','t','u','b','C','l','s','i','d','3','2',0};
1982 WCHAR path[ARRAYSIZE(wszInterface) - 1 + CHARS_IN_GUID - 1 + ARRAYSIZE(wszPSC)];
1983 WCHAR value[CHARS_IN_GUID];
1986 APARTMENT *apt = COM_CurrentApt();
1987 struct registered_psclsid *registered_psclsid;
1989 TRACE("() riid=%s, pclsid=%p\n", debugstr_guid(riid), pclsid);
1993 ERR("apartment not initialised\n");
1994 return CO_E_NOTINITIALIZED;
1999 ERR("pclsid isn't optional\n");
2000 return E_INVALIDARG;
2003 EnterCriticalSection(&apt->cs);
2005 LIST_FOR_EACH_ENTRY(registered_psclsid, &apt->psclsids, struct registered_psclsid, entry)
2006 if (IsEqualIID(®istered_psclsid->iid, riid))
2008 *pclsid = registered_psclsid->clsid;
2009 LeaveCriticalSection(&apt->cs);
2013 LeaveCriticalSection(&apt->cs);
2015 /* Interface\\{string form of riid}\\ProxyStubClsid32 */
2016 strcpyW(path, wszInterface);
2017 StringFromGUID2(riid, path + ARRAYSIZE(wszInterface) - 1, CHARS_IN_GUID);
2018 strcpyW(path + ARRAYSIZE(wszInterface) - 1 + CHARS_IN_GUID - 1, wszPSC);
2020 /* Open the key.. */
2021 if (RegOpenKeyExW(HKEY_CLASSES_ROOT, path, 0, KEY_READ, &hkey))
2023 WARN("No PSFactoryBuffer object is registered for IID %s\n", debugstr_guid(riid));
2024 return REGDB_E_IIDNOTREG;
2027 /* ... Once we have the key, query the registry to get the
2028 value of CLSID as a string, and convert it into a
2029 proper CLSID structure to be passed back to the app */
2030 len = sizeof(value);
2031 if (ERROR_SUCCESS != RegQueryValueW(hkey, NULL, value, &len))
2034 return REGDB_E_IIDNOTREG;
2038 /* We have the CLSID we want back from the registry as a string, so
2039 let's convert it into a CLSID structure */
2040 if (CLSIDFromString(value, pclsid) != NOERROR)
2041 return REGDB_E_IIDNOTREG;
2043 TRACE ("() Returning CLSID=%s\n", debugstr_guid(pclsid));
2047 /*****************************************************************************
2048 * CoRegisterPSClsid [OLE32.@]
2050 * Register a proxy/stub CLSID for the given interface in the current process
2054 * riid [I] Interface whose proxy/stub CLSID is to be registered.
2055 * rclsid [I] CLSID of the proxy/stub.
2059 * Failure: E_OUTOFMEMORY
2063 * This function does not add anything to the registry and the effects are
2064 * limited to the lifetime of the current process.
2069 HRESULT WINAPI CoRegisterPSClsid(REFIID riid, REFCLSID rclsid)
2071 APARTMENT *apt = COM_CurrentApt();
2072 struct registered_psclsid *registered_psclsid;
2074 TRACE("(%s, %s)\n", debugstr_guid(riid), debugstr_guid(rclsid));
2078 ERR("apartment not initialised\n");
2079 return CO_E_NOTINITIALIZED;
2082 EnterCriticalSection(&apt->cs);
2084 LIST_FOR_EACH_ENTRY(registered_psclsid, &apt->psclsids, struct registered_psclsid, entry)
2085 if (IsEqualIID(®istered_psclsid->iid, riid))
2087 registered_psclsid->clsid = *rclsid;
2088 LeaveCriticalSection(&apt->cs);
2092 registered_psclsid = HeapAlloc(GetProcessHeap(), 0, sizeof(struct registered_psclsid));
2093 if (!registered_psclsid)
2095 LeaveCriticalSection(&apt->cs);
2096 return E_OUTOFMEMORY;
2099 registered_psclsid->iid = *riid;
2100 registered_psclsid->clsid = *rclsid;
2101 list_add_head(&apt->psclsids, ®istered_psclsid->entry);
2103 LeaveCriticalSection(&apt->cs);
2110 * COM_GetRegisteredClassObject
2112 * This internal method is used to scan the registered class list to
2113 * find a class object.
2116 * rclsid Class ID of the class to find.
2117 * dwClsContext Class context to match.
2118 * ppv [out] returns a pointer to the class object. Complying
2119 * to normal COM usage, this method will increase the
2120 * reference count on this object.
2122 static HRESULT COM_GetRegisteredClassObject(const struct apartment *apt, REFCLSID rclsid,
2123 DWORD dwClsContext, LPUNKNOWN* ppUnk)
2125 HRESULT hr = S_FALSE;
2126 RegisteredClass *curClass;
2128 EnterCriticalSection( &csRegisteredClassList );
2130 LIST_FOR_EACH_ENTRY(curClass, &RegisteredClassList, RegisteredClass, entry)
2133 * Check if we have a match on the class ID and context.
2135 if ((apt->oxid == curClass->apartment_id) &&
2136 (dwClsContext & curClass->runContext) &&
2137 IsEqualGUID(&(curClass->classIdentifier), rclsid))
2140 * We have a match, return the pointer to the class object.
2142 *ppUnk = curClass->classObject;
2144 IUnknown_AddRef(curClass->classObject);
2151 LeaveCriticalSection( &csRegisteredClassList );
2156 /******************************************************************************
2157 * CoRegisterClassObject [OLE32.@]
2159 * Registers the class object for a given class ID. Servers housed in EXE
2160 * files use this method instead of exporting DllGetClassObject to allow
2161 * other code to connect to their objects.
2164 * rclsid [I] CLSID of the object to register.
2165 * pUnk [I] IUnknown of the object.
2166 * dwClsContext [I] CLSCTX flags indicating the context in which to run the executable.
2167 * flags [I] REGCLS flags indicating how connections are made.
2168 * lpdwRegister [I] A unique cookie that can be passed to CoRevokeClassObject.
2172 * E_INVALIDARG if lpdwRegister or pUnk are NULL,
2173 * CO_E_OBJISREG if the object is already registered. We should not return this.
2176 * CoRevokeClassObject, CoGetClassObject
2179 * In-process objects are only registered for the current apartment.
2180 * CoGetClassObject() and CoCreateInstance() will not return objects registered
2181 * in other apartments.
2184 * MSDN claims that multiple interface registrations are legal, but we
2185 * can't do that with our current implementation.
2187 HRESULT WINAPI CoRegisterClassObject(
2192 LPDWORD lpdwRegister)
2194 static LONG next_cookie;
2195 RegisteredClass* newClass;
2196 LPUNKNOWN foundObject;
2200 TRACE("(%s,%p,0x%08x,0x%08x,%p)\n",
2201 debugstr_guid(rclsid),pUnk,dwClsContext,flags,lpdwRegister);
2203 if ( (lpdwRegister==0) || (pUnk==0) )
2204 return E_INVALIDARG;
2206 apt = COM_CurrentApt();
2209 ERR("COM was not initialized\n");
2210 return CO_E_NOTINITIALIZED;
2215 /* REGCLS_MULTIPLEUSE implies registering as inproc server. This is what
2216 * differentiates the flag from REGCLS_MULTI_SEPARATE. */
2217 if (flags & REGCLS_MULTIPLEUSE)
2218 dwClsContext |= CLSCTX_INPROC_SERVER;
2221 * First, check if the class is already registered.
2222 * If it is, this should cause an error.
2224 hr = COM_GetRegisteredClassObject(apt, rclsid, dwClsContext, &foundObject);
2226 if (flags & REGCLS_MULTIPLEUSE) {
2227 if (dwClsContext & CLSCTX_LOCAL_SERVER)
2228 hr = CoLockObjectExternal(foundObject, TRUE, FALSE);
2229 IUnknown_Release(foundObject);
2232 IUnknown_Release(foundObject);
2233 ERR("object already registered for class %s\n", debugstr_guid(rclsid));
2234 return CO_E_OBJISREG;
2237 newClass = HeapAlloc(GetProcessHeap(), 0, sizeof(RegisteredClass));
2238 if ( newClass == NULL )
2239 return E_OUTOFMEMORY;
2241 newClass->classIdentifier = *rclsid;
2242 newClass->apartment_id = apt->oxid;
2243 newClass->runContext = dwClsContext;
2244 newClass->connectFlags = flags;
2245 newClass->pMarshaledData = NULL;
2246 newClass->RpcRegistration = NULL;
2248 if (!(newClass->dwCookie = InterlockedIncrement( &next_cookie )))
2249 newClass->dwCookie = InterlockedIncrement( &next_cookie );
2252 * Since we're making a copy of the object pointer, we have to increase its
2255 newClass->classObject = pUnk;
2256 IUnknown_AddRef(newClass->classObject);
2258 EnterCriticalSection( &csRegisteredClassList );
2259 list_add_tail(&RegisteredClassList, &newClass->entry);
2260 LeaveCriticalSection( &csRegisteredClassList );
2262 *lpdwRegister = newClass->dwCookie;
2264 if (dwClsContext & CLSCTX_LOCAL_SERVER) {
2265 hr = CreateStreamOnHGlobal(0, TRUE, &newClass->pMarshaledData);
2267 FIXME("Failed to create stream on hglobal, %x\n", hr);
2270 hr = CoMarshalInterface(newClass->pMarshaledData, &IID_IUnknown,
2271 newClass->classObject, MSHCTX_LOCAL, NULL,
2272 MSHLFLAGS_TABLESTRONG);
2274 FIXME("CoMarshalInterface failed, %x!\n",hr);
2278 hr = RPC_StartLocalServer(&newClass->classIdentifier,
2279 newClass->pMarshaledData,
2280 flags & (REGCLS_MULTIPLEUSE|REGCLS_MULTI_SEPARATE),
2281 &newClass->RpcRegistration);
2286 static void get_threading_model(HKEY key, LPWSTR value, DWORD len)
2288 static const WCHAR wszThreadingModel[] = {'T','h','r','e','a','d','i','n','g','M','o','d','e','l',0};
2291 DWORD dwLength = len * sizeof(WCHAR);
2293 ret = RegQueryValueExW(key, wszThreadingModel, NULL, &keytype, (LPBYTE)value, &dwLength);
2294 if ((ret != ERROR_SUCCESS) || (keytype != REG_SZ))
2298 static HRESULT get_inproc_class_object(APARTMENT *apt, HKEY hkeydll,
2299 REFCLSID rclsid, REFIID riid,
2300 BOOL hostifnecessary, void **ppv)
2302 WCHAR dllpath[MAX_PATH+1];
2303 BOOL apartment_threaded;
2305 if (hostifnecessary)
2307 static const WCHAR wszApartment[] = {'A','p','a','r','t','m','e','n','t',0};
2308 static const WCHAR wszFree[] = {'F','r','e','e',0};
2309 static const WCHAR wszBoth[] = {'B','o','t','h',0};
2310 WCHAR threading_model[10 /* strlenW(L"apartment")+1 */];
2312 get_threading_model(hkeydll, threading_model, ARRAYSIZE(threading_model));
2314 if (!strcmpiW(threading_model, wszApartment))
2316 apartment_threaded = TRUE;
2317 if (apt->multi_threaded)
2318 return apartment_hostobject_in_hostapt(apt, FALSE, FALSE, hkeydll, rclsid, riid, ppv);
2321 else if (!strcmpiW(threading_model, wszFree))
2323 apartment_threaded = FALSE;
2324 if (!apt->multi_threaded)
2325 return apartment_hostobject_in_hostapt(apt, TRUE, FALSE, hkeydll, rclsid, riid, ppv);
2327 /* everything except "Apartment", "Free" and "Both" */
2328 else if (strcmpiW(threading_model, wszBoth))
2330 apartment_threaded = TRUE;
2331 /* everything else is main-threaded */
2332 if (threading_model[0])
2333 FIXME("unrecognised threading model %s for object %s, should be main-threaded?\n",
2334 debugstr_w(threading_model), debugstr_guid(rclsid));
2336 if (apt->multi_threaded || !apt->main)
2337 return apartment_hostobject_in_hostapt(apt, FALSE, TRUE, hkeydll, rclsid, riid, ppv);
2340 apartment_threaded = FALSE;
2343 apartment_threaded = !apt->multi_threaded;
2345 if (COM_RegReadPath(hkeydll, NULL, NULL, dllpath, ARRAYSIZE(dllpath)) != ERROR_SUCCESS)
2347 /* failure: CLSID is not found in registry */
2348 WARN("class %s not registered inproc\n", debugstr_guid(rclsid));
2349 return REGDB_E_CLASSNOTREG;
2352 return apartment_getclassobject(apt, dllpath, apartment_threaded,
2356 /***********************************************************************
2357 * CoGetClassObject [OLE32.@]
2359 * Creates an object of the specified class.
2362 * rclsid [I] Class ID to create an instance of.
2363 * dwClsContext [I] Flags to restrict the location of the created instance.
2364 * pServerInfo [I] Optional. Details for connecting to a remote server.
2365 * iid [I] The ID of the interface of the instance to return.
2366 * ppv [O] On returns, contains a pointer to the specified interface of the object.
2370 * Failure: HRESULT code.
2373 * The dwClsContext parameter can be one or more of the following:
2374 *| CLSCTX_INPROC_SERVER - Use an in-process server, such as from a DLL.
2375 *| CLSCTX_INPROC_HANDLER - Use an in-process object which handles certain functions for an object running in another process.
2376 *| CLSCTX_LOCAL_SERVER - Connect to an object running in another process.
2377 *| CLSCTX_REMOTE_SERVER - Connect to an object running on another machine.
2380 * CoCreateInstance()
2382 HRESULT WINAPI CoGetClassObject(
2383 REFCLSID rclsid, DWORD dwClsContext, COSERVERINFO *pServerInfo,
2384 REFIID iid, LPVOID *ppv)
2386 LPUNKNOWN regClassObject;
2387 HRESULT hres = E_UNEXPECTED;
2389 BOOL release_apt = FALSE;
2391 TRACE("CLSID: %s,IID: %s\n", debugstr_guid(rclsid), debugstr_guid(iid));
2394 return E_INVALIDARG;
2398 if (!(apt = COM_CurrentApt()))
2400 if (!(apt = apartment_find_multi_threaded()))
2402 ERR("apartment not initialised\n");
2403 return CO_E_NOTINITIALIZED;
2409 FIXME("pServerInfo->name=%s pAuthInfo=%p\n",
2410 debugstr_w(pServerInfo->pwszName), pServerInfo->pAuthInfo);
2414 * First, try and see if we can't match the class ID with one of the
2415 * registered classes.
2417 if (S_OK == COM_GetRegisteredClassObject(apt, rclsid, dwClsContext,
2420 /* Get the required interface from the retrieved pointer. */
2421 hres = IUnknown_QueryInterface(regClassObject, iid, ppv);
2424 * Since QI got another reference on the pointer, we want to release the
2425 * one we already have. If QI was unsuccessful, this will release the object. This
2426 * is good since we are not returning it in the "out" parameter.
2428 IUnknown_Release(regClassObject);
2429 if (release_apt) apartment_release(apt);
2433 /* First try in-process server */
2434 if (CLSCTX_INPROC_SERVER & dwClsContext)
2436 static const WCHAR wszInprocServer32[] = {'I','n','p','r','o','c','S','e','r','v','e','r','3','2',0};
2439 if (IsEqualCLSID(rclsid, &CLSID_InProcFreeMarshaler))
2441 if (release_apt) apartment_release(apt);
2442 return FTMarshalCF_Create(iid, ppv);
2445 hres = COM_OpenKeyForCLSID(rclsid, wszInprocServer32, KEY_READ, &hkey);
2448 if (hres == REGDB_E_CLASSNOTREG)
2449 ERR("class %s not registered\n", debugstr_guid(rclsid));
2450 else if (hres == REGDB_E_KEYMISSING)
2452 WARN("class %s not registered as in-proc server\n", debugstr_guid(rclsid));
2453 hres = REGDB_E_CLASSNOTREG;
2457 if (SUCCEEDED(hres))
2459 hres = get_inproc_class_object(apt, hkey, rclsid, iid,
2460 !(dwClsContext & WINE_CLSCTX_DONT_HOST), ppv);
2464 /* return if we got a class, otherwise fall through to one of the
2466 if (SUCCEEDED(hres))
2468 if (release_apt) apartment_release(apt);
2473 /* Next try in-process handler */
2474 if (CLSCTX_INPROC_HANDLER & dwClsContext)
2476 static const WCHAR wszInprocHandler32[] = {'I','n','p','r','o','c','H','a','n','d','l','e','r','3','2',0};
2479 hres = COM_OpenKeyForCLSID(rclsid, wszInprocHandler32, KEY_READ, &hkey);
2482 if (hres == REGDB_E_CLASSNOTREG)
2483 ERR("class %s not registered\n", debugstr_guid(rclsid));
2484 else if (hres == REGDB_E_KEYMISSING)
2486 WARN("class %s not registered in-proc handler\n", debugstr_guid(rclsid));
2487 hres = REGDB_E_CLASSNOTREG;
2491 if (SUCCEEDED(hres))
2493 hres = get_inproc_class_object(apt, hkey, rclsid, iid,
2494 !(dwClsContext & WINE_CLSCTX_DONT_HOST), ppv);
2498 /* return if we got a class, otherwise fall through to one of the
2500 if (SUCCEEDED(hres))
2502 if (release_apt) apartment_release(apt);
2506 if (release_apt) apartment_release(apt);
2508 /* Next try out of process */
2509 if (CLSCTX_LOCAL_SERVER & dwClsContext)
2511 hres = RPC_GetLocalClassObject(rclsid,iid,ppv);
2512 if (SUCCEEDED(hres))
2516 /* Finally try remote: this requires networked DCOM (a lot of work) */
2517 if (CLSCTX_REMOTE_SERVER & dwClsContext)
2519 FIXME ("CLSCTX_REMOTE_SERVER not supported\n");
2520 hres = REGDB_E_CLASSNOTREG;
2524 ERR("no class object %s could be created for context 0x%x\n",
2525 debugstr_guid(rclsid), dwClsContext);
2529 /***********************************************************************
2530 * CoResumeClassObjects (OLE32.@)
2532 * Resumes all class objects registered with REGCLS_SUSPENDED.
2536 * Failure: HRESULT code.
2538 HRESULT WINAPI CoResumeClassObjects(void)
2544 /***********************************************************************
2545 * CoCreateInstance [OLE32.@]
2547 * Creates an instance of the specified class.
2550 * rclsid [I] Class ID to create an instance of.
2551 * pUnkOuter [I] Optional outer unknown to allow aggregation with another object.
2552 * dwClsContext [I] Flags to restrict the location of the created instance.
2553 * iid [I] The ID of the interface of the instance to return.
2554 * ppv [O] On returns, contains a pointer to the specified interface of the instance.
2558 * Failure: HRESULT code.
2561 * The dwClsContext parameter can be one or more of the following:
2562 *| CLSCTX_INPROC_SERVER - Use an in-process server, such as from a DLL.
2563 *| CLSCTX_INPROC_HANDLER - Use an in-process object which handles certain functions for an object running in another process.
2564 *| CLSCTX_LOCAL_SERVER - Connect to an object running in another process.
2565 *| CLSCTX_REMOTE_SERVER - Connect to an object running on another machine.
2567 * Aggregation is the concept of deferring the IUnknown of an object to another
2568 * object. This allows a separate object to behave as though it was part of
2569 * the object and to allow this the pUnkOuter parameter can be set. Note that
2570 * not all objects support having an outer of unknown.
2573 * CoGetClassObject()
2575 HRESULT WINAPI CoCreateInstance(
2577 LPUNKNOWN pUnkOuter,
2583 LPCLASSFACTORY lpclf = 0;
2586 TRACE("(rclsid=%s, pUnkOuter=%p, dwClsContext=%08x, riid=%s, ppv=%p)\n", debugstr_guid(rclsid),
2587 pUnkOuter, dwClsContext, debugstr_guid(iid), ppv);
2596 * Initialize the "out" parameter
2600 if (!(apt = COM_CurrentApt()))
2602 if (!(apt = apartment_find_multi_threaded()))
2604 ERR("apartment not initialised\n");
2605 return CO_E_NOTINITIALIZED;
2607 apartment_release(apt);
2611 * The Standard Global Interface Table (GIT) object is a process-wide singleton.
2612 * Rather than create a class factory, we can just check for it here
2614 if (IsEqualIID(rclsid, &CLSID_StdGlobalInterfaceTable)) {
2615 if (StdGlobalInterfaceTableInstance == NULL)
2616 StdGlobalInterfaceTableInstance = StdGlobalInterfaceTable_Construct();
2617 hres = IGlobalInterfaceTable_QueryInterface( (IGlobalInterfaceTable*) StdGlobalInterfaceTableInstance, iid, ppv);
2618 if (hres) return hres;
2620 TRACE("Retrieved GIT (%p)\n", *ppv);
2624 if (IsEqualCLSID(rclsid, &CLSID_ManualResetEvent))
2625 return ManualResetEvent_Construct(pUnkOuter, iid, ppv);
2628 * Get a class factory to construct the object we want.
2630 hres = CoGetClassObject(rclsid,
2640 * Create the object and don't forget to release the factory
2642 hres = IClassFactory_CreateInstance(lpclf, pUnkOuter, iid, ppv);
2643 IClassFactory_Release(lpclf);
2646 if (hres == CLASS_E_NOAGGREGATION && pUnkOuter)
2647 FIXME("Class %s does not support aggregation\n", debugstr_guid(rclsid));
2649 FIXME("no instance created for interface %s of class %s, hres is 0x%08x\n", debugstr_guid(iid), debugstr_guid(rclsid),hres);
2655 /***********************************************************************
2656 * CoCreateInstanceEx [OLE32.@]
2658 HRESULT WINAPI CoCreateInstanceEx(
2660 LPUNKNOWN pUnkOuter,
2662 COSERVERINFO* pServerInfo,
2666 IUnknown* pUnk = NULL;
2669 ULONG successCount = 0;
2674 if ( (cmq==0) || (pResults==NULL))
2675 return E_INVALIDARG;
2677 if (pServerInfo!=NULL)
2678 FIXME("() non-NULL pServerInfo not supported!\n");
2681 * Initialize all the "out" parameters.
2683 for (index = 0; index < cmq; index++)
2685 pResults[index].pItf = NULL;
2686 pResults[index].hr = E_NOINTERFACE;
2690 * Get the object and get its IUnknown pointer.
2692 hr = CoCreateInstance(rclsid,
2702 * Then, query for all the interfaces requested.
2704 for (index = 0; index < cmq; index++)
2706 pResults[index].hr = IUnknown_QueryInterface(pUnk,
2707 pResults[index].pIID,
2708 (VOID**)&(pResults[index].pItf));
2710 if (pResults[index].hr == S_OK)
2715 * Release our temporary unknown pointer.
2717 IUnknown_Release(pUnk);
2719 if (successCount == 0)
2720 return E_NOINTERFACE;
2722 if (successCount!=cmq)
2723 return CO_S_NOTALLINTERFACES;
2728 /***********************************************************************
2729 * CoLoadLibrary (OLE32.@)
2734 * lpszLibName [I] Path to library.
2735 * bAutoFree [I] Whether the library should automatically be freed.
2738 * Success: Handle to loaded library.
2742 * CoFreeLibrary, CoFreeAllLibraries, CoFreeUnusedLibraries
2744 HINSTANCE WINAPI CoLoadLibrary(LPOLESTR lpszLibName, BOOL bAutoFree)
2746 TRACE("(%s, %d)\n", debugstr_w(lpszLibName), bAutoFree);
2748 return LoadLibraryExW(lpszLibName, 0, LOAD_WITH_ALTERED_SEARCH_PATH);
2751 /***********************************************************************
2752 * CoFreeLibrary [OLE32.@]
2754 * Unloads a library from memory.
2757 * hLibrary [I] Handle to library to unload.
2763 * CoLoadLibrary, CoFreeAllLibraries, CoFreeUnusedLibraries
2765 void WINAPI CoFreeLibrary(HINSTANCE hLibrary)
2767 FreeLibrary(hLibrary);
2771 /***********************************************************************
2772 * CoFreeAllLibraries [OLE32.@]
2774 * Function for backwards compatibility only. Does nothing.
2780 * CoLoadLibrary, CoFreeLibrary, CoFreeUnusedLibraries
2782 void WINAPI CoFreeAllLibraries(void)
2787 /***********************************************************************
2788 * CoFreeUnusedLibrariesEx [OLE32.@]
2790 * Frees any previously unused libraries whose delay has expired and marks
2791 * currently unused libraries for unloading. Unused are identified as those that
2792 * return S_OK from their DllCanUnloadNow function.
2795 * dwUnloadDelay [I] Unload delay in milliseconds.
2796 * dwReserved [I] Reserved. Set to 0.
2802 * CoLoadLibrary, CoFreeAllLibraries, CoFreeLibrary
2804 void WINAPI CoFreeUnusedLibrariesEx(DWORD dwUnloadDelay, DWORD dwReserved)
2806 struct apartment *apt = COM_CurrentApt();
2809 ERR("apartment not initialised\n");
2813 apartment_freeunusedlibraries(apt, dwUnloadDelay);
2816 /***********************************************************************
2817 * CoFreeUnusedLibraries [OLE32.@]
2819 * Frees any unused libraries. Unused are identified as those that return
2820 * S_OK from their DllCanUnloadNow function.
2826 * CoLoadLibrary, CoFreeAllLibraries, CoFreeLibrary
2828 void WINAPI CoFreeUnusedLibraries(void)
2830 CoFreeUnusedLibrariesEx(INFINITE, 0);
2833 /***********************************************************************
2834 * CoFileTimeNow [OLE32.@]
2836 * Retrieves the current time in FILETIME format.
2839 * lpFileTime [O] The current time.
2844 HRESULT WINAPI CoFileTimeNow( FILETIME *lpFileTime )
2846 GetSystemTimeAsFileTime( lpFileTime );
2850 /******************************************************************************
2851 * CoLockObjectExternal [OLE32.@]
2853 * Increments or decrements the external reference count of a stub object.
2856 * pUnk [I] Stub object.
2857 * fLock [I] If TRUE then increments the external ref-count,
2858 * otherwise decrements.
2859 * fLastUnlockReleases [I] If TRUE then the last unlock has the effect of
2860 * calling CoDisconnectObject.
2864 * Failure: HRESULT code.
2867 * If fLock is TRUE and an object is passed in that doesn't have a stub
2868 * manager then a new stub manager is created for the object.
2870 HRESULT WINAPI CoLockObjectExternal(
2873 BOOL fLastUnlockReleases)
2875 struct stub_manager *stubmgr;
2876 struct apartment *apt;
2878 TRACE("pUnk=%p, fLock=%s, fLastUnlockReleases=%s\n",
2879 pUnk, fLock ? "TRUE" : "FALSE", fLastUnlockReleases ? "TRUE" : "FALSE");
2881 apt = COM_CurrentApt();
2882 if (!apt) return CO_E_NOTINITIALIZED;
2884 stubmgr = get_stub_manager_from_object(apt, pUnk);
2889 stub_manager_ext_addref(stubmgr, 1, FALSE);
2891 stub_manager_ext_release(stubmgr, 1, FALSE, fLastUnlockReleases);
2893 stub_manager_int_release(stubmgr);
2899 stubmgr = new_stub_manager(apt, pUnk);
2903 stub_manager_ext_addref(stubmgr, 1, FALSE);
2904 stub_manager_int_release(stubmgr);
2911 WARN("stub object not found %p\n", pUnk);
2912 /* Note: native is pretty broken here because it just silently
2913 * fails, without returning an appropriate error code, making apps
2914 * think that the object was disconnected, when it actually wasn't */
2919 /***********************************************************************
2920 * CoInitializeWOW (OLE32.@)
2922 * WOW equivalent of CoInitialize?
2931 HRESULT WINAPI CoInitializeWOW(DWORD x,DWORD y)
2933 FIXME("(0x%08x,0x%08x),stub!\n",x,y);
2937 /***********************************************************************
2938 * CoGetState [OLE32.@]
2940 * Retrieves the thread state object previously stored by CoSetState().
2943 * ppv [I] Address where pointer to object will be stored.
2947 * Failure: E_OUTOFMEMORY.
2950 * Crashes on all invalid ppv addresses, including NULL.
2951 * If the function returns a non-NULL object then the caller must release its
2952 * reference on the object when the object is no longer required.
2957 HRESULT WINAPI CoGetState(IUnknown ** ppv)
2959 struct oletls *info = COM_CurrentInfo();
2960 if (!info) return E_OUTOFMEMORY;
2966 IUnknown_AddRef(info->state);
2968 TRACE("apt->state=%p\n", info->state);
2974 /***********************************************************************
2975 * CoSetState [OLE32.@]
2977 * Sets the thread state object.
2980 * pv [I] Pointer to state object to be stored.
2983 * The system keeps a reference on the object while the object stored.
2987 * Failure: E_OUTOFMEMORY.
2989 HRESULT WINAPI CoSetState(IUnknown * pv)
2991 struct oletls *info = COM_CurrentInfo();
2992 if (!info) return E_OUTOFMEMORY;
2994 if (pv) IUnknown_AddRef(pv);
2998 TRACE("-- release %p now\n", info->state);
2999 IUnknown_Release(info->state);
3008 /******************************************************************************
3009 * CoTreatAsClass [OLE32.@]
3011 * Sets the TreatAs value of a class.
3014 * clsidOld [I] Class to set TreatAs value on.
3015 * clsidNew [I] The class the clsidOld should be treated as.
3019 * Failure: HRESULT code.
3024 HRESULT WINAPI CoTreatAsClass(REFCLSID clsidOld, REFCLSID clsidNew)
3026 static const WCHAR wszAutoTreatAs[] = {'A','u','t','o','T','r','e','a','t','A','s',0};
3027 static const WCHAR wszTreatAs[] = {'T','r','e','a','t','A','s',0};
3029 WCHAR szClsidNew[CHARS_IN_GUID];
3031 WCHAR auto_treat_as[CHARS_IN_GUID];
3032 LONG auto_treat_as_size = sizeof(auto_treat_as);
3035 res = COM_OpenKeyForCLSID(clsidOld, NULL, KEY_READ | KEY_WRITE, &hkey);
3038 if (!memcmp( clsidOld, clsidNew, sizeof(*clsidOld) ))
3040 if (!RegQueryValueW(hkey, wszAutoTreatAs, auto_treat_as, &auto_treat_as_size) &&
3041 CLSIDFromString(auto_treat_as, &id) == S_OK)
3043 if (RegSetValueW(hkey, wszTreatAs, REG_SZ, auto_treat_as, sizeof(auto_treat_as)))
3045 res = REGDB_E_WRITEREGDB;
3051 RegDeleteKeyW(hkey, wszTreatAs);
3055 else if (!StringFromGUID2(clsidNew, szClsidNew, ARRAYSIZE(szClsidNew)) &&
3056 !RegSetValueW(hkey, wszTreatAs, REG_SZ, szClsidNew, sizeof(szClsidNew)))
3058 res = REGDB_E_WRITEREGDB;
3063 if (hkey) RegCloseKey(hkey);
3067 /******************************************************************************
3068 * CoGetTreatAsClass [OLE32.@]
3070 * Gets the TreatAs value of a class.
3073 * clsidOld [I] Class to get the TreatAs value of.
3074 * clsidNew [I] The class the clsidOld should be treated as.
3078 * Failure: HRESULT code.
3083 HRESULT WINAPI CoGetTreatAsClass(REFCLSID clsidOld, LPCLSID clsidNew)
3085 static const WCHAR wszTreatAs[] = {'T','r','e','a','t','A','s',0};
3087 WCHAR szClsidNew[CHARS_IN_GUID];
3089 LONG len = sizeof(szClsidNew);
3091 TRACE("(%s,%p)\n", debugstr_guid(clsidOld), clsidNew);
3092 *clsidNew = *clsidOld; /* copy over old value */
3094 res = COM_OpenKeyForCLSID(clsidOld, wszTreatAs, KEY_READ, &hkey);
3100 if (RegQueryValueW(hkey, NULL, szClsidNew, &len))
3105 res = CLSIDFromString(szClsidNew,clsidNew);
3107 ERR("Failed CLSIDFromStringA(%s), hres 0x%08x\n", debugstr_w(szClsidNew), res);
3109 if (hkey) RegCloseKey(hkey);
3113 /******************************************************************************
3114 * CoGetCurrentProcess [OLE32.@]
3116 * Gets the current process ID.
3119 * The current process ID.
3122 * Is DWORD really the correct return type for this function?
3124 DWORD WINAPI CoGetCurrentProcess(void)
3126 return GetCurrentProcessId();
3129 /******************************************************************************
3130 * CoRegisterMessageFilter [OLE32.@]
3132 * Registers a message filter.
3135 * lpMessageFilter [I] Pointer to interface.
3136 * lplpMessageFilter [O] Indirect pointer to prior instance if non-NULL.
3140 * Failure: HRESULT code.
3143 * Both lpMessageFilter and lplpMessageFilter are optional. Passing in a NULL
3144 * lpMessageFilter removes the message filter.
3146 * If lplpMessageFilter is not NULL the previous message filter will be
3147 * returned in the memory pointer to this parameter and the caller is
3148 * responsible for releasing the object.
3150 * The current thread be in an apartment otherwise the function will crash.
3152 HRESULT WINAPI CoRegisterMessageFilter(
3153 LPMESSAGEFILTER lpMessageFilter,
3154 LPMESSAGEFILTER *lplpMessageFilter)
3156 struct apartment *apt;
3157 IMessageFilter *lpOldMessageFilter;
3159 TRACE("(%p, %p)\n", lpMessageFilter, lplpMessageFilter);
3161 apt = COM_CurrentApt();
3163 /* can't set a message filter in a multi-threaded apartment */
3164 if (!apt || apt->multi_threaded)
3166 WARN("can't set message filter in MTA or uninitialized apt\n");
3167 return CO_E_NOT_SUPPORTED;
3170 if (lpMessageFilter)
3171 IMessageFilter_AddRef(lpMessageFilter);
3173 EnterCriticalSection(&apt->cs);
3175 lpOldMessageFilter = apt->filter;
3176 apt->filter = lpMessageFilter;
3178 LeaveCriticalSection(&apt->cs);
3180 if (lplpMessageFilter)
3181 *lplpMessageFilter = lpOldMessageFilter;
3182 else if (lpOldMessageFilter)
3183 IMessageFilter_Release(lpOldMessageFilter);
3188 /***********************************************************************
3189 * CoIsOle1Class [OLE32.@]
3191 * Determines whether the specified class an OLE v1 class.
3194 * clsid [I] Class to test.
3197 * TRUE if the class is an OLE v1 class, or FALSE otherwise.
3199 BOOL WINAPI CoIsOle1Class(REFCLSID clsid)
3201 FIXME("%s\n", debugstr_guid(clsid));
3205 /***********************************************************************
3206 * IsEqualGUID [OLE32.@]
3208 * Compares two Unique Identifiers.
3211 * rguid1 [I] The first GUID to compare.
3212 * rguid2 [I] The other GUID to compare.
3218 BOOL WINAPI IsEqualGUID(
3222 return !memcmp(rguid1,rguid2,sizeof(GUID));
3225 /***********************************************************************
3226 * CoInitializeSecurity [OLE32.@]
3228 HRESULT WINAPI CoInitializeSecurity(PSECURITY_DESCRIPTOR pSecDesc, LONG cAuthSvc,
3229 SOLE_AUTHENTICATION_SERVICE* asAuthSvc,
3230 void* pReserved1, DWORD dwAuthnLevel,
3231 DWORD dwImpLevel, void* pReserved2,
3232 DWORD dwCapabilities, void* pReserved3)
3234 FIXME("(%p,%d,%p,%p,%d,%d,%p,%d,%p) - stub!\n", pSecDesc, cAuthSvc,
3235 asAuthSvc, pReserved1, dwAuthnLevel, dwImpLevel, pReserved2,
3236 dwCapabilities, pReserved3);
3240 /***********************************************************************
3241 * CoSuspendClassObjects [OLE32.@]
3243 * Suspends all registered class objects to prevent further requests coming in
3244 * for those objects.
3248 * Failure: HRESULT code.
3250 HRESULT WINAPI CoSuspendClassObjects(void)
3256 /***********************************************************************
3257 * CoAddRefServerProcess [OLE32.@]
3259 * Helper function for incrementing the reference count of a local-server
3263 * New reference count.
3266 * CoReleaseServerProcess().
3268 ULONG WINAPI CoAddRefServerProcess(void)
3274 EnterCriticalSection(&csRegisteredClassList);
3275 refs = ++s_COMServerProcessReferences;
3276 LeaveCriticalSection(&csRegisteredClassList);
3278 TRACE("refs before: %d\n", refs - 1);
3283 /***********************************************************************
3284 * CoReleaseServerProcess [OLE32.@]
3286 * Helper function for decrementing the reference count of a local-server
3290 * New reference count.
3293 * When reference count reaches 0, this function suspends all registered
3294 * classes so no new connections are accepted.
3297 * CoAddRefServerProcess(), CoSuspendClassObjects().
3299 ULONG WINAPI CoReleaseServerProcess(void)
3305 EnterCriticalSection(&csRegisteredClassList);
3307 refs = --s_COMServerProcessReferences;
3308 /* FIXME: if (!refs) COM_SuspendClassObjects(); */
3310 LeaveCriticalSection(&csRegisteredClassList);
3312 TRACE("refs after: %d\n", refs);
3317 /***********************************************************************
3318 * CoIsHandlerConnected [OLE32.@]
3320 * Determines whether a proxy is connected to a remote stub.
3323 * pUnk [I] Pointer to object that may or may not be connected.
3326 * TRUE if pUnk is not a proxy or if pUnk is connected to a remote stub, or
3329 BOOL WINAPI CoIsHandlerConnected(IUnknown *pUnk)
3331 FIXME("%p\n", pUnk);
3336 /***********************************************************************
3337 * CoAllowSetForegroundWindow [OLE32.@]
3340 HRESULT WINAPI CoAllowSetForegroundWindow(IUnknown *pUnk, void *pvReserved)
3342 FIXME("(%p, %p): stub\n", pUnk, pvReserved);
3346 /***********************************************************************
3347 * CoQueryProxyBlanket [OLE32.@]
3349 * Retrieves the security settings being used by a proxy.
3352 * pProxy [I] Pointer to the proxy object.
3353 * pAuthnSvc [O] The type of authentication service.
3354 * pAuthzSvc [O] The type of authorization service.
3355 * ppServerPrincName [O] Optional. The server prinicple name.
3356 * pAuthnLevel [O] The authentication level.
3357 * pImpLevel [O] The impersonation level.
3358 * ppAuthInfo [O] Information specific to the authorization/authentication service.
3359 * pCapabilities [O] Flags affecting the security behaviour.
3363 * Failure: HRESULT code.
3366 * CoCopyProxy, CoSetProxyBlanket.
3368 HRESULT WINAPI CoQueryProxyBlanket(IUnknown *pProxy, DWORD *pAuthnSvc,
3369 DWORD *pAuthzSvc, OLECHAR **ppServerPrincName, DWORD *pAuthnLevel,
3370 DWORD *pImpLevel, void **ppAuthInfo, DWORD *pCapabilities)
3372 IClientSecurity *pCliSec;
3375 TRACE("%p\n", pProxy);
3377 hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
3380 hr = IClientSecurity_QueryBlanket(pCliSec, pProxy, pAuthnSvc,
3381 pAuthzSvc, ppServerPrincName,
3382 pAuthnLevel, pImpLevel, ppAuthInfo,
3384 IClientSecurity_Release(pCliSec);
3387 if (FAILED(hr)) ERR("-- failed with 0x%08x\n", hr);
3391 /***********************************************************************
3392 * CoSetProxyBlanket [OLE32.@]
3394 * Sets the security settings for a proxy.
3397 * pProxy [I] Pointer to the proxy object.
3398 * AuthnSvc [I] The type of authentication service.
3399 * AuthzSvc [I] The type of authorization service.
3400 * pServerPrincName [I] The server prinicple name.
3401 * AuthnLevel [I] The authentication level.
3402 * ImpLevel [I] The impersonation level.
3403 * pAuthInfo [I] Information specific to the authorization/authentication service.
3404 * Capabilities [I] Flags affecting the security behaviour.
3408 * Failure: HRESULT code.
3411 * CoQueryProxyBlanket, CoCopyProxy.
3413 HRESULT WINAPI CoSetProxyBlanket(IUnknown *pProxy, DWORD AuthnSvc,
3414 DWORD AuthzSvc, OLECHAR *pServerPrincName, DWORD AuthnLevel,
3415 DWORD ImpLevel, void *pAuthInfo, DWORD Capabilities)
3417 IClientSecurity *pCliSec;
3420 TRACE("%p\n", pProxy);
3422 hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
3425 hr = IClientSecurity_SetBlanket(pCliSec, pProxy, AuthnSvc,
3426 AuthzSvc, pServerPrincName,
3427 AuthnLevel, ImpLevel, pAuthInfo,
3429 IClientSecurity_Release(pCliSec);
3432 if (FAILED(hr)) ERR("-- failed with 0x%08x\n", hr);
3436 /***********************************************************************
3437 * CoCopyProxy [OLE32.@]
3442 * pProxy [I] Pointer to the proxy object.
3443 * ppCopy [O] Copy of the proxy.
3447 * Failure: HRESULT code.
3450 * CoQueryProxyBlanket, CoSetProxyBlanket.
3452 HRESULT WINAPI CoCopyProxy(IUnknown *pProxy, IUnknown **ppCopy)
3454 IClientSecurity *pCliSec;
3457 TRACE("%p\n", pProxy);
3459 hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
3462 hr = IClientSecurity_CopyProxy(pCliSec, pProxy, ppCopy);
3463 IClientSecurity_Release(pCliSec);
3466 if (FAILED(hr)) ERR("-- failed with 0x%08x\n", hr);
3471 /***********************************************************************
3472 * CoGetCallContext [OLE32.@]
3474 * Gets the context of the currently executing server call in the current
3478 * riid [I] Context interface to return.
3479 * ppv [O] Pointer to memory that will receive the context on return.
3483 * Failure: HRESULT code.
3485 HRESULT WINAPI CoGetCallContext(REFIID riid, void **ppv)
3487 struct oletls *info = COM_CurrentInfo();
3489 TRACE("(%s, %p)\n", debugstr_guid(riid), ppv);
3492 return E_OUTOFMEMORY;
3494 if (!info->call_state)
3495 return RPC_E_CALL_COMPLETE;
3497 return IUnknown_QueryInterface(info->call_state, riid, ppv);
3500 /***********************************************************************
3501 * CoSwitchCallContext [OLE32.@]
3503 * Switches the context of the currently executing server call in the current
3507 * pObject [I] Pointer to new context object
3508 * ppOldObject [O] Pointer to memory that will receive old context object pointer
3512 * Failure: HRESULT code.
3514 HRESULT WINAPI CoSwitchCallContext(IUnknown *pObject, IUnknown **ppOldObject)
3516 struct oletls *info = COM_CurrentInfo();
3518 TRACE("(%p, %p)\n", pObject, ppOldObject);
3521 return E_OUTOFMEMORY;
3523 *ppOldObject = info->call_state;
3524 info->call_state = pObject; /* CoSwitchCallContext does not addref nor release objects */
3529 /***********************************************************************
3530 * CoQueryClientBlanket [OLE32.@]
3532 * Retrieves the authentication information about the client of the currently
3533 * executing server call in the current thread.
3536 * pAuthnSvc [O] Optional. The type of authentication service.
3537 * pAuthzSvc [O] Optional. The type of authorization service.
3538 * pServerPrincName [O] Optional. The server prinicple name.
3539 * pAuthnLevel [O] Optional. The authentication level.
3540 * pImpLevel [O] Optional. The impersonation level.
3541 * pPrivs [O] Optional. Information about the privileges of the client.
3542 * pCapabilities [IO] Optional. Flags affecting the security behaviour.
3546 * Failure: HRESULT code.
3549 * CoImpersonateClient, CoRevertToSelf, CoGetCallContext.
3551 HRESULT WINAPI CoQueryClientBlanket(
3554 OLECHAR **pServerPrincName,
3557 RPC_AUTHZ_HANDLE *pPrivs,
3558 DWORD *pCapabilities)
3560 IServerSecurity *pSrvSec;
3563 TRACE("(%p, %p, %p, %p, %p, %p, %p)\n",
3564 pAuthnSvc, pAuthzSvc, pServerPrincName, pAuthnLevel, pImpLevel,
3565 pPrivs, pCapabilities);
3567 hr = CoGetCallContext(&IID_IServerSecurity, (void **)&pSrvSec);
3570 hr = IServerSecurity_QueryBlanket(
3571 pSrvSec, pAuthnSvc, pAuthzSvc, pServerPrincName, pAuthnLevel,
3572 pImpLevel, pPrivs, pCapabilities);
3573 IServerSecurity_Release(pSrvSec);
3579 /***********************************************************************
3580 * CoImpersonateClient [OLE32.@]
3582 * Impersonates the client of the currently executing server call in the
3590 * Failure: HRESULT code.
3593 * If this function fails then the current thread will not be impersonating
3594 * the client and all actions will take place on behalf of the server.
3595 * Therefore, it is important to check the return value from this function.
3598 * CoRevertToSelf, CoQueryClientBlanket, CoGetCallContext.
3600 HRESULT WINAPI CoImpersonateClient(void)
3602 IServerSecurity *pSrvSec;
3607 hr = CoGetCallContext(&IID_IServerSecurity, (void **)&pSrvSec);
3610 hr = IServerSecurity_ImpersonateClient(pSrvSec);
3611 IServerSecurity_Release(pSrvSec);
3617 /***********************************************************************
3618 * CoRevertToSelf [OLE32.@]
3620 * Ends the impersonation of the client of the currently executing server
3621 * call in the current thread.
3628 * Failure: HRESULT code.
3631 * CoImpersonateClient, CoQueryClientBlanket, CoGetCallContext.
3633 HRESULT WINAPI CoRevertToSelf(void)
3635 IServerSecurity *pSrvSec;
3640 hr = CoGetCallContext(&IID_IServerSecurity, (void **)&pSrvSec);
3643 hr = IServerSecurity_RevertToSelf(pSrvSec);
3644 IServerSecurity_Release(pSrvSec);
3650 static BOOL COM_PeekMessage(struct apartment *apt, MSG *msg)
3652 /* first try to retrieve messages for incoming COM calls to the apartment window */
3653 return PeekMessageW(msg, apt->win, 0, 0, PM_REMOVE|PM_NOYIELD) ||
3654 /* next retrieve other messages necessary for the app to remain responsive */
3655 PeekMessageW(msg, NULL, WM_DDE_FIRST, WM_DDE_LAST, PM_REMOVE|PM_NOYIELD) ||
3656 PeekMessageW(msg, NULL, 0, 0, PM_QS_PAINT|PM_QS_SENDMESSAGE|PM_REMOVE|PM_NOYIELD);
3659 /***********************************************************************
3660 * CoWaitForMultipleHandles [OLE32.@]
3662 * Waits for one or more handles to become signaled.
3665 * dwFlags [I] Flags. See notes.
3666 * dwTimeout [I] Timeout in milliseconds.
3667 * cHandles [I] Number of handles pointed to by pHandles.
3668 * pHandles [I] Handles to wait for.
3669 * lpdwindex [O] Index of handle that was signaled.
3673 * Failure: RPC_S_CALLPENDING on timeout.
3677 * The dwFlags parameter can be zero or more of the following:
3678 *| COWAIT_WAITALL - Wait for all of the handles to become signaled.
3679 *| COWAIT_ALERTABLE - Allows a queued APC to run during the wait.
3682 * MsgWaitForMultipleObjects, WaitForMultipleObjects.
3684 HRESULT WINAPI CoWaitForMultipleHandles(DWORD dwFlags, DWORD dwTimeout,
3685 ULONG cHandles, LPHANDLE pHandles, LPDWORD lpdwindex)
3688 DWORD start_time = GetTickCount();
3689 APARTMENT *apt = COM_CurrentApt();
3690 BOOL message_loop = apt && !apt->multi_threaded;
3692 TRACE("(0x%08x, 0x%08x, %d, %p, %p)\n", dwFlags, dwTimeout, cHandles,
3693 pHandles, lpdwindex);
3697 DWORD now = GetTickCount();
3700 if (now - start_time > dwTimeout)
3702 hr = RPC_S_CALLPENDING;
3708 DWORD wait_flags = ((dwFlags & COWAIT_WAITALL) ? MWMO_WAITALL : 0) |
3709 ((dwFlags & COWAIT_ALERTABLE ) ? MWMO_ALERTABLE : 0);
3711 TRACE("waiting for rpc completion or window message\n");
3713 res = MsgWaitForMultipleObjectsEx(cHandles, pHandles,
3714 (dwTimeout == INFINITE) ? INFINITE : start_time + dwTimeout - now,
3715 QS_SENDMESSAGE | QS_ALLPOSTMESSAGE | QS_PAINT, wait_flags);
3717 if (res == WAIT_OBJECT_0 + cHandles) /* messages available */
3721 /* call message filter */
3723 if (COM_CurrentApt()->filter)
3725 PENDINGTYPE pendingtype =
3726 COM_CurrentInfo()->pending_call_count_server ?
3727 PENDINGTYPE_NESTED : PENDINGTYPE_TOPLEVEL;
3728 DWORD be_handled = IMessageFilter_MessagePending(
3729 COM_CurrentApt()->filter, 0 /* FIXME */,
3730 now - start_time, pendingtype);
3731 TRACE("IMessageFilter_MessagePending returned %d\n", be_handled);
3734 case PENDINGMSG_CANCELCALL:
3735 WARN("call canceled\n");
3736 hr = RPC_E_CALL_CANCELED;
3738 case PENDINGMSG_WAITNOPROCESS:
3739 case PENDINGMSG_WAITDEFPROCESS:
3741 /* FIXME: MSDN is very vague about the difference
3742 * between WAITNOPROCESS and WAITDEFPROCESS - there
3743 * appears to be none, so it is possibly a left-over
3744 * from the 16-bit world. */
3749 while (COM_PeekMessage(apt, &msg))
3751 TRACE("received message whilst waiting for RPC: 0x%04x\n", msg.message);
3752 TranslateMessage(&msg);
3753 DispatchMessageW(&msg);
3754 if (msg.message == WM_QUIT)
3756 TRACE("resending WM_QUIT to outer message loop\n");
3757 PostQuitMessage(msg.wParam);
3758 /* no longer need to process messages */
3759 message_loop = FALSE;
3768 TRACE("waiting for rpc completion\n");
3770 res = WaitForMultipleObjectsEx(cHandles, pHandles,
3771 (dwFlags & COWAIT_WAITALL) ? TRUE : FALSE,
3772 (dwTimeout == INFINITE) ? INFINITE : start_time + dwTimeout - now,
3773 (dwFlags & COWAIT_ALERTABLE) ? TRUE : FALSE);
3779 hr = RPC_S_CALLPENDING;
3782 hr = HRESULT_FROM_WIN32( GetLastError() );
3790 TRACE("-- 0x%08x\n", hr);
3795 /***********************************************************************
3796 * CoGetObject [OLE32.@]
3798 * Gets the object named by converting the name to a moniker and binding to it.
3801 * pszName [I] String representing the object.
3802 * pBindOptions [I] Parameters affecting the binding to the named object.
3803 * riid [I] Interface to bind to on the objecct.
3804 * ppv [O] On output, the interface riid of the object represented
3809 * Failure: HRESULT code.
3812 * MkParseDisplayName.
3814 HRESULT WINAPI CoGetObject(LPCWSTR pszName, BIND_OPTS *pBindOptions,
3815 REFIID riid, void **ppv)
3822 hr = CreateBindCtx(0, &pbc);
3826 hr = IBindCtx_SetBindOptions(pbc, pBindOptions);
3833 hr = MkParseDisplayName(pbc, pszName, &chEaten, &pmk);
3836 hr = IMoniker_BindToObject(pmk, pbc, NULL, riid, ppv);
3837 IMoniker_Release(pmk);
3841 IBindCtx_Release(pbc);
3846 /***********************************************************************
3847 * CoRegisterChannelHook [OLE32.@]
3849 * Registers a process-wide hook that is called during ORPC calls.
3852 * guidExtension [I] GUID of the channel hook to register.
3853 * pChannelHook [I] Channel hook object to register.
3857 * Failure: HRESULT code.
3859 HRESULT WINAPI CoRegisterChannelHook(REFGUID guidExtension, IChannelHook *pChannelHook)
3861 TRACE("(%s, %p)\n", debugstr_guid(guidExtension), pChannelHook);
3863 return RPC_RegisterChannelHook(guidExtension, pChannelHook);
3866 typedef struct Context
3868 IComThreadingInfo IComThreadingInfo_iface;
3869 IContextCallback IContextCallback_iface;
3870 IObjContext IObjContext_iface;
3875 static inline Context *impl_from_IComThreadingInfo( IComThreadingInfo *iface )
3877 return CONTAINING_RECORD(iface, Context, IComThreadingInfo_iface);
3880 static inline Context *impl_from_IContextCallback( IContextCallback *iface )
3882 return CONTAINING_RECORD(iface, Context, IContextCallback_iface);
3885 static inline Context *impl_from_IObjContext( IObjContext *iface )
3887 return CONTAINING_RECORD(iface, Context, IObjContext_iface);
3890 static HRESULT Context_QueryInterface(Context *iface, REFIID riid, LPVOID *ppv)
3894 if (IsEqualIID(riid, &IID_IComThreadingInfo) ||
3895 IsEqualIID(riid, &IID_IUnknown))
3897 *ppv = &iface->IComThreadingInfo_iface;
3899 else if (IsEqualIID(riid, &IID_IContextCallback))
3901 *ppv = &iface->IContextCallback_iface;
3903 else if (IsEqualIID(riid, &IID_IObjContext))
3905 *ppv = &iface->IObjContext_iface;
3910 IUnknown_AddRef((IUnknown*)*ppv);
3914 FIXME("interface not implemented %s\n", debugstr_guid(riid));
3915 return E_NOINTERFACE;
3918 static ULONG Context_AddRef(Context *This)
3920 return InterlockedIncrement(&This->refs);
3923 static ULONG Context_Release(Context *This)
3925 ULONG refs = InterlockedDecrement(&This->refs);
3927 HeapFree(GetProcessHeap(), 0, This);
3931 static HRESULT WINAPI Context_CTI_QueryInterface(IComThreadingInfo *iface, REFIID riid, LPVOID *ppv)
3933 Context *This = impl_from_IComThreadingInfo(iface);
3934 return Context_QueryInterface(This, riid, ppv);
3937 static ULONG WINAPI Context_CTI_AddRef(IComThreadingInfo *iface)
3939 Context *This = impl_from_IComThreadingInfo(iface);
3940 return Context_AddRef(This);
3943 static ULONG WINAPI Context_CTI_Release(IComThreadingInfo *iface)
3945 Context *This = impl_from_IComThreadingInfo(iface);
3946 return Context_Release(This);
3949 static HRESULT WINAPI Context_CTI_GetCurrentApartmentType(IComThreadingInfo *iface, APTTYPE *apttype)
3951 Context *This = impl_from_IComThreadingInfo(iface);
3953 TRACE("(%p)\n", apttype);
3955 *apttype = This->apttype;
3959 static HRESULT WINAPI Context_CTI_GetCurrentThreadType(IComThreadingInfo *iface, THDTYPE *thdtype)
3961 Context *This = impl_from_IComThreadingInfo(iface);
3963 TRACE("(%p)\n", thdtype);
3965 switch (This->apttype)
3968 case APTTYPE_MAINSTA:
3969 *thdtype = THDTYPE_PROCESSMESSAGES;
3972 *thdtype = THDTYPE_BLOCKMESSAGES;
3978 static HRESULT WINAPI Context_CTI_GetCurrentLogicalThreadId(IComThreadingInfo *iface, GUID *logical_thread_id)
3980 FIXME("(%p): stub\n", logical_thread_id);
3984 static HRESULT WINAPI Context_CTI_SetCurrentLogicalThreadId(IComThreadingInfo *iface, REFGUID logical_thread_id)
3986 FIXME("(%s): stub\n", debugstr_guid(logical_thread_id));
3990 static const IComThreadingInfoVtbl Context_Threading_Vtbl =
3992 Context_CTI_QueryInterface,
3994 Context_CTI_Release,
3995 Context_CTI_GetCurrentApartmentType,
3996 Context_CTI_GetCurrentThreadType,
3997 Context_CTI_GetCurrentLogicalThreadId,
3998 Context_CTI_SetCurrentLogicalThreadId
4001 static HRESULT WINAPI Context_CC_QueryInterface(IContextCallback *iface, REFIID riid, LPVOID *ppv)
4003 Context *This = impl_from_IContextCallback(iface);
4004 return Context_QueryInterface(This, riid, ppv);
4007 static ULONG WINAPI Context_CC_AddRef(IContextCallback *iface)
4009 Context *This = impl_from_IContextCallback(iface);
4010 return Context_AddRef(This);
4013 static ULONG WINAPI Context_CC_Release(IContextCallback *iface)
4015 Context *This = impl_from_IContextCallback(iface);
4016 return Context_Release(This);
4019 static HRESULT WINAPI Context_CC_ContextCallback(IContextCallback *iface, PFNCONTEXTCALL pCallback,
4020 ComCallData *param, REFIID riid, int method, IUnknown *punk)
4022 Context *This = impl_from_IContextCallback(iface);
4024 FIXME("(%p/%p)->(%p, %p, %s, %d, %p)\n", This, iface, pCallback, param, debugstr_guid(riid), method, punk);
4028 static const IContextCallbackVtbl Context_Callback_Vtbl =
4030 Context_CC_QueryInterface,
4033 Context_CC_ContextCallback
4036 static HRESULT WINAPI Context_OC_QueryInterface(IObjContext *iface, REFIID riid, LPVOID *ppv)
4038 Context *This = impl_from_IObjContext(iface);
4039 return Context_QueryInterface(This, riid, ppv);
4042 static ULONG WINAPI Context_OC_AddRef(IObjContext *iface)
4044 Context *This = impl_from_IObjContext(iface);
4045 return Context_AddRef(This);
4048 static ULONG WINAPI Context_OC_Release(IObjContext *iface)
4050 Context *This = impl_from_IObjContext(iface);
4051 return Context_Release(This);
4054 static HRESULT WINAPI Context_OC_SetProperty(IObjContext *iface, REFGUID propid, CPFLAGS flags, IUnknown *punk)
4056 Context *This = impl_from_IObjContext(iface);
4058 FIXME("(%p/%p)->(%s, %x, %p)\n", This, iface, debugstr_guid(propid), flags, punk);
4062 static HRESULT WINAPI Context_OC_RemoveProperty(IObjContext *iface, REFGUID propid)
4064 Context *This = impl_from_IObjContext(iface);
4066 FIXME("(%p/%p)->(%s)\n", This, iface, debugstr_guid(propid));
4070 static HRESULT WINAPI Context_OC_GetProperty(IObjContext *iface, REFGUID propid, CPFLAGS *flags, IUnknown **punk)
4072 Context *This = impl_from_IObjContext(iface);
4074 FIXME("(%p/%p)->(%s, %p, %p)\n", This, iface, debugstr_guid(propid), flags, punk);
4078 static HRESULT WINAPI Context_OC_EnumContextProps(IObjContext *iface, IEnumContextProps **props)
4080 Context *This = impl_from_IObjContext(iface);
4082 FIXME("(%p/%p)->(%p)\n", This, iface, props);
4086 static void WINAPI Context_OC_Reserved1(IObjContext *iface)
4088 Context *This = impl_from_IObjContext(iface);
4089 FIXME("(%p/%p)\n", This, iface);
4092 static void WINAPI Context_OC_Reserved2(IObjContext *iface)
4094 Context *This = impl_from_IObjContext(iface);
4095 FIXME("(%p/%p)\n", This, iface);
4098 static void WINAPI Context_OC_Reserved3(IObjContext *iface)
4100 Context *This = impl_from_IObjContext(iface);
4101 FIXME("(%p/%p)\n", This, iface);
4104 static void WINAPI Context_OC_Reserved4(IObjContext *iface)
4106 Context *This = impl_from_IObjContext(iface);
4107 FIXME("(%p/%p)\n", This, iface);
4110 static void WINAPI Context_OC_Reserved5(IObjContext *iface)
4112 Context *This = impl_from_IObjContext(iface);
4113 FIXME("(%p/%p)\n", This, iface);
4116 static void WINAPI Context_OC_Reserved6(IObjContext *iface)
4118 Context *This = impl_from_IObjContext(iface);
4119 FIXME("(%p/%p)\n", This, iface);
4122 static void WINAPI Context_OC_Reserved7(IObjContext *iface)
4124 Context *This = impl_from_IObjContext(iface);
4125 FIXME("(%p/%p)\n", This, iface);
4128 static const IObjContextVtbl Context_Object_Vtbl =
4130 Context_OC_QueryInterface,
4133 Context_OC_SetProperty,
4134 Context_OC_RemoveProperty,
4135 Context_OC_GetProperty,
4136 Context_OC_EnumContextProps,
4137 Context_OC_Reserved1,
4138 Context_OC_Reserved2,
4139 Context_OC_Reserved3,
4140 Context_OC_Reserved4,
4141 Context_OC_Reserved5,
4142 Context_OC_Reserved6,
4143 Context_OC_Reserved7
4146 /***********************************************************************
4147 * CoGetObjectContext [OLE32.@]
4149 * Retrieves an object associated with the current context (i.e. apartment).
4152 * riid [I] ID of the interface of the object to retrieve.
4153 * ppv [O] Address where object will be stored on return.
4157 * Failure: HRESULT code.
4159 HRESULT WINAPI CoGetObjectContext(REFIID riid, void **ppv)
4161 APARTMENT *apt = COM_CurrentApt();
4165 TRACE("(%s, %p)\n", debugstr_guid(riid), ppv);
4170 if (!(apt = apartment_find_multi_threaded()))
4172 ERR("apartment not initialised\n");
4173 return CO_E_NOTINITIALIZED;
4175 apartment_release(apt);
4178 context = HeapAlloc(GetProcessHeap(), 0, sizeof(*context));
4180 return E_OUTOFMEMORY;
4182 context->IComThreadingInfo_iface.lpVtbl = &Context_Threading_Vtbl;
4183 context->IContextCallback_iface.lpVtbl = &Context_Callback_Vtbl;
4184 context->IObjContext_iface.lpVtbl = &Context_Object_Vtbl;
4186 if (apt->multi_threaded)
4187 context->apttype = APTTYPE_MTA;
4189 context->apttype = APTTYPE_MAINSTA;
4191 context->apttype = APTTYPE_STA;
4193 hr = IUnknown_QueryInterface((IUnknown *)&context->IComThreadingInfo_iface, riid, ppv);
4194 IUnknown_Release((IUnknown *)&context->IComThreadingInfo_iface);
4200 /***********************************************************************
4201 * CoGetContextToken [OLE32.@]
4203 HRESULT WINAPI CoGetContextToken( ULONG_PTR *token )
4205 struct oletls *info = COM_CurrentInfo();
4207 TRACE("(%p)\n", token);
4210 return E_OUTOFMEMORY;
4215 if (!(apt = apartment_find_multi_threaded()))
4217 ERR("apartment not initialised\n");
4218 return CO_E_NOTINITIALIZED;
4220 apartment_release(apt);
4226 if (!info->context_token)
4231 hr = CoGetObjectContext(&IID_IObjContext, (void **)&ctx);
4232 if (FAILED(hr)) return hr;
4233 info->context_token = ctx;
4236 *token = (ULONG_PTR)info->context_token;
4237 TRACE("apt->context_token=%p\n", info->context_token);
4242 HRESULT Handler_DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv)
4244 static const WCHAR wszInprocHandler32[] = {'I','n','p','r','o','c','H','a','n','d','l','e','r','3','2',0};
4248 hres = COM_OpenKeyForCLSID(rclsid, wszInprocHandler32, KEY_READ, &hkey);
4249 if (SUCCEEDED(hres))
4251 WCHAR dllpath[MAX_PATH+1];
4253 if (COM_RegReadPath(hkey, NULL, NULL, dllpath, ARRAYSIZE(dllpath)) == ERROR_SUCCESS)
4255 static const WCHAR wszOle32[] = {'o','l','e','3','2','.','d','l','l',0};
4256 if (!strcmpiW(dllpath, wszOle32))
4259 return HandlerCF_Create(rclsid, riid, ppv);
4263 WARN("not creating object for inproc handler path %s\n", debugstr_w(dllpath));
4267 return CLASS_E_CLASSNOTAVAILABLE;
4270 /***********************************************************************
4273 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID fImpLoad)
4275 TRACE("%p 0x%x %p\n", hinstDLL, fdwReason, fImpLoad);
4278 case DLL_PROCESS_ATTACH:
4279 hProxyDll = hinstDLL;
4280 COMPOBJ_InitProcess();
4283 case DLL_PROCESS_DETACH:
4284 COMPOBJ_UninitProcess();
4285 RPC_UnregisterAllChannelHooks();
4286 COMPOBJ_DllList_Free();
4287 DeleteCriticalSection(&csRegisteredClassList);
4288 DeleteCriticalSection(&csApartment);
4291 case DLL_THREAD_DETACH:
4298 /***********************************************************************
4299 * DllRegisterServer (OLE32.@)
4301 HRESULT WINAPI DllRegisterServer(void)
4303 return OLE32_DllRegisterServer();
4306 /***********************************************************************
4307 * DllUnregisterServer (OLE32.@)
4309 HRESULT WINAPI DllUnregisterServer(void)
4311 return OLE32_DllUnregisterServer();