Release 0.9.39.
[wine/gsoc-2012-control.git] / dlls / ole32 / compobj.c
blob832770ee1fd12e17398acfd8106edd26ca961dac
1 /*
2 * COMPOBJ library
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
26 * Note
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
38 * native DCOM
42 #include "config.h"
44 #include <stdarg.h>
45 #include <stdio.h>
46 #include <string.h>
47 #include <assert.h>
49 #define COBJMACROS
50 #define NONAMELESSUNION
51 #define NONAMELESSSTRUCT
53 #include "windef.h"
54 #include "winbase.h"
55 #include "winerror.h"
56 #include "winreg.h"
57 #include "winuser.h"
58 #include "objbase.h"
59 #include "ole2.h"
60 #include "ole2ver.h"
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(struct apartment *apt, REFCLSID rclsid, DWORD dwClsContext, LPUNKNOWN* ppUnk);
80 static void COM_RevokeAllClasses(struct apartment *apt);
81 static HRESULT get_inproc_class_object(APARTMENT *apt, HKEY hkeydll, REFCLSID rclsid, REFIID riid, void **ppv);
83 static APARTMENT *MTA; /* protected by csApartment */
84 static APARTMENT *MainApartment; /* the first STA apartment */
85 static struct list apts = LIST_INIT( apts ); /* protected by csApartment */
87 static CRITICAL_SECTION csApartment;
88 static CRITICAL_SECTION_DEBUG critsect_debug =
90 0, 0, &csApartment,
91 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
92 0, 0, { (DWORD_PTR)(__FILE__ ": csApartment") }
94 static CRITICAL_SECTION csApartment = { &critsect_debug, -1, 0, 0, 0, 0 };
96 struct registered_psclsid
98 struct list entry;
99 IID iid;
100 CLSID clsid;
104 * This lock count counts the number of times CoInitialize is called. It is
105 * decreased every time CoUninitialize is called. When it hits 0, the COM
106 * libraries are freed
108 static LONG s_COMLockCount = 0;
109 /* Reference count used by CoAddRefServerProcess/CoReleaseServerProcess */
110 static LONG s_COMServerProcessReferences = 0;
113 * This linked list contains the list of registered class objects. These
114 * are mostly used to register the factories for out-of-proc servers of OLE
115 * objects.
117 * TODO: Make this data structure aware of inter-process communication. This
118 * means that parts of this will be exported to the Wine Server.
120 typedef struct tagRegisteredClass
122 struct list entry;
123 CLSID classIdentifier;
124 OXID apartment_id;
125 LPUNKNOWN classObject;
126 DWORD runContext;
127 DWORD connectFlags;
128 DWORD dwCookie;
129 LPSTREAM pMarshaledData; /* FIXME: only really need to store OXID and IPID */
130 void *RpcRegistration;
131 } RegisteredClass;
133 static struct list RegisteredClassList = LIST_INIT(RegisteredClassList);
135 static CRITICAL_SECTION csRegisteredClassList;
136 static CRITICAL_SECTION_DEBUG class_cs_debug =
138 0, 0, &csRegisteredClassList,
139 { &class_cs_debug.ProcessLocksList, &class_cs_debug.ProcessLocksList },
140 0, 0, { (DWORD_PTR)(__FILE__ ": csRegisteredClassList") }
142 static CRITICAL_SECTION csRegisteredClassList = { &class_cs_debug, -1, 0, 0, 0, 0 };
144 /*****************************************************************************
145 * This section contains OpenDllList definitions
147 * The OpenDllList contains only handles of dll loaded by CoGetClassObject or
148 * other functions that do LoadLibrary _without_ giving back a HMODULE.
149 * Without this list these handles would never be freed.
151 * FIXME: a DLL that says OK when asked for unloading is unloaded in the
152 * next unload-call but not before 600 sec.
155 typedef HRESULT (CALLBACK *DllGetClassObjectFunc)(REFCLSID clsid, REFIID iid, LPVOID *ppv);
156 typedef HRESULT (WINAPI *DllCanUnloadNowFunc)(void);
158 typedef struct tagOpenDll
160 LONG refs;
161 LPWSTR library_name;
162 HANDLE library;
163 DllGetClassObjectFunc DllGetClassObject;
164 DllCanUnloadNowFunc DllCanUnloadNow;
165 struct list entry;
166 } OpenDll;
168 static struct list openDllList = LIST_INIT(openDllList);
170 static CRITICAL_SECTION csOpenDllList;
171 static CRITICAL_SECTION_DEBUG dll_cs_debug =
173 0, 0, &csOpenDllList,
174 { &dll_cs_debug.ProcessLocksList, &dll_cs_debug.ProcessLocksList },
175 0, 0, { (DWORD_PTR)(__FILE__ ": csOpenDllList") }
177 static CRITICAL_SECTION csOpenDllList = { &dll_cs_debug, -1, 0, 0, 0, 0 };
179 struct apartment_loaded_dll
181 struct list entry;
182 OpenDll *dll;
185 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',' ',
186 '0','x','#','#','#','#','#','#','#','#',' ',0};
187 static LRESULT CALLBACK apartment_wndproc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
188 static HRESULT apartment_getclassobject(struct apartment *apt, LPCWSTR dllpath,
189 REFCLSID rclsid, REFIID riid, void **ppv);
190 static void apartment_freeunusedlibraries(struct apartment *apt);
192 static HRESULT COMPOBJ_DllList_Add(LPCWSTR library_name, OpenDll **ret);
193 static OpenDll *COMPOBJ_DllList_Get(LPCWSTR library_name);
194 static void COMPOBJ_DllList_ReleaseRef(OpenDll *entry, BOOL free_entry);
196 static DWORD COM_RegReadPath(HKEY hkeyroot, const WCHAR *keyname, const WCHAR *valuename, WCHAR * dst, DWORD dstlen);
198 static void COMPOBJ_InitProcess( void )
200 WNDCLASSW wclass;
202 /* Dispatching to the correct thread in an apartment is done through
203 * window messages rather than RPC transports. When an interface is
204 * marshalled into another apartment in the same process, a window of the
205 * following class is created. The *caller* of CoMarshalInterface (ie the
206 * application) is responsible for pumping the message loop in that thread.
207 * The WM_USER messages which point to the RPCs are then dispatched to
208 * COM_AptWndProc by the user's code from the apartment in which the interface
209 * was unmarshalled.
211 memset(&wclass, 0, sizeof(wclass));
212 wclass.lpfnWndProc = apartment_wndproc;
213 wclass.hInstance = OLE32_hInstance;
214 wclass.lpszClassName = wszAptWinClass;
215 RegisterClassW(&wclass);
218 static void COMPOBJ_UninitProcess( void )
220 UnregisterClassW(wszAptWinClass, OLE32_hInstance);
223 static void COM_TlsDestroy(void)
225 struct oletls *info = NtCurrentTeb()->ReservedForOle;
226 if (info)
228 if (info->apt) apartment_release(info->apt);
229 if (info->errorinfo) IErrorInfo_Release(info->errorinfo);
230 if (info->state) IUnknown_Release(info->state);
231 HeapFree(GetProcessHeap(), 0, info);
232 NtCurrentTeb()->ReservedForOle = NULL;
236 /******************************************************************************
237 * Manage apartments.
240 /* allocates memory and fills in the necessary fields for a new apartment
241 * object. must be called inside apartment cs */
242 static APARTMENT *apartment_construct(DWORD model)
244 APARTMENT *apt;
246 TRACE("creating new apartment, model=%d\n", model);
248 apt = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*apt));
249 apt->tid = GetCurrentThreadId();
251 list_init(&apt->proxies);
252 list_init(&apt->stubmgrs);
253 list_init(&apt->psclsids);
254 list_init(&apt->loaded_dlls);
255 apt->ipidc = 0;
256 apt->refs = 1;
257 apt->remunk_exported = FALSE;
258 apt->oidc = 1;
259 InitializeCriticalSection(&apt->cs);
260 DEBUG_SET_CRITSEC_NAME(&apt->cs, "apartment");
262 apt->multi_threaded = !(model & COINIT_APARTMENTTHREADED);
264 if (apt->multi_threaded)
266 /* FIXME: should be randomly generated by in an RPC call to rpcss */
267 apt->oxid = ((OXID)GetCurrentProcessId() << 32) | 0xcafe;
269 else
271 /* FIXME: should be randomly generated by in an RPC call to rpcss */
272 apt->oxid = ((OXID)GetCurrentProcessId() << 32) | GetCurrentThreadId();
275 TRACE("Created apartment on OXID %s\n", wine_dbgstr_longlong(apt->oxid));
277 list_add_head(&apts, &apt->entry);
279 return apt;
282 /* gets and existing apartment if one exists or otherwise creates an apartment
283 * structure which stores OLE apartment-local information and stores a pointer
284 * to it in the thread-local storage */
285 static APARTMENT *apartment_get_or_create(DWORD model)
287 APARTMENT *apt = COM_CurrentApt();
289 if (!apt)
291 if (model & COINIT_APARTMENTTHREADED)
293 EnterCriticalSection(&csApartment);
295 apt = apartment_construct(model);
296 if (!MainApartment)
298 MainApartment = apt;
299 apt->main = TRUE;
300 TRACE("Created main-threaded apartment with OXID %s\n", wine_dbgstr_longlong(apt->oxid));
303 LeaveCriticalSection(&csApartment);
305 else
307 EnterCriticalSection(&csApartment);
309 /* The multi-threaded apartment (MTA) contains zero or more threads interacting
310 * with free threaded (ie thread safe) COM objects. There is only ever one MTA
311 * in a process */
312 if (MTA)
314 TRACE("entering the multithreaded apartment %s\n", wine_dbgstr_longlong(MTA->oxid));
315 apartment_addref(MTA);
317 else
318 MTA = apartment_construct(model);
320 apt = MTA;
322 LeaveCriticalSection(&csApartment);
324 COM_CurrentInfo()->apt = apt;
327 return apt;
330 static inline BOOL apartment_is_model(APARTMENT *apt, DWORD model)
332 return (apt->multi_threaded == !(model & COINIT_APARTMENTTHREADED));
335 DWORD apartment_addref(struct apartment *apt)
337 DWORD refs = InterlockedIncrement(&apt->refs);
338 TRACE("%s: before = %d\n", wine_dbgstr_longlong(apt->oxid), refs - 1);
339 return refs;
342 DWORD apartment_release(struct apartment *apt)
344 DWORD ret;
346 EnterCriticalSection(&csApartment);
348 ret = InterlockedDecrement(&apt->refs);
349 TRACE("%s: after = %d\n", wine_dbgstr_longlong(apt->oxid), ret);
350 /* destruction stuff that needs to happen under csApartment CS */
351 if (ret == 0)
353 if (apt == MTA) MTA = NULL;
354 else if (apt == MainApartment) MainApartment = NULL;
355 list_remove(&apt->entry);
358 LeaveCriticalSection(&csApartment);
360 if (ret == 0)
362 struct list *cursor, *cursor2;
364 TRACE("destroying apartment %p, oxid %s\n", apt, wine_dbgstr_longlong(apt->oxid));
366 /* Release the references to the registered class objects */
367 COM_RevokeAllClasses(apt);
369 /* no locking is needed for this apartment, because no other thread
370 * can access it at this point */
372 apartment_disconnectproxies(apt);
374 if (apt->win) DestroyWindow(apt->win);
375 if (apt->host_apt_tid) PostThreadMessageW(apt->host_apt_tid, WM_QUIT, 0, 0);
377 LIST_FOR_EACH_SAFE(cursor, cursor2, &apt->stubmgrs)
379 struct stub_manager *stubmgr = LIST_ENTRY(cursor, struct stub_manager, entry);
380 /* release the implicit reference given by the fact that the
381 * stub has external references (it must do since it is in the
382 * stub manager list in the apartment and all non-apartment users
383 * must have a ref on the apartment and so it cannot be destroyed).
385 stub_manager_int_release(stubmgr);
388 LIST_FOR_EACH_SAFE(cursor, cursor2, &apt->psclsids)
390 struct registered_psclsid *registered_psclsid =
391 LIST_ENTRY(cursor, struct registered_psclsid, entry);
393 list_remove(&registered_psclsid->entry);
394 HeapFree(GetProcessHeap(), 0, registered_psclsid);
397 /* if this assert fires, then another thread took a reference to a
398 * stub manager without taking a reference to the containing
399 * apartment, which it must do. */
400 assert(list_empty(&apt->stubmgrs));
402 if (apt->filter) IUnknown_Release(apt->filter);
404 /* free as many unused libraries as possible... */
405 apartment_freeunusedlibraries(apt);
407 /* ... and free the memory for the apartment loaded dll entry and
408 * release the dll list reference without freeing the library for the
409 * rest */
410 while ((cursor = list_head(&apt->loaded_dlls)))
412 struct apartment_loaded_dll *apartment_loaded_dll = LIST_ENTRY(cursor, struct apartment_loaded_dll, entry);
413 COMPOBJ_DllList_ReleaseRef(apartment_loaded_dll->dll, FALSE);
414 list_remove(cursor);
415 HeapFree(GetProcessHeap(), 0, apartment_loaded_dll);
418 DEBUG_CLEAR_CRITSEC_NAME(&apt->cs);
419 DeleteCriticalSection(&apt->cs);
421 HeapFree(GetProcessHeap(), 0, apt);
424 return ret;
427 /* The given OXID must be local to this process:
429 * The ref parameter is here mostly to ensure people remember that
430 * they get one, you should normally take a ref for thread safety.
432 APARTMENT *apartment_findfromoxid(OXID oxid, BOOL ref)
434 APARTMENT *result = NULL;
435 struct list *cursor;
437 EnterCriticalSection(&csApartment);
438 LIST_FOR_EACH( cursor, &apts )
440 struct apartment *apt = LIST_ENTRY( cursor, struct apartment, entry );
441 if (apt->oxid == oxid)
443 result = apt;
444 if (ref) apartment_addref(result);
445 break;
448 LeaveCriticalSection(&csApartment);
450 return result;
453 /* gets the apartment which has a given creator thread ID. The caller must
454 * release the reference from the apartment as soon as the apartment pointer
455 * is no longer required. */
456 APARTMENT *apartment_findfromtid(DWORD tid)
458 APARTMENT *result = NULL;
459 struct list *cursor;
461 EnterCriticalSection(&csApartment);
462 LIST_FOR_EACH( cursor, &apts )
464 struct apartment *apt = LIST_ENTRY( cursor, struct apartment, entry );
465 if (apt->tid == tid)
467 result = apt;
468 apartment_addref(result);
469 break;
472 LeaveCriticalSection(&csApartment);
474 return result;
477 /* gets the main apartment if it exists. The caller must
478 * release the reference from the apartment as soon as the apartment pointer
479 * is no longer required. */
480 static APARTMENT *apartment_findmain(void)
482 APARTMENT *result;
484 EnterCriticalSection(&csApartment);
486 result = MainApartment;
487 if (result) apartment_addref(result);
489 LeaveCriticalSection(&csApartment);
491 return result;
494 struct host_object_params
496 HKEY hkeydll;
497 CLSID clsid; /* clsid of object to marshal */
498 IID iid; /* interface to marshal */
499 HANDLE event; /* event signalling when ready for multi-threaded case */
500 HRESULT hr; /* result for multi-threaded case */
501 IStream *stream; /* stream that the object will be marshaled into */
504 static HRESULT apartment_hostobject(struct apartment *apt,
505 const struct host_object_params *params)
507 IUnknown *object;
508 HRESULT hr;
509 static const LARGE_INTEGER llZero;
510 WCHAR dllpath[MAX_PATH+1];
512 TRACE("clsid %s, iid %s\n", debugstr_guid(&params->clsid), debugstr_guid(&params->iid));
514 if (COM_RegReadPath(params->hkeydll, NULL, NULL, dllpath, ARRAYSIZE(dllpath)) != ERROR_SUCCESS)
516 /* failure: CLSID is not found in registry */
517 WARN("class %s not registered inproc\n", debugstr_guid(&params->clsid));
518 return REGDB_E_CLASSNOTREG;
521 hr = apartment_getclassobject(apt, dllpath, &params->clsid, &params->iid, (void **)&object);
522 if (FAILED(hr))
523 return hr;
525 hr = CoMarshalInterface(params->stream, &params->iid, object, MSHCTX_INPROC, NULL, MSHLFLAGS_NORMAL);
526 if (FAILED(hr))
527 IUnknown_Release(object);
528 IStream_Seek(params->stream, llZero, STREAM_SEEK_SET, NULL);
530 return hr;
533 static LRESULT CALLBACK apartment_wndproc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
535 switch (msg)
537 case DM_EXECUTERPC:
538 RPC_ExecuteCall((struct dispatch_params *)lParam);
539 return 0;
540 case DM_HOSTOBJECT:
541 return apartment_hostobject(COM_CurrentApt(), (const struct host_object_params *)lParam);
542 default:
543 return DefWindowProcW(hWnd, msg, wParam, lParam);
547 struct host_thread_params
549 COINIT threading_model;
550 HANDLE ready_event;
551 HWND apartment_hwnd;
554 static DWORD CALLBACK apartment_hostobject_thread(LPVOID p)
556 struct host_thread_params *params = p;
557 MSG msg;
558 HRESULT hr;
559 struct apartment *apt;
561 TRACE("\n");
563 hr = CoInitializeEx(NULL, params->threading_model);
564 if (FAILED(hr)) return hr;
566 apt = COM_CurrentApt();
567 if (params->threading_model == COINIT_APARTMENTTHREADED)
569 apartment_createwindowifneeded(apt);
570 params->apartment_hwnd = apartment_getwindow(apt);
572 else
573 params->apartment_hwnd = NULL;
575 /* force the message queue to be created before signaling parent thread */
576 PeekMessageW(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
578 SetEvent(params->ready_event);
579 params = NULL; /* can't touch params after here as it may be invalid */
581 while (GetMessageW(&msg, NULL, 0, 0))
583 if (!msg.hwnd && (msg.message == DM_HOSTOBJECT))
585 struct host_object_params *params = (struct host_object_params *)msg.lParam;
586 params->hr = apartment_hostobject(apt, params);
587 SetEvent(params->event);
589 else
591 TranslateMessage(&msg);
592 DispatchMessageW(&msg);
596 TRACE("exiting\n");
598 CoUninitialize();
600 return S_OK;
603 static HRESULT apartment_hostobject_in_hostapt(struct apartment *apt, BOOL multi_threaded, BOOL main_apartment, HKEY hkeydll, REFCLSID rclsid, REFIID riid, void **ppv)
605 struct host_object_params params;
606 HWND apartment_hwnd = NULL;
607 DWORD apartment_tid = 0;
608 HRESULT hr;
610 if (!multi_threaded && main_apartment)
612 APARTMENT *host_apt = apartment_findmain();
613 if (host_apt)
615 apartment_hwnd = apartment_getwindow(host_apt);
616 apartment_release(host_apt);
620 if (!apartment_hwnd)
622 EnterCriticalSection(&apt->cs);
624 if (!apt->host_apt_tid)
626 struct host_thread_params thread_params;
627 HANDLE handles[2];
628 DWORD wait_value;
630 thread_params.threading_model = multi_threaded ? COINIT_MULTITHREADED : COINIT_APARTMENTTHREADED;
631 handles[0] = thread_params.ready_event = CreateEventW(NULL, FALSE, FALSE, NULL);
632 thread_params.apartment_hwnd = NULL;
633 handles[1] = CreateThread(NULL, 0, apartment_hostobject_thread, &thread_params, 0, &apt->host_apt_tid);
634 if (!handles[1])
636 CloseHandle(handles[0]);
637 LeaveCriticalSection(&apt->cs);
638 return E_OUTOFMEMORY;
640 wait_value = WaitForMultipleObjects(2, handles, FALSE, INFINITE);
641 CloseHandle(handles[0]);
642 CloseHandle(handles[1]);
643 if (wait_value == WAIT_OBJECT_0)
644 apt->host_apt_hwnd = thread_params.apartment_hwnd;
645 else
647 LeaveCriticalSection(&apt->cs);
648 return E_OUTOFMEMORY;
652 if (multi_threaded || !main_apartment)
654 apartment_hwnd = apt->host_apt_hwnd;
655 apartment_tid = apt->host_apt_tid;
658 LeaveCriticalSection(&apt->cs);
661 /* another thread may have become the main apartment in the time it took
662 * us to create the thread for the host apartment */
663 if (!apartment_hwnd && !multi_threaded && main_apartment)
665 APARTMENT *host_apt = apartment_findmain();
666 if (host_apt)
668 apartment_hwnd = apartment_getwindow(host_apt);
669 apartment_release(host_apt);
673 params.hkeydll = hkeydll;
674 params.clsid = *rclsid;
675 params.iid = *riid;
676 hr = CreateStreamOnHGlobal(NULL, TRUE, &params.stream);
677 if (FAILED(hr))
678 return hr;
679 if (multi_threaded)
681 params.hr = S_OK;
682 params.event = CreateEventW(NULL, FALSE, FALSE, NULL);
683 if (!PostThreadMessageW(apartment_tid, DM_HOSTOBJECT, 0, (LPARAM)&params))
684 hr = E_OUTOFMEMORY;
685 else
687 WaitForSingleObject(params.event, INFINITE);
688 hr = params.hr;
690 CloseHandle(params.event);
692 else
694 if (!apartment_hwnd)
696 ERR("host apartment didn't create window\n");
697 hr = E_OUTOFMEMORY;
699 else
700 hr = SendMessageW(apartment_hwnd, DM_HOSTOBJECT, 0, (LPARAM)&params);
702 if (SUCCEEDED(hr))
703 hr = CoUnmarshalInterface(params.stream, riid, ppv);
704 IStream_Release(params.stream);
705 return hr;
708 HRESULT apartment_createwindowifneeded(struct apartment *apt)
710 if (apt->multi_threaded)
711 return S_OK;
713 if (!apt->win)
715 HWND hwnd = CreateWindowW(wszAptWinClass, NULL, 0,
716 0, 0, 0, 0,
717 0, 0, OLE32_hInstance, NULL);
718 if (!hwnd)
720 ERR("CreateWindow failed with error %d\n", GetLastError());
721 return HRESULT_FROM_WIN32(GetLastError());
723 if (InterlockedCompareExchangePointer((PVOID *)&apt->win, hwnd, NULL))
724 /* someone beat us to it */
725 DestroyWindow(hwnd);
728 return S_OK;
731 HWND apartment_getwindow(struct apartment *apt)
733 assert(!apt->multi_threaded);
734 return apt->win;
737 void apartment_joinmta(void)
739 apartment_addref(MTA);
740 COM_CurrentInfo()->apt = MTA;
743 static HRESULT apartment_getclassobject(struct apartment *apt, LPCWSTR dllpath,
744 REFCLSID rclsid, REFIID riid, void **ppv)
746 static const WCHAR wszOle32[] = {'o','l','e','3','2','.','d','l','l',0};
747 HRESULT hr = S_OK;
748 BOOL found = FALSE;
749 struct apartment_loaded_dll *apartment_loaded_dll;
751 if (!strcmpiW(dllpath, wszOle32))
753 /* we don't need to control the lifetime of this dll, so use the local
754 * implementation of DllGetClassObject directly */
755 TRACE("calling ole32!DllGetClassObject\n");
756 hr = DllGetClassObject(rclsid, riid, ppv);
758 if (hr != S_OK)
759 ERR("DllGetClassObject returned error 0x%08x\n", hr);
761 return hr;
764 EnterCriticalSection(&apt->cs);
766 LIST_FOR_EACH_ENTRY(apartment_loaded_dll, &apt->loaded_dlls, struct apartment_loaded_dll, entry)
767 if (!strcmpiW(dllpath, apartment_loaded_dll->dll->library_name))
769 TRACE("found %s already loaded\n", debugstr_w(dllpath));
770 found = TRUE;
771 break;
774 if (!found)
776 apartment_loaded_dll = HeapAlloc(GetProcessHeap(), 0, sizeof(*apartment_loaded_dll));
777 if (!apartment_loaded_dll)
778 hr = E_OUTOFMEMORY;
779 if (SUCCEEDED(hr))
781 hr = COMPOBJ_DllList_Add( dllpath, &apartment_loaded_dll->dll );
782 if (FAILED(hr))
783 HeapFree(GetProcessHeap(), 0, apartment_loaded_dll);
785 if (SUCCEEDED(hr))
787 TRACE("added new loaded dll %s\n", debugstr_w(dllpath));
788 list_add_tail(&apt->loaded_dlls, &apartment_loaded_dll->entry);
792 LeaveCriticalSection(&apt->cs);
794 if (SUCCEEDED(hr))
796 TRACE("calling DllGetClassObject %p\n", apartment_loaded_dll->dll->DllGetClassObject);
797 /* OK: get the ClassObject */
798 hr = apartment_loaded_dll->dll->DllGetClassObject(rclsid, riid, ppv);
800 if (hr != S_OK)
801 ERR("DllGetClassObject returned error 0x%08x\n", hr);
804 return hr;
807 static void apartment_freeunusedlibraries(struct apartment *apt)
809 struct apartment_loaded_dll *entry, *next;
810 EnterCriticalSection(&apt->cs);
811 LIST_FOR_EACH_ENTRY_SAFE(entry, next, &apt->loaded_dlls, struct apartment_loaded_dll, entry)
813 if (entry->dll->DllCanUnloadNow && (entry->dll->DllCanUnloadNow() == S_OK))
815 list_remove(&entry->entry);
816 COMPOBJ_DllList_ReleaseRef(entry->dll, TRUE);
817 HeapFree(GetProcessHeap(), 0, entry);
820 LeaveCriticalSection(&apt->cs);
823 /*****************************************************************************
824 * This section contains OpenDllList implementation
827 /* caller must ensure that library_name is not already in the open dll list */
828 static HRESULT COMPOBJ_DllList_Add(LPCWSTR library_name, OpenDll **ret)
830 OpenDll *entry;
831 int len;
832 HRESULT hr = S_OK;
833 HANDLE hLibrary;
834 DllCanUnloadNowFunc DllCanUnloadNow;
835 DllGetClassObjectFunc DllGetClassObject;
837 TRACE("\n");
839 *ret = COMPOBJ_DllList_Get(library_name);
840 if (*ret) return S_OK;
842 /* do this outside the csOpenDllList to avoid creating a lock dependency on
843 * the loader lock */
844 hLibrary = LoadLibraryExW(library_name, 0, LOAD_WITH_ALTERED_SEARCH_PATH);
845 if (!hLibrary)
847 ERR("couldn't load in-process dll %s\n", debugstr_w(library_name));
848 /* failure: DLL could not be loaded */
849 return E_ACCESSDENIED; /* FIXME: or should this be CO_E_DLLNOTFOUND? */
852 DllCanUnloadNow = (void *)GetProcAddress(hLibrary, "DllCanUnloadNow");
853 /* Note: failing to find DllCanUnloadNow is not a failure */
854 DllGetClassObject = (void *)GetProcAddress(hLibrary, "DllGetClassObject");
855 if (!DllGetClassObject)
857 /* failure: the dll did not export DllGetClassObject */
858 ERR("couldn't find function DllGetClassObject in %s\n", debugstr_w(library_name));
859 FreeLibrary(hLibrary);
860 return CO_E_DLLNOTFOUND;
863 EnterCriticalSection( &csOpenDllList );
865 *ret = COMPOBJ_DllList_Get(library_name);
866 if (*ret)
868 /* another caller to this function already added the dll while we
869 * weren't in the critical section */
870 FreeLibrary(hLibrary);
872 else
874 len = strlenW(library_name);
875 entry = HeapAlloc(GetProcessHeap(),0, sizeof(OpenDll));
876 if (entry)
877 entry->library_name = HeapAlloc(GetProcessHeap(), 0, (len + 1)*sizeof(WCHAR));
878 if (entry && entry->library_name)
880 memcpy(entry->library_name, library_name, (len + 1)*sizeof(WCHAR));
881 entry->library = hLibrary;
882 entry->refs = 1;
883 entry->DllCanUnloadNow = DllCanUnloadNow;
884 entry->DllGetClassObject = DllGetClassObject;
885 list_add_tail(&openDllList, &entry->entry);
887 else
889 hr = E_OUTOFMEMORY;
890 FreeLibrary(hLibrary);
892 *ret = entry;
895 LeaveCriticalSection( &csOpenDllList );
897 return hr;
900 static OpenDll *COMPOBJ_DllList_Get(LPCWSTR library_name)
902 OpenDll *ptr;
903 OpenDll *ret = NULL;
904 EnterCriticalSection(&csOpenDllList);
905 LIST_FOR_EACH_ENTRY(ptr, &openDllList, OpenDll, entry)
907 if (!strcmpiW(library_name, ptr->library_name) &&
908 (InterlockedIncrement(&ptr->refs) != 1) /* entry is being destroy if == 1 */)
910 ret = ptr;
911 break;
914 LeaveCriticalSection(&csOpenDllList);
915 return ret;
918 /* pass FALSE for free_entry to release a reference without destroying the
919 * entry if it reaches zero or TRUE otherwise */
920 static void COMPOBJ_DllList_ReleaseRef(OpenDll *entry, BOOL free_entry)
922 if (!InterlockedDecrement(&entry->refs) && free_entry)
924 EnterCriticalSection(&csOpenDllList);
925 list_remove(&entry->entry);
926 LeaveCriticalSection(&csOpenDllList);
928 TRACE("freeing %p\n", entry->library);
929 FreeLibrary(entry->library);
931 HeapFree(GetProcessHeap(), 0, entry->library_name);
932 HeapFree(GetProcessHeap(), 0, entry);
936 /******************************************************************************
937 * CoBuildVersion [OLE32.@]
938 * CoBuildVersion [COMPOBJ.1]
940 * Gets the build version of the DLL.
942 * PARAMS
944 * RETURNS
945 * Current build version, hiword is majornumber, loword is minornumber
947 DWORD WINAPI CoBuildVersion(void)
949 TRACE("Returning version %d, build %d.\n", rmm, rup);
950 return (rmm<<16)+rup;
953 /******************************************************************************
954 * CoInitialize [OLE32.@]
956 * Initializes the COM libraries by calling CoInitializeEx with
957 * COINIT_APARTMENTTHREADED, ie it enters a STA thread.
959 * PARAMS
960 * lpReserved [I] Pointer to IMalloc interface (obsolete, should be NULL).
962 * RETURNS
963 * Success: S_OK if not already initialized, S_FALSE otherwise.
964 * Failure: HRESULT code.
966 * SEE ALSO
967 * CoInitializeEx
969 HRESULT WINAPI CoInitialize(LPVOID lpReserved)
972 * Just delegate to the newer method.
974 return CoInitializeEx(lpReserved, COINIT_APARTMENTTHREADED);
977 /******************************************************************************
978 * CoInitializeEx [OLE32.@]
980 * Initializes the COM libraries.
982 * PARAMS
983 * lpReserved [I] Pointer to IMalloc interface (obsolete, should be NULL).
984 * dwCoInit [I] One or more flags from the COINIT enumeration. See notes.
986 * RETURNS
987 * S_OK if successful,
988 * S_FALSE if this function was called already.
989 * RPC_E_CHANGED_MODE if a previous call to CoInitializeEx specified another
990 * threading model.
992 * NOTES
994 * The behavior used to set the IMalloc used for memory management is
995 * obsolete.
996 * The dwCoInit parameter must specify one of the following apartment
997 * threading models:
998 *| COINIT_APARTMENTTHREADED - A single-threaded apartment (STA).
999 *| COINIT_MULTITHREADED - A multi-threaded apartment (MTA).
1000 * The parameter may also specify zero or more of the following flags:
1001 *| COINIT_DISABLE_OLE1DDE - Don't use DDE for OLE1 support.
1002 *| COINIT_SPEED_OVER_MEMORY - Trade memory for speed.
1004 * SEE ALSO
1005 * CoUninitialize
1007 HRESULT WINAPI CoInitializeEx(LPVOID lpReserved, DWORD dwCoInit)
1009 HRESULT hr = S_OK;
1010 APARTMENT *apt;
1012 TRACE("(%p, %x)\n", lpReserved, (int)dwCoInit);
1014 if (lpReserved!=NULL)
1016 ERR("(%p, %x) - Bad parameter passed-in %p, must be an old Windows Application\n", lpReserved, (int)dwCoInit, lpReserved);
1020 * Check the lock count. If this is the first time going through the initialize
1021 * process, we have to initialize the libraries.
1023 * And crank-up that lock count.
1025 if (InterlockedExchangeAdd(&s_COMLockCount,1)==0)
1028 * Initialize the various COM libraries and data structures.
1030 TRACE("() - Initializing the COM libraries\n");
1032 /* we may need to defer this until after apartment initialisation */
1033 RunningObjectTableImpl_Initialize();
1036 if (!(apt = COM_CurrentInfo()->apt))
1038 apt = apartment_get_or_create(dwCoInit);
1039 if (!apt) return E_OUTOFMEMORY;
1041 else if (!apartment_is_model(apt, dwCoInit))
1043 /* Changing the threading model after it's been set is illegal. If this warning is triggered by Wine
1044 code then we are probably using the wrong threading model to implement that API. */
1045 ERR("Attempt to change threading model of this apartment from %s to %s\n",
1046 apt->multi_threaded ? "multi-threaded" : "apartment threaded",
1047 dwCoInit & COINIT_APARTMENTTHREADED ? "apartment threaded" : "multi-threaded");
1048 return RPC_E_CHANGED_MODE;
1050 else
1051 hr = S_FALSE;
1053 COM_CurrentInfo()->inits++;
1055 return hr;
1058 /* On COM finalization for a STA thread, the message queue is flushed to ensure no
1059 pending RPCs are ignored. Non-COM messages are discarded at this point.
1061 static void COM_FlushMessageQueue(void)
1063 MSG message;
1064 APARTMENT *apt = COM_CurrentApt();
1066 if (!apt || !apt->win) return;
1068 TRACE("Flushing STA message queue\n");
1070 while (PeekMessageA(&message, NULL, 0, 0, PM_REMOVE))
1072 if (message.hwnd != apt->win)
1074 WARN("discarding message 0x%x for window %p\n", message.message, message.hwnd);
1075 continue;
1078 TranslateMessage(&message);
1079 DispatchMessageA(&message);
1083 /***********************************************************************
1084 * CoUninitialize [OLE32.@]
1086 * This method will decrement the refcount on the current apartment, freeing
1087 * the resources associated with it if it is the last thread in the apartment.
1088 * If the last apartment is freed, the function will additionally release
1089 * any COM resources associated with the process.
1091 * PARAMS
1093 * RETURNS
1094 * Nothing.
1096 * SEE ALSO
1097 * CoInitializeEx
1099 void WINAPI CoUninitialize(void)
1101 struct oletls * info = COM_CurrentInfo();
1102 LONG lCOMRefCnt;
1104 TRACE("()\n");
1106 /* will only happen on OOM */
1107 if (!info) return;
1109 /* sanity check */
1110 if (!info->inits)
1112 ERR("Mismatched CoUninitialize\n");
1113 return;
1116 if (!--info->inits)
1118 apartment_release(info->apt);
1119 info->apt = NULL;
1123 * Decrease the reference count.
1124 * If we are back to 0 locks on the COM library, make sure we free
1125 * all the associated data structures.
1127 lCOMRefCnt = InterlockedExchangeAdd(&s_COMLockCount,-1);
1128 if (lCOMRefCnt==1)
1130 TRACE("() - Releasing the COM libraries\n");
1132 RunningObjectTableImpl_UnInitialize();
1134 /* This will free the loaded COM Dlls */
1135 CoFreeAllLibraries();
1137 /* This ensures we deal with any pending RPCs */
1138 COM_FlushMessageQueue();
1140 else if (lCOMRefCnt<1) {
1141 ERR( "CoUninitialize() - not CoInitialized.\n" );
1142 InterlockedExchangeAdd(&s_COMLockCount,1); /* restore the lock count. */
1146 /******************************************************************************
1147 * CoDisconnectObject [OLE32.@]
1149 * Disconnects all connections to this object from remote processes. Dispatches
1150 * pending RPCs while blocking new RPCs from occurring, and then calls
1151 * IMarshal::DisconnectObject on the given object.
1153 * Typically called when the object server is forced to shut down, for instance by
1154 * the user.
1156 * PARAMS
1157 * lpUnk [I] The object whose stub should be disconnected.
1158 * reserved [I] Reserved. Should be set to 0.
1160 * RETURNS
1161 * Success: S_OK.
1162 * Failure: HRESULT code.
1164 * SEE ALSO
1165 * CoMarshalInterface, CoReleaseMarshalData, CoLockObjectExternal
1167 HRESULT WINAPI CoDisconnectObject( LPUNKNOWN lpUnk, DWORD reserved )
1169 HRESULT hr;
1170 IMarshal *marshal;
1171 APARTMENT *apt;
1173 TRACE("(%p, 0x%08x)\n", lpUnk, reserved);
1175 hr = IUnknown_QueryInterface(lpUnk, &IID_IMarshal, (void **)&marshal);
1176 if (hr == S_OK)
1178 hr = IMarshal_DisconnectObject(marshal, reserved);
1179 IMarshal_Release(marshal);
1180 return hr;
1183 apt = COM_CurrentApt();
1184 if (!apt)
1185 return CO_E_NOTINITIALIZED;
1187 apartment_disconnectobject(apt, lpUnk);
1189 /* Note: native is pretty broken here because it just silently
1190 * fails, without returning an appropriate error code if the object was
1191 * not found, making apps think that the object was disconnected, when
1192 * it actually wasn't */
1194 return S_OK;
1197 /******************************************************************************
1198 * CoCreateGuid [OLE32.@]
1200 * Simply forwards to UuidCreate in RPCRT4.
1202 * PARAMS
1203 * pguid [O] Points to the GUID to initialize.
1205 * RETURNS
1206 * Success: S_OK.
1207 * Failure: HRESULT code.
1209 * SEE ALSO
1210 * UuidCreate
1212 HRESULT WINAPI CoCreateGuid(GUID *pguid)
1214 return UuidCreate(pguid);
1217 /******************************************************************************
1218 * CLSIDFromString [OLE32.@]
1219 * IIDFromString [OLE32.@]
1221 * Converts a unique identifier from its string representation into
1222 * the GUID struct.
1224 * PARAMS
1225 * idstr [I] The string representation of the GUID.
1226 * id [O] GUID converted from the string.
1228 * RETURNS
1229 * S_OK on success
1230 * CO_E_CLASSSTRING if idstr is not a valid CLSID
1232 * SEE ALSO
1233 * StringFromCLSID
1235 static HRESULT WINAPI __CLSIDFromString(LPCWSTR s, CLSID *id)
1237 int i;
1238 BYTE table[256];
1240 if (!s) {
1241 memset( id, 0, sizeof (CLSID) );
1242 return S_OK;
1245 /* validate the CLSID string */
1246 if (strlenW(s) != 38)
1247 return CO_E_CLASSSTRING;
1249 if ((s[0]!='{') || (s[9]!='-') || (s[14]!='-') || (s[19]!='-') || (s[24]!='-') || (s[37]!='}'))
1250 return CO_E_CLASSSTRING;
1252 for (i=1; i<37; i++) {
1253 if ((i == 9)||(i == 14)||(i == 19)||(i == 24)) continue;
1254 if (!(((s[i] >= '0') && (s[i] <= '9')) ||
1255 ((s[i] >= 'a') && (s[i] <= 'f')) ||
1256 ((s[i] >= 'A') && (s[i] <= 'F'))))
1257 return CO_E_CLASSSTRING;
1260 TRACE("%s -> %p\n", debugstr_w(s), id);
1262 /* quick lookup table */
1263 memset(table, 0, 256);
1265 for (i = 0; i < 10; i++) {
1266 table['0' + i] = i;
1268 for (i = 0; i < 6; i++) {
1269 table['A' + i] = i+10;
1270 table['a' + i] = i+10;
1273 /* in form {XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX} */
1275 id->Data1 = (table[s[1]] << 28 | table[s[2]] << 24 | table[s[3]] << 20 | table[s[4]] << 16 |
1276 table[s[5]] << 12 | table[s[6]] << 8 | table[s[7]] << 4 | table[s[8]]);
1277 id->Data2 = table[s[10]] << 12 | table[s[11]] << 8 | table[s[12]] << 4 | table[s[13]];
1278 id->Data3 = table[s[15]] << 12 | table[s[16]] << 8 | table[s[17]] << 4 | table[s[18]];
1280 /* these are just sequential bytes */
1281 id->Data4[0] = table[s[20]] << 4 | table[s[21]];
1282 id->Data4[1] = table[s[22]] << 4 | table[s[23]];
1283 id->Data4[2] = table[s[25]] << 4 | table[s[26]];
1284 id->Data4[3] = table[s[27]] << 4 | table[s[28]];
1285 id->Data4[4] = table[s[29]] << 4 | table[s[30]];
1286 id->Data4[5] = table[s[31]] << 4 | table[s[32]];
1287 id->Data4[6] = table[s[33]] << 4 | table[s[34]];
1288 id->Data4[7] = table[s[35]] << 4 | table[s[36]];
1290 return S_OK;
1293 /*****************************************************************************/
1295 HRESULT WINAPI CLSIDFromString(LPOLESTR idstr, CLSID *id )
1297 HRESULT ret;
1299 if (!id)
1300 return E_INVALIDARG;
1302 ret = __CLSIDFromString(idstr, id);
1303 if(ret != S_OK) { /* It appears a ProgID is also valid */
1304 ret = CLSIDFromProgID(idstr, id);
1306 return ret;
1309 /* Converts a GUID into the respective string representation. */
1310 HRESULT WINE_StringFromCLSID(
1311 const CLSID *id, /* [in] GUID to be converted */
1312 LPSTR idstr /* [out] pointer to buffer to contain converted guid */
1314 static const char hex[] = "0123456789ABCDEF";
1315 char *s;
1316 int i;
1318 if (!id)
1319 { ERR("called with id=Null\n");
1320 *idstr = 0x00;
1321 return E_FAIL;
1324 sprintf(idstr, "{%08X-%04X-%04X-%02X%02X-",
1325 id->Data1, id->Data2, id->Data3,
1326 id->Data4[0], id->Data4[1]);
1327 s = &idstr[25];
1329 /* 6 hex bytes */
1330 for (i = 2; i < 8; i++) {
1331 *s++ = hex[id->Data4[i]>>4];
1332 *s++ = hex[id->Data4[i] & 0xf];
1335 *s++ = '}';
1336 *s++ = '\0';
1338 TRACE("%p->%s\n", id, idstr);
1340 return S_OK;
1344 /******************************************************************************
1345 * StringFromCLSID [OLE32.@]
1346 * StringFromIID [OLE32.@]
1348 * Converts a GUID into the respective string representation.
1349 * The target string is allocated using the OLE IMalloc.
1351 * PARAMS
1352 * id [I] the GUID to be converted.
1353 * idstr [O] A pointer to a to-be-allocated pointer pointing to the resulting string.
1355 * RETURNS
1356 * S_OK
1357 * E_FAIL
1359 * SEE ALSO
1360 * StringFromGUID2, CLSIDFromString
1362 HRESULT WINAPI StringFromCLSID(REFCLSID id, LPOLESTR *idstr)
1364 char buf[80];
1365 HRESULT ret;
1366 LPMALLOC mllc;
1368 if ((ret = CoGetMalloc(0,&mllc)))
1369 return ret;
1371 ret=WINE_StringFromCLSID(id,buf);
1372 if (!ret) {
1373 DWORD len = MultiByteToWideChar( CP_ACP, 0, buf, -1, NULL, 0 );
1374 *idstr = IMalloc_Alloc( mllc, len * sizeof(WCHAR) );
1375 MultiByteToWideChar( CP_ACP, 0, buf, -1, *idstr, len );
1377 return ret;
1380 /******************************************************************************
1381 * StringFromGUID2 [OLE32.@]
1382 * StringFromGUID2 [COMPOBJ.76]
1384 * Modified version of StringFromCLSID that allows you to specify max
1385 * buffer size.
1387 * PARAMS
1388 * id [I] GUID to convert to string.
1389 * str [O] Buffer where the result will be stored.
1390 * cmax [I] Size of the buffer in characters.
1392 * RETURNS
1393 * Success: The length of the resulting string in characters.
1394 * Failure: 0.
1396 INT WINAPI StringFromGUID2(REFGUID id, LPOLESTR str, INT cmax)
1398 char xguid[80];
1400 if (WINE_StringFromCLSID(id,xguid))
1401 return 0;
1402 return MultiByteToWideChar( CP_ACP, 0, xguid, -1, str, cmax );
1405 /* open HKCR\\CLSID\\{string form of clsid}\\{keyname} key */
1406 HRESULT COM_OpenKeyForCLSID(REFCLSID clsid, LPCWSTR keyname, REGSAM access, HKEY *subkey)
1408 static const WCHAR wszCLSIDSlash[] = {'C','L','S','I','D','\\',0};
1409 WCHAR path[CHARS_IN_GUID + ARRAYSIZE(wszCLSIDSlash) - 1];
1410 LONG res;
1411 HKEY key;
1413 strcpyW(path, wszCLSIDSlash);
1414 StringFromGUID2(clsid, path + strlenW(wszCLSIDSlash), CHARS_IN_GUID);
1415 res = RegOpenKeyExW(HKEY_CLASSES_ROOT, path, 0, keyname ? KEY_READ : access, &key);
1416 if (res == ERROR_FILE_NOT_FOUND)
1417 return REGDB_E_CLASSNOTREG;
1418 else if (res != ERROR_SUCCESS)
1419 return REGDB_E_READREGDB;
1421 if (!keyname)
1423 *subkey = key;
1424 return S_OK;
1427 res = RegOpenKeyExW(key, keyname, 0, access, subkey);
1428 RegCloseKey(key);
1429 if (res == ERROR_FILE_NOT_FOUND)
1430 return REGDB_E_KEYMISSING;
1431 else if (res != ERROR_SUCCESS)
1432 return REGDB_E_READREGDB;
1434 return S_OK;
1437 /* open HKCR\\AppId\\{string form of appid clsid} key */
1438 HRESULT COM_OpenKeyForAppIdFromCLSID(REFCLSID clsid, REGSAM access, HKEY *subkey)
1440 static const WCHAR szAppId[] = { 'A','p','p','I','d',0 };
1441 static const WCHAR szAppIdKey[] = { 'A','p','p','I','d','\\',0 };
1442 DWORD res;
1443 WCHAR buf[CHARS_IN_GUID];
1444 WCHAR keyname[ARRAYSIZE(szAppIdKey) + CHARS_IN_GUID];
1445 DWORD size;
1446 HKEY hkey;
1447 DWORD type;
1448 HRESULT hr;
1450 /* read the AppID value under the class's key */
1451 hr = COM_OpenKeyForCLSID(clsid, NULL, KEY_READ, &hkey);
1452 if (FAILED(hr))
1453 return hr;
1455 size = sizeof(buf);
1456 res = RegQueryValueExW(hkey, szAppId, NULL, &type, (LPBYTE)buf, &size);
1457 RegCloseKey(hkey);
1458 if (res == ERROR_FILE_NOT_FOUND)
1459 return REGDB_E_KEYMISSING;
1460 else if (res != ERROR_SUCCESS || type!=REG_SZ)
1461 return REGDB_E_READREGDB;
1463 strcpyW(keyname, szAppIdKey);
1464 strcatW(keyname, buf);
1465 res = RegOpenKeyExW(HKEY_CLASSES_ROOT, keyname, 0, access, subkey);
1466 if (res == ERROR_FILE_NOT_FOUND)
1467 return REGDB_E_KEYMISSING;
1468 else if (res != ERROR_SUCCESS)
1469 return REGDB_E_READREGDB;
1471 return S_OK;
1474 /******************************************************************************
1475 * ProgIDFromCLSID [OLE32.@]
1477 * Converts a class id into the respective program ID.
1479 * PARAMS
1480 * clsid [I] Class ID, as found in registry.
1481 * ppszProgID [O] Associated ProgID.
1483 * RETURNS
1484 * S_OK
1485 * E_OUTOFMEMORY
1486 * REGDB_E_CLASSNOTREG if the given clsid has no associated ProgID
1488 HRESULT WINAPI ProgIDFromCLSID(REFCLSID clsid, LPOLESTR *ppszProgID)
1490 static const WCHAR wszProgID[] = {'P','r','o','g','I','D',0};
1491 HKEY hkey;
1492 HRESULT ret;
1493 LONG progidlen = 0;
1495 if (!ppszProgID)
1497 ERR("ppszProgId isn't optional\n");
1498 return E_INVALIDARG;
1501 *ppszProgID = NULL;
1502 ret = COM_OpenKeyForCLSID(clsid, wszProgID, KEY_READ, &hkey);
1503 if (FAILED(ret))
1504 return ret;
1506 if (RegQueryValueW(hkey, NULL, NULL, &progidlen))
1507 ret = REGDB_E_CLASSNOTREG;
1509 if (ret == S_OK)
1511 *ppszProgID = CoTaskMemAlloc(progidlen * sizeof(WCHAR));
1512 if (*ppszProgID)
1514 if (RegQueryValueW(hkey, NULL, *ppszProgID, &progidlen))
1515 ret = REGDB_E_CLASSNOTREG;
1517 else
1518 ret = E_OUTOFMEMORY;
1521 RegCloseKey(hkey);
1522 return ret;
1525 /******************************************************************************
1526 * CLSIDFromProgID [OLE32.@]
1528 * Converts a program id into the respective GUID.
1530 * PARAMS
1531 * progid [I] Unicode program ID, as found in registry.
1532 * clsid [O] Associated CLSID.
1534 * RETURNS
1535 * Success: S_OK
1536 * Failure: CO_E_CLASSSTRING - the given ProgID cannot be found.
1538 HRESULT WINAPI CLSIDFromProgID(LPCOLESTR progid, LPCLSID clsid)
1540 static const WCHAR clsidW[] = { '\\','C','L','S','I','D',0 };
1541 WCHAR buf2[CHARS_IN_GUID];
1542 LONG buf2len = sizeof(buf2);
1543 HKEY xhkey;
1544 WCHAR *buf;
1546 if (!progid || !clsid)
1548 ERR("neither progid (%p) nor clsid (%p) are optional\n", progid, clsid);
1549 return E_INVALIDARG;
1552 /* initialise clsid in case of failure */
1553 memset(clsid, 0, sizeof(*clsid));
1555 buf = HeapAlloc( GetProcessHeap(),0,(strlenW(progid)+8) * sizeof(WCHAR) );
1556 strcpyW( buf, progid );
1557 strcatW( buf, clsidW );
1558 if (RegOpenKeyW(HKEY_CLASSES_ROOT,buf,&xhkey))
1560 HeapFree(GetProcessHeap(),0,buf);
1561 WARN("couldn't open key for ProgID %s\n", debugstr_w(progid));
1562 return CO_E_CLASSSTRING;
1564 HeapFree(GetProcessHeap(),0,buf);
1566 if (RegQueryValueW(xhkey,NULL,buf2,&buf2len))
1568 RegCloseKey(xhkey);
1569 WARN("couldn't query clsid value for ProgID %s\n", debugstr_w(progid));
1570 return CO_E_CLASSSTRING;
1572 RegCloseKey(xhkey);
1573 return CLSIDFromString(buf2,clsid);
1577 /*****************************************************************************
1578 * CoGetPSClsid [OLE32.@]
1580 * Retrieves the CLSID of the proxy/stub factory that implements
1581 * IPSFactoryBuffer for the specified interface.
1583 * PARAMS
1584 * riid [I] Interface whose proxy/stub CLSID is to be returned.
1585 * pclsid [O] Where to store returned proxy/stub CLSID.
1587 * RETURNS
1588 * S_OK
1589 * E_OUTOFMEMORY
1590 * REGDB_E_IIDNOTREG if no PSFactoryBuffer is associated with the IID, or it could not be parsed
1592 * NOTES
1594 * The standard marshaller activates the object with the CLSID
1595 * returned and uses the CreateProxy and CreateStub methods on its
1596 * IPSFactoryBuffer interface to construct the proxies and stubs for a
1597 * given object.
1599 * CoGetPSClsid determines this CLSID by searching the
1600 * HKEY_CLASSES_ROOT\Interface\{string form of riid}\ProxyStubClsid32
1601 * in the registry and any interface id registered by
1602 * CoRegisterPSClsid within the current process.
1604 * BUGS
1606 * Native returns S_OK for interfaces with a key in HKCR\Interface, but
1607 * without a ProxyStubClsid32 key and leaves garbage in pclsid. This should be
1608 * considered a bug in native unless an application depends on this (unlikely).
1610 * SEE ALSO
1611 * CoRegisterPSClsid.
1613 HRESULT WINAPI CoGetPSClsid(REFIID riid, CLSID *pclsid)
1615 static const WCHAR wszInterface[] = {'I','n','t','e','r','f','a','c','e','\\',0};
1616 static const WCHAR wszPSC[] = {'\\','P','r','o','x','y','S','t','u','b','C','l','s','i','d','3','2',0};
1617 WCHAR path[ARRAYSIZE(wszInterface) - 1 + CHARS_IN_GUID - 1 + ARRAYSIZE(wszPSC)];
1618 WCHAR value[CHARS_IN_GUID];
1619 LONG len;
1620 HKEY hkey;
1621 APARTMENT *apt = COM_CurrentApt();
1622 struct registered_psclsid *registered_psclsid;
1624 TRACE("() riid=%s, pclsid=%p\n", debugstr_guid(riid), pclsid);
1626 if (!apt)
1628 ERR("apartment not initialised\n");
1629 return CO_E_NOTINITIALIZED;
1632 if (!pclsid)
1634 ERR("pclsid isn't optional\n");
1635 return E_INVALIDARG;
1638 EnterCriticalSection(&apt->cs);
1640 LIST_FOR_EACH_ENTRY(registered_psclsid, &apt->psclsids, struct registered_psclsid, entry)
1641 if (IsEqualIID(&registered_psclsid->iid, riid))
1643 *pclsid = registered_psclsid->clsid;
1644 LeaveCriticalSection(&apt->cs);
1645 return S_OK;
1648 LeaveCriticalSection(&apt->cs);
1650 /* Interface\\{string form of riid}\\ProxyStubClsid32 */
1651 strcpyW(path, wszInterface);
1652 StringFromGUID2(riid, path + ARRAYSIZE(wszInterface) - 1, CHARS_IN_GUID);
1653 strcpyW(path + ARRAYSIZE(wszInterface) - 1 + CHARS_IN_GUID - 1, wszPSC);
1655 /* Open the key.. */
1656 if (RegOpenKeyExW(HKEY_CLASSES_ROOT, path, 0, KEY_READ, &hkey))
1658 WARN("No PSFactoryBuffer object is registered for IID %s\n", debugstr_guid(riid));
1659 return REGDB_E_IIDNOTREG;
1662 /* ... Once we have the key, query the registry to get the
1663 value of CLSID as a string, and convert it into a
1664 proper CLSID structure to be passed back to the app */
1665 len = sizeof(value);
1666 if (ERROR_SUCCESS != RegQueryValueW(hkey, NULL, value, &len))
1668 RegCloseKey(hkey);
1669 return REGDB_E_IIDNOTREG;
1671 RegCloseKey(hkey);
1673 /* We have the CLSid we want back from the registry as a string, so
1674 lets convert it into a CLSID structure */
1675 if (CLSIDFromString(value, pclsid) != NOERROR)
1676 return REGDB_E_IIDNOTREG;
1678 TRACE ("() Returning CLSID=%s\n", debugstr_guid(pclsid));
1679 return S_OK;
1682 /*****************************************************************************
1683 * CoRegisterPSClsid [OLE32.@]
1685 * Register a proxy/stub CLSID for the given interface in the current process
1686 * only.
1688 * PARAMS
1689 * riid [I] Interface whose proxy/stub CLSID is to be registered.
1690 * rclsid [I] CLSID of the proxy/stub.
1692 * RETURNS
1693 * Success: S_OK
1694 * Failure: E_OUTOFMEMORY
1696 * NOTES
1698 * This function does not add anything to the registry and the effects are
1699 * limited to the lifetime of the current process.
1701 * SEE ALSO
1702 * CoGetPSClsid.
1704 HRESULT WINAPI CoRegisterPSClsid(REFIID riid, REFCLSID rclsid)
1706 APARTMENT *apt = COM_CurrentApt();
1707 struct registered_psclsid *registered_psclsid;
1709 TRACE("(%s, %s)\n", debugstr_guid(riid), debugstr_guid(rclsid));
1711 if (!apt)
1713 ERR("apartment not initialised\n");
1714 return CO_E_NOTINITIALIZED;
1717 EnterCriticalSection(&apt->cs);
1719 LIST_FOR_EACH_ENTRY(registered_psclsid, &apt->psclsids, struct registered_psclsid, entry)
1720 if (IsEqualIID(&registered_psclsid->iid, riid))
1722 registered_psclsid->clsid = *rclsid;
1723 LeaveCriticalSection(&apt->cs);
1724 return S_OK;
1727 registered_psclsid = HeapAlloc(GetProcessHeap(), 0, sizeof(struct registered_psclsid));
1728 if (!registered_psclsid)
1730 LeaveCriticalSection(&apt->cs);
1731 return E_OUTOFMEMORY;
1734 registered_psclsid->iid = *riid;
1735 registered_psclsid->clsid = *rclsid;
1736 list_add_head(&apt->psclsids, &registered_psclsid->entry);
1738 LeaveCriticalSection(&apt->cs);
1740 return S_OK;
1744 /***
1745 * COM_GetRegisteredClassObject
1747 * This internal method is used to scan the registered class list to
1748 * find a class object.
1750 * Params:
1751 * rclsid Class ID of the class to find.
1752 * dwClsContext Class context to match.
1753 * ppv [out] returns a pointer to the class object. Complying
1754 * to normal COM usage, this method will increase the
1755 * reference count on this object.
1757 static HRESULT COM_GetRegisteredClassObject(
1758 struct apartment *apt,
1759 REFCLSID rclsid,
1760 DWORD dwClsContext,
1761 LPUNKNOWN* ppUnk)
1763 HRESULT hr = S_FALSE;
1764 RegisteredClass *curClass;
1767 * Sanity check
1769 assert(ppUnk!=0);
1771 EnterCriticalSection( &csRegisteredClassList );
1773 LIST_FOR_EACH_ENTRY(curClass, &RegisteredClassList, RegisteredClass, entry)
1776 * Check if we have a match on the class ID and context.
1778 if ((apt->oxid == curClass->apartment_id) &&
1779 (dwClsContext & curClass->runContext) &&
1780 IsEqualGUID(&(curClass->classIdentifier), rclsid))
1783 * We have a match, return the pointer to the class object.
1785 *ppUnk = curClass->classObject;
1787 IUnknown_AddRef(curClass->classObject);
1789 hr = S_OK;
1790 break;
1794 LeaveCriticalSection( &csRegisteredClassList );
1796 return hr;
1799 /******************************************************************************
1800 * CoRegisterClassObject [OLE32.@]
1802 * Registers the class object for a given class ID. Servers housed in EXE
1803 * files use this method instead of exporting DllGetClassObject to allow
1804 * other code to connect to their objects.
1806 * PARAMS
1807 * rclsid [I] CLSID of the object to register.
1808 * pUnk [I] IUnknown of the object.
1809 * dwClsContext [I] CLSCTX flags indicating the context in which to run the executable.
1810 * flags [I] REGCLS flags indicating how connections are made.
1811 * lpdwRegister [I] A unique cookie that can be passed to CoRevokeClassObject.
1813 * RETURNS
1814 * S_OK on success,
1815 * E_INVALIDARG if lpdwRegister or pUnk are NULL,
1816 * CO_E_OBJISREG if the object is already registered. We should not return this.
1818 * SEE ALSO
1819 * CoRevokeClassObject, CoGetClassObject
1821 * NOTES
1822 * In-process objects are only registered for the current apartment.
1823 * CoGetClassObject() and CoCreateInstance() will not return objects registered
1824 * in other apartments.
1826 * BUGS
1827 * MSDN claims that multiple interface registrations are legal, but we
1828 * can't do that with our current implementation.
1830 HRESULT WINAPI CoRegisterClassObject(
1831 REFCLSID rclsid,
1832 LPUNKNOWN pUnk,
1833 DWORD dwClsContext,
1834 DWORD flags,
1835 LPDWORD lpdwRegister)
1837 RegisteredClass* newClass;
1838 LPUNKNOWN foundObject;
1839 HRESULT hr;
1840 APARTMENT *apt;
1842 TRACE("(%s,%p,0x%08x,0x%08x,%p)\n",
1843 debugstr_guid(rclsid),pUnk,dwClsContext,flags,lpdwRegister);
1845 if ( (lpdwRegister==0) || (pUnk==0) )
1846 return E_INVALIDARG;
1848 apt = COM_CurrentApt();
1849 if (!apt)
1851 ERR("COM was not initialized\n");
1852 return CO_E_NOTINITIALIZED;
1855 *lpdwRegister = 0;
1857 /* REGCLS_MULTIPLEUSE implies registering as inproc server. This is what
1858 * differentiates the flag from REGCLS_MULTI_SEPARATE. */
1859 if (flags & REGCLS_MULTIPLEUSE)
1860 dwClsContext |= CLSCTX_INPROC_SERVER;
1863 * First, check if the class is already registered.
1864 * If it is, this should cause an error.
1866 hr = COM_GetRegisteredClassObject(apt, rclsid, dwClsContext, &foundObject);
1867 if (hr == S_OK) {
1868 if (flags & REGCLS_MULTIPLEUSE) {
1869 if (dwClsContext & CLSCTX_LOCAL_SERVER)
1870 hr = CoLockObjectExternal(foundObject, TRUE, FALSE);
1871 IUnknown_Release(foundObject);
1872 return hr;
1874 IUnknown_Release(foundObject);
1875 ERR("object already registered for class %s\n", debugstr_guid(rclsid));
1876 return CO_E_OBJISREG;
1879 newClass = HeapAlloc(GetProcessHeap(), 0, sizeof(RegisteredClass));
1880 if ( newClass == NULL )
1881 return E_OUTOFMEMORY;
1883 newClass->classIdentifier = *rclsid;
1884 newClass->apartment_id = apt->oxid;
1885 newClass->runContext = dwClsContext;
1886 newClass->connectFlags = flags;
1887 newClass->pMarshaledData = NULL;
1888 newClass->RpcRegistration = NULL;
1891 * Use the address of the chain node as the cookie since we are sure it's
1892 * unique. FIXME: not on 64-bit platforms.
1894 newClass->dwCookie = (DWORD)newClass;
1897 * Since we're making a copy of the object pointer, we have to increase its
1898 * reference count.
1900 newClass->classObject = pUnk;
1901 IUnknown_AddRef(newClass->classObject);
1903 EnterCriticalSection( &csRegisteredClassList );
1904 list_add_tail(&RegisteredClassList, &newClass->entry);
1905 LeaveCriticalSection( &csRegisteredClassList );
1907 *lpdwRegister = newClass->dwCookie;
1909 if (dwClsContext & CLSCTX_LOCAL_SERVER) {
1910 hr = CreateStreamOnHGlobal(0, TRUE, &newClass->pMarshaledData);
1911 if (hr) {
1912 FIXME("Failed to create stream on hglobal, %x\n", hr);
1913 return hr;
1915 hr = CoMarshalInterface(newClass->pMarshaledData, &IID_IClassFactory,
1916 newClass->classObject, MSHCTX_LOCAL, NULL,
1917 MSHLFLAGS_TABLESTRONG);
1918 if (hr) {
1919 FIXME("CoMarshalInterface failed, %x!\n",hr);
1920 return hr;
1923 hr = RPC_StartLocalServer(&newClass->classIdentifier,
1924 newClass->pMarshaledData,
1925 flags & (REGCLS_MULTIPLEUSE|REGCLS_MULTI_SEPARATE),
1926 &newClass->RpcRegistration);
1928 return S_OK;
1931 static void COM_RevokeRegisteredClassObject(RegisteredClass *curClass)
1933 list_remove(&curClass->entry);
1935 if (curClass->runContext & CLSCTX_LOCAL_SERVER)
1936 RPC_StopLocalServer(curClass->RpcRegistration);
1939 * Release the reference to the class object.
1941 IUnknown_Release(curClass->classObject);
1943 if (curClass->pMarshaledData)
1945 LARGE_INTEGER zero;
1946 memset(&zero, 0, sizeof(zero));
1947 IStream_Seek(curClass->pMarshaledData, zero, STREAM_SEEK_SET, NULL);
1948 CoReleaseMarshalData(curClass->pMarshaledData);
1951 HeapFree(GetProcessHeap(), 0, curClass);
1954 static void COM_RevokeAllClasses(struct apartment *apt)
1956 RegisteredClass *curClass, *cursor;
1958 EnterCriticalSection( &csRegisteredClassList );
1960 LIST_FOR_EACH_ENTRY_SAFE(curClass, cursor, &RegisteredClassList, RegisteredClass, entry)
1962 if (curClass->apartment_id == apt->oxid)
1963 COM_RevokeRegisteredClassObject(curClass);
1966 LeaveCriticalSection( &csRegisteredClassList );
1969 /***********************************************************************
1970 * CoRevokeClassObject [OLE32.@]
1972 * Removes a class object from the class registry.
1974 * PARAMS
1975 * dwRegister [I] Cookie returned from CoRegisterClassObject().
1977 * RETURNS
1978 * Success: S_OK.
1979 * Failure: HRESULT code.
1981 * NOTES
1982 * Must be called from the same apartment that called CoRegisterClassObject(),
1983 * otherwise it will fail with RPC_E_WRONG_THREAD.
1985 * SEE ALSO
1986 * CoRegisterClassObject
1988 HRESULT WINAPI CoRevokeClassObject(
1989 DWORD dwRegister)
1991 HRESULT hr = E_INVALIDARG;
1992 RegisteredClass *curClass;
1993 APARTMENT *apt;
1995 TRACE("(%08x)\n",dwRegister);
1997 apt = COM_CurrentApt();
1998 if (!apt)
2000 ERR("COM was not initialized\n");
2001 return CO_E_NOTINITIALIZED;
2004 EnterCriticalSection( &csRegisteredClassList );
2006 LIST_FOR_EACH_ENTRY(curClass, &RegisteredClassList, RegisteredClass, entry)
2009 * Check if we have a match on the cookie.
2011 if (curClass->dwCookie == dwRegister)
2013 if (curClass->apartment_id == apt->oxid)
2015 COM_RevokeRegisteredClassObject(curClass);
2016 hr = S_OK;
2018 else
2020 ERR("called from wrong apartment, should be called from %s\n",
2021 wine_dbgstr_longlong(curClass->apartment_id));
2022 hr = RPC_E_WRONG_THREAD;
2024 break;
2028 LeaveCriticalSection( &csRegisteredClassList );
2030 return hr;
2033 /***********************************************************************
2034 * COM_RegReadPath [internal]
2036 * Reads a registry value and expands it when necessary
2038 static DWORD COM_RegReadPath(HKEY hkeyroot, const WCHAR *keyname, const WCHAR *valuename, WCHAR * dst, DWORD dstlen)
2040 DWORD ret;
2041 HKEY key;
2042 DWORD keytype;
2043 WCHAR src[MAX_PATH];
2044 DWORD dwLength = dstlen * sizeof(WCHAR);
2046 if((ret = RegOpenKeyExW(hkeyroot, keyname, 0, KEY_READ, &key)) == ERROR_SUCCESS) {
2047 if( (ret = RegQueryValueExW(key, NULL, NULL, &keytype, (LPBYTE)src, &dwLength)) == ERROR_SUCCESS ) {
2048 if (keytype == REG_EXPAND_SZ) {
2049 if (dstlen <= ExpandEnvironmentStringsW(src, dst, dstlen)) ret = ERROR_MORE_DATA;
2050 } else {
2051 lstrcpynW(dst, src, dstlen);
2054 RegCloseKey (key);
2056 return ret;
2059 static void get_threading_model(HKEY key, LPWSTR value, DWORD len)
2061 static const WCHAR wszThreadingModel[] = {'T','h','r','e','a','d','i','n','g','M','o','d','e','l',0};
2062 DWORD keytype;
2063 DWORD ret;
2064 DWORD dwLength = len * sizeof(WCHAR);
2066 ret = RegQueryValueExW(key, wszThreadingModel, NULL, &keytype, (LPBYTE)value, &dwLength);
2067 if ((ret != ERROR_SUCCESS) || (keytype != REG_SZ))
2068 value[0] = '\0';
2071 static HRESULT get_inproc_class_object(APARTMENT *apt, HKEY hkeydll,
2072 REFCLSID rclsid, REFIID riid, void **ppv)
2074 static const WCHAR wszApartment[] = {'A','p','a','r','t','m','e','n','t',0};
2075 static const WCHAR wszFree[] = {'F','r','e','e',0};
2076 static const WCHAR wszBoth[] = {'B','o','t','h',0};
2077 WCHAR dllpath[MAX_PATH+1];
2078 WCHAR threading_model[10 /* strlenW(L"apartment")+1 */];
2080 get_threading_model(hkeydll, threading_model, ARRAYSIZE(threading_model));
2081 /* "Apartment" */
2082 if (!strcmpiW(threading_model, wszApartment))
2084 if (apt->multi_threaded)
2085 return apartment_hostobject_in_hostapt(apt, FALSE, FALSE, hkeydll, rclsid, riid, ppv);
2087 /* "Free" */
2088 else if (!strcmpiW(threading_model, wszFree))
2090 if (!apt->multi_threaded)
2091 return apartment_hostobject_in_hostapt(apt, TRUE, FALSE, hkeydll, rclsid, riid, ppv);
2093 /* everything except "Apartment", "Free" and "Both" */
2094 else if (strcmpiW(threading_model, wszBoth))
2096 /* everything else is main-threaded */
2097 if (threading_model[0])
2098 FIXME("unrecognised threading model %s for object %s, should be main-threaded?\n",
2099 debugstr_w(threading_model), debugstr_guid(rclsid));
2101 if (apt->multi_threaded || !apt->main)
2102 return apartment_hostobject_in_hostapt(apt, FALSE, TRUE, hkeydll, rclsid, riid, ppv);
2105 if (COM_RegReadPath(hkeydll, NULL, NULL, dllpath, ARRAYSIZE(dllpath)) != ERROR_SUCCESS)
2107 /* failure: CLSID is not found in registry */
2108 WARN("class %s not registered inproc\n", debugstr_guid(rclsid));
2109 return REGDB_E_CLASSNOTREG;
2112 return apartment_getclassobject(apt, dllpath, rclsid, riid, ppv);
2115 /***********************************************************************
2116 * CoGetClassObject [OLE32.@]
2118 * Creates an object of the specified class.
2120 * PARAMS
2121 * rclsid [I] Class ID to create an instance of.
2122 * dwClsContext [I] Flags to restrict the location of the created instance.
2123 * pServerInfo [I] Optional. Details for connecting to a remote server.
2124 * iid [I] The ID of the interface of the instance to return.
2125 * ppv [O] On returns, contains a pointer to the specified interface of the object.
2127 * RETURNS
2128 * Success: S_OK
2129 * Failure: HRESULT code.
2131 * NOTES
2132 * The dwClsContext parameter can be one or more of the following:
2133 *| CLSCTX_INPROC_SERVER - Use an in-process server, such as from a DLL.
2134 *| CLSCTX_INPROC_HANDLER - Use an in-process object which handles certain functions for an object running in another process.
2135 *| CLSCTX_LOCAL_SERVER - Connect to an object running in another process.
2136 *| CLSCTX_REMOTE_SERVER - Connect to an object running on another machine.
2138 * SEE ALSO
2139 * CoCreateInstance()
2141 HRESULT WINAPI CoGetClassObject(
2142 REFCLSID rclsid, DWORD dwClsContext, COSERVERINFO *pServerInfo,
2143 REFIID iid, LPVOID *ppv)
2145 LPUNKNOWN regClassObject;
2146 HRESULT hres = E_UNEXPECTED;
2147 APARTMENT *apt;
2149 TRACE("\n\tCLSID:\t%s,\n\tIID:\t%s\n", debugstr_guid(rclsid), debugstr_guid(iid));
2151 if (!ppv)
2152 return E_INVALIDARG;
2154 *ppv = NULL;
2156 apt = COM_CurrentApt();
2157 if (!apt)
2159 ERR("apartment not initialised\n");
2160 return CO_E_NOTINITIALIZED;
2163 if (pServerInfo) {
2164 FIXME("\tpServerInfo: name=%s\n",debugstr_w(pServerInfo->pwszName));
2165 FIXME("\t\tpAuthInfo=%p\n",pServerInfo->pAuthInfo);
2169 * First, try and see if we can't match the class ID with one of the
2170 * registered classes.
2172 if (S_OK == COM_GetRegisteredClassObject(apt, rclsid, dwClsContext,
2173 &regClassObject))
2175 /* Get the required interface from the retrieved pointer. */
2176 hres = IUnknown_QueryInterface(regClassObject, iid, ppv);
2179 * Since QI got another reference on the pointer, we want to release the
2180 * one we already have. If QI was unsuccessful, this will release the object. This
2181 * is good since we are not returning it in the "out" parameter.
2183 IUnknown_Release(regClassObject);
2185 return hres;
2188 /* First try in-process server */
2189 if (CLSCTX_INPROC_SERVER & dwClsContext)
2191 static const WCHAR wszInprocServer32[] = {'I','n','p','r','o','c','S','e','r','v','e','r','3','2',0};
2192 HKEY hkey;
2194 if (IsEqualCLSID(rclsid, &CLSID_InProcFreeMarshaler))
2195 return FTMarshalCF_Create(iid, ppv);
2197 hres = COM_OpenKeyForCLSID(rclsid, wszInprocServer32, KEY_READ, &hkey);
2198 if (FAILED(hres))
2200 if (hres == REGDB_E_CLASSNOTREG)
2201 ERR("class %s not registered\n", debugstr_guid(rclsid));
2202 else if (hres == REGDB_E_KEYMISSING)
2204 WARN("class %s not registered as in-proc server\n", debugstr_guid(rclsid));
2205 hres = REGDB_E_CLASSNOTREG;
2209 if (SUCCEEDED(hres))
2211 hres = get_inproc_class_object(apt, hkey, rclsid, iid, ppv);
2212 RegCloseKey(hkey);
2215 /* return if we got a class, otherwise fall through to one of the
2216 * other types */
2217 if (SUCCEEDED(hres))
2218 return hres;
2221 /* Next try in-process handler */
2222 if (CLSCTX_INPROC_HANDLER & dwClsContext)
2224 static const WCHAR wszInprocHandler32[] = {'I','n','p','r','o','c','H','a','n','d','l','e','r','3','2',0};
2225 HKEY hkey;
2227 hres = COM_OpenKeyForCLSID(rclsid, wszInprocHandler32, KEY_READ, &hkey);
2228 if (FAILED(hres))
2230 if (hres == REGDB_E_CLASSNOTREG)
2231 ERR("class %s not registered\n", debugstr_guid(rclsid));
2232 else if (hres == REGDB_E_KEYMISSING)
2234 WARN("class %s not registered in-proc handler\n", debugstr_guid(rclsid));
2235 hres = REGDB_E_CLASSNOTREG;
2239 if (SUCCEEDED(hres))
2241 hres = get_inproc_class_object(apt, hkey, rclsid, iid, ppv);
2242 RegCloseKey(hkey);
2245 /* return if we got a class, otherwise fall through to one of the
2246 * other types */
2247 if (SUCCEEDED(hres))
2248 return hres;
2251 /* Next try out of process */
2252 if (CLSCTX_LOCAL_SERVER & dwClsContext)
2254 hres = RPC_GetLocalClassObject(rclsid,iid,ppv);
2255 if (SUCCEEDED(hres))
2256 return hres;
2259 /* Finally try remote: this requires networked DCOM (a lot of work) */
2260 if (CLSCTX_REMOTE_SERVER & dwClsContext)
2262 FIXME ("CLSCTX_REMOTE_SERVER not supported\n");
2263 hres = E_NOINTERFACE;
2266 if (FAILED(hres))
2267 ERR("no class object %s could be created for context 0x%x\n",
2268 debugstr_guid(rclsid), dwClsContext);
2269 return hres;
2272 /***********************************************************************
2273 * CoResumeClassObjects (OLE32.@)
2275 * Resumes all class objects registered with REGCLS_SUSPENDED.
2277 * RETURNS
2278 * Success: S_OK.
2279 * Failure: HRESULT code.
2281 HRESULT WINAPI CoResumeClassObjects(void)
2283 FIXME("stub\n");
2284 return S_OK;
2287 /***********************************************************************
2288 * CoCreateInstance [OLE32.@]
2290 * Creates an instance of the specified class.
2292 * PARAMS
2293 * rclsid [I] Class ID to create an instance of.
2294 * pUnkOuter [I] Optional outer unknown to allow aggregation with another object.
2295 * dwClsContext [I] Flags to restrict the location of the created instance.
2296 * iid [I] The ID of the interface of the instance to return.
2297 * ppv [O] On returns, contains a pointer to the specified interface of the instance.
2299 * RETURNS
2300 * Success: S_OK
2301 * Failure: HRESULT code.
2303 * NOTES
2304 * The dwClsContext parameter can be one or more of the following:
2305 *| CLSCTX_INPROC_SERVER - Use an in-process server, such as from a DLL.
2306 *| CLSCTX_INPROC_HANDLER - Use an in-process object which handles certain functions for an object running in another process.
2307 *| CLSCTX_LOCAL_SERVER - Connect to an object running in another process.
2308 *| CLSCTX_REMOTE_SERVER - Connect to an object running on another machine.
2310 * Aggregation is the concept of deferring the IUnknown of an object to another
2311 * object. This allows a separate object to behave as though it was part of
2312 * the object and to allow this the pUnkOuter parameter can be set. Note that
2313 * not all objects support having an outer of unknown.
2315 * SEE ALSO
2316 * CoGetClassObject()
2318 HRESULT WINAPI CoCreateInstance(
2319 REFCLSID rclsid,
2320 LPUNKNOWN pUnkOuter,
2321 DWORD dwClsContext,
2322 REFIID iid,
2323 LPVOID *ppv)
2325 HRESULT hres;
2326 LPCLASSFACTORY lpclf = 0;
2328 TRACE("(rclsid=%s, pUnkOuter=%p, dwClsContext=%08x, riid=%s, ppv=%p)\n", debugstr_guid(rclsid),
2329 pUnkOuter, dwClsContext, debugstr_guid(iid), ppv);
2332 * Sanity check
2334 if (ppv==0)
2335 return E_POINTER;
2338 * Initialize the "out" parameter
2340 *ppv = 0;
2342 if (!COM_CurrentApt())
2344 ERR("apartment not initialised\n");
2345 return CO_E_NOTINITIALIZED;
2349 * The Standard Global Interface Table (GIT) object is a process-wide singleton.
2350 * Rather than create a class factory, we can just check for it here
2352 if (IsEqualIID(rclsid, &CLSID_StdGlobalInterfaceTable)) {
2353 if (StdGlobalInterfaceTableInstance == NULL)
2354 StdGlobalInterfaceTableInstance = StdGlobalInterfaceTable_Construct();
2355 hres = IGlobalInterfaceTable_QueryInterface( (IGlobalInterfaceTable*) StdGlobalInterfaceTableInstance, iid, ppv);
2356 if (hres) return hres;
2358 TRACE("Retrieved GIT (%p)\n", *ppv);
2359 return S_OK;
2363 * Get a class factory to construct the object we want.
2365 hres = CoGetClassObject(rclsid,
2366 dwClsContext,
2367 NULL,
2368 &IID_IClassFactory,
2369 (LPVOID)&lpclf);
2371 if (FAILED(hres))
2372 return hres;
2375 * Create the object and don't forget to release the factory
2377 hres = IClassFactory_CreateInstance(lpclf, pUnkOuter, iid, ppv);
2378 IClassFactory_Release(lpclf);
2379 if(FAILED(hres))
2380 FIXME("no instance created for interface %s of class %s, hres is 0x%08x\n",
2381 debugstr_guid(iid), debugstr_guid(rclsid),hres);
2383 return hres;
2386 /***********************************************************************
2387 * CoCreateInstanceEx [OLE32.@]
2389 HRESULT WINAPI CoCreateInstanceEx(
2390 REFCLSID rclsid,
2391 LPUNKNOWN pUnkOuter,
2392 DWORD dwClsContext,
2393 COSERVERINFO* pServerInfo,
2394 ULONG cmq,
2395 MULTI_QI* pResults)
2397 IUnknown* pUnk = NULL;
2398 HRESULT hr;
2399 ULONG index;
2400 ULONG successCount = 0;
2403 * Sanity check
2405 if ( (cmq==0) || (pResults==NULL))
2406 return E_INVALIDARG;
2408 if (pServerInfo!=NULL)
2409 FIXME("() non-NULL pServerInfo not supported!\n");
2412 * Initialize all the "out" parameters.
2414 for (index = 0; index < cmq; index++)
2416 pResults[index].pItf = NULL;
2417 pResults[index].hr = E_NOINTERFACE;
2421 * Get the object and get its IUnknown pointer.
2423 hr = CoCreateInstance(rclsid,
2424 pUnkOuter,
2425 dwClsContext,
2426 &IID_IUnknown,
2427 (VOID**)&pUnk);
2429 if (hr)
2430 return hr;
2433 * Then, query for all the interfaces requested.
2435 for (index = 0; index < cmq; index++)
2437 pResults[index].hr = IUnknown_QueryInterface(pUnk,
2438 pResults[index].pIID,
2439 (VOID**)&(pResults[index].pItf));
2441 if (pResults[index].hr == S_OK)
2442 successCount++;
2446 * Release our temporary unknown pointer.
2448 IUnknown_Release(pUnk);
2450 if (successCount == 0)
2451 return E_NOINTERFACE;
2453 if (successCount!=cmq)
2454 return CO_S_NOTALLINTERFACES;
2456 return S_OK;
2459 /***********************************************************************
2460 * CoLoadLibrary (OLE32.@)
2462 * Loads a library.
2464 * PARAMS
2465 * lpszLibName [I] Path to library.
2466 * bAutoFree [I] Whether the library should automatically be freed.
2468 * RETURNS
2469 * Success: Handle to loaded library.
2470 * Failure: NULL.
2472 * SEE ALSO
2473 * CoFreeLibrary, CoFreeAllLibraries, CoFreeUnusedLibraries
2475 HINSTANCE WINAPI CoLoadLibrary(LPOLESTR lpszLibName, BOOL bAutoFree)
2477 TRACE("(%s, %d)\n", debugstr_w(lpszLibName), bAutoFree);
2479 return LoadLibraryExW(lpszLibName, 0, LOAD_WITH_ALTERED_SEARCH_PATH);
2482 /***********************************************************************
2483 * CoFreeLibrary [OLE32.@]
2485 * Unloads a library from memory.
2487 * PARAMS
2488 * hLibrary [I] Handle to library to unload.
2490 * RETURNS
2491 * Nothing
2493 * SEE ALSO
2494 * CoLoadLibrary, CoFreeAllLibraries, CoFreeUnusedLibraries
2496 void WINAPI CoFreeLibrary(HINSTANCE hLibrary)
2498 FreeLibrary(hLibrary);
2502 /***********************************************************************
2503 * CoFreeAllLibraries [OLE32.@]
2505 * Function for backwards compatibility only. Does nothing.
2507 * RETURNS
2508 * Nothing.
2510 * SEE ALSO
2511 * CoLoadLibrary, CoFreeLibrary, CoFreeUnusedLibraries
2513 void WINAPI CoFreeAllLibraries(void)
2515 /* NOP */
2519 /***********************************************************************
2520 * CoFreeUnusedLibraries [OLE32.@]
2521 * CoFreeUnusedLibraries [COMPOBJ.17]
2523 * Frees any unused libraries. Unused are identified as those that return
2524 * S_OK from their DllCanUnloadNow function.
2526 * RETURNS
2527 * Nothing.
2529 * SEE ALSO
2530 * CoLoadLibrary, CoFreeAllLibraries, CoFreeLibrary
2532 void WINAPI CoFreeUnusedLibraries(void)
2534 struct apartment *apt = COM_CurrentApt();
2535 if (!apt)
2537 ERR("apartment not initialised\n");
2538 return;
2541 apartment_freeunusedlibraries(apt);
2544 /***********************************************************************
2545 * CoFileTimeNow [OLE32.@]
2546 * CoFileTimeNow [COMPOBJ.82]
2548 * Retrieves the current time in FILETIME format.
2550 * PARAMS
2551 * lpFileTime [O] The current time.
2553 * RETURNS
2554 * S_OK.
2556 HRESULT WINAPI CoFileTimeNow( FILETIME *lpFileTime )
2558 GetSystemTimeAsFileTime( lpFileTime );
2559 return S_OK;
2562 /******************************************************************************
2563 * CoLockObjectExternal [OLE32.@]
2565 * Increments or decrements the external reference count of a stub object.
2567 * PARAMS
2568 * pUnk [I] Stub object.
2569 * fLock [I] If TRUE then increments the external ref-count,
2570 * otherwise decrements.
2571 * fLastUnlockReleases [I] If TRUE then the last unlock has the effect of
2572 * calling CoDisconnectObject.
2574 * RETURNS
2575 * Success: S_OK.
2576 * Failure: HRESULT code.
2578 * NOTES
2579 * If fLock is TRUE and an object is passed in that doesn't have a stub
2580 * manager then a new stub manager is created for the object.
2582 HRESULT WINAPI CoLockObjectExternal(
2583 LPUNKNOWN pUnk,
2584 BOOL fLock,
2585 BOOL fLastUnlockReleases)
2587 struct stub_manager *stubmgr;
2588 struct apartment *apt;
2590 TRACE("pUnk=%p, fLock=%s, fLastUnlockReleases=%s\n",
2591 pUnk, fLock ? "TRUE" : "FALSE", fLastUnlockReleases ? "TRUE" : "FALSE");
2593 apt = COM_CurrentApt();
2594 if (!apt) return CO_E_NOTINITIALIZED;
2596 stubmgr = get_stub_manager_from_object(apt, pUnk);
2598 if (stubmgr)
2600 if (fLock)
2601 stub_manager_ext_addref(stubmgr, 1);
2602 else
2603 stub_manager_ext_release(stubmgr, 1, fLastUnlockReleases);
2605 stub_manager_int_release(stubmgr);
2607 return S_OK;
2609 else if (fLock)
2611 stubmgr = new_stub_manager(apt, pUnk);
2613 if (stubmgr)
2615 stub_manager_ext_addref(stubmgr, 1);
2616 stub_manager_int_release(stubmgr);
2619 return S_OK;
2621 else
2623 WARN("stub object not found %p\n", pUnk);
2624 /* Note: native is pretty broken here because it just silently
2625 * fails, without returning an appropriate error code, making apps
2626 * think that the object was disconnected, when it actually wasn't */
2627 return S_OK;
2631 /***********************************************************************
2632 * CoInitializeWOW (OLE32.@)
2634 * WOW equivalent of CoInitialize?
2636 * PARAMS
2637 * x [I] Unknown.
2638 * y [I] Unknown.
2640 * RETURNS
2641 * Unknown.
2643 HRESULT WINAPI CoInitializeWOW(DWORD x,DWORD y)
2645 FIXME("(0x%08x,0x%08x),stub!\n",x,y);
2646 return 0;
2649 /***********************************************************************
2650 * CoGetState [OLE32.@]
2652 * Retrieves the thread state object previously stored by CoSetState().
2654 * PARAMS
2655 * ppv [I] Address where pointer to object will be stored.
2657 * RETURNS
2658 * Success: S_OK.
2659 * Failure: E_OUTOFMEMORY.
2661 * NOTES
2662 * Crashes on all invalid ppv addresses, including NULL.
2663 * If the function returns a non-NULL object then the caller must release its
2664 * reference on the object when the object is no longer required.
2666 * SEE ALSO
2667 * CoSetState().
2669 HRESULT WINAPI CoGetState(IUnknown ** ppv)
2671 struct oletls *info = COM_CurrentInfo();
2672 if (!info) return E_OUTOFMEMORY;
2674 *ppv = NULL;
2676 if (info->state)
2678 IUnknown_AddRef(info->state);
2679 *ppv = info->state;
2680 TRACE("apt->state=%p\n", info->state);
2683 return S_OK;
2686 /***********************************************************************
2687 * CoSetState [OLE32.@]
2689 * Sets the thread state object.
2691 * PARAMS
2692 * pv [I] Pointer to state object to be stored.
2694 * NOTES
2695 * The system keeps a reference on the object while the object stored.
2697 * RETURNS
2698 * Success: S_OK.
2699 * Failure: E_OUTOFMEMORY.
2701 HRESULT WINAPI CoSetState(IUnknown * pv)
2703 struct oletls *info = COM_CurrentInfo();
2704 if (!info) return E_OUTOFMEMORY;
2706 if (pv) IUnknown_AddRef(pv);
2708 if (info->state)
2710 TRACE("-- release %p now\n", info->state);
2711 IUnknown_Release(info->state);
2714 info->state = pv;
2716 return S_OK;
2720 /******************************************************************************
2721 * CoTreatAsClass [OLE32.@]
2723 * Sets the TreatAs value of a class.
2725 * PARAMS
2726 * clsidOld [I] Class to set TreatAs value on.
2727 * clsidNew [I] The class the clsidOld should be treated as.
2729 * RETURNS
2730 * Success: S_OK.
2731 * Failure: HRESULT code.
2733 * SEE ALSO
2734 * CoGetTreatAsClass
2736 HRESULT WINAPI CoTreatAsClass(REFCLSID clsidOld, REFCLSID clsidNew)
2738 static const WCHAR wszAutoTreatAs[] = {'A','u','t','o','T','r','e','a','t','A','s',0};
2739 static const WCHAR wszTreatAs[] = {'T','r','e','a','t','A','s',0};
2740 HKEY hkey = NULL;
2741 WCHAR szClsidNew[CHARS_IN_GUID];
2742 HRESULT res = S_OK;
2743 WCHAR auto_treat_as[CHARS_IN_GUID];
2744 LONG auto_treat_as_size = sizeof(auto_treat_as);
2745 CLSID id;
2747 res = COM_OpenKeyForCLSID(clsidOld, NULL, KEY_READ | KEY_WRITE, &hkey);
2748 if (FAILED(res))
2749 goto done;
2750 if (!memcmp( clsidOld, clsidNew, sizeof(*clsidOld) ))
2752 if (!RegQueryValueW(hkey, wszAutoTreatAs, auto_treat_as, &auto_treat_as_size) &&
2753 !CLSIDFromString(auto_treat_as, &id))
2755 if (RegSetValueW(hkey, wszTreatAs, REG_SZ, auto_treat_as, sizeof(auto_treat_as)))
2757 res = REGDB_E_WRITEREGDB;
2758 goto done;
2761 else
2763 RegDeleteKeyW(hkey, wszTreatAs);
2764 goto done;
2767 else if (!StringFromGUID2(clsidNew, szClsidNew, ARRAYSIZE(szClsidNew)) &&
2768 !RegSetValueW(hkey, wszTreatAs, REG_SZ, szClsidNew, sizeof(szClsidNew)))
2770 res = REGDB_E_WRITEREGDB;
2771 goto done;
2774 done:
2775 if (hkey) RegCloseKey(hkey);
2776 return res;
2779 /******************************************************************************
2780 * CoGetTreatAsClass [OLE32.@]
2782 * Gets the TreatAs value of a class.
2784 * PARAMS
2785 * clsidOld [I] Class to get the TreatAs value of.
2786 * clsidNew [I] The class the clsidOld should be treated as.
2788 * RETURNS
2789 * Success: S_OK.
2790 * Failure: HRESULT code.
2792 * SEE ALSO
2793 * CoSetTreatAsClass
2795 HRESULT WINAPI CoGetTreatAsClass(REFCLSID clsidOld, LPCLSID clsidNew)
2797 static const WCHAR wszTreatAs[] = {'T','r','e','a','t','A','s',0};
2798 HKEY hkey = NULL;
2799 WCHAR szClsidNew[CHARS_IN_GUID];
2800 HRESULT res = S_OK;
2801 LONG len = sizeof(szClsidNew);
2803 FIXME("(%s,%p)\n", debugstr_guid(clsidOld), clsidNew);
2804 memcpy(clsidNew,clsidOld,sizeof(CLSID)); /* copy over old value */
2806 res = COM_OpenKeyForCLSID(clsidOld, wszTreatAs, KEY_READ, &hkey);
2807 if (FAILED(res))
2808 goto done;
2809 if (RegQueryValueW(hkey, NULL, szClsidNew, &len))
2811 res = S_FALSE;
2812 goto done;
2814 res = CLSIDFromString(szClsidNew,clsidNew);
2815 if (FAILED(res))
2816 ERR("Failed CLSIDFromStringA(%s), hres 0x%08x\n", debugstr_w(szClsidNew), res);
2817 done:
2818 if (hkey) RegCloseKey(hkey);
2819 return res;
2822 /******************************************************************************
2823 * CoGetCurrentProcess [OLE32.@]
2824 * CoGetCurrentProcess [COMPOBJ.34]
2826 * Gets the current process ID.
2828 * RETURNS
2829 * The current process ID.
2831 * NOTES
2832 * Is DWORD really the correct return type for this function?
2834 DWORD WINAPI CoGetCurrentProcess(void)
2836 return GetCurrentProcessId();
2839 /******************************************************************************
2840 * CoRegisterMessageFilter [OLE32.@]
2842 * Registers a message filter.
2844 * PARAMS
2845 * lpMessageFilter [I] Pointer to interface.
2846 * lplpMessageFilter [O] Indirect pointer to prior instance if non-NULL.
2848 * RETURNS
2849 * Success: S_OK.
2850 * Failure: HRESULT code.
2852 * NOTES
2853 * Both lpMessageFilter and lplpMessageFilter are optional. Passing in a NULL
2854 * lpMessageFilter removes the message filter.
2856 * If lplpMessageFilter is not NULL the previous message filter will be
2857 * returned in the memory pointer to this parameter and the caller is
2858 * responsible for releasing the object.
2860 * The current thread be in an apartment otherwise the function will crash.
2862 HRESULT WINAPI CoRegisterMessageFilter(
2863 LPMESSAGEFILTER lpMessageFilter,
2864 LPMESSAGEFILTER *lplpMessageFilter)
2866 struct apartment *apt;
2867 IMessageFilter *lpOldMessageFilter;
2869 TRACE("(%p, %p)\n", lpMessageFilter, lplpMessageFilter);
2871 apt = COM_CurrentApt();
2873 /* can't set a message filter in a multi-threaded apartment */
2874 if (!apt || apt->multi_threaded)
2876 WARN("can't set message filter in MTA or uninitialized apt\n");
2877 return CO_E_NOT_SUPPORTED;
2880 if (lpMessageFilter)
2881 IMessageFilter_AddRef(lpMessageFilter);
2883 EnterCriticalSection(&apt->cs);
2885 lpOldMessageFilter = apt->filter;
2886 apt->filter = lpMessageFilter;
2888 LeaveCriticalSection(&apt->cs);
2890 if (lplpMessageFilter)
2891 *lplpMessageFilter = lpOldMessageFilter;
2892 else if (lpOldMessageFilter)
2893 IMessageFilter_Release(lpOldMessageFilter);
2895 return S_OK;
2898 /***********************************************************************
2899 * CoIsOle1Class [OLE32.@]
2901 * Determines whether the specified class an OLE v1 class.
2903 * PARAMS
2904 * clsid [I] Class to test.
2906 * RETURNS
2907 * TRUE if the class is an OLE v1 class, or FALSE otherwise.
2909 BOOL WINAPI CoIsOle1Class(REFCLSID clsid)
2911 FIXME("%s\n", debugstr_guid(clsid));
2912 return FALSE;
2915 /***********************************************************************
2916 * IsEqualGUID [OLE32.@]
2918 * Compares two Unique Identifiers.
2920 * PARAMS
2921 * rguid1 [I] The first GUID to compare.
2922 * rguid2 [I] The other GUID to compare.
2924 * RETURNS
2925 * TRUE if equal
2927 #undef IsEqualGUID
2928 BOOL WINAPI IsEqualGUID(
2929 REFGUID rguid1,
2930 REFGUID rguid2)
2932 return !memcmp(rguid1,rguid2,sizeof(GUID));
2935 /***********************************************************************
2936 * CoInitializeSecurity [OLE32.@]
2938 HRESULT WINAPI CoInitializeSecurity(PSECURITY_DESCRIPTOR pSecDesc, LONG cAuthSvc,
2939 SOLE_AUTHENTICATION_SERVICE* asAuthSvc,
2940 void* pReserved1, DWORD dwAuthnLevel,
2941 DWORD dwImpLevel, void* pReserved2,
2942 DWORD dwCapabilities, void* pReserved3)
2944 FIXME("(%p,%d,%p,%p,%d,%d,%p,%d,%p) - stub!\n", pSecDesc, cAuthSvc,
2945 asAuthSvc, pReserved1, dwAuthnLevel, dwImpLevel, pReserved2,
2946 dwCapabilities, pReserved3);
2947 return S_OK;
2950 /***********************************************************************
2951 * CoSuspendClassObjects [OLE32.@]
2953 * Suspends all registered class objects to prevent further requests coming in
2954 * for those objects.
2956 * RETURNS
2957 * Success: S_OK.
2958 * Failure: HRESULT code.
2960 HRESULT WINAPI CoSuspendClassObjects(void)
2962 FIXME("\n");
2963 return S_OK;
2966 /***********************************************************************
2967 * CoAddRefServerProcess [OLE32.@]
2969 * Helper function for incrementing the reference count of a local-server
2970 * process.
2972 * RETURNS
2973 * New reference count.
2975 * SEE ALSO
2976 * CoReleaseServerProcess().
2978 ULONG WINAPI CoAddRefServerProcess(void)
2980 ULONG refs;
2982 TRACE("\n");
2984 EnterCriticalSection(&csRegisteredClassList);
2985 refs = ++s_COMServerProcessReferences;
2986 LeaveCriticalSection(&csRegisteredClassList);
2988 TRACE("refs before: %d\n", refs - 1);
2990 return refs;
2993 /***********************************************************************
2994 * CoReleaseServerProcess [OLE32.@]
2996 * Helper function for decrementing the reference count of a local-server
2997 * process.
2999 * RETURNS
3000 * New reference count.
3002 * NOTES
3003 * When reference count reaches 0, this function suspends all registered
3004 * classes so no new connections are accepted.
3006 * SEE ALSO
3007 * CoAddRefServerProcess(), CoSuspendClassObjects().
3009 ULONG WINAPI CoReleaseServerProcess(void)
3011 ULONG refs;
3013 TRACE("\n");
3015 EnterCriticalSection(&csRegisteredClassList);
3017 refs = --s_COMServerProcessReferences;
3018 /* FIXME: if (!refs) COM_SuspendClassObjects(); */
3020 LeaveCriticalSection(&csRegisteredClassList);
3022 TRACE("refs after: %d\n", refs);
3024 return refs;
3027 /***********************************************************************
3028 * CoIsHandlerConnected [OLE32.@]
3030 * Determines whether a proxy is connected to a remote stub.
3032 * PARAMS
3033 * pUnk [I] Pointer to object that may or may not be connected.
3035 * RETURNS
3036 * TRUE if pUnk is not a proxy or if pUnk is connected to a remote stub, or
3037 * FALSE otherwise.
3039 BOOL WINAPI CoIsHandlerConnected(IUnknown *pUnk)
3041 FIXME("%p\n", pUnk);
3043 return TRUE;
3046 /***********************************************************************
3047 * CoAllowSetForegroundWindow [OLE32.@]
3050 HRESULT WINAPI CoAllowSetForegroundWindow(IUnknown *pUnk, void *pvReserved)
3052 FIXME("(%p, %p): stub\n", pUnk, pvReserved);
3053 return S_OK;
3056 /***********************************************************************
3057 * CoQueryProxyBlanket [OLE32.@]
3059 * Retrieves the security settings being used by a proxy.
3061 * PARAMS
3062 * pProxy [I] Pointer to the proxy object.
3063 * pAuthnSvc [O] The type of authentication service.
3064 * pAuthzSvc [O] The type of authorization service.
3065 * ppServerPrincName [O] Optional. The server prinicple name.
3066 * pAuthnLevel [O] The authentication level.
3067 * pImpLevel [O] The impersonation level.
3068 * ppAuthInfo [O] Information specific to the authorization/authentication service.
3069 * pCapabilities [O] Flags affecting the security behaviour.
3071 * RETURNS
3072 * Success: S_OK.
3073 * Failure: HRESULT code.
3075 * SEE ALSO
3076 * CoCopyProxy, CoSetProxyBlanket.
3078 HRESULT WINAPI CoQueryProxyBlanket(IUnknown *pProxy, DWORD *pAuthnSvc,
3079 DWORD *pAuthzSvc, OLECHAR **ppServerPrincName, DWORD *pAuthnLevel,
3080 DWORD *pImpLevel, void **ppAuthInfo, DWORD *pCapabilities)
3082 IClientSecurity *pCliSec;
3083 HRESULT hr;
3085 TRACE("%p\n", pProxy);
3087 hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
3088 if (SUCCEEDED(hr))
3090 hr = IClientSecurity_QueryBlanket(pCliSec, pProxy, pAuthnSvc,
3091 pAuthzSvc, ppServerPrincName,
3092 pAuthnLevel, pImpLevel, ppAuthInfo,
3093 pCapabilities);
3094 IClientSecurity_Release(pCliSec);
3097 if (FAILED(hr)) ERR("-- failed with 0x%08x\n", hr);
3098 return hr;
3101 /***********************************************************************
3102 * CoSetProxyBlanket [OLE32.@]
3104 * Sets the security settings for a proxy.
3106 * PARAMS
3107 * pProxy [I] Pointer to the proxy object.
3108 * AuthnSvc [I] The type of authentication service.
3109 * AuthzSvc [I] The type of authorization service.
3110 * pServerPrincName [I] The server prinicple name.
3111 * AuthnLevel [I] The authentication level.
3112 * ImpLevel [I] The impersonation level.
3113 * pAuthInfo [I] Information specific to the authorization/authentication service.
3114 * Capabilities [I] Flags affecting the security behaviour.
3116 * RETURNS
3117 * Success: S_OK.
3118 * Failure: HRESULT code.
3120 * SEE ALSO
3121 * CoQueryProxyBlanket, CoCopyProxy.
3123 HRESULT WINAPI CoSetProxyBlanket(IUnknown *pProxy, DWORD AuthnSvc,
3124 DWORD AuthzSvc, OLECHAR *pServerPrincName, DWORD AuthnLevel,
3125 DWORD ImpLevel, void *pAuthInfo, DWORD Capabilities)
3127 IClientSecurity *pCliSec;
3128 HRESULT hr;
3130 TRACE("%p\n", pProxy);
3132 hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
3133 if (SUCCEEDED(hr))
3135 hr = IClientSecurity_SetBlanket(pCliSec, pProxy, AuthnSvc,
3136 AuthzSvc, pServerPrincName,
3137 AuthnLevel, ImpLevel, pAuthInfo,
3138 Capabilities);
3139 IClientSecurity_Release(pCliSec);
3142 if (FAILED(hr)) ERR("-- failed with 0x%08x\n", hr);
3143 return hr;
3146 /***********************************************************************
3147 * CoCopyProxy [OLE32.@]
3149 * Copies a proxy.
3151 * PARAMS
3152 * pProxy [I] Pointer to the proxy object.
3153 * ppCopy [O] Copy of the proxy.
3155 * RETURNS
3156 * Success: S_OK.
3157 * Failure: HRESULT code.
3159 * SEE ALSO
3160 * CoQueryProxyBlanket, CoSetProxyBlanket.
3162 HRESULT WINAPI CoCopyProxy(IUnknown *pProxy, IUnknown **ppCopy)
3164 IClientSecurity *pCliSec;
3165 HRESULT hr;
3167 TRACE("%p\n", pProxy);
3169 hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
3170 if (SUCCEEDED(hr))
3172 hr = IClientSecurity_CopyProxy(pCliSec, pProxy, ppCopy);
3173 IClientSecurity_Release(pCliSec);
3176 if (FAILED(hr)) ERR("-- failed with 0x%08x\n", hr);
3177 return hr;
3181 /***********************************************************************
3182 * CoGetCallContext [OLE32.@]
3184 * Gets the context of the currently executing server call in the current
3185 * thread.
3187 * PARAMS
3188 * riid [I] Context interface to return.
3189 * ppv [O] Pointer to memory that will receive the context on return.
3191 * RETURNS
3192 * Success: S_OK.
3193 * Failure: HRESULT code.
3195 HRESULT WINAPI CoGetCallContext(REFIID riid, void **ppv)
3197 FIXME("(%s, %p): stub\n", debugstr_guid(riid), ppv);
3199 *ppv = NULL;
3200 return E_NOINTERFACE;
3203 /***********************************************************************
3204 * CoQueryClientBlanket [OLE32.@]
3206 * Retrieves the authentication information about the client of the currently
3207 * executing server call in the current thread.
3209 * PARAMS
3210 * pAuthnSvc [O] Optional. The type of authentication service.
3211 * pAuthzSvc [O] Optional. The type of authorization service.
3212 * pServerPrincName [O] Optional. The server prinicple name.
3213 * pAuthnLevel [O] Optional. The authentication level.
3214 * pImpLevel [O] Optional. The impersonation level.
3215 * pPrivs [O] Optional. Information about the privileges of the client.
3216 * pCapabilities [IO] Optional. Flags affecting the security behaviour.
3218 * RETURNS
3219 * Success: S_OK.
3220 * Failure: HRESULT code.
3222 * SEE ALSO
3223 * CoImpersonateClient, CoRevertToSelf, CoGetCallContext.
3225 HRESULT WINAPI CoQueryClientBlanket(
3226 DWORD *pAuthnSvc,
3227 DWORD *pAuthzSvc,
3228 OLECHAR **pServerPrincName,
3229 DWORD *pAuthnLevel,
3230 DWORD *pImpLevel,
3231 RPC_AUTHZ_HANDLE *pPrivs,
3232 DWORD *pCapabilities)
3234 IServerSecurity *pSrvSec;
3235 HRESULT hr;
3237 TRACE("(%p, %p, %p, %p, %p, %p, %p)\n",
3238 pAuthnSvc, pAuthzSvc, pServerPrincName, pAuthnLevel, pImpLevel,
3239 pPrivs, pCapabilities);
3241 hr = CoGetCallContext(&IID_IServerSecurity, (void **)&pSrvSec);
3242 if (SUCCEEDED(hr))
3244 hr = IServerSecurity_QueryBlanket(
3245 pSrvSec, pAuthnSvc, pAuthzSvc, pServerPrincName, pAuthnLevel,
3246 pImpLevel, pPrivs, pCapabilities);
3247 IServerSecurity_Release(pSrvSec);
3250 return hr;
3253 /***********************************************************************
3254 * CoImpersonateClient [OLE32.@]
3256 * Impersonates the client of the currently executing server call in the
3257 * current thread.
3259 * PARAMS
3260 * None.
3262 * RETURNS
3263 * Success: S_OK.
3264 * Failure: HRESULT code.
3266 * NOTES
3267 * If this function fails then the current thread will not be impersonating
3268 * the client and all actions will take place on behalf of the server.
3269 * Therefore, it is important to check the return value from this function.
3271 * SEE ALSO
3272 * CoRevertToSelf, CoQueryClientBlanket, CoGetCallContext.
3274 HRESULT WINAPI CoImpersonateClient(void)
3276 IServerSecurity *pSrvSec;
3277 HRESULT hr;
3279 TRACE("\n");
3281 hr = CoGetCallContext(&IID_IServerSecurity, (void **)&pSrvSec);
3282 if (SUCCEEDED(hr))
3284 hr = IServerSecurity_ImpersonateClient(pSrvSec);
3285 IServerSecurity_Release(pSrvSec);
3288 return hr;
3291 /***********************************************************************
3292 * CoRevertToSelf [OLE32.@]
3294 * Ends the impersonation of the client of the currently executing server
3295 * call in the current thread.
3297 * PARAMS
3298 * None.
3300 * RETURNS
3301 * Success: S_OK.
3302 * Failure: HRESULT code.
3304 * SEE ALSO
3305 * CoImpersonateClient, CoQueryClientBlanket, CoGetCallContext.
3307 HRESULT WINAPI CoRevertToSelf(void)
3309 IServerSecurity *pSrvSec;
3310 HRESULT hr;
3312 TRACE("\n");
3314 hr = CoGetCallContext(&IID_IServerSecurity, (void **)&pSrvSec);
3315 if (SUCCEEDED(hr))
3317 hr = IServerSecurity_RevertToSelf(pSrvSec);
3318 IServerSecurity_Release(pSrvSec);
3321 return hr;
3324 static BOOL COM_PeekMessage(struct apartment *apt, MSG *msg)
3326 /* first try to retrieve messages for incoming COM calls to the apartment window */
3327 return PeekMessageW(msg, apt->win, WM_USER, WM_APP - 1, PM_REMOVE|PM_NOYIELD) ||
3328 /* next retrieve other messages necessary for the app to remain responsive */
3329 PeekMessageW(msg, NULL, 0, 0, PM_QS_PAINT|PM_QS_POSTMESSAGE|PM_REMOVE|PM_NOYIELD);
3332 /***********************************************************************
3333 * CoWaitForMultipleHandles [OLE32.@]
3335 * Waits for one or more handles to become signaled.
3337 * PARAMS
3338 * dwFlags [I] Flags. See notes.
3339 * dwTimeout [I] Timeout in milliseconds.
3340 * cHandles [I] Number of handles pointed to by pHandles.
3341 * pHandles [I] Handles to wait for.
3342 * lpdwindex [O] Index of handle that was signaled.
3344 * RETURNS
3345 * Success: S_OK.
3346 * Failure: RPC_S_CALLPENDING on timeout.
3348 * NOTES
3350 * The dwFlags parameter can be zero or more of the following:
3351 *| COWAIT_WAITALL - Wait for all of the handles to become signaled.
3352 *| COWAIT_ALERTABLE - Allows a queued APC to run during the wait.
3354 * SEE ALSO
3355 * MsgWaitForMultipleObjects, WaitForMultipleObjects.
3357 HRESULT WINAPI CoWaitForMultipleHandles(DWORD dwFlags, DWORD dwTimeout,
3358 ULONG cHandles, LPHANDLE pHandles, LPDWORD lpdwindex)
3360 HRESULT hr = S_OK;
3361 DWORD start_time = GetTickCount();
3362 APARTMENT *apt = COM_CurrentApt();
3363 BOOL message_loop = apt && !apt->multi_threaded;
3365 TRACE("(0x%08x, 0x%08x, %d, %p, %p)\n", dwFlags, dwTimeout, cHandles,
3366 pHandles, lpdwindex);
3368 while (TRUE)
3370 DWORD now = GetTickCount();
3371 DWORD res;
3373 if ((dwTimeout != INFINITE) && (start_time + dwTimeout >= now))
3375 hr = RPC_S_CALLPENDING;
3376 break;
3379 if (message_loop)
3381 DWORD wait_flags = (dwFlags & COWAIT_WAITALL) ? MWMO_WAITALL : 0 |
3382 (dwFlags & COWAIT_ALERTABLE ) ? MWMO_ALERTABLE : 0;
3384 TRACE("waiting for rpc completion or window message\n");
3386 res = MsgWaitForMultipleObjectsEx(cHandles, pHandles,
3387 (dwTimeout == INFINITE) ? INFINITE : start_time + dwTimeout - now,
3388 QS_ALLINPUT, wait_flags);
3390 if (res == WAIT_OBJECT_0 + cHandles) /* messages available */
3392 MSG msg;
3394 /* call message filter */
3396 if (COM_CurrentApt()->filter)
3398 PENDINGTYPE pendingtype =
3399 COM_CurrentInfo()->pending_call_count_server ?
3400 PENDINGTYPE_NESTED : PENDINGTYPE_TOPLEVEL;
3401 DWORD be_handled = IMessageFilter_MessagePending(
3402 COM_CurrentApt()->filter, 0 /* FIXME */,
3403 now - start_time, pendingtype);
3404 TRACE("IMessageFilter_MessagePending returned %d\n", be_handled);
3405 switch (be_handled)
3407 case PENDINGMSG_CANCELCALL:
3408 WARN("call canceled\n");
3409 hr = RPC_E_CALL_CANCELED;
3410 break;
3411 case PENDINGMSG_WAITNOPROCESS:
3412 case PENDINGMSG_WAITDEFPROCESS:
3413 default:
3414 /* FIXME: MSDN is very vague about the difference
3415 * between WAITNOPROCESS and WAITDEFPROCESS - there
3416 * appears to be none, so it is possibly a left-over
3417 * from the 16-bit world. */
3418 break;
3422 /* note: using "if" here instead of "while" might seem less
3423 * efficient, but only if we are optimising for quick delivery
3424 * of pending messages, rather than quick completion of the
3425 * COM call */
3426 if (COM_PeekMessage(apt, &msg))
3428 TRACE("received message whilst waiting for RPC: 0x%04x\n", msg.message);
3429 TranslateMessage(&msg);
3430 DispatchMessageW(&msg);
3431 if (msg.message == WM_QUIT)
3433 TRACE("resending WM_QUIT to outer message loop\n");
3434 PostQuitMessage(msg.wParam);
3435 /* no longer need to process messages */
3436 message_loop = FALSE;
3439 continue;
3442 else
3444 TRACE("waiting for rpc completion\n");
3446 res = WaitForMultipleObjectsEx(cHandles, pHandles,
3447 (dwFlags & COWAIT_WAITALL) ? TRUE : FALSE,
3448 (dwTimeout == INFINITE) ? INFINITE : start_time + dwTimeout - now,
3449 (dwFlags & COWAIT_ALERTABLE) ? TRUE : FALSE);
3452 if ((res >= WAIT_OBJECT_0) && (res < WAIT_OBJECT_0 + cHandles))
3454 /* handle signaled, store index */
3455 *lpdwindex = (res - WAIT_OBJECT_0);
3456 break;
3458 else if (res == WAIT_TIMEOUT)
3460 hr = RPC_S_CALLPENDING;
3461 break;
3463 else
3465 ERR("Unexpected wait termination: %d, %d\n", res, GetLastError());
3466 hr = E_UNEXPECTED;
3467 break;
3470 TRACE("-- 0x%08x\n", hr);
3471 return hr;
3475 /***********************************************************************
3476 * CoGetObject [OLE32.@]
3478 * Gets the object named by coverting the name to a moniker and binding to it.
3480 * PARAMS
3481 * pszName [I] String representing the object.
3482 * pBindOptions [I] Parameters affecting the binding to the named object.
3483 * riid [I] Interface to bind to on the objecct.
3484 * ppv [O] On output, the interface riid of the object represented
3485 * by pszName.
3487 * RETURNS
3488 * Success: S_OK.
3489 * Failure: HRESULT code.
3491 * SEE ALSO
3492 * MkParseDisplayName.
3494 HRESULT WINAPI CoGetObject(LPCWSTR pszName, BIND_OPTS *pBindOptions,
3495 REFIID riid, void **ppv)
3497 IBindCtx *pbc;
3498 HRESULT hr;
3500 *ppv = NULL;
3502 hr = CreateBindCtx(0, &pbc);
3503 if (SUCCEEDED(hr))
3505 if (pBindOptions)
3506 hr = IBindCtx_SetBindOptions(pbc, pBindOptions);
3508 if (SUCCEEDED(hr))
3510 ULONG chEaten;
3511 IMoniker *pmk;
3513 hr = MkParseDisplayName(pbc, pszName, &chEaten, &pmk);
3514 if (SUCCEEDED(hr))
3516 hr = IMoniker_BindToObject(pmk, pbc, NULL, riid, ppv);
3517 IMoniker_Release(pmk);
3521 IBindCtx_Release(pbc);
3523 return hr;
3526 /***********************************************************************
3527 * CoRegisterChannelHook [OLE32.@]
3529 * Registers a process-wide hook that is called during ORPC calls.
3531 * PARAMS
3532 * guidExtension [I] GUID of the channel hook to register.
3533 * pChannelHook [I] Channel hook object to register.
3535 * RETURNS
3536 * Success: S_OK.
3537 * Failure: HRESULT code.
3539 HRESULT WINAPI CoRegisterChannelHook(REFGUID guidExtension, IChannelHook *pChannelHook)
3541 TRACE("(%s, %p)\n", debugstr_guid(guidExtension), pChannelHook);
3543 return RPC_RegisterChannelHook(guidExtension, pChannelHook);
3546 /***********************************************************************
3547 * DllMain (OLE32.@)
3549 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID fImpLoad)
3551 TRACE("%p 0x%x %p\n", hinstDLL, fdwReason, fImpLoad);
3553 switch(fdwReason) {
3554 case DLL_PROCESS_ATTACH:
3555 OLE32_hInstance = hinstDLL;
3556 COMPOBJ_InitProcess();
3557 if (TRACE_ON(ole)) CoRegisterMallocSpy((LPVOID)-1);
3558 break;
3560 case DLL_PROCESS_DETACH:
3561 if (TRACE_ON(ole)) CoRevokeMallocSpy();
3562 OLEDD_UnInitialize();
3563 COMPOBJ_UninitProcess();
3564 RPC_UnregisterAllChannelHooks();
3565 OLE32_hInstance = 0;
3566 break;
3568 case DLL_THREAD_DETACH:
3569 COM_TlsDestroy();
3570 break;
3572 return TRUE;
3575 /* NOTE: DllRegisterServer and DllUnregisterServer are in regsvr.c */