4 * Copyright 1995 Martin von Loewis
5 * Copyright 1998 Justin Bradford
6 * Copyright 1999 Francis Beaudet
7 * Copyright 1999 Sylvain St-Germain
8 * Copyright 2002 Marcus Meissner
9 * Copyright 2004 Mike Hearn
10 * Copyright 2005-2006 Robert Shearman (for CodeWeavers)
12 * This library is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Lesser General Public
14 * License as published by the Free Software Foundation; either
15 * version 2.1 of the License, or (at your option) any later version.
17 * This library is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * Lesser General Public License for more details.
22 * You should have received a copy of the GNU Lesser General Public
23 * License along with this library; if not, write to the Free Software
24 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
27 * 1. COINIT_MULTITHREADED is 0; it is the lack of COINIT_APARTMENTTHREADED
28 * Therefore do not test against COINIT_MULTITHREADED
30 * TODO list: (items bunched together depend on each other)
32 * - Implement the service control manager (in rpcss) to keep track
33 * of registered class objects: ISCM::ServerRegisterClsid et al
34 * - Implement the OXID resolver so we don't need magic endpoint names for
35 * clients and servers to meet up
47 #define NONAMELESSUNION
48 #define NONAMELESSSTRUCT
59 #include "compobj_private.h"
61 #include "wine/unicode.h"
62 #include "wine/debug.h"
64 WINE_DEFAULT_DEBUG_CHANNEL(ole
);
66 #define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))
68 /****************************************************************************
69 * This section defines variables internal to the COM module.
72 static HRESULT
COM_GetRegisteredClassObject(const struct apartment
*apt
, REFCLSID rclsid
,
73 DWORD dwClsContext
, LPUNKNOWN
* ppUnk
);
74 static void COM_RevokeAllClasses(const struct apartment
*apt
);
75 static HRESULT
get_inproc_class_object(APARTMENT
*apt
, HKEY hkeydll
, REFCLSID rclsid
, REFIID riid
, BOOL hostifnecessary
, void **ppv
);
77 static APARTMENT
*MTA
; /* protected by csApartment */
78 static APARTMENT
*MainApartment
; /* the first STA apartment */
79 static struct list apts
= LIST_INIT( apts
); /* protected by csApartment */
81 static CRITICAL_SECTION csApartment
;
82 static CRITICAL_SECTION_DEBUG critsect_debug
=
85 { &critsect_debug
.ProcessLocksList
, &critsect_debug
.ProcessLocksList
},
86 0, 0, { (DWORD_PTR
)(__FILE__
": csApartment") }
88 static CRITICAL_SECTION csApartment
= { &critsect_debug
, -1, 0, 0, 0, 0 };
90 struct registered_psclsid
98 * This lock count counts the number of times CoInitialize is called. It is
99 * decreased every time CoUninitialize is called. When it hits 0, the COM
100 * libraries are freed
102 static LONG s_COMLockCount
= 0;
103 /* Reference count used by CoAddRefServerProcess/CoReleaseServerProcess */
104 static LONG s_COMServerProcessReferences
= 0;
107 * This linked list contains the list of registered class objects. These
108 * are mostly used to register the factories for out-of-proc servers of OLE
111 * TODO: Make this data structure aware of inter-process communication. This
112 * means that parts of this will be exported to rpcss.
114 typedef struct tagRegisteredClass
117 CLSID classIdentifier
;
119 LPUNKNOWN classObject
;
123 LPSTREAM pMarshaledData
; /* FIXME: only really need to store OXID and IPID */
124 void *RpcRegistration
;
127 static struct list RegisteredClassList
= LIST_INIT(RegisteredClassList
);
129 static CRITICAL_SECTION csRegisteredClassList
;
130 static CRITICAL_SECTION_DEBUG class_cs_debug
=
132 0, 0, &csRegisteredClassList
,
133 { &class_cs_debug
.ProcessLocksList
, &class_cs_debug
.ProcessLocksList
},
134 0, 0, { (DWORD_PTR
)(__FILE__
": csRegisteredClassList") }
136 static CRITICAL_SECTION csRegisteredClassList
= { &class_cs_debug
, -1, 0, 0, 0, 0 };
138 /*****************************************************************************
139 * This section contains OpenDllList definitions
141 * The OpenDllList contains only handles of dll loaded by CoGetClassObject or
142 * other functions that do LoadLibrary _without_ giving back a HMODULE.
143 * Without this list these handles would never be freed.
145 * FIXME: a DLL that says OK when asked for unloading is unloaded in the
146 * next unload-call but not before 600 sec.
149 typedef HRESULT (CALLBACK
*DllGetClassObjectFunc
)(REFCLSID clsid
, REFIID iid
, LPVOID
*ppv
);
150 typedef HRESULT (WINAPI
*DllCanUnloadNowFunc
)(void);
152 typedef struct tagOpenDll
157 DllGetClassObjectFunc DllGetClassObject
;
158 DllCanUnloadNowFunc DllCanUnloadNow
;
162 static struct list openDllList
= LIST_INIT(openDllList
);
164 static CRITICAL_SECTION csOpenDllList
;
165 static CRITICAL_SECTION_DEBUG dll_cs_debug
=
167 0, 0, &csOpenDllList
,
168 { &dll_cs_debug
.ProcessLocksList
, &dll_cs_debug
.ProcessLocksList
},
169 0, 0, { (DWORD_PTR
)(__FILE__
": csOpenDllList") }
171 static CRITICAL_SECTION csOpenDllList
= { &dll_cs_debug
, -1, 0, 0, 0, 0 };
173 struct apartment_loaded_dll
181 static const WCHAR wszAptWinClass
[] = {'O','l','e','M','a','i','n','T','h','r','e','a','d','W','n','d','C','l','a','s','s',' ',
182 '0','x','#','#','#','#','#','#','#','#',' ',0};
183 static LRESULT CALLBACK
apartment_wndproc(HWND hWnd
, UINT msg
, WPARAM wParam
, LPARAM lParam
);
184 static HRESULT
apartment_getclassobject(struct apartment
*apt
, LPCWSTR dllpath
,
185 BOOL apartment_threaded
,
186 REFCLSID rclsid
, REFIID riid
, void **ppv
);
187 static void apartment_freeunusedlibraries(struct apartment
*apt
, DWORD delay
);
189 static HRESULT
COMPOBJ_DllList_Add(LPCWSTR library_name
, OpenDll
**ret
);
190 static OpenDll
*COMPOBJ_DllList_Get(LPCWSTR library_name
);
191 static void COMPOBJ_DllList_ReleaseRef(OpenDll
*entry
, BOOL free_entry
);
193 static DWORD
COM_RegReadPath(HKEY hkeyroot
, const WCHAR
*keyname
, const WCHAR
*valuename
, WCHAR
* dst
, DWORD dstlen
);
195 static void COMPOBJ_InitProcess( void )
199 /* Dispatching to the correct thread in an apartment is done through
200 * window messages rather than RPC transports. When an interface is
201 * marshalled into another apartment in the same process, a window of the
202 * following class is created. The *caller* of CoMarshalInterface (i.e., the
203 * application) is responsible for pumping the message loop in that thread.
204 * The WM_USER messages which point to the RPCs are then dispatched to
205 * apartment_wndproc by the user's code from the apartment in which the
206 * interface was unmarshalled.
208 memset(&wclass
, 0, sizeof(wclass
));
209 wclass
.lpfnWndProc
= apartment_wndproc
;
210 wclass
.hInstance
= hProxyDll
;
211 wclass
.lpszClassName
= wszAptWinClass
;
212 RegisterClassW(&wclass
);
215 static void COMPOBJ_UninitProcess( void )
217 UnregisterClassW(wszAptWinClass
, hProxyDll
);
220 static void COM_TlsDestroy(void)
222 struct oletls
*info
= NtCurrentTeb()->ReservedForOle
;
225 if (info
->apt
) apartment_release(info
->apt
);
226 if (info
->errorinfo
) IErrorInfo_Release(info
->errorinfo
);
227 if (info
->state
) IUnknown_Release(info
->state
);
228 if (info
->spy
) IUnknown_Release(info
->spy
);
229 HeapFree(GetProcessHeap(), 0, info
);
230 NtCurrentTeb()->ReservedForOle
= NULL
;
234 /******************************************************************************
238 /* allocates memory and fills in the necessary fields for a new apartment
239 * object. must be called inside apartment cs */
240 static APARTMENT
*apartment_construct(DWORD model
)
244 TRACE("creating new apartment, model=%d\n", model
);
246 apt
= HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY
, sizeof(*apt
));
247 apt
->tid
= GetCurrentThreadId();
249 list_init(&apt
->proxies
);
250 list_init(&apt
->stubmgrs
);
251 list_init(&apt
->psclsids
);
252 list_init(&apt
->loaded_dlls
);
255 apt
->remunk_exported
= FALSE
;
257 InitializeCriticalSection(&apt
->cs
);
258 DEBUG_SET_CRITSEC_NAME(&apt
->cs
, "apartment");
260 apt
->multi_threaded
= !(model
& COINIT_APARTMENTTHREADED
);
262 if (apt
->multi_threaded
)
264 /* FIXME: should be randomly generated by in an RPC call to rpcss */
265 apt
->oxid
= ((OXID
)GetCurrentProcessId() << 32) | 0xcafe;
269 /* FIXME: should be randomly generated by in an RPC call to rpcss */
270 apt
->oxid
= ((OXID
)GetCurrentProcessId() << 32) | GetCurrentThreadId();
273 TRACE("Created apartment on OXID %s\n", wine_dbgstr_longlong(apt
->oxid
));
275 list_add_head(&apts
, &apt
->entry
);
280 /* gets and existing apartment if one exists or otherwise creates an apartment
281 * structure which stores OLE apartment-local information and stores a pointer
282 * to it in the thread-local storage */
283 static APARTMENT
*apartment_get_or_create(DWORD model
)
285 APARTMENT
*apt
= COM_CurrentApt();
289 if (model
& COINIT_APARTMENTTHREADED
)
291 EnterCriticalSection(&csApartment
);
293 apt
= apartment_construct(model
);
298 TRACE("Created main-threaded apartment with OXID %s\n", wine_dbgstr_longlong(apt
->oxid
));
301 LeaveCriticalSection(&csApartment
);
304 apartment_createwindowifneeded(apt
);
308 EnterCriticalSection(&csApartment
);
310 /* The multi-threaded apartment (MTA) contains zero or more threads interacting
311 * with free threaded (ie thread safe) COM objects. There is only ever one MTA
315 TRACE("entering the multithreaded apartment %s\n", wine_dbgstr_longlong(MTA
->oxid
));
316 apartment_addref(MTA
);
319 MTA
= apartment_construct(model
);
323 LeaveCriticalSection(&csApartment
);
325 COM_CurrentInfo()->apt
= apt
;
331 static inline BOOL
apartment_is_model(const APARTMENT
*apt
, DWORD model
)
333 return (apt
->multi_threaded
== !(model
& COINIT_APARTMENTTHREADED
));
336 DWORD
apartment_addref(struct apartment
*apt
)
338 DWORD refs
= InterlockedIncrement(&apt
->refs
);
339 TRACE("%s: before = %d\n", wine_dbgstr_longlong(apt
->oxid
), refs
- 1);
343 DWORD
apartment_release(struct apartment
*apt
)
347 EnterCriticalSection(&csApartment
);
349 ret
= InterlockedDecrement(&apt
->refs
);
350 TRACE("%s: after = %d\n", wine_dbgstr_longlong(apt
->oxid
), ret
);
351 /* destruction stuff that needs to happen under csApartment CS */
354 if (apt
== MTA
) MTA
= NULL
;
355 else if (apt
== MainApartment
) MainApartment
= NULL
;
356 list_remove(&apt
->entry
);
359 LeaveCriticalSection(&csApartment
);
363 struct list
*cursor
, *cursor2
;
365 TRACE("destroying apartment %p, oxid %s\n", apt
, wine_dbgstr_longlong(apt
->oxid
));
367 /* Release the references to the registered class objects */
368 COM_RevokeAllClasses(apt
);
370 /* no locking is needed for this apartment, because no other thread
371 * can access it at this point */
373 apartment_disconnectproxies(apt
);
375 if (apt
->win
) DestroyWindow(apt
->win
);
376 if (apt
->host_apt_tid
) PostThreadMessageW(apt
->host_apt_tid
, WM_QUIT
, 0, 0);
378 LIST_FOR_EACH_SAFE(cursor
, cursor2
, &apt
->stubmgrs
)
380 struct stub_manager
*stubmgr
= LIST_ENTRY(cursor
, struct stub_manager
, entry
);
381 /* release the implicit reference given by the fact that the
382 * stub has external references (it must do since it is in the
383 * stub manager list in the apartment and all non-apartment users
384 * must have a ref on the apartment and so it cannot be destroyed).
386 stub_manager_int_release(stubmgr
);
389 LIST_FOR_EACH_SAFE(cursor
, cursor2
, &apt
->psclsids
)
391 struct registered_psclsid
*registered_psclsid
=
392 LIST_ENTRY(cursor
, struct registered_psclsid
, entry
);
394 list_remove(®istered_psclsid
->entry
);
395 HeapFree(GetProcessHeap(), 0, registered_psclsid
);
398 /* if this assert fires, then another thread took a reference to a
399 * stub manager without taking a reference to the containing
400 * apartment, which it must do. */
401 assert(list_empty(&apt
->stubmgrs
));
403 if (apt
->filter
) IUnknown_Release(apt
->filter
);
405 /* free as many unused libraries as possible... */
406 apartment_freeunusedlibraries(apt
, 0);
408 /* ... and free the memory for the apartment loaded dll entry and
409 * release the dll list reference without freeing the library for the
411 while ((cursor
= list_head(&apt
->loaded_dlls
)))
413 struct apartment_loaded_dll
*apartment_loaded_dll
= LIST_ENTRY(cursor
, struct apartment_loaded_dll
, entry
);
414 COMPOBJ_DllList_ReleaseRef(apartment_loaded_dll
->dll
, FALSE
);
416 HeapFree(GetProcessHeap(), 0, apartment_loaded_dll
);
419 DEBUG_CLEAR_CRITSEC_NAME(&apt
->cs
);
420 DeleteCriticalSection(&apt
->cs
);
422 HeapFree(GetProcessHeap(), 0, apt
);
428 /* The given OXID must be local to this process:
430 * The ref parameter is here mostly to ensure people remember that
431 * they get one, you should normally take a ref for thread safety.
433 APARTMENT
*apartment_findfromoxid(OXID oxid
, BOOL ref
)
435 APARTMENT
*result
= NULL
;
438 EnterCriticalSection(&csApartment
);
439 LIST_FOR_EACH( cursor
, &apts
)
441 struct apartment
*apt
= LIST_ENTRY( cursor
, struct apartment
, entry
);
442 if (apt
->oxid
== oxid
)
445 if (ref
) apartment_addref(result
);
449 LeaveCriticalSection(&csApartment
);
454 /* gets the apartment which has a given creator thread ID. The caller must
455 * release the reference from the apartment as soon as the apartment pointer
456 * is no longer required. */
457 APARTMENT
*apartment_findfromtid(DWORD tid
)
459 APARTMENT
*result
= NULL
;
462 EnterCriticalSection(&csApartment
);
463 LIST_FOR_EACH( cursor
, &apts
)
465 struct apartment
*apt
= LIST_ENTRY( cursor
, struct apartment
, entry
);
469 apartment_addref(result
);
473 LeaveCriticalSection(&csApartment
);
478 /* gets the main apartment if it exists. The caller must
479 * release the reference from the apartment as soon as the apartment pointer
480 * is no longer required. */
481 static APARTMENT
*apartment_findmain(void)
485 EnterCriticalSection(&csApartment
);
487 result
= MainApartment
;
488 if (result
) apartment_addref(result
);
490 LeaveCriticalSection(&csApartment
);
495 struct host_object_params
498 CLSID clsid
; /* clsid of object to marshal */
499 IID iid
; /* interface to marshal */
500 HANDLE event
; /* event signalling when ready for multi-threaded case */
501 HRESULT hr
; /* result for multi-threaded case */
502 IStream
*stream
; /* stream that the object will be marshaled into */
503 BOOL apartment_threaded
; /* is the component purely apartment-threaded? */
506 static HRESULT
apartment_hostobject(struct apartment
*apt
,
507 const struct host_object_params
*params
)
511 static const LARGE_INTEGER llZero
;
512 WCHAR dllpath
[MAX_PATH
+1];
514 TRACE("clsid %s, iid %s\n", debugstr_guid(¶ms
->clsid
), debugstr_guid(¶ms
->iid
));
516 if (COM_RegReadPath(params
->hkeydll
, NULL
, NULL
, dllpath
, ARRAYSIZE(dllpath
)) != ERROR_SUCCESS
)
518 /* failure: CLSID is not found in registry */
519 WARN("class %s not registered inproc\n", debugstr_guid(¶ms
->clsid
));
520 return REGDB_E_CLASSNOTREG
;
523 hr
= apartment_getclassobject(apt
, dllpath
, params
->apartment_threaded
,
524 ¶ms
->clsid
, ¶ms
->iid
, (void **)&object
);
528 hr
= CoMarshalInterface(params
->stream
, ¶ms
->iid
, object
, MSHCTX_INPROC
, NULL
, MSHLFLAGS_NORMAL
);
530 IUnknown_Release(object
);
531 IStream_Seek(params
->stream
, llZero
, STREAM_SEEK_SET
, NULL
);
536 static LRESULT CALLBACK
apartment_wndproc(HWND hWnd
, UINT msg
, WPARAM wParam
, LPARAM lParam
)
541 RPC_ExecuteCall((struct dispatch_params
*)lParam
);
544 return apartment_hostobject(COM_CurrentApt(), (const struct host_object_params
*)lParam
);
546 return DefWindowProcW(hWnd
, msg
, wParam
, lParam
);
550 struct host_thread_params
552 COINIT threading_model
;
557 /* thread for hosting an object to allow an object to appear to be created in
558 * an apartment with an incompatible threading model */
559 static DWORD CALLBACK
apartment_hostobject_thread(LPVOID p
)
561 struct host_thread_params
*params
= p
;
564 struct apartment
*apt
;
568 hr
= CoInitializeEx(NULL
, params
->threading_model
);
569 if (FAILED(hr
)) return hr
;
571 apt
= COM_CurrentApt();
572 if (params
->threading_model
== COINIT_APARTMENTTHREADED
)
574 apartment_createwindowifneeded(apt
);
575 params
->apartment_hwnd
= apartment_getwindow(apt
);
578 params
->apartment_hwnd
= NULL
;
580 /* force the message queue to be created before signaling parent thread */
581 PeekMessageW(&msg
, NULL
, WM_USER
, WM_USER
, PM_NOREMOVE
);
583 SetEvent(params
->ready_event
);
584 params
= NULL
; /* can't touch params after here as it may be invalid */
586 while (GetMessageW(&msg
, NULL
, 0, 0))
588 if (!msg
.hwnd
&& (msg
.message
== DM_HOSTOBJECT
))
590 struct host_object_params
*obj_params
= (struct host_object_params
*)msg
.lParam
;
591 obj_params
->hr
= apartment_hostobject(apt
, obj_params
);
592 SetEvent(obj_params
->event
);
596 TranslateMessage(&msg
);
597 DispatchMessageW(&msg
);
608 /* finds or creates a host apartment, creates the object inside it and returns
609 * a proxy to it so that the object can be used in the apartment of the
610 * caller of this function */
611 static HRESULT
apartment_hostobject_in_hostapt(
612 struct apartment
*apt
, BOOL multi_threaded
, BOOL main_apartment
,
613 HKEY hkeydll
, REFCLSID rclsid
, REFIID riid
, void **ppv
)
615 struct host_object_params params
;
616 HWND apartment_hwnd
= NULL
;
617 DWORD apartment_tid
= 0;
620 if (!multi_threaded
&& main_apartment
)
622 APARTMENT
*host_apt
= apartment_findmain();
625 apartment_hwnd
= apartment_getwindow(host_apt
);
626 apartment_release(host_apt
);
632 EnterCriticalSection(&apt
->cs
);
634 if (!apt
->host_apt_tid
)
636 struct host_thread_params thread_params
;
640 thread_params
.threading_model
= multi_threaded
? COINIT_MULTITHREADED
: COINIT_APARTMENTTHREADED
;
641 handles
[0] = thread_params
.ready_event
= CreateEventW(NULL
, FALSE
, FALSE
, NULL
);
642 thread_params
.apartment_hwnd
= NULL
;
643 handles
[1] = CreateThread(NULL
, 0, apartment_hostobject_thread
, &thread_params
, 0, &apt
->host_apt_tid
);
646 CloseHandle(handles
[0]);
647 LeaveCriticalSection(&apt
->cs
);
648 return E_OUTOFMEMORY
;
650 wait_value
= WaitForMultipleObjects(2, handles
, FALSE
, INFINITE
);
651 CloseHandle(handles
[0]);
652 CloseHandle(handles
[1]);
653 if (wait_value
== WAIT_OBJECT_0
)
654 apt
->host_apt_hwnd
= thread_params
.apartment_hwnd
;
657 LeaveCriticalSection(&apt
->cs
);
658 return E_OUTOFMEMORY
;
662 if (multi_threaded
|| !main_apartment
)
664 apartment_hwnd
= apt
->host_apt_hwnd
;
665 apartment_tid
= apt
->host_apt_tid
;
668 LeaveCriticalSection(&apt
->cs
);
671 /* another thread may have become the main apartment in the time it took
672 * us to create the thread for the host apartment */
673 if (!apartment_hwnd
&& !multi_threaded
&& main_apartment
)
675 APARTMENT
*host_apt
= apartment_findmain();
678 apartment_hwnd
= apartment_getwindow(host_apt
);
679 apartment_release(host_apt
);
683 params
.hkeydll
= hkeydll
;
684 params
.clsid
= *rclsid
;
686 hr
= CreateStreamOnHGlobal(NULL
, TRUE
, ¶ms
.stream
);
689 params
.apartment_threaded
= !multi_threaded
;
693 params
.event
= CreateEventW(NULL
, FALSE
, FALSE
, NULL
);
694 if (!PostThreadMessageW(apartment_tid
, DM_HOSTOBJECT
, 0, (LPARAM
)¶ms
))
698 WaitForSingleObject(params
.event
, INFINITE
);
701 CloseHandle(params
.event
);
707 ERR("host apartment didn't create window\n");
711 hr
= SendMessageW(apartment_hwnd
, DM_HOSTOBJECT
, 0, (LPARAM
)¶ms
);
714 hr
= CoUnmarshalInterface(params
.stream
, riid
, ppv
);
715 IStream_Release(params
.stream
);
719 /* create a window for the apartment or return the current one if one has
720 * already been created */
721 HRESULT
apartment_createwindowifneeded(struct apartment
*apt
)
723 if (apt
->multi_threaded
)
728 HWND hwnd
= CreateWindowW(wszAptWinClass
, NULL
, 0,
730 HWND_MESSAGE
, 0, hProxyDll
, NULL
);
733 ERR("CreateWindow failed with error %d\n", GetLastError());
734 return HRESULT_FROM_WIN32(GetLastError());
736 if (InterlockedCompareExchangePointer((PVOID
*)&apt
->win
, hwnd
, NULL
))
737 /* someone beat us to it */
744 /* retrieves the window for the main- or apartment-threaded apartment */
745 HWND
apartment_getwindow(const struct apartment
*apt
)
747 assert(!apt
->multi_threaded
);
751 void apartment_joinmta(void)
753 apartment_addref(MTA
);
754 COM_CurrentInfo()->apt
= MTA
;
757 /* gets the specified class object by loading the appropriate DLL, if
758 * necessary and calls the DllGetClassObject function for the DLL */
759 static HRESULT
apartment_getclassobject(struct apartment
*apt
, LPCWSTR dllpath
,
760 BOOL apartment_threaded
,
761 REFCLSID rclsid
, REFIID riid
, void **ppv
)
763 static const WCHAR wszOle32
[] = {'o','l','e','3','2','.','d','l','l',0};
766 struct apartment_loaded_dll
*apartment_loaded_dll
;
768 if (!strcmpiW(dllpath
, wszOle32
))
770 /* we don't need to control the lifetime of this dll, so use the local
771 * implementation of DllGetClassObject directly */
772 TRACE("calling ole32!DllGetClassObject\n");
773 hr
= DllGetClassObject(rclsid
, riid
, ppv
);
776 ERR("DllGetClassObject returned error 0x%08x\n", hr
);
781 EnterCriticalSection(&apt
->cs
);
783 LIST_FOR_EACH_ENTRY(apartment_loaded_dll
, &apt
->loaded_dlls
, struct apartment_loaded_dll
, entry
)
784 if (!strcmpiW(dllpath
, apartment_loaded_dll
->dll
->library_name
))
786 TRACE("found %s already loaded\n", debugstr_w(dllpath
));
793 apartment_loaded_dll
= HeapAlloc(GetProcessHeap(), 0, sizeof(*apartment_loaded_dll
));
794 if (!apartment_loaded_dll
)
798 apartment_loaded_dll
->unload_time
= 0;
799 apartment_loaded_dll
->multi_threaded
= FALSE
;
800 hr
= COMPOBJ_DllList_Add( dllpath
, &apartment_loaded_dll
->dll
);
802 HeapFree(GetProcessHeap(), 0, apartment_loaded_dll
);
806 TRACE("added new loaded dll %s\n", debugstr_w(dllpath
));
807 list_add_tail(&apt
->loaded_dlls
, &apartment_loaded_dll
->entry
);
811 LeaveCriticalSection(&apt
->cs
);
815 /* one component being multi-threaded overrides any number of
816 * apartment-threaded components */
817 if (!apartment_threaded
)
818 apartment_loaded_dll
->multi_threaded
= TRUE
;
820 TRACE("calling DllGetClassObject %p\n", apartment_loaded_dll
->dll
->DllGetClassObject
);
821 /* OK: get the ClassObject */
822 hr
= apartment_loaded_dll
->dll
->DllGetClassObject(rclsid
, riid
, ppv
);
825 ERR("DllGetClassObject returned error 0x%08x\n", hr
);
831 /* frees unused libraries loaded by apartment_getclassobject by calling the
832 * DLL's DllCanUnloadNow entry point */
833 static void apartment_freeunusedlibraries(struct apartment
*apt
, DWORD delay
)
835 struct apartment_loaded_dll
*entry
, *next
;
836 EnterCriticalSection(&apt
->cs
);
837 LIST_FOR_EACH_ENTRY_SAFE(entry
, next
, &apt
->loaded_dlls
, struct apartment_loaded_dll
, entry
)
839 if (entry
->dll
->DllCanUnloadNow
&& (entry
->dll
->DllCanUnloadNow() == S_OK
))
841 DWORD real_delay
= delay
;
843 if (real_delay
== INFINITE
)
845 /* DLLs that return multi-threaded objects aren't unloaded
846 * straight away to cope for programs that have races between
847 * last object destruction and threads in the DLLs that haven't
848 * finished, despite DllCanUnloadNow returning S_OK */
849 if (entry
->multi_threaded
)
850 real_delay
= 10 * 60 * 1000; /* 10 minutes */
855 if (!real_delay
|| (entry
->unload_time
&& (entry
->unload_time
< GetTickCount())))
857 list_remove(&entry
->entry
);
858 COMPOBJ_DllList_ReleaseRef(entry
->dll
, TRUE
);
859 HeapFree(GetProcessHeap(), 0, entry
);
862 entry
->unload_time
= GetTickCount() + real_delay
;
864 else if (entry
->unload_time
)
865 entry
->unload_time
= 0;
867 LeaveCriticalSection(&apt
->cs
);
870 /*****************************************************************************
871 * This section contains OpenDllList implementation
874 /* caller must ensure that library_name is not already in the open dll list */
875 static HRESULT
COMPOBJ_DllList_Add(LPCWSTR library_name
, OpenDll
**ret
)
881 DllCanUnloadNowFunc DllCanUnloadNow
;
882 DllGetClassObjectFunc DllGetClassObject
;
886 *ret
= COMPOBJ_DllList_Get(library_name
);
887 if (*ret
) return S_OK
;
889 /* do this outside the csOpenDllList to avoid creating a lock dependency on
891 hLibrary
= LoadLibraryExW(library_name
, 0, LOAD_WITH_ALTERED_SEARCH_PATH
);
894 ERR("couldn't load in-process dll %s\n", debugstr_w(library_name
));
895 /* failure: DLL could not be loaded */
896 return E_ACCESSDENIED
; /* FIXME: or should this be CO_E_DLLNOTFOUND? */
899 DllCanUnloadNow
= (void *)GetProcAddress(hLibrary
, "DllCanUnloadNow");
900 /* Note: failing to find DllCanUnloadNow is not a failure */
901 DllGetClassObject
= (void *)GetProcAddress(hLibrary
, "DllGetClassObject");
902 if (!DllGetClassObject
)
904 /* failure: the dll did not export DllGetClassObject */
905 ERR("couldn't find function DllGetClassObject in %s\n", debugstr_w(library_name
));
906 FreeLibrary(hLibrary
);
907 return CO_E_DLLNOTFOUND
;
910 EnterCriticalSection( &csOpenDllList
);
912 *ret
= COMPOBJ_DllList_Get(library_name
);
915 /* another caller to this function already added the dll while we
916 * weren't in the critical section */
917 FreeLibrary(hLibrary
);
921 len
= strlenW(library_name
);
922 entry
= HeapAlloc(GetProcessHeap(),0, sizeof(OpenDll
));
924 entry
->library_name
= HeapAlloc(GetProcessHeap(), 0, (len
+ 1)*sizeof(WCHAR
));
925 if (entry
&& entry
->library_name
)
927 memcpy(entry
->library_name
, library_name
, (len
+ 1)*sizeof(WCHAR
));
928 entry
->library
= hLibrary
;
930 entry
->DllCanUnloadNow
= DllCanUnloadNow
;
931 entry
->DllGetClassObject
= DllGetClassObject
;
932 list_add_tail(&openDllList
, &entry
->entry
);
937 FreeLibrary(hLibrary
);
942 LeaveCriticalSection( &csOpenDllList
);
947 static OpenDll
*COMPOBJ_DllList_Get(LPCWSTR library_name
)
951 EnterCriticalSection(&csOpenDllList
);
952 LIST_FOR_EACH_ENTRY(ptr
, &openDllList
, OpenDll
, entry
)
954 if (!strcmpiW(library_name
, ptr
->library_name
) &&
955 (InterlockedIncrement(&ptr
->refs
) != 1) /* entry is being destroy if == 1 */)
961 LeaveCriticalSection(&csOpenDllList
);
965 /* pass FALSE for free_entry to release a reference without destroying the
966 * entry if it reaches zero or TRUE otherwise */
967 static void COMPOBJ_DllList_ReleaseRef(OpenDll
*entry
, BOOL free_entry
)
969 if (!InterlockedDecrement(&entry
->refs
) && free_entry
)
971 EnterCriticalSection(&csOpenDllList
);
972 list_remove(&entry
->entry
);
973 LeaveCriticalSection(&csOpenDllList
);
975 TRACE("freeing %p\n", entry
->library
);
976 FreeLibrary(entry
->library
);
978 HeapFree(GetProcessHeap(), 0, entry
->library_name
);
979 HeapFree(GetProcessHeap(), 0, entry
);
983 /* frees memory associated with active dll list */
984 static void COMPOBJ_DllList_Free(void)
986 OpenDll
*entry
, *cursor2
;
987 EnterCriticalSection(&csOpenDllList
);
988 LIST_FOR_EACH_ENTRY_SAFE(entry
, cursor2
, &openDllList
, OpenDll
, entry
)
990 list_remove(&entry
->entry
);
992 HeapFree(GetProcessHeap(), 0, entry
->library_name
);
993 HeapFree(GetProcessHeap(), 0, entry
);
995 LeaveCriticalSection(&csOpenDllList
);
998 /******************************************************************************
999 * CoBuildVersion [OLE32.@]
1000 * CoBuildVersion [COMPOBJ.1]
1002 * Gets the build version of the DLL.
1007 * Current build version, hiword is majornumber, loword is minornumber
1009 DWORD WINAPI
CoBuildVersion(void)
1011 TRACE("Returning version %d, build %d.\n", rmm
, rup
);
1012 return (rmm
<<16)+rup
;
1015 /******************************************************************************
1016 * CoRegisterInitializeSpy [OLE32.@]
1018 * Add a Spy that watches CoInitializeEx calls
1021 * spy [I] Pointer to IUnknown interface that will be QueryInterface'd.
1022 * cookie [II] cookie receiver
1025 * Success: S_OK if not already initialized, S_FALSE otherwise.
1026 * Failure: HRESULT code.
1031 HRESULT WINAPI
CoRegisterInitializeSpy(IInitializeSpy
*spy
, ULARGE_INTEGER
*cookie
)
1033 struct oletls
*info
= COM_CurrentInfo();
1036 TRACE("(%p, %p)\n", spy
, cookie
);
1038 if (!spy
|| !cookie
|| !info
)
1041 WARN("Could not allocate tls\n");
1042 return E_INVALIDARG
;
1047 FIXME("Already registered?\n");
1048 return E_UNEXPECTED
;
1051 hr
= IUnknown_QueryInterface(spy
, &IID_IInitializeSpy
, (void **) &info
->spy
);
1054 cookie
->QuadPart
= (DWORD_PTR
)spy
;
1060 /******************************************************************************
1061 * CoRevokeInitializeSpy [OLE32.@]
1063 * Remove a spy that previously watched CoInitializeEx calls
1066 * cookie [I] The cookie obtained from a previous CoRegisterInitializeSpy call
1069 * Success: S_OK if a spy is removed
1070 * Failure: E_INVALIDARG
1075 HRESULT WINAPI
CoRevokeInitializeSpy(ULARGE_INTEGER cookie
)
1077 struct oletls
*info
= COM_CurrentInfo();
1078 TRACE("(%s)\n", wine_dbgstr_longlong(cookie
.QuadPart
));
1080 if (!info
|| !info
->spy
|| cookie
.QuadPart
!= (DWORD_PTR
)info
->spy
)
1081 return E_INVALIDARG
;
1083 IUnknown_Release(info
->spy
);
1089 /******************************************************************************
1090 * CoInitialize [OLE32.@]
1092 * Initializes the COM libraries by calling CoInitializeEx with
1093 * COINIT_APARTMENTTHREADED, ie it enters a STA thread.
1096 * lpReserved [I] Pointer to IMalloc interface (obsolete, should be NULL).
1099 * Success: S_OK if not already initialized, S_FALSE otherwise.
1100 * Failure: HRESULT code.
1105 HRESULT WINAPI
CoInitialize(LPVOID lpReserved
)
1108 * Just delegate to the newer method.
1110 return CoInitializeEx(lpReserved
, COINIT_APARTMENTTHREADED
);
1113 /******************************************************************************
1114 * CoInitializeEx [OLE32.@]
1116 * Initializes the COM libraries.
1119 * lpReserved [I] Pointer to IMalloc interface (obsolete, should be NULL).
1120 * dwCoInit [I] One or more flags from the COINIT enumeration. See notes.
1123 * S_OK if successful,
1124 * S_FALSE if this function was called already.
1125 * RPC_E_CHANGED_MODE if a previous call to CoInitializeEx specified another
1130 * The behavior used to set the IMalloc used for memory management is
1132 * The dwCoInit parameter must specify one of the following apartment
1134 *| COINIT_APARTMENTTHREADED - A single-threaded apartment (STA).
1135 *| COINIT_MULTITHREADED - A multi-threaded apartment (MTA).
1136 * The parameter may also specify zero or more of the following flags:
1137 *| COINIT_DISABLE_OLE1DDE - Don't use DDE for OLE1 support.
1138 *| COINIT_SPEED_OVER_MEMORY - Trade memory for speed.
1143 HRESULT WINAPI
CoInitializeEx(LPVOID lpReserved
, DWORD dwCoInit
)
1145 struct oletls
*info
= COM_CurrentInfo();
1149 TRACE("(%p, %x)\n", lpReserved
, (int)dwCoInit
);
1151 if (lpReserved
!=NULL
)
1153 ERR("(%p, %x) - Bad parameter passed-in %p, must be an old Windows Application\n", lpReserved
, (int)dwCoInit
, lpReserved
);
1157 * Check the lock count. If this is the first time going through the initialize
1158 * process, we have to initialize the libraries.
1160 * And crank-up that lock count.
1162 if (InterlockedExchangeAdd(&s_COMLockCount
,1)==0)
1165 * Initialize the various COM libraries and data structures.
1167 TRACE("() - Initializing the COM libraries\n");
1169 /* we may need to defer this until after apartment initialisation */
1170 RunningObjectTableImpl_Initialize();
1174 IInitializeSpy_PreInitialize(info
->spy
, dwCoInit
, info
->inits
);
1176 if (!(apt
= info
->apt
))
1178 apt
= apartment_get_or_create(dwCoInit
);
1179 if (!apt
) return E_OUTOFMEMORY
;
1181 else if (!apartment_is_model(apt
, dwCoInit
))
1183 /* Changing the threading model after it's been set is illegal. If this warning is triggered by Wine
1184 code then we are probably using the wrong threading model to implement that API. */
1185 ERR("Attempt to change threading model of this apartment from %s to %s\n",
1186 apt
->multi_threaded
? "multi-threaded" : "apartment threaded",
1187 dwCoInit
& COINIT_APARTMENTTHREADED
? "apartment threaded" : "multi-threaded");
1188 return RPC_E_CHANGED_MODE
;
1196 IInitializeSpy_PostInitialize(info
->spy
, hr
, dwCoInit
, info
->inits
);
1201 /***********************************************************************
1202 * CoUninitialize [OLE32.@]
1204 * This method will decrement the refcount on the current apartment, freeing
1205 * the resources associated with it if it is the last thread in the apartment.
1206 * If the last apartment is freed, the function will additionally release
1207 * any COM resources associated with the process.
1217 void WINAPI
CoUninitialize(void)
1219 struct oletls
* info
= COM_CurrentInfo();
1224 /* will only happen on OOM */
1228 IInitializeSpy_PreUninitialize(info
->spy
, info
->inits
);
1233 ERR("Mismatched CoUninitialize\n");
1236 IInitializeSpy_PostUninitialize(info
->spy
, info
->inits
);
1242 apartment_release(info
->apt
);
1247 * Decrease the reference count.
1248 * If we are back to 0 locks on the COM library, make sure we free
1249 * all the associated data structures.
1251 lCOMRefCnt
= InterlockedExchangeAdd(&s_COMLockCount
,-1);
1254 TRACE("() - Releasing the COM libraries\n");
1256 RunningObjectTableImpl_UnInitialize();
1258 else if (lCOMRefCnt
<1) {
1259 ERR( "CoUninitialize() - not CoInitialized.\n" );
1260 InterlockedExchangeAdd(&s_COMLockCount
,1); /* restore the lock count. */
1263 IInitializeSpy_PostUninitialize(info
->spy
, info
->inits
);
1266 /******************************************************************************
1267 * CoDisconnectObject [OLE32.@]
1269 * Disconnects all connections to this object from remote processes. Dispatches
1270 * pending RPCs while blocking new RPCs from occurring, and then calls
1271 * IMarshal::DisconnectObject on the given object.
1273 * Typically called when the object server is forced to shut down, for instance by
1277 * lpUnk [I] The object whose stub should be disconnected.
1278 * reserved [I] Reserved. Should be set to 0.
1282 * Failure: HRESULT code.
1285 * CoMarshalInterface, CoReleaseMarshalData, CoLockObjectExternal
1287 HRESULT WINAPI
CoDisconnectObject( LPUNKNOWN lpUnk
, DWORD reserved
)
1293 TRACE("(%p, 0x%08x)\n", lpUnk
, reserved
);
1295 hr
= IUnknown_QueryInterface(lpUnk
, &IID_IMarshal
, (void **)&marshal
);
1298 hr
= IMarshal_DisconnectObject(marshal
, reserved
);
1299 IMarshal_Release(marshal
);
1303 apt
= COM_CurrentApt();
1305 return CO_E_NOTINITIALIZED
;
1307 apartment_disconnectobject(apt
, lpUnk
);
1309 /* Note: native is pretty broken here because it just silently
1310 * fails, without returning an appropriate error code if the object was
1311 * not found, making apps think that the object was disconnected, when
1312 * it actually wasn't */
1317 /******************************************************************************
1318 * CoCreateGuid [OLE32.@]
1319 * CoCreateGuid [COMPOBJ.73]
1321 * Simply forwards to UuidCreate in RPCRT4.
1324 * pguid [O] Points to the GUID to initialize.
1328 * Failure: HRESULT code.
1333 HRESULT WINAPI
CoCreateGuid(GUID
*pguid
)
1335 DWORD status
= UuidCreate(pguid
);
1336 if (status
== RPC_S_OK
|| status
== RPC_S_UUID_LOCAL_ONLY
) return S_OK
;
1337 return HRESULT_FROM_WIN32( status
);
1340 /******************************************************************************
1341 * CLSIDFromString [OLE32.@]
1342 * IIDFromString [OLE32.@]
1344 * Converts a unique identifier from its string representation into
1348 * idstr [I] The string representation of the GUID.
1349 * id [O] GUID converted from the string.
1353 * CO_E_CLASSSTRING if idstr is not a valid CLSID
1358 static HRESULT
__CLSIDFromString(LPCWSTR s
, CLSID
*id
)
1364 memset( id
, 0, sizeof (CLSID
) );
1368 /* validate the CLSID string */
1369 if (strlenW(s
) != 38)
1370 return CO_E_CLASSSTRING
;
1372 if ((s
[0]!='{') || (s
[9]!='-') || (s
[14]!='-') || (s
[19]!='-') || (s
[24]!='-') || (s
[37]!='}'))
1373 return CO_E_CLASSSTRING
;
1375 for (i
=1; i
<37; i
++) {
1376 if ((i
== 9)||(i
== 14)||(i
== 19)||(i
== 24)) continue;
1377 if (!(((s
[i
] >= '0') && (s
[i
] <= '9')) ||
1378 ((s
[i
] >= 'a') && (s
[i
] <= 'f')) ||
1379 ((s
[i
] >= 'A') && (s
[i
] <= 'F'))))
1380 return CO_E_CLASSSTRING
;
1383 TRACE("%s -> %p\n", debugstr_w(s
), id
);
1385 /* quick lookup table */
1386 memset(table
, 0, 256);
1388 for (i
= 0; i
< 10; i
++) {
1391 for (i
= 0; i
< 6; i
++) {
1392 table
['A' + i
] = i
+10;
1393 table
['a' + i
] = i
+10;
1396 /* in form {XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX} */
1398 id
->Data1
= (table
[s
[1]] << 28 | table
[s
[2]] << 24 | table
[s
[3]] << 20 | table
[s
[4]] << 16 |
1399 table
[s
[5]] << 12 | table
[s
[6]] << 8 | table
[s
[7]] << 4 | table
[s
[8]]);
1400 id
->Data2
= table
[s
[10]] << 12 | table
[s
[11]] << 8 | table
[s
[12]] << 4 | table
[s
[13]];
1401 id
->Data3
= table
[s
[15]] << 12 | table
[s
[16]] << 8 | table
[s
[17]] << 4 | table
[s
[18]];
1403 /* these are just sequential bytes */
1404 id
->Data4
[0] = table
[s
[20]] << 4 | table
[s
[21]];
1405 id
->Data4
[1] = table
[s
[22]] << 4 | table
[s
[23]];
1406 id
->Data4
[2] = table
[s
[25]] << 4 | table
[s
[26]];
1407 id
->Data4
[3] = table
[s
[27]] << 4 | table
[s
[28]];
1408 id
->Data4
[4] = table
[s
[29]] << 4 | table
[s
[30]];
1409 id
->Data4
[5] = table
[s
[31]] << 4 | table
[s
[32]];
1410 id
->Data4
[6] = table
[s
[33]] << 4 | table
[s
[34]];
1411 id
->Data4
[7] = table
[s
[35]] << 4 | table
[s
[36]];
1416 /*****************************************************************************/
1418 HRESULT WINAPI
CLSIDFromString(LPOLESTR idstr
, CLSID
*id
)
1423 return E_INVALIDARG
;
1425 ret
= __CLSIDFromString(idstr
, id
);
1426 if(ret
!= S_OK
) { /* It appears a ProgID is also valid */
1427 ret
= CLSIDFromProgID(idstr
, id
);
1432 /* Converts a GUID into the respective string representation. */
1433 HRESULT
WINE_StringFromCLSID(
1434 const CLSID
*id
, /* [in] GUID to be converted */
1435 LPSTR idstr
/* [out] pointer to buffer to contain converted guid */
1437 static const char hex
[] = "0123456789ABCDEF";
1442 { ERR("called with id=Null\n");
1447 sprintf(idstr
, "{%08X-%04X-%04X-%02X%02X-",
1448 id
->Data1
, id
->Data2
, id
->Data3
,
1449 id
->Data4
[0], id
->Data4
[1]);
1453 for (i
= 2; i
< 8; i
++) {
1454 *s
++ = hex
[id
->Data4
[i
]>>4];
1455 *s
++ = hex
[id
->Data4
[i
] & 0xf];
1461 TRACE("%p->%s\n", id
, idstr
);
1467 /******************************************************************************
1468 * StringFromCLSID [OLE32.@]
1469 * StringFromIID [OLE32.@]
1471 * Converts a GUID into the respective string representation.
1472 * The target string is allocated using the OLE IMalloc.
1475 * id [I] the GUID to be converted.
1476 * idstr [O] A pointer to a to-be-allocated pointer pointing to the resulting string.
1483 * StringFromGUID2, CLSIDFromString
1485 HRESULT WINAPI
StringFromCLSID(REFCLSID id
, LPOLESTR
*idstr
)
1491 if ((ret
= CoGetMalloc(0,&mllc
)))
1494 ret
=WINE_StringFromCLSID(id
,buf
);
1496 DWORD len
= MultiByteToWideChar( CP_ACP
, 0, buf
, -1, NULL
, 0 );
1497 *idstr
= IMalloc_Alloc( mllc
, len
* sizeof(WCHAR
) );
1498 MultiByteToWideChar( CP_ACP
, 0, buf
, -1, *idstr
, len
);
1503 /******************************************************************************
1504 * StringFromGUID2 [OLE32.@]
1505 * StringFromGUID2 [COMPOBJ.76]
1507 * Modified version of StringFromCLSID that allows you to specify max
1511 * id [I] GUID to convert to string.
1512 * str [O] Buffer where the result will be stored.
1513 * cmax [I] Size of the buffer in characters.
1516 * Success: The length of the resulting string in characters.
1519 INT WINAPI
StringFromGUID2(REFGUID id
, LPOLESTR str
, INT cmax
)
1523 if (WINE_StringFromCLSID(id
,xguid
))
1525 return MultiByteToWideChar( CP_ACP
, 0, xguid
, -1, str
, cmax
);
1528 /* open HKCR\\CLSID\\{string form of clsid}\\{keyname} key */
1529 HRESULT
COM_OpenKeyForCLSID(REFCLSID clsid
, LPCWSTR keyname
, REGSAM access
, HKEY
*subkey
)
1531 static const WCHAR wszCLSIDSlash
[] = {'C','L','S','I','D','\\',0};
1532 WCHAR path
[CHARS_IN_GUID
+ ARRAYSIZE(wszCLSIDSlash
) - 1];
1536 strcpyW(path
, wszCLSIDSlash
);
1537 StringFromGUID2(clsid
, path
+ strlenW(wszCLSIDSlash
), CHARS_IN_GUID
);
1538 res
= RegOpenKeyExW(HKEY_CLASSES_ROOT
, path
, 0, keyname
? KEY_READ
: access
, &key
);
1539 if (res
== ERROR_FILE_NOT_FOUND
)
1540 return REGDB_E_CLASSNOTREG
;
1541 else if (res
!= ERROR_SUCCESS
)
1542 return REGDB_E_READREGDB
;
1550 res
= RegOpenKeyExW(key
, keyname
, 0, access
, subkey
);
1552 if (res
== ERROR_FILE_NOT_FOUND
)
1553 return REGDB_E_KEYMISSING
;
1554 else if (res
!= ERROR_SUCCESS
)
1555 return REGDB_E_READREGDB
;
1560 /* open HKCR\\AppId\\{string form of appid clsid} key */
1561 HRESULT
COM_OpenKeyForAppIdFromCLSID(REFCLSID clsid
, REGSAM access
, HKEY
*subkey
)
1563 static const WCHAR szAppId
[] = { 'A','p','p','I','d',0 };
1564 static const WCHAR szAppIdKey
[] = { 'A','p','p','I','d','\\',0 };
1566 WCHAR buf
[CHARS_IN_GUID
];
1567 WCHAR keyname
[ARRAYSIZE(szAppIdKey
) + CHARS_IN_GUID
];
1573 /* read the AppID value under the class's key */
1574 hr
= COM_OpenKeyForCLSID(clsid
, NULL
, KEY_READ
, &hkey
);
1579 res
= RegQueryValueExW(hkey
, szAppId
, NULL
, &type
, (LPBYTE
)buf
, &size
);
1581 if (res
== ERROR_FILE_NOT_FOUND
)
1582 return REGDB_E_KEYMISSING
;
1583 else if (res
!= ERROR_SUCCESS
|| type
!=REG_SZ
)
1584 return REGDB_E_READREGDB
;
1586 strcpyW(keyname
, szAppIdKey
);
1587 strcatW(keyname
, buf
);
1588 res
= RegOpenKeyExW(HKEY_CLASSES_ROOT
, keyname
, 0, access
, subkey
);
1589 if (res
== ERROR_FILE_NOT_FOUND
)
1590 return REGDB_E_KEYMISSING
;
1591 else if (res
!= ERROR_SUCCESS
)
1592 return REGDB_E_READREGDB
;
1597 /******************************************************************************
1598 * ProgIDFromCLSID [OLE32.@]
1600 * Converts a class id into the respective program ID.
1603 * clsid [I] Class ID, as found in registry.
1604 * ppszProgID [O] Associated ProgID.
1609 * REGDB_E_CLASSNOTREG if the given clsid has no associated ProgID
1611 HRESULT WINAPI
ProgIDFromCLSID(REFCLSID clsid
, LPOLESTR
*ppszProgID
)
1613 static const WCHAR wszProgID
[] = {'P','r','o','g','I','D',0};
1620 ERR("ppszProgId isn't optional\n");
1621 return E_INVALIDARG
;
1625 ret
= COM_OpenKeyForCLSID(clsid
, wszProgID
, KEY_READ
, &hkey
);
1629 if (RegQueryValueW(hkey
, NULL
, NULL
, &progidlen
))
1630 ret
= REGDB_E_CLASSNOTREG
;
1634 *ppszProgID
= CoTaskMemAlloc(progidlen
* sizeof(WCHAR
));
1637 if (RegQueryValueW(hkey
, NULL
, *ppszProgID
, &progidlen
))
1638 ret
= REGDB_E_CLASSNOTREG
;
1641 ret
= E_OUTOFMEMORY
;
1648 /******************************************************************************
1649 * CLSIDFromProgID [OLE32.@]
1651 * Converts a program id into the respective GUID.
1654 * progid [I] Unicode program ID, as found in registry.
1655 * clsid [O] Associated CLSID.
1659 * Failure: CO_E_CLASSSTRING - the given ProgID cannot be found.
1661 HRESULT WINAPI
CLSIDFromProgID(LPCOLESTR progid
, LPCLSID clsid
)
1663 static const WCHAR clsidW
[] = { '\\','C','L','S','I','D',0 };
1664 WCHAR buf2
[CHARS_IN_GUID
];
1665 LONG buf2len
= sizeof(buf2
);
1669 if (!progid
|| !clsid
)
1671 ERR("neither progid (%p) nor clsid (%p) are optional\n", progid
, clsid
);
1672 return E_INVALIDARG
;
1675 /* initialise clsid in case of failure */
1676 memset(clsid
, 0, sizeof(*clsid
));
1678 buf
= HeapAlloc( GetProcessHeap(),0,(strlenW(progid
)+8) * sizeof(WCHAR
) );
1679 strcpyW( buf
, progid
);
1680 strcatW( buf
, clsidW
);
1681 if (RegOpenKeyW(HKEY_CLASSES_ROOT
,buf
,&xhkey
))
1683 HeapFree(GetProcessHeap(),0,buf
);
1684 WARN("couldn't open key for ProgID %s\n", debugstr_w(progid
));
1685 return CO_E_CLASSSTRING
;
1687 HeapFree(GetProcessHeap(),0,buf
);
1689 if (RegQueryValueW(xhkey
,NULL
,buf2
,&buf2len
))
1692 WARN("couldn't query clsid value for ProgID %s\n", debugstr_w(progid
));
1693 return CO_E_CLASSSTRING
;
1696 return CLSIDFromString(buf2
,clsid
);
1700 /*****************************************************************************
1701 * CoGetPSClsid [OLE32.@]
1703 * Retrieves the CLSID of the proxy/stub factory that implements
1704 * IPSFactoryBuffer for the specified interface.
1707 * riid [I] Interface whose proxy/stub CLSID is to be returned.
1708 * pclsid [O] Where to store returned proxy/stub CLSID.
1713 * REGDB_E_IIDNOTREG if no PSFactoryBuffer is associated with the IID, or it could not be parsed
1717 * The standard marshaller activates the object with the CLSID
1718 * returned and uses the CreateProxy and CreateStub methods on its
1719 * IPSFactoryBuffer interface to construct the proxies and stubs for a
1722 * CoGetPSClsid determines this CLSID by searching the
1723 * HKEY_CLASSES_ROOT\Interface\{string form of riid}\ProxyStubClsid32
1724 * in the registry and any interface id registered by
1725 * CoRegisterPSClsid within the current process.
1729 * Native returns S_OK for interfaces with a key in HKCR\Interface, but
1730 * without a ProxyStubClsid32 key and leaves garbage in pclsid. This should be
1731 * considered a bug in native unless an application depends on this (unlikely).
1734 * CoRegisterPSClsid.
1736 HRESULT WINAPI
CoGetPSClsid(REFIID riid
, CLSID
*pclsid
)
1738 static const WCHAR wszInterface
[] = {'I','n','t','e','r','f','a','c','e','\\',0};
1739 static const WCHAR wszPSC
[] = {'\\','P','r','o','x','y','S','t','u','b','C','l','s','i','d','3','2',0};
1740 WCHAR path
[ARRAYSIZE(wszInterface
) - 1 + CHARS_IN_GUID
- 1 + ARRAYSIZE(wszPSC
)];
1741 WCHAR value
[CHARS_IN_GUID
];
1744 APARTMENT
*apt
= COM_CurrentApt();
1745 struct registered_psclsid
*registered_psclsid
;
1747 TRACE("() riid=%s, pclsid=%p\n", debugstr_guid(riid
), pclsid
);
1751 ERR("apartment not initialised\n");
1752 return CO_E_NOTINITIALIZED
;
1757 ERR("pclsid isn't optional\n");
1758 return E_INVALIDARG
;
1761 EnterCriticalSection(&apt
->cs
);
1763 LIST_FOR_EACH_ENTRY(registered_psclsid
, &apt
->psclsids
, struct registered_psclsid
, entry
)
1764 if (IsEqualIID(®istered_psclsid
->iid
, riid
))
1766 *pclsid
= registered_psclsid
->clsid
;
1767 LeaveCriticalSection(&apt
->cs
);
1771 LeaveCriticalSection(&apt
->cs
);
1773 /* Interface\\{string form of riid}\\ProxyStubClsid32 */
1774 strcpyW(path
, wszInterface
);
1775 StringFromGUID2(riid
, path
+ ARRAYSIZE(wszInterface
) - 1, CHARS_IN_GUID
);
1776 strcpyW(path
+ ARRAYSIZE(wszInterface
) - 1 + CHARS_IN_GUID
- 1, wszPSC
);
1778 /* Open the key.. */
1779 if (RegOpenKeyExW(HKEY_CLASSES_ROOT
, path
, 0, KEY_READ
, &hkey
))
1781 WARN("No PSFactoryBuffer object is registered for IID %s\n", debugstr_guid(riid
));
1782 return REGDB_E_IIDNOTREG
;
1785 /* ... Once we have the key, query the registry to get the
1786 value of CLSID as a string, and convert it into a
1787 proper CLSID structure to be passed back to the app */
1788 len
= sizeof(value
);
1789 if (ERROR_SUCCESS
!= RegQueryValueW(hkey
, NULL
, value
, &len
))
1792 return REGDB_E_IIDNOTREG
;
1796 /* We have the CLSID we want back from the registry as a string, so
1797 let's convert it into a CLSID structure */
1798 if (CLSIDFromString(value
, pclsid
) != NOERROR
)
1799 return REGDB_E_IIDNOTREG
;
1801 TRACE ("() Returning CLSID=%s\n", debugstr_guid(pclsid
));
1805 /*****************************************************************************
1806 * CoRegisterPSClsid [OLE32.@]
1808 * Register a proxy/stub CLSID for the given interface in the current process
1812 * riid [I] Interface whose proxy/stub CLSID is to be registered.
1813 * rclsid [I] CLSID of the proxy/stub.
1817 * Failure: E_OUTOFMEMORY
1821 * This function does not add anything to the registry and the effects are
1822 * limited to the lifetime of the current process.
1827 HRESULT WINAPI
CoRegisterPSClsid(REFIID riid
, REFCLSID rclsid
)
1829 APARTMENT
*apt
= COM_CurrentApt();
1830 struct registered_psclsid
*registered_psclsid
;
1832 TRACE("(%s, %s)\n", debugstr_guid(riid
), debugstr_guid(rclsid
));
1836 ERR("apartment not initialised\n");
1837 return CO_E_NOTINITIALIZED
;
1840 EnterCriticalSection(&apt
->cs
);
1842 LIST_FOR_EACH_ENTRY(registered_psclsid
, &apt
->psclsids
, struct registered_psclsid
, entry
)
1843 if (IsEqualIID(®istered_psclsid
->iid
, riid
))
1845 registered_psclsid
->clsid
= *rclsid
;
1846 LeaveCriticalSection(&apt
->cs
);
1850 registered_psclsid
= HeapAlloc(GetProcessHeap(), 0, sizeof(struct registered_psclsid
));
1851 if (!registered_psclsid
)
1853 LeaveCriticalSection(&apt
->cs
);
1854 return E_OUTOFMEMORY
;
1857 registered_psclsid
->iid
= *riid
;
1858 registered_psclsid
->clsid
= *rclsid
;
1859 list_add_head(&apt
->psclsids
, ®istered_psclsid
->entry
);
1861 LeaveCriticalSection(&apt
->cs
);
1868 * COM_GetRegisteredClassObject
1870 * This internal method is used to scan the registered class list to
1871 * find a class object.
1874 * rclsid Class ID of the class to find.
1875 * dwClsContext Class context to match.
1876 * ppv [out] returns a pointer to the class object. Complying
1877 * to normal COM usage, this method will increase the
1878 * reference count on this object.
1880 static HRESULT
COM_GetRegisteredClassObject(const struct apartment
*apt
, REFCLSID rclsid
,
1881 DWORD dwClsContext
, LPUNKNOWN
* ppUnk
)
1883 HRESULT hr
= S_FALSE
;
1884 RegisteredClass
*curClass
;
1886 EnterCriticalSection( &csRegisteredClassList
);
1888 LIST_FOR_EACH_ENTRY(curClass
, &RegisteredClassList
, RegisteredClass
, entry
)
1891 * Check if we have a match on the class ID and context.
1893 if ((apt
->oxid
== curClass
->apartment_id
) &&
1894 (dwClsContext
& curClass
->runContext
) &&
1895 IsEqualGUID(&(curClass
->classIdentifier
), rclsid
))
1898 * We have a match, return the pointer to the class object.
1900 *ppUnk
= curClass
->classObject
;
1902 IUnknown_AddRef(curClass
->classObject
);
1909 LeaveCriticalSection( &csRegisteredClassList
);
1914 /******************************************************************************
1915 * CoRegisterClassObject [OLE32.@]
1917 * Registers the class object for a given class ID. Servers housed in EXE
1918 * files use this method instead of exporting DllGetClassObject to allow
1919 * other code to connect to their objects.
1922 * rclsid [I] CLSID of the object to register.
1923 * pUnk [I] IUnknown of the object.
1924 * dwClsContext [I] CLSCTX flags indicating the context in which to run the executable.
1925 * flags [I] REGCLS flags indicating how connections are made.
1926 * lpdwRegister [I] A unique cookie that can be passed to CoRevokeClassObject.
1930 * E_INVALIDARG if lpdwRegister or pUnk are NULL,
1931 * CO_E_OBJISREG if the object is already registered. We should not return this.
1934 * CoRevokeClassObject, CoGetClassObject
1937 * In-process objects are only registered for the current apartment.
1938 * CoGetClassObject() and CoCreateInstance() will not return objects registered
1939 * in other apartments.
1942 * MSDN claims that multiple interface registrations are legal, but we
1943 * can't do that with our current implementation.
1945 HRESULT WINAPI
CoRegisterClassObject(
1950 LPDWORD lpdwRegister
)
1952 RegisteredClass
* newClass
;
1953 LPUNKNOWN foundObject
;
1957 TRACE("(%s,%p,0x%08x,0x%08x,%p)\n",
1958 debugstr_guid(rclsid
),pUnk
,dwClsContext
,flags
,lpdwRegister
);
1960 if ( (lpdwRegister
==0) || (pUnk
==0) )
1961 return E_INVALIDARG
;
1963 apt
= COM_CurrentApt();
1966 ERR("COM was not initialized\n");
1967 return CO_E_NOTINITIALIZED
;
1972 /* REGCLS_MULTIPLEUSE implies registering as inproc server. This is what
1973 * differentiates the flag from REGCLS_MULTI_SEPARATE. */
1974 if (flags
& REGCLS_MULTIPLEUSE
)
1975 dwClsContext
|= CLSCTX_INPROC_SERVER
;
1978 * First, check if the class is already registered.
1979 * If it is, this should cause an error.
1981 hr
= COM_GetRegisteredClassObject(apt
, rclsid
, dwClsContext
, &foundObject
);
1983 if (flags
& REGCLS_MULTIPLEUSE
) {
1984 if (dwClsContext
& CLSCTX_LOCAL_SERVER
)
1985 hr
= CoLockObjectExternal(foundObject
, TRUE
, FALSE
);
1986 IUnknown_Release(foundObject
);
1989 IUnknown_Release(foundObject
);
1990 ERR("object already registered for class %s\n", debugstr_guid(rclsid
));
1991 return CO_E_OBJISREG
;
1994 newClass
= HeapAlloc(GetProcessHeap(), 0, sizeof(RegisteredClass
));
1995 if ( newClass
== NULL
)
1996 return E_OUTOFMEMORY
;
1998 newClass
->classIdentifier
= *rclsid
;
1999 newClass
->apartment_id
= apt
->oxid
;
2000 newClass
->runContext
= dwClsContext
;
2001 newClass
->connectFlags
= flags
;
2002 newClass
->pMarshaledData
= NULL
;
2003 newClass
->RpcRegistration
= NULL
;
2006 * Use the address of the chain node as the cookie since we are sure it's
2007 * unique. FIXME: not on 64-bit platforms.
2009 newClass
->dwCookie
= (DWORD
)newClass
;
2012 * Since we're making a copy of the object pointer, we have to increase its
2015 newClass
->classObject
= pUnk
;
2016 IUnknown_AddRef(newClass
->classObject
);
2018 EnterCriticalSection( &csRegisteredClassList
);
2019 list_add_tail(&RegisteredClassList
, &newClass
->entry
);
2020 LeaveCriticalSection( &csRegisteredClassList
);
2022 *lpdwRegister
= newClass
->dwCookie
;
2024 if (dwClsContext
& CLSCTX_LOCAL_SERVER
) {
2025 hr
= CreateStreamOnHGlobal(0, TRUE
, &newClass
->pMarshaledData
);
2027 FIXME("Failed to create stream on hglobal, %x\n", hr
);
2030 hr
= CoMarshalInterface(newClass
->pMarshaledData
, &IID_IClassFactory
,
2031 newClass
->classObject
, MSHCTX_LOCAL
, NULL
,
2032 MSHLFLAGS_TABLESTRONG
);
2034 FIXME("CoMarshalInterface failed, %x!\n",hr
);
2038 hr
= RPC_StartLocalServer(&newClass
->classIdentifier
,
2039 newClass
->pMarshaledData
,
2040 flags
& (REGCLS_MULTIPLEUSE
|REGCLS_MULTI_SEPARATE
),
2041 &newClass
->RpcRegistration
);
2046 static void COM_RevokeRegisteredClassObject(RegisteredClass
*curClass
)
2048 list_remove(&curClass
->entry
);
2050 if (curClass
->runContext
& CLSCTX_LOCAL_SERVER
)
2051 RPC_StopLocalServer(curClass
->RpcRegistration
);
2054 * Release the reference to the class object.
2056 IUnknown_Release(curClass
->classObject
);
2058 if (curClass
->pMarshaledData
)
2061 memset(&zero
, 0, sizeof(zero
));
2062 IStream_Seek(curClass
->pMarshaledData
, zero
, STREAM_SEEK_SET
, NULL
);
2063 CoReleaseMarshalData(curClass
->pMarshaledData
);
2064 IStream_Release(curClass
->pMarshaledData
);
2067 HeapFree(GetProcessHeap(), 0, curClass
);
2070 static void COM_RevokeAllClasses(const struct apartment
*apt
)
2072 RegisteredClass
*curClass
, *cursor
;
2074 EnterCriticalSection( &csRegisteredClassList
);
2076 LIST_FOR_EACH_ENTRY_SAFE(curClass
, cursor
, &RegisteredClassList
, RegisteredClass
, entry
)
2078 if (curClass
->apartment_id
== apt
->oxid
)
2079 COM_RevokeRegisteredClassObject(curClass
);
2082 LeaveCriticalSection( &csRegisteredClassList
);
2085 /***********************************************************************
2086 * CoRevokeClassObject [OLE32.@]
2088 * Removes a class object from the class registry.
2091 * dwRegister [I] Cookie returned from CoRegisterClassObject().
2095 * Failure: HRESULT code.
2098 * Must be called from the same apartment that called CoRegisterClassObject(),
2099 * otherwise it will fail with RPC_E_WRONG_THREAD.
2102 * CoRegisterClassObject
2104 HRESULT WINAPI
CoRevokeClassObject(
2107 HRESULT hr
= E_INVALIDARG
;
2108 RegisteredClass
*curClass
;
2111 TRACE("(%08x)\n",dwRegister
);
2113 apt
= COM_CurrentApt();
2116 ERR("COM was not initialized\n");
2117 return CO_E_NOTINITIALIZED
;
2120 EnterCriticalSection( &csRegisteredClassList
);
2122 LIST_FOR_EACH_ENTRY(curClass
, &RegisteredClassList
, RegisteredClass
, entry
)
2125 * Check if we have a match on the cookie.
2127 if (curClass
->dwCookie
== dwRegister
)
2129 if (curClass
->apartment_id
== apt
->oxid
)
2131 COM_RevokeRegisteredClassObject(curClass
);
2136 ERR("called from wrong apartment, should be called from %s\n",
2137 wine_dbgstr_longlong(curClass
->apartment_id
));
2138 hr
= RPC_E_WRONG_THREAD
;
2144 LeaveCriticalSection( &csRegisteredClassList
);
2149 /***********************************************************************
2150 * COM_RegReadPath [internal]
2152 * Reads a registry value and expands it when necessary
2154 static DWORD
COM_RegReadPath(HKEY hkeyroot
, const WCHAR
*keyname
, const WCHAR
*valuename
, WCHAR
* dst
, DWORD dstlen
)
2159 WCHAR src
[MAX_PATH
];
2160 DWORD dwLength
= dstlen
* sizeof(WCHAR
);
2162 if((ret
= RegOpenKeyExW(hkeyroot
, keyname
, 0, KEY_READ
, &key
)) == ERROR_SUCCESS
) {
2163 if( (ret
= RegQueryValueExW(key
, NULL
, NULL
, &keytype
, (LPBYTE
)src
, &dwLength
)) == ERROR_SUCCESS
) {
2164 if (keytype
== REG_EXPAND_SZ
) {
2165 if (dstlen
<= ExpandEnvironmentStringsW(src
, dst
, dstlen
)) ret
= ERROR_MORE_DATA
;
2167 lstrcpynW(dst
, src
, dstlen
);
2175 static void get_threading_model(HKEY key
, LPWSTR value
, DWORD len
)
2177 static const WCHAR wszThreadingModel
[] = {'T','h','r','e','a','d','i','n','g','M','o','d','e','l',0};
2180 DWORD dwLength
= len
* sizeof(WCHAR
);
2182 ret
= RegQueryValueExW(key
, wszThreadingModel
, NULL
, &keytype
, (LPBYTE
)value
, &dwLength
);
2183 if ((ret
!= ERROR_SUCCESS
) || (keytype
!= REG_SZ
))
2187 static HRESULT
get_inproc_class_object(APARTMENT
*apt
, HKEY hkeydll
,
2188 REFCLSID rclsid
, REFIID riid
,
2189 BOOL hostifnecessary
, void **ppv
)
2191 WCHAR dllpath
[MAX_PATH
+1];
2192 BOOL apartment_threaded
;
2194 if (hostifnecessary
)
2196 static const WCHAR wszApartment
[] = {'A','p','a','r','t','m','e','n','t',0};
2197 static const WCHAR wszFree
[] = {'F','r','e','e',0};
2198 static const WCHAR wszBoth
[] = {'B','o','t','h',0};
2199 WCHAR threading_model
[10 /* strlenW(L"apartment")+1 */];
2201 get_threading_model(hkeydll
, threading_model
, ARRAYSIZE(threading_model
));
2203 if (!strcmpiW(threading_model
, wszApartment
))
2205 apartment_threaded
= TRUE
;
2206 if (apt
->multi_threaded
)
2207 return apartment_hostobject_in_hostapt(apt
, FALSE
, FALSE
, hkeydll
, rclsid
, riid
, ppv
);
2210 else if (!strcmpiW(threading_model
, wszFree
))
2212 apartment_threaded
= FALSE
;
2213 if (!apt
->multi_threaded
)
2214 return apartment_hostobject_in_hostapt(apt
, TRUE
, FALSE
, hkeydll
, rclsid
, riid
, ppv
);
2216 /* everything except "Apartment", "Free" and "Both" */
2217 else if (strcmpiW(threading_model
, wszBoth
))
2219 apartment_threaded
= TRUE
;
2220 /* everything else is main-threaded */
2221 if (threading_model
[0])
2222 FIXME("unrecognised threading model %s for object %s, should be main-threaded?\n",
2223 debugstr_w(threading_model
), debugstr_guid(rclsid
));
2225 if (apt
->multi_threaded
|| !apt
->main
)
2226 return apartment_hostobject_in_hostapt(apt
, FALSE
, TRUE
, hkeydll
, rclsid
, riid
, ppv
);
2229 apartment_threaded
= FALSE
;
2232 apartment_threaded
= !apt
->multi_threaded
;
2234 if (COM_RegReadPath(hkeydll
, NULL
, NULL
, dllpath
, ARRAYSIZE(dllpath
)) != ERROR_SUCCESS
)
2236 /* failure: CLSID is not found in registry */
2237 WARN("class %s not registered inproc\n", debugstr_guid(rclsid
));
2238 return REGDB_E_CLASSNOTREG
;
2241 return apartment_getclassobject(apt
, dllpath
, apartment_threaded
,
2245 /***********************************************************************
2246 * CoGetClassObject [OLE32.@]
2248 * Creates an object of the specified class.
2251 * rclsid [I] Class ID to create an instance of.
2252 * dwClsContext [I] Flags to restrict the location of the created instance.
2253 * pServerInfo [I] Optional. Details for connecting to a remote server.
2254 * iid [I] The ID of the interface of the instance to return.
2255 * ppv [O] On returns, contains a pointer to the specified interface of the object.
2259 * Failure: HRESULT code.
2262 * The dwClsContext parameter can be one or more of the following:
2263 *| CLSCTX_INPROC_SERVER - Use an in-process server, such as from a DLL.
2264 *| CLSCTX_INPROC_HANDLER - Use an in-process object which handles certain functions for an object running in another process.
2265 *| CLSCTX_LOCAL_SERVER - Connect to an object running in another process.
2266 *| CLSCTX_REMOTE_SERVER - Connect to an object running on another machine.
2269 * CoCreateInstance()
2271 HRESULT WINAPI
CoGetClassObject(
2272 REFCLSID rclsid
, DWORD dwClsContext
, COSERVERINFO
*pServerInfo
,
2273 REFIID iid
, LPVOID
*ppv
)
2275 LPUNKNOWN regClassObject
;
2276 HRESULT hres
= E_UNEXPECTED
;
2279 TRACE("\n\tCLSID:\t%s,\n\tIID:\t%s\n", debugstr_guid(rclsid
), debugstr_guid(iid
));
2282 return E_INVALIDARG
;
2286 apt
= COM_CurrentApt();
2289 ERR("apartment not initialised\n");
2290 return CO_E_NOTINITIALIZED
;
2294 FIXME("\tpServerInfo: name=%s\n",debugstr_w(pServerInfo
->pwszName
));
2295 FIXME("\t\tpAuthInfo=%p\n",pServerInfo
->pAuthInfo
);
2299 * First, try and see if we can't match the class ID with one of the
2300 * registered classes.
2302 if (S_OK
== COM_GetRegisteredClassObject(apt
, rclsid
, dwClsContext
,
2305 /* Get the required interface from the retrieved pointer. */
2306 hres
= IUnknown_QueryInterface(regClassObject
, iid
, ppv
);
2309 * Since QI got another reference on the pointer, we want to release the
2310 * one we already have. If QI was unsuccessful, this will release the object. This
2311 * is good since we are not returning it in the "out" parameter.
2313 IUnknown_Release(regClassObject
);
2318 /* First try in-process server */
2319 if (CLSCTX_INPROC_SERVER
& dwClsContext
)
2321 static const WCHAR wszInprocServer32
[] = {'I','n','p','r','o','c','S','e','r','v','e','r','3','2',0};
2324 if (IsEqualCLSID(rclsid
, &CLSID_InProcFreeMarshaler
))
2325 return FTMarshalCF_Create(iid
, ppv
);
2327 hres
= COM_OpenKeyForCLSID(rclsid
, wszInprocServer32
, KEY_READ
, &hkey
);
2330 if (hres
== REGDB_E_CLASSNOTREG
)
2331 ERR("class %s not registered\n", debugstr_guid(rclsid
));
2332 else if (hres
== REGDB_E_KEYMISSING
)
2334 WARN("class %s not registered as in-proc server\n", debugstr_guid(rclsid
));
2335 hres
= REGDB_E_CLASSNOTREG
;
2339 if (SUCCEEDED(hres
))
2341 hres
= get_inproc_class_object(apt
, hkey
, rclsid
, iid
,
2342 !(dwClsContext
& WINE_CLSCTX_DONT_HOST
), ppv
);
2346 /* return if we got a class, otherwise fall through to one of the
2348 if (SUCCEEDED(hres
))
2352 /* Next try in-process handler */
2353 if (CLSCTX_INPROC_HANDLER
& dwClsContext
)
2355 static const WCHAR wszInprocHandler32
[] = {'I','n','p','r','o','c','H','a','n','d','l','e','r','3','2',0};
2358 hres
= COM_OpenKeyForCLSID(rclsid
, wszInprocHandler32
, KEY_READ
, &hkey
);
2361 if (hres
== REGDB_E_CLASSNOTREG
)
2362 ERR("class %s not registered\n", debugstr_guid(rclsid
));
2363 else if (hres
== REGDB_E_KEYMISSING
)
2365 WARN("class %s not registered in-proc handler\n", debugstr_guid(rclsid
));
2366 hres
= REGDB_E_CLASSNOTREG
;
2370 if (SUCCEEDED(hres
))
2372 hres
= get_inproc_class_object(apt
, hkey
, rclsid
, iid
,
2373 !(dwClsContext
& WINE_CLSCTX_DONT_HOST
), ppv
);
2377 /* return if we got a class, otherwise fall through to one of the
2379 if (SUCCEEDED(hres
))
2383 /* Next try out of process */
2384 if (CLSCTX_LOCAL_SERVER
& dwClsContext
)
2386 hres
= RPC_GetLocalClassObject(rclsid
,iid
,ppv
);
2387 if (SUCCEEDED(hres
))
2391 /* Finally try remote: this requires networked DCOM (a lot of work) */
2392 if (CLSCTX_REMOTE_SERVER
& dwClsContext
)
2394 FIXME ("CLSCTX_REMOTE_SERVER not supported\n");
2395 hres
= E_NOINTERFACE
;
2399 ERR("no class object %s could be created for context 0x%x\n",
2400 debugstr_guid(rclsid
), dwClsContext
);
2404 /***********************************************************************
2405 * CoResumeClassObjects (OLE32.@)
2407 * Resumes all class objects registered with REGCLS_SUSPENDED.
2411 * Failure: HRESULT code.
2413 HRESULT WINAPI
CoResumeClassObjects(void)
2419 /***********************************************************************
2420 * CoCreateInstance [OLE32.@]
2422 * Creates an instance of the specified class.
2425 * rclsid [I] Class ID to create an instance of.
2426 * pUnkOuter [I] Optional outer unknown to allow aggregation with another object.
2427 * dwClsContext [I] Flags to restrict the location of the created instance.
2428 * iid [I] The ID of the interface of the instance to return.
2429 * ppv [O] On returns, contains a pointer to the specified interface of the instance.
2433 * Failure: HRESULT code.
2436 * The dwClsContext parameter can be one or more of the following:
2437 *| CLSCTX_INPROC_SERVER - Use an in-process server, such as from a DLL.
2438 *| CLSCTX_INPROC_HANDLER - Use an in-process object which handles certain functions for an object running in another process.
2439 *| CLSCTX_LOCAL_SERVER - Connect to an object running in another process.
2440 *| CLSCTX_REMOTE_SERVER - Connect to an object running on another machine.
2442 * Aggregation is the concept of deferring the IUnknown of an object to another
2443 * object. This allows a separate object to behave as though it was part of
2444 * the object and to allow this the pUnkOuter parameter can be set. Note that
2445 * not all objects support having an outer of unknown.
2448 * CoGetClassObject()
2450 HRESULT WINAPI
CoCreateInstance(
2452 LPUNKNOWN pUnkOuter
,
2458 LPCLASSFACTORY lpclf
= 0;
2460 TRACE("(rclsid=%s, pUnkOuter=%p, dwClsContext=%08x, riid=%s, ppv=%p)\n", debugstr_guid(rclsid
),
2461 pUnkOuter
, dwClsContext
, debugstr_guid(iid
), ppv
);
2470 * Initialize the "out" parameter
2474 if (!COM_CurrentApt())
2476 ERR("apartment not initialised\n");
2477 return CO_E_NOTINITIALIZED
;
2481 * The Standard Global Interface Table (GIT) object is a process-wide singleton.
2482 * Rather than create a class factory, we can just check for it here
2484 if (IsEqualIID(rclsid
, &CLSID_StdGlobalInterfaceTable
)) {
2485 if (StdGlobalInterfaceTableInstance
== NULL
)
2486 StdGlobalInterfaceTableInstance
= StdGlobalInterfaceTable_Construct();
2487 hres
= IGlobalInterfaceTable_QueryInterface( (IGlobalInterfaceTable
*) StdGlobalInterfaceTableInstance
, iid
, ppv
);
2488 if (hres
) return hres
;
2490 TRACE("Retrieved GIT (%p)\n", *ppv
);
2495 * Get a class factory to construct the object we want.
2497 hres
= CoGetClassObject(rclsid
,
2507 * Create the object and don't forget to release the factory
2509 hres
= IClassFactory_CreateInstance(lpclf
, pUnkOuter
, iid
, ppv
);
2510 IClassFactory_Release(lpclf
);
2513 if (hres
== CLASS_E_NOAGGREGATION
&& pUnkOuter
)
2514 FIXME("Class %s does not support aggregation\n", debugstr_guid(rclsid
));
2516 FIXME("no instance created for interface %s of class %s, hres is 0x%08x\n", debugstr_guid(iid
), debugstr_guid(rclsid
),hres
);
2522 /***********************************************************************
2523 * CoCreateInstanceEx [OLE32.@]
2525 HRESULT WINAPI
CoCreateInstanceEx(
2527 LPUNKNOWN pUnkOuter
,
2529 COSERVERINFO
* pServerInfo
,
2533 IUnknown
* pUnk
= NULL
;
2536 ULONG successCount
= 0;
2541 if ( (cmq
==0) || (pResults
==NULL
))
2542 return E_INVALIDARG
;
2544 if (pServerInfo
!=NULL
)
2545 FIXME("() non-NULL pServerInfo not supported!\n");
2548 * Initialize all the "out" parameters.
2550 for (index
= 0; index
< cmq
; index
++)
2552 pResults
[index
].pItf
= NULL
;
2553 pResults
[index
].hr
= E_NOINTERFACE
;
2557 * Get the object and get its IUnknown pointer.
2559 hr
= CoCreateInstance(rclsid
,
2569 * Then, query for all the interfaces requested.
2571 for (index
= 0; index
< cmq
; index
++)
2573 pResults
[index
].hr
= IUnknown_QueryInterface(pUnk
,
2574 pResults
[index
].pIID
,
2575 (VOID
**)&(pResults
[index
].pItf
));
2577 if (pResults
[index
].hr
== S_OK
)
2582 * Release our temporary unknown pointer.
2584 IUnknown_Release(pUnk
);
2586 if (successCount
== 0)
2587 return E_NOINTERFACE
;
2589 if (successCount
!=cmq
)
2590 return CO_S_NOTALLINTERFACES
;
2595 /***********************************************************************
2596 * CoLoadLibrary (OLE32.@)
2601 * lpszLibName [I] Path to library.
2602 * bAutoFree [I] Whether the library should automatically be freed.
2605 * Success: Handle to loaded library.
2609 * CoFreeLibrary, CoFreeAllLibraries, CoFreeUnusedLibraries
2611 HINSTANCE WINAPI
CoLoadLibrary(LPOLESTR lpszLibName
, BOOL bAutoFree
)
2613 TRACE("(%s, %d)\n", debugstr_w(lpszLibName
), bAutoFree
);
2615 return LoadLibraryExW(lpszLibName
, 0, LOAD_WITH_ALTERED_SEARCH_PATH
);
2618 /***********************************************************************
2619 * CoFreeLibrary [OLE32.@]
2621 * Unloads a library from memory.
2624 * hLibrary [I] Handle to library to unload.
2630 * CoLoadLibrary, CoFreeAllLibraries, CoFreeUnusedLibraries
2632 void WINAPI
CoFreeLibrary(HINSTANCE hLibrary
)
2634 FreeLibrary(hLibrary
);
2638 /***********************************************************************
2639 * CoFreeAllLibraries [OLE32.@]
2641 * Function for backwards compatibility only. Does nothing.
2647 * CoLoadLibrary, CoFreeLibrary, CoFreeUnusedLibraries
2649 void WINAPI
CoFreeAllLibraries(void)
2654 /***********************************************************************
2655 * CoFreeUnusedLibrariesEx [OLE32.@]
2657 * Frees any previously unused libraries whose delay has expired and marks
2658 * currently unused libraries for unloading. Unused are identified as those that
2659 * return S_OK from their DllCanUnloadNow function.
2662 * dwUnloadDelay [I] Unload delay in milliseconds.
2663 * dwReserved [I] Reserved. Set to 0.
2669 * CoLoadLibrary, CoFreeAllLibraries, CoFreeLibrary
2671 void WINAPI
CoFreeUnusedLibrariesEx(DWORD dwUnloadDelay
, DWORD dwReserved
)
2673 struct apartment
*apt
= COM_CurrentApt();
2676 ERR("apartment not initialised\n");
2680 apartment_freeunusedlibraries(apt
, dwUnloadDelay
);
2683 /***********************************************************************
2684 * CoFreeUnusedLibraries [OLE32.@]
2685 * CoFreeUnusedLibraries [COMPOBJ.17]
2687 * Frees any unused libraries. Unused are identified as those that return
2688 * S_OK from their DllCanUnloadNow function.
2694 * CoLoadLibrary, CoFreeAllLibraries, CoFreeLibrary
2696 void WINAPI
CoFreeUnusedLibraries(void)
2698 CoFreeUnusedLibrariesEx(INFINITE
, 0);
2701 /***********************************************************************
2702 * CoFileTimeNow [OLE32.@]
2703 * CoFileTimeNow [COMPOBJ.82]
2705 * Retrieves the current time in FILETIME format.
2708 * lpFileTime [O] The current time.
2713 HRESULT WINAPI
CoFileTimeNow( FILETIME
*lpFileTime
)
2715 GetSystemTimeAsFileTime( lpFileTime
);
2719 /******************************************************************************
2720 * CoLockObjectExternal [OLE32.@]
2722 * Increments or decrements the external reference count of a stub object.
2725 * pUnk [I] Stub object.
2726 * fLock [I] If TRUE then increments the external ref-count,
2727 * otherwise decrements.
2728 * fLastUnlockReleases [I] If TRUE then the last unlock has the effect of
2729 * calling CoDisconnectObject.
2733 * Failure: HRESULT code.
2736 * If fLock is TRUE and an object is passed in that doesn't have a stub
2737 * manager then a new stub manager is created for the object.
2739 HRESULT WINAPI
CoLockObjectExternal(
2742 BOOL fLastUnlockReleases
)
2744 struct stub_manager
*stubmgr
;
2745 struct apartment
*apt
;
2747 TRACE("pUnk=%p, fLock=%s, fLastUnlockReleases=%s\n",
2748 pUnk
, fLock
? "TRUE" : "FALSE", fLastUnlockReleases
? "TRUE" : "FALSE");
2750 apt
= COM_CurrentApt();
2751 if (!apt
) return CO_E_NOTINITIALIZED
;
2753 stubmgr
= get_stub_manager_from_object(apt
, pUnk
);
2758 stub_manager_ext_addref(stubmgr
, 1, FALSE
);
2760 stub_manager_ext_release(stubmgr
, 1, FALSE
, fLastUnlockReleases
);
2762 stub_manager_int_release(stubmgr
);
2768 stubmgr
= new_stub_manager(apt
, pUnk
);
2772 stub_manager_ext_addref(stubmgr
, 1, FALSE
);
2773 stub_manager_int_release(stubmgr
);
2780 WARN("stub object not found %p\n", pUnk
);
2781 /* Note: native is pretty broken here because it just silently
2782 * fails, without returning an appropriate error code, making apps
2783 * think that the object was disconnected, when it actually wasn't */
2788 /***********************************************************************
2789 * CoInitializeWOW (OLE32.@)
2791 * WOW equivalent of CoInitialize?
2800 HRESULT WINAPI
CoInitializeWOW(DWORD x
,DWORD y
)
2802 FIXME("(0x%08x,0x%08x),stub!\n",x
,y
);
2806 /***********************************************************************
2807 * CoGetState [OLE32.@]
2809 * Retrieves the thread state object previously stored by CoSetState().
2812 * ppv [I] Address where pointer to object will be stored.
2816 * Failure: E_OUTOFMEMORY.
2819 * Crashes on all invalid ppv addresses, including NULL.
2820 * If the function returns a non-NULL object then the caller must release its
2821 * reference on the object when the object is no longer required.
2826 HRESULT WINAPI
CoGetState(IUnknown
** ppv
)
2828 struct oletls
*info
= COM_CurrentInfo();
2829 if (!info
) return E_OUTOFMEMORY
;
2835 IUnknown_AddRef(info
->state
);
2837 TRACE("apt->state=%p\n", info
->state
);
2843 /***********************************************************************
2844 * CoSetState [OLE32.@]
2846 * Sets the thread state object.
2849 * pv [I] Pointer to state object to be stored.
2852 * The system keeps a reference on the object while the object stored.
2856 * Failure: E_OUTOFMEMORY.
2858 HRESULT WINAPI
CoSetState(IUnknown
* pv
)
2860 struct oletls
*info
= COM_CurrentInfo();
2861 if (!info
) return E_OUTOFMEMORY
;
2863 if (pv
) IUnknown_AddRef(pv
);
2867 TRACE("-- release %p now\n", info
->state
);
2868 IUnknown_Release(info
->state
);
2877 /******************************************************************************
2878 * CoTreatAsClass [OLE32.@]
2880 * Sets the TreatAs value of a class.
2883 * clsidOld [I] Class to set TreatAs value on.
2884 * clsidNew [I] The class the clsidOld should be treated as.
2888 * Failure: HRESULT code.
2893 HRESULT WINAPI
CoTreatAsClass(REFCLSID clsidOld
, REFCLSID clsidNew
)
2895 static const WCHAR wszAutoTreatAs
[] = {'A','u','t','o','T','r','e','a','t','A','s',0};
2896 static const WCHAR wszTreatAs
[] = {'T','r','e','a','t','A','s',0};
2898 WCHAR szClsidNew
[CHARS_IN_GUID
];
2900 WCHAR auto_treat_as
[CHARS_IN_GUID
];
2901 LONG auto_treat_as_size
= sizeof(auto_treat_as
);
2904 res
= COM_OpenKeyForCLSID(clsidOld
, NULL
, KEY_READ
| KEY_WRITE
, &hkey
);
2907 if (!memcmp( clsidOld
, clsidNew
, sizeof(*clsidOld
) ))
2909 if (!RegQueryValueW(hkey
, wszAutoTreatAs
, auto_treat_as
, &auto_treat_as_size
) &&
2910 CLSIDFromString(auto_treat_as
, &id
) == S_OK
)
2912 if (RegSetValueW(hkey
, wszTreatAs
, REG_SZ
, auto_treat_as
, sizeof(auto_treat_as
)))
2914 res
= REGDB_E_WRITEREGDB
;
2920 RegDeleteKeyW(hkey
, wszTreatAs
);
2924 else if (!StringFromGUID2(clsidNew
, szClsidNew
, ARRAYSIZE(szClsidNew
)) &&
2925 !RegSetValueW(hkey
, wszTreatAs
, REG_SZ
, szClsidNew
, sizeof(szClsidNew
)))
2927 res
= REGDB_E_WRITEREGDB
;
2932 if (hkey
) RegCloseKey(hkey
);
2936 /******************************************************************************
2937 * CoGetTreatAsClass [OLE32.@]
2939 * Gets the TreatAs value of a class.
2942 * clsidOld [I] Class to get the TreatAs value of.
2943 * clsidNew [I] The class the clsidOld should be treated as.
2947 * Failure: HRESULT code.
2952 HRESULT WINAPI
CoGetTreatAsClass(REFCLSID clsidOld
, LPCLSID clsidNew
)
2954 static const WCHAR wszTreatAs
[] = {'T','r','e','a','t','A','s',0};
2956 WCHAR szClsidNew
[CHARS_IN_GUID
];
2958 LONG len
= sizeof(szClsidNew
);
2960 FIXME("(%s,%p)\n", debugstr_guid(clsidOld
), clsidNew
);
2961 *clsidNew
= *clsidOld
; /* copy over old value */
2963 res
= COM_OpenKeyForCLSID(clsidOld
, wszTreatAs
, KEY_READ
, &hkey
);
2966 if (RegQueryValueW(hkey
, NULL
, szClsidNew
, &len
))
2971 res
= CLSIDFromString(szClsidNew
,clsidNew
);
2973 ERR("Failed CLSIDFromStringA(%s), hres 0x%08x\n", debugstr_w(szClsidNew
), res
);
2975 if (hkey
) RegCloseKey(hkey
);
2979 /******************************************************************************
2980 * CoGetCurrentProcess [OLE32.@]
2981 * CoGetCurrentProcess [COMPOBJ.34]
2983 * Gets the current process ID.
2986 * The current process ID.
2989 * Is DWORD really the correct return type for this function?
2991 DWORD WINAPI
CoGetCurrentProcess(void)
2993 return GetCurrentProcessId();
2996 /******************************************************************************
2997 * CoRegisterMessageFilter [OLE32.@]
2999 * Registers a message filter.
3002 * lpMessageFilter [I] Pointer to interface.
3003 * lplpMessageFilter [O] Indirect pointer to prior instance if non-NULL.
3007 * Failure: HRESULT code.
3010 * Both lpMessageFilter and lplpMessageFilter are optional. Passing in a NULL
3011 * lpMessageFilter removes the message filter.
3013 * If lplpMessageFilter is not NULL the previous message filter will be
3014 * returned in the memory pointer to this parameter and the caller is
3015 * responsible for releasing the object.
3017 * The current thread be in an apartment otherwise the function will crash.
3019 HRESULT WINAPI
CoRegisterMessageFilter(
3020 LPMESSAGEFILTER lpMessageFilter
,
3021 LPMESSAGEFILTER
*lplpMessageFilter
)
3023 struct apartment
*apt
;
3024 IMessageFilter
*lpOldMessageFilter
;
3026 TRACE("(%p, %p)\n", lpMessageFilter
, lplpMessageFilter
);
3028 apt
= COM_CurrentApt();
3030 /* can't set a message filter in a multi-threaded apartment */
3031 if (!apt
|| apt
->multi_threaded
)
3033 WARN("can't set message filter in MTA or uninitialized apt\n");
3034 return CO_E_NOT_SUPPORTED
;
3037 if (lpMessageFilter
)
3038 IMessageFilter_AddRef(lpMessageFilter
);
3040 EnterCriticalSection(&apt
->cs
);
3042 lpOldMessageFilter
= apt
->filter
;
3043 apt
->filter
= lpMessageFilter
;
3045 LeaveCriticalSection(&apt
->cs
);
3047 if (lplpMessageFilter
)
3048 *lplpMessageFilter
= lpOldMessageFilter
;
3049 else if (lpOldMessageFilter
)
3050 IMessageFilter_Release(lpOldMessageFilter
);
3055 /***********************************************************************
3056 * CoIsOle1Class [OLE32.@]
3058 * Determines whether the specified class an OLE v1 class.
3061 * clsid [I] Class to test.
3064 * TRUE if the class is an OLE v1 class, or FALSE otherwise.
3066 BOOL WINAPI
CoIsOle1Class(REFCLSID clsid
)
3068 FIXME("%s\n", debugstr_guid(clsid
));
3072 /***********************************************************************
3073 * IsEqualGUID [OLE32.@]
3075 * Compares two Unique Identifiers.
3078 * rguid1 [I] The first GUID to compare.
3079 * rguid2 [I] The other GUID to compare.
3085 BOOL WINAPI
IsEqualGUID(
3089 return !memcmp(rguid1
,rguid2
,sizeof(GUID
));
3092 /***********************************************************************
3093 * CoInitializeSecurity [OLE32.@]
3095 HRESULT WINAPI
CoInitializeSecurity(PSECURITY_DESCRIPTOR pSecDesc
, LONG cAuthSvc
,
3096 SOLE_AUTHENTICATION_SERVICE
* asAuthSvc
,
3097 void* pReserved1
, DWORD dwAuthnLevel
,
3098 DWORD dwImpLevel
, void* pReserved2
,
3099 DWORD dwCapabilities
, void* pReserved3
)
3101 FIXME("(%p,%d,%p,%p,%d,%d,%p,%d,%p) - stub!\n", pSecDesc
, cAuthSvc
,
3102 asAuthSvc
, pReserved1
, dwAuthnLevel
, dwImpLevel
, pReserved2
,
3103 dwCapabilities
, pReserved3
);
3107 /***********************************************************************
3108 * CoSuspendClassObjects [OLE32.@]
3110 * Suspends all registered class objects to prevent further requests coming in
3111 * for those objects.
3115 * Failure: HRESULT code.
3117 HRESULT WINAPI
CoSuspendClassObjects(void)
3123 /***********************************************************************
3124 * CoAddRefServerProcess [OLE32.@]
3126 * Helper function for incrementing the reference count of a local-server
3130 * New reference count.
3133 * CoReleaseServerProcess().
3135 ULONG WINAPI
CoAddRefServerProcess(void)
3141 EnterCriticalSection(&csRegisteredClassList
);
3142 refs
= ++s_COMServerProcessReferences
;
3143 LeaveCriticalSection(&csRegisteredClassList
);
3145 TRACE("refs before: %d\n", refs
- 1);
3150 /***********************************************************************
3151 * CoReleaseServerProcess [OLE32.@]
3153 * Helper function for decrementing the reference count of a local-server
3157 * New reference count.
3160 * When reference count reaches 0, this function suspends all registered
3161 * classes so no new connections are accepted.
3164 * CoAddRefServerProcess(), CoSuspendClassObjects().
3166 ULONG WINAPI
CoReleaseServerProcess(void)
3172 EnterCriticalSection(&csRegisteredClassList
);
3174 refs
= --s_COMServerProcessReferences
;
3175 /* FIXME: if (!refs) COM_SuspendClassObjects(); */
3177 LeaveCriticalSection(&csRegisteredClassList
);
3179 TRACE("refs after: %d\n", refs
);
3184 /***********************************************************************
3185 * CoIsHandlerConnected [OLE32.@]
3187 * Determines whether a proxy is connected to a remote stub.
3190 * pUnk [I] Pointer to object that may or may not be connected.
3193 * TRUE if pUnk is not a proxy or if pUnk is connected to a remote stub, or
3196 BOOL WINAPI
CoIsHandlerConnected(IUnknown
*pUnk
)
3198 FIXME("%p\n", pUnk
);
3203 /***********************************************************************
3204 * CoAllowSetForegroundWindow [OLE32.@]
3207 HRESULT WINAPI
CoAllowSetForegroundWindow(IUnknown
*pUnk
, void *pvReserved
)
3209 FIXME("(%p, %p): stub\n", pUnk
, pvReserved
);
3213 /***********************************************************************
3214 * CoQueryProxyBlanket [OLE32.@]
3216 * Retrieves the security settings being used by a proxy.
3219 * pProxy [I] Pointer to the proxy object.
3220 * pAuthnSvc [O] The type of authentication service.
3221 * pAuthzSvc [O] The type of authorization service.
3222 * ppServerPrincName [O] Optional. The server prinicple name.
3223 * pAuthnLevel [O] The authentication level.
3224 * pImpLevel [O] The impersonation level.
3225 * ppAuthInfo [O] Information specific to the authorization/authentication service.
3226 * pCapabilities [O] Flags affecting the security behaviour.
3230 * Failure: HRESULT code.
3233 * CoCopyProxy, CoSetProxyBlanket.
3235 HRESULT WINAPI
CoQueryProxyBlanket(IUnknown
*pProxy
, DWORD
*pAuthnSvc
,
3236 DWORD
*pAuthzSvc
, OLECHAR
**ppServerPrincName
, DWORD
*pAuthnLevel
,
3237 DWORD
*pImpLevel
, void **ppAuthInfo
, DWORD
*pCapabilities
)
3239 IClientSecurity
*pCliSec
;
3242 TRACE("%p\n", pProxy
);
3244 hr
= IUnknown_QueryInterface(pProxy
, &IID_IClientSecurity
, (void **)&pCliSec
);
3247 hr
= IClientSecurity_QueryBlanket(pCliSec
, pProxy
, pAuthnSvc
,
3248 pAuthzSvc
, ppServerPrincName
,
3249 pAuthnLevel
, pImpLevel
, ppAuthInfo
,
3251 IClientSecurity_Release(pCliSec
);
3254 if (FAILED(hr
)) ERR("-- failed with 0x%08x\n", hr
);
3258 /***********************************************************************
3259 * CoSetProxyBlanket [OLE32.@]
3261 * Sets the security settings for a proxy.
3264 * pProxy [I] Pointer to the proxy object.
3265 * AuthnSvc [I] The type of authentication service.
3266 * AuthzSvc [I] The type of authorization service.
3267 * pServerPrincName [I] The server prinicple name.
3268 * AuthnLevel [I] The authentication level.
3269 * ImpLevel [I] The impersonation level.
3270 * pAuthInfo [I] Information specific to the authorization/authentication service.
3271 * Capabilities [I] Flags affecting the security behaviour.
3275 * Failure: HRESULT code.
3278 * CoQueryProxyBlanket, CoCopyProxy.
3280 HRESULT WINAPI
CoSetProxyBlanket(IUnknown
*pProxy
, DWORD AuthnSvc
,
3281 DWORD AuthzSvc
, OLECHAR
*pServerPrincName
, DWORD AuthnLevel
,
3282 DWORD ImpLevel
, void *pAuthInfo
, DWORD Capabilities
)
3284 IClientSecurity
*pCliSec
;
3287 TRACE("%p\n", pProxy
);
3289 hr
= IUnknown_QueryInterface(pProxy
, &IID_IClientSecurity
, (void **)&pCliSec
);
3292 hr
= IClientSecurity_SetBlanket(pCliSec
, pProxy
, AuthnSvc
,
3293 AuthzSvc
, pServerPrincName
,
3294 AuthnLevel
, ImpLevel
, pAuthInfo
,
3296 IClientSecurity_Release(pCliSec
);
3299 if (FAILED(hr
)) ERR("-- failed with 0x%08x\n", hr
);
3303 /***********************************************************************
3304 * CoCopyProxy [OLE32.@]
3309 * pProxy [I] Pointer to the proxy object.
3310 * ppCopy [O] Copy of the proxy.
3314 * Failure: HRESULT code.
3317 * CoQueryProxyBlanket, CoSetProxyBlanket.
3319 HRESULT WINAPI
CoCopyProxy(IUnknown
*pProxy
, IUnknown
**ppCopy
)
3321 IClientSecurity
*pCliSec
;
3324 TRACE("%p\n", pProxy
);
3326 hr
= IUnknown_QueryInterface(pProxy
, &IID_IClientSecurity
, (void **)&pCliSec
);
3329 hr
= IClientSecurity_CopyProxy(pCliSec
, pProxy
, ppCopy
);
3330 IClientSecurity_Release(pCliSec
);
3333 if (FAILED(hr
)) ERR("-- failed with 0x%08x\n", hr
);
3338 /***********************************************************************
3339 * CoGetCallContext [OLE32.@]
3341 * Gets the context of the currently executing server call in the current
3345 * riid [I] Context interface to return.
3346 * ppv [O] Pointer to memory that will receive the context on return.
3350 * Failure: HRESULT code.
3352 HRESULT WINAPI
CoGetCallContext(REFIID riid
, void **ppv
)
3354 FIXME("(%s, %p): stub\n", debugstr_guid(riid
), ppv
);
3357 return E_NOINTERFACE
;
3360 /***********************************************************************
3361 * CoQueryClientBlanket [OLE32.@]
3363 * Retrieves the authentication information about the client of the currently
3364 * executing server call in the current thread.
3367 * pAuthnSvc [O] Optional. The type of authentication service.
3368 * pAuthzSvc [O] Optional. The type of authorization service.
3369 * pServerPrincName [O] Optional. The server prinicple name.
3370 * pAuthnLevel [O] Optional. The authentication level.
3371 * pImpLevel [O] Optional. The impersonation level.
3372 * pPrivs [O] Optional. Information about the privileges of the client.
3373 * pCapabilities [IO] Optional. Flags affecting the security behaviour.
3377 * Failure: HRESULT code.
3380 * CoImpersonateClient, CoRevertToSelf, CoGetCallContext.
3382 HRESULT WINAPI
CoQueryClientBlanket(
3385 OLECHAR
**pServerPrincName
,
3388 RPC_AUTHZ_HANDLE
*pPrivs
,
3389 DWORD
*pCapabilities
)
3391 IServerSecurity
*pSrvSec
;
3394 TRACE("(%p, %p, %p, %p, %p, %p, %p)\n",
3395 pAuthnSvc
, pAuthzSvc
, pServerPrincName
, pAuthnLevel
, pImpLevel
,
3396 pPrivs
, pCapabilities
);
3398 hr
= CoGetCallContext(&IID_IServerSecurity
, (void **)&pSrvSec
);
3401 hr
= IServerSecurity_QueryBlanket(
3402 pSrvSec
, pAuthnSvc
, pAuthzSvc
, pServerPrincName
, pAuthnLevel
,
3403 pImpLevel
, pPrivs
, pCapabilities
);
3404 IServerSecurity_Release(pSrvSec
);
3410 /***********************************************************************
3411 * CoImpersonateClient [OLE32.@]
3413 * Impersonates the client of the currently executing server call in the
3421 * Failure: HRESULT code.
3424 * If this function fails then the current thread will not be impersonating
3425 * the client and all actions will take place on behalf of the server.
3426 * Therefore, it is important to check the return value from this function.
3429 * CoRevertToSelf, CoQueryClientBlanket, CoGetCallContext.
3431 HRESULT WINAPI
CoImpersonateClient(void)
3433 IServerSecurity
*pSrvSec
;
3438 hr
= CoGetCallContext(&IID_IServerSecurity
, (void **)&pSrvSec
);
3441 hr
= IServerSecurity_ImpersonateClient(pSrvSec
);
3442 IServerSecurity_Release(pSrvSec
);
3448 /***********************************************************************
3449 * CoRevertToSelf [OLE32.@]
3451 * Ends the impersonation of the client of the currently executing server
3452 * call in the current thread.
3459 * Failure: HRESULT code.
3462 * CoImpersonateClient, CoQueryClientBlanket, CoGetCallContext.
3464 HRESULT WINAPI
CoRevertToSelf(void)
3466 IServerSecurity
*pSrvSec
;
3471 hr
= CoGetCallContext(&IID_IServerSecurity
, (void **)&pSrvSec
);
3474 hr
= IServerSecurity_RevertToSelf(pSrvSec
);
3475 IServerSecurity_Release(pSrvSec
);
3481 static BOOL
COM_PeekMessage(struct apartment
*apt
, MSG
*msg
)
3483 /* first try to retrieve messages for incoming COM calls to the apartment window */
3484 return PeekMessageW(msg
, apt
->win
, WM_USER
, WM_APP
- 1, PM_REMOVE
|PM_NOYIELD
) ||
3485 /* next retrieve other messages necessary for the app to remain responsive */
3486 PeekMessageW(msg
, NULL
, 0, 0, PM_QS_PAINT
|PM_QS_POSTMESSAGE
|PM_REMOVE
|PM_NOYIELD
);
3489 /***********************************************************************
3490 * CoWaitForMultipleHandles [OLE32.@]
3492 * Waits for one or more handles to become signaled.
3495 * dwFlags [I] Flags. See notes.
3496 * dwTimeout [I] Timeout in milliseconds.
3497 * cHandles [I] Number of handles pointed to by pHandles.
3498 * pHandles [I] Handles to wait for.
3499 * lpdwindex [O] Index of handle that was signaled.
3503 * Failure: RPC_S_CALLPENDING on timeout.
3507 * The dwFlags parameter can be zero or more of the following:
3508 *| COWAIT_WAITALL - Wait for all of the handles to become signaled.
3509 *| COWAIT_ALERTABLE - Allows a queued APC to run during the wait.
3512 * MsgWaitForMultipleObjects, WaitForMultipleObjects.
3514 HRESULT WINAPI
CoWaitForMultipleHandles(DWORD dwFlags
, DWORD dwTimeout
,
3515 ULONG cHandles
, LPHANDLE pHandles
, LPDWORD lpdwindex
)
3518 DWORD start_time
= GetTickCount();
3519 APARTMENT
*apt
= COM_CurrentApt();
3520 BOOL message_loop
= apt
&& !apt
->multi_threaded
;
3522 TRACE("(0x%08x, 0x%08x, %d, %p, %p)\n", dwFlags
, dwTimeout
, cHandles
,
3523 pHandles
, lpdwindex
);
3527 DWORD now
= GetTickCount();
3530 if (now
- start_time
> dwTimeout
)
3532 hr
= RPC_S_CALLPENDING
;
3538 DWORD wait_flags
= ((dwFlags
& COWAIT_WAITALL
) ? MWMO_WAITALL
: 0) |
3539 ((dwFlags
& COWAIT_ALERTABLE
) ? MWMO_ALERTABLE
: 0);
3541 TRACE("waiting for rpc completion or window message\n");
3543 res
= MsgWaitForMultipleObjectsEx(cHandles
, pHandles
,
3544 (dwTimeout
== INFINITE
) ? INFINITE
: start_time
+ dwTimeout
- now
,
3545 QS_ALLINPUT
, wait_flags
);
3547 if (res
== WAIT_OBJECT_0
+ cHandles
) /* messages available */
3551 /* call message filter */
3553 if (COM_CurrentApt()->filter
)
3555 PENDINGTYPE pendingtype
=
3556 COM_CurrentInfo()->pending_call_count_server
?
3557 PENDINGTYPE_NESTED
: PENDINGTYPE_TOPLEVEL
;
3558 DWORD be_handled
= IMessageFilter_MessagePending(
3559 COM_CurrentApt()->filter
, 0 /* FIXME */,
3560 now
- start_time
, pendingtype
);
3561 TRACE("IMessageFilter_MessagePending returned %d\n", be_handled
);
3564 case PENDINGMSG_CANCELCALL
:
3565 WARN("call canceled\n");
3566 hr
= RPC_E_CALL_CANCELED
;
3568 case PENDINGMSG_WAITNOPROCESS
:
3569 case PENDINGMSG_WAITDEFPROCESS
:
3571 /* FIXME: MSDN is very vague about the difference
3572 * between WAITNOPROCESS and WAITDEFPROCESS - there
3573 * appears to be none, so it is possibly a left-over
3574 * from the 16-bit world. */
3579 /* note: using "if" here instead of "while" might seem less
3580 * efficient, but only if we are optimising for quick delivery
3581 * of pending messages, rather than quick completion of the
3583 if (COM_PeekMessage(apt
, &msg
))
3585 TRACE("received message whilst waiting for RPC: 0x%04x\n", msg
.message
);
3586 TranslateMessage(&msg
);
3587 DispatchMessageW(&msg
);
3588 if (msg
.message
== WM_QUIT
)
3590 TRACE("resending WM_QUIT to outer message loop\n");
3591 PostQuitMessage(msg
.wParam
);
3592 /* no longer need to process messages */
3593 message_loop
= FALSE
;
3601 TRACE("waiting for rpc completion\n");
3603 res
= WaitForMultipleObjectsEx(cHandles
, pHandles
,
3604 (dwFlags
& COWAIT_WAITALL
) ? TRUE
: FALSE
,
3605 (dwTimeout
== INFINITE
) ? INFINITE
: start_time
+ dwTimeout
- now
,
3606 (dwFlags
& COWAIT_ALERTABLE
) ? TRUE
: FALSE
);
3609 if (res
< WAIT_OBJECT_0
+ cHandles
)
3611 /* handle signaled, store index */
3612 *lpdwindex
= (res
- WAIT_OBJECT_0
);
3615 else if (res
== WAIT_TIMEOUT
)
3617 hr
= RPC_S_CALLPENDING
;
3622 ERR("Unexpected wait termination: %d, %d\n", res
, GetLastError());
3627 TRACE("-- 0x%08x\n", hr
);
3632 /***********************************************************************
3633 * CoGetObject [OLE32.@]
3635 * Gets the object named by converting the name to a moniker and binding to it.
3638 * pszName [I] String representing the object.
3639 * pBindOptions [I] Parameters affecting the binding to the named object.
3640 * riid [I] Interface to bind to on the objecct.
3641 * ppv [O] On output, the interface riid of the object represented
3646 * Failure: HRESULT code.
3649 * MkParseDisplayName.
3651 HRESULT WINAPI
CoGetObject(LPCWSTR pszName
, BIND_OPTS
*pBindOptions
,
3652 REFIID riid
, void **ppv
)
3659 hr
= CreateBindCtx(0, &pbc
);
3663 hr
= IBindCtx_SetBindOptions(pbc
, pBindOptions
);
3670 hr
= MkParseDisplayName(pbc
, pszName
, &chEaten
, &pmk
);
3673 hr
= IMoniker_BindToObject(pmk
, pbc
, NULL
, riid
, ppv
);
3674 IMoniker_Release(pmk
);
3678 IBindCtx_Release(pbc
);
3683 /***********************************************************************
3684 * CoRegisterChannelHook [OLE32.@]
3686 * Registers a process-wide hook that is called during ORPC calls.
3689 * guidExtension [I] GUID of the channel hook to register.
3690 * pChannelHook [I] Channel hook object to register.
3694 * Failure: HRESULT code.
3696 HRESULT WINAPI
CoRegisterChannelHook(REFGUID guidExtension
, IChannelHook
*pChannelHook
)
3698 TRACE("(%s, %p)\n", debugstr_guid(guidExtension
), pChannelHook
);
3700 return RPC_RegisterChannelHook(guidExtension
, pChannelHook
);
3703 typedef struct Context
3705 const IComThreadingInfoVtbl
*lpVtbl
;
3710 static HRESULT WINAPI
Context_QueryInterface(IComThreadingInfo
*iface
, REFIID riid
, LPVOID
*ppv
)
3714 if (IsEqualIID(riid
, &IID_IComThreadingInfo
) ||
3715 IsEqualIID(riid
, &IID_IUnknown
))
3718 IUnknown_AddRef(iface
);
3722 FIXME("interface not implemented %s\n", debugstr_guid(riid
));
3723 return E_NOINTERFACE
;
3726 static ULONG WINAPI
Context_AddRef(IComThreadingInfo
*iface
)
3728 Context
*This
= (Context
*)iface
;
3729 return InterlockedIncrement(&This
->refs
);
3732 static ULONG WINAPI
Context_Release(IComThreadingInfo
*iface
)
3734 Context
*This
= (Context
*)iface
;
3735 ULONG refs
= InterlockedDecrement(&This
->refs
);
3737 HeapFree(GetProcessHeap(), 0, This
);
3741 static HRESULT WINAPI
Context_GetCurrentApartmentType(IComThreadingInfo
*iface
, APTTYPE
*apttype
)
3743 Context
*This
= (Context
*)iface
;
3745 TRACE("(%p)\n", apttype
);
3747 *apttype
= This
->apttype
;
3751 static HRESULT WINAPI
Context_GetCurrentThreadType(IComThreadingInfo
*iface
, THDTYPE
*thdtype
)
3753 Context
*This
= (Context
*)iface
;
3755 TRACE("(%p)\n", thdtype
);
3757 switch (This
->apttype
)
3760 case APTTYPE_MAINSTA
:
3761 *thdtype
= THDTYPE_PROCESSMESSAGES
;
3764 *thdtype
= THDTYPE_BLOCKMESSAGES
;
3770 static HRESULT WINAPI
Context_GetCurrentLogicalThreadId(IComThreadingInfo
*iface
, GUID
*logical_thread_id
)
3772 FIXME("(%p): stub\n", logical_thread_id
);
3776 static HRESULT WINAPI
Context_SetCurrentLogicalThreadId(IComThreadingInfo
*iface
, REFGUID logical_thread_id
)
3778 FIXME("(%s): stub\n", debugstr_guid(logical_thread_id
));
3782 static const IComThreadingInfoVtbl Context_Threading_Vtbl
=
3784 Context_QueryInterface
,
3787 Context_GetCurrentApartmentType
,
3788 Context_GetCurrentThreadType
,
3789 Context_GetCurrentLogicalThreadId
,
3790 Context_SetCurrentLogicalThreadId
3793 /***********************************************************************
3794 * CoGetObjectContext [OLE32.@]
3796 * Retrieves an object associated with the current context (i.e. apartment).
3799 * riid [I] ID of the interface of the object to retrieve.
3800 * ppv [O] Address where object will be stored on return.
3804 * Failure: HRESULT code.
3806 HRESULT WINAPI
CoGetObjectContext(REFIID riid
, void **ppv
)
3808 APARTMENT
*apt
= COM_CurrentApt();
3812 TRACE("(%s, %p)\n", debugstr_guid(riid
), ppv
);
3817 ERR("apartment not initialised\n");
3818 return CO_E_NOTINITIALIZED
;
3821 context
= HeapAlloc(GetProcessHeap(), 0, sizeof(*context
));
3823 return E_OUTOFMEMORY
;
3825 context
->lpVtbl
= &Context_Threading_Vtbl
;
3827 if (apt
->multi_threaded
)
3828 context
->apttype
= APTTYPE_MTA
;
3830 context
->apttype
= APTTYPE_MAINSTA
;
3832 context
->apttype
= APTTYPE_STA
;
3834 hr
= IUnknown_QueryInterface((IUnknown
*)&context
->lpVtbl
, riid
, ppv
);
3835 IUnknown_Release((IUnknown
*)&context
->lpVtbl
);
3841 /***********************************************************************
3842 * CoGetContextToken [OLE32.@]
3844 HRESULT WINAPI
CoGetContextToken( ULONG_PTR
*token
)
3847 if(!(calls
++)) FIXME( "stub\n" );
3848 if (token
) *token
= 0;
3853 /***********************************************************************
3856 BOOL WINAPI
DllMain(HINSTANCE hinstDLL
, DWORD fdwReason
, LPVOID fImpLoad
)
3858 TRACE("%p 0x%x %p\n", hinstDLL
, fdwReason
, fImpLoad
);
3861 case DLL_PROCESS_ATTACH
:
3862 hProxyDll
= hinstDLL
;
3863 COMPOBJ_InitProcess();
3864 if (TRACE_ON(ole
)) CoRegisterMallocSpy((LPVOID
)-1);
3867 case DLL_PROCESS_DETACH
:
3868 if (TRACE_ON(ole
)) CoRevokeMallocSpy();
3869 OLEDD_UnInitialize();
3870 COMPOBJ_UninitProcess();
3871 RPC_UnregisterAllChannelHooks();
3872 COMPOBJ_DllList_Free();
3875 case DLL_THREAD_DETACH
:
3882 /* NOTE: DllRegisterServer and DllUnregisterServer are in regsvr.c */