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 /* frees memory associated with active dll list */
969 static void COMPOBJ_DllList_Free(void)
971 OpenDll *entry, *cursor2;
972 EnterCriticalSection(&csOpenDllList);
973 LIST_FOR_EACH_ENTRY_SAFE(entry, cursor2, &openDllList, OpenDll, entry)
975 list_remove(&entry->entry);
977 HeapFree(GetProcessHeap(), 0, entry->library_name);
978 HeapFree(GetProcessHeap(), 0, entry);
980 LeaveCriticalSection(&csOpenDllList);
983 /******************************************************************************
984 * CoBuildVersion [OLE32.@]
985 * CoBuildVersion [COMPOBJ.1]
987 * Gets the build version of the DLL.
992 * Current build version, hiword is majornumber, loword is minornumber
994 DWORD WINAPI CoBuildVersion(void)
996 TRACE("Returning version %d, build %d.\n", rmm, rup);
997 return (rmm<<16)+rup;
1000 /******************************************************************************
1001 * CoInitialize [OLE32.@]
1003 * Initializes the COM libraries by calling CoInitializeEx with
1004 * COINIT_APARTMENTTHREADED, ie it enters a STA thread.
1007 * lpReserved [I] Pointer to IMalloc interface (obsolete, should be NULL).
1010 * Success: S_OK if not already initialized, S_FALSE otherwise.
1011 * Failure: HRESULT code.
1016 HRESULT WINAPI CoInitialize(LPVOID lpReserved)
1019 * Just delegate to the newer method.
1021 return CoInitializeEx(lpReserved, COINIT_APARTMENTTHREADED);
1024 /******************************************************************************
1025 * CoInitializeEx [OLE32.@]
1027 * Initializes the COM libraries.
1030 * lpReserved [I] Pointer to IMalloc interface (obsolete, should be NULL).
1031 * dwCoInit [I] One or more flags from the COINIT enumeration. See notes.
1034 * S_OK if successful,
1035 * S_FALSE if this function was called already.
1036 * RPC_E_CHANGED_MODE if a previous call to CoInitializeEx specified another
1041 * The behavior used to set the IMalloc used for memory management is
1043 * The dwCoInit parameter must specify one of the following apartment
1045 *| COINIT_APARTMENTTHREADED - A single-threaded apartment (STA).
1046 *| COINIT_MULTITHREADED - A multi-threaded apartment (MTA).
1047 * The parameter may also specify zero or more of the following flags:
1048 *| COINIT_DISABLE_OLE1DDE - Don't use DDE for OLE1 support.
1049 *| COINIT_SPEED_OVER_MEMORY - Trade memory for speed.
1054 HRESULT WINAPI CoInitializeEx(LPVOID lpReserved, DWORD dwCoInit)
1059 TRACE("(%p, %x)\n", lpReserved, (int)dwCoInit);
1061 if (lpReserved!=NULL)
1063 ERR("(%p, %x) - Bad parameter passed-in %p, must be an old Windows Application\n", lpReserved, (int)dwCoInit, lpReserved);
1067 * Check the lock count. If this is the first time going through the initialize
1068 * process, we have to initialize the libraries.
1070 * And crank-up that lock count.
1072 if (InterlockedExchangeAdd(&s_COMLockCount,1)==0)
1075 * Initialize the various COM libraries and data structures.
1077 TRACE("() - Initializing the COM libraries\n");
1079 /* we may need to defer this until after apartment initialisation */
1080 RunningObjectTableImpl_Initialize();
1083 if (!(apt = COM_CurrentInfo()->apt))
1085 apt = apartment_get_or_create(dwCoInit);
1086 if (!apt) return E_OUTOFMEMORY;
1088 else if (!apartment_is_model(apt, dwCoInit))
1090 /* Changing the threading model after it's been set is illegal. If this warning is triggered by Wine
1091 code then we are probably using the wrong threading model to implement that API. */
1092 ERR("Attempt to change threading model of this apartment from %s to %s\n",
1093 apt->multi_threaded ? "multi-threaded" : "apartment threaded",
1094 dwCoInit & COINIT_APARTMENTTHREADED ? "apartment threaded" : "multi-threaded");
1095 return RPC_E_CHANGED_MODE;
1100 COM_CurrentInfo()->inits++;
1105 /***********************************************************************
1106 * CoUninitialize [OLE32.@]
1108 * This method will decrement the refcount on the current apartment, freeing
1109 * the resources associated with it if it is the last thread in the apartment.
1110 * If the last apartment is freed, the function will additionally release
1111 * any COM resources associated with the process.
1121 void WINAPI CoUninitialize(void)
1123 struct oletls * info = COM_CurrentInfo();
1128 /* will only happen on OOM */
1134 ERR("Mismatched CoUninitialize\n");
1140 apartment_release(info->apt);
1145 * Decrease the reference count.
1146 * If we are back to 0 locks on the COM library, make sure we free
1147 * all the associated data structures.
1149 lCOMRefCnt = InterlockedExchangeAdd(&s_COMLockCount,-1);
1152 TRACE("() - Releasing the COM libraries\n");
1154 RunningObjectTableImpl_UnInitialize();
1156 else if (lCOMRefCnt<1) {
1157 ERR( "CoUninitialize() - not CoInitialized.\n" );
1158 InterlockedExchangeAdd(&s_COMLockCount,1); /* restore the lock count. */
1162 /******************************************************************************
1163 * CoDisconnectObject [OLE32.@]
1165 * Disconnects all connections to this object from remote processes. Dispatches
1166 * pending RPCs while blocking new RPCs from occurring, and then calls
1167 * IMarshal::DisconnectObject on the given object.
1169 * Typically called when the object server is forced to shut down, for instance by
1173 * lpUnk [I] The object whose stub should be disconnected.
1174 * reserved [I] Reserved. Should be set to 0.
1178 * Failure: HRESULT code.
1181 * CoMarshalInterface, CoReleaseMarshalData, CoLockObjectExternal
1183 HRESULT WINAPI CoDisconnectObject( LPUNKNOWN lpUnk, DWORD reserved )
1189 TRACE("(%p, 0x%08x)\n", lpUnk, reserved);
1191 hr = IUnknown_QueryInterface(lpUnk, &IID_IMarshal, (void **)&marshal);
1194 hr = IMarshal_DisconnectObject(marshal, reserved);
1195 IMarshal_Release(marshal);
1199 apt = COM_CurrentApt();
1201 return CO_E_NOTINITIALIZED;
1203 apartment_disconnectobject(apt, lpUnk);
1205 /* Note: native is pretty broken here because it just silently
1206 * fails, without returning an appropriate error code if the object was
1207 * not found, making apps think that the object was disconnected, when
1208 * it actually wasn't */
1213 /******************************************************************************
1214 * CoCreateGuid [OLE32.@]
1215 * CoCreateGuid [COMPOBJ.73]
1217 * Simply forwards to UuidCreate in RPCRT4.
1220 * pguid [O] Points to the GUID to initialize.
1224 * Failure: HRESULT code.
1229 HRESULT WINAPI CoCreateGuid(GUID *pguid)
1231 return UuidCreate(pguid);
1234 /******************************************************************************
1235 * CLSIDFromString [OLE32.@]
1236 * IIDFromString [OLE32.@]
1238 * Converts a unique identifier from its string representation into
1242 * idstr [I] The string representation of the GUID.
1243 * id [O] GUID converted from the string.
1247 * CO_E_CLASSSTRING if idstr is not a valid CLSID
1252 static HRESULT WINAPI __CLSIDFromString(LPCWSTR s, CLSID *id)
1258 memset( id, 0, sizeof (CLSID) );
1262 /* validate the CLSID string */
1263 if (strlenW(s) != 38)
1264 return CO_E_CLASSSTRING;
1266 if ((s[0]!='{') || (s[9]!='-') || (s[14]!='-') || (s[19]!='-') || (s[24]!='-') || (s[37]!='}'))
1267 return CO_E_CLASSSTRING;
1269 for (i=1; i<37; i++) {
1270 if ((i == 9)||(i == 14)||(i == 19)||(i == 24)) continue;
1271 if (!(((s[i] >= '0') && (s[i] <= '9')) ||
1272 ((s[i] >= 'a') && (s[i] <= 'f')) ||
1273 ((s[i] >= 'A') && (s[i] <= 'F'))))
1274 return CO_E_CLASSSTRING;
1277 TRACE("%s -> %p\n", debugstr_w(s), id);
1279 /* quick lookup table */
1280 memset(table, 0, 256);
1282 for (i = 0; i < 10; i++) {
1285 for (i = 0; i < 6; i++) {
1286 table['A' + i] = i+10;
1287 table['a' + i] = i+10;
1290 /* in form {XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX} */
1292 id->Data1 = (table[s[1]] << 28 | table[s[2]] << 24 | table[s[3]] << 20 | table[s[4]] << 16 |
1293 table[s[5]] << 12 | table[s[6]] << 8 | table[s[7]] << 4 | table[s[8]]);
1294 id->Data2 = table[s[10]] << 12 | table[s[11]] << 8 | table[s[12]] << 4 | table[s[13]];
1295 id->Data3 = table[s[15]] << 12 | table[s[16]] << 8 | table[s[17]] << 4 | table[s[18]];
1297 /* these are just sequential bytes */
1298 id->Data4[0] = table[s[20]] << 4 | table[s[21]];
1299 id->Data4[1] = table[s[22]] << 4 | table[s[23]];
1300 id->Data4[2] = table[s[25]] << 4 | table[s[26]];
1301 id->Data4[3] = table[s[27]] << 4 | table[s[28]];
1302 id->Data4[4] = table[s[29]] << 4 | table[s[30]];
1303 id->Data4[5] = table[s[31]] << 4 | table[s[32]];
1304 id->Data4[6] = table[s[33]] << 4 | table[s[34]];
1305 id->Data4[7] = table[s[35]] << 4 | table[s[36]];
1310 /*****************************************************************************/
1312 HRESULT WINAPI CLSIDFromString(LPOLESTR idstr, CLSID *id )
1317 return E_INVALIDARG;
1319 ret = __CLSIDFromString(idstr, id);
1320 if(ret != S_OK) { /* It appears a ProgID is also valid */
1321 ret = CLSIDFromProgID(idstr, id);
1326 /* Converts a GUID into the respective string representation. */
1327 HRESULT WINE_StringFromCLSID(
1328 const CLSID *id, /* [in] GUID to be converted */
1329 LPSTR idstr /* [out] pointer to buffer to contain converted guid */
1331 static const char hex[] = "0123456789ABCDEF";
1336 { ERR("called with id=Null\n");
1341 sprintf(idstr, "{%08X-%04X-%04X-%02X%02X-",
1342 id->Data1, id->Data2, id->Data3,
1343 id->Data4[0], id->Data4[1]);
1347 for (i = 2; i < 8; i++) {
1348 *s++ = hex[id->Data4[i]>>4];
1349 *s++ = hex[id->Data4[i] & 0xf];
1355 TRACE("%p->%s\n", id, idstr);
1361 /******************************************************************************
1362 * StringFromCLSID [OLE32.@]
1363 * StringFromIID [OLE32.@]
1365 * Converts a GUID into the respective string representation.
1366 * The target string is allocated using the OLE IMalloc.
1369 * id [I] the GUID to be converted.
1370 * idstr [O] A pointer to a to-be-allocated pointer pointing to the resulting string.
1377 * StringFromGUID2, CLSIDFromString
1379 HRESULT WINAPI StringFromCLSID(REFCLSID id, LPOLESTR *idstr)
1385 if ((ret = CoGetMalloc(0,&mllc)))
1388 ret=WINE_StringFromCLSID(id,buf);
1390 DWORD len = MultiByteToWideChar( CP_ACP, 0, buf, -1, NULL, 0 );
1391 *idstr = IMalloc_Alloc( mllc, len * sizeof(WCHAR) );
1392 MultiByteToWideChar( CP_ACP, 0, buf, -1, *idstr, len );
1397 /******************************************************************************
1398 * StringFromGUID2 [OLE32.@]
1399 * StringFromGUID2 [COMPOBJ.76]
1401 * Modified version of StringFromCLSID that allows you to specify max
1405 * id [I] GUID to convert to string.
1406 * str [O] Buffer where the result will be stored.
1407 * cmax [I] Size of the buffer in characters.
1410 * Success: The length of the resulting string in characters.
1413 INT WINAPI StringFromGUID2(REFGUID id, LPOLESTR str, INT cmax)
1417 if (WINE_StringFromCLSID(id,xguid))
1419 return MultiByteToWideChar( CP_ACP, 0, xguid, -1, str, cmax );
1422 /* open HKCR\\CLSID\\{string form of clsid}\\{keyname} key */
1423 HRESULT COM_OpenKeyForCLSID(REFCLSID clsid, LPCWSTR keyname, REGSAM access, HKEY *subkey)
1425 static const WCHAR wszCLSIDSlash[] = {'C','L','S','I','D','\\',0};
1426 WCHAR path[CHARS_IN_GUID + ARRAYSIZE(wszCLSIDSlash) - 1];
1430 strcpyW(path, wszCLSIDSlash);
1431 StringFromGUID2(clsid, path + strlenW(wszCLSIDSlash), CHARS_IN_GUID);
1432 res = RegOpenKeyExW(HKEY_CLASSES_ROOT, path, 0, keyname ? KEY_READ : access, &key);
1433 if (res == ERROR_FILE_NOT_FOUND)
1434 return REGDB_E_CLASSNOTREG;
1435 else if (res != ERROR_SUCCESS)
1436 return REGDB_E_READREGDB;
1444 res = RegOpenKeyExW(key, keyname, 0, access, subkey);
1446 if (res == ERROR_FILE_NOT_FOUND)
1447 return REGDB_E_KEYMISSING;
1448 else if (res != ERROR_SUCCESS)
1449 return REGDB_E_READREGDB;
1454 /* open HKCR\\AppId\\{string form of appid clsid} key */
1455 HRESULT COM_OpenKeyForAppIdFromCLSID(REFCLSID clsid, REGSAM access, HKEY *subkey)
1457 static const WCHAR szAppId[] = { 'A','p','p','I','d',0 };
1458 static const WCHAR szAppIdKey[] = { 'A','p','p','I','d','\\',0 };
1460 WCHAR buf[CHARS_IN_GUID];
1461 WCHAR keyname[ARRAYSIZE(szAppIdKey) + CHARS_IN_GUID];
1467 /* read the AppID value under the class's key */
1468 hr = COM_OpenKeyForCLSID(clsid, NULL, KEY_READ, &hkey);
1473 res = RegQueryValueExW(hkey, szAppId, NULL, &type, (LPBYTE)buf, &size);
1475 if (res == ERROR_FILE_NOT_FOUND)
1476 return REGDB_E_KEYMISSING;
1477 else if (res != ERROR_SUCCESS || type!=REG_SZ)
1478 return REGDB_E_READREGDB;
1480 strcpyW(keyname, szAppIdKey);
1481 strcatW(keyname, buf);
1482 res = RegOpenKeyExW(HKEY_CLASSES_ROOT, keyname, 0, access, subkey);
1483 if (res == ERROR_FILE_NOT_FOUND)
1484 return REGDB_E_KEYMISSING;
1485 else if (res != ERROR_SUCCESS)
1486 return REGDB_E_READREGDB;
1491 /******************************************************************************
1492 * ProgIDFromCLSID [OLE32.@]
1494 * Converts a class id into the respective program ID.
1497 * clsid [I] Class ID, as found in registry.
1498 * ppszProgID [O] Associated ProgID.
1503 * REGDB_E_CLASSNOTREG if the given clsid has no associated ProgID
1505 HRESULT WINAPI ProgIDFromCLSID(REFCLSID clsid, LPOLESTR *ppszProgID)
1507 static const WCHAR wszProgID[] = {'P','r','o','g','I','D',0};
1514 ERR("ppszProgId isn't optional\n");
1515 return E_INVALIDARG;
1519 ret = COM_OpenKeyForCLSID(clsid, wszProgID, KEY_READ, &hkey);
1523 if (RegQueryValueW(hkey, NULL, NULL, &progidlen))
1524 ret = REGDB_E_CLASSNOTREG;
1528 *ppszProgID = CoTaskMemAlloc(progidlen * sizeof(WCHAR));
1531 if (RegQueryValueW(hkey, NULL, *ppszProgID, &progidlen))
1532 ret = REGDB_E_CLASSNOTREG;
1535 ret = E_OUTOFMEMORY;
1542 /******************************************************************************
1543 * CLSIDFromProgID [OLE32.@]
1545 * Converts a program id into the respective GUID.
1548 * progid [I] Unicode program ID, as found in registry.
1549 * clsid [O] Associated CLSID.
1553 * Failure: CO_E_CLASSSTRING - the given ProgID cannot be found.
1555 HRESULT WINAPI CLSIDFromProgID(LPCOLESTR progid, LPCLSID clsid)
1557 static const WCHAR clsidW[] = { '\\','C','L','S','I','D',0 };
1558 WCHAR buf2[CHARS_IN_GUID];
1559 LONG buf2len = sizeof(buf2);
1563 if (!progid || !clsid)
1565 ERR("neither progid (%p) nor clsid (%p) are optional\n", progid, clsid);
1566 return E_INVALIDARG;
1569 /* initialise clsid in case of failure */
1570 memset(clsid, 0, sizeof(*clsid));
1572 buf = HeapAlloc( GetProcessHeap(),0,(strlenW(progid)+8) * sizeof(WCHAR) );
1573 strcpyW( buf, progid );
1574 strcatW( buf, clsidW );
1575 if (RegOpenKeyW(HKEY_CLASSES_ROOT,buf,&xhkey))
1577 HeapFree(GetProcessHeap(),0,buf);
1578 WARN("couldn't open key for ProgID %s\n", debugstr_w(progid));
1579 return CO_E_CLASSSTRING;
1581 HeapFree(GetProcessHeap(),0,buf);
1583 if (RegQueryValueW(xhkey,NULL,buf2,&buf2len))
1586 WARN("couldn't query clsid value for ProgID %s\n", debugstr_w(progid));
1587 return CO_E_CLASSSTRING;
1590 return CLSIDFromString(buf2,clsid);
1594 /*****************************************************************************
1595 * CoGetPSClsid [OLE32.@]
1597 * Retrieves the CLSID of the proxy/stub factory that implements
1598 * IPSFactoryBuffer for the specified interface.
1601 * riid [I] Interface whose proxy/stub CLSID is to be returned.
1602 * pclsid [O] Where to store returned proxy/stub CLSID.
1607 * REGDB_E_IIDNOTREG if no PSFactoryBuffer is associated with the IID, or it could not be parsed
1611 * The standard marshaller activates the object with the CLSID
1612 * returned and uses the CreateProxy and CreateStub methods on its
1613 * IPSFactoryBuffer interface to construct the proxies and stubs for a
1616 * CoGetPSClsid determines this CLSID by searching the
1617 * HKEY_CLASSES_ROOT\Interface\{string form of riid}\ProxyStubClsid32
1618 * in the registry and any interface id registered by
1619 * CoRegisterPSClsid within the current process.
1623 * Native returns S_OK for interfaces with a key in HKCR\Interface, but
1624 * without a ProxyStubClsid32 key and leaves garbage in pclsid. This should be
1625 * considered a bug in native unless an application depends on this (unlikely).
1628 * CoRegisterPSClsid.
1630 HRESULT WINAPI CoGetPSClsid(REFIID riid, CLSID *pclsid)
1632 static const WCHAR wszInterface[] = {'I','n','t','e','r','f','a','c','e','\\',0};
1633 static const WCHAR wszPSC[] = {'\\','P','r','o','x','y','S','t','u','b','C','l','s','i','d','3','2',0};
1634 WCHAR path[ARRAYSIZE(wszInterface) - 1 + CHARS_IN_GUID - 1 + ARRAYSIZE(wszPSC)];
1635 WCHAR value[CHARS_IN_GUID];
1638 APARTMENT *apt = COM_CurrentApt();
1639 struct registered_psclsid *registered_psclsid;
1641 TRACE("() riid=%s, pclsid=%p\n", debugstr_guid(riid), pclsid);
1645 ERR("apartment not initialised\n");
1646 return CO_E_NOTINITIALIZED;
1651 ERR("pclsid isn't optional\n");
1652 return E_INVALIDARG;
1655 EnterCriticalSection(&apt->cs);
1657 LIST_FOR_EACH_ENTRY(registered_psclsid, &apt->psclsids, struct registered_psclsid, entry)
1658 if (IsEqualIID(®istered_psclsid->iid, riid))
1660 *pclsid = registered_psclsid->clsid;
1661 LeaveCriticalSection(&apt->cs);
1665 LeaveCriticalSection(&apt->cs);
1667 /* Interface\\{string form of riid}\\ProxyStubClsid32 */
1668 strcpyW(path, wszInterface);
1669 StringFromGUID2(riid, path + ARRAYSIZE(wszInterface) - 1, CHARS_IN_GUID);
1670 strcpyW(path + ARRAYSIZE(wszInterface) - 1 + CHARS_IN_GUID - 1, wszPSC);
1672 /* Open the key.. */
1673 if (RegOpenKeyExW(HKEY_CLASSES_ROOT, path, 0, KEY_READ, &hkey))
1675 WARN("No PSFactoryBuffer object is registered for IID %s\n", debugstr_guid(riid));
1676 return REGDB_E_IIDNOTREG;
1679 /* ... Once we have the key, query the registry to get the
1680 value of CLSID as a string, and convert it into a
1681 proper CLSID structure to be passed back to the app */
1682 len = sizeof(value);
1683 if (ERROR_SUCCESS != RegQueryValueW(hkey, NULL, value, &len))
1686 return REGDB_E_IIDNOTREG;
1690 /* We have the CLSid we want back from the registry as a string, so
1691 lets convert it into a CLSID structure */
1692 if (CLSIDFromString(value, pclsid) != NOERROR)
1693 return REGDB_E_IIDNOTREG;
1695 TRACE ("() Returning CLSID=%s\n", debugstr_guid(pclsid));
1699 /*****************************************************************************
1700 * CoRegisterPSClsid [OLE32.@]
1702 * Register a proxy/stub CLSID for the given interface in the current process
1706 * riid [I] Interface whose proxy/stub CLSID is to be registered.
1707 * rclsid [I] CLSID of the proxy/stub.
1711 * Failure: E_OUTOFMEMORY
1715 * This function does not add anything to the registry and the effects are
1716 * limited to the lifetime of the current process.
1721 HRESULT WINAPI CoRegisterPSClsid(REFIID riid, REFCLSID rclsid)
1723 APARTMENT *apt = COM_CurrentApt();
1724 struct registered_psclsid *registered_psclsid;
1726 TRACE("(%s, %s)\n", debugstr_guid(riid), debugstr_guid(rclsid));
1730 ERR("apartment not initialised\n");
1731 return CO_E_NOTINITIALIZED;
1734 EnterCriticalSection(&apt->cs);
1736 LIST_FOR_EACH_ENTRY(registered_psclsid, &apt->psclsids, struct registered_psclsid, entry)
1737 if (IsEqualIID(®istered_psclsid->iid, riid))
1739 registered_psclsid->clsid = *rclsid;
1740 LeaveCriticalSection(&apt->cs);
1744 registered_psclsid = HeapAlloc(GetProcessHeap(), 0, sizeof(struct registered_psclsid));
1745 if (!registered_psclsid)
1747 LeaveCriticalSection(&apt->cs);
1748 return E_OUTOFMEMORY;
1751 registered_psclsid->iid = *riid;
1752 registered_psclsid->clsid = *rclsid;
1753 list_add_head(&apt->psclsids, ®istered_psclsid->entry);
1755 LeaveCriticalSection(&apt->cs);
1762 * COM_GetRegisteredClassObject
1764 * This internal method is used to scan the registered class list to
1765 * find a class object.
1768 * rclsid Class ID of the class to find.
1769 * dwClsContext Class context to match.
1770 * ppv [out] returns a pointer to the class object. Complying
1771 * to normal COM usage, this method will increase the
1772 * reference count on this object.
1774 static HRESULT COM_GetRegisteredClassObject(const struct apartment *apt, REFCLSID rclsid,
1775 DWORD dwClsContext, LPUNKNOWN* ppUnk)
1777 HRESULT hr = S_FALSE;
1778 RegisteredClass *curClass;
1785 EnterCriticalSection( &csRegisteredClassList );
1787 LIST_FOR_EACH_ENTRY(curClass, &RegisteredClassList, RegisteredClass, entry)
1790 * Check if we have a match on the class ID and context.
1792 if ((apt->oxid == curClass->apartment_id) &&
1793 (dwClsContext & curClass->runContext) &&
1794 IsEqualGUID(&(curClass->classIdentifier), rclsid))
1797 * We have a match, return the pointer to the class object.
1799 *ppUnk = curClass->classObject;
1801 IUnknown_AddRef(curClass->classObject);
1808 LeaveCriticalSection( &csRegisteredClassList );
1813 /******************************************************************************
1814 * CoRegisterClassObject [OLE32.@]
1816 * Registers the class object for a given class ID. Servers housed in EXE
1817 * files use this method instead of exporting DllGetClassObject to allow
1818 * other code to connect to their objects.
1821 * rclsid [I] CLSID of the object to register.
1822 * pUnk [I] IUnknown of the object.
1823 * dwClsContext [I] CLSCTX flags indicating the context in which to run the executable.
1824 * flags [I] REGCLS flags indicating how connections are made.
1825 * lpdwRegister [I] A unique cookie that can be passed to CoRevokeClassObject.
1829 * E_INVALIDARG if lpdwRegister or pUnk are NULL,
1830 * CO_E_OBJISREG if the object is already registered. We should not return this.
1833 * CoRevokeClassObject, CoGetClassObject
1836 * In-process objects are only registered for the current apartment.
1837 * CoGetClassObject() and CoCreateInstance() will not return objects registered
1838 * in other apartments.
1841 * MSDN claims that multiple interface registrations are legal, but we
1842 * can't do that with our current implementation.
1844 HRESULT WINAPI CoRegisterClassObject(
1849 LPDWORD lpdwRegister)
1851 RegisteredClass* newClass;
1852 LPUNKNOWN foundObject;
1856 TRACE("(%s,%p,0x%08x,0x%08x,%p)\n",
1857 debugstr_guid(rclsid),pUnk,dwClsContext,flags,lpdwRegister);
1859 if ( (lpdwRegister==0) || (pUnk==0) )
1860 return E_INVALIDARG;
1862 apt = COM_CurrentApt();
1865 ERR("COM was not initialized\n");
1866 return CO_E_NOTINITIALIZED;
1871 /* REGCLS_MULTIPLEUSE implies registering as inproc server. This is what
1872 * differentiates the flag from REGCLS_MULTI_SEPARATE. */
1873 if (flags & REGCLS_MULTIPLEUSE)
1874 dwClsContext |= CLSCTX_INPROC_SERVER;
1877 * First, check if the class is already registered.
1878 * If it is, this should cause an error.
1880 hr = COM_GetRegisteredClassObject(apt, rclsid, dwClsContext, &foundObject);
1882 if (flags & REGCLS_MULTIPLEUSE) {
1883 if (dwClsContext & CLSCTX_LOCAL_SERVER)
1884 hr = CoLockObjectExternal(foundObject, TRUE, FALSE);
1885 IUnknown_Release(foundObject);
1888 IUnknown_Release(foundObject);
1889 ERR("object already registered for class %s\n", debugstr_guid(rclsid));
1890 return CO_E_OBJISREG;
1893 newClass = HeapAlloc(GetProcessHeap(), 0, sizeof(RegisteredClass));
1894 if ( newClass == NULL )
1895 return E_OUTOFMEMORY;
1897 newClass->classIdentifier = *rclsid;
1898 newClass->apartment_id = apt->oxid;
1899 newClass->runContext = dwClsContext;
1900 newClass->connectFlags = flags;
1901 newClass->pMarshaledData = NULL;
1902 newClass->RpcRegistration = NULL;
1905 * Use the address of the chain node as the cookie since we are sure it's
1906 * unique. FIXME: not on 64-bit platforms.
1908 newClass->dwCookie = (DWORD)newClass;
1911 * Since we're making a copy of the object pointer, we have to increase its
1914 newClass->classObject = pUnk;
1915 IUnknown_AddRef(newClass->classObject);
1917 EnterCriticalSection( &csRegisteredClassList );
1918 list_add_tail(&RegisteredClassList, &newClass->entry);
1919 LeaveCriticalSection( &csRegisteredClassList );
1921 *lpdwRegister = newClass->dwCookie;
1923 if (dwClsContext & CLSCTX_LOCAL_SERVER) {
1924 hr = CreateStreamOnHGlobal(0, TRUE, &newClass->pMarshaledData);
1926 FIXME("Failed to create stream on hglobal, %x\n", hr);
1929 hr = CoMarshalInterface(newClass->pMarshaledData, &IID_IClassFactory,
1930 newClass->classObject, MSHCTX_LOCAL, NULL,
1931 MSHLFLAGS_TABLESTRONG);
1933 FIXME("CoMarshalInterface failed, %x!\n",hr);
1937 hr = RPC_StartLocalServer(&newClass->classIdentifier,
1938 newClass->pMarshaledData,
1939 flags & (REGCLS_MULTIPLEUSE|REGCLS_MULTI_SEPARATE),
1940 &newClass->RpcRegistration);
1945 static void COM_RevokeRegisteredClassObject(RegisteredClass *curClass)
1947 list_remove(&curClass->entry);
1949 if (curClass->runContext & CLSCTX_LOCAL_SERVER)
1950 RPC_StopLocalServer(curClass->RpcRegistration);
1953 * Release the reference to the class object.
1955 IUnknown_Release(curClass->classObject);
1957 if (curClass->pMarshaledData)
1960 memset(&zero, 0, sizeof(zero));
1961 IStream_Seek(curClass->pMarshaledData, zero, STREAM_SEEK_SET, NULL);
1962 CoReleaseMarshalData(curClass->pMarshaledData);
1963 IStream_Release(curClass->pMarshaledData);
1966 HeapFree(GetProcessHeap(), 0, curClass);
1969 static void COM_RevokeAllClasses(const struct apartment *apt)
1971 RegisteredClass *curClass, *cursor;
1973 EnterCriticalSection( &csRegisteredClassList );
1975 LIST_FOR_EACH_ENTRY_SAFE(curClass, cursor, &RegisteredClassList, RegisteredClass, entry)
1977 if (curClass->apartment_id == apt->oxid)
1978 COM_RevokeRegisteredClassObject(curClass);
1981 LeaveCriticalSection( &csRegisteredClassList );
1984 /***********************************************************************
1985 * CoRevokeClassObject [OLE32.@]
1987 * Removes a class object from the class registry.
1990 * dwRegister [I] Cookie returned from CoRegisterClassObject().
1994 * Failure: HRESULT code.
1997 * Must be called from the same apartment that called CoRegisterClassObject(),
1998 * otherwise it will fail with RPC_E_WRONG_THREAD.
2001 * CoRegisterClassObject
2003 HRESULT WINAPI CoRevokeClassObject(
2006 HRESULT hr = E_INVALIDARG;
2007 RegisteredClass *curClass;
2010 TRACE("(%08x)\n",dwRegister);
2012 apt = COM_CurrentApt();
2015 ERR("COM was not initialized\n");
2016 return CO_E_NOTINITIALIZED;
2019 EnterCriticalSection( &csRegisteredClassList );
2021 LIST_FOR_EACH_ENTRY(curClass, &RegisteredClassList, RegisteredClass, entry)
2024 * Check if we have a match on the cookie.
2026 if (curClass->dwCookie == dwRegister)
2028 if (curClass->apartment_id == apt->oxid)
2030 COM_RevokeRegisteredClassObject(curClass);
2035 ERR("called from wrong apartment, should be called from %s\n",
2036 wine_dbgstr_longlong(curClass->apartment_id));
2037 hr = RPC_E_WRONG_THREAD;
2043 LeaveCriticalSection( &csRegisteredClassList );
2048 /***********************************************************************
2049 * COM_RegReadPath [internal]
2051 * Reads a registry value and expands it when necessary
2053 static DWORD COM_RegReadPath(HKEY hkeyroot, const WCHAR *keyname, const WCHAR *valuename, WCHAR * dst, DWORD dstlen)
2058 WCHAR src[MAX_PATH];
2059 DWORD dwLength = dstlen * sizeof(WCHAR);
2061 if((ret = RegOpenKeyExW(hkeyroot, keyname, 0, KEY_READ, &key)) == ERROR_SUCCESS) {
2062 if( (ret = RegQueryValueExW(key, NULL, NULL, &keytype, (LPBYTE)src, &dwLength)) == ERROR_SUCCESS ) {
2063 if (keytype == REG_EXPAND_SZ) {
2064 if (dstlen <= ExpandEnvironmentStringsW(src, dst, dstlen)) ret = ERROR_MORE_DATA;
2066 lstrcpynW(dst, src, dstlen);
2074 static void get_threading_model(HKEY key, LPWSTR value, DWORD len)
2076 static const WCHAR wszThreadingModel[] = {'T','h','r','e','a','d','i','n','g','M','o','d','e','l',0};
2079 DWORD dwLength = len * sizeof(WCHAR);
2081 ret = RegQueryValueExW(key, wszThreadingModel, NULL, &keytype, (LPBYTE)value, &dwLength);
2082 if ((ret != ERROR_SUCCESS) || (keytype != REG_SZ))
2086 static HRESULT get_inproc_class_object(APARTMENT *apt, HKEY hkeydll,
2087 REFCLSID rclsid, REFIID riid, void **ppv)
2089 static const WCHAR wszApartment[] = {'A','p','a','r','t','m','e','n','t',0};
2090 static const WCHAR wszFree[] = {'F','r','e','e',0};
2091 static const WCHAR wszBoth[] = {'B','o','t','h',0};
2092 WCHAR dllpath[MAX_PATH+1];
2093 WCHAR threading_model[10 /* strlenW(L"apartment")+1 */];
2095 get_threading_model(hkeydll, threading_model, ARRAYSIZE(threading_model));
2097 if (!strcmpiW(threading_model, wszApartment))
2099 if (apt->multi_threaded)
2100 return apartment_hostobject_in_hostapt(apt, FALSE, FALSE, hkeydll, rclsid, riid, ppv);
2103 else if (!strcmpiW(threading_model, wszFree))
2105 if (!apt->multi_threaded)
2106 return apartment_hostobject_in_hostapt(apt, TRUE, FALSE, hkeydll, rclsid, riid, ppv);
2108 /* everything except "Apartment", "Free" and "Both" */
2109 else if (strcmpiW(threading_model, wszBoth))
2111 /* everything else is main-threaded */
2112 if (threading_model[0])
2113 FIXME("unrecognised threading model %s for object %s, should be main-threaded?\n",
2114 debugstr_w(threading_model), debugstr_guid(rclsid));
2116 if (apt->multi_threaded || !apt->main)
2117 return apartment_hostobject_in_hostapt(apt, FALSE, TRUE, hkeydll, rclsid, riid, ppv);
2120 if (COM_RegReadPath(hkeydll, NULL, NULL, dllpath, ARRAYSIZE(dllpath)) != ERROR_SUCCESS)
2122 /* failure: CLSID is not found in registry */
2123 WARN("class %s not registered inproc\n", debugstr_guid(rclsid));
2124 return REGDB_E_CLASSNOTREG;
2127 return apartment_getclassobject(apt, dllpath,
2128 !strcmpiW(threading_model, wszApartment),
2132 /***********************************************************************
2133 * CoGetClassObject [OLE32.@]
2135 * Creates an object of the specified class.
2138 * rclsid [I] Class ID to create an instance of.
2139 * dwClsContext [I] Flags to restrict the location of the created instance.
2140 * pServerInfo [I] Optional. Details for connecting to a remote server.
2141 * iid [I] The ID of the interface of the instance to return.
2142 * ppv [O] On returns, contains a pointer to the specified interface of the object.
2146 * Failure: HRESULT code.
2149 * The dwClsContext parameter can be one or more of the following:
2150 *| CLSCTX_INPROC_SERVER - Use an in-process server, such as from a DLL.
2151 *| CLSCTX_INPROC_HANDLER - Use an in-process object which handles certain functions for an object running in another process.
2152 *| CLSCTX_LOCAL_SERVER - Connect to an object running in another process.
2153 *| CLSCTX_REMOTE_SERVER - Connect to an object running on another machine.
2156 * CoCreateInstance()
2158 HRESULT WINAPI CoGetClassObject(
2159 REFCLSID rclsid, DWORD dwClsContext, COSERVERINFO *pServerInfo,
2160 REFIID iid, LPVOID *ppv)
2162 LPUNKNOWN regClassObject;
2163 HRESULT hres = E_UNEXPECTED;
2166 TRACE("\n\tCLSID:\t%s,\n\tIID:\t%s\n", debugstr_guid(rclsid), debugstr_guid(iid));
2169 return E_INVALIDARG;
2173 apt = COM_CurrentApt();
2176 ERR("apartment not initialised\n");
2177 return CO_E_NOTINITIALIZED;
2181 FIXME("\tpServerInfo: name=%s\n",debugstr_w(pServerInfo->pwszName));
2182 FIXME("\t\tpAuthInfo=%p\n",pServerInfo->pAuthInfo);
2186 * First, try and see if we can't match the class ID with one of the
2187 * registered classes.
2189 if (S_OK == COM_GetRegisteredClassObject(apt, rclsid, dwClsContext,
2192 /* Get the required interface from the retrieved pointer. */
2193 hres = IUnknown_QueryInterface(regClassObject, iid, ppv);
2196 * Since QI got another reference on the pointer, we want to release the
2197 * one we already have. If QI was unsuccessful, this will release the object. This
2198 * is good since we are not returning it in the "out" parameter.
2200 IUnknown_Release(regClassObject);
2205 /* First try in-process server */
2206 if (CLSCTX_INPROC_SERVER & dwClsContext)
2208 static const WCHAR wszInprocServer32[] = {'I','n','p','r','o','c','S','e','r','v','e','r','3','2',0};
2211 if (IsEqualCLSID(rclsid, &CLSID_InProcFreeMarshaler))
2212 return FTMarshalCF_Create(iid, ppv);
2214 hres = COM_OpenKeyForCLSID(rclsid, wszInprocServer32, KEY_READ, &hkey);
2217 if (hres == REGDB_E_CLASSNOTREG)
2218 ERR("class %s not registered\n", debugstr_guid(rclsid));
2219 else if (hres == REGDB_E_KEYMISSING)
2221 WARN("class %s not registered as in-proc server\n", debugstr_guid(rclsid));
2222 hres = REGDB_E_CLASSNOTREG;
2226 if (SUCCEEDED(hres))
2228 hres = get_inproc_class_object(apt, hkey, rclsid, iid, ppv);
2232 /* return if we got a class, otherwise fall through to one of the
2234 if (SUCCEEDED(hres))
2238 /* Next try in-process handler */
2239 if (CLSCTX_INPROC_HANDLER & dwClsContext)
2241 static const WCHAR wszInprocHandler32[] = {'I','n','p','r','o','c','H','a','n','d','l','e','r','3','2',0};
2244 hres = COM_OpenKeyForCLSID(rclsid, wszInprocHandler32, KEY_READ, &hkey);
2247 if (hres == REGDB_E_CLASSNOTREG)
2248 ERR("class %s not registered\n", debugstr_guid(rclsid));
2249 else if (hres == REGDB_E_KEYMISSING)
2251 WARN("class %s not registered in-proc handler\n", debugstr_guid(rclsid));
2252 hres = REGDB_E_CLASSNOTREG;
2256 if (SUCCEEDED(hres))
2258 hres = get_inproc_class_object(apt, hkey, rclsid, iid, ppv);
2262 /* return if we got a class, otherwise fall through to one of the
2264 if (SUCCEEDED(hres))
2268 /* Next try out of process */
2269 if (CLSCTX_LOCAL_SERVER & dwClsContext)
2271 hres = RPC_GetLocalClassObject(rclsid,iid,ppv);
2272 if (SUCCEEDED(hres))
2276 /* Finally try remote: this requires networked DCOM (a lot of work) */
2277 if (CLSCTX_REMOTE_SERVER & dwClsContext)
2279 FIXME ("CLSCTX_REMOTE_SERVER not supported\n");
2280 hres = E_NOINTERFACE;
2284 ERR("no class object %s could be created for context 0x%x\n",
2285 debugstr_guid(rclsid), dwClsContext);
2289 /***********************************************************************
2290 * CoResumeClassObjects (OLE32.@)
2292 * Resumes all class objects registered with REGCLS_SUSPENDED.
2296 * Failure: HRESULT code.
2298 HRESULT WINAPI CoResumeClassObjects(void)
2304 /***********************************************************************
2305 * CoCreateInstance [OLE32.@]
2307 * Creates an instance of the specified class.
2310 * rclsid [I] Class ID to create an instance of.
2311 * pUnkOuter [I] Optional outer unknown to allow aggregation with another object.
2312 * dwClsContext [I] Flags to restrict the location of the created instance.
2313 * iid [I] The ID of the interface of the instance to return.
2314 * ppv [O] On returns, contains a pointer to the specified interface of the instance.
2318 * Failure: HRESULT code.
2321 * The dwClsContext parameter can be one or more of the following:
2322 *| CLSCTX_INPROC_SERVER - Use an in-process server, such as from a DLL.
2323 *| CLSCTX_INPROC_HANDLER - Use an in-process object which handles certain functions for an object running in another process.
2324 *| CLSCTX_LOCAL_SERVER - Connect to an object running in another process.
2325 *| CLSCTX_REMOTE_SERVER - Connect to an object running on another machine.
2327 * Aggregation is the concept of deferring the IUnknown of an object to another
2328 * object. This allows a separate object to behave as though it was part of
2329 * the object and to allow this the pUnkOuter parameter can be set. Note that
2330 * not all objects support having an outer of unknown.
2333 * CoGetClassObject()
2335 HRESULT WINAPI CoCreateInstance(
2337 LPUNKNOWN pUnkOuter,
2343 LPCLASSFACTORY lpclf = 0;
2345 TRACE("(rclsid=%s, pUnkOuter=%p, dwClsContext=%08x, riid=%s, ppv=%p)\n", debugstr_guid(rclsid),
2346 pUnkOuter, dwClsContext, debugstr_guid(iid), ppv);
2355 * Initialize the "out" parameter
2359 if (!COM_CurrentApt())
2361 ERR("apartment not initialised\n");
2362 return CO_E_NOTINITIALIZED;
2366 * The Standard Global Interface Table (GIT) object is a process-wide singleton.
2367 * Rather than create a class factory, we can just check for it here
2369 if (IsEqualIID(rclsid, &CLSID_StdGlobalInterfaceTable)) {
2370 if (StdGlobalInterfaceTableInstance == NULL)
2371 StdGlobalInterfaceTableInstance = StdGlobalInterfaceTable_Construct();
2372 hres = IGlobalInterfaceTable_QueryInterface( (IGlobalInterfaceTable*) StdGlobalInterfaceTableInstance, iid, ppv);
2373 if (hres) return hres;
2375 TRACE("Retrieved GIT (%p)\n", *ppv);
2380 * Get a class factory to construct the object we want.
2382 hres = CoGetClassObject(rclsid,
2392 * Create the object and don't forget to release the factory
2394 hres = IClassFactory_CreateInstance(lpclf, pUnkOuter, iid, ppv);
2395 IClassFactory_Release(lpclf);
2397 FIXME("no instance created for interface %s of class %s, hres is 0x%08x\n",
2398 debugstr_guid(iid), debugstr_guid(rclsid),hres);
2403 /***********************************************************************
2404 * CoCreateInstanceEx [OLE32.@]
2406 HRESULT WINAPI CoCreateInstanceEx(
2408 LPUNKNOWN pUnkOuter,
2410 COSERVERINFO* pServerInfo,
2414 IUnknown* pUnk = NULL;
2417 ULONG successCount = 0;
2422 if ( (cmq==0) || (pResults==NULL))
2423 return E_INVALIDARG;
2425 if (pServerInfo!=NULL)
2426 FIXME("() non-NULL pServerInfo not supported!\n");
2429 * Initialize all the "out" parameters.
2431 for (index = 0; index < cmq; index++)
2433 pResults[index].pItf = NULL;
2434 pResults[index].hr = E_NOINTERFACE;
2438 * Get the object and get its IUnknown pointer.
2440 hr = CoCreateInstance(rclsid,
2450 * Then, query for all the interfaces requested.
2452 for (index = 0; index < cmq; index++)
2454 pResults[index].hr = IUnknown_QueryInterface(pUnk,
2455 pResults[index].pIID,
2456 (VOID**)&(pResults[index].pItf));
2458 if (pResults[index].hr == S_OK)
2463 * Release our temporary unknown pointer.
2465 IUnknown_Release(pUnk);
2467 if (successCount == 0)
2468 return E_NOINTERFACE;
2470 if (successCount!=cmq)
2471 return CO_S_NOTALLINTERFACES;
2476 /***********************************************************************
2477 * CoLoadLibrary (OLE32.@)
2482 * lpszLibName [I] Path to library.
2483 * bAutoFree [I] Whether the library should automatically be freed.
2486 * Success: Handle to loaded library.
2490 * CoFreeLibrary, CoFreeAllLibraries, CoFreeUnusedLibraries
2492 HINSTANCE WINAPI CoLoadLibrary(LPOLESTR lpszLibName, BOOL bAutoFree)
2494 TRACE("(%s, %d)\n", debugstr_w(lpszLibName), bAutoFree);
2496 return LoadLibraryExW(lpszLibName, 0, LOAD_WITH_ALTERED_SEARCH_PATH);
2499 /***********************************************************************
2500 * CoFreeLibrary [OLE32.@]
2502 * Unloads a library from memory.
2505 * hLibrary [I] Handle to library to unload.
2511 * CoLoadLibrary, CoFreeAllLibraries, CoFreeUnusedLibraries
2513 void WINAPI CoFreeLibrary(HINSTANCE hLibrary)
2515 FreeLibrary(hLibrary);
2519 /***********************************************************************
2520 * CoFreeAllLibraries [OLE32.@]
2522 * Function for backwards compatibility only. Does nothing.
2528 * CoLoadLibrary, CoFreeLibrary, CoFreeUnusedLibraries
2530 void WINAPI CoFreeAllLibraries(void)
2535 /***********************************************************************
2536 * CoFreeUnusedLibrariesEx [OLE32.@]
2538 * Frees any previously unused libraries whose delay has expired and marks
2539 * currently unused libraries for unloading. Unused are identified as those that
2540 * return S_OK from their DllCanUnloadNow function.
2543 * dwUnloadDelay [I] Unload delay in milliseconds.
2544 * dwReserved [I] Reserved. Set to 0.
2550 * CoLoadLibrary, CoFreeAllLibraries, CoFreeLibrary
2552 void WINAPI CoFreeUnusedLibrariesEx(DWORD dwUnloadDelay, DWORD dwReserved)
2554 struct apartment *apt = COM_CurrentApt();
2557 ERR("apartment not initialised\n");
2561 apartment_freeunusedlibraries(apt, dwUnloadDelay);
2564 /***********************************************************************
2565 * CoFreeUnusedLibraries [OLE32.@]
2566 * CoFreeUnusedLibraries [COMPOBJ.17]
2568 * Frees any unused libraries. Unused are identified as those that return
2569 * S_OK from their DllCanUnloadNow function.
2575 * CoLoadLibrary, CoFreeAllLibraries, CoFreeLibrary
2577 void WINAPI CoFreeUnusedLibraries(void)
2579 CoFreeUnusedLibrariesEx(INFINITE, 0);
2582 /***********************************************************************
2583 * CoFileTimeNow [OLE32.@]
2584 * CoFileTimeNow [COMPOBJ.82]
2586 * Retrieves the current time in FILETIME format.
2589 * lpFileTime [O] The current time.
2594 HRESULT WINAPI CoFileTimeNow( FILETIME *lpFileTime )
2596 GetSystemTimeAsFileTime( lpFileTime );
2600 /******************************************************************************
2601 * CoLockObjectExternal [OLE32.@]
2603 * Increments or decrements the external reference count of a stub object.
2606 * pUnk [I] Stub object.
2607 * fLock [I] If TRUE then increments the external ref-count,
2608 * otherwise decrements.
2609 * fLastUnlockReleases [I] If TRUE then the last unlock has the effect of
2610 * calling CoDisconnectObject.
2614 * Failure: HRESULT code.
2617 * If fLock is TRUE and an object is passed in that doesn't have a stub
2618 * manager then a new stub manager is created for the object.
2620 HRESULT WINAPI CoLockObjectExternal(
2623 BOOL fLastUnlockReleases)
2625 struct stub_manager *stubmgr;
2626 struct apartment *apt;
2628 TRACE("pUnk=%p, fLock=%s, fLastUnlockReleases=%s\n",
2629 pUnk, fLock ? "TRUE" : "FALSE", fLastUnlockReleases ? "TRUE" : "FALSE");
2631 apt = COM_CurrentApt();
2632 if (!apt) return CO_E_NOTINITIALIZED;
2634 stubmgr = get_stub_manager_from_object(apt, pUnk);
2639 stub_manager_ext_addref(stubmgr, 1);
2641 stub_manager_ext_release(stubmgr, 1, fLastUnlockReleases);
2643 stub_manager_int_release(stubmgr);
2649 stubmgr = new_stub_manager(apt, pUnk);
2653 stub_manager_ext_addref(stubmgr, 1);
2654 stub_manager_int_release(stubmgr);
2661 WARN("stub object not found %p\n", pUnk);
2662 /* Note: native is pretty broken here because it just silently
2663 * fails, without returning an appropriate error code, making apps
2664 * think that the object was disconnected, when it actually wasn't */
2669 /***********************************************************************
2670 * CoInitializeWOW (OLE32.@)
2672 * WOW equivalent of CoInitialize?
2681 HRESULT WINAPI CoInitializeWOW(DWORD x,DWORD y)
2683 FIXME("(0x%08x,0x%08x),stub!\n",x,y);
2687 /***********************************************************************
2688 * CoGetState [OLE32.@]
2690 * Retrieves the thread state object previously stored by CoSetState().
2693 * ppv [I] Address where pointer to object will be stored.
2697 * Failure: E_OUTOFMEMORY.
2700 * Crashes on all invalid ppv addresses, including NULL.
2701 * If the function returns a non-NULL object then the caller must release its
2702 * reference on the object when the object is no longer required.
2707 HRESULT WINAPI CoGetState(IUnknown ** ppv)
2709 struct oletls *info = COM_CurrentInfo();
2710 if (!info) return E_OUTOFMEMORY;
2716 IUnknown_AddRef(info->state);
2718 TRACE("apt->state=%p\n", info->state);
2724 /***********************************************************************
2725 * CoSetState [OLE32.@]
2727 * Sets the thread state object.
2730 * pv [I] Pointer to state object to be stored.
2733 * The system keeps a reference on the object while the object stored.
2737 * Failure: E_OUTOFMEMORY.
2739 HRESULT WINAPI CoSetState(IUnknown * pv)
2741 struct oletls *info = COM_CurrentInfo();
2742 if (!info) return E_OUTOFMEMORY;
2744 if (pv) IUnknown_AddRef(pv);
2748 TRACE("-- release %p now\n", info->state);
2749 IUnknown_Release(info->state);
2758 /******************************************************************************
2759 * CoTreatAsClass [OLE32.@]
2761 * Sets the TreatAs value of a class.
2764 * clsidOld [I] Class to set TreatAs value on.
2765 * clsidNew [I] The class the clsidOld should be treated as.
2769 * Failure: HRESULT code.
2774 HRESULT WINAPI CoTreatAsClass(REFCLSID clsidOld, REFCLSID clsidNew)
2776 static const WCHAR wszAutoTreatAs[] = {'A','u','t','o','T','r','e','a','t','A','s',0};
2777 static const WCHAR wszTreatAs[] = {'T','r','e','a','t','A','s',0};
2779 WCHAR szClsidNew[CHARS_IN_GUID];
2781 WCHAR auto_treat_as[CHARS_IN_GUID];
2782 LONG auto_treat_as_size = sizeof(auto_treat_as);
2785 res = COM_OpenKeyForCLSID(clsidOld, NULL, KEY_READ | KEY_WRITE, &hkey);
2788 if (!memcmp( clsidOld, clsidNew, sizeof(*clsidOld) ))
2790 if (!RegQueryValueW(hkey, wszAutoTreatAs, auto_treat_as, &auto_treat_as_size) &&
2791 !CLSIDFromString(auto_treat_as, &id))
2793 if (RegSetValueW(hkey, wszTreatAs, REG_SZ, auto_treat_as, sizeof(auto_treat_as)))
2795 res = REGDB_E_WRITEREGDB;
2801 RegDeleteKeyW(hkey, wszTreatAs);
2805 else if (!StringFromGUID2(clsidNew, szClsidNew, ARRAYSIZE(szClsidNew)) &&
2806 !RegSetValueW(hkey, wszTreatAs, REG_SZ, szClsidNew, sizeof(szClsidNew)))
2808 res = REGDB_E_WRITEREGDB;
2813 if (hkey) RegCloseKey(hkey);
2817 /******************************************************************************
2818 * CoGetTreatAsClass [OLE32.@]
2820 * Gets the TreatAs value of a class.
2823 * clsidOld [I] Class to get the TreatAs value of.
2824 * clsidNew [I] The class the clsidOld should be treated as.
2828 * Failure: HRESULT code.
2833 HRESULT WINAPI CoGetTreatAsClass(REFCLSID clsidOld, LPCLSID clsidNew)
2835 static const WCHAR wszTreatAs[] = {'T','r','e','a','t','A','s',0};
2837 WCHAR szClsidNew[CHARS_IN_GUID];
2839 LONG len = sizeof(szClsidNew);
2841 FIXME("(%s,%p)\n", debugstr_guid(clsidOld), clsidNew);
2842 memcpy(clsidNew,clsidOld,sizeof(CLSID)); /* copy over old value */
2844 res = COM_OpenKeyForCLSID(clsidOld, wszTreatAs, KEY_READ, &hkey);
2847 if (RegQueryValueW(hkey, NULL, szClsidNew, &len))
2852 res = CLSIDFromString(szClsidNew,clsidNew);
2854 ERR("Failed CLSIDFromStringA(%s), hres 0x%08x\n", debugstr_w(szClsidNew), res);
2856 if (hkey) RegCloseKey(hkey);
2860 /******************************************************************************
2861 * CoGetCurrentProcess [OLE32.@]
2862 * CoGetCurrentProcess [COMPOBJ.34]
2864 * Gets the current process ID.
2867 * The current process ID.
2870 * Is DWORD really the correct return type for this function?
2872 DWORD WINAPI CoGetCurrentProcess(void)
2874 return GetCurrentProcessId();
2877 /******************************************************************************
2878 * CoRegisterMessageFilter [OLE32.@]
2880 * Registers a message filter.
2883 * lpMessageFilter [I] Pointer to interface.
2884 * lplpMessageFilter [O] Indirect pointer to prior instance if non-NULL.
2888 * Failure: HRESULT code.
2891 * Both lpMessageFilter and lplpMessageFilter are optional. Passing in a NULL
2892 * lpMessageFilter removes the message filter.
2894 * If lplpMessageFilter is not NULL the previous message filter will be
2895 * returned in the memory pointer to this parameter and the caller is
2896 * responsible for releasing the object.
2898 * The current thread be in an apartment otherwise the function will crash.
2900 HRESULT WINAPI CoRegisterMessageFilter(
2901 LPMESSAGEFILTER lpMessageFilter,
2902 LPMESSAGEFILTER *lplpMessageFilter)
2904 struct apartment *apt;
2905 IMessageFilter *lpOldMessageFilter;
2907 TRACE("(%p, %p)\n", lpMessageFilter, lplpMessageFilter);
2909 apt = COM_CurrentApt();
2911 /* can't set a message filter in a multi-threaded apartment */
2912 if (!apt || apt->multi_threaded)
2914 WARN("can't set message filter in MTA or uninitialized apt\n");
2915 return CO_E_NOT_SUPPORTED;
2918 if (lpMessageFilter)
2919 IMessageFilter_AddRef(lpMessageFilter);
2921 EnterCriticalSection(&apt->cs);
2923 lpOldMessageFilter = apt->filter;
2924 apt->filter = lpMessageFilter;
2926 LeaveCriticalSection(&apt->cs);
2928 if (lplpMessageFilter)
2929 *lplpMessageFilter = lpOldMessageFilter;
2930 else if (lpOldMessageFilter)
2931 IMessageFilter_Release(lpOldMessageFilter);
2936 /***********************************************************************
2937 * CoIsOle1Class [OLE32.@]
2939 * Determines whether the specified class an OLE v1 class.
2942 * clsid [I] Class to test.
2945 * TRUE if the class is an OLE v1 class, or FALSE otherwise.
2947 BOOL WINAPI CoIsOle1Class(REFCLSID clsid)
2949 FIXME("%s\n", debugstr_guid(clsid));
2953 /***********************************************************************
2954 * IsEqualGUID [OLE32.@]
2956 * Compares two Unique Identifiers.
2959 * rguid1 [I] The first GUID to compare.
2960 * rguid2 [I] The other GUID to compare.
2966 BOOL WINAPI IsEqualGUID(
2970 return !memcmp(rguid1,rguid2,sizeof(GUID));
2973 /***********************************************************************
2974 * CoInitializeSecurity [OLE32.@]
2976 HRESULT WINAPI CoInitializeSecurity(PSECURITY_DESCRIPTOR pSecDesc, LONG cAuthSvc,
2977 SOLE_AUTHENTICATION_SERVICE* asAuthSvc,
2978 void* pReserved1, DWORD dwAuthnLevel,
2979 DWORD dwImpLevel, void* pReserved2,
2980 DWORD dwCapabilities, void* pReserved3)
2982 FIXME("(%p,%d,%p,%p,%d,%d,%p,%d,%p) - stub!\n", pSecDesc, cAuthSvc,
2983 asAuthSvc, pReserved1, dwAuthnLevel, dwImpLevel, pReserved2,
2984 dwCapabilities, pReserved3);
2988 /***********************************************************************
2989 * CoSuspendClassObjects [OLE32.@]
2991 * Suspends all registered class objects to prevent further requests coming in
2992 * for those objects.
2996 * Failure: HRESULT code.
2998 HRESULT WINAPI CoSuspendClassObjects(void)
3004 /***********************************************************************
3005 * CoAddRefServerProcess [OLE32.@]
3007 * Helper function for incrementing the reference count of a local-server
3011 * New reference count.
3014 * CoReleaseServerProcess().
3016 ULONG WINAPI CoAddRefServerProcess(void)
3022 EnterCriticalSection(&csRegisteredClassList);
3023 refs = ++s_COMServerProcessReferences;
3024 LeaveCriticalSection(&csRegisteredClassList);
3026 TRACE("refs before: %d\n", refs - 1);
3031 /***********************************************************************
3032 * CoReleaseServerProcess [OLE32.@]
3034 * Helper function for decrementing the reference count of a local-server
3038 * New reference count.
3041 * When reference count reaches 0, this function suspends all registered
3042 * classes so no new connections are accepted.
3045 * CoAddRefServerProcess(), CoSuspendClassObjects().
3047 ULONG WINAPI CoReleaseServerProcess(void)
3053 EnterCriticalSection(&csRegisteredClassList);
3055 refs = --s_COMServerProcessReferences;
3056 /* FIXME: if (!refs) COM_SuspendClassObjects(); */
3058 LeaveCriticalSection(&csRegisteredClassList);
3060 TRACE("refs after: %d\n", refs);
3065 /***********************************************************************
3066 * CoIsHandlerConnected [OLE32.@]
3068 * Determines whether a proxy is connected to a remote stub.
3071 * pUnk [I] Pointer to object that may or may not be connected.
3074 * TRUE if pUnk is not a proxy or if pUnk is connected to a remote stub, or
3077 BOOL WINAPI CoIsHandlerConnected(IUnknown *pUnk)
3079 FIXME("%p\n", pUnk);
3084 /***********************************************************************
3085 * CoAllowSetForegroundWindow [OLE32.@]
3088 HRESULT WINAPI CoAllowSetForegroundWindow(IUnknown *pUnk, void *pvReserved)
3090 FIXME("(%p, %p): stub\n", pUnk, pvReserved);
3094 /***********************************************************************
3095 * CoQueryProxyBlanket [OLE32.@]
3097 * Retrieves the security settings being used by a proxy.
3100 * pProxy [I] Pointer to the proxy object.
3101 * pAuthnSvc [O] The type of authentication service.
3102 * pAuthzSvc [O] The type of authorization service.
3103 * ppServerPrincName [O] Optional. The server prinicple name.
3104 * pAuthnLevel [O] The authentication level.
3105 * pImpLevel [O] The impersonation level.
3106 * ppAuthInfo [O] Information specific to the authorization/authentication service.
3107 * pCapabilities [O] Flags affecting the security behaviour.
3111 * Failure: HRESULT code.
3114 * CoCopyProxy, CoSetProxyBlanket.
3116 HRESULT WINAPI CoQueryProxyBlanket(IUnknown *pProxy, DWORD *pAuthnSvc,
3117 DWORD *pAuthzSvc, OLECHAR **ppServerPrincName, DWORD *pAuthnLevel,
3118 DWORD *pImpLevel, void **ppAuthInfo, DWORD *pCapabilities)
3120 IClientSecurity *pCliSec;
3123 TRACE("%p\n", pProxy);
3125 hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
3128 hr = IClientSecurity_QueryBlanket(pCliSec, pProxy, pAuthnSvc,
3129 pAuthzSvc, ppServerPrincName,
3130 pAuthnLevel, pImpLevel, ppAuthInfo,
3132 IClientSecurity_Release(pCliSec);
3135 if (FAILED(hr)) ERR("-- failed with 0x%08x\n", hr);
3139 /***********************************************************************
3140 * CoSetProxyBlanket [OLE32.@]
3142 * Sets the security settings for a proxy.
3145 * pProxy [I] Pointer to the proxy object.
3146 * AuthnSvc [I] The type of authentication service.
3147 * AuthzSvc [I] The type of authorization service.
3148 * pServerPrincName [I] The server prinicple name.
3149 * AuthnLevel [I] The authentication level.
3150 * ImpLevel [I] The impersonation level.
3151 * pAuthInfo [I] Information specific to the authorization/authentication service.
3152 * Capabilities [I] Flags affecting the security behaviour.
3156 * Failure: HRESULT code.
3159 * CoQueryProxyBlanket, CoCopyProxy.
3161 HRESULT WINAPI CoSetProxyBlanket(IUnknown *pProxy, DWORD AuthnSvc,
3162 DWORD AuthzSvc, OLECHAR *pServerPrincName, DWORD AuthnLevel,
3163 DWORD ImpLevel, void *pAuthInfo, DWORD Capabilities)
3165 IClientSecurity *pCliSec;
3168 TRACE("%p\n", pProxy);
3170 hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
3173 hr = IClientSecurity_SetBlanket(pCliSec, pProxy, AuthnSvc,
3174 AuthzSvc, pServerPrincName,
3175 AuthnLevel, ImpLevel, pAuthInfo,
3177 IClientSecurity_Release(pCliSec);
3180 if (FAILED(hr)) ERR("-- failed with 0x%08x\n", hr);
3184 /***********************************************************************
3185 * CoCopyProxy [OLE32.@]
3190 * pProxy [I] Pointer to the proxy object.
3191 * ppCopy [O] Copy of the proxy.
3195 * Failure: HRESULT code.
3198 * CoQueryProxyBlanket, CoSetProxyBlanket.
3200 HRESULT WINAPI CoCopyProxy(IUnknown *pProxy, IUnknown **ppCopy)
3202 IClientSecurity *pCliSec;
3205 TRACE("%p\n", pProxy);
3207 hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
3210 hr = IClientSecurity_CopyProxy(pCliSec, pProxy, ppCopy);
3211 IClientSecurity_Release(pCliSec);
3214 if (FAILED(hr)) ERR("-- failed with 0x%08x\n", hr);
3219 /***********************************************************************
3220 * CoGetCallContext [OLE32.@]
3222 * Gets the context of the currently executing server call in the current
3226 * riid [I] Context interface to return.
3227 * ppv [O] Pointer to memory that will receive the context on return.
3231 * Failure: HRESULT code.
3233 HRESULT WINAPI CoGetCallContext(REFIID riid, void **ppv)
3235 FIXME("(%s, %p): stub\n", debugstr_guid(riid), ppv);
3238 return E_NOINTERFACE;
3241 /***********************************************************************
3242 * CoQueryClientBlanket [OLE32.@]
3244 * Retrieves the authentication information about the client of the currently
3245 * executing server call in the current thread.
3248 * pAuthnSvc [O] Optional. The type of authentication service.
3249 * pAuthzSvc [O] Optional. The type of authorization service.
3250 * pServerPrincName [O] Optional. The server prinicple name.
3251 * pAuthnLevel [O] Optional. The authentication level.
3252 * pImpLevel [O] Optional. The impersonation level.
3253 * pPrivs [O] Optional. Information about the privileges of the client.
3254 * pCapabilities [IO] Optional. Flags affecting the security behaviour.
3258 * Failure: HRESULT code.
3261 * CoImpersonateClient, CoRevertToSelf, CoGetCallContext.
3263 HRESULT WINAPI CoQueryClientBlanket(
3266 OLECHAR **pServerPrincName,
3269 RPC_AUTHZ_HANDLE *pPrivs,
3270 DWORD *pCapabilities)
3272 IServerSecurity *pSrvSec;
3275 TRACE("(%p, %p, %p, %p, %p, %p, %p)\n",
3276 pAuthnSvc, pAuthzSvc, pServerPrincName, pAuthnLevel, pImpLevel,
3277 pPrivs, pCapabilities);
3279 hr = CoGetCallContext(&IID_IServerSecurity, (void **)&pSrvSec);
3282 hr = IServerSecurity_QueryBlanket(
3283 pSrvSec, pAuthnSvc, pAuthzSvc, pServerPrincName, pAuthnLevel,
3284 pImpLevel, pPrivs, pCapabilities);
3285 IServerSecurity_Release(pSrvSec);
3291 /***********************************************************************
3292 * CoImpersonateClient [OLE32.@]
3294 * Impersonates the client of the currently executing server call in the
3302 * Failure: HRESULT code.
3305 * If this function fails then the current thread will not be impersonating
3306 * the client and all actions will take place on behalf of the server.
3307 * Therefore, it is important to check the return value from this function.
3310 * CoRevertToSelf, CoQueryClientBlanket, CoGetCallContext.
3312 HRESULT WINAPI CoImpersonateClient(void)
3314 IServerSecurity *pSrvSec;
3319 hr = CoGetCallContext(&IID_IServerSecurity, (void **)&pSrvSec);
3322 hr = IServerSecurity_ImpersonateClient(pSrvSec);
3323 IServerSecurity_Release(pSrvSec);
3329 /***********************************************************************
3330 * CoRevertToSelf [OLE32.@]
3332 * Ends the impersonation of the client of the currently executing server
3333 * call in the current thread.
3340 * Failure: HRESULT code.
3343 * CoImpersonateClient, CoQueryClientBlanket, CoGetCallContext.
3345 HRESULT WINAPI CoRevertToSelf(void)
3347 IServerSecurity *pSrvSec;
3352 hr = CoGetCallContext(&IID_IServerSecurity, (void **)&pSrvSec);
3355 hr = IServerSecurity_RevertToSelf(pSrvSec);
3356 IServerSecurity_Release(pSrvSec);
3362 static BOOL COM_PeekMessage(struct apartment *apt, MSG *msg)
3364 /* first try to retrieve messages for incoming COM calls to the apartment window */
3365 return PeekMessageW(msg, apt->win, WM_USER, WM_APP - 1, PM_REMOVE|PM_NOYIELD) ||
3366 /* next retrieve other messages necessary for the app to remain responsive */
3367 PeekMessageW(msg, NULL, 0, 0, PM_QS_PAINT|PM_QS_POSTMESSAGE|PM_REMOVE|PM_NOYIELD);
3370 /***********************************************************************
3371 * CoWaitForMultipleHandles [OLE32.@]
3373 * Waits for one or more handles to become signaled.
3376 * dwFlags [I] Flags. See notes.
3377 * dwTimeout [I] Timeout in milliseconds.
3378 * cHandles [I] Number of handles pointed to by pHandles.
3379 * pHandles [I] Handles to wait for.
3380 * lpdwindex [O] Index of handle that was signaled.
3384 * Failure: RPC_S_CALLPENDING on timeout.
3388 * The dwFlags parameter can be zero or more of the following:
3389 *| COWAIT_WAITALL - Wait for all of the handles to become signaled.
3390 *| COWAIT_ALERTABLE - Allows a queued APC to run during the wait.
3393 * MsgWaitForMultipleObjects, WaitForMultipleObjects.
3395 HRESULT WINAPI CoWaitForMultipleHandles(DWORD dwFlags, DWORD dwTimeout,
3396 ULONG cHandles, LPHANDLE pHandles, LPDWORD lpdwindex)
3399 DWORD start_time = GetTickCount();
3400 APARTMENT *apt = COM_CurrentApt();
3401 BOOL message_loop = apt && !apt->multi_threaded;
3403 TRACE("(0x%08x, 0x%08x, %d, %p, %p)\n", dwFlags, dwTimeout, cHandles,
3404 pHandles, lpdwindex);
3408 DWORD now = GetTickCount();
3411 if ((dwTimeout != INFINITE) && (start_time + dwTimeout >= now))
3413 hr = RPC_S_CALLPENDING;
3419 DWORD wait_flags = (dwFlags & COWAIT_WAITALL) ? MWMO_WAITALL : 0 |
3420 (dwFlags & COWAIT_ALERTABLE ) ? MWMO_ALERTABLE : 0;
3422 TRACE("waiting for rpc completion or window message\n");
3424 res = MsgWaitForMultipleObjectsEx(cHandles, pHandles,
3425 (dwTimeout == INFINITE) ? INFINITE : start_time + dwTimeout - now,
3426 QS_ALLINPUT, wait_flags);
3428 if (res == WAIT_OBJECT_0 + cHandles) /* messages available */
3432 /* call message filter */
3434 if (COM_CurrentApt()->filter)
3436 PENDINGTYPE pendingtype =
3437 COM_CurrentInfo()->pending_call_count_server ?
3438 PENDINGTYPE_NESTED : PENDINGTYPE_TOPLEVEL;
3439 DWORD be_handled = IMessageFilter_MessagePending(
3440 COM_CurrentApt()->filter, 0 /* FIXME */,
3441 now - start_time, pendingtype);
3442 TRACE("IMessageFilter_MessagePending returned %d\n", be_handled);
3445 case PENDINGMSG_CANCELCALL:
3446 WARN("call canceled\n");
3447 hr = RPC_E_CALL_CANCELED;
3449 case PENDINGMSG_WAITNOPROCESS:
3450 case PENDINGMSG_WAITDEFPROCESS:
3452 /* FIXME: MSDN is very vague about the difference
3453 * between WAITNOPROCESS and WAITDEFPROCESS - there
3454 * appears to be none, so it is possibly a left-over
3455 * from the 16-bit world. */
3460 /* note: using "if" here instead of "while" might seem less
3461 * efficient, but only if we are optimising for quick delivery
3462 * of pending messages, rather than quick completion of the
3464 if (COM_PeekMessage(apt, &msg))
3466 TRACE("received message whilst waiting for RPC: 0x%04x\n", msg.message);
3467 TranslateMessage(&msg);
3468 DispatchMessageW(&msg);
3469 if (msg.message == WM_QUIT)
3471 TRACE("resending WM_QUIT to outer message loop\n");
3472 PostQuitMessage(msg.wParam);
3473 /* no longer need to process messages */
3474 message_loop = FALSE;
3482 TRACE("waiting for rpc completion\n");
3484 res = WaitForMultipleObjectsEx(cHandles, pHandles,
3485 (dwFlags & COWAIT_WAITALL) ? TRUE : FALSE,
3486 (dwTimeout == INFINITE) ? INFINITE : start_time + dwTimeout - now,
3487 (dwFlags & COWAIT_ALERTABLE) ? TRUE : FALSE);
3490 if ((res >= WAIT_OBJECT_0) && (res < WAIT_OBJECT_0 + cHandles))
3492 /* handle signaled, store index */
3493 *lpdwindex = (res - WAIT_OBJECT_0);
3496 else if (res == WAIT_TIMEOUT)
3498 hr = RPC_S_CALLPENDING;
3503 ERR("Unexpected wait termination: %d, %d\n", res, GetLastError());
3508 TRACE("-- 0x%08x\n", hr);
3513 /***********************************************************************
3514 * CoGetObject [OLE32.@]
3516 * Gets the object named by coverting the name to a moniker and binding to it.
3519 * pszName [I] String representing the object.
3520 * pBindOptions [I] Parameters affecting the binding to the named object.
3521 * riid [I] Interface to bind to on the objecct.
3522 * ppv [O] On output, the interface riid of the object represented
3527 * Failure: HRESULT code.
3530 * MkParseDisplayName.
3532 HRESULT WINAPI CoGetObject(LPCWSTR pszName, BIND_OPTS *pBindOptions,
3533 REFIID riid, void **ppv)
3540 hr = CreateBindCtx(0, &pbc);
3544 hr = IBindCtx_SetBindOptions(pbc, pBindOptions);
3551 hr = MkParseDisplayName(pbc, pszName, &chEaten, &pmk);
3554 hr = IMoniker_BindToObject(pmk, pbc, NULL, riid, ppv);
3555 IMoniker_Release(pmk);
3559 IBindCtx_Release(pbc);
3564 /***********************************************************************
3565 * CoRegisterChannelHook [OLE32.@]
3567 * Registers a process-wide hook that is called during ORPC calls.
3570 * guidExtension [I] GUID of the channel hook to register.
3571 * pChannelHook [I] Channel hook object to register.
3575 * Failure: HRESULT code.
3577 HRESULT WINAPI CoRegisterChannelHook(REFGUID guidExtension, IChannelHook *pChannelHook)
3579 TRACE("(%s, %p)\n", debugstr_guid(guidExtension), pChannelHook);
3581 return RPC_RegisterChannelHook(guidExtension, pChannelHook);
3584 typedef struct Context
3586 const IComThreadingInfoVtbl *lpVtbl;
3591 static HRESULT WINAPI Context_QueryInterface(IComThreadingInfo *iface, REFIID riid, LPVOID *ppv)
3595 if (IsEqualIID(riid, &IID_IComThreadingInfo) ||
3596 IsEqualIID(riid, &IID_IUnknown))
3599 IUnknown_AddRef(iface);
3603 FIXME("interface not implemented %s\n", debugstr_guid(riid));
3604 return E_NOINTERFACE;
3607 static ULONG WINAPI Context_AddRef(IComThreadingInfo *iface)
3609 Context *This = (Context *)iface;
3610 return InterlockedIncrement(&This->refs);
3613 static ULONG WINAPI Context_Release(IComThreadingInfo *iface)
3615 Context *This = (Context *)iface;
3616 ULONG refs = InterlockedDecrement(&This->refs);
3618 HeapFree(GetProcessHeap(), 0, This);
3622 static HRESULT WINAPI Context_GetCurrentApartmentType(IComThreadingInfo *iface, APTTYPE *apttype)
3624 Context *This = (Context *)iface;
3626 TRACE("(%p)\n", apttype);
3628 *apttype = This->apttype;
3632 static HRESULT WINAPI Context_GetCurrentThreadType(IComThreadingInfo *iface, THDTYPE *thdtype)
3634 Context *This = (Context *)iface;
3636 TRACE("(%p)\n", thdtype);
3638 switch (This->apttype)
3641 case APTTYPE_MAINSTA:
3642 *thdtype = THDTYPE_PROCESSMESSAGES;
3645 *thdtype = THDTYPE_BLOCKMESSAGES;
3651 static HRESULT WINAPI Context_GetCurrentLogicalThreadId(IComThreadingInfo *iface, GUID *logical_thread_id)
3653 FIXME("(%p): stub\n", logical_thread_id);
3657 static HRESULT WINAPI Context_SetCurrentLogicalThreadId(IComThreadingInfo *iface, REFGUID logical_thread_id)
3659 FIXME("(%s): stub\n", debugstr_guid(logical_thread_id));
3663 static const IComThreadingInfoVtbl Context_Threading_Vtbl =
3665 Context_QueryInterface,
3668 Context_GetCurrentApartmentType,
3669 Context_GetCurrentThreadType,
3670 Context_GetCurrentLogicalThreadId,
3671 Context_SetCurrentLogicalThreadId
3674 /***********************************************************************
3675 * CoGetObjectContext [OLE32.@]
3677 * Retrieves an object associated with the current context (i.e. apartment).
3680 * riid [I] ID of the interface of the object to retrieve.
3681 * ppv [O] Address where object will be stored on return.
3685 * Failure: HRESULT code.
3687 HRESULT WINAPI CoGetObjectContext(REFIID riid, void **ppv)
3689 APARTMENT *apt = COM_CurrentApt();
3693 TRACE("(%s, %p)\n", debugstr_guid(riid), ppv);
3698 ERR("apartment not initialised\n");
3699 return CO_E_NOTINITIALIZED;
3702 context = HeapAlloc(GetProcessHeap(), 0, sizeof(*context));
3704 return E_OUTOFMEMORY;
3706 context->lpVtbl = &Context_Threading_Vtbl;
3708 if (apt->multi_threaded)
3709 context->apttype = APTTYPE_MTA;
3711 context->apttype = APTTYPE_MAINSTA;
3713 context->apttype = APTTYPE_STA;
3715 hr = IUnknown_QueryInterface((IUnknown *)&context->lpVtbl, riid, ppv);
3716 IUnknown_Release((IUnknown *)&context->lpVtbl);
3721 /***********************************************************************
3724 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID fImpLoad)
3726 TRACE("%p 0x%x %p\n", hinstDLL, fdwReason, fImpLoad);
3729 case DLL_PROCESS_ATTACH:
3730 OLE32_hInstance = hinstDLL;
3731 COMPOBJ_InitProcess();
3732 if (TRACE_ON(ole)) CoRegisterMallocSpy((LPVOID)-1);
3735 case DLL_PROCESS_DETACH:
3736 if (TRACE_ON(ole)) CoRevokeMallocSpy();
3737 OLEDD_UnInitialize();
3738 COMPOBJ_UninitProcess();
3739 RPC_UnregisterAllChannelHooks();
3740 COMPOBJ_DllList_Free();
3741 OLE32_hInstance = 0;
3744 case DLL_THREAD_DETACH:
3751 /* NOTE: DllRegisterServer and DllUnregisterServer are in regsvr.c */