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
37 * - Make all ole interface marshaling use NDR to be wire compatible with
50 #define NONAMELESSUNION
51 #define NONAMELESSSTRUCT
62 #include "compobj_private.h"
64 #include "wine/unicode.h"
65 #include "wine/debug.h"
67 WINE_DEFAULT_DEBUG_CHANNEL(ole);
69 HINSTANCE OLE32_hInstance = 0; /* FIXME: make static ... */
71 #define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))
73 /****************************************************************************
74 * This section defines variables internal to the COM module.
76 * TODO: Most of these things will have to be made thread-safe.
79 static HRESULT COM_GetRegisteredClassObject(const struct apartment *apt, REFCLSID rclsid,
80 DWORD dwClsContext, LPUNKNOWN* ppUnk);
81 static void COM_RevokeAllClasses(const struct apartment *apt);
82 static HRESULT get_inproc_class_object(APARTMENT *apt, HKEY hkeydll, REFCLSID rclsid, REFIID riid, void **ppv);
84 static APARTMENT *MTA; /* protected by csApartment */
85 static APARTMENT *MainApartment; /* the first STA apartment */
86 static struct list apts = LIST_INIT( apts ); /* protected by csApartment */
88 static CRITICAL_SECTION csApartment;
89 static CRITICAL_SECTION_DEBUG critsect_debug =
92 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
93 0, 0, { (DWORD_PTR)(__FILE__ ": csApartment") }
95 static CRITICAL_SECTION csApartment = { &critsect_debug, -1, 0, 0, 0, 0 };
97 struct registered_psclsid
105 * This lock count counts the number of times CoInitialize is called. It is
106 * decreased every time CoUninitialize is called. When it hits 0, the COM
107 * libraries are freed
109 static LONG s_COMLockCount = 0;
110 /* Reference count used by CoAddRefServerProcess/CoReleaseServerProcess */
111 static LONG s_COMServerProcessReferences = 0;
114 * This linked list contains the list of registered class objects. These
115 * are mostly used to register the factories for out-of-proc servers of OLE
118 * TODO: Make this data structure aware of inter-process communication. This
119 * means that parts of this will be exported to the Wine Server.
121 typedef struct tagRegisteredClass
124 CLSID classIdentifier;
126 LPUNKNOWN classObject;
130 LPSTREAM pMarshaledData; /* FIXME: only really need to store OXID and IPID */
131 void *RpcRegistration;
134 static struct list RegisteredClassList = LIST_INIT(RegisteredClassList);
136 static CRITICAL_SECTION csRegisteredClassList;
137 static CRITICAL_SECTION_DEBUG class_cs_debug =
139 0, 0, &csRegisteredClassList,
140 { &class_cs_debug.ProcessLocksList, &class_cs_debug.ProcessLocksList },
141 0, 0, { (DWORD_PTR)(__FILE__ ": csRegisteredClassList") }
143 static CRITICAL_SECTION csRegisteredClassList = { &class_cs_debug, -1, 0, 0, 0, 0 };
145 /*****************************************************************************
146 * This section contains OpenDllList definitions
148 * The OpenDllList contains only handles of dll loaded by CoGetClassObject or
149 * other functions that do LoadLibrary _without_ giving back a HMODULE.
150 * Without this list these handles would never be freed.
152 * FIXME: a DLL that says OK when asked for unloading is unloaded in the
153 * next unload-call but not before 600 sec.
156 typedef HRESULT (CALLBACK *DllGetClassObjectFunc)(REFCLSID clsid, REFIID iid, LPVOID *ppv);
157 typedef HRESULT (WINAPI *DllCanUnloadNowFunc)(void);
159 typedef struct tagOpenDll
164 DllGetClassObjectFunc DllGetClassObject;
165 DllCanUnloadNowFunc DllCanUnloadNow;
169 static struct list openDllList = LIST_INIT(openDllList);
171 static CRITICAL_SECTION csOpenDllList;
172 static CRITICAL_SECTION_DEBUG dll_cs_debug =
174 0, 0, &csOpenDllList,
175 { &dll_cs_debug.ProcessLocksList, &dll_cs_debug.ProcessLocksList },
176 0, 0, { (DWORD_PTR)(__FILE__ ": csOpenDllList") }
178 static CRITICAL_SECTION csOpenDllList = { &dll_cs_debug, -1, 0, 0, 0, 0 };
180 struct apartment_loaded_dll
188 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',' ',
189 '0','x','#','#','#','#','#','#','#','#',' ',0};
190 static LRESULT CALLBACK apartment_wndproc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
191 static HRESULT apartment_getclassobject(struct apartment *apt, LPCWSTR dllpath,
192 BOOL apartment_threaded,
193 REFCLSID rclsid, REFIID riid, void **ppv);
194 static void apartment_freeunusedlibraries(struct apartment *apt, DWORD delay);
196 static HRESULT COMPOBJ_DllList_Add(LPCWSTR library_name, OpenDll **ret);
197 static OpenDll *COMPOBJ_DllList_Get(LPCWSTR library_name);
198 static void COMPOBJ_DllList_ReleaseRef(OpenDll *entry, BOOL free_entry);
200 static DWORD COM_RegReadPath(HKEY hkeyroot, const WCHAR *keyname, const WCHAR *valuename, WCHAR * dst, DWORD dstlen);
202 static void COMPOBJ_InitProcess( void )
206 /* Dispatching to the correct thread in an apartment is done through
207 * window messages rather than RPC transports. When an interface is
208 * marshalled into another apartment in the same process, a window of the
209 * following class is created. The *caller* of CoMarshalInterface (ie the
210 * application) is responsible for pumping the message loop in that thread.
211 * The WM_USER messages which point to the RPCs are then dispatched to
212 * COM_AptWndProc by the user's code from the apartment in which the interface
215 memset(&wclass, 0, sizeof(wclass));
216 wclass.lpfnWndProc = apartment_wndproc;
217 wclass.hInstance = OLE32_hInstance;
218 wclass.lpszClassName = wszAptWinClass;
219 RegisterClassW(&wclass);
222 static void COMPOBJ_UninitProcess( void )
224 UnregisterClassW(wszAptWinClass, OLE32_hInstance);
227 static void COM_TlsDestroy(void)
229 struct oletls *info = NtCurrentTeb()->ReservedForOle;
232 if (info->apt) apartment_release(info->apt);
233 if (info->errorinfo) IErrorInfo_Release(info->errorinfo);
234 if (info->state) IUnknown_Release(info->state);
235 HeapFree(GetProcessHeap(), 0, info);
236 NtCurrentTeb()->ReservedForOle = NULL;
240 /******************************************************************************
244 /* allocates memory and fills in the necessary fields for a new apartment
245 * object. must be called inside apartment cs */
246 static APARTMENT *apartment_construct(DWORD model)
250 TRACE("creating new apartment, model=%d\n", model);
252 apt = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*apt));
253 apt->tid = GetCurrentThreadId();
255 list_init(&apt->proxies);
256 list_init(&apt->stubmgrs);
257 list_init(&apt->psclsids);
258 list_init(&apt->loaded_dlls);
261 apt->remunk_exported = FALSE;
263 InitializeCriticalSection(&apt->cs);
264 DEBUG_SET_CRITSEC_NAME(&apt->cs, "apartment");
266 apt->multi_threaded = !(model & COINIT_APARTMENTTHREADED);
268 if (apt->multi_threaded)
270 /* FIXME: should be randomly generated by in an RPC call to rpcss */
271 apt->oxid = ((OXID)GetCurrentProcessId() << 32) | 0xcafe;
275 /* FIXME: should be randomly generated by in an RPC call to rpcss */
276 apt->oxid = ((OXID)GetCurrentProcessId() << 32) | GetCurrentThreadId();
279 TRACE("Created apartment on OXID %s\n", wine_dbgstr_longlong(apt->oxid));
281 list_add_head(&apts, &apt->entry);
286 /* gets and existing apartment if one exists or otherwise creates an apartment
287 * structure which stores OLE apartment-local information and stores a pointer
288 * to it in the thread-local storage */
289 static APARTMENT *apartment_get_or_create(DWORD model)
291 APARTMENT *apt = COM_CurrentApt();
295 if (model & COINIT_APARTMENTTHREADED)
297 EnterCriticalSection(&csApartment);
299 apt = apartment_construct(model);
304 TRACE("Created main-threaded apartment with OXID %s\n", wine_dbgstr_longlong(apt->oxid));
307 LeaveCriticalSection(&csApartment);
311 EnterCriticalSection(&csApartment);
313 /* The multi-threaded apartment (MTA) contains zero or more threads interacting
314 * with free threaded (ie thread safe) COM objects. There is only ever one MTA
318 TRACE("entering the multithreaded apartment %s\n", wine_dbgstr_longlong(MTA->oxid));
319 apartment_addref(MTA);
322 MTA = apartment_construct(model);
326 LeaveCriticalSection(&csApartment);
328 COM_CurrentInfo()->apt = apt;
334 static inline BOOL apartment_is_model(const APARTMENT *apt, DWORD model)
336 return (apt->multi_threaded == !(model & COINIT_APARTMENTTHREADED));
339 DWORD apartment_addref(struct apartment *apt)
341 DWORD refs = InterlockedIncrement(&apt->refs);
342 TRACE("%s: before = %d\n", wine_dbgstr_longlong(apt->oxid), refs - 1);
346 DWORD apartment_release(struct apartment *apt)
350 EnterCriticalSection(&csApartment);
352 ret = InterlockedDecrement(&apt->refs);
353 TRACE("%s: after = %d\n", wine_dbgstr_longlong(apt->oxid), ret);
354 /* destruction stuff that needs to happen under csApartment CS */
357 if (apt == MTA) MTA = NULL;
358 else if (apt == MainApartment) MainApartment = NULL;
359 list_remove(&apt->entry);
362 LeaveCriticalSection(&csApartment);
366 struct list *cursor, *cursor2;
368 TRACE("destroying apartment %p, oxid %s\n", apt, wine_dbgstr_longlong(apt->oxid));
370 /* Release the references to the registered class objects */
371 COM_RevokeAllClasses(apt);
373 /* no locking is needed for this apartment, because no other thread
374 * can access it at this point */
376 apartment_disconnectproxies(apt);
378 if (apt->win) DestroyWindow(apt->win);
379 if (apt->host_apt_tid) PostThreadMessageW(apt->host_apt_tid, WM_QUIT, 0, 0);
381 LIST_FOR_EACH_SAFE(cursor, cursor2, &apt->stubmgrs)
383 struct stub_manager *stubmgr = LIST_ENTRY(cursor, struct stub_manager, entry);
384 /* release the implicit reference given by the fact that the
385 * stub has external references (it must do since it is in the
386 * stub manager list in the apartment and all non-apartment users
387 * must have a ref on the apartment and so it cannot be destroyed).
389 stub_manager_int_release(stubmgr);
392 LIST_FOR_EACH_SAFE(cursor, cursor2, &apt->psclsids)
394 struct registered_psclsid *registered_psclsid =
395 LIST_ENTRY(cursor, struct registered_psclsid, entry);
397 list_remove(®istered_psclsid->entry);
398 HeapFree(GetProcessHeap(), 0, registered_psclsid);
401 /* if this assert fires, then another thread took a reference to a
402 * stub manager without taking a reference to the containing
403 * apartment, which it must do. */
404 assert(list_empty(&apt->stubmgrs));
406 if (apt->filter) IUnknown_Release(apt->filter);
408 /* free as many unused libraries as possible... */
409 apartment_freeunusedlibraries(apt, 0);
411 /* ... and free the memory for the apartment loaded dll entry and
412 * release the dll list reference without freeing the library for the
414 while ((cursor = list_head(&apt->loaded_dlls)))
416 struct apartment_loaded_dll *apartment_loaded_dll = LIST_ENTRY(cursor, struct apartment_loaded_dll, entry);
417 COMPOBJ_DllList_ReleaseRef(apartment_loaded_dll->dll, FALSE);
419 HeapFree(GetProcessHeap(), 0, apartment_loaded_dll);
422 DEBUG_CLEAR_CRITSEC_NAME(&apt->cs);
423 DeleteCriticalSection(&apt->cs);
425 HeapFree(GetProcessHeap(), 0, apt);
431 /* The given OXID must be local to this process:
433 * The ref parameter is here mostly to ensure people remember that
434 * they get one, you should normally take a ref for thread safety.
436 APARTMENT *apartment_findfromoxid(OXID oxid, BOOL ref)
438 APARTMENT *result = NULL;
441 EnterCriticalSection(&csApartment);
442 LIST_FOR_EACH( cursor, &apts )
444 struct apartment *apt = LIST_ENTRY( cursor, struct apartment, entry );
445 if (apt->oxid == oxid)
448 if (ref) apartment_addref(result);
452 LeaveCriticalSection(&csApartment);
457 /* gets the apartment which has a given creator thread ID. The caller must
458 * release the reference from the apartment as soon as the apartment pointer
459 * is no longer required. */
460 APARTMENT *apartment_findfromtid(DWORD tid)
462 APARTMENT *result = NULL;
465 EnterCriticalSection(&csApartment);
466 LIST_FOR_EACH( cursor, &apts )
468 struct apartment *apt = LIST_ENTRY( cursor, struct apartment, entry );
472 apartment_addref(result);
476 LeaveCriticalSection(&csApartment);
481 /* gets the main apartment if it exists. The caller must
482 * release the reference from the apartment as soon as the apartment pointer
483 * is no longer required. */
484 static APARTMENT *apartment_findmain(void)
488 EnterCriticalSection(&csApartment);
490 result = MainApartment;
491 if (result) apartment_addref(result);
493 LeaveCriticalSection(&csApartment);
498 struct host_object_params
501 CLSID clsid; /* clsid of object to marshal */
502 IID iid; /* interface to marshal */
503 HANDLE event; /* event signalling when ready for multi-threaded case */
504 HRESULT hr; /* result for multi-threaded case */
505 IStream *stream; /* stream that the object will be marshaled into */
506 BOOL apartment_threaded; /* is the component purely apartment-threaded? */
509 static HRESULT apartment_hostobject(struct apartment *apt,
510 const struct host_object_params *params)
514 static const LARGE_INTEGER llZero;
515 WCHAR dllpath[MAX_PATH+1];
517 TRACE("clsid %s, iid %s\n", debugstr_guid(¶ms->clsid), debugstr_guid(¶ms->iid));
519 if (COM_RegReadPath(params->hkeydll, NULL, NULL, dllpath, ARRAYSIZE(dllpath)) != ERROR_SUCCESS)
521 /* failure: CLSID is not found in registry */
522 WARN("class %s not registered inproc\n", debugstr_guid(¶ms->clsid));
523 return REGDB_E_CLASSNOTREG;
526 hr = apartment_getclassobject(apt, dllpath, params->apartment_threaded,
527 ¶ms->clsid, ¶ms->iid, (void **)&object);
531 hr = CoMarshalInterface(params->stream, ¶ms->iid, object, MSHCTX_INPROC, NULL, MSHLFLAGS_NORMAL);
533 IUnknown_Release(object);
534 IStream_Seek(params->stream, llZero, STREAM_SEEK_SET, NULL);
539 static LRESULT CALLBACK apartment_wndproc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
544 RPC_ExecuteCall((struct dispatch_params *)lParam);
547 return apartment_hostobject(COM_CurrentApt(), (const struct host_object_params *)lParam);
549 return DefWindowProcW(hWnd, msg, wParam, lParam);
553 struct host_thread_params
555 COINIT threading_model;
560 static DWORD CALLBACK apartment_hostobject_thread(LPVOID p)
562 struct host_thread_params *params = p;
565 struct apartment *apt;
569 hr = CoInitializeEx(NULL, params->threading_model);
570 if (FAILED(hr)) return hr;
572 apt = COM_CurrentApt();
573 if (params->threading_model == COINIT_APARTMENTTHREADED)
575 apartment_createwindowifneeded(apt);
576 params->apartment_hwnd = apartment_getwindow(apt);
579 params->apartment_hwnd = NULL;
581 /* force the message queue to be created before signaling parent thread */
582 PeekMessageW(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
584 SetEvent(params->ready_event);
585 params = NULL; /* can't touch params after here as it may be invalid */
587 while (GetMessageW(&msg, NULL, 0, 0))
589 if (!msg.hwnd && (msg.message == DM_HOSTOBJECT))
591 struct host_object_params *params = (struct host_object_params *)msg.lParam;
592 params->hr = apartment_hostobject(apt, params);
593 SetEvent(params->event);
597 TranslateMessage(&msg);
598 DispatchMessageW(&msg);
609 static HRESULT apartment_hostobject_in_hostapt(struct apartment *apt, BOOL multi_threaded, BOOL main_apartment, HKEY hkeydll, REFCLSID rclsid, REFIID riid, void **ppv)
611 struct host_object_params params;
612 HWND apartment_hwnd = NULL;
613 DWORD apartment_tid = 0;
616 if (!multi_threaded && main_apartment)
618 APARTMENT *host_apt = apartment_findmain();
621 apartment_hwnd = apartment_getwindow(host_apt);
622 apartment_release(host_apt);
628 EnterCriticalSection(&apt->cs);
630 if (!apt->host_apt_tid)
632 struct host_thread_params thread_params;
636 thread_params.threading_model = multi_threaded ? COINIT_MULTITHREADED : COINIT_APARTMENTTHREADED;
637 handles[0] = thread_params.ready_event = CreateEventW(NULL, FALSE, FALSE, NULL);
638 thread_params.apartment_hwnd = NULL;
639 handles[1] = CreateThread(NULL, 0, apartment_hostobject_thread, &thread_params, 0, &apt->host_apt_tid);
642 CloseHandle(handles[0]);
643 LeaveCriticalSection(&apt->cs);
644 return E_OUTOFMEMORY;
646 wait_value = WaitForMultipleObjects(2, handles, FALSE, INFINITE);
647 CloseHandle(handles[0]);
648 CloseHandle(handles[1]);
649 if (wait_value == WAIT_OBJECT_0)
650 apt->host_apt_hwnd = thread_params.apartment_hwnd;
653 LeaveCriticalSection(&apt->cs);
654 return E_OUTOFMEMORY;
658 if (multi_threaded || !main_apartment)
660 apartment_hwnd = apt->host_apt_hwnd;
661 apartment_tid = apt->host_apt_tid;
664 LeaveCriticalSection(&apt->cs);
667 /* another thread may have become the main apartment in the time it took
668 * us to create the thread for the host apartment */
669 if (!apartment_hwnd && !multi_threaded && main_apartment)
671 APARTMENT *host_apt = apartment_findmain();
674 apartment_hwnd = apartment_getwindow(host_apt);
675 apartment_release(host_apt);
679 params.hkeydll = hkeydll;
680 params.clsid = *rclsid;
682 hr = CreateStreamOnHGlobal(NULL, TRUE, ¶ms.stream);
685 params.apartment_threaded = !multi_threaded;
689 params.event = CreateEventW(NULL, FALSE, FALSE, NULL);
690 if (!PostThreadMessageW(apartment_tid, DM_HOSTOBJECT, 0, (LPARAM)¶ms))
694 WaitForSingleObject(params.event, INFINITE);
697 CloseHandle(params.event);
703 ERR("host apartment didn't create window\n");
707 hr = SendMessageW(apartment_hwnd, DM_HOSTOBJECT, 0, (LPARAM)¶ms);
710 hr = CoUnmarshalInterface(params.stream, riid, ppv);
711 IStream_Release(params.stream);
715 HRESULT apartment_createwindowifneeded(struct apartment *apt)
717 if (apt->multi_threaded)
722 HWND hwnd = CreateWindowW(wszAptWinClass, NULL, 0,
724 0, 0, OLE32_hInstance, NULL);
727 ERR("CreateWindow failed with error %d\n", GetLastError());
728 return HRESULT_FROM_WIN32(GetLastError());
730 if (InterlockedCompareExchangePointer((PVOID *)&apt->win, hwnd, NULL))
731 /* someone beat us to it */
738 HWND apartment_getwindow(const struct apartment *apt)
740 assert(!apt->multi_threaded);
744 void apartment_joinmta(void)
746 apartment_addref(MTA);
747 COM_CurrentInfo()->apt = MTA;
750 static HRESULT apartment_getclassobject(struct apartment *apt, LPCWSTR dllpath,
751 BOOL apartment_threaded,
752 REFCLSID rclsid, REFIID riid, void **ppv)
754 static const WCHAR wszOle32[] = {'o','l','e','3','2','.','d','l','l',0};
757 struct apartment_loaded_dll *apartment_loaded_dll;
759 if (!strcmpiW(dllpath, wszOle32))
761 /* we don't need to control the lifetime of this dll, so use the local
762 * implementation of DllGetClassObject directly */
763 TRACE("calling ole32!DllGetClassObject\n");
764 hr = DllGetClassObject(rclsid, riid, ppv);
767 ERR("DllGetClassObject returned error 0x%08x\n", hr);
772 EnterCriticalSection(&apt->cs);
774 LIST_FOR_EACH_ENTRY(apartment_loaded_dll, &apt->loaded_dlls, struct apartment_loaded_dll, entry)
775 if (!strcmpiW(dllpath, apartment_loaded_dll->dll->library_name))
777 TRACE("found %s already loaded\n", debugstr_w(dllpath));
784 apartment_loaded_dll = HeapAlloc(GetProcessHeap(), 0, sizeof(*apartment_loaded_dll));
785 if (!apartment_loaded_dll)
789 apartment_loaded_dll->unload_time = 0;
790 apartment_loaded_dll->multi_threaded = FALSE;
791 hr = COMPOBJ_DllList_Add( dllpath, &apartment_loaded_dll->dll );
793 HeapFree(GetProcessHeap(), 0, apartment_loaded_dll);
797 TRACE("added new loaded dll %s\n", debugstr_w(dllpath));
798 list_add_tail(&apt->loaded_dlls, &apartment_loaded_dll->entry);
802 LeaveCriticalSection(&apt->cs);
806 /* one component being multi-threaded overrides any number of
807 * apartment-threaded components */
808 if (!apartment_threaded)
809 apartment_loaded_dll->multi_threaded = TRUE;
811 TRACE("calling DllGetClassObject %p\n", apartment_loaded_dll->dll->DllGetClassObject);
812 /* OK: get the ClassObject */
813 hr = apartment_loaded_dll->dll->DllGetClassObject(rclsid, riid, ppv);
816 ERR("DllGetClassObject returned error 0x%08x\n", hr);
822 static void apartment_freeunusedlibraries(struct apartment *apt, DWORD delay)
824 struct apartment_loaded_dll *entry, *next;
825 EnterCriticalSection(&apt->cs);
826 LIST_FOR_EACH_ENTRY_SAFE(entry, next, &apt->loaded_dlls, struct apartment_loaded_dll, entry)
828 if (entry->dll->DllCanUnloadNow && (entry->dll->DllCanUnloadNow() == S_OK))
830 DWORD real_delay = delay;
832 if (real_delay == INFINITE)
834 if (entry->multi_threaded)
835 real_delay = 10 * 60 * 1000; /* 10 minutes */
840 if (!real_delay || (entry->unload_time && (entry->unload_time < GetTickCount())))
842 list_remove(&entry->entry);
843 COMPOBJ_DllList_ReleaseRef(entry->dll, TRUE);
844 HeapFree(GetProcessHeap(), 0, entry);
847 entry->unload_time = GetTickCount() + real_delay;
849 else if (entry->unload_time)
850 entry->unload_time = 0;
852 LeaveCriticalSection(&apt->cs);
855 /*****************************************************************************
856 * This section contains OpenDllList implementation
859 /* caller must ensure that library_name is not already in the open dll list */
860 static HRESULT COMPOBJ_DllList_Add(LPCWSTR library_name, OpenDll **ret)
866 DllCanUnloadNowFunc DllCanUnloadNow;
867 DllGetClassObjectFunc DllGetClassObject;
871 *ret = COMPOBJ_DllList_Get(library_name);
872 if (*ret) return S_OK;
874 /* do this outside the csOpenDllList to avoid creating a lock dependency on
876 hLibrary = LoadLibraryExW(library_name, 0, LOAD_WITH_ALTERED_SEARCH_PATH);
879 ERR("couldn't load in-process dll %s\n", debugstr_w(library_name));
880 /* failure: DLL could not be loaded */
881 return E_ACCESSDENIED; /* FIXME: or should this be CO_E_DLLNOTFOUND? */
884 DllCanUnloadNow = (void *)GetProcAddress(hLibrary, "DllCanUnloadNow");
885 /* Note: failing to find DllCanUnloadNow is not a failure */
886 DllGetClassObject = (void *)GetProcAddress(hLibrary, "DllGetClassObject");
887 if (!DllGetClassObject)
889 /* failure: the dll did not export DllGetClassObject */
890 ERR("couldn't find function DllGetClassObject in %s\n", debugstr_w(library_name));
891 FreeLibrary(hLibrary);
892 return CO_E_DLLNOTFOUND;
895 EnterCriticalSection( &csOpenDllList );
897 *ret = COMPOBJ_DllList_Get(library_name);
900 /* another caller to this function already added the dll while we
901 * weren't in the critical section */
902 FreeLibrary(hLibrary);
906 len = strlenW(library_name);
907 entry = HeapAlloc(GetProcessHeap(),0, sizeof(OpenDll));
909 entry->library_name = HeapAlloc(GetProcessHeap(), 0, (len + 1)*sizeof(WCHAR));
910 if (entry && entry->library_name)
912 memcpy(entry->library_name, library_name, (len + 1)*sizeof(WCHAR));
913 entry->library = hLibrary;
915 entry->DllCanUnloadNow = DllCanUnloadNow;
916 entry->DllGetClassObject = DllGetClassObject;
917 list_add_tail(&openDllList, &entry->entry);
922 FreeLibrary(hLibrary);
927 LeaveCriticalSection( &csOpenDllList );
932 static OpenDll *COMPOBJ_DllList_Get(LPCWSTR library_name)
936 EnterCriticalSection(&csOpenDllList);
937 LIST_FOR_EACH_ENTRY(ptr, &openDllList, OpenDll, entry)
939 if (!strcmpiW(library_name, ptr->library_name) &&
940 (InterlockedIncrement(&ptr->refs) != 1) /* entry is being destroy if == 1 */)
946 LeaveCriticalSection(&csOpenDllList);
950 /* pass FALSE for free_entry to release a reference without destroying the
951 * entry if it reaches zero or TRUE otherwise */
952 static void COMPOBJ_DllList_ReleaseRef(OpenDll *entry, BOOL free_entry)
954 if (!InterlockedDecrement(&entry->refs) && free_entry)
956 EnterCriticalSection(&csOpenDllList);
957 list_remove(&entry->entry);
958 LeaveCriticalSection(&csOpenDllList);
960 TRACE("freeing %p\n", entry->library);
961 FreeLibrary(entry->library);
963 HeapFree(GetProcessHeap(), 0, entry->library_name);
964 HeapFree(GetProcessHeap(), 0, entry);
968 /******************************************************************************
969 * CoBuildVersion [OLE32.@]
970 * CoBuildVersion [COMPOBJ.1]
972 * Gets the build version of the DLL.
977 * Current build version, hiword is majornumber, loword is minornumber
979 DWORD WINAPI CoBuildVersion(void)
981 TRACE("Returning version %d, build %d.\n", rmm, rup);
982 return (rmm<<16)+rup;
985 /******************************************************************************
986 * CoInitialize [OLE32.@]
988 * Initializes the COM libraries by calling CoInitializeEx with
989 * COINIT_APARTMENTTHREADED, ie it enters a STA thread.
992 * lpReserved [I] Pointer to IMalloc interface (obsolete, should be NULL).
995 * Success: S_OK if not already initialized, S_FALSE otherwise.
996 * Failure: HRESULT code.
1001 HRESULT WINAPI CoInitialize(LPVOID lpReserved)
1004 * Just delegate to the newer method.
1006 return CoInitializeEx(lpReserved, COINIT_APARTMENTTHREADED);
1009 /******************************************************************************
1010 * CoInitializeEx [OLE32.@]
1012 * Initializes the COM libraries.
1015 * lpReserved [I] Pointer to IMalloc interface (obsolete, should be NULL).
1016 * dwCoInit [I] One or more flags from the COINIT enumeration. See notes.
1019 * S_OK if successful,
1020 * S_FALSE if this function was called already.
1021 * RPC_E_CHANGED_MODE if a previous call to CoInitializeEx specified another
1026 * The behavior used to set the IMalloc used for memory management is
1028 * The dwCoInit parameter must specify one of the following apartment
1030 *| COINIT_APARTMENTTHREADED - A single-threaded apartment (STA).
1031 *| COINIT_MULTITHREADED - A multi-threaded apartment (MTA).
1032 * The parameter may also specify zero or more of the following flags:
1033 *| COINIT_DISABLE_OLE1DDE - Don't use DDE for OLE1 support.
1034 *| COINIT_SPEED_OVER_MEMORY - Trade memory for speed.
1039 HRESULT WINAPI CoInitializeEx(LPVOID lpReserved, DWORD dwCoInit)
1044 TRACE("(%p, %x)\n", lpReserved, (int)dwCoInit);
1046 if (lpReserved!=NULL)
1048 ERR("(%p, %x) - Bad parameter passed-in %p, must be an old Windows Application\n", lpReserved, (int)dwCoInit, lpReserved);
1052 * Check the lock count. If this is the first time going through the initialize
1053 * process, we have to initialize the libraries.
1055 * And crank-up that lock count.
1057 if (InterlockedExchangeAdd(&s_COMLockCount,1)==0)
1060 * Initialize the various COM libraries and data structures.
1062 TRACE("() - Initializing the COM libraries\n");
1064 /* we may need to defer this until after apartment initialisation */
1065 RunningObjectTableImpl_Initialize();
1068 if (!(apt = COM_CurrentInfo()->apt))
1070 apt = apartment_get_or_create(dwCoInit);
1071 if (!apt) return E_OUTOFMEMORY;
1073 else if (!apartment_is_model(apt, dwCoInit))
1075 /* Changing the threading model after it's been set is illegal. If this warning is triggered by Wine
1076 code then we are probably using the wrong threading model to implement that API. */
1077 ERR("Attempt to change threading model of this apartment from %s to %s\n",
1078 apt->multi_threaded ? "multi-threaded" : "apartment threaded",
1079 dwCoInit & COINIT_APARTMENTTHREADED ? "apartment threaded" : "multi-threaded");
1080 return RPC_E_CHANGED_MODE;
1085 COM_CurrentInfo()->inits++;
1090 /***********************************************************************
1091 * CoUninitialize [OLE32.@]
1093 * This method will decrement the refcount on the current apartment, freeing
1094 * the resources associated with it if it is the last thread in the apartment.
1095 * If the last apartment is freed, the function will additionally release
1096 * any COM resources associated with the process.
1106 void WINAPI CoUninitialize(void)
1108 struct oletls * info = COM_CurrentInfo();
1113 /* will only happen on OOM */
1119 ERR("Mismatched CoUninitialize\n");
1125 apartment_release(info->apt);
1130 * Decrease the reference count.
1131 * If we are back to 0 locks on the COM library, make sure we free
1132 * all the associated data structures.
1134 lCOMRefCnt = InterlockedExchangeAdd(&s_COMLockCount,-1);
1137 TRACE("() - Releasing the COM libraries\n");
1139 RunningObjectTableImpl_UnInitialize();
1141 else if (lCOMRefCnt<1) {
1142 ERR( "CoUninitialize() - not CoInitialized.\n" );
1143 InterlockedExchangeAdd(&s_COMLockCount,1); /* restore the lock count. */
1147 /******************************************************************************
1148 * CoDisconnectObject [OLE32.@]
1150 * Disconnects all connections to this object from remote processes. Dispatches
1151 * pending RPCs while blocking new RPCs from occurring, and then calls
1152 * IMarshal::DisconnectObject on the given object.
1154 * Typically called when the object server is forced to shut down, for instance by
1158 * lpUnk [I] The object whose stub should be disconnected.
1159 * reserved [I] Reserved. Should be set to 0.
1163 * Failure: HRESULT code.
1166 * CoMarshalInterface, CoReleaseMarshalData, CoLockObjectExternal
1168 HRESULT WINAPI CoDisconnectObject( LPUNKNOWN lpUnk, DWORD reserved )
1174 TRACE("(%p, 0x%08x)\n", lpUnk, reserved);
1176 hr = IUnknown_QueryInterface(lpUnk, &IID_IMarshal, (void **)&marshal);
1179 hr = IMarshal_DisconnectObject(marshal, reserved);
1180 IMarshal_Release(marshal);
1184 apt = COM_CurrentApt();
1186 return CO_E_NOTINITIALIZED;
1188 apartment_disconnectobject(apt, lpUnk);
1190 /* Note: native is pretty broken here because it just silently
1191 * fails, without returning an appropriate error code if the object was
1192 * not found, making apps think that the object was disconnected, when
1193 * it actually wasn't */
1198 /******************************************************************************
1199 * CoCreateGuid [OLE32.@]
1200 * CoCreateGuid [COMPOBJ.73]
1202 * Simply forwards to UuidCreate in RPCRT4.
1205 * pguid [O] Points to the GUID to initialize.
1209 * Failure: HRESULT code.
1214 HRESULT WINAPI CoCreateGuid(GUID *pguid)
1216 return UuidCreate(pguid);
1219 /******************************************************************************
1220 * CLSIDFromString [OLE32.@]
1221 * IIDFromString [OLE32.@]
1223 * Converts a unique identifier from its string representation into
1227 * idstr [I] The string representation of the GUID.
1228 * id [O] GUID converted from the string.
1232 * CO_E_CLASSSTRING if idstr is not a valid CLSID
1237 static HRESULT WINAPI __CLSIDFromString(LPCWSTR s, CLSID *id)
1243 memset( id, 0, sizeof (CLSID) );
1247 /* validate the CLSID string */
1248 if (strlenW(s) != 38)
1249 return CO_E_CLASSSTRING;
1251 if ((s[0]!='{') || (s[9]!='-') || (s[14]!='-') || (s[19]!='-') || (s[24]!='-') || (s[37]!='}'))
1252 return CO_E_CLASSSTRING;
1254 for (i=1; i<37; i++) {
1255 if ((i == 9)||(i == 14)||(i == 19)||(i == 24)) continue;
1256 if (!(((s[i] >= '0') && (s[i] <= '9')) ||
1257 ((s[i] >= 'a') && (s[i] <= 'f')) ||
1258 ((s[i] >= 'A') && (s[i] <= 'F'))))
1259 return CO_E_CLASSSTRING;
1262 TRACE("%s -> %p\n", debugstr_w(s), id);
1264 /* quick lookup table */
1265 memset(table, 0, 256);
1267 for (i = 0; i < 10; i++) {
1270 for (i = 0; i < 6; i++) {
1271 table['A' + i] = i+10;
1272 table['a' + i] = i+10;
1275 /* in form {XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX} */
1277 id->Data1 = (table[s[1]] << 28 | table[s[2]] << 24 | table[s[3]] << 20 | table[s[4]] << 16 |
1278 table[s[5]] << 12 | table[s[6]] << 8 | table[s[7]] << 4 | table[s[8]]);
1279 id->Data2 = table[s[10]] << 12 | table[s[11]] << 8 | table[s[12]] << 4 | table[s[13]];
1280 id->Data3 = table[s[15]] << 12 | table[s[16]] << 8 | table[s[17]] << 4 | table[s[18]];
1282 /* these are just sequential bytes */
1283 id->Data4[0] = table[s[20]] << 4 | table[s[21]];
1284 id->Data4[1] = table[s[22]] << 4 | table[s[23]];
1285 id->Data4[2] = table[s[25]] << 4 | table[s[26]];
1286 id->Data4[3] = table[s[27]] << 4 | table[s[28]];
1287 id->Data4[4] = table[s[29]] << 4 | table[s[30]];
1288 id->Data4[5] = table[s[31]] << 4 | table[s[32]];
1289 id->Data4[6] = table[s[33]] << 4 | table[s[34]];
1290 id->Data4[7] = table[s[35]] << 4 | table[s[36]];
1295 /*****************************************************************************/
1297 HRESULT WINAPI CLSIDFromString(LPOLESTR idstr, CLSID *id )
1302 return E_INVALIDARG;
1304 ret = __CLSIDFromString(idstr, id);
1305 if(ret != S_OK) { /* It appears a ProgID is also valid */
1306 ret = CLSIDFromProgID(idstr, id);
1311 /* Converts a GUID into the respective string representation. */
1312 HRESULT WINE_StringFromCLSID(
1313 const CLSID *id, /* [in] GUID to be converted */
1314 LPSTR idstr /* [out] pointer to buffer to contain converted guid */
1316 static const char hex[] = "0123456789ABCDEF";
1321 { ERR("called with id=Null\n");
1326 sprintf(idstr, "{%08X-%04X-%04X-%02X%02X-",
1327 id->Data1, id->Data2, id->Data3,
1328 id->Data4[0], id->Data4[1]);
1332 for (i = 2; i < 8; i++) {
1333 *s++ = hex[id->Data4[i]>>4];
1334 *s++ = hex[id->Data4[i] & 0xf];
1340 TRACE("%p->%s\n", id, idstr);
1346 /******************************************************************************
1347 * StringFromCLSID [OLE32.@]
1348 * StringFromIID [OLE32.@]
1350 * Converts a GUID into the respective string representation.
1351 * The target string is allocated using the OLE IMalloc.
1354 * id [I] the GUID to be converted.
1355 * idstr [O] A pointer to a to-be-allocated pointer pointing to the resulting string.
1362 * StringFromGUID2, CLSIDFromString
1364 HRESULT WINAPI StringFromCLSID(REFCLSID id, LPOLESTR *idstr)
1370 if ((ret = CoGetMalloc(0,&mllc)))
1373 ret=WINE_StringFromCLSID(id,buf);
1375 DWORD len = MultiByteToWideChar( CP_ACP, 0, buf, -1, NULL, 0 );
1376 *idstr = IMalloc_Alloc( mllc, len * sizeof(WCHAR) );
1377 MultiByteToWideChar( CP_ACP, 0, buf, -1, *idstr, len );
1382 /******************************************************************************
1383 * StringFromGUID2 [OLE32.@]
1384 * StringFromGUID2 [COMPOBJ.76]
1386 * Modified version of StringFromCLSID that allows you to specify max
1390 * id [I] GUID to convert to string.
1391 * str [O] Buffer where the result will be stored.
1392 * cmax [I] Size of the buffer in characters.
1395 * Success: The length of the resulting string in characters.
1398 INT WINAPI StringFromGUID2(REFGUID id, LPOLESTR str, INT cmax)
1402 if (WINE_StringFromCLSID(id,xguid))
1404 return MultiByteToWideChar( CP_ACP, 0, xguid, -1, str, cmax );
1407 /* open HKCR\\CLSID\\{string form of clsid}\\{keyname} key */
1408 HRESULT COM_OpenKeyForCLSID(REFCLSID clsid, LPCWSTR keyname, REGSAM access, HKEY *subkey)
1410 static const WCHAR wszCLSIDSlash[] = {'C','L','S','I','D','\\',0};
1411 WCHAR path[CHARS_IN_GUID + ARRAYSIZE(wszCLSIDSlash) - 1];
1415 strcpyW(path, wszCLSIDSlash);
1416 StringFromGUID2(clsid, path + strlenW(wszCLSIDSlash), CHARS_IN_GUID);
1417 res = RegOpenKeyExW(HKEY_CLASSES_ROOT, path, 0, keyname ? KEY_READ : access, &key);
1418 if (res == ERROR_FILE_NOT_FOUND)
1419 return REGDB_E_CLASSNOTREG;
1420 else if (res != ERROR_SUCCESS)
1421 return REGDB_E_READREGDB;
1429 res = RegOpenKeyExW(key, keyname, 0, access, subkey);
1431 if (res == ERROR_FILE_NOT_FOUND)
1432 return REGDB_E_KEYMISSING;
1433 else if (res != ERROR_SUCCESS)
1434 return REGDB_E_READREGDB;
1439 /* open HKCR\\AppId\\{string form of appid clsid} key */
1440 HRESULT COM_OpenKeyForAppIdFromCLSID(REFCLSID clsid, REGSAM access, HKEY *subkey)
1442 static const WCHAR szAppId[] = { 'A','p','p','I','d',0 };
1443 static const WCHAR szAppIdKey[] = { 'A','p','p','I','d','\\',0 };
1445 WCHAR buf[CHARS_IN_GUID];
1446 WCHAR keyname[ARRAYSIZE(szAppIdKey) + CHARS_IN_GUID];
1452 /* read the AppID value under the class's key */
1453 hr = COM_OpenKeyForCLSID(clsid, NULL, KEY_READ, &hkey);
1458 res = RegQueryValueExW(hkey, szAppId, NULL, &type, (LPBYTE)buf, &size);
1460 if (res == ERROR_FILE_NOT_FOUND)
1461 return REGDB_E_KEYMISSING;
1462 else if (res != ERROR_SUCCESS || type!=REG_SZ)
1463 return REGDB_E_READREGDB;
1465 strcpyW(keyname, szAppIdKey);
1466 strcatW(keyname, buf);
1467 res = RegOpenKeyExW(HKEY_CLASSES_ROOT, keyname, 0, access, subkey);
1468 if (res == ERROR_FILE_NOT_FOUND)
1469 return REGDB_E_KEYMISSING;
1470 else if (res != ERROR_SUCCESS)
1471 return REGDB_E_READREGDB;
1476 /******************************************************************************
1477 * ProgIDFromCLSID [OLE32.@]
1479 * Converts a class id into the respective program ID.
1482 * clsid [I] Class ID, as found in registry.
1483 * ppszProgID [O] Associated ProgID.
1488 * REGDB_E_CLASSNOTREG if the given clsid has no associated ProgID
1490 HRESULT WINAPI ProgIDFromCLSID(REFCLSID clsid, LPOLESTR *ppszProgID)
1492 static const WCHAR wszProgID[] = {'P','r','o','g','I','D',0};
1499 ERR("ppszProgId isn't optional\n");
1500 return E_INVALIDARG;
1504 ret = COM_OpenKeyForCLSID(clsid, wszProgID, KEY_READ, &hkey);
1508 if (RegQueryValueW(hkey, NULL, NULL, &progidlen))
1509 ret = REGDB_E_CLASSNOTREG;
1513 *ppszProgID = CoTaskMemAlloc(progidlen * sizeof(WCHAR));
1516 if (RegQueryValueW(hkey, NULL, *ppszProgID, &progidlen))
1517 ret = REGDB_E_CLASSNOTREG;
1520 ret = E_OUTOFMEMORY;
1527 /******************************************************************************
1528 * CLSIDFromProgID [OLE32.@]
1530 * Converts a program id into the respective GUID.
1533 * progid [I] Unicode program ID, as found in registry.
1534 * clsid [O] Associated CLSID.
1538 * Failure: CO_E_CLASSSTRING - the given ProgID cannot be found.
1540 HRESULT WINAPI CLSIDFromProgID(LPCOLESTR progid, LPCLSID clsid)
1542 static const WCHAR clsidW[] = { '\\','C','L','S','I','D',0 };
1543 WCHAR buf2[CHARS_IN_GUID];
1544 LONG buf2len = sizeof(buf2);
1548 if (!progid || !clsid)
1550 ERR("neither progid (%p) nor clsid (%p) are optional\n", progid, clsid);
1551 return E_INVALIDARG;
1554 /* initialise clsid in case of failure */
1555 memset(clsid, 0, sizeof(*clsid));
1557 buf = HeapAlloc( GetProcessHeap(),0,(strlenW(progid)+8) * sizeof(WCHAR) );
1558 strcpyW( buf, progid );
1559 strcatW( buf, clsidW );
1560 if (RegOpenKeyW(HKEY_CLASSES_ROOT,buf,&xhkey))
1562 HeapFree(GetProcessHeap(),0,buf);
1563 WARN("couldn't open key for ProgID %s\n", debugstr_w(progid));
1564 return CO_E_CLASSSTRING;
1566 HeapFree(GetProcessHeap(),0,buf);
1568 if (RegQueryValueW(xhkey,NULL,buf2,&buf2len))
1571 WARN("couldn't query clsid value for ProgID %s\n", debugstr_w(progid));
1572 return CO_E_CLASSSTRING;
1575 return CLSIDFromString(buf2,clsid);
1579 /*****************************************************************************
1580 * CoGetPSClsid [OLE32.@]
1582 * Retrieves the CLSID of the proxy/stub factory that implements
1583 * IPSFactoryBuffer for the specified interface.
1586 * riid [I] Interface whose proxy/stub CLSID is to be returned.
1587 * pclsid [O] Where to store returned proxy/stub CLSID.
1592 * REGDB_E_IIDNOTREG if no PSFactoryBuffer is associated with the IID, or it could not be parsed
1596 * The standard marshaller activates the object with the CLSID
1597 * returned and uses the CreateProxy and CreateStub methods on its
1598 * IPSFactoryBuffer interface to construct the proxies and stubs for a
1601 * CoGetPSClsid determines this CLSID by searching the
1602 * HKEY_CLASSES_ROOT\Interface\{string form of riid}\ProxyStubClsid32
1603 * in the registry and any interface id registered by
1604 * CoRegisterPSClsid within the current process.
1608 * Native returns S_OK for interfaces with a key in HKCR\Interface, but
1609 * without a ProxyStubClsid32 key and leaves garbage in pclsid. This should be
1610 * considered a bug in native unless an application depends on this (unlikely).
1613 * CoRegisterPSClsid.
1615 HRESULT WINAPI CoGetPSClsid(REFIID riid, CLSID *pclsid)
1617 static const WCHAR wszInterface[] = {'I','n','t','e','r','f','a','c','e','\\',0};
1618 static const WCHAR wszPSC[] = {'\\','P','r','o','x','y','S','t','u','b','C','l','s','i','d','3','2',0};
1619 WCHAR path[ARRAYSIZE(wszInterface) - 1 + CHARS_IN_GUID - 1 + ARRAYSIZE(wszPSC)];
1620 WCHAR value[CHARS_IN_GUID];
1623 APARTMENT *apt = COM_CurrentApt();
1624 struct registered_psclsid *registered_psclsid;
1626 TRACE("() riid=%s, pclsid=%p\n", debugstr_guid(riid), pclsid);
1630 ERR("apartment not initialised\n");
1631 return CO_E_NOTINITIALIZED;
1636 ERR("pclsid isn't optional\n");
1637 return E_INVALIDARG;
1640 EnterCriticalSection(&apt->cs);
1642 LIST_FOR_EACH_ENTRY(registered_psclsid, &apt->psclsids, struct registered_psclsid, entry)
1643 if (IsEqualIID(®istered_psclsid->iid, riid))
1645 *pclsid = registered_psclsid->clsid;
1646 LeaveCriticalSection(&apt->cs);
1650 LeaveCriticalSection(&apt->cs);
1652 /* Interface\\{string form of riid}\\ProxyStubClsid32 */
1653 strcpyW(path, wszInterface);
1654 StringFromGUID2(riid, path + ARRAYSIZE(wszInterface) - 1, CHARS_IN_GUID);
1655 strcpyW(path + ARRAYSIZE(wszInterface) - 1 + CHARS_IN_GUID - 1, wszPSC);
1657 /* Open the key.. */
1658 if (RegOpenKeyExW(HKEY_CLASSES_ROOT, path, 0, KEY_READ, &hkey))
1660 WARN("No PSFactoryBuffer object is registered for IID %s\n", debugstr_guid(riid));
1661 return REGDB_E_IIDNOTREG;
1664 /* ... Once we have the key, query the registry to get the
1665 value of CLSID as a string, and convert it into a
1666 proper CLSID structure to be passed back to the app */
1667 len = sizeof(value);
1668 if (ERROR_SUCCESS != RegQueryValueW(hkey, NULL, value, &len))
1671 return REGDB_E_IIDNOTREG;
1675 /* We have the CLSid we want back from the registry as a string, so
1676 lets convert it into a CLSID structure */
1677 if (CLSIDFromString(value, pclsid) != NOERROR)
1678 return REGDB_E_IIDNOTREG;
1680 TRACE ("() Returning CLSID=%s\n", debugstr_guid(pclsid));
1684 /*****************************************************************************
1685 * CoRegisterPSClsid [OLE32.@]
1687 * Register a proxy/stub CLSID for the given interface in the current process
1691 * riid [I] Interface whose proxy/stub CLSID is to be registered.
1692 * rclsid [I] CLSID of the proxy/stub.
1696 * Failure: E_OUTOFMEMORY
1700 * This function does not add anything to the registry and the effects are
1701 * limited to the lifetime of the current process.
1706 HRESULT WINAPI CoRegisterPSClsid(REFIID riid, REFCLSID rclsid)
1708 APARTMENT *apt = COM_CurrentApt();
1709 struct registered_psclsid *registered_psclsid;
1711 TRACE("(%s, %s)\n", debugstr_guid(riid), debugstr_guid(rclsid));
1715 ERR("apartment not initialised\n");
1716 return CO_E_NOTINITIALIZED;
1719 EnterCriticalSection(&apt->cs);
1721 LIST_FOR_EACH_ENTRY(registered_psclsid, &apt->psclsids, struct registered_psclsid, entry)
1722 if (IsEqualIID(®istered_psclsid->iid, riid))
1724 registered_psclsid->clsid = *rclsid;
1725 LeaveCriticalSection(&apt->cs);
1729 registered_psclsid = HeapAlloc(GetProcessHeap(), 0, sizeof(struct registered_psclsid));
1730 if (!registered_psclsid)
1732 LeaveCriticalSection(&apt->cs);
1733 return E_OUTOFMEMORY;
1736 registered_psclsid->iid = *riid;
1737 registered_psclsid->clsid = *rclsid;
1738 list_add_head(&apt->psclsids, ®istered_psclsid->entry);
1740 LeaveCriticalSection(&apt->cs);
1747 * COM_GetRegisteredClassObject
1749 * This internal method is used to scan the registered class list to
1750 * find a class object.
1753 * rclsid Class ID of the class to find.
1754 * dwClsContext Class context to match.
1755 * ppv [out] returns a pointer to the class object. Complying
1756 * to normal COM usage, this method will increase the
1757 * reference count on this object.
1759 static HRESULT COM_GetRegisteredClassObject(const struct apartment *apt, REFCLSID rclsid,
1760 DWORD dwClsContext, LPUNKNOWN* ppUnk)
1762 HRESULT hr = S_FALSE;
1763 RegisteredClass *curClass;
1770 EnterCriticalSection( &csRegisteredClassList );
1772 LIST_FOR_EACH_ENTRY(curClass, &RegisteredClassList, RegisteredClass, entry)
1775 * Check if we have a match on the class ID and context.
1777 if ((apt->oxid == curClass->apartment_id) &&
1778 (dwClsContext & curClass->runContext) &&
1779 IsEqualGUID(&(curClass->classIdentifier), rclsid))
1782 * We have a match, return the pointer to the class object.
1784 *ppUnk = curClass->classObject;
1786 IUnknown_AddRef(curClass->classObject);
1793 LeaveCriticalSection( &csRegisteredClassList );
1798 /******************************************************************************
1799 * CoRegisterClassObject [OLE32.@]
1801 * Registers the class object for a given class ID. Servers housed in EXE
1802 * files use this method instead of exporting DllGetClassObject to allow
1803 * other code to connect to their objects.
1806 * rclsid [I] CLSID of the object to register.
1807 * pUnk [I] IUnknown of the object.
1808 * dwClsContext [I] CLSCTX flags indicating the context in which to run the executable.
1809 * flags [I] REGCLS flags indicating how connections are made.
1810 * lpdwRegister [I] A unique cookie that can be passed to CoRevokeClassObject.
1814 * E_INVALIDARG if lpdwRegister or pUnk are NULL,
1815 * CO_E_OBJISREG if the object is already registered. We should not return this.
1818 * CoRevokeClassObject, CoGetClassObject
1821 * In-process objects are only registered for the current apartment.
1822 * CoGetClassObject() and CoCreateInstance() will not return objects registered
1823 * in other apartments.
1826 * MSDN claims that multiple interface registrations are legal, but we
1827 * can't do that with our current implementation.
1829 HRESULT WINAPI CoRegisterClassObject(
1834 LPDWORD lpdwRegister)
1836 RegisteredClass* newClass;
1837 LPUNKNOWN foundObject;
1841 TRACE("(%s,%p,0x%08x,0x%08x,%p)\n",
1842 debugstr_guid(rclsid),pUnk,dwClsContext,flags,lpdwRegister);
1844 if ( (lpdwRegister==0) || (pUnk==0) )
1845 return E_INVALIDARG;
1847 apt = COM_CurrentApt();
1850 ERR("COM was not initialized\n");
1851 return CO_E_NOTINITIALIZED;
1856 /* REGCLS_MULTIPLEUSE implies registering as inproc server. This is what
1857 * differentiates the flag from REGCLS_MULTI_SEPARATE. */
1858 if (flags & REGCLS_MULTIPLEUSE)
1859 dwClsContext |= CLSCTX_INPROC_SERVER;
1862 * First, check if the class is already registered.
1863 * If it is, this should cause an error.
1865 hr = COM_GetRegisteredClassObject(apt, rclsid, dwClsContext, &foundObject);
1867 if (flags & REGCLS_MULTIPLEUSE) {
1868 if (dwClsContext & CLSCTX_LOCAL_SERVER)
1869 hr = CoLockObjectExternal(foundObject, TRUE, FALSE);
1870 IUnknown_Release(foundObject);
1873 IUnknown_Release(foundObject);
1874 ERR("object already registered for class %s\n", debugstr_guid(rclsid));
1875 return CO_E_OBJISREG;
1878 newClass = HeapAlloc(GetProcessHeap(), 0, sizeof(RegisteredClass));
1879 if ( newClass == NULL )
1880 return E_OUTOFMEMORY;
1882 newClass->classIdentifier = *rclsid;
1883 newClass->apartment_id = apt->oxid;
1884 newClass->runContext = dwClsContext;
1885 newClass->connectFlags = flags;
1886 newClass->pMarshaledData = NULL;
1887 newClass->RpcRegistration = NULL;
1890 * Use the address of the chain node as the cookie since we are sure it's
1891 * unique. FIXME: not on 64-bit platforms.
1893 newClass->dwCookie = (DWORD)newClass;
1896 * Since we're making a copy of the object pointer, we have to increase its
1899 newClass->classObject = pUnk;
1900 IUnknown_AddRef(newClass->classObject);
1902 EnterCriticalSection( &csRegisteredClassList );
1903 list_add_tail(&RegisteredClassList, &newClass->entry);
1904 LeaveCriticalSection( &csRegisteredClassList );
1906 *lpdwRegister = newClass->dwCookie;
1908 if (dwClsContext & CLSCTX_LOCAL_SERVER) {
1909 hr = CreateStreamOnHGlobal(0, TRUE, &newClass->pMarshaledData);
1911 FIXME("Failed to create stream on hglobal, %x\n", hr);
1914 hr = CoMarshalInterface(newClass->pMarshaledData, &IID_IClassFactory,
1915 newClass->classObject, MSHCTX_LOCAL, NULL,
1916 MSHLFLAGS_TABLESTRONG);
1918 FIXME("CoMarshalInterface failed, %x!\n",hr);
1922 hr = RPC_StartLocalServer(&newClass->classIdentifier,
1923 newClass->pMarshaledData,
1924 flags & (REGCLS_MULTIPLEUSE|REGCLS_MULTI_SEPARATE),
1925 &newClass->RpcRegistration);
1930 static void COM_RevokeRegisteredClassObject(RegisteredClass *curClass)
1932 list_remove(&curClass->entry);
1934 if (curClass->runContext & CLSCTX_LOCAL_SERVER)
1935 RPC_StopLocalServer(curClass->RpcRegistration);
1938 * Release the reference to the class object.
1940 IUnknown_Release(curClass->classObject);
1942 if (curClass->pMarshaledData)
1945 memset(&zero, 0, sizeof(zero));
1946 IStream_Seek(curClass->pMarshaledData, zero, STREAM_SEEK_SET, NULL);
1947 CoReleaseMarshalData(curClass->pMarshaledData);
1950 HeapFree(GetProcessHeap(), 0, curClass);
1953 static void COM_RevokeAllClasses(const struct apartment *apt)
1955 RegisteredClass *curClass, *cursor;
1957 EnterCriticalSection( &csRegisteredClassList );
1959 LIST_FOR_EACH_ENTRY_SAFE(curClass, cursor, &RegisteredClassList, RegisteredClass, entry)
1961 if (curClass->apartment_id == apt->oxid)
1962 COM_RevokeRegisteredClassObject(curClass);
1965 LeaveCriticalSection( &csRegisteredClassList );
1968 /***********************************************************************
1969 * CoRevokeClassObject [OLE32.@]
1971 * Removes a class object from the class registry.
1974 * dwRegister [I] Cookie returned from CoRegisterClassObject().
1978 * Failure: HRESULT code.
1981 * Must be called from the same apartment that called CoRegisterClassObject(),
1982 * otherwise it will fail with RPC_E_WRONG_THREAD.
1985 * CoRegisterClassObject
1987 HRESULT WINAPI CoRevokeClassObject(
1990 HRESULT hr = E_INVALIDARG;
1991 RegisteredClass *curClass;
1994 TRACE("(%08x)\n",dwRegister);
1996 apt = COM_CurrentApt();
1999 ERR("COM was not initialized\n");
2000 return CO_E_NOTINITIALIZED;
2003 EnterCriticalSection( &csRegisteredClassList );
2005 LIST_FOR_EACH_ENTRY(curClass, &RegisteredClassList, RegisteredClass, entry)
2008 * Check if we have a match on the cookie.
2010 if (curClass->dwCookie == dwRegister)
2012 if (curClass->apartment_id == apt->oxid)
2014 COM_RevokeRegisteredClassObject(curClass);
2019 ERR("called from wrong apartment, should be called from %s\n",
2020 wine_dbgstr_longlong(curClass->apartment_id));
2021 hr = RPC_E_WRONG_THREAD;
2027 LeaveCriticalSection( &csRegisteredClassList );
2032 /***********************************************************************
2033 * COM_RegReadPath [internal]
2035 * Reads a registry value and expands it when necessary
2037 static DWORD COM_RegReadPath(HKEY hkeyroot, const WCHAR *keyname, const WCHAR *valuename, WCHAR * dst, DWORD dstlen)
2042 WCHAR src[MAX_PATH];
2043 DWORD dwLength = dstlen * sizeof(WCHAR);
2045 if((ret = RegOpenKeyExW(hkeyroot, keyname, 0, KEY_READ, &key)) == ERROR_SUCCESS) {
2046 if( (ret = RegQueryValueExW(key, NULL, NULL, &keytype, (LPBYTE)src, &dwLength)) == ERROR_SUCCESS ) {
2047 if (keytype == REG_EXPAND_SZ) {
2048 if (dstlen <= ExpandEnvironmentStringsW(src, dst, dstlen)) ret = ERROR_MORE_DATA;
2050 lstrcpynW(dst, src, dstlen);
2058 static void get_threading_model(HKEY key, LPWSTR value, DWORD len)
2060 static const WCHAR wszThreadingModel[] = {'T','h','r','e','a','d','i','n','g','M','o','d','e','l',0};
2063 DWORD dwLength = len * sizeof(WCHAR);
2065 ret = RegQueryValueExW(key, wszThreadingModel, NULL, &keytype, (LPBYTE)value, &dwLength);
2066 if ((ret != ERROR_SUCCESS) || (keytype != REG_SZ))
2070 static HRESULT get_inproc_class_object(APARTMENT *apt, HKEY hkeydll,
2071 REFCLSID rclsid, REFIID riid, void **ppv)
2073 static const WCHAR wszApartment[] = {'A','p','a','r','t','m','e','n','t',0};
2074 static const WCHAR wszFree[] = {'F','r','e','e',0};
2075 static const WCHAR wszBoth[] = {'B','o','t','h',0};
2076 WCHAR dllpath[MAX_PATH+1];
2077 WCHAR threading_model[10 /* strlenW(L"apartment")+1 */];
2079 get_threading_model(hkeydll, threading_model, ARRAYSIZE(threading_model));
2081 if (!strcmpiW(threading_model, wszApartment))
2083 if (apt->multi_threaded)
2084 return apartment_hostobject_in_hostapt(apt, FALSE, FALSE, hkeydll, rclsid, riid, ppv);
2087 else if (!strcmpiW(threading_model, wszFree))
2089 if (!apt->multi_threaded)
2090 return apartment_hostobject_in_hostapt(apt, TRUE, FALSE, hkeydll, rclsid, riid, ppv);
2092 /* everything except "Apartment", "Free" and "Both" */
2093 else if (strcmpiW(threading_model, wszBoth))
2095 /* everything else is main-threaded */
2096 if (threading_model[0])
2097 FIXME("unrecognised threading model %s for object %s, should be main-threaded?\n",
2098 debugstr_w(threading_model), debugstr_guid(rclsid));
2100 if (apt->multi_threaded || !apt->main)
2101 return apartment_hostobject_in_hostapt(apt, FALSE, TRUE, hkeydll, rclsid, riid, ppv);
2104 if (COM_RegReadPath(hkeydll, NULL, NULL, dllpath, ARRAYSIZE(dllpath)) != ERROR_SUCCESS)
2106 /* failure: CLSID is not found in registry */
2107 WARN("class %s not registered inproc\n", debugstr_guid(rclsid));
2108 return REGDB_E_CLASSNOTREG;
2111 return apartment_getclassobject(apt, dllpath,
2112 !strcmpiW(threading_model, wszApartment),
2116 /***********************************************************************
2117 * CoGetClassObject [OLE32.@]
2119 * Creates an object of the specified class.
2122 * rclsid [I] Class ID to create an instance of.
2123 * dwClsContext [I] Flags to restrict the location of the created instance.
2124 * pServerInfo [I] Optional. Details for connecting to a remote server.
2125 * iid [I] The ID of the interface of the instance to return.
2126 * ppv [O] On returns, contains a pointer to the specified interface of the object.
2130 * Failure: HRESULT code.
2133 * The dwClsContext parameter can be one or more of the following:
2134 *| CLSCTX_INPROC_SERVER - Use an in-process server, such as from a DLL.
2135 *| CLSCTX_INPROC_HANDLER - Use an in-process object which handles certain functions for an object running in another process.
2136 *| CLSCTX_LOCAL_SERVER - Connect to an object running in another process.
2137 *| CLSCTX_REMOTE_SERVER - Connect to an object running on another machine.
2140 * CoCreateInstance()
2142 HRESULT WINAPI CoGetClassObject(
2143 REFCLSID rclsid, DWORD dwClsContext, COSERVERINFO *pServerInfo,
2144 REFIID iid, LPVOID *ppv)
2146 LPUNKNOWN regClassObject;
2147 HRESULT hres = E_UNEXPECTED;
2150 TRACE("\n\tCLSID:\t%s,\n\tIID:\t%s\n", debugstr_guid(rclsid), debugstr_guid(iid));
2153 return E_INVALIDARG;
2157 apt = COM_CurrentApt();
2160 ERR("apartment not initialised\n");
2161 return CO_E_NOTINITIALIZED;
2165 FIXME("\tpServerInfo: name=%s\n",debugstr_w(pServerInfo->pwszName));
2166 FIXME("\t\tpAuthInfo=%p\n",pServerInfo->pAuthInfo);
2170 * First, try and see if we can't match the class ID with one of the
2171 * registered classes.
2173 if (S_OK == COM_GetRegisteredClassObject(apt, rclsid, dwClsContext,
2176 /* Get the required interface from the retrieved pointer. */
2177 hres = IUnknown_QueryInterface(regClassObject, iid, ppv);
2180 * Since QI got another reference on the pointer, we want to release the
2181 * one we already have. If QI was unsuccessful, this will release the object. This
2182 * is good since we are not returning it in the "out" parameter.
2184 IUnknown_Release(regClassObject);
2189 /* First try in-process server */
2190 if (CLSCTX_INPROC_SERVER & dwClsContext)
2192 static const WCHAR wszInprocServer32[] = {'I','n','p','r','o','c','S','e','r','v','e','r','3','2',0};
2195 if (IsEqualCLSID(rclsid, &CLSID_InProcFreeMarshaler))
2196 return FTMarshalCF_Create(iid, ppv);
2198 hres = COM_OpenKeyForCLSID(rclsid, wszInprocServer32, KEY_READ, &hkey);
2201 if (hres == REGDB_E_CLASSNOTREG)
2202 ERR("class %s not registered\n", debugstr_guid(rclsid));
2203 else if (hres == REGDB_E_KEYMISSING)
2205 WARN("class %s not registered as in-proc server\n", debugstr_guid(rclsid));
2206 hres = REGDB_E_CLASSNOTREG;
2210 if (SUCCEEDED(hres))
2212 hres = get_inproc_class_object(apt, hkey, rclsid, iid, ppv);
2216 /* return if we got a class, otherwise fall through to one of the
2218 if (SUCCEEDED(hres))
2222 /* Next try in-process handler */
2223 if (CLSCTX_INPROC_HANDLER & dwClsContext)
2225 static const WCHAR wszInprocHandler32[] = {'I','n','p','r','o','c','H','a','n','d','l','e','r','3','2',0};
2228 hres = COM_OpenKeyForCLSID(rclsid, wszInprocHandler32, KEY_READ, &hkey);
2231 if (hres == REGDB_E_CLASSNOTREG)
2232 ERR("class %s not registered\n", debugstr_guid(rclsid));
2233 else if (hres == REGDB_E_KEYMISSING)
2235 WARN("class %s not registered in-proc handler\n", debugstr_guid(rclsid));
2236 hres = REGDB_E_CLASSNOTREG;
2240 if (SUCCEEDED(hres))
2242 hres = get_inproc_class_object(apt, hkey, rclsid, iid, ppv);
2246 /* return if we got a class, otherwise fall through to one of the
2248 if (SUCCEEDED(hres))
2252 /* Next try out of process */
2253 if (CLSCTX_LOCAL_SERVER & dwClsContext)
2255 hres = RPC_GetLocalClassObject(rclsid,iid,ppv);
2256 if (SUCCEEDED(hres))
2260 /* Finally try remote: this requires networked DCOM (a lot of work) */
2261 if (CLSCTX_REMOTE_SERVER & dwClsContext)
2263 FIXME ("CLSCTX_REMOTE_SERVER not supported\n");
2264 hres = E_NOINTERFACE;
2268 ERR("no class object %s could be created for context 0x%x\n",
2269 debugstr_guid(rclsid), dwClsContext);
2273 /***********************************************************************
2274 * CoResumeClassObjects (OLE32.@)
2276 * Resumes all class objects registered with REGCLS_SUSPENDED.
2280 * Failure: HRESULT code.
2282 HRESULT WINAPI CoResumeClassObjects(void)
2288 /***********************************************************************
2289 * CoCreateInstance [OLE32.@]
2291 * Creates an instance of the specified class.
2294 * rclsid [I] Class ID to create an instance of.
2295 * pUnkOuter [I] Optional outer unknown to allow aggregation with another object.
2296 * dwClsContext [I] Flags to restrict the location of the created instance.
2297 * iid [I] The ID of the interface of the instance to return.
2298 * ppv [O] On returns, contains a pointer to the specified interface of the instance.
2302 * Failure: HRESULT code.
2305 * The dwClsContext parameter can be one or more of the following:
2306 *| CLSCTX_INPROC_SERVER - Use an in-process server, such as from a DLL.
2307 *| CLSCTX_INPROC_HANDLER - Use an in-process object which handles certain functions for an object running in another process.
2308 *| CLSCTX_LOCAL_SERVER - Connect to an object running in another process.
2309 *| CLSCTX_REMOTE_SERVER - Connect to an object running on another machine.
2311 * Aggregation is the concept of deferring the IUnknown of an object to another
2312 * object. This allows a separate object to behave as though it was part of
2313 * the object and to allow this the pUnkOuter parameter can be set. Note that
2314 * not all objects support having an outer of unknown.
2317 * CoGetClassObject()
2319 HRESULT WINAPI CoCreateInstance(
2321 LPUNKNOWN pUnkOuter,
2327 LPCLASSFACTORY lpclf = 0;
2329 TRACE("(rclsid=%s, pUnkOuter=%p, dwClsContext=%08x, riid=%s, ppv=%p)\n", debugstr_guid(rclsid),
2330 pUnkOuter, dwClsContext, debugstr_guid(iid), ppv);
2339 * Initialize the "out" parameter
2343 if (!COM_CurrentApt())
2345 ERR("apartment not initialised\n");
2346 return CO_E_NOTINITIALIZED;
2350 * The Standard Global Interface Table (GIT) object is a process-wide singleton.
2351 * Rather than create a class factory, we can just check for it here
2353 if (IsEqualIID(rclsid, &CLSID_StdGlobalInterfaceTable)) {
2354 if (StdGlobalInterfaceTableInstance == NULL)
2355 StdGlobalInterfaceTableInstance = StdGlobalInterfaceTable_Construct();
2356 hres = IGlobalInterfaceTable_QueryInterface( (IGlobalInterfaceTable*) StdGlobalInterfaceTableInstance, iid, ppv);
2357 if (hres) return hres;
2359 TRACE("Retrieved GIT (%p)\n", *ppv);
2364 * Get a class factory to construct the object we want.
2366 hres = CoGetClassObject(rclsid,
2376 * Create the object and don't forget to release the factory
2378 hres = IClassFactory_CreateInstance(lpclf, pUnkOuter, iid, ppv);
2379 IClassFactory_Release(lpclf);
2381 FIXME("no instance created for interface %s of class %s, hres is 0x%08x\n",
2382 debugstr_guid(iid), debugstr_guid(rclsid),hres);
2387 /***********************************************************************
2388 * CoCreateInstanceEx [OLE32.@]
2390 HRESULT WINAPI CoCreateInstanceEx(
2392 LPUNKNOWN pUnkOuter,
2394 COSERVERINFO* pServerInfo,
2398 IUnknown* pUnk = NULL;
2401 ULONG successCount = 0;
2406 if ( (cmq==0) || (pResults==NULL))
2407 return E_INVALIDARG;
2409 if (pServerInfo!=NULL)
2410 FIXME("() non-NULL pServerInfo not supported!\n");
2413 * Initialize all the "out" parameters.
2415 for (index = 0; index < cmq; index++)
2417 pResults[index].pItf = NULL;
2418 pResults[index].hr = E_NOINTERFACE;
2422 * Get the object and get its IUnknown pointer.
2424 hr = CoCreateInstance(rclsid,
2434 * Then, query for all the interfaces requested.
2436 for (index = 0; index < cmq; index++)
2438 pResults[index].hr = IUnknown_QueryInterface(pUnk,
2439 pResults[index].pIID,
2440 (VOID**)&(pResults[index].pItf));
2442 if (pResults[index].hr == S_OK)
2447 * Release our temporary unknown pointer.
2449 IUnknown_Release(pUnk);
2451 if (successCount == 0)
2452 return E_NOINTERFACE;
2454 if (successCount!=cmq)
2455 return CO_S_NOTALLINTERFACES;
2460 /***********************************************************************
2461 * CoLoadLibrary (OLE32.@)
2466 * lpszLibName [I] Path to library.
2467 * bAutoFree [I] Whether the library should automatically be freed.
2470 * Success: Handle to loaded library.
2474 * CoFreeLibrary, CoFreeAllLibraries, CoFreeUnusedLibraries
2476 HINSTANCE WINAPI CoLoadLibrary(LPOLESTR lpszLibName, BOOL bAutoFree)
2478 TRACE("(%s, %d)\n", debugstr_w(lpszLibName), bAutoFree);
2480 return LoadLibraryExW(lpszLibName, 0, LOAD_WITH_ALTERED_SEARCH_PATH);
2483 /***********************************************************************
2484 * CoFreeLibrary [OLE32.@]
2486 * Unloads a library from memory.
2489 * hLibrary [I] Handle to library to unload.
2495 * CoLoadLibrary, CoFreeAllLibraries, CoFreeUnusedLibraries
2497 void WINAPI CoFreeLibrary(HINSTANCE hLibrary)
2499 FreeLibrary(hLibrary);
2503 /***********************************************************************
2504 * CoFreeAllLibraries [OLE32.@]
2506 * Function for backwards compatibility only. Does nothing.
2512 * CoLoadLibrary, CoFreeLibrary, CoFreeUnusedLibraries
2514 void WINAPI CoFreeAllLibraries(void)
2519 /***********************************************************************
2520 * CoFreeUnusedLibrariesEx [OLE32.@]
2522 * Frees any previously unused libraries whose delay has expired and marks
2523 * currently unused libraries for unloading. Unused are identified as those that
2524 * return S_OK from their DllCanUnloadNow function.
2527 * dwUnloadDelay [I] Unload delay in milliseconds.
2528 * dwReserved [I] Reserved. Set to 0.
2534 * CoLoadLibrary, CoFreeAllLibraries, CoFreeLibrary
2536 void WINAPI CoFreeUnusedLibrariesEx(DWORD dwUnloadDelay, DWORD dwReserved)
2538 struct apartment *apt = COM_CurrentApt();
2541 ERR("apartment not initialised\n");
2545 apartment_freeunusedlibraries(apt, dwUnloadDelay);
2548 /***********************************************************************
2549 * CoFreeUnusedLibraries [OLE32.@]
2550 * CoFreeUnusedLibraries [COMPOBJ.17]
2552 * Frees any unused libraries. Unused are identified as those that return
2553 * S_OK from their DllCanUnloadNow function.
2559 * CoLoadLibrary, CoFreeAllLibraries, CoFreeLibrary
2561 void WINAPI CoFreeUnusedLibraries(void)
2563 CoFreeUnusedLibrariesEx(INFINITE, 0);
2566 /***********************************************************************
2567 * CoFileTimeNow [OLE32.@]
2568 * CoFileTimeNow [COMPOBJ.82]
2570 * Retrieves the current time in FILETIME format.
2573 * lpFileTime [O] The current time.
2578 HRESULT WINAPI CoFileTimeNow( FILETIME *lpFileTime )
2580 GetSystemTimeAsFileTime( lpFileTime );
2584 /******************************************************************************
2585 * CoLockObjectExternal [OLE32.@]
2587 * Increments or decrements the external reference count of a stub object.
2590 * pUnk [I] Stub object.
2591 * fLock [I] If TRUE then increments the external ref-count,
2592 * otherwise decrements.
2593 * fLastUnlockReleases [I] If TRUE then the last unlock has the effect of
2594 * calling CoDisconnectObject.
2598 * Failure: HRESULT code.
2601 * If fLock is TRUE and an object is passed in that doesn't have a stub
2602 * manager then a new stub manager is created for the object.
2604 HRESULT WINAPI CoLockObjectExternal(
2607 BOOL fLastUnlockReleases)
2609 struct stub_manager *stubmgr;
2610 struct apartment *apt;
2612 TRACE("pUnk=%p, fLock=%s, fLastUnlockReleases=%s\n",
2613 pUnk, fLock ? "TRUE" : "FALSE", fLastUnlockReleases ? "TRUE" : "FALSE");
2615 apt = COM_CurrentApt();
2616 if (!apt) return CO_E_NOTINITIALIZED;
2618 stubmgr = get_stub_manager_from_object(apt, pUnk);
2623 stub_manager_ext_addref(stubmgr, 1);
2625 stub_manager_ext_release(stubmgr, 1, fLastUnlockReleases);
2627 stub_manager_int_release(stubmgr);
2633 stubmgr = new_stub_manager(apt, pUnk);
2637 stub_manager_ext_addref(stubmgr, 1);
2638 stub_manager_int_release(stubmgr);
2645 WARN("stub object not found %p\n", pUnk);
2646 /* Note: native is pretty broken here because it just silently
2647 * fails, without returning an appropriate error code, making apps
2648 * think that the object was disconnected, when it actually wasn't */
2653 /***********************************************************************
2654 * CoInitializeWOW (OLE32.@)
2656 * WOW equivalent of CoInitialize?
2665 HRESULT WINAPI CoInitializeWOW(DWORD x,DWORD y)
2667 FIXME("(0x%08x,0x%08x),stub!\n",x,y);
2671 /***********************************************************************
2672 * CoGetState [OLE32.@]
2674 * Retrieves the thread state object previously stored by CoSetState().
2677 * ppv [I] Address where pointer to object will be stored.
2681 * Failure: E_OUTOFMEMORY.
2684 * Crashes on all invalid ppv addresses, including NULL.
2685 * If the function returns a non-NULL object then the caller must release its
2686 * reference on the object when the object is no longer required.
2691 HRESULT WINAPI CoGetState(IUnknown ** ppv)
2693 struct oletls *info = COM_CurrentInfo();
2694 if (!info) return E_OUTOFMEMORY;
2700 IUnknown_AddRef(info->state);
2702 TRACE("apt->state=%p\n", info->state);
2708 /***********************************************************************
2709 * CoSetState [OLE32.@]
2711 * Sets the thread state object.
2714 * pv [I] Pointer to state object to be stored.
2717 * The system keeps a reference on the object while the object stored.
2721 * Failure: E_OUTOFMEMORY.
2723 HRESULT WINAPI CoSetState(IUnknown * pv)
2725 struct oletls *info = COM_CurrentInfo();
2726 if (!info) return E_OUTOFMEMORY;
2728 if (pv) IUnknown_AddRef(pv);
2732 TRACE("-- release %p now\n", info->state);
2733 IUnknown_Release(info->state);
2742 /******************************************************************************
2743 * CoTreatAsClass [OLE32.@]
2745 * Sets the TreatAs value of a class.
2748 * clsidOld [I] Class to set TreatAs value on.
2749 * clsidNew [I] The class the clsidOld should be treated as.
2753 * Failure: HRESULT code.
2758 HRESULT WINAPI CoTreatAsClass(REFCLSID clsidOld, REFCLSID clsidNew)
2760 static const WCHAR wszAutoTreatAs[] = {'A','u','t','o','T','r','e','a','t','A','s',0};
2761 static const WCHAR wszTreatAs[] = {'T','r','e','a','t','A','s',0};
2763 WCHAR szClsidNew[CHARS_IN_GUID];
2765 WCHAR auto_treat_as[CHARS_IN_GUID];
2766 LONG auto_treat_as_size = sizeof(auto_treat_as);
2769 res = COM_OpenKeyForCLSID(clsidOld, NULL, KEY_READ | KEY_WRITE, &hkey);
2772 if (!memcmp( clsidOld, clsidNew, sizeof(*clsidOld) ))
2774 if (!RegQueryValueW(hkey, wszAutoTreatAs, auto_treat_as, &auto_treat_as_size) &&
2775 !CLSIDFromString(auto_treat_as, &id))
2777 if (RegSetValueW(hkey, wszTreatAs, REG_SZ, auto_treat_as, sizeof(auto_treat_as)))
2779 res = REGDB_E_WRITEREGDB;
2785 RegDeleteKeyW(hkey, wszTreatAs);
2789 else if (!StringFromGUID2(clsidNew, szClsidNew, ARRAYSIZE(szClsidNew)) &&
2790 !RegSetValueW(hkey, wszTreatAs, REG_SZ, szClsidNew, sizeof(szClsidNew)))
2792 res = REGDB_E_WRITEREGDB;
2797 if (hkey) RegCloseKey(hkey);
2801 /******************************************************************************
2802 * CoGetTreatAsClass [OLE32.@]
2804 * Gets the TreatAs value of a class.
2807 * clsidOld [I] Class to get the TreatAs value of.
2808 * clsidNew [I] The class the clsidOld should be treated as.
2812 * Failure: HRESULT code.
2817 HRESULT WINAPI CoGetTreatAsClass(REFCLSID clsidOld, LPCLSID clsidNew)
2819 static const WCHAR wszTreatAs[] = {'T','r','e','a','t','A','s',0};
2821 WCHAR szClsidNew[CHARS_IN_GUID];
2823 LONG len = sizeof(szClsidNew);
2825 FIXME("(%s,%p)\n", debugstr_guid(clsidOld), clsidNew);
2826 memcpy(clsidNew,clsidOld,sizeof(CLSID)); /* copy over old value */
2828 res = COM_OpenKeyForCLSID(clsidOld, wszTreatAs, KEY_READ, &hkey);
2831 if (RegQueryValueW(hkey, NULL, szClsidNew, &len))
2836 res = CLSIDFromString(szClsidNew,clsidNew);
2838 ERR("Failed CLSIDFromStringA(%s), hres 0x%08x\n", debugstr_w(szClsidNew), res);
2840 if (hkey) RegCloseKey(hkey);
2844 /******************************************************************************
2845 * CoGetCurrentProcess [OLE32.@]
2846 * CoGetCurrentProcess [COMPOBJ.34]
2848 * Gets the current process ID.
2851 * The current process ID.
2854 * Is DWORD really the correct return type for this function?
2856 DWORD WINAPI CoGetCurrentProcess(void)
2858 return GetCurrentProcessId();
2861 /******************************************************************************
2862 * CoRegisterMessageFilter [OLE32.@]
2864 * Registers a message filter.
2867 * lpMessageFilter [I] Pointer to interface.
2868 * lplpMessageFilter [O] Indirect pointer to prior instance if non-NULL.
2872 * Failure: HRESULT code.
2875 * Both lpMessageFilter and lplpMessageFilter are optional. Passing in a NULL
2876 * lpMessageFilter removes the message filter.
2878 * If lplpMessageFilter is not NULL the previous message filter will be
2879 * returned in the memory pointer to this parameter and the caller is
2880 * responsible for releasing the object.
2882 * The current thread be in an apartment otherwise the function will crash.
2884 HRESULT WINAPI CoRegisterMessageFilter(
2885 LPMESSAGEFILTER lpMessageFilter,
2886 LPMESSAGEFILTER *lplpMessageFilter)
2888 struct apartment *apt;
2889 IMessageFilter *lpOldMessageFilter;
2891 TRACE("(%p, %p)\n", lpMessageFilter, lplpMessageFilter);
2893 apt = COM_CurrentApt();
2895 /* can't set a message filter in a multi-threaded apartment */
2896 if (!apt || apt->multi_threaded)
2898 WARN("can't set message filter in MTA or uninitialized apt\n");
2899 return CO_E_NOT_SUPPORTED;
2902 if (lpMessageFilter)
2903 IMessageFilter_AddRef(lpMessageFilter);
2905 EnterCriticalSection(&apt->cs);
2907 lpOldMessageFilter = apt->filter;
2908 apt->filter = lpMessageFilter;
2910 LeaveCriticalSection(&apt->cs);
2912 if (lplpMessageFilter)
2913 *lplpMessageFilter = lpOldMessageFilter;
2914 else if (lpOldMessageFilter)
2915 IMessageFilter_Release(lpOldMessageFilter);
2920 /***********************************************************************
2921 * CoIsOle1Class [OLE32.@]
2923 * Determines whether the specified class an OLE v1 class.
2926 * clsid [I] Class to test.
2929 * TRUE if the class is an OLE v1 class, or FALSE otherwise.
2931 BOOL WINAPI CoIsOle1Class(REFCLSID clsid)
2933 FIXME("%s\n", debugstr_guid(clsid));
2937 /***********************************************************************
2938 * IsEqualGUID [OLE32.@]
2940 * Compares two Unique Identifiers.
2943 * rguid1 [I] The first GUID to compare.
2944 * rguid2 [I] The other GUID to compare.
2950 BOOL WINAPI IsEqualGUID(
2954 return !memcmp(rguid1,rguid2,sizeof(GUID));
2957 /***********************************************************************
2958 * CoInitializeSecurity [OLE32.@]
2960 HRESULT WINAPI CoInitializeSecurity(PSECURITY_DESCRIPTOR pSecDesc, LONG cAuthSvc,
2961 SOLE_AUTHENTICATION_SERVICE* asAuthSvc,
2962 void* pReserved1, DWORD dwAuthnLevel,
2963 DWORD dwImpLevel, void* pReserved2,
2964 DWORD dwCapabilities, void* pReserved3)
2966 FIXME("(%p,%d,%p,%p,%d,%d,%p,%d,%p) - stub!\n", pSecDesc, cAuthSvc,
2967 asAuthSvc, pReserved1, dwAuthnLevel, dwImpLevel, pReserved2,
2968 dwCapabilities, pReserved3);
2972 /***********************************************************************
2973 * CoSuspendClassObjects [OLE32.@]
2975 * Suspends all registered class objects to prevent further requests coming in
2976 * for those objects.
2980 * Failure: HRESULT code.
2982 HRESULT WINAPI CoSuspendClassObjects(void)
2988 /***********************************************************************
2989 * CoAddRefServerProcess [OLE32.@]
2991 * Helper function for incrementing the reference count of a local-server
2995 * New reference count.
2998 * CoReleaseServerProcess().
3000 ULONG WINAPI CoAddRefServerProcess(void)
3006 EnterCriticalSection(&csRegisteredClassList);
3007 refs = ++s_COMServerProcessReferences;
3008 LeaveCriticalSection(&csRegisteredClassList);
3010 TRACE("refs before: %d\n", refs - 1);
3015 /***********************************************************************
3016 * CoReleaseServerProcess [OLE32.@]
3018 * Helper function for decrementing the reference count of a local-server
3022 * New reference count.
3025 * When reference count reaches 0, this function suspends all registered
3026 * classes so no new connections are accepted.
3029 * CoAddRefServerProcess(), CoSuspendClassObjects().
3031 ULONG WINAPI CoReleaseServerProcess(void)
3037 EnterCriticalSection(&csRegisteredClassList);
3039 refs = --s_COMServerProcessReferences;
3040 /* FIXME: if (!refs) COM_SuspendClassObjects(); */
3042 LeaveCriticalSection(&csRegisteredClassList);
3044 TRACE("refs after: %d\n", refs);
3049 /***********************************************************************
3050 * CoIsHandlerConnected [OLE32.@]
3052 * Determines whether a proxy is connected to a remote stub.
3055 * pUnk [I] Pointer to object that may or may not be connected.
3058 * TRUE if pUnk is not a proxy or if pUnk is connected to a remote stub, or
3061 BOOL WINAPI CoIsHandlerConnected(IUnknown *pUnk)
3063 FIXME("%p\n", pUnk);
3068 /***********************************************************************
3069 * CoAllowSetForegroundWindow [OLE32.@]
3072 HRESULT WINAPI CoAllowSetForegroundWindow(IUnknown *pUnk, void *pvReserved)
3074 FIXME("(%p, %p): stub\n", pUnk, pvReserved);
3078 /***********************************************************************
3079 * CoQueryProxyBlanket [OLE32.@]
3081 * Retrieves the security settings being used by a proxy.
3084 * pProxy [I] Pointer to the proxy object.
3085 * pAuthnSvc [O] The type of authentication service.
3086 * pAuthzSvc [O] The type of authorization service.
3087 * ppServerPrincName [O] Optional. The server prinicple name.
3088 * pAuthnLevel [O] The authentication level.
3089 * pImpLevel [O] The impersonation level.
3090 * ppAuthInfo [O] Information specific to the authorization/authentication service.
3091 * pCapabilities [O] Flags affecting the security behaviour.
3095 * Failure: HRESULT code.
3098 * CoCopyProxy, CoSetProxyBlanket.
3100 HRESULT WINAPI CoQueryProxyBlanket(IUnknown *pProxy, DWORD *pAuthnSvc,
3101 DWORD *pAuthzSvc, OLECHAR **ppServerPrincName, DWORD *pAuthnLevel,
3102 DWORD *pImpLevel, void **ppAuthInfo, DWORD *pCapabilities)
3104 IClientSecurity *pCliSec;
3107 TRACE("%p\n", pProxy);
3109 hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
3112 hr = IClientSecurity_QueryBlanket(pCliSec, pProxy, pAuthnSvc,
3113 pAuthzSvc, ppServerPrincName,
3114 pAuthnLevel, pImpLevel, ppAuthInfo,
3116 IClientSecurity_Release(pCliSec);
3119 if (FAILED(hr)) ERR("-- failed with 0x%08x\n", hr);
3123 /***********************************************************************
3124 * CoSetProxyBlanket [OLE32.@]
3126 * Sets the security settings for a proxy.
3129 * pProxy [I] Pointer to the proxy object.
3130 * AuthnSvc [I] The type of authentication service.
3131 * AuthzSvc [I] The type of authorization service.
3132 * pServerPrincName [I] The server prinicple name.
3133 * AuthnLevel [I] The authentication level.
3134 * ImpLevel [I] The impersonation level.
3135 * pAuthInfo [I] Information specific to the authorization/authentication service.
3136 * Capabilities [I] Flags affecting the security behaviour.
3140 * Failure: HRESULT code.
3143 * CoQueryProxyBlanket, CoCopyProxy.
3145 HRESULT WINAPI CoSetProxyBlanket(IUnknown *pProxy, DWORD AuthnSvc,
3146 DWORD AuthzSvc, OLECHAR *pServerPrincName, DWORD AuthnLevel,
3147 DWORD ImpLevel, void *pAuthInfo, DWORD Capabilities)
3149 IClientSecurity *pCliSec;
3152 TRACE("%p\n", pProxy);
3154 hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
3157 hr = IClientSecurity_SetBlanket(pCliSec, pProxy, AuthnSvc,
3158 AuthzSvc, pServerPrincName,
3159 AuthnLevel, ImpLevel, pAuthInfo,
3161 IClientSecurity_Release(pCliSec);
3164 if (FAILED(hr)) ERR("-- failed with 0x%08x\n", hr);
3168 /***********************************************************************
3169 * CoCopyProxy [OLE32.@]
3174 * pProxy [I] Pointer to the proxy object.
3175 * ppCopy [O] Copy of the proxy.
3179 * Failure: HRESULT code.
3182 * CoQueryProxyBlanket, CoSetProxyBlanket.
3184 HRESULT WINAPI CoCopyProxy(IUnknown *pProxy, IUnknown **ppCopy)
3186 IClientSecurity *pCliSec;
3189 TRACE("%p\n", pProxy);
3191 hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
3194 hr = IClientSecurity_CopyProxy(pCliSec, pProxy, ppCopy);
3195 IClientSecurity_Release(pCliSec);
3198 if (FAILED(hr)) ERR("-- failed with 0x%08x\n", hr);
3203 /***********************************************************************
3204 * CoGetCallContext [OLE32.@]
3206 * Gets the context of the currently executing server call in the current
3210 * riid [I] Context interface to return.
3211 * ppv [O] Pointer to memory that will receive the context on return.
3215 * Failure: HRESULT code.
3217 HRESULT WINAPI CoGetCallContext(REFIID riid, void **ppv)
3219 FIXME("(%s, %p): stub\n", debugstr_guid(riid), ppv);
3222 return E_NOINTERFACE;
3225 /***********************************************************************
3226 * CoQueryClientBlanket [OLE32.@]
3228 * Retrieves the authentication information about the client of the currently
3229 * executing server call in the current thread.
3232 * pAuthnSvc [O] Optional. The type of authentication service.
3233 * pAuthzSvc [O] Optional. The type of authorization service.
3234 * pServerPrincName [O] Optional. The server prinicple name.
3235 * pAuthnLevel [O] Optional. The authentication level.
3236 * pImpLevel [O] Optional. The impersonation level.
3237 * pPrivs [O] Optional. Information about the privileges of the client.
3238 * pCapabilities [IO] Optional. Flags affecting the security behaviour.
3242 * Failure: HRESULT code.
3245 * CoImpersonateClient, CoRevertToSelf, CoGetCallContext.
3247 HRESULT WINAPI CoQueryClientBlanket(
3250 OLECHAR **pServerPrincName,
3253 RPC_AUTHZ_HANDLE *pPrivs,
3254 DWORD *pCapabilities)
3256 IServerSecurity *pSrvSec;
3259 TRACE("(%p, %p, %p, %p, %p, %p, %p)\n",
3260 pAuthnSvc, pAuthzSvc, pServerPrincName, pAuthnLevel, pImpLevel,
3261 pPrivs, pCapabilities);
3263 hr = CoGetCallContext(&IID_IServerSecurity, (void **)&pSrvSec);
3266 hr = IServerSecurity_QueryBlanket(
3267 pSrvSec, pAuthnSvc, pAuthzSvc, pServerPrincName, pAuthnLevel,
3268 pImpLevel, pPrivs, pCapabilities);
3269 IServerSecurity_Release(pSrvSec);
3275 /***********************************************************************
3276 * CoImpersonateClient [OLE32.@]
3278 * Impersonates the client of the currently executing server call in the
3286 * Failure: HRESULT code.
3289 * If this function fails then the current thread will not be impersonating
3290 * the client and all actions will take place on behalf of the server.
3291 * Therefore, it is important to check the return value from this function.
3294 * CoRevertToSelf, CoQueryClientBlanket, CoGetCallContext.
3296 HRESULT WINAPI CoImpersonateClient(void)
3298 IServerSecurity *pSrvSec;
3303 hr = CoGetCallContext(&IID_IServerSecurity, (void **)&pSrvSec);
3306 hr = IServerSecurity_ImpersonateClient(pSrvSec);
3307 IServerSecurity_Release(pSrvSec);
3313 /***********************************************************************
3314 * CoRevertToSelf [OLE32.@]
3316 * Ends the impersonation of the client of the currently executing server
3317 * call in the current thread.
3324 * Failure: HRESULT code.
3327 * CoImpersonateClient, CoQueryClientBlanket, CoGetCallContext.
3329 HRESULT WINAPI CoRevertToSelf(void)
3331 IServerSecurity *pSrvSec;
3336 hr = CoGetCallContext(&IID_IServerSecurity, (void **)&pSrvSec);
3339 hr = IServerSecurity_RevertToSelf(pSrvSec);
3340 IServerSecurity_Release(pSrvSec);
3346 static BOOL COM_PeekMessage(struct apartment *apt, MSG *msg)
3348 /* first try to retrieve messages for incoming COM calls to the apartment window */
3349 return PeekMessageW(msg, apt->win, WM_USER, WM_APP - 1, PM_REMOVE|PM_NOYIELD) ||
3350 /* next retrieve other messages necessary for the app to remain responsive */
3351 PeekMessageW(msg, NULL, 0, 0, PM_QS_PAINT|PM_QS_POSTMESSAGE|PM_REMOVE|PM_NOYIELD);
3354 /***********************************************************************
3355 * CoWaitForMultipleHandles [OLE32.@]
3357 * Waits for one or more handles to become signaled.
3360 * dwFlags [I] Flags. See notes.
3361 * dwTimeout [I] Timeout in milliseconds.
3362 * cHandles [I] Number of handles pointed to by pHandles.
3363 * pHandles [I] Handles to wait for.
3364 * lpdwindex [O] Index of handle that was signaled.
3368 * Failure: RPC_S_CALLPENDING on timeout.
3372 * The dwFlags parameter can be zero or more of the following:
3373 *| COWAIT_WAITALL - Wait for all of the handles to become signaled.
3374 *| COWAIT_ALERTABLE - Allows a queued APC to run during the wait.
3377 * MsgWaitForMultipleObjects, WaitForMultipleObjects.
3379 HRESULT WINAPI CoWaitForMultipleHandles(DWORD dwFlags, DWORD dwTimeout,
3380 ULONG cHandles, LPHANDLE pHandles, LPDWORD lpdwindex)
3383 DWORD start_time = GetTickCount();
3384 APARTMENT *apt = COM_CurrentApt();
3385 BOOL message_loop = apt && !apt->multi_threaded;
3387 TRACE("(0x%08x, 0x%08x, %d, %p, %p)\n", dwFlags, dwTimeout, cHandles,
3388 pHandles, lpdwindex);
3392 DWORD now = GetTickCount();
3395 if ((dwTimeout != INFINITE) && (start_time + dwTimeout >= now))
3397 hr = RPC_S_CALLPENDING;
3403 DWORD wait_flags = (dwFlags & COWAIT_WAITALL) ? MWMO_WAITALL : 0 |
3404 (dwFlags & COWAIT_ALERTABLE ) ? MWMO_ALERTABLE : 0;
3406 TRACE("waiting for rpc completion or window message\n");
3408 res = MsgWaitForMultipleObjectsEx(cHandles, pHandles,
3409 (dwTimeout == INFINITE) ? INFINITE : start_time + dwTimeout - now,
3410 QS_ALLINPUT, wait_flags);
3412 if (res == WAIT_OBJECT_0 + cHandles) /* messages available */
3416 /* call message filter */
3418 if (COM_CurrentApt()->filter)
3420 PENDINGTYPE pendingtype =
3421 COM_CurrentInfo()->pending_call_count_server ?
3422 PENDINGTYPE_NESTED : PENDINGTYPE_TOPLEVEL;
3423 DWORD be_handled = IMessageFilter_MessagePending(
3424 COM_CurrentApt()->filter, 0 /* FIXME */,
3425 now - start_time, pendingtype);
3426 TRACE("IMessageFilter_MessagePending returned %d\n", be_handled);
3429 case PENDINGMSG_CANCELCALL:
3430 WARN("call canceled\n");
3431 hr = RPC_E_CALL_CANCELED;
3433 case PENDINGMSG_WAITNOPROCESS:
3434 case PENDINGMSG_WAITDEFPROCESS:
3436 /* FIXME: MSDN is very vague about the difference
3437 * between WAITNOPROCESS and WAITDEFPROCESS - there
3438 * appears to be none, so it is possibly a left-over
3439 * from the 16-bit world. */
3444 /* note: using "if" here instead of "while" might seem less
3445 * efficient, but only if we are optimising for quick delivery
3446 * of pending messages, rather than quick completion of the
3448 if (COM_PeekMessage(apt, &msg))
3450 TRACE("received message whilst waiting for RPC: 0x%04x\n", msg.message);
3451 TranslateMessage(&msg);
3452 DispatchMessageW(&msg);
3453 if (msg.message == WM_QUIT)
3455 TRACE("resending WM_QUIT to outer message loop\n");
3456 PostQuitMessage(msg.wParam);
3457 /* no longer need to process messages */
3458 message_loop = FALSE;
3466 TRACE("waiting for rpc completion\n");
3468 res = WaitForMultipleObjectsEx(cHandles, pHandles,
3469 (dwFlags & COWAIT_WAITALL) ? TRUE : FALSE,
3470 (dwTimeout == INFINITE) ? INFINITE : start_time + dwTimeout - now,
3471 (dwFlags & COWAIT_ALERTABLE) ? TRUE : FALSE);
3474 if ((res >= WAIT_OBJECT_0) && (res < WAIT_OBJECT_0 + cHandles))
3476 /* handle signaled, store index */
3477 *lpdwindex = (res - WAIT_OBJECT_0);
3480 else if (res == WAIT_TIMEOUT)
3482 hr = RPC_S_CALLPENDING;
3487 ERR("Unexpected wait termination: %d, %d\n", res, GetLastError());
3492 TRACE("-- 0x%08x\n", hr);
3497 /***********************************************************************
3498 * CoGetObject [OLE32.@]
3500 * Gets the object named by coverting the name to a moniker and binding to it.
3503 * pszName [I] String representing the object.
3504 * pBindOptions [I] Parameters affecting the binding to the named object.
3505 * riid [I] Interface to bind to on the objecct.
3506 * ppv [O] On output, the interface riid of the object represented
3511 * Failure: HRESULT code.
3514 * MkParseDisplayName.
3516 HRESULT WINAPI CoGetObject(LPCWSTR pszName, BIND_OPTS *pBindOptions,
3517 REFIID riid, void **ppv)
3524 hr = CreateBindCtx(0, &pbc);
3528 hr = IBindCtx_SetBindOptions(pbc, pBindOptions);
3535 hr = MkParseDisplayName(pbc, pszName, &chEaten, &pmk);
3538 hr = IMoniker_BindToObject(pmk, pbc, NULL, riid, ppv);
3539 IMoniker_Release(pmk);
3543 IBindCtx_Release(pbc);
3548 /***********************************************************************
3549 * CoRegisterChannelHook [OLE32.@]
3551 * Registers a process-wide hook that is called during ORPC calls.
3554 * guidExtension [I] GUID of the channel hook to register.
3555 * pChannelHook [I] Channel hook object to register.
3559 * Failure: HRESULT code.
3561 HRESULT WINAPI CoRegisterChannelHook(REFGUID guidExtension, IChannelHook *pChannelHook)
3563 TRACE("(%s, %p)\n", debugstr_guid(guidExtension), pChannelHook);
3565 return RPC_RegisterChannelHook(guidExtension, pChannelHook);
3568 typedef struct Context
3570 const IComThreadingInfoVtbl *lpVtbl;
3575 static HRESULT WINAPI Context_QueryInterface(IComThreadingInfo *iface, REFIID riid, LPVOID *ppv)
3579 if (IsEqualIID(riid, &IID_IComThreadingInfo) ||
3580 IsEqualIID(riid, &IID_IUnknown))
3583 IUnknown_AddRef(iface);
3587 FIXME("interface not implemented %s\n", debugstr_guid(riid));
3588 return E_NOINTERFACE;
3591 static ULONG WINAPI Context_AddRef(IComThreadingInfo *iface)
3593 Context *This = (Context *)iface;
3594 return InterlockedIncrement(&This->refs);
3597 static ULONG WINAPI Context_Release(IComThreadingInfo *iface)
3599 Context *This = (Context *)iface;
3600 ULONG refs = InterlockedDecrement(&This->refs);
3602 HeapFree(GetProcessHeap(), 0, This);
3606 static HRESULT WINAPI Context_GetCurrentApartmentType(IComThreadingInfo *iface, APTTYPE *apttype)
3608 Context *This = (Context *)iface;
3610 TRACE("(%p)\n", apttype);
3612 *apttype = This->apttype;
3616 static HRESULT WINAPI Context_GetCurrentThreadType(IComThreadingInfo *iface, THDTYPE *thdtype)
3618 Context *This = (Context *)iface;
3620 TRACE("(%p)\n", thdtype);
3622 switch (This->apttype)
3625 case APTTYPE_MAINSTA:
3626 *thdtype = THDTYPE_PROCESSMESSAGES;
3629 *thdtype = THDTYPE_BLOCKMESSAGES;
3635 static HRESULT WINAPI Context_GetCurrentLogicalThreadId(IComThreadingInfo *iface, GUID *logical_thread_id)
3637 FIXME("(%p): stub\n", logical_thread_id);
3641 static HRESULT WINAPI Context_SetCurrentLogicalThreadId(IComThreadingInfo *iface, REFGUID logical_thread_id)
3643 FIXME("(%s): stub\n", debugstr_guid(logical_thread_id));
3647 static const IComThreadingInfoVtbl Context_Threading_Vtbl =
3649 Context_QueryInterface,
3652 Context_GetCurrentApartmentType,
3653 Context_GetCurrentThreadType,
3654 Context_GetCurrentLogicalThreadId,
3655 Context_SetCurrentLogicalThreadId
3658 /***********************************************************************
3659 * CoGetObjectContext [OLE32.@]
3661 * Retrieves an object associated with the current context (i.e. apartment).
3664 * riid [I] ID of the interface of the object to retrieve.
3665 * ppv [O] Address where object will be stored on return.
3669 * Failure: HRESULT code.
3671 HRESULT WINAPI CoGetObjectContext(REFIID riid, void **ppv)
3673 APARTMENT *apt = COM_CurrentApt();
3677 TRACE("(%s, %p)\n", debugstr_guid(riid), ppv);
3682 ERR("apartment not initialised\n");
3683 return CO_E_NOTINITIALIZED;
3686 context = HeapAlloc(GetProcessHeap(), 0, sizeof(*context));
3688 return E_OUTOFMEMORY;
3690 context->lpVtbl = &Context_Threading_Vtbl;
3692 if (apt->multi_threaded)
3693 context->apttype = APTTYPE_MTA;
3695 context->apttype = APTTYPE_MAINSTA;
3697 context->apttype = APTTYPE_STA;
3699 hr = IUnknown_QueryInterface((IUnknown *)&context->lpVtbl, riid, ppv);
3700 IUnknown_Release((IUnknown *)&context->lpVtbl);
3705 /***********************************************************************
3708 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID fImpLoad)
3710 TRACE("%p 0x%x %p\n", hinstDLL, fdwReason, fImpLoad);
3713 case DLL_PROCESS_ATTACH:
3714 OLE32_hInstance = hinstDLL;
3715 COMPOBJ_InitProcess();
3716 if (TRACE_ON(ole)) CoRegisterMallocSpy((LPVOID)-1);
3719 case DLL_PROCESS_DETACH:
3720 if (TRACE_ON(ole)) CoRevokeMallocSpy();
3721 OLEDD_UnInitialize();
3722 COMPOBJ_UninitProcess();
3723 RPC_UnregisterAllChannelHooks();
3724 OLE32_hInstance = 0;
3727 case DLL_THREAD_DETACH:
3734 /* NOTE: DllRegisterServer and DllUnregisterServer are in regsvr.c */