4 * Copyright 1995 Martin von Loewis
5 * Copyright 1998 Justin Bradford
6 * Copyright 1999 Francis Beaudet
7 * Copyright 1999 Sylvain St-Germain
8 * Copyright 2002 Marcus Meissner
9 * Copyright 2004 Mike Hearn
10 * Copyright 2005-2006 Robert Shearman (for CodeWeavers)
12 * This library is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Lesser General Public
14 * License as published by the Free Software Foundation; either
15 * version 2.1 of the License, or (at your option) any later version.
17 * This library is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * Lesser General Public License for more details.
22 * You should have received a copy of the GNU Lesser General Public
23 * License along with this library; if not, write to the Free Software
24 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
27 * 1. COINIT_MULTITHREADED is 0; it is the lack of COINIT_APARTMENTTHREADED
28 * Therefore do not test against COINIT_MULTITHREADED
30 * TODO list: (items bunched together depend on each other)
32 * - Implement the service control manager (in rpcss) to keep track
33 * of registered class objects: ISCM::ServerRegisterClsid et al
34 * - Implement the OXID resolver so we don't need magic endpoint names for
35 * clients and servers to meet up
37 * - Make all ole interface marshaling use NDR to be wire compatible with
50 #define NONAMELESSUNION
51 #define NONAMELESSSTRUCT
62 #include "compobj_private.h"
64 #include "wine/unicode.h"
65 #include "wine/debug.h"
67 WINE_DEFAULT_DEBUG_CHANNEL(ole
);
69 HINSTANCE OLE32_hInstance
= 0; /* FIXME: make static ... */
71 #define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))
73 /****************************************************************************
74 * This section defines variables internal to the COM module.
76 * TODO: Most of these things will have to be made thread-safe.
79 static HRESULT
COM_GetRegisteredClassObject(const struct apartment
*apt
, REFCLSID rclsid
,
80 DWORD dwClsContext
, LPUNKNOWN
* ppUnk
);
81 static void COM_RevokeAllClasses(const struct apartment
*apt
);
82 static HRESULT
get_inproc_class_object(APARTMENT
*apt
, HKEY hkeydll
, REFCLSID rclsid
, REFIID riid
, BOOL hostifnecessary
, void **ppv
);
84 static APARTMENT
*MTA
; /* protected by csApartment */
85 static APARTMENT
*MainApartment
; /* the first STA apartment */
86 static struct list apts
= LIST_INIT( apts
); /* protected by csApartment */
88 static CRITICAL_SECTION csApartment
;
89 static CRITICAL_SECTION_DEBUG critsect_debug
=
92 { &critsect_debug
.ProcessLocksList
, &critsect_debug
.ProcessLocksList
},
93 0, 0, { (DWORD_PTR
)(__FILE__
": csApartment") }
95 static CRITICAL_SECTION csApartment
= { &critsect_debug
, -1, 0, 0, 0, 0 };
97 struct registered_psclsid
105 * This lock count counts the number of times CoInitialize is called. It is
106 * decreased every time CoUninitialize is called. When it hits 0, the COM
107 * libraries are freed
109 static LONG s_COMLockCount
= 0;
110 /* Reference count used by CoAddRefServerProcess/CoReleaseServerProcess */
111 static LONG s_COMServerProcessReferences
= 0;
114 * This linked list contains the list of registered class objects. These
115 * are mostly used to register the factories for out-of-proc servers of OLE
118 * TODO: Make this data structure aware of inter-process communication. This
119 * means that parts of this will be exported to the Wine Server.
121 typedef struct tagRegisteredClass
124 CLSID classIdentifier
;
126 LPUNKNOWN classObject
;
130 LPSTREAM pMarshaledData
; /* FIXME: only really need to store OXID and IPID */
131 void *RpcRegistration
;
134 static struct list RegisteredClassList
= LIST_INIT(RegisteredClassList
);
136 static CRITICAL_SECTION csRegisteredClassList
;
137 static CRITICAL_SECTION_DEBUG class_cs_debug
=
139 0, 0, &csRegisteredClassList
,
140 { &class_cs_debug
.ProcessLocksList
, &class_cs_debug
.ProcessLocksList
},
141 0, 0, { (DWORD_PTR
)(__FILE__
": csRegisteredClassList") }
143 static CRITICAL_SECTION csRegisteredClassList
= { &class_cs_debug
, -1, 0, 0, 0, 0 };
145 /*****************************************************************************
146 * This section contains OpenDllList definitions
148 * The OpenDllList contains only handles of dll loaded by CoGetClassObject or
149 * other functions that do LoadLibrary _without_ giving back a HMODULE.
150 * Without this list these handles would never be freed.
152 * FIXME: a DLL that says OK when asked for unloading is unloaded in the
153 * next unload-call but not before 600 sec.
156 typedef HRESULT (CALLBACK
*DllGetClassObjectFunc
)(REFCLSID clsid
, REFIID iid
, LPVOID
*ppv
);
157 typedef HRESULT (WINAPI
*DllCanUnloadNowFunc
)(void);
159 typedef struct tagOpenDll
164 DllGetClassObjectFunc DllGetClassObject
;
165 DllCanUnloadNowFunc DllCanUnloadNow
;
169 static struct list openDllList
= LIST_INIT(openDllList
);
171 static CRITICAL_SECTION csOpenDllList
;
172 static CRITICAL_SECTION_DEBUG dll_cs_debug
=
174 0, 0, &csOpenDllList
,
175 { &dll_cs_debug
.ProcessLocksList
, &dll_cs_debug
.ProcessLocksList
},
176 0, 0, { (DWORD_PTR
)(__FILE__
": csOpenDllList") }
178 static CRITICAL_SECTION csOpenDllList
= { &dll_cs_debug
, -1, 0, 0, 0, 0 };
180 struct apartment_loaded_dll
188 static const WCHAR wszAptWinClass
[] = {'O','l','e','M','a','i','n','T','h','r','e','a','d','W','n','d','C','l','a','s','s',' ',
189 '0','x','#','#','#','#','#','#','#','#',' ',0};
190 static LRESULT CALLBACK
apartment_wndproc(HWND hWnd
, UINT msg
, WPARAM wParam
, LPARAM lParam
);
191 static HRESULT
apartment_getclassobject(struct apartment
*apt
, LPCWSTR dllpath
,
192 BOOL apartment_threaded
,
193 REFCLSID rclsid
, REFIID riid
, void **ppv
);
194 static void apartment_freeunusedlibraries(struct apartment
*apt
, DWORD delay
);
196 static HRESULT
COMPOBJ_DllList_Add(LPCWSTR library_name
, OpenDll
**ret
);
197 static OpenDll
*COMPOBJ_DllList_Get(LPCWSTR library_name
);
198 static void COMPOBJ_DllList_ReleaseRef(OpenDll
*entry
, BOOL free_entry
);
200 static DWORD
COM_RegReadPath(HKEY hkeyroot
, const WCHAR
*keyname
, const WCHAR
*valuename
, WCHAR
* dst
, DWORD dstlen
);
202 static void COMPOBJ_InitProcess( void )
206 /* Dispatching to the correct thread in an apartment is done through
207 * window messages rather than RPC transports. When an interface is
208 * marshalled into another apartment in the same process, a window of the
209 * following class is created. The *caller* of CoMarshalInterface (i.e., the
210 * application) is responsible for pumping the message loop in that thread.
211 * The WM_USER messages which point to the RPCs are then dispatched to
212 * COM_AptWndProc by the user's code from the apartment in which the interface
215 memset(&wclass
, 0, sizeof(wclass
));
216 wclass
.lpfnWndProc
= apartment_wndproc
;
217 wclass
.hInstance
= OLE32_hInstance
;
218 wclass
.lpszClassName
= wszAptWinClass
;
219 RegisterClassW(&wclass
);
222 static void COMPOBJ_UninitProcess( void )
224 UnregisterClassW(wszAptWinClass
, OLE32_hInstance
);
227 static void COM_TlsDestroy(void)
229 struct oletls
*info
= NtCurrentTeb()->ReservedForOle
;
232 if (info
->apt
) apartment_release(info
->apt
);
233 if (info
->errorinfo
) IErrorInfo_Release(info
->errorinfo
);
234 if (info
->state
) IUnknown_Release(info
->state
);
235 HeapFree(GetProcessHeap(), 0, info
);
236 NtCurrentTeb()->ReservedForOle
= NULL
;
240 /******************************************************************************
244 /* allocates memory and fills in the necessary fields for a new apartment
245 * object. must be called inside apartment cs */
246 static APARTMENT
*apartment_construct(DWORD model
)
250 TRACE("creating new apartment, model=%d\n", model
);
252 apt
= HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY
, sizeof(*apt
));
253 apt
->tid
= GetCurrentThreadId();
255 list_init(&apt
->proxies
);
256 list_init(&apt
->stubmgrs
);
257 list_init(&apt
->psclsids
);
258 list_init(&apt
->loaded_dlls
);
261 apt
->remunk_exported
= FALSE
;
263 InitializeCriticalSection(&apt
->cs
);
264 DEBUG_SET_CRITSEC_NAME(&apt
->cs
, "apartment");
266 apt
->multi_threaded
= !(model
& COINIT_APARTMENTTHREADED
);
268 if (apt
->multi_threaded
)
270 /* FIXME: should be randomly generated by in an RPC call to rpcss */
271 apt
->oxid
= ((OXID
)GetCurrentProcessId() << 32) | 0xcafe;
275 /* FIXME: should be randomly generated by in an RPC call to rpcss */
276 apt
->oxid
= ((OXID
)GetCurrentProcessId() << 32) | GetCurrentThreadId();
279 TRACE("Created apartment on OXID %s\n", wine_dbgstr_longlong(apt
->oxid
));
281 list_add_head(&apts
, &apt
->entry
);
286 /* gets and existing apartment if one exists or otherwise creates an apartment
287 * structure which stores OLE apartment-local information and stores a pointer
288 * to it in the thread-local storage */
289 static APARTMENT
*apartment_get_or_create(DWORD model
)
291 APARTMENT
*apt
= COM_CurrentApt();
295 if (model
& COINIT_APARTMENTTHREADED
)
297 EnterCriticalSection(&csApartment
);
299 apt
= apartment_construct(model
);
304 TRACE("Created main-threaded apartment with OXID %s\n", wine_dbgstr_longlong(apt
->oxid
));
307 LeaveCriticalSection(&csApartment
);
310 apartment_createwindowifneeded(apt
);
314 EnterCriticalSection(&csApartment
);
316 /* The multi-threaded apartment (MTA) contains zero or more threads interacting
317 * with free threaded (ie thread safe) COM objects. There is only ever one MTA
321 TRACE("entering the multithreaded apartment %s\n", wine_dbgstr_longlong(MTA
->oxid
));
322 apartment_addref(MTA
);
325 MTA
= apartment_construct(model
);
329 LeaveCriticalSection(&csApartment
);
331 COM_CurrentInfo()->apt
= apt
;
337 static inline BOOL
apartment_is_model(const APARTMENT
*apt
, DWORD model
)
339 return (apt
->multi_threaded
== !(model
& COINIT_APARTMENTTHREADED
));
342 DWORD
apartment_addref(struct apartment
*apt
)
344 DWORD refs
= InterlockedIncrement(&apt
->refs
);
345 TRACE("%s: before = %d\n", wine_dbgstr_longlong(apt
->oxid
), refs
- 1);
349 DWORD
apartment_release(struct apartment
*apt
)
353 EnterCriticalSection(&csApartment
);
355 ret
= InterlockedDecrement(&apt
->refs
);
356 TRACE("%s: after = %d\n", wine_dbgstr_longlong(apt
->oxid
), ret
);
357 /* destruction stuff that needs to happen under csApartment CS */
360 if (apt
== MTA
) MTA
= NULL
;
361 else if (apt
== MainApartment
) MainApartment
= NULL
;
362 list_remove(&apt
->entry
);
365 LeaveCriticalSection(&csApartment
);
369 struct list
*cursor
, *cursor2
;
371 TRACE("destroying apartment %p, oxid %s\n", apt
, wine_dbgstr_longlong(apt
->oxid
));
373 /* Release the references to the registered class objects */
374 COM_RevokeAllClasses(apt
);
376 /* no locking is needed for this apartment, because no other thread
377 * can access it at this point */
379 apartment_disconnectproxies(apt
);
381 if (apt
->win
) DestroyWindow(apt
->win
);
382 if (apt
->host_apt_tid
) PostThreadMessageW(apt
->host_apt_tid
, WM_QUIT
, 0, 0);
384 LIST_FOR_EACH_SAFE(cursor
, cursor2
, &apt
->stubmgrs
)
386 struct stub_manager
*stubmgr
= LIST_ENTRY(cursor
, struct stub_manager
, entry
);
387 /* release the implicit reference given by the fact that the
388 * stub has external references (it must do since it is in the
389 * stub manager list in the apartment and all non-apartment users
390 * must have a ref on the apartment and so it cannot be destroyed).
392 stub_manager_int_release(stubmgr
);
395 LIST_FOR_EACH_SAFE(cursor
, cursor2
, &apt
->psclsids
)
397 struct registered_psclsid
*registered_psclsid
=
398 LIST_ENTRY(cursor
, struct registered_psclsid
, entry
);
400 list_remove(®istered_psclsid
->entry
);
401 HeapFree(GetProcessHeap(), 0, registered_psclsid
);
404 /* if this assert fires, then another thread took a reference to a
405 * stub manager without taking a reference to the containing
406 * apartment, which it must do. */
407 assert(list_empty(&apt
->stubmgrs
));
409 if (apt
->filter
) IUnknown_Release(apt
->filter
);
411 /* free as many unused libraries as possible... */
412 apartment_freeunusedlibraries(apt
, 0);
414 /* ... and free the memory for the apartment loaded dll entry and
415 * release the dll list reference without freeing the library for the
417 while ((cursor
= list_head(&apt
->loaded_dlls
)))
419 struct apartment_loaded_dll
*apartment_loaded_dll
= LIST_ENTRY(cursor
, struct apartment_loaded_dll
, entry
);
420 COMPOBJ_DllList_ReleaseRef(apartment_loaded_dll
->dll
, FALSE
);
422 HeapFree(GetProcessHeap(), 0, apartment_loaded_dll
);
425 DEBUG_CLEAR_CRITSEC_NAME(&apt
->cs
);
426 DeleteCriticalSection(&apt
->cs
);
428 HeapFree(GetProcessHeap(), 0, apt
);
434 /* The given OXID must be local to this process:
436 * The ref parameter is here mostly to ensure people remember that
437 * they get one, you should normally take a ref for thread safety.
439 APARTMENT
*apartment_findfromoxid(OXID oxid
, BOOL ref
)
441 APARTMENT
*result
= NULL
;
444 EnterCriticalSection(&csApartment
);
445 LIST_FOR_EACH( cursor
, &apts
)
447 struct apartment
*apt
= LIST_ENTRY( cursor
, struct apartment
, entry
);
448 if (apt
->oxid
== oxid
)
451 if (ref
) apartment_addref(result
);
455 LeaveCriticalSection(&csApartment
);
460 /* gets the apartment which has a given creator thread ID. The caller must
461 * release the reference from the apartment as soon as the apartment pointer
462 * is no longer required. */
463 APARTMENT
*apartment_findfromtid(DWORD tid
)
465 APARTMENT
*result
= NULL
;
468 EnterCriticalSection(&csApartment
);
469 LIST_FOR_EACH( cursor
, &apts
)
471 struct apartment
*apt
= LIST_ENTRY( cursor
, struct apartment
, entry
);
475 apartment_addref(result
);
479 LeaveCriticalSection(&csApartment
);
484 /* gets the main apartment if it exists. The caller must
485 * release the reference from the apartment as soon as the apartment pointer
486 * is no longer required. */
487 static APARTMENT
*apartment_findmain(void)
491 EnterCriticalSection(&csApartment
);
493 result
= MainApartment
;
494 if (result
) apartment_addref(result
);
496 LeaveCriticalSection(&csApartment
);
501 struct host_object_params
504 CLSID clsid
; /* clsid of object to marshal */
505 IID iid
; /* interface to marshal */
506 HANDLE event
; /* event signalling when ready for multi-threaded case */
507 HRESULT hr
; /* result for multi-threaded case */
508 IStream
*stream
; /* stream that the object will be marshaled into */
509 BOOL apartment_threaded
; /* is the component purely apartment-threaded? */
512 static HRESULT
apartment_hostobject(struct apartment
*apt
,
513 const struct host_object_params
*params
)
517 static const LARGE_INTEGER llZero
;
518 WCHAR dllpath
[MAX_PATH
+1];
520 TRACE("clsid %s, iid %s\n", debugstr_guid(¶ms
->clsid
), debugstr_guid(¶ms
->iid
));
522 if (COM_RegReadPath(params
->hkeydll
, NULL
, NULL
, dllpath
, ARRAYSIZE(dllpath
)) != ERROR_SUCCESS
)
524 /* failure: CLSID is not found in registry */
525 WARN("class %s not registered inproc\n", debugstr_guid(¶ms
->clsid
));
526 return REGDB_E_CLASSNOTREG
;
529 hr
= apartment_getclassobject(apt
, dllpath
, params
->apartment_threaded
,
530 ¶ms
->clsid
, ¶ms
->iid
, (void **)&object
);
534 hr
= CoMarshalInterface(params
->stream
, ¶ms
->iid
, object
, MSHCTX_INPROC
, NULL
, MSHLFLAGS_NORMAL
);
536 IUnknown_Release(object
);
537 IStream_Seek(params
->stream
, llZero
, STREAM_SEEK_SET
, NULL
);
542 static LRESULT CALLBACK
apartment_wndproc(HWND hWnd
, UINT msg
, WPARAM wParam
, LPARAM lParam
)
547 RPC_ExecuteCall((struct dispatch_params
*)lParam
);
550 return apartment_hostobject(COM_CurrentApt(), (const struct host_object_params
*)lParam
);
552 return DefWindowProcW(hWnd
, msg
, wParam
, lParam
);
556 struct host_thread_params
558 COINIT threading_model
;
563 static DWORD CALLBACK
apartment_hostobject_thread(LPVOID p
)
565 struct host_thread_params
*params
= p
;
568 struct apartment
*apt
;
572 hr
= CoInitializeEx(NULL
, params
->threading_model
);
573 if (FAILED(hr
)) return hr
;
575 apt
= COM_CurrentApt();
576 if (params
->threading_model
== COINIT_APARTMENTTHREADED
)
578 apartment_createwindowifneeded(apt
);
579 params
->apartment_hwnd
= apartment_getwindow(apt
);
582 params
->apartment_hwnd
= NULL
;
584 /* force the message queue to be created before signaling parent thread */
585 PeekMessageW(&msg
, NULL
, WM_USER
, WM_USER
, PM_NOREMOVE
);
587 SetEvent(params
->ready_event
);
588 params
= NULL
; /* can't touch params after here as it may be invalid */
590 while (GetMessageW(&msg
, NULL
, 0, 0))
592 if (!msg
.hwnd
&& (msg
.message
== DM_HOSTOBJECT
))
594 struct host_object_params
*obj_params
= (struct host_object_params
*)msg
.lParam
;
595 obj_params
->hr
= apartment_hostobject(apt
, obj_params
);
596 SetEvent(obj_params
->event
);
600 TranslateMessage(&msg
);
601 DispatchMessageW(&msg
);
612 static HRESULT
apartment_hostobject_in_hostapt(struct apartment
*apt
, BOOL multi_threaded
, BOOL main_apartment
, HKEY hkeydll
, REFCLSID rclsid
, REFIID riid
, void **ppv
)
614 struct host_object_params params
;
615 HWND apartment_hwnd
= NULL
;
616 DWORD apartment_tid
= 0;
619 if (!multi_threaded
&& main_apartment
)
621 APARTMENT
*host_apt
= apartment_findmain();
624 apartment_hwnd
= apartment_getwindow(host_apt
);
625 apartment_release(host_apt
);
631 EnterCriticalSection(&apt
->cs
);
633 if (!apt
->host_apt_tid
)
635 struct host_thread_params thread_params
;
639 thread_params
.threading_model
= multi_threaded
? COINIT_MULTITHREADED
: COINIT_APARTMENTTHREADED
;
640 handles
[0] = thread_params
.ready_event
= CreateEventW(NULL
, FALSE
, FALSE
, NULL
);
641 thread_params
.apartment_hwnd
= NULL
;
642 handles
[1] = CreateThread(NULL
, 0, apartment_hostobject_thread
, &thread_params
, 0, &apt
->host_apt_tid
);
645 CloseHandle(handles
[0]);
646 LeaveCriticalSection(&apt
->cs
);
647 return E_OUTOFMEMORY
;
649 wait_value
= WaitForMultipleObjects(2, handles
, FALSE
, INFINITE
);
650 CloseHandle(handles
[0]);
651 CloseHandle(handles
[1]);
652 if (wait_value
== WAIT_OBJECT_0
)
653 apt
->host_apt_hwnd
= thread_params
.apartment_hwnd
;
656 LeaveCriticalSection(&apt
->cs
);
657 return E_OUTOFMEMORY
;
661 if (multi_threaded
|| !main_apartment
)
663 apartment_hwnd
= apt
->host_apt_hwnd
;
664 apartment_tid
= apt
->host_apt_tid
;
667 LeaveCriticalSection(&apt
->cs
);
670 /* another thread may have become the main apartment in the time it took
671 * us to create the thread for the host apartment */
672 if (!apartment_hwnd
&& !multi_threaded
&& main_apartment
)
674 APARTMENT
*host_apt
= apartment_findmain();
677 apartment_hwnd
= apartment_getwindow(host_apt
);
678 apartment_release(host_apt
);
682 params
.hkeydll
= hkeydll
;
683 params
.clsid
= *rclsid
;
685 hr
= CreateStreamOnHGlobal(NULL
, TRUE
, ¶ms
.stream
);
688 params
.apartment_threaded
= !multi_threaded
;
692 params
.event
= CreateEventW(NULL
, FALSE
, FALSE
, NULL
);
693 if (!PostThreadMessageW(apartment_tid
, DM_HOSTOBJECT
, 0, (LPARAM
)¶ms
))
697 WaitForSingleObject(params
.event
, INFINITE
);
700 CloseHandle(params
.event
);
706 ERR("host apartment didn't create window\n");
710 hr
= SendMessageW(apartment_hwnd
, DM_HOSTOBJECT
, 0, (LPARAM
)¶ms
);
713 hr
= CoUnmarshalInterface(params
.stream
, riid
, ppv
);
714 IStream_Release(params
.stream
);
718 HRESULT
apartment_createwindowifneeded(struct apartment
*apt
)
720 if (apt
->multi_threaded
)
725 HWND hwnd
= CreateWindowW(wszAptWinClass
, NULL
, 0,
727 0, 0, OLE32_hInstance
, NULL
);
730 ERR("CreateWindow failed with error %d\n", GetLastError());
731 return HRESULT_FROM_WIN32(GetLastError());
733 if (InterlockedCompareExchangePointer((PVOID
*)&apt
->win
, hwnd
, NULL
))
734 /* someone beat us to it */
741 HWND
apartment_getwindow(const struct apartment
*apt
)
743 assert(!apt
->multi_threaded
);
747 void apartment_joinmta(void)
749 apartment_addref(MTA
);
750 COM_CurrentInfo()->apt
= MTA
;
753 static HRESULT
apartment_getclassobject(struct apartment
*apt
, LPCWSTR dllpath
,
754 BOOL apartment_threaded
,
755 REFCLSID rclsid
, REFIID riid
, void **ppv
)
757 static const WCHAR wszOle32
[] = {'o','l','e','3','2','.','d','l','l',0};
760 struct apartment_loaded_dll
*apartment_loaded_dll
;
762 if (!strcmpiW(dllpath
, wszOle32
))
764 /* we don't need to control the lifetime of this dll, so use the local
765 * implementation of DllGetClassObject directly */
766 TRACE("calling ole32!DllGetClassObject\n");
767 hr
= DllGetClassObject(rclsid
, riid
, ppv
);
770 ERR("DllGetClassObject returned error 0x%08x\n", hr
);
775 EnterCriticalSection(&apt
->cs
);
777 LIST_FOR_EACH_ENTRY(apartment_loaded_dll
, &apt
->loaded_dlls
, struct apartment_loaded_dll
, entry
)
778 if (!strcmpiW(dllpath
, apartment_loaded_dll
->dll
->library_name
))
780 TRACE("found %s already loaded\n", debugstr_w(dllpath
));
787 apartment_loaded_dll
= HeapAlloc(GetProcessHeap(), 0, sizeof(*apartment_loaded_dll
));
788 if (!apartment_loaded_dll
)
792 apartment_loaded_dll
->unload_time
= 0;
793 apartment_loaded_dll
->multi_threaded
= FALSE
;
794 hr
= COMPOBJ_DllList_Add( dllpath
, &apartment_loaded_dll
->dll
);
796 HeapFree(GetProcessHeap(), 0, apartment_loaded_dll
);
800 TRACE("added new loaded dll %s\n", debugstr_w(dllpath
));
801 list_add_tail(&apt
->loaded_dlls
, &apartment_loaded_dll
->entry
);
805 LeaveCriticalSection(&apt
->cs
);
809 /* one component being multi-threaded overrides any number of
810 * apartment-threaded components */
811 if (!apartment_threaded
)
812 apartment_loaded_dll
->multi_threaded
= TRUE
;
814 TRACE("calling DllGetClassObject %p\n", apartment_loaded_dll
->dll
->DllGetClassObject
);
815 /* OK: get the ClassObject */
816 hr
= apartment_loaded_dll
->dll
->DllGetClassObject(rclsid
, riid
, ppv
);
819 ERR("DllGetClassObject returned error 0x%08x\n", hr
);
825 static void apartment_freeunusedlibraries(struct apartment
*apt
, DWORD delay
)
827 struct apartment_loaded_dll
*entry
, *next
;
828 EnterCriticalSection(&apt
->cs
);
829 LIST_FOR_EACH_ENTRY_SAFE(entry
, next
, &apt
->loaded_dlls
, struct apartment_loaded_dll
, entry
)
831 if (entry
->dll
->DllCanUnloadNow
&& (entry
->dll
->DllCanUnloadNow() == S_OK
))
833 DWORD real_delay
= delay
;
835 if (real_delay
== INFINITE
)
837 if (entry
->multi_threaded
)
838 real_delay
= 10 * 60 * 1000; /* 10 minutes */
843 if (!real_delay
|| (entry
->unload_time
&& (entry
->unload_time
< GetTickCount())))
845 list_remove(&entry
->entry
);
846 COMPOBJ_DllList_ReleaseRef(entry
->dll
, TRUE
);
847 HeapFree(GetProcessHeap(), 0, entry
);
850 entry
->unload_time
= GetTickCount() + real_delay
;
852 else if (entry
->unload_time
)
853 entry
->unload_time
= 0;
855 LeaveCriticalSection(&apt
->cs
);
858 /*****************************************************************************
859 * This section contains OpenDllList implementation
862 /* caller must ensure that library_name is not already in the open dll list */
863 static HRESULT
COMPOBJ_DllList_Add(LPCWSTR library_name
, OpenDll
**ret
)
869 DllCanUnloadNowFunc DllCanUnloadNow
;
870 DllGetClassObjectFunc DllGetClassObject
;
874 *ret
= COMPOBJ_DllList_Get(library_name
);
875 if (*ret
) return S_OK
;
877 /* do this outside the csOpenDllList to avoid creating a lock dependency on
879 hLibrary
= LoadLibraryExW(library_name
, 0, LOAD_WITH_ALTERED_SEARCH_PATH
);
882 ERR("couldn't load in-process dll %s\n", debugstr_w(library_name
));
883 /* failure: DLL could not be loaded */
884 return E_ACCESSDENIED
; /* FIXME: or should this be CO_E_DLLNOTFOUND? */
887 DllCanUnloadNow
= (void *)GetProcAddress(hLibrary
, "DllCanUnloadNow");
888 /* Note: failing to find DllCanUnloadNow is not a failure */
889 DllGetClassObject
= (void *)GetProcAddress(hLibrary
, "DllGetClassObject");
890 if (!DllGetClassObject
)
892 /* failure: the dll did not export DllGetClassObject */
893 ERR("couldn't find function DllGetClassObject in %s\n", debugstr_w(library_name
));
894 FreeLibrary(hLibrary
);
895 return CO_E_DLLNOTFOUND
;
898 EnterCriticalSection( &csOpenDllList
);
900 *ret
= COMPOBJ_DllList_Get(library_name
);
903 /* another caller to this function already added the dll while we
904 * weren't in the critical section */
905 FreeLibrary(hLibrary
);
909 len
= strlenW(library_name
);
910 entry
= HeapAlloc(GetProcessHeap(),0, sizeof(OpenDll
));
912 entry
->library_name
= HeapAlloc(GetProcessHeap(), 0, (len
+ 1)*sizeof(WCHAR
));
913 if (entry
&& entry
->library_name
)
915 memcpy(entry
->library_name
, library_name
, (len
+ 1)*sizeof(WCHAR
));
916 entry
->library
= hLibrary
;
918 entry
->DllCanUnloadNow
= DllCanUnloadNow
;
919 entry
->DllGetClassObject
= DllGetClassObject
;
920 list_add_tail(&openDllList
, &entry
->entry
);
925 FreeLibrary(hLibrary
);
930 LeaveCriticalSection( &csOpenDllList
);
935 static OpenDll
*COMPOBJ_DllList_Get(LPCWSTR library_name
)
939 EnterCriticalSection(&csOpenDllList
);
940 LIST_FOR_EACH_ENTRY(ptr
, &openDllList
, OpenDll
, entry
)
942 if (!strcmpiW(library_name
, ptr
->library_name
) &&
943 (InterlockedIncrement(&ptr
->refs
) != 1) /* entry is being destroy if == 1 */)
949 LeaveCriticalSection(&csOpenDllList
);
953 /* pass FALSE for free_entry to release a reference without destroying the
954 * entry if it reaches zero or TRUE otherwise */
955 static void COMPOBJ_DllList_ReleaseRef(OpenDll
*entry
, BOOL free_entry
)
957 if (!InterlockedDecrement(&entry
->refs
) && free_entry
)
959 EnterCriticalSection(&csOpenDllList
);
960 list_remove(&entry
->entry
);
961 LeaveCriticalSection(&csOpenDllList
);
963 TRACE("freeing %p\n", entry
->library
);
964 FreeLibrary(entry
->library
);
966 HeapFree(GetProcessHeap(), 0, entry
->library_name
);
967 HeapFree(GetProcessHeap(), 0, entry
);
971 /* frees memory associated with active dll list */
972 static void COMPOBJ_DllList_Free(void)
974 OpenDll
*entry
, *cursor2
;
975 EnterCriticalSection(&csOpenDllList
);
976 LIST_FOR_EACH_ENTRY_SAFE(entry
, cursor2
, &openDllList
, OpenDll
, entry
)
978 list_remove(&entry
->entry
);
980 HeapFree(GetProcessHeap(), 0, entry
->library_name
);
981 HeapFree(GetProcessHeap(), 0, entry
);
983 LeaveCriticalSection(&csOpenDllList
);
986 /******************************************************************************
987 * CoBuildVersion [OLE32.@]
988 * CoBuildVersion [COMPOBJ.1]
990 * Gets the build version of the DLL.
995 * Current build version, hiword is majornumber, loword is minornumber
997 DWORD WINAPI
CoBuildVersion(void)
999 TRACE("Returning version %d, build %d.\n", rmm
, rup
);
1000 return (rmm
<<16)+rup
;
1003 /******************************************************************************
1004 * CoInitialize [OLE32.@]
1006 * Initializes the COM libraries by calling CoInitializeEx with
1007 * COINIT_APARTMENTTHREADED, ie it enters a STA thread.
1010 * lpReserved [I] Pointer to IMalloc interface (obsolete, should be NULL).
1013 * Success: S_OK if not already initialized, S_FALSE otherwise.
1014 * Failure: HRESULT code.
1019 HRESULT WINAPI
CoInitialize(LPVOID lpReserved
)
1022 * Just delegate to the newer method.
1024 return CoInitializeEx(lpReserved
, COINIT_APARTMENTTHREADED
);
1027 /******************************************************************************
1028 * CoInitializeEx [OLE32.@]
1030 * Initializes the COM libraries.
1033 * lpReserved [I] Pointer to IMalloc interface (obsolete, should be NULL).
1034 * dwCoInit [I] One or more flags from the COINIT enumeration. See notes.
1037 * S_OK if successful,
1038 * S_FALSE if this function was called already.
1039 * RPC_E_CHANGED_MODE if a previous call to CoInitializeEx specified another
1044 * The behavior used to set the IMalloc used for memory management is
1046 * The dwCoInit parameter must specify one of the following apartment
1048 *| COINIT_APARTMENTTHREADED - A single-threaded apartment (STA).
1049 *| COINIT_MULTITHREADED - A multi-threaded apartment (MTA).
1050 * The parameter may also specify zero or more of the following flags:
1051 *| COINIT_DISABLE_OLE1DDE - Don't use DDE for OLE1 support.
1052 *| COINIT_SPEED_OVER_MEMORY - Trade memory for speed.
1057 HRESULT WINAPI
CoInitializeEx(LPVOID lpReserved
, DWORD dwCoInit
)
1062 TRACE("(%p, %x)\n", lpReserved
, (int)dwCoInit
);
1064 if (lpReserved
!=NULL
)
1066 ERR("(%p, %x) - Bad parameter passed-in %p, must be an old Windows Application\n", lpReserved
, (int)dwCoInit
, lpReserved
);
1070 * Check the lock count. If this is the first time going through the initialize
1071 * process, we have to initialize the libraries.
1073 * And crank-up that lock count.
1075 if (InterlockedExchangeAdd(&s_COMLockCount
,1)==0)
1078 * Initialize the various COM libraries and data structures.
1080 TRACE("() - Initializing the COM libraries\n");
1082 /* we may need to defer this until after apartment initialisation */
1083 RunningObjectTableImpl_Initialize();
1086 if (!(apt
= COM_CurrentInfo()->apt
))
1088 apt
= apartment_get_or_create(dwCoInit
);
1089 if (!apt
) return E_OUTOFMEMORY
;
1091 else if (!apartment_is_model(apt
, dwCoInit
))
1093 /* Changing the threading model after it's been set is illegal. If this warning is triggered by Wine
1094 code then we are probably using the wrong threading model to implement that API. */
1095 ERR("Attempt to change threading model of this apartment from %s to %s\n",
1096 apt
->multi_threaded
? "multi-threaded" : "apartment threaded",
1097 dwCoInit
& COINIT_APARTMENTTHREADED
? "apartment threaded" : "multi-threaded");
1098 return RPC_E_CHANGED_MODE
;
1103 COM_CurrentInfo()->inits
++;
1108 /***********************************************************************
1109 * CoUninitialize [OLE32.@]
1111 * This method will decrement the refcount on the current apartment, freeing
1112 * the resources associated with it if it is the last thread in the apartment.
1113 * If the last apartment is freed, the function will additionally release
1114 * any COM resources associated with the process.
1124 void WINAPI
CoUninitialize(void)
1126 struct oletls
* info
= COM_CurrentInfo();
1131 /* will only happen on OOM */
1137 ERR("Mismatched CoUninitialize\n");
1143 apartment_release(info
->apt
);
1148 * Decrease the reference count.
1149 * If we are back to 0 locks on the COM library, make sure we free
1150 * all the associated data structures.
1152 lCOMRefCnt
= InterlockedExchangeAdd(&s_COMLockCount
,-1);
1155 TRACE("() - Releasing the COM libraries\n");
1157 RunningObjectTableImpl_UnInitialize();
1159 else if (lCOMRefCnt
<1) {
1160 ERR( "CoUninitialize() - not CoInitialized.\n" );
1161 InterlockedExchangeAdd(&s_COMLockCount
,1); /* restore the lock count. */
1165 /******************************************************************************
1166 * CoDisconnectObject [OLE32.@]
1168 * Disconnects all connections to this object from remote processes. Dispatches
1169 * pending RPCs while blocking new RPCs from occurring, and then calls
1170 * IMarshal::DisconnectObject on the given object.
1172 * Typically called when the object server is forced to shut down, for instance by
1176 * lpUnk [I] The object whose stub should be disconnected.
1177 * reserved [I] Reserved. Should be set to 0.
1181 * Failure: HRESULT code.
1184 * CoMarshalInterface, CoReleaseMarshalData, CoLockObjectExternal
1186 HRESULT WINAPI
CoDisconnectObject( LPUNKNOWN lpUnk
, DWORD reserved
)
1192 TRACE("(%p, 0x%08x)\n", lpUnk
, reserved
);
1194 hr
= IUnknown_QueryInterface(lpUnk
, &IID_IMarshal
, (void **)&marshal
);
1197 hr
= IMarshal_DisconnectObject(marshal
, reserved
);
1198 IMarshal_Release(marshal
);
1202 apt
= COM_CurrentApt();
1204 return CO_E_NOTINITIALIZED
;
1206 apartment_disconnectobject(apt
, lpUnk
);
1208 /* Note: native is pretty broken here because it just silently
1209 * fails, without returning an appropriate error code if the object was
1210 * not found, making apps think that the object was disconnected, when
1211 * it actually wasn't */
1216 /******************************************************************************
1217 * CoCreateGuid [OLE32.@]
1218 * CoCreateGuid [COMPOBJ.73]
1220 * Simply forwards to UuidCreate in RPCRT4.
1223 * pguid [O] Points to the GUID to initialize.
1227 * Failure: HRESULT code.
1232 HRESULT WINAPI
CoCreateGuid(GUID
*pguid
)
1234 return UuidCreate(pguid
);
1237 /******************************************************************************
1238 * CLSIDFromString [OLE32.@]
1239 * IIDFromString [OLE32.@]
1241 * Converts a unique identifier from its string representation into
1245 * idstr [I] The string representation of the GUID.
1246 * id [O] GUID converted from the string.
1250 * CO_E_CLASSSTRING if idstr is not a valid CLSID
1255 static HRESULT WINAPI
__CLSIDFromString(LPCWSTR s
, CLSID
*id
)
1261 memset( id
, 0, sizeof (CLSID
) );
1265 /* validate the CLSID string */
1266 if (strlenW(s
) != 38)
1267 return CO_E_CLASSSTRING
;
1269 if ((s
[0]!='{') || (s
[9]!='-') || (s
[14]!='-') || (s
[19]!='-') || (s
[24]!='-') || (s
[37]!='}'))
1270 return CO_E_CLASSSTRING
;
1272 for (i
=1; i
<37; i
++) {
1273 if ((i
== 9)||(i
== 14)||(i
== 19)||(i
== 24)) continue;
1274 if (!(((s
[i
] >= '0') && (s
[i
] <= '9')) ||
1275 ((s
[i
] >= 'a') && (s
[i
] <= 'f')) ||
1276 ((s
[i
] >= 'A') && (s
[i
] <= 'F'))))
1277 return CO_E_CLASSSTRING
;
1280 TRACE("%s -> %p\n", debugstr_w(s
), id
);
1282 /* quick lookup table */
1283 memset(table
, 0, 256);
1285 for (i
= 0; i
< 10; i
++) {
1288 for (i
= 0; i
< 6; i
++) {
1289 table
['A' + i
] = i
+10;
1290 table
['a' + i
] = i
+10;
1293 /* in form {XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX} */
1295 id
->Data1
= (table
[s
[1]] << 28 | table
[s
[2]] << 24 | table
[s
[3]] << 20 | table
[s
[4]] << 16 |
1296 table
[s
[5]] << 12 | table
[s
[6]] << 8 | table
[s
[7]] << 4 | table
[s
[8]]);
1297 id
->Data2
= table
[s
[10]] << 12 | table
[s
[11]] << 8 | table
[s
[12]] << 4 | table
[s
[13]];
1298 id
->Data3
= table
[s
[15]] << 12 | table
[s
[16]] << 8 | table
[s
[17]] << 4 | table
[s
[18]];
1300 /* these are just sequential bytes */
1301 id
->Data4
[0] = table
[s
[20]] << 4 | table
[s
[21]];
1302 id
->Data4
[1] = table
[s
[22]] << 4 | table
[s
[23]];
1303 id
->Data4
[2] = table
[s
[25]] << 4 | table
[s
[26]];
1304 id
->Data4
[3] = table
[s
[27]] << 4 | table
[s
[28]];
1305 id
->Data4
[4] = table
[s
[29]] << 4 | table
[s
[30]];
1306 id
->Data4
[5] = table
[s
[31]] << 4 | table
[s
[32]];
1307 id
->Data4
[6] = table
[s
[33]] << 4 | table
[s
[34]];
1308 id
->Data4
[7] = table
[s
[35]] << 4 | table
[s
[36]];
1313 /*****************************************************************************/
1315 HRESULT WINAPI
CLSIDFromString(LPOLESTR idstr
, CLSID
*id
)
1320 return E_INVALIDARG
;
1322 ret
= __CLSIDFromString(idstr
, id
);
1323 if(ret
!= S_OK
) { /* It appears a ProgID is also valid */
1324 ret
= CLSIDFromProgID(idstr
, id
);
1329 /* Converts a GUID into the respective string representation. */
1330 HRESULT
WINE_StringFromCLSID(
1331 const CLSID
*id
, /* [in] GUID to be converted */
1332 LPSTR idstr
/* [out] pointer to buffer to contain converted guid */
1334 static const char hex
[] = "0123456789ABCDEF";
1339 { ERR("called with id=Null\n");
1344 sprintf(idstr
, "{%08X-%04X-%04X-%02X%02X-",
1345 id
->Data1
, id
->Data2
, id
->Data3
,
1346 id
->Data4
[0], id
->Data4
[1]);
1350 for (i
= 2; i
< 8; i
++) {
1351 *s
++ = hex
[id
->Data4
[i
]>>4];
1352 *s
++ = hex
[id
->Data4
[i
] & 0xf];
1358 TRACE("%p->%s\n", id
, idstr
);
1364 /******************************************************************************
1365 * StringFromCLSID [OLE32.@]
1366 * StringFromIID [OLE32.@]
1368 * Converts a GUID into the respective string representation.
1369 * The target string is allocated using the OLE IMalloc.
1372 * id [I] the GUID to be converted.
1373 * idstr [O] A pointer to a to-be-allocated pointer pointing to the resulting string.
1380 * StringFromGUID2, CLSIDFromString
1382 HRESULT WINAPI
StringFromCLSID(REFCLSID id
, LPOLESTR
*idstr
)
1388 if ((ret
= CoGetMalloc(0,&mllc
)))
1391 ret
=WINE_StringFromCLSID(id
,buf
);
1393 DWORD len
= MultiByteToWideChar( CP_ACP
, 0, buf
, -1, NULL
, 0 );
1394 *idstr
= IMalloc_Alloc( mllc
, len
* sizeof(WCHAR
) );
1395 MultiByteToWideChar( CP_ACP
, 0, buf
, -1, *idstr
, len
);
1400 /******************************************************************************
1401 * StringFromGUID2 [OLE32.@]
1402 * StringFromGUID2 [COMPOBJ.76]
1404 * Modified version of StringFromCLSID that allows you to specify max
1408 * id [I] GUID to convert to string.
1409 * str [O] Buffer where the result will be stored.
1410 * cmax [I] Size of the buffer in characters.
1413 * Success: The length of the resulting string in characters.
1416 INT WINAPI
StringFromGUID2(REFGUID id
, LPOLESTR str
, INT cmax
)
1420 if (WINE_StringFromCLSID(id
,xguid
))
1422 return MultiByteToWideChar( CP_ACP
, 0, xguid
, -1, str
, cmax
);
1425 /* open HKCR\\CLSID\\{string form of clsid}\\{keyname} key */
1426 HRESULT
COM_OpenKeyForCLSID(REFCLSID clsid
, LPCWSTR keyname
, REGSAM access
, HKEY
*subkey
)
1428 static const WCHAR wszCLSIDSlash
[] = {'C','L','S','I','D','\\',0};
1429 WCHAR path
[CHARS_IN_GUID
+ ARRAYSIZE(wszCLSIDSlash
) - 1];
1433 strcpyW(path
, wszCLSIDSlash
);
1434 StringFromGUID2(clsid
, path
+ strlenW(wszCLSIDSlash
), CHARS_IN_GUID
);
1435 res
= RegOpenKeyExW(HKEY_CLASSES_ROOT
, path
, 0, keyname
? KEY_READ
: access
, &key
);
1436 if (res
== ERROR_FILE_NOT_FOUND
)
1437 return REGDB_E_CLASSNOTREG
;
1438 else if (res
!= ERROR_SUCCESS
)
1439 return REGDB_E_READREGDB
;
1447 res
= RegOpenKeyExW(key
, keyname
, 0, access
, subkey
);
1449 if (res
== ERROR_FILE_NOT_FOUND
)
1450 return REGDB_E_KEYMISSING
;
1451 else if (res
!= ERROR_SUCCESS
)
1452 return REGDB_E_READREGDB
;
1457 /* open HKCR\\AppId\\{string form of appid clsid} key */
1458 HRESULT
COM_OpenKeyForAppIdFromCLSID(REFCLSID clsid
, REGSAM access
, HKEY
*subkey
)
1460 static const WCHAR szAppId
[] = { 'A','p','p','I','d',0 };
1461 static const WCHAR szAppIdKey
[] = { 'A','p','p','I','d','\\',0 };
1463 WCHAR buf
[CHARS_IN_GUID
];
1464 WCHAR keyname
[ARRAYSIZE(szAppIdKey
) + CHARS_IN_GUID
];
1470 /* read the AppID value under the class's key */
1471 hr
= COM_OpenKeyForCLSID(clsid
, NULL
, KEY_READ
, &hkey
);
1476 res
= RegQueryValueExW(hkey
, szAppId
, NULL
, &type
, (LPBYTE
)buf
, &size
);
1478 if (res
== ERROR_FILE_NOT_FOUND
)
1479 return REGDB_E_KEYMISSING
;
1480 else if (res
!= ERROR_SUCCESS
|| type
!=REG_SZ
)
1481 return REGDB_E_READREGDB
;
1483 strcpyW(keyname
, szAppIdKey
);
1484 strcatW(keyname
, buf
);
1485 res
= RegOpenKeyExW(HKEY_CLASSES_ROOT
, keyname
, 0, access
, subkey
);
1486 if (res
== ERROR_FILE_NOT_FOUND
)
1487 return REGDB_E_KEYMISSING
;
1488 else if (res
!= ERROR_SUCCESS
)
1489 return REGDB_E_READREGDB
;
1494 /******************************************************************************
1495 * ProgIDFromCLSID [OLE32.@]
1497 * Converts a class id into the respective program ID.
1500 * clsid [I] Class ID, as found in registry.
1501 * ppszProgID [O] Associated ProgID.
1506 * REGDB_E_CLASSNOTREG if the given clsid has no associated ProgID
1508 HRESULT WINAPI
ProgIDFromCLSID(REFCLSID clsid
, LPOLESTR
*ppszProgID
)
1510 static const WCHAR wszProgID
[] = {'P','r','o','g','I','D',0};
1517 ERR("ppszProgId isn't optional\n");
1518 return E_INVALIDARG
;
1522 ret
= COM_OpenKeyForCLSID(clsid
, wszProgID
, KEY_READ
, &hkey
);
1526 if (RegQueryValueW(hkey
, NULL
, NULL
, &progidlen
))
1527 ret
= REGDB_E_CLASSNOTREG
;
1531 *ppszProgID
= CoTaskMemAlloc(progidlen
* sizeof(WCHAR
));
1534 if (RegQueryValueW(hkey
, NULL
, *ppszProgID
, &progidlen
))
1535 ret
= REGDB_E_CLASSNOTREG
;
1538 ret
= E_OUTOFMEMORY
;
1545 /******************************************************************************
1546 * CLSIDFromProgID [OLE32.@]
1548 * Converts a program id into the respective GUID.
1551 * progid [I] Unicode program ID, as found in registry.
1552 * clsid [O] Associated CLSID.
1556 * Failure: CO_E_CLASSSTRING - the given ProgID cannot be found.
1558 HRESULT WINAPI
CLSIDFromProgID(LPCOLESTR progid
, LPCLSID clsid
)
1560 static const WCHAR clsidW
[] = { '\\','C','L','S','I','D',0 };
1561 WCHAR buf2
[CHARS_IN_GUID
];
1562 LONG buf2len
= sizeof(buf2
);
1566 if (!progid
|| !clsid
)
1568 ERR("neither progid (%p) nor clsid (%p) are optional\n", progid
, clsid
);
1569 return E_INVALIDARG
;
1572 /* initialise clsid in case of failure */
1573 memset(clsid
, 0, sizeof(*clsid
));
1575 buf
= HeapAlloc( GetProcessHeap(),0,(strlenW(progid
)+8) * sizeof(WCHAR
) );
1576 strcpyW( buf
, progid
);
1577 strcatW( buf
, clsidW
);
1578 if (RegOpenKeyW(HKEY_CLASSES_ROOT
,buf
,&xhkey
))
1580 HeapFree(GetProcessHeap(),0,buf
);
1581 WARN("couldn't open key for ProgID %s\n", debugstr_w(progid
));
1582 return CO_E_CLASSSTRING
;
1584 HeapFree(GetProcessHeap(),0,buf
);
1586 if (RegQueryValueW(xhkey
,NULL
,buf2
,&buf2len
))
1589 WARN("couldn't query clsid value for ProgID %s\n", debugstr_w(progid
));
1590 return CO_E_CLASSSTRING
;
1593 return CLSIDFromString(buf2
,clsid
);
1597 /*****************************************************************************
1598 * CoGetPSClsid [OLE32.@]
1600 * Retrieves the CLSID of the proxy/stub factory that implements
1601 * IPSFactoryBuffer for the specified interface.
1604 * riid [I] Interface whose proxy/stub CLSID is to be returned.
1605 * pclsid [O] Where to store returned proxy/stub CLSID.
1610 * REGDB_E_IIDNOTREG if no PSFactoryBuffer is associated with the IID, or it could not be parsed
1614 * The standard marshaller activates the object with the CLSID
1615 * returned and uses the CreateProxy and CreateStub methods on its
1616 * IPSFactoryBuffer interface to construct the proxies and stubs for a
1619 * CoGetPSClsid determines this CLSID by searching the
1620 * HKEY_CLASSES_ROOT\Interface\{string form of riid}\ProxyStubClsid32
1621 * in the registry and any interface id registered by
1622 * CoRegisterPSClsid within the current process.
1626 * Native returns S_OK for interfaces with a key in HKCR\Interface, but
1627 * without a ProxyStubClsid32 key and leaves garbage in pclsid. This should be
1628 * considered a bug in native unless an application depends on this (unlikely).
1631 * CoRegisterPSClsid.
1633 HRESULT WINAPI
CoGetPSClsid(REFIID riid
, CLSID
*pclsid
)
1635 static const WCHAR wszInterface
[] = {'I','n','t','e','r','f','a','c','e','\\',0};
1636 static const WCHAR wszPSC
[] = {'\\','P','r','o','x','y','S','t','u','b','C','l','s','i','d','3','2',0};
1637 WCHAR path
[ARRAYSIZE(wszInterface
) - 1 + CHARS_IN_GUID
- 1 + ARRAYSIZE(wszPSC
)];
1638 WCHAR value
[CHARS_IN_GUID
];
1641 APARTMENT
*apt
= COM_CurrentApt();
1642 struct registered_psclsid
*registered_psclsid
;
1644 TRACE("() riid=%s, pclsid=%p\n", debugstr_guid(riid
), pclsid
);
1648 ERR("apartment not initialised\n");
1649 return CO_E_NOTINITIALIZED
;
1654 ERR("pclsid isn't optional\n");
1655 return E_INVALIDARG
;
1658 EnterCriticalSection(&apt
->cs
);
1660 LIST_FOR_EACH_ENTRY(registered_psclsid
, &apt
->psclsids
, struct registered_psclsid
, entry
)
1661 if (IsEqualIID(®istered_psclsid
->iid
, riid
))
1663 *pclsid
= registered_psclsid
->clsid
;
1664 LeaveCriticalSection(&apt
->cs
);
1668 LeaveCriticalSection(&apt
->cs
);
1670 /* Interface\\{string form of riid}\\ProxyStubClsid32 */
1671 strcpyW(path
, wszInterface
);
1672 StringFromGUID2(riid
, path
+ ARRAYSIZE(wszInterface
) - 1, CHARS_IN_GUID
);
1673 strcpyW(path
+ ARRAYSIZE(wszInterface
) - 1 + CHARS_IN_GUID
- 1, wszPSC
);
1675 /* Open the key.. */
1676 if (RegOpenKeyExW(HKEY_CLASSES_ROOT
, path
, 0, KEY_READ
, &hkey
))
1678 WARN("No PSFactoryBuffer object is registered for IID %s\n", debugstr_guid(riid
));
1679 return REGDB_E_IIDNOTREG
;
1682 /* ... Once we have the key, query the registry to get the
1683 value of CLSID as a string, and convert it into a
1684 proper CLSID structure to be passed back to the app */
1685 len
= sizeof(value
);
1686 if (ERROR_SUCCESS
!= RegQueryValueW(hkey
, NULL
, value
, &len
))
1689 return REGDB_E_IIDNOTREG
;
1693 /* We have the CLSID we want back from the registry as a string, so
1694 let's convert it into a CLSID structure */
1695 if (CLSIDFromString(value
, pclsid
) != NOERROR
)
1696 return REGDB_E_IIDNOTREG
;
1698 TRACE ("() Returning CLSID=%s\n", debugstr_guid(pclsid
));
1702 /*****************************************************************************
1703 * CoRegisterPSClsid [OLE32.@]
1705 * Register a proxy/stub CLSID for the given interface in the current process
1709 * riid [I] Interface whose proxy/stub CLSID is to be registered.
1710 * rclsid [I] CLSID of the proxy/stub.
1714 * Failure: E_OUTOFMEMORY
1718 * This function does not add anything to the registry and the effects are
1719 * limited to the lifetime of the current process.
1724 HRESULT WINAPI
CoRegisterPSClsid(REFIID riid
, REFCLSID rclsid
)
1726 APARTMENT
*apt
= COM_CurrentApt();
1727 struct registered_psclsid
*registered_psclsid
;
1729 TRACE("(%s, %s)\n", debugstr_guid(riid
), debugstr_guid(rclsid
));
1733 ERR("apartment not initialised\n");
1734 return CO_E_NOTINITIALIZED
;
1737 EnterCriticalSection(&apt
->cs
);
1739 LIST_FOR_EACH_ENTRY(registered_psclsid
, &apt
->psclsids
, struct registered_psclsid
, entry
)
1740 if (IsEqualIID(®istered_psclsid
->iid
, riid
))
1742 registered_psclsid
->clsid
= *rclsid
;
1743 LeaveCriticalSection(&apt
->cs
);
1747 registered_psclsid
= HeapAlloc(GetProcessHeap(), 0, sizeof(struct registered_psclsid
));
1748 if (!registered_psclsid
)
1750 LeaveCriticalSection(&apt
->cs
);
1751 return E_OUTOFMEMORY
;
1754 registered_psclsid
->iid
= *riid
;
1755 registered_psclsid
->clsid
= *rclsid
;
1756 list_add_head(&apt
->psclsids
, ®istered_psclsid
->entry
);
1758 LeaveCriticalSection(&apt
->cs
);
1765 * COM_GetRegisteredClassObject
1767 * This internal method is used to scan the registered class list to
1768 * find a class object.
1771 * rclsid Class ID of the class to find.
1772 * dwClsContext Class context to match.
1773 * ppv [out] returns a pointer to the class object. Complying
1774 * to normal COM usage, this method will increase the
1775 * reference count on this object.
1777 static HRESULT
COM_GetRegisteredClassObject(const struct apartment
*apt
, REFCLSID rclsid
,
1778 DWORD dwClsContext
, LPUNKNOWN
* ppUnk
)
1780 HRESULT hr
= S_FALSE
;
1781 RegisteredClass
*curClass
;
1783 EnterCriticalSection( &csRegisteredClassList
);
1785 LIST_FOR_EACH_ENTRY(curClass
, &RegisteredClassList
, RegisteredClass
, entry
)
1788 * Check if we have a match on the class ID and context.
1790 if ((apt
->oxid
== curClass
->apartment_id
) &&
1791 (dwClsContext
& curClass
->runContext
) &&
1792 IsEqualGUID(&(curClass
->classIdentifier
), rclsid
))
1795 * We have a match, return the pointer to the class object.
1797 *ppUnk
= curClass
->classObject
;
1799 IUnknown_AddRef(curClass
->classObject
);
1806 LeaveCriticalSection( &csRegisteredClassList
);
1811 /******************************************************************************
1812 * CoRegisterClassObject [OLE32.@]
1814 * Registers the class object for a given class ID. Servers housed in EXE
1815 * files use this method instead of exporting DllGetClassObject to allow
1816 * other code to connect to their objects.
1819 * rclsid [I] CLSID of the object to register.
1820 * pUnk [I] IUnknown of the object.
1821 * dwClsContext [I] CLSCTX flags indicating the context in which to run the executable.
1822 * flags [I] REGCLS flags indicating how connections are made.
1823 * lpdwRegister [I] A unique cookie that can be passed to CoRevokeClassObject.
1827 * E_INVALIDARG if lpdwRegister or pUnk are NULL,
1828 * CO_E_OBJISREG if the object is already registered. We should not return this.
1831 * CoRevokeClassObject, CoGetClassObject
1834 * In-process objects are only registered for the current apartment.
1835 * CoGetClassObject() and CoCreateInstance() will not return objects registered
1836 * in other apartments.
1839 * MSDN claims that multiple interface registrations are legal, but we
1840 * can't do that with our current implementation.
1842 HRESULT WINAPI
CoRegisterClassObject(
1847 LPDWORD lpdwRegister
)
1849 RegisteredClass
* newClass
;
1850 LPUNKNOWN foundObject
;
1854 TRACE("(%s,%p,0x%08x,0x%08x,%p)\n",
1855 debugstr_guid(rclsid
),pUnk
,dwClsContext
,flags
,lpdwRegister
);
1857 if ( (lpdwRegister
==0) || (pUnk
==0) )
1858 return E_INVALIDARG
;
1860 apt
= COM_CurrentApt();
1863 ERR("COM was not initialized\n");
1864 return CO_E_NOTINITIALIZED
;
1869 /* REGCLS_MULTIPLEUSE implies registering as inproc server. This is what
1870 * differentiates the flag from REGCLS_MULTI_SEPARATE. */
1871 if (flags
& REGCLS_MULTIPLEUSE
)
1872 dwClsContext
|= CLSCTX_INPROC_SERVER
;
1875 * First, check if the class is already registered.
1876 * If it is, this should cause an error.
1878 hr
= COM_GetRegisteredClassObject(apt
, rclsid
, dwClsContext
, &foundObject
);
1880 if (flags
& REGCLS_MULTIPLEUSE
) {
1881 if (dwClsContext
& CLSCTX_LOCAL_SERVER
)
1882 hr
= CoLockObjectExternal(foundObject
, TRUE
, FALSE
);
1883 IUnknown_Release(foundObject
);
1886 IUnknown_Release(foundObject
);
1887 ERR("object already registered for class %s\n", debugstr_guid(rclsid
));
1888 return CO_E_OBJISREG
;
1891 newClass
= HeapAlloc(GetProcessHeap(), 0, sizeof(RegisteredClass
));
1892 if ( newClass
== NULL
)
1893 return E_OUTOFMEMORY
;
1895 newClass
->classIdentifier
= *rclsid
;
1896 newClass
->apartment_id
= apt
->oxid
;
1897 newClass
->runContext
= dwClsContext
;
1898 newClass
->connectFlags
= flags
;
1899 newClass
->pMarshaledData
= NULL
;
1900 newClass
->RpcRegistration
= NULL
;
1903 * Use the address of the chain node as the cookie since we are sure it's
1904 * unique. FIXME: not on 64-bit platforms.
1906 newClass
->dwCookie
= (DWORD
)newClass
;
1909 * Since we're making a copy of the object pointer, we have to increase its
1912 newClass
->classObject
= pUnk
;
1913 IUnknown_AddRef(newClass
->classObject
);
1915 EnterCriticalSection( &csRegisteredClassList
);
1916 list_add_tail(&RegisteredClassList
, &newClass
->entry
);
1917 LeaveCriticalSection( &csRegisteredClassList
);
1919 *lpdwRegister
= newClass
->dwCookie
;
1921 if (dwClsContext
& CLSCTX_LOCAL_SERVER
) {
1922 hr
= CreateStreamOnHGlobal(0, TRUE
, &newClass
->pMarshaledData
);
1924 FIXME("Failed to create stream on hglobal, %x\n", hr
);
1927 hr
= CoMarshalInterface(newClass
->pMarshaledData
, &IID_IClassFactory
,
1928 newClass
->classObject
, MSHCTX_LOCAL
, NULL
,
1929 MSHLFLAGS_TABLESTRONG
);
1931 FIXME("CoMarshalInterface failed, %x!\n",hr
);
1935 hr
= RPC_StartLocalServer(&newClass
->classIdentifier
,
1936 newClass
->pMarshaledData
,
1937 flags
& (REGCLS_MULTIPLEUSE
|REGCLS_MULTI_SEPARATE
),
1938 &newClass
->RpcRegistration
);
1943 static void COM_RevokeRegisteredClassObject(RegisteredClass
*curClass
)
1945 list_remove(&curClass
->entry
);
1947 if (curClass
->runContext
& CLSCTX_LOCAL_SERVER
)
1948 RPC_StopLocalServer(curClass
->RpcRegistration
);
1951 * Release the reference to the class object.
1953 IUnknown_Release(curClass
->classObject
);
1955 if (curClass
->pMarshaledData
)
1958 memset(&zero
, 0, sizeof(zero
));
1959 IStream_Seek(curClass
->pMarshaledData
, zero
, STREAM_SEEK_SET
, NULL
);
1960 CoReleaseMarshalData(curClass
->pMarshaledData
);
1961 IStream_Release(curClass
->pMarshaledData
);
1964 HeapFree(GetProcessHeap(), 0, curClass
);
1967 static void COM_RevokeAllClasses(const struct apartment
*apt
)
1969 RegisteredClass
*curClass
, *cursor
;
1971 EnterCriticalSection( &csRegisteredClassList
);
1973 LIST_FOR_EACH_ENTRY_SAFE(curClass
, cursor
, &RegisteredClassList
, RegisteredClass
, entry
)
1975 if (curClass
->apartment_id
== apt
->oxid
)
1976 COM_RevokeRegisteredClassObject(curClass
);
1979 LeaveCriticalSection( &csRegisteredClassList
);
1982 /***********************************************************************
1983 * CoRevokeClassObject [OLE32.@]
1985 * Removes a class object from the class registry.
1988 * dwRegister [I] Cookie returned from CoRegisterClassObject().
1992 * Failure: HRESULT code.
1995 * Must be called from the same apartment that called CoRegisterClassObject(),
1996 * otherwise it will fail with RPC_E_WRONG_THREAD.
1999 * CoRegisterClassObject
2001 HRESULT WINAPI
CoRevokeClassObject(
2004 HRESULT hr
= E_INVALIDARG
;
2005 RegisteredClass
*curClass
;
2008 TRACE("(%08x)\n",dwRegister
);
2010 apt
= COM_CurrentApt();
2013 ERR("COM was not initialized\n");
2014 return CO_E_NOTINITIALIZED
;
2017 EnterCriticalSection( &csRegisteredClassList
);
2019 LIST_FOR_EACH_ENTRY(curClass
, &RegisteredClassList
, RegisteredClass
, entry
)
2022 * Check if we have a match on the cookie.
2024 if (curClass
->dwCookie
== dwRegister
)
2026 if (curClass
->apartment_id
== apt
->oxid
)
2028 COM_RevokeRegisteredClassObject(curClass
);
2033 ERR("called from wrong apartment, should be called from %s\n",
2034 wine_dbgstr_longlong(curClass
->apartment_id
));
2035 hr
= RPC_E_WRONG_THREAD
;
2041 LeaveCriticalSection( &csRegisteredClassList
);
2046 /***********************************************************************
2047 * COM_RegReadPath [internal]
2049 * Reads a registry value and expands it when necessary
2051 static DWORD
COM_RegReadPath(HKEY hkeyroot
, const WCHAR
*keyname
, const WCHAR
*valuename
, WCHAR
* dst
, DWORD dstlen
)
2056 WCHAR src
[MAX_PATH
];
2057 DWORD dwLength
= dstlen
* sizeof(WCHAR
);
2059 if((ret
= RegOpenKeyExW(hkeyroot
, keyname
, 0, KEY_READ
, &key
)) == ERROR_SUCCESS
) {
2060 if( (ret
= RegQueryValueExW(key
, NULL
, NULL
, &keytype
, (LPBYTE
)src
, &dwLength
)) == ERROR_SUCCESS
) {
2061 if (keytype
== REG_EXPAND_SZ
) {
2062 if (dstlen
<= ExpandEnvironmentStringsW(src
, dst
, dstlen
)) ret
= ERROR_MORE_DATA
;
2064 lstrcpynW(dst
, src
, dstlen
);
2072 static void get_threading_model(HKEY key
, LPWSTR value
, DWORD len
)
2074 static const WCHAR wszThreadingModel
[] = {'T','h','r','e','a','d','i','n','g','M','o','d','e','l',0};
2077 DWORD dwLength
= len
* sizeof(WCHAR
);
2079 ret
= RegQueryValueExW(key
, wszThreadingModel
, NULL
, &keytype
, (LPBYTE
)value
, &dwLength
);
2080 if ((ret
!= ERROR_SUCCESS
) || (keytype
!= REG_SZ
))
2084 static HRESULT
get_inproc_class_object(APARTMENT
*apt
, HKEY hkeydll
,
2085 REFCLSID rclsid
, REFIID riid
,
2086 BOOL hostifnecessary
, void **ppv
)
2088 WCHAR dllpath
[MAX_PATH
+1];
2089 BOOL apartment_threaded
;
2091 if (hostifnecessary
)
2093 static const WCHAR wszApartment
[] = {'A','p','a','r','t','m','e','n','t',0};
2094 static const WCHAR wszFree
[] = {'F','r','e','e',0};
2095 static const WCHAR wszBoth
[] = {'B','o','t','h',0};
2096 WCHAR threading_model
[10 /* strlenW(L"apartment")+1 */];
2098 get_threading_model(hkeydll
, threading_model
, ARRAYSIZE(threading_model
));
2100 if (!strcmpiW(threading_model
, wszApartment
))
2102 apartment_threaded
= TRUE
;
2103 if (apt
->multi_threaded
)
2104 return apartment_hostobject_in_hostapt(apt
, FALSE
, FALSE
, hkeydll
, rclsid
, riid
, ppv
);
2107 else if (!strcmpiW(threading_model
, wszFree
))
2109 apartment_threaded
= FALSE
;
2110 if (!apt
->multi_threaded
)
2111 return apartment_hostobject_in_hostapt(apt
, TRUE
, FALSE
, hkeydll
, rclsid
, riid
, ppv
);
2113 /* everything except "Apartment", "Free" and "Both" */
2114 else if (strcmpiW(threading_model
, wszBoth
))
2116 apartment_threaded
= TRUE
;
2117 /* everything else is main-threaded */
2118 if (threading_model
[0])
2119 FIXME("unrecognised threading model %s for object %s, should be main-threaded?\n",
2120 debugstr_w(threading_model
), debugstr_guid(rclsid
));
2122 if (apt
->multi_threaded
|| !apt
->main
)
2123 return apartment_hostobject_in_hostapt(apt
, FALSE
, TRUE
, hkeydll
, rclsid
, riid
, ppv
);
2126 apartment_threaded
= FALSE
;
2129 apartment_threaded
= !apt
->multi_threaded
;
2131 if (COM_RegReadPath(hkeydll
, NULL
, NULL
, dllpath
, ARRAYSIZE(dllpath
)) != ERROR_SUCCESS
)
2133 /* failure: CLSID is not found in registry */
2134 WARN("class %s not registered inproc\n", debugstr_guid(rclsid
));
2135 return REGDB_E_CLASSNOTREG
;
2138 return apartment_getclassobject(apt
, dllpath
, apartment_threaded
,
2142 /***********************************************************************
2143 * CoGetClassObject [OLE32.@]
2145 * Creates an object of the specified class.
2148 * rclsid [I] Class ID to create an instance of.
2149 * dwClsContext [I] Flags to restrict the location of the created instance.
2150 * pServerInfo [I] Optional. Details for connecting to a remote server.
2151 * iid [I] The ID of the interface of the instance to return.
2152 * ppv [O] On returns, contains a pointer to the specified interface of the object.
2156 * Failure: HRESULT code.
2159 * The dwClsContext parameter can be one or more of the following:
2160 *| CLSCTX_INPROC_SERVER - Use an in-process server, such as from a DLL.
2161 *| CLSCTX_INPROC_HANDLER - Use an in-process object which handles certain functions for an object running in another process.
2162 *| CLSCTX_LOCAL_SERVER - Connect to an object running in another process.
2163 *| CLSCTX_REMOTE_SERVER - Connect to an object running on another machine.
2166 * CoCreateInstance()
2168 HRESULT WINAPI
CoGetClassObject(
2169 REFCLSID rclsid
, DWORD dwClsContext
, COSERVERINFO
*pServerInfo
,
2170 REFIID iid
, LPVOID
*ppv
)
2172 LPUNKNOWN regClassObject
;
2173 HRESULT hres
= E_UNEXPECTED
;
2176 TRACE("\n\tCLSID:\t%s,\n\tIID:\t%s\n", debugstr_guid(rclsid
), debugstr_guid(iid
));
2179 return E_INVALIDARG
;
2183 apt
= COM_CurrentApt();
2186 ERR("apartment not initialised\n");
2187 return CO_E_NOTINITIALIZED
;
2191 FIXME("\tpServerInfo: name=%s\n",debugstr_w(pServerInfo
->pwszName
));
2192 FIXME("\t\tpAuthInfo=%p\n",pServerInfo
->pAuthInfo
);
2196 * First, try and see if we can't match the class ID with one of the
2197 * registered classes.
2199 if (S_OK
== COM_GetRegisteredClassObject(apt
, rclsid
, dwClsContext
,
2202 /* Get the required interface from the retrieved pointer. */
2203 hres
= IUnknown_QueryInterface(regClassObject
, iid
, ppv
);
2206 * Since QI got another reference on the pointer, we want to release the
2207 * one we already have. If QI was unsuccessful, this will release the object. This
2208 * is good since we are not returning it in the "out" parameter.
2210 IUnknown_Release(regClassObject
);
2215 /* First try in-process server */
2216 if (CLSCTX_INPROC_SERVER
& dwClsContext
)
2218 static const WCHAR wszInprocServer32
[] = {'I','n','p','r','o','c','S','e','r','v','e','r','3','2',0};
2221 if (IsEqualCLSID(rclsid
, &CLSID_InProcFreeMarshaler
))
2222 return FTMarshalCF_Create(iid
, ppv
);
2224 hres
= COM_OpenKeyForCLSID(rclsid
, wszInprocServer32
, KEY_READ
, &hkey
);
2227 if (hres
== REGDB_E_CLASSNOTREG
)
2228 ERR("class %s not registered\n", debugstr_guid(rclsid
));
2229 else if (hres
== REGDB_E_KEYMISSING
)
2231 WARN("class %s not registered as in-proc server\n", debugstr_guid(rclsid
));
2232 hres
= REGDB_E_CLASSNOTREG
;
2236 if (SUCCEEDED(hres
))
2238 hres
= get_inproc_class_object(apt
, hkey
, rclsid
, iid
,
2239 !(dwClsContext
& WINE_CLSCTX_DONT_HOST
), ppv
);
2243 /* return if we got a class, otherwise fall through to one of the
2245 if (SUCCEEDED(hres
))
2249 /* Next try in-process handler */
2250 if (CLSCTX_INPROC_HANDLER
& dwClsContext
)
2252 static const WCHAR wszInprocHandler32
[] = {'I','n','p','r','o','c','H','a','n','d','l','e','r','3','2',0};
2255 hres
= COM_OpenKeyForCLSID(rclsid
, wszInprocHandler32
, KEY_READ
, &hkey
);
2258 if (hres
== REGDB_E_CLASSNOTREG
)
2259 ERR("class %s not registered\n", debugstr_guid(rclsid
));
2260 else if (hres
== REGDB_E_KEYMISSING
)
2262 WARN("class %s not registered in-proc handler\n", debugstr_guid(rclsid
));
2263 hres
= REGDB_E_CLASSNOTREG
;
2267 if (SUCCEEDED(hres
))
2269 hres
= get_inproc_class_object(apt
, hkey
, rclsid
, iid
,
2270 !(dwClsContext
& WINE_CLSCTX_DONT_HOST
), ppv
);
2274 /* return if we got a class, otherwise fall through to one of the
2276 if (SUCCEEDED(hres
))
2280 /* Next try out of process */
2281 if (CLSCTX_LOCAL_SERVER
& dwClsContext
)
2283 hres
= RPC_GetLocalClassObject(rclsid
,iid
,ppv
);
2284 if (SUCCEEDED(hres
))
2288 /* Finally try remote: this requires networked DCOM (a lot of work) */
2289 if (CLSCTX_REMOTE_SERVER
& dwClsContext
)
2291 FIXME ("CLSCTX_REMOTE_SERVER not supported\n");
2292 hres
= E_NOINTERFACE
;
2296 ERR("no class object %s could be created for context 0x%x\n",
2297 debugstr_guid(rclsid
), dwClsContext
);
2301 /***********************************************************************
2302 * CoResumeClassObjects (OLE32.@)
2304 * Resumes all class objects registered with REGCLS_SUSPENDED.
2308 * Failure: HRESULT code.
2310 HRESULT WINAPI
CoResumeClassObjects(void)
2316 /***********************************************************************
2317 * CoCreateInstance [OLE32.@]
2319 * Creates an instance of the specified class.
2322 * rclsid [I] Class ID to create an instance of.
2323 * pUnkOuter [I] Optional outer unknown to allow aggregation with another object.
2324 * dwClsContext [I] Flags to restrict the location of the created instance.
2325 * iid [I] The ID of the interface of the instance to return.
2326 * ppv [O] On returns, contains a pointer to the specified interface of the instance.
2330 * Failure: HRESULT code.
2333 * The dwClsContext parameter can be one or more of the following:
2334 *| CLSCTX_INPROC_SERVER - Use an in-process server, such as from a DLL.
2335 *| CLSCTX_INPROC_HANDLER - Use an in-process object which handles certain functions for an object running in another process.
2336 *| CLSCTX_LOCAL_SERVER - Connect to an object running in another process.
2337 *| CLSCTX_REMOTE_SERVER - Connect to an object running on another machine.
2339 * Aggregation is the concept of deferring the IUnknown of an object to another
2340 * object. This allows a separate object to behave as though it was part of
2341 * the object and to allow this the pUnkOuter parameter can be set. Note that
2342 * not all objects support having an outer of unknown.
2345 * CoGetClassObject()
2347 HRESULT WINAPI
CoCreateInstance(
2349 LPUNKNOWN pUnkOuter
,
2355 LPCLASSFACTORY lpclf
= 0;
2357 TRACE("(rclsid=%s, pUnkOuter=%p, dwClsContext=%08x, riid=%s, ppv=%p)\n", debugstr_guid(rclsid
),
2358 pUnkOuter
, dwClsContext
, debugstr_guid(iid
), ppv
);
2367 * Initialize the "out" parameter
2371 if (!COM_CurrentApt())
2373 ERR("apartment not initialised\n");
2374 return CO_E_NOTINITIALIZED
;
2378 * The Standard Global Interface Table (GIT) object is a process-wide singleton.
2379 * Rather than create a class factory, we can just check for it here
2381 if (IsEqualIID(rclsid
, &CLSID_StdGlobalInterfaceTable
)) {
2382 if (StdGlobalInterfaceTableInstance
== NULL
)
2383 StdGlobalInterfaceTableInstance
= StdGlobalInterfaceTable_Construct();
2384 hres
= IGlobalInterfaceTable_QueryInterface( (IGlobalInterfaceTable
*) StdGlobalInterfaceTableInstance
, iid
, ppv
);
2385 if (hres
) return hres
;
2387 TRACE("Retrieved GIT (%p)\n", *ppv
);
2392 * Get a class factory to construct the object we want.
2394 hres
= CoGetClassObject(rclsid
,
2404 * Create the object and don't forget to release the factory
2406 hres
= IClassFactory_CreateInstance(lpclf
, pUnkOuter
, iid
, ppv
);
2407 IClassFactory_Release(lpclf
);
2410 if (hres
== CLASS_E_NOAGGREGATION
&& pUnkOuter
)
2411 FIXME("Class %s does not support aggregation\n", debugstr_guid(rclsid
));
2413 FIXME("no instance created for interface %s of class %s, hres is 0x%08x\n", debugstr_guid(iid
), debugstr_guid(rclsid
),hres
);
2419 /***********************************************************************
2420 * CoCreateInstanceEx [OLE32.@]
2422 HRESULT WINAPI
CoCreateInstanceEx(
2424 LPUNKNOWN pUnkOuter
,
2426 COSERVERINFO
* pServerInfo
,
2430 IUnknown
* pUnk
= NULL
;
2433 ULONG successCount
= 0;
2438 if ( (cmq
==0) || (pResults
==NULL
))
2439 return E_INVALIDARG
;
2441 if (pServerInfo
!=NULL
)
2442 FIXME("() non-NULL pServerInfo not supported!\n");
2445 * Initialize all the "out" parameters.
2447 for (index
= 0; index
< cmq
; index
++)
2449 pResults
[index
].pItf
= NULL
;
2450 pResults
[index
].hr
= E_NOINTERFACE
;
2454 * Get the object and get its IUnknown pointer.
2456 hr
= CoCreateInstance(rclsid
,
2466 * Then, query for all the interfaces requested.
2468 for (index
= 0; index
< cmq
; index
++)
2470 pResults
[index
].hr
= IUnknown_QueryInterface(pUnk
,
2471 pResults
[index
].pIID
,
2472 (VOID
**)&(pResults
[index
].pItf
));
2474 if (pResults
[index
].hr
== S_OK
)
2479 * Release our temporary unknown pointer.
2481 IUnknown_Release(pUnk
);
2483 if (successCount
== 0)
2484 return E_NOINTERFACE
;
2486 if (successCount
!=cmq
)
2487 return CO_S_NOTALLINTERFACES
;
2492 /***********************************************************************
2493 * CoLoadLibrary (OLE32.@)
2498 * lpszLibName [I] Path to library.
2499 * bAutoFree [I] Whether the library should automatically be freed.
2502 * Success: Handle to loaded library.
2506 * CoFreeLibrary, CoFreeAllLibraries, CoFreeUnusedLibraries
2508 HINSTANCE WINAPI
CoLoadLibrary(LPOLESTR lpszLibName
, BOOL bAutoFree
)
2510 TRACE("(%s, %d)\n", debugstr_w(lpszLibName
), bAutoFree
);
2512 return LoadLibraryExW(lpszLibName
, 0, LOAD_WITH_ALTERED_SEARCH_PATH
);
2515 /***********************************************************************
2516 * CoFreeLibrary [OLE32.@]
2518 * Unloads a library from memory.
2521 * hLibrary [I] Handle to library to unload.
2527 * CoLoadLibrary, CoFreeAllLibraries, CoFreeUnusedLibraries
2529 void WINAPI
CoFreeLibrary(HINSTANCE hLibrary
)
2531 FreeLibrary(hLibrary
);
2535 /***********************************************************************
2536 * CoFreeAllLibraries [OLE32.@]
2538 * Function for backwards compatibility only. Does nothing.
2544 * CoLoadLibrary, CoFreeLibrary, CoFreeUnusedLibraries
2546 void WINAPI
CoFreeAllLibraries(void)
2551 /***********************************************************************
2552 * CoFreeUnusedLibrariesEx [OLE32.@]
2554 * Frees any previously unused libraries whose delay has expired and marks
2555 * currently unused libraries for unloading. Unused are identified as those that
2556 * return S_OK from their DllCanUnloadNow function.
2559 * dwUnloadDelay [I] Unload delay in milliseconds.
2560 * dwReserved [I] Reserved. Set to 0.
2566 * CoLoadLibrary, CoFreeAllLibraries, CoFreeLibrary
2568 void WINAPI
CoFreeUnusedLibrariesEx(DWORD dwUnloadDelay
, DWORD dwReserved
)
2570 struct apartment
*apt
= COM_CurrentApt();
2573 ERR("apartment not initialised\n");
2577 apartment_freeunusedlibraries(apt
, dwUnloadDelay
);
2580 /***********************************************************************
2581 * CoFreeUnusedLibraries [OLE32.@]
2582 * CoFreeUnusedLibraries [COMPOBJ.17]
2584 * Frees any unused libraries. Unused are identified as those that return
2585 * S_OK from their DllCanUnloadNow function.
2591 * CoLoadLibrary, CoFreeAllLibraries, CoFreeLibrary
2593 void WINAPI
CoFreeUnusedLibraries(void)
2595 CoFreeUnusedLibrariesEx(INFINITE
, 0);
2598 /***********************************************************************
2599 * CoFileTimeNow [OLE32.@]
2600 * CoFileTimeNow [COMPOBJ.82]
2602 * Retrieves the current time in FILETIME format.
2605 * lpFileTime [O] The current time.
2610 HRESULT WINAPI
CoFileTimeNow( FILETIME
*lpFileTime
)
2612 GetSystemTimeAsFileTime( lpFileTime
);
2616 /******************************************************************************
2617 * CoLockObjectExternal [OLE32.@]
2619 * Increments or decrements the external reference count of a stub object.
2622 * pUnk [I] Stub object.
2623 * fLock [I] If TRUE then increments the external ref-count,
2624 * otherwise decrements.
2625 * fLastUnlockReleases [I] If TRUE then the last unlock has the effect of
2626 * calling CoDisconnectObject.
2630 * Failure: HRESULT code.
2633 * If fLock is TRUE and an object is passed in that doesn't have a stub
2634 * manager then a new stub manager is created for the object.
2636 HRESULT WINAPI
CoLockObjectExternal(
2639 BOOL fLastUnlockReleases
)
2641 struct stub_manager
*stubmgr
;
2642 struct apartment
*apt
;
2644 TRACE("pUnk=%p, fLock=%s, fLastUnlockReleases=%s\n",
2645 pUnk
, fLock
? "TRUE" : "FALSE", fLastUnlockReleases
? "TRUE" : "FALSE");
2647 apt
= COM_CurrentApt();
2648 if (!apt
) return CO_E_NOTINITIALIZED
;
2650 stubmgr
= get_stub_manager_from_object(apt
, pUnk
);
2655 stub_manager_ext_addref(stubmgr
, 1);
2657 stub_manager_ext_release(stubmgr
, 1, fLastUnlockReleases
);
2659 stub_manager_int_release(stubmgr
);
2665 stubmgr
= new_stub_manager(apt
, pUnk
);
2669 stub_manager_ext_addref(stubmgr
, 1);
2670 stub_manager_int_release(stubmgr
);
2677 WARN("stub object not found %p\n", pUnk
);
2678 /* Note: native is pretty broken here because it just silently
2679 * fails, without returning an appropriate error code, making apps
2680 * think that the object was disconnected, when it actually wasn't */
2685 /***********************************************************************
2686 * CoInitializeWOW (OLE32.@)
2688 * WOW equivalent of CoInitialize?
2697 HRESULT WINAPI
CoInitializeWOW(DWORD x
,DWORD y
)
2699 FIXME("(0x%08x,0x%08x),stub!\n",x
,y
);
2703 /***********************************************************************
2704 * CoGetState [OLE32.@]
2706 * Retrieves the thread state object previously stored by CoSetState().
2709 * ppv [I] Address where pointer to object will be stored.
2713 * Failure: E_OUTOFMEMORY.
2716 * Crashes on all invalid ppv addresses, including NULL.
2717 * If the function returns a non-NULL object then the caller must release its
2718 * reference on the object when the object is no longer required.
2723 HRESULT WINAPI
CoGetState(IUnknown
** ppv
)
2725 struct oletls
*info
= COM_CurrentInfo();
2726 if (!info
) return E_OUTOFMEMORY
;
2732 IUnknown_AddRef(info
->state
);
2734 TRACE("apt->state=%p\n", info
->state
);
2740 /***********************************************************************
2741 * CoSetState [OLE32.@]
2743 * Sets the thread state object.
2746 * pv [I] Pointer to state object to be stored.
2749 * The system keeps a reference on the object while the object stored.
2753 * Failure: E_OUTOFMEMORY.
2755 HRESULT WINAPI
CoSetState(IUnknown
* pv
)
2757 struct oletls
*info
= COM_CurrentInfo();
2758 if (!info
) return E_OUTOFMEMORY
;
2760 if (pv
) IUnknown_AddRef(pv
);
2764 TRACE("-- release %p now\n", info
->state
);
2765 IUnknown_Release(info
->state
);
2774 /******************************************************************************
2775 * CoTreatAsClass [OLE32.@]
2777 * Sets the TreatAs value of a class.
2780 * clsidOld [I] Class to set TreatAs value on.
2781 * clsidNew [I] The class the clsidOld should be treated as.
2785 * Failure: HRESULT code.
2790 HRESULT WINAPI
CoTreatAsClass(REFCLSID clsidOld
, REFCLSID clsidNew
)
2792 static const WCHAR wszAutoTreatAs
[] = {'A','u','t','o','T','r','e','a','t','A','s',0};
2793 static const WCHAR wszTreatAs
[] = {'T','r','e','a','t','A','s',0};
2795 WCHAR szClsidNew
[CHARS_IN_GUID
];
2797 WCHAR auto_treat_as
[CHARS_IN_GUID
];
2798 LONG auto_treat_as_size
= sizeof(auto_treat_as
);
2801 res
= COM_OpenKeyForCLSID(clsidOld
, NULL
, KEY_READ
| KEY_WRITE
, &hkey
);
2804 if (!memcmp( clsidOld
, clsidNew
, sizeof(*clsidOld
) ))
2806 if (!RegQueryValueW(hkey
, wszAutoTreatAs
, auto_treat_as
, &auto_treat_as_size
) &&
2807 !CLSIDFromString(auto_treat_as
, &id
))
2809 if (RegSetValueW(hkey
, wszTreatAs
, REG_SZ
, auto_treat_as
, sizeof(auto_treat_as
)))
2811 res
= REGDB_E_WRITEREGDB
;
2817 RegDeleteKeyW(hkey
, wszTreatAs
);
2821 else if (!StringFromGUID2(clsidNew
, szClsidNew
, ARRAYSIZE(szClsidNew
)) &&
2822 !RegSetValueW(hkey
, wszTreatAs
, REG_SZ
, szClsidNew
, sizeof(szClsidNew
)))
2824 res
= REGDB_E_WRITEREGDB
;
2829 if (hkey
) RegCloseKey(hkey
);
2833 /******************************************************************************
2834 * CoGetTreatAsClass [OLE32.@]
2836 * Gets the TreatAs value of a class.
2839 * clsidOld [I] Class to get the TreatAs value of.
2840 * clsidNew [I] The class the clsidOld should be treated as.
2844 * Failure: HRESULT code.
2849 HRESULT WINAPI
CoGetTreatAsClass(REFCLSID clsidOld
, LPCLSID clsidNew
)
2851 static const WCHAR wszTreatAs
[] = {'T','r','e','a','t','A','s',0};
2853 WCHAR szClsidNew
[CHARS_IN_GUID
];
2855 LONG len
= sizeof(szClsidNew
);
2857 FIXME("(%s,%p)\n", debugstr_guid(clsidOld
), clsidNew
);
2858 *clsidNew
= *clsidOld
; /* copy over old value */
2860 res
= COM_OpenKeyForCLSID(clsidOld
, wszTreatAs
, KEY_READ
, &hkey
);
2863 if (RegQueryValueW(hkey
, NULL
, szClsidNew
, &len
))
2868 res
= CLSIDFromString(szClsidNew
,clsidNew
);
2870 ERR("Failed CLSIDFromStringA(%s), hres 0x%08x\n", debugstr_w(szClsidNew
), res
);
2872 if (hkey
) RegCloseKey(hkey
);
2876 /******************************************************************************
2877 * CoGetCurrentProcess [OLE32.@]
2878 * CoGetCurrentProcess [COMPOBJ.34]
2880 * Gets the current process ID.
2883 * The current process ID.
2886 * Is DWORD really the correct return type for this function?
2888 DWORD WINAPI
CoGetCurrentProcess(void)
2890 return GetCurrentProcessId();
2893 /******************************************************************************
2894 * CoRegisterMessageFilter [OLE32.@]
2896 * Registers a message filter.
2899 * lpMessageFilter [I] Pointer to interface.
2900 * lplpMessageFilter [O] Indirect pointer to prior instance if non-NULL.
2904 * Failure: HRESULT code.
2907 * Both lpMessageFilter and lplpMessageFilter are optional. Passing in a NULL
2908 * lpMessageFilter removes the message filter.
2910 * If lplpMessageFilter is not NULL the previous message filter will be
2911 * returned in the memory pointer to this parameter and the caller is
2912 * responsible for releasing the object.
2914 * The current thread be in an apartment otherwise the function will crash.
2916 HRESULT WINAPI
CoRegisterMessageFilter(
2917 LPMESSAGEFILTER lpMessageFilter
,
2918 LPMESSAGEFILTER
*lplpMessageFilter
)
2920 struct apartment
*apt
;
2921 IMessageFilter
*lpOldMessageFilter
;
2923 TRACE("(%p, %p)\n", lpMessageFilter
, lplpMessageFilter
);
2925 apt
= COM_CurrentApt();
2927 /* can't set a message filter in a multi-threaded apartment */
2928 if (!apt
|| apt
->multi_threaded
)
2930 WARN("can't set message filter in MTA or uninitialized apt\n");
2931 return CO_E_NOT_SUPPORTED
;
2934 if (lpMessageFilter
)
2935 IMessageFilter_AddRef(lpMessageFilter
);
2937 EnterCriticalSection(&apt
->cs
);
2939 lpOldMessageFilter
= apt
->filter
;
2940 apt
->filter
= lpMessageFilter
;
2942 LeaveCriticalSection(&apt
->cs
);
2944 if (lplpMessageFilter
)
2945 *lplpMessageFilter
= lpOldMessageFilter
;
2946 else if (lpOldMessageFilter
)
2947 IMessageFilter_Release(lpOldMessageFilter
);
2952 /***********************************************************************
2953 * CoIsOle1Class [OLE32.@]
2955 * Determines whether the specified class an OLE v1 class.
2958 * clsid [I] Class to test.
2961 * TRUE if the class is an OLE v1 class, or FALSE otherwise.
2963 BOOL WINAPI
CoIsOle1Class(REFCLSID clsid
)
2965 FIXME("%s\n", debugstr_guid(clsid
));
2969 /***********************************************************************
2970 * IsEqualGUID [OLE32.@]
2972 * Compares two Unique Identifiers.
2975 * rguid1 [I] The first GUID to compare.
2976 * rguid2 [I] The other GUID to compare.
2982 BOOL WINAPI
IsEqualGUID(
2986 return !memcmp(rguid1
,rguid2
,sizeof(GUID
));
2989 /***********************************************************************
2990 * CoInitializeSecurity [OLE32.@]
2992 HRESULT WINAPI
CoInitializeSecurity(PSECURITY_DESCRIPTOR pSecDesc
, LONG cAuthSvc
,
2993 SOLE_AUTHENTICATION_SERVICE
* asAuthSvc
,
2994 void* pReserved1
, DWORD dwAuthnLevel
,
2995 DWORD dwImpLevel
, void* pReserved2
,
2996 DWORD dwCapabilities
, void* pReserved3
)
2998 FIXME("(%p,%d,%p,%p,%d,%d,%p,%d,%p) - stub!\n", pSecDesc
, cAuthSvc
,
2999 asAuthSvc
, pReserved1
, dwAuthnLevel
, dwImpLevel
, pReserved2
,
3000 dwCapabilities
, pReserved3
);
3004 /***********************************************************************
3005 * CoSuspendClassObjects [OLE32.@]
3007 * Suspends all registered class objects to prevent further requests coming in
3008 * for those objects.
3012 * Failure: HRESULT code.
3014 HRESULT WINAPI
CoSuspendClassObjects(void)
3020 /***********************************************************************
3021 * CoAddRefServerProcess [OLE32.@]
3023 * Helper function for incrementing the reference count of a local-server
3027 * New reference count.
3030 * CoReleaseServerProcess().
3032 ULONG WINAPI
CoAddRefServerProcess(void)
3038 EnterCriticalSection(&csRegisteredClassList
);
3039 refs
= ++s_COMServerProcessReferences
;
3040 LeaveCriticalSection(&csRegisteredClassList
);
3042 TRACE("refs before: %d\n", refs
- 1);
3047 /***********************************************************************
3048 * CoReleaseServerProcess [OLE32.@]
3050 * Helper function for decrementing the reference count of a local-server
3054 * New reference count.
3057 * When reference count reaches 0, this function suspends all registered
3058 * classes so no new connections are accepted.
3061 * CoAddRefServerProcess(), CoSuspendClassObjects().
3063 ULONG WINAPI
CoReleaseServerProcess(void)
3069 EnterCriticalSection(&csRegisteredClassList
);
3071 refs
= --s_COMServerProcessReferences
;
3072 /* FIXME: if (!refs) COM_SuspendClassObjects(); */
3074 LeaveCriticalSection(&csRegisteredClassList
);
3076 TRACE("refs after: %d\n", refs
);
3081 /***********************************************************************
3082 * CoIsHandlerConnected [OLE32.@]
3084 * Determines whether a proxy is connected to a remote stub.
3087 * pUnk [I] Pointer to object that may or may not be connected.
3090 * TRUE if pUnk is not a proxy or if pUnk is connected to a remote stub, or
3093 BOOL WINAPI
CoIsHandlerConnected(IUnknown
*pUnk
)
3095 FIXME("%p\n", pUnk
);
3100 /***********************************************************************
3101 * CoAllowSetForegroundWindow [OLE32.@]
3104 HRESULT WINAPI
CoAllowSetForegroundWindow(IUnknown
*pUnk
, void *pvReserved
)
3106 FIXME("(%p, %p): stub\n", pUnk
, pvReserved
);
3110 /***********************************************************************
3111 * CoQueryProxyBlanket [OLE32.@]
3113 * Retrieves the security settings being used by a proxy.
3116 * pProxy [I] Pointer to the proxy object.
3117 * pAuthnSvc [O] The type of authentication service.
3118 * pAuthzSvc [O] The type of authorization service.
3119 * ppServerPrincName [O] Optional. The server prinicple name.
3120 * pAuthnLevel [O] The authentication level.
3121 * pImpLevel [O] The impersonation level.
3122 * ppAuthInfo [O] Information specific to the authorization/authentication service.
3123 * pCapabilities [O] Flags affecting the security behaviour.
3127 * Failure: HRESULT code.
3130 * CoCopyProxy, CoSetProxyBlanket.
3132 HRESULT WINAPI
CoQueryProxyBlanket(IUnknown
*pProxy
, DWORD
*pAuthnSvc
,
3133 DWORD
*pAuthzSvc
, OLECHAR
**ppServerPrincName
, DWORD
*pAuthnLevel
,
3134 DWORD
*pImpLevel
, void **ppAuthInfo
, DWORD
*pCapabilities
)
3136 IClientSecurity
*pCliSec
;
3139 TRACE("%p\n", pProxy
);
3141 hr
= IUnknown_QueryInterface(pProxy
, &IID_IClientSecurity
, (void **)&pCliSec
);
3144 hr
= IClientSecurity_QueryBlanket(pCliSec
, pProxy
, pAuthnSvc
,
3145 pAuthzSvc
, ppServerPrincName
,
3146 pAuthnLevel
, pImpLevel
, ppAuthInfo
,
3148 IClientSecurity_Release(pCliSec
);
3151 if (FAILED(hr
)) ERR("-- failed with 0x%08x\n", hr
);
3155 /***********************************************************************
3156 * CoSetProxyBlanket [OLE32.@]
3158 * Sets the security settings for a proxy.
3161 * pProxy [I] Pointer to the proxy object.
3162 * AuthnSvc [I] The type of authentication service.
3163 * AuthzSvc [I] The type of authorization service.
3164 * pServerPrincName [I] The server prinicple name.
3165 * AuthnLevel [I] The authentication level.
3166 * ImpLevel [I] The impersonation level.
3167 * pAuthInfo [I] Information specific to the authorization/authentication service.
3168 * Capabilities [I] Flags affecting the security behaviour.
3172 * Failure: HRESULT code.
3175 * CoQueryProxyBlanket, CoCopyProxy.
3177 HRESULT WINAPI
CoSetProxyBlanket(IUnknown
*pProxy
, DWORD AuthnSvc
,
3178 DWORD AuthzSvc
, OLECHAR
*pServerPrincName
, DWORD AuthnLevel
,
3179 DWORD ImpLevel
, void *pAuthInfo
, DWORD Capabilities
)
3181 IClientSecurity
*pCliSec
;
3184 TRACE("%p\n", pProxy
);
3186 hr
= IUnknown_QueryInterface(pProxy
, &IID_IClientSecurity
, (void **)&pCliSec
);
3189 hr
= IClientSecurity_SetBlanket(pCliSec
, pProxy
, AuthnSvc
,
3190 AuthzSvc
, pServerPrincName
,
3191 AuthnLevel
, ImpLevel
, pAuthInfo
,
3193 IClientSecurity_Release(pCliSec
);
3196 if (FAILED(hr
)) ERR("-- failed with 0x%08x\n", hr
);
3200 /***********************************************************************
3201 * CoCopyProxy [OLE32.@]
3206 * pProxy [I] Pointer to the proxy object.
3207 * ppCopy [O] Copy of the proxy.
3211 * Failure: HRESULT code.
3214 * CoQueryProxyBlanket, CoSetProxyBlanket.
3216 HRESULT WINAPI
CoCopyProxy(IUnknown
*pProxy
, IUnknown
**ppCopy
)
3218 IClientSecurity
*pCliSec
;
3221 TRACE("%p\n", pProxy
);
3223 hr
= IUnknown_QueryInterface(pProxy
, &IID_IClientSecurity
, (void **)&pCliSec
);
3226 hr
= IClientSecurity_CopyProxy(pCliSec
, pProxy
, ppCopy
);
3227 IClientSecurity_Release(pCliSec
);
3230 if (FAILED(hr
)) ERR("-- failed with 0x%08x\n", hr
);
3235 /***********************************************************************
3236 * CoGetCallContext [OLE32.@]
3238 * Gets the context of the currently executing server call in the current
3242 * riid [I] Context interface to return.
3243 * ppv [O] Pointer to memory that will receive the context on return.
3247 * Failure: HRESULT code.
3249 HRESULT WINAPI
CoGetCallContext(REFIID riid
, void **ppv
)
3251 FIXME("(%s, %p): stub\n", debugstr_guid(riid
), ppv
);
3254 return E_NOINTERFACE
;
3257 /***********************************************************************
3258 * CoQueryClientBlanket [OLE32.@]
3260 * Retrieves the authentication information about the client of the currently
3261 * executing server call in the current thread.
3264 * pAuthnSvc [O] Optional. The type of authentication service.
3265 * pAuthzSvc [O] Optional. The type of authorization service.
3266 * pServerPrincName [O] Optional. The server prinicple name.
3267 * pAuthnLevel [O] Optional. The authentication level.
3268 * pImpLevel [O] Optional. The impersonation level.
3269 * pPrivs [O] Optional. Information about the privileges of the client.
3270 * pCapabilities [IO] Optional. Flags affecting the security behaviour.
3274 * Failure: HRESULT code.
3277 * CoImpersonateClient, CoRevertToSelf, CoGetCallContext.
3279 HRESULT WINAPI
CoQueryClientBlanket(
3282 OLECHAR
**pServerPrincName
,
3285 RPC_AUTHZ_HANDLE
*pPrivs
,
3286 DWORD
*pCapabilities
)
3288 IServerSecurity
*pSrvSec
;
3291 TRACE("(%p, %p, %p, %p, %p, %p, %p)\n",
3292 pAuthnSvc
, pAuthzSvc
, pServerPrincName
, pAuthnLevel
, pImpLevel
,
3293 pPrivs
, pCapabilities
);
3295 hr
= CoGetCallContext(&IID_IServerSecurity
, (void **)&pSrvSec
);
3298 hr
= IServerSecurity_QueryBlanket(
3299 pSrvSec
, pAuthnSvc
, pAuthzSvc
, pServerPrincName
, pAuthnLevel
,
3300 pImpLevel
, pPrivs
, pCapabilities
);
3301 IServerSecurity_Release(pSrvSec
);
3307 /***********************************************************************
3308 * CoImpersonateClient [OLE32.@]
3310 * Impersonates the client of the currently executing server call in the
3318 * Failure: HRESULT code.
3321 * If this function fails then the current thread will not be impersonating
3322 * the client and all actions will take place on behalf of the server.
3323 * Therefore, it is important to check the return value from this function.
3326 * CoRevertToSelf, CoQueryClientBlanket, CoGetCallContext.
3328 HRESULT WINAPI
CoImpersonateClient(void)
3330 IServerSecurity
*pSrvSec
;
3335 hr
= CoGetCallContext(&IID_IServerSecurity
, (void **)&pSrvSec
);
3338 hr
= IServerSecurity_ImpersonateClient(pSrvSec
);
3339 IServerSecurity_Release(pSrvSec
);
3345 /***********************************************************************
3346 * CoRevertToSelf [OLE32.@]
3348 * Ends the impersonation of the client of the currently executing server
3349 * call in the current thread.
3356 * Failure: HRESULT code.
3359 * CoImpersonateClient, CoQueryClientBlanket, CoGetCallContext.
3361 HRESULT WINAPI
CoRevertToSelf(void)
3363 IServerSecurity
*pSrvSec
;
3368 hr
= CoGetCallContext(&IID_IServerSecurity
, (void **)&pSrvSec
);
3371 hr
= IServerSecurity_RevertToSelf(pSrvSec
);
3372 IServerSecurity_Release(pSrvSec
);
3378 static BOOL
COM_PeekMessage(struct apartment
*apt
, MSG
*msg
)
3380 /* first try to retrieve messages for incoming COM calls to the apartment window */
3381 return PeekMessageW(msg
, apt
->win
, WM_USER
, WM_APP
- 1, PM_REMOVE
|PM_NOYIELD
) ||
3382 /* next retrieve other messages necessary for the app to remain responsive */
3383 PeekMessageW(msg
, NULL
, 0, 0, PM_QS_PAINT
|PM_QS_POSTMESSAGE
|PM_REMOVE
|PM_NOYIELD
);
3386 /***********************************************************************
3387 * CoWaitForMultipleHandles [OLE32.@]
3389 * Waits for one or more handles to become signaled.
3392 * dwFlags [I] Flags. See notes.
3393 * dwTimeout [I] Timeout in milliseconds.
3394 * cHandles [I] Number of handles pointed to by pHandles.
3395 * pHandles [I] Handles to wait for.
3396 * lpdwindex [O] Index of handle that was signaled.
3400 * Failure: RPC_S_CALLPENDING on timeout.
3404 * The dwFlags parameter can be zero or more of the following:
3405 *| COWAIT_WAITALL - Wait for all of the handles to become signaled.
3406 *| COWAIT_ALERTABLE - Allows a queued APC to run during the wait.
3409 * MsgWaitForMultipleObjects, WaitForMultipleObjects.
3411 HRESULT WINAPI
CoWaitForMultipleHandles(DWORD dwFlags
, DWORD dwTimeout
,
3412 ULONG cHandles
, LPHANDLE pHandles
, LPDWORD lpdwindex
)
3415 DWORD start_time
= GetTickCount();
3416 APARTMENT
*apt
= COM_CurrentApt();
3417 BOOL message_loop
= apt
&& !apt
->multi_threaded
;
3419 TRACE("(0x%08x, 0x%08x, %d, %p, %p)\n", dwFlags
, dwTimeout
, cHandles
,
3420 pHandles
, lpdwindex
);
3424 DWORD now
= GetTickCount();
3427 if (now
- start_time
> dwTimeout
)
3429 hr
= RPC_S_CALLPENDING
;
3435 DWORD wait_flags
= ((dwFlags
& COWAIT_WAITALL
) ? MWMO_WAITALL
: 0) |
3436 ((dwFlags
& COWAIT_ALERTABLE
) ? MWMO_ALERTABLE
: 0);
3438 TRACE("waiting for rpc completion or window message\n");
3440 res
= MsgWaitForMultipleObjectsEx(cHandles
, pHandles
,
3441 (dwTimeout
== INFINITE
) ? INFINITE
: start_time
+ dwTimeout
- now
,
3442 QS_ALLINPUT
, wait_flags
);
3444 if (res
== WAIT_OBJECT_0
+ cHandles
) /* messages available */
3448 /* call message filter */
3450 if (COM_CurrentApt()->filter
)
3452 PENDINGTYPE pendingtype
=
3453 COM_CurrentInfo()->pending_call_count_server
?
3454 PENDINGTYPE_NESTED
: PENDINGTYPE_TOPLEVEL
;
3455 DWORD be_handled
= IMessageFilter_MessagePending(
3456 COM_CurrentApt()->filter
, 0 /* FIXME */,
3457 now
- start_time
, pendingtype
);
3458 TRACE("IMessageFilter_MessagePending returned %d\n", be_handled
);
3461 case PENDINGMSG_CANCELCALL
:
3462 WARN("call canceled\n");
3463 hr
= RPC_E_CALL_CANCELED
;
3465 case PENDINGMSG_WAITNOPROCESS
:
3466 case PENDINGMSG_WAITDEFPROCESS
:
3468 /* FIXME: MSDN is very vague about the difference
3469 * between WAITNOPROCESS and WAITDEFPROCESS - there
3470 * appears to be none, so it is possibly a left-over
3471 * from the 16-bit world. */
3476 /* note: using "if" here instead of "while" might seem less
3477 * efficient, but only if we are optimising for quick delivery
3478 * of pending messages, rather than quick completion of the
3480 if (COM_PeekMessage(apt
, &msg
))
3482 TRACE("received message whilst waiting for RPC: 0x%04x\n", msg
.message
);
3483 TranslateMessage(&msg
);
3484 DispatchMessageW(&msg
);
3485 if (msg
.message
== WM_QUIT
)
3487 TRACE("resending WM_QUIT to outer message loop\n");
3488 PostQuitMessage(msg
.wParam
);
3489 /* no longer need to process messages */
3490 message_loop
= FALSE
;
3498 TRACE("waiting for rpc completion\n");
3500 res
= WaitForMultipleObjectsEx(cHandles
, pHandles
,
3501 (dwFlags
& COWAIT_WAITALL
) ? TRUE
: FALSE
,
3502 (dwTimeout
== INFINITE
) ? INFINITE
: start_time
+ dwTimeout
- now
,
3503 (dwFlags
& COWAIT_ALERTABLE
) ? TRUE
: FALSE
);
3506 if (res
< WAIT_OBJECT_0
+ cHandles
)
3508 /* handle signaled, store index */
3509 *lpdwindex
= (res
- WAIT_OBJECT_0
);
3512 else if (res
== WAIT_TIMEOUT
)
3514 hr
= RPC_S_CALLPENDING
;
3519 ERR("Unexpected wait termination: %d, %d\n", res
, GetLastError());
3524 TRACE("-- 0x%08x\n", hr
);
3529 /***********************************************************************
3530 * CoGetObject [OLE32.@]
3532 * Gets the object named by converting the name to a moniker and binding to it.
3535 * pszName [I] String representing the object.
3536 * pBindOptions [I] Parameters affecting the binding to the named object.
3537 * riid [I] Interface to bind to on the objecct.
3538 * ppv [O] On output, the interface riid of the object represented
3543 * Failure: HRESULT code.
3546 * MkParseDisplayName.
3548 HRESULT WINAPI
CoGetObject(LPCWSTR pszName
, BIND_OPTS
*pBindOptions
,
3549 REFIID riid
, void **ppv
)
3556 hr
= CreateBindCtx(0, &pbc
);
3560 hr
= IBindCtx_SetBindOptions(pbc
, pBindOptions
);
3567 hr
= MkParseDisplayName(pbc
, pszName
, &chEaten
, &pmk
);
3570 hr
= IMoniker_BindToObject(pmk
, pbc
, NULL
, riid
, ppv
);
3571 IMoniker_Release(pmk
);
3575 IBindCtx_Release(pbc
);
3580 /***********************************************************************
3581 * CoRegisterChannelHook [OLE32.@]
3583 * Registers a process-wide hook that is called during ORPC calls.
3586 * guidExtension [I] GUID of the channel hook to register.
3587 * pChannelHook [I] Channel hook object to register.
3591 * Failure: HRESULT code.
3593 HRESULT WINAPI
CoRegisterChannelHook(REFGUID guidExtension
, IChannelHook
*pChannelHook
)
3595 TRACE("(%s, %p)\n", debugstr_guid(guidExtension
), pChannelHook
);
3597 return RPC_RegisterChannelHook(guidExtension
, pChannelHook
);
3600 typedef struct Context
3602 const IComThreadingInfoVtbl
*lpVtbl
;
3607 static HRESULT WINAPI
Context_QueryInterface(IComThreadingInfo
*iface
, REFIID riid
, LPVOID
*ppv
)
3611 if (IsEqualIID(riid
, &IID_IComThreadingInfo
) ||
3612 IsEqualIID(riid
, &IID_IUnknown
))
3615 IUnknown_AddRef(iface
);
3619 FIXME("interface not implemented %s\n", debugstr_guid(riid
));
3620 return E_NOINTERFACE
;
3623 static ULONG WINAPI
Context_AddRef(IComThreadingInfo
*iface
)
3625 Context
*This
= (Context
*)iface
;
3626 return InterlockedIncrement(&This
->refs
);
3629 static ULONG WINAPI
Context_Release(IComThreadingInfo
*iface
)
3631 Context
*This
= (Context
*)iface
;
3632 ULONG refs
= InterlockedDecrement(&This
->refs
);
3634 HeapFree(GetProcessHeap(), 0, This
);
3638 static HRESULT WINAPI
Context_GetCurrentApartmentType(IComThreadingInfo
*iface
, APTTYPE
*apttype
)
3640 Context
*This
= (Context
*)iface
;
3642 TRACE("(%p)\n", apttype
);
3644 *apttype
= This
->apttype
;
3648 static HRESULT WINAPI
Context_GetCurrentThreadType(IComThreadingInfo
*iface
, THDTYPE
*thdtype
)
3650 Context
*This
= (Context
*)iface
;
3652 TRACE("(%p)\n", thdtype
);
3654 switch (This
->apttype
)
3657 case APTTYPE_MAINSTA
:
3658 *thdtype
= THDTYPE_PROCESSMESSAGES
;
3661 *thdtype
= THDTYPE_BLOCKMESSAGES
;
3667 static HRESULT WINAPI
Context_GetCurrentLogicalThreadId(IComThreadingInfo
*iface
, GUID
*logical_thread_id
)
3669 FIXME("(%p): stub\n", logical_thread_id
);
3673 static HRESULT WINAPI
Context_SetCurrentLogicalThreadId(IComThreadingInfo
*iface
, REFGUID logical_thread_id
)
3675 FIXME("(%s): stub\n", debugstr_guid(logical_thread_id
));
3679 static const IComThreadingInfoVtbl Context_Threading_Vtbl
=
3681 Context_QueryInterface
,
3684 Context_GetCurrentApartmentType
,
3685 Context_GetCurrentThreadType
,
3686 Context_GetCurrentLogicalThreadId
,
3687 Context_SetCurrentLogicalThreadId
3690 /***********************************************************************
3691 * CoGetObjectContext [OLE32.@]
3693 * Retrieves an object associated with the current context (i.e. apartment).
3696 * riid [I] ID of the interface of the object to retrieve.
3697 * ppv [O] Address where object will be stored on return.
3701 * Failure: HRESULT code.
3703 HRESULT WINAPI
CoGetObjectContext(REFIID riid
, void **ppv
)
3705 APARTMENT
*apt
= COM_CurrentApt();
3709 TRACE("(%s, %p)\n", debugstr_guid(riid
), ppv
);
3714 ERR("apartment not initialised\n");
3715 return CO_E_NOTINITIALIZED
;
3718 context
= HeapAlloc(GetProcessHeap(), 0, sizeof(*context
));
3720 return E_OUTOFMEMORY
;
3722 context
->lpVtbl
= &Context_Threading_Vtbl
;
3724 if (apt
->multi_threaded
)
3725 context
->apttype
= APTTYPE_MTA
;
3727 context
->apttype
= APTTYPE_MAINSTA
;
3729 context
->apttype
= APTTYPE_STA
;
3731 hr
= IUnknown_QueryInterface((IUnknown
*)&context
->lpVtbl
, riid
, ppv
);
3732 IUnknown_Release((IUnknown
*)&context
->lpVtbl
);
3738 /***********************************************************************
3739 * CoGetContextToken [OLE32.@]
3741 HRESULT WINAPI
CoGetContextToken( ULONG_PTR
*token
)
3744 if (token
) *token
= 0;
3749 /***********************************************************************
3752 BOOL WINAPI
DllMain(HINSTANCE hinstDLL
, DWORD fdwReason
, LPVOID fImpLoad
)
3754 TRACE("%p 0x%x %p\n", hinstDLL
, fdwReason
, fImpLoad
);
3757 case DLL_PROCESS_ATTACH
:
3758 OLE32_hInstance
= hinstDLL
;
3759 COMPOBJ_InitProcess();
3760 if (TRACE_ON(ole
)) CoRegisterMallocSpy((LPVOID
)-1);
3763 case DLL_PROCESS_DETACH
:
3764 if (TRACE_ON(ole
)) CoRevokeMallocSpy();
3765 OLEDD_UnInitialize();
3766 COMPOBJ_UninitProcess();
3767 RPC_UnregisterAllChannelHooks();
3768 COMPOBJ_DllList_Free();
3769 OLE32_hInstance
= 0;
3772 case DLL_THREAD_DETACH
:
3779 /* NOTE: DllRegisterServer and DllUnregisterServer are in regsvr.c */