4 * Copyright 1995 Martin von Loewis
5 * Copyright 1998 Justin Bradford
6 * Copyright 1999 Francis Beaudet
7 * Copyright 1999 Sylvain St-Germain
8 * Copyright 2002 Marcus Meissner
9 * Copyright 2004 Mike Hearn
10 * Copyright 2005-2006 Robert Shearman (for CodeWeavers)
12 * This library is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Lesser General Public
14 * License as published by the Free Software Foundation; either
15 * version 2.1 of the License, or (at your option) any later version.
17 * This library is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * Lesser General Public License for more details.
22 * You should have received a copy of the GNU Lesser General Public
23 * License along with this library; if not, write to the Free Software
24 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
27 * 1. COINIT_MULTITHREADED is 0; it is the lack of COINIT_APARTMENTTHREADED
28 * Therefore do not test against COINIT_MULTITHREADED
30 * TODO list: (items bunched together depend on each other)
32 * - Implement the service control manager (in rpcss) to keep track
33 * of registered class objects: ISCM::ServerRegisterClsid et al
34 * - Implement the OXID resolver so we don't need magic endpoint names for
35 * clients and servers to meet up
47 #define NONAMELESSUNION
48 #define NONAMELESSSTRUCT
60 #include "compobj_private.h"
62 #include "wine/unicode.h"
63 #include "wine/debug.h"
65 WINE_DEFAULT_DEBUG_CHANNEL(ole
);
67 #define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))
69 /****************************************************************************
70 * This section defines variables internal to the COM module.
73 static HRESULT
COM_GetRegisteredClassObject(const struct apartment
*apt
, REFCLSID rclsid
,
74 DWORD dwClsContext
, LPUNKNOWN
* ppUnk
);
75 static void COM_RevokeAllClasses(const struct apartment
*apt
);
76 static HRESULT
get_inproc_class_object(APARTMENT
*apt
, HKEY hkeydll
, REFCLSID rclsid
, REFIID riid
, BOOL hostifnecessary
, void **ppv
);
78 static APARTMENT
*MTA
; /* protected by csApartment */
79 static APARTMENT
*MainApartment
; /* the first STA apartment */
80 static struct list apts
= LIST_INIT( apts
); /* protected by csApartment */
82 static CRITICAL_SECTION csApartment
;
83 static CRITICAL_SECTION_DEBUG critsect_debug
=
86 { &critsect_debug
.ProcessLocksList
, &critsect_debug
.ProcessLocksList
},
87 0, 0, { (DWORD_PTR
)(__FILE__
": csApartment") }
89 static CRITICAL_SECTION csApartment
= { &critsect_debug
, -1, 0, 0, 0, 0 };
91 struct registered_psclsid
99 * This lock count counts the number of times CoInitialize is called. It is
100 * decreased every time CoUninitialize is called. When it hits 0, the COM
101 * libraries are freed
103 static LONG s_COMLockCount
= 0;
104 /* Reference count used by CoAddRefServerProcess/CoReleaseServerProcess */
105 static LONG s_COMServerProcessReferences
= 0;
108 * This linked list contains the list of registered class objects. These
109 * are mostly used to register the factories for out-of-proc servers of OLE
112 * TODO: Make this data structure aware of inter-process communication. This
113 * means that parts of this will be exported to rpcss.
115 typedef struct tagRegisteredClass
118 CLSID classIdentifier
;
120 LPUNKNOWN classObject
;
124 LPSTREAM pMarshaledData
; /* FIXME: only really need to store OXID and IPID */
125 void *RpcRegistration
;
128 static struct list RegisteredClassList
= LIST_INIT(RegisteredClassList
);
130 static CRITICAL_SECTION csRegisteredClassList
;
131 static CRITICAL_SECTION_DEBUG class_cs_debug
=
133 0, 0, &csRegisteredClassList
,
134 { &class_cs_debug
.ProcessLocksList
, &class_cs_debug
.ProcessLocksList
},
135 0, 0, { (DWORD_PTR
)(__FILE__
": csRegisteredClassList") }
137 static CRITICAL_SECTION csRegisteredClassList
= { &class_cs_debug
, -1, 0, 0, 0, 0 };
139 /*****************************************************************************
140 * This section contains OpenDllList definitions
142 * The OpenDllList contains only handles of dll loaded by CoGetClassObject or
143 * other functions that do LoadLibrary _without_ giving back a HMODULE.
144 * Without this list these handles would never be freed.
146 * FIXME: a DLL that says OK when asked for unloading is unloaded in the
147 * next unload-call but not before 600 sec.
150 typedef HRESULT (CALLBACK
*DllGetClassObjectFunc
)(REFCLSID clsid
, REFIID iid
, LPVOID
*ppv
);
151 typedef HRESULT (WINAPI
*DllCanUnloadNowFunc
)(void);
153 typedef struct tagOpenDll
158 DllGetClassObjectFunc DllGetClassObject
;
159 DllCanUnloadNowFunc DllCanUnloadNow
;
163 static struct list openDllList
= LIST_INIT(openDllList
);
165 static CRITICAL_SECTION csOpenDllList
;
166 static CRITICAL_SECTION_DEBUG dll_cs_debug
=
168 0, 0, &csOpenDllList
,
169 { &dll_cs_debug
.ProcessLocksList
, &dll_cs_debug
.ProcessLocksList
},
170 0, 0, { (DWORD_PTR
)(__FILE__
": csOpenDllList") }
172 static CRITICAL_SECTION csOpenDllList
= { &dll_cs_debug
, -1, 0, 0, 0, 0 };
174 struct apartment_loaded_dll
182 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',' ',
183 '0','x','#','#','#','#','#','#','#','#',' ',0};
184 static LRESULT CALLBACK
apartment_wndproc(HWND hWnd
, UINT msg
, WPARAM wParam
, LPARAM lParam
);
185 static HRESULT
apartment_getclassobject(struct apartment
*apt
, LPCWSTR dllpath
,
186 BOOL apartment_threaded
,
187 REFCLSID rclsid
, REFIID riid
, void **ppv
);
188 static void apartment_freeunusedlibraries(struct apartment
*apt
, DWORD delay
);
190 static HRESULT
COMPOBJ_DllList_Add(LPCWSTR library_name
, OpenDll
**ret
);
191 static OpenDll
*COMPOBJ_DllList_Get(LPCWSTR library_name
);
192 static void COMPOBJ_DllList_ReleaseRef(OpenDll
*entry
, BOOL free_entry
);
194 static DWORD
COM_RegReadPath(HKEY hkeyroot
, const WCHAR
*keyname
, const WCHAR
*valuename
, WCHAR
* dst
, DWORD dstlen
);
196 static void COMPOBJ_InitProcess( void )
200 /* Dispatching to the correct thread in an apartment is done through
201 * window messages rather than RPC transports. When an interface is
202 * marshalled into another apartment in the same process, a window of the
203 * following class is created. The *caller* of CoMarshalInterface (i.e., the
204 * application) is responsible for pumping the message loop in that thread.
205 * The WM_USER messages which point to the RPCs are then dispatched to
206 * apartment_wndproc by the user's code from the apartment in which the
207 * interface was unmarshalled.
209 memset(&wclass
, 0, sizeof(wclass
));
210 wclass
.lpfnWndProc
= apartment_wndproc
;
211 wclass
.hInstance
= hProxyDll
;
212 wclass
.lpszClassName
= wszAptWinClass
;
213 RegisterClassW(&wclass
);
216 static void COMPOBJ_UninitProcess( void )
218 UnregisterClassW(wszAptWinClass
, hProxyDll
);
221 static void COM_TlsDestroy(void)
223 struct oletls
*info
= NtCurrentTeb()->ReservedForOle
;
226 if (info
->apt
) apartment_release(info
->apt
);
227 if (info
->errorinfo
) IErrorInfo_Release(info
->errorinfo
);
228 if (info
->state
) IUnknown_Release(info
->state
);
229 if (info
->spy
) IUnknown_Release(info
->spy
);
230 HeapFree(GetProcessHeap(), 0, info
);
231 NtCurrentTeb()->ReservedForOle
= NULL
;
235 /******************************************************************************
239 /* allocates memory and fills in the necessary fields for a new apartment
240 * object. must be called inside apartment cs */
241 static APARTMENT
*apartment_construct(DWORD model
)
245 TRACE("creating new apartment, model=%d\n", model
);
247 apt
= HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY
, sizeof(*apt
));
248 apt
->tid
= GetCurrentThreadId();
250 list_init(&apt
->proxies
);
251 list_init(&apt
->stubmgrs
);
252 list_init(&apt
->psclsids
);
253 list_init(&apt
->loaded_dlls
);
256 apt
->remunk_exported
= FALSE
;
258 InitializeCriticalSection(&apt
->cs
);
259 DEBUG_SET_CRITSEC_NAME(&apt
->cs
, "apartment");
261 apt
->multi_threaded
= !(model
& COINIT_APARTMENTTHREADED
);
263 if (apt
->multi_threaded
)
265 /* FIXME: should be randomly generated by in an RPC call to rpcss */
266 apt
->oxid
= ((OXID
)GetCurrentProcessId() << 32) | 0xcafe;
270 /* FIXME: should be randomly generated by in an RPC call to rpcss */
271 apt
->oxid
= ((OXID
)GetCurrentProcessId() << 32) | GetCurrentThreadId();
274 TRACE("Created apartment on OXID %s\n", wine_dbgstr_longlong(apt
->oxid
));
276 list_add_head(&apts
, &apt
->entry
);
281 /* gets and existing apartment if one exists or otherwise creates an apartment
282 * structure which stores OLE apartment-local information and stores a pointer
283 * to it in the thread-local storage */
284 static APARTMENT
*apartment_get_or_create(DWORD model
)
286 APARTMENT
*apt
= COM_CurrentApt();
290 if (model
& COINIT_APARTMENTTHREADED
)
292 EnterCriticalSection(&csApartment
);
294 apt
= apartment_construct(model
);
299 TRACE("Created main-threaded apartment with OXID %s\n", wine_dbgstr_longlong(apt
->oxid
));
302 LeaveCriticalSection(&csApartment
);
305 apartment_createwindowifneeded(apt
);
309 EnterCriticalSection(&csApartment
);
311 /* The multi-threaded apartment (MTA) contains zero or more threads interacting
312 * with free threaded (ie thread safe) COM objects. There is only ever one MTA
316 TRACE("entering the multithreaded apartment %s\n", wine_dbgstr_longlong(MTA
->oxid
));
317 apartment_addref(MTA
);
320 MTA
= apartment_construct(model
);
324 LeaveCriticalSection(&csApartment
);
326 COM_CurrentInfo()->apt
= apt
;
332 static inline BOOL
apartment_is_model(const APARTMENT
*apt
, DWORD model
)
334 return (apt
->multi_threaded
== !(model
& COINIT_APARTMENTTHREADED
));
337 DWORD
apartment_addref(struct apartment
*apt
)
339 DWORD refs
= InterlockedIncrement(&apt
->refs
);
340 TRACE("%s: before = %d\n", wine_dbgstr_longlong(apt
->oxid
), refs
- 1);
344 DWORD
apartment_release(struct apartment
*apt
)
348 EnterCriticalSection(&csApartment
);
350 ret
= InterlockedDecrement(&apt
->refs
);
351 TRACE("%s: after = %d\n", wine_dbgstr_longlong(apt
->oxid
), ret
);
352 /* destruction stuff that needs to happen under csApartment CS */
355 if (apt
== MTA
) MTA
= NULL
;
356 else if (apt
== MainApartment
) MainApartment
= NULL
;
357 list_remove(&apt
->entry
);
360 LeaveCriticalSection(&csApartment
);
364 struct list
*cursor
, *cursor2
;
366 TRACE("destroying apartment %p, oxid %s\n", apt
, wine_dbgstr_longlong(apt
->oxid
));
368 /* Release the references to the registered class objects */
369 COM_RevokeAllClasses(apt
);
371 /* no locking is needed for this apartment, because no other thread
372 * can access it at this point */
374 apartment_disconnectproxies(apt
);
376 if (apt
->win
) DestroyWindow(apt
->win
);
377 if (apt
->host_apt_tid
) PostThreadMessageW(apt
->host_apt_tid
, WM_QUIT
, 0, 0);
379 LIST_FOR_EACH_SAFE(cursor
, cursor2
, &apt
->stubmgrs
)
381 struct stub_manager
*stubmgr
= LIST_ENTRY(cursor
, struct stub_manager
, entry
);
382 /* release the implicit reference given by the fact that the
383 * stub has external references (it must do since it is in the
384 * stub manager list in the apartment and all non-apartment users
385 * must have a ref on the apartment and so it cannot be destroyed).
387 stub_manager_int_release(stubmgr
);
390 LIST_FOR_EACH_SAFE(cursor
, cursor2
, &apt
->psclsids
)
392 struct registered_psclsid
*registered_psclsid
=
393 LIST_ENTRY(cursor
, struct registered_psclsid
, entry
);
395 list_remove(®istered_psclsid
->entry
);
396 HeapFree(GetProcessHeap(), 0, registered_psclsid
);
399 /* if this assert fires, then another thread took a reference to a
400 * stub manager without taking a reference to the containing
401 * apartment, which it must do. */
402 assert(list_empty(&apt
->stubmgrs
));
404 if (apt
->filter
) IUnknown_Release(apt
->filter
);
406 /* free as many unused libraries as possible... */
407 apartment_freeunusedlibraries(apt
, 0);
409 /* ... and free the memory for the apartment loaded dll entry and
410 * release the dll list reference without freeing the library for the
412 while ((cursor
= list_head(&apt
->loaded_dlls
)))
414 struct apartment_loaded_dll
*apartment_loaded_dll
= LIST_ENTRY(cursor
, struct apartment_loaded_dll
, entry
);
415 COMPOBJ_DllList_ReleaseRef(apartment_loaded_dll
->dll
, FALSE
);
417 HeapFree(GetProcessHeap(), 0, apartment_loaded_dll
);
420 DEBUG_CLEAR_CRITSEC_NAME(&apt
->cs
);
421 DeleteCriticalSection(&apt
->cs
);
423 HeapFree(GetProcessHeap(), 0, apt
);
429 /* The given OXID must be local to this process:
431 * The ref parameter is here mostly to ensure people remember that
432 * they get one, you should normally take a ref for thread safety.
434 APARTMENT
*apartment_findfromoxid(OXID oxid
, BOOL ref
)
436 APARTMENT
*result
= NULL
;
439 EnterCriticalSection(&csApartment
);
440 LIST_FOR_EACH( cursor
, &apts
)
442 struct apartment
*apt
= LIST_ENTRY( cursor
, struct apartment
, entry
);
443 if (apt
->oxid
== oxid
)
446 if (ref
) apartment_addref(result
);
450 LeaveCriticalSection(&csApartment
);
455 /* gets the apartment which has a given creator thread ID. The caller must
456 * release the reference from the apartment as soon as the apartment pointer
457 * is no longer required. */
458 APARTMENT
*apartment_findfromtid(DWORD tid
)
460 APARTMENT
*result
= NULL
;
463 EnterCriticalSection(&csApartment
);
464 LIST_FOR_EACH( cursor
, &apts
)
466 struct apartment
*apt
= LIST_ENTRY( cursor
, struct apartment
, entry
);
470 apartment_addref(result
);
474 LeaveCriticalSection(&csApartment
);
479 /* gets the main apartment if it exists. The caller must
480 * release the reference from the apartment as soon as the apartment pointer
481 * is no longer required. */
482 static APARTMENT
*apartment_findmain(void)
486 EnterCriticalSection(&csApartment
);
488 result
= MainApartment
;
489 if (result
) apartment_addref(result
);
491 LeaveCriticalSection(&csApartment
);
496 struct host_object_params
499 CLSID clsid
; /* clsid of object to marshal */
500 IID iid
; /* interface to marshal */
501 HANDLE event
; /* event signalling when ready for multi-threaded case */
502 HRESULT hr
; /* result for multi-threaded case */
503 IStream
*stream
; /* stream that the object will be marshaled into */
504 BOOL apartment_threaded
; /* is the component purely apartment-threaded? */
507 static HRESULT
apartment_hostobject(struct apartment
*apt
,
508 const struct host_object_params
*params
)
512 static const LARGE_INTEGER llZero
;
513 WCHAR dllpath
[MAX_PATH
+1];
515 TRACE("clsid %s, iid %s\n", debugstr_guid(¶ms
->clsid
), debugstr_guid(¶ms
->iid
));
517 if (COM_RegReadPath(params
->hkeydll
, NULL
, NULL
, dllpath
, ARRAYSIZE(dllpath
)) != ERROR_SUCCESS
)
519 /* failure: CLSID is not found in registry */
520 WARN("class %s not registered inproc\n", debugstr_guid(¶ms
->clsid
));
521 return REGDB_E_CLASSNOTREG
;
524 hr
= apartment_getclassobject(apt
, dllpath
, params
->apartment_threaded
,
525 ¶ms
->clsid
, ¶ms
->iid
, (void **)&object
);
529 hr
= CoMarshalInterface(params
->stream
, ¶ms
->iid
, object
, MSHCTX_INPROC
, NULL
, MSHLFLAGS_NORMAL
);
531 IUnknown_Release(object
);
532 IStream_Seek(params
->stream
, llZero
, STREAM_SEEK_SET
, NULL
);
537 static LRESULT CALLBACK
apartment_wndproc(HWND hWnd
, UINT msg
, WPARAM wParam
, LPARAM lParam
)
542 RPC_ExecuteCall((struct dispatch_params
*)lParam
);
545 return apartment_hostobject(COM_CurrentApt(), (const struct host_object_params
*)lParam
);
547 return DefWindowProcW(hWnd
, msg
, wParam
, lParam
);
551 struct host_thread_params
553 COINIT threading_model
;
558 /* thread for hosting an object to allow an object to appear to be created in
559 * an apartment with an incompatible threading model */
560 static DWORD CALLBACK
apartment_hostobject_thread(LPVOID p
)
562 struct host_thread_params
*params
= p
;
565 struct apartment
*apt
;
569 hr
= CoInitializeEx(NULL
, params
->threading_model
);
570 if (FAILED(hr
)) return hr
;
572 apt
= COM_CurrentApt();
573 if (params
->threading_model
== COINIT_APARTMENTTHREADED
)
575 apartment_createwindowifneeded(apt
);
576 params
->apartment_hwnd
= apartment_getwindow(apt
);
579 params
->apartment_hwnd
= NULL
;
581 /* force the message queue to be created before signaling parent thread */
582 PeekMessageW(&msg
, NULL
, WM_USER
, WM_USER
, PM_NOREMOVE
);
584 SetEvent(params
->ready_event
);
585 params
= NULL
; /* can't touch params after here as it may be invalid */
587 while (GetMessageW(&msg
, NULL
, 0, 0))
589 if (!msg
.hwnd
&& (msg
.message
== DM_HOSTOBJECT
))
591 struct host_object_params
*obj_params
= (struct host_object_params
*)msg
.lParam
;
592 obj_params
->hr
= apartment_hostobject(apt
, obj_params
);
593 SetEvent(obj_params
->event
);
597 TranslateMessage(&msg
);
598 DispatchMessageW(&msg
);
609 /* finds or creates a host apartment, creates the object inside it and returns
610 * a proxy to it so that the object can be used in the apartment of the
611 * caller of this function */
612 static HRESULT
apartment_hostobject_in_hostapt(
613 struct apartment
*apt
, BOOL multi_threaded
, BOOL main_apartment
,
614 HKEY hkeydll
, REFCLSID rclsid
, REFIID riid
, void **ppv
)
616 struct host_object_params params
;
617 HWND apartment_hwnd
= NULL
;
618 DWORD apartment_tid
= 0;
621 if (!multi_threaded
&& main_apartment
)
623 APARTMENT
*host_apt
= apartment_findmain();
626 apartment_hwnd
= apartment_getwindow(host_apt
);
627 apartment_release(host_apt
);
633 EnterCriticalSection(&apt
->cs
);
635 if (!apt
->host_apt_tid
)
637 struct host_thread_params thread_params
;
641 thread_params
.threading_model
= multi_threaded
? COINIT_MULTITHREADED
: COINIT_APARTMENTTHREADED
;
642 handles
[0] = thread_params
.ready_event
= CreateEventW(NULL
, FALSE
, FALSE
, NULL
);
643 thread_params
.apartment_hwnd
= NULL
;
644 handles
[1] = CreateThread(NULL
, 0, apartment_hostobject_thread
, &thread_params
, 0, &apt
->host_apt_tid
);
647 CloseHandle(handles
[0]);
648 LeaveCriticalSection(&apt
->cs
);
649 return E_OUTOFMEMORY
;
651 wait_value
= WaitForMultipleObjects(2, handles
, FALSE
, INFINITE
);
652 CloseHandle(handles
[0]);
653 CloseHandle(handles
[1]);
654 if (wait_value
== WAIT_OBJECT_0
)
655 apt
->host_apt_hwnd
= thread_params
.apartment_hwnd
;
658 LeaveCriticalSection(&apt
->cs
);
659 return E_OUTOFMEMORY
;
663 if (multi_threaded
|| !main_apartment
)
665 apartment_hwnd
= apt
->host_apt_hwnd
;
666 apartment_tid
= apt
->host_apt_tid
;
669 LeaveCriticalSection(&apt
->cs
);
672 /* another thread may have become the main apartment in the time it took
673 * us to create the thread for the host apartment */
674 if (!apartment_hwnd
&& !multi_threaded
&& main_apartment
)
676 APARTMENT
*host_apt
= apartment_findmain();
679 apartment_hwnd
= apartment_getwindow(host_apt
);
680 apartment_release(host_apt
);
684 params
.hkeydll
= hkeydll
;
685 params
.clsid
= *rclsid
;
687 hr
= CreateStreamOnHGlobal(NULL
, TRUE
, ¶ms
.stream
);
690 params
.apartment_threaded
= !multi_threaded
;
694 params
.event
= CreateEventW(NULL
, FALSE
, FALSE
, NULL
);
695 if (!PostThreadMessageW(apartment_tid
, DM_HOSTOBJECT
, 0, (LPARAM
)¶ms
))
699 WaitForSingleObject(params
.event
, INFINITE
);
702 CloseHandle(params
.event
);
708 ERR("host apartment didn't create window\n");
712 hr
= SendMessageW(apartment_hwnd
, DM_HOSTOBJECT
, 0, (LPARAM
)¶ms
);
715 hr
= CoUnmarshalInterface(params
.stream
, riid
, ppv
);
716 IStream_Release(params
.stream
);
720 /* create a window for the apartment or return the current one if one has
721 * already been created */
722 HRESULT
apartment_createwindowifneeded(struct apartment
*apt
)
724 if (apt
->multi_threaded
)
729 HWND hwnd
= CreateWindowW(wszAptWinClass
, NULL
, 0,
731 HWND_MESSAGE
, 0, hProxyDll
, NULL
);
734 ERR("CreateWindow failed with error %d\n", GetLastError());
735 return HRESULT_FROM_WIN32(GetLastError());
737 if (InterlockedCompareExchangePointer((PVOID
*)&apt
->win
, hwnd
, NULL
))
738 /* someone beat us to it */
745 /* retrieves the window for the main- or apartment-threaded apartment */
746 HWND
apartment_getwindow(const struct apartment
*apt
)
748 assert(!apt
->multi_threaded
);
752 void apartment_joinmta(void)
754 apartment_addref(MTA
);
755 COM_CurrentInfo()->apt
= MTA
;
758 /* gets the specified class object by loading the appropriate DLL, if
759 * necessary and calls the DllGetClassObject function for the DLL */
760 static HRESULT
apartment_getclassobject(struct apartment
*apt
, LPCWSTR dllpath
,
761 BOOL apartment_threaded
,
762 REFCLSID rclsid
, REFIID riid
, void **ppv
)
764 static const WCHAR wszOle32
[] = {'o','l','e','3','2','.','d','l','l',0};
767 struct apartment_loaded_dll
*apartment_loaded_dll
;
769 if (!strcmpiW(dllpath
, wszOle32
))
771 /* we don't need to control the lifetime of this dll, so use the local
772 * implementation of DllGetClassObject directly */
773 TRACE("calling ole32!DllGetClassObject\n");
774 hr
= DllGetClassObject(rclsid
, riid
, ppv
);
777 ERR("DllGetClassObject returned error 0x%08x\n", hr
);
782 EnterCriticalSection(&apt
->cs
);
784 LIST_FOR_EACH_ENTRY(apartment_loaded_dll
, &apt
->loaded_dlls
, struct apartment_loaded_dll
, entry
)
785 if (!strcmpiW(dllpath
, apartment_loaded_dll
->dll
->library_name
))
787 TRACE("found %s already loaded\n", debugstr_w(dllpath
));
794 apartment_loaded_dll
= HeapAlloc(GetProcessHeap(), 0, sizeof(*apartment_loaded_dll
));
795 if (!apartment_loaded_dll
)
799 apartment_loaded_dll
->unload_time
= 0;
800 apartment_loaded_dll
->multi_threaded
= FALSE
;
801 hr
= COMPOBJ_DllList_Add( dllpath
, &apartment_loaded_dll
->dll
);
803 HeapFree(GetProcessHeap(), 0, apartment_loaded_dll
);
807 TRACE("added new loaded dll %s\n", debugstr_w(dllpath
));
808 list_add_tail(&apt
->loaded_dlls
, &apartment_loaded_dll
->entry
);
812 LeaveCriticalSection(&apt
->cs
);
816 /* one component being multi-threaded overrides any number of
817 * apartment-threaded components */
818 if (!apartment_threaded
)
819 apartment_loaded_dll
->multi_threaded
= TRUE
;
821 TRACE("calling DllGetClassObject %p\n", apartment_loaded_dll
->dll
->DllGetClassObject
);
822 /* OK: get the ClassObject */
823 hr
= apartment_loaded_dll
->dll
->DllGetClassObject(rclsid
, riid
, ppv
);
826 ERR("DllGetClassObject returned error 0x%08x\n", hr
);
832 /* frees unused libraries loaded by apartment_getclassobject by calling the
833 * DLL's DllCanUnloadNow entry point */
834 static void apartment_freeunusedlibraries(struct apartment
*apt
, DWORD delay
)
836 struct apartment_loaded_dll
*entry
, *next
;
837 EnterCriticalSection(&apt
->cs
);
838 LIST_FOR_EACH_ENTRY_SAFE(entry
, next
, &apt
->loaded_dlls
, struct apartment_loaded_dll
, entry
)
840 if (entry
->dll
->DllCanUnloadNow
&& (entry
->dll
->DllCanUnloadNow() == S_OK
))
842 DWORD real_delay
= delay
;
844 if (real_delay
== INFINITE
)
846 /* DLLs that return multi-threaded objects aren't unloaded
847 * straight away to cope for programs that have races between
848 * last object destruction and threads in the DLLs that haven't
849 * finished, despite DllCanUnloadNow returning S_OK */
850 if (entry
->multi_threaded
)
851 real_delay
= 10 * 60 * 1000; /* 10 minutes */
856 if (!real_delay
|| (entry
->unload_time
&& (entry
->unload_time
< GetTickCount())))
858 list_remove(&entry
->entry
);
859 COMPOBJ_DllList_ReleaseRef(entry
->dll
, TRUE
);
860 HeapFree(GetProcessHeap(), 0, entry
);
863 entry
->unload_time
= GetTickCount() + real_delay
;
865 else if (entry
->unload_time
)
866 entry
->unload_time
= 0;
868 LeaveCriticalSection(&apt
->cs
);
871 /*****************************************************************************
872 * This section contains OpenDllList implementation
875 /* caller must ensure that library_name is not already in the open dll list */
876 static HRESULT
COMPOBJ_DllList_Add(LPCWSTR library_name
, OpenDll
**ret
)
882 DllCanUnloadNowFunc DllCanUnloadNow
;
883 DllGetClassObjectFunc DllGetClassObject
;
887 *ret
= COMPOBJ_DllList_Get(library_name
);
888 if (*ret
) return S_OK
;
890 /* do this outside the csOpenDllList to avoid creating a lock dependency on
892 hLibrary
= LoadLibraryExW(library_name
, 0, LOAD_WITH_ALTERED_SEARCH_PATH
);
895 ERR("couldn't load in-process dll %s\n", debugstr_w(library_name
));
896 /* failure: DLL could not be loaded */
897 return E_ACCESSDENIED
; /* FIXME: or should this be CO_E_DLLNOTFOUND? */
900 DllCanUnloadNow
= (void *)GetProcAddress(hLibrary
, "DllCanUnloadNow");
901 /* Note: failing to find DllCanUnloadNow is not a failure */
902 DllGetClassObject
= (void *)GetProcAddress(hLibrary
, "DllGetClassObject");
903 if (!DllGetClassObject
)
905 /* failure: the dll did not export DllGetClassObject */
906 ERR("couldn't find function DllGetClassObject in %s\n", debugstr_w(library_name
));
907 FreeLibrary(hLibrary
);
908 return CO_E_DLLNOTFOUND
;
911 EnterCriticalSection( &csOpenDllList
);
913 *ret
= COMPOBJ_DllList_Get(library_name
);
916 /* another caller to this function already added the dll while we
917 * weren't in the critical section */
918 FreeLibrary(hLibrary
);
922 len
= strlenW(library_name
);
923 entry
= HeapAlloc(GetProcessHeap(),0, sizeof(OpenDll
));
925 entry
->library_name
= HeapAlloc(GetProcessHeap(), 0, (len
+ 1)*sizeof(WCHAR
));
926 if (entry
&& entry
->library_name
)
928 memcpy(entry
->library_name
, library_name
, (len
+ 1)*sizeof(WCHAR
));
929 entry
->library
= hLibrary
;
931 entry
->DllCanUnloadNow
= DllCanUnloadNow
;
932 entry
->DllGetClassObject
= DllGetClassObject
;
933 list_add_tail(&openDllList
, &entry
->entry
);
937 HeapFree(GetProcessHeap(), 0, entry
);
939 FreeLibrary(hLibrary
);
944 LeaveCriticalSection( &csOpenDllList
);
949 static OpenDll
*COMPOBJ_DllList_Get(LPCWSTR library_name
)
953 EnterCriticalSection(&csOpenDllList
);
954 LIST_FOR_EACH_ENTRY(ptr
, &openDllList
, OpenDll
, entry
)
956 if (!strcmpiW(library_name
, ptr
->library_name
) &&
957 (InterlockedIncrement(&ptr
->refs
) != 1) /* entry is being destroy if == 1 */)
963 LeaveCriticalSection(&csOpenDllList
);
967 /* pass FALSE for free_entry to release a reference without destroying the
968 * entry if it reaches zero or TRUE otherwise */
969 static void COMPOBJ_DllList_ReleaseRef(OpenDll
*entry
, BOOL free_entry
)
971 if (!InterlockedDecrement(&entry
->refs
) && free_entry
)
973 EnterCriticalSection(&csOpenDllList
);
974 list_remove(&entry
->entry
);
975 LeaveCriticalSection(&csOpenDllList
);
977 TRACE("freeing %p\n", entry
->library
);
978 FreeLibrary(entry
->library
);
980 HeapFree(GetProcessHeap(), 0, entry
->library_name
);
981 HeapFree(GetProcessHeap(), 0, entry
);
985 /* frees memory associated with active dll list */
986 static void COMPOBJ_DllList_Free(void)
988 OpenDll
*entry
, *cursor2
;
989 EnterCriticalSection(&csOpenDllList
);
990 LIST_FOR_EACH_ENTRY_SAFE(entry
, cursor2
, &openDllList
, OpenDll
, entry
)
992 list_remove(&entry
->entry
);
994 HeapFree(GetProcessHeap(), 0, entry
->library_name
);
995 HeapFree(GetProcessHeap(), 0, entry
);
997 LeaveCriticalSection(&csOpenDllList
);
1000 /******************************************************************************
1001 * CoBuildVersion [OLE32.@]
1003 * Gets the build version of the DLL.
1008 * Current build version, hiword is majornumber, loword is minornumber
1010 DWORD WINAPI
CoBuildVersion(void)
1012 TRACE("Returning version %d, build %d.\n", rmm
, rup
);
1013 return (rmm
<<16)+rup
;
1016 /******************************************************************************
1017 * CoRegisterInitializeSpy [OLE32.@]
1019 * Add a Spy that watches CoInitializeEx calls
1022 * spy [I] Pointer to IUnknown interface that will be QueryInterface'd.
1023 * cookie [II] cookie receiver
1026 * Success: S_OK if not already initialized, S_FALSE otherwise.
1027 * Failure: HRESULT code.
1032 HRESULT WINAPI
CoRegisterInitializeSpy(IInitializeSpy
*spy
, ULARGE_INTEGER
*cookie
)
1034 struct oletls
*info
= COM_CurrentInfo();
1037 TRACE("(%p, %p)\n", spy
, cookie
);
1039 if (!spy
|| !cookie
|| !info
)
1042 WARN("Could not allocate tls\n");
1043 return E_INVALIDARG
;
1048 FIXME("Already registered?\n");
1049 return E_UNEXPECTED
;
1052 hr
= IUnknown_QueryInterface(spy
, &IID_IInitializeSpy
, (void **) &info
->spy
);
1055 cookie
->QuadPart
= (DWORD_PTR
)spy
;
1061 /******************************************************************************
1062 * CoRevokeInitializeSpy [OLE32.@]
1064 * Remove a spy that previously watched CoInitializeEx calls
1067 * cookie [I] The cookie obtained from a previous CoRegisterInitializeSpy call
1070 * Success: S_OK if a spy is removed
1071 * Failure: E_INVALIDARG
1076 HRESULT WINAPI
CoRevokeInitializeSpy(ULARGE_INTEGER cookie
)
1078 struct oletls
*info
= COM_CurrentInfo();
1079 TRACE("(%s)\n", wine_dbgstr_longlong(cookie
.QuadPart
));
1081 if (!info
|| !info
->spy
|| cookie
.QuadPart
!= (DWORD_PTR
)info
->spy
)
1082 return E_INVALIDARG
;
1084 IUnknown_Release(info
->spy
);
1090 /******************************************************************************
1091 * CoInitialize [OLE32.@]
1093 * Initializes the COM libraries by calling CoInitializeEx with
1094 * COINIT_APARTMENTTHREADED, ie it enters a STA thread.
1097 * lpReserved [I] Pointer to IMalloc interface (obsolete, should be NULL).
1100 * Success: S_OK if not already initialized, S_FALSE otherwise.
1101 * Failure: HRESULT code.
1106 HRESULT WINAPI
CoInitialize(LPVOID lpReserved
)
1109 * Just delegate to the newer method.
1111 return CoInitializeEx(lpReserved
, COINIT_APARTMENTTHREADED
);
1114 /******************************************************************************
1115 * CoInitializeEx [OLE32.@]
1117 * Initializes the COM libraries.
1120 * lpReserved [I] Pointer to IMalloc interface (obsolete, should be NULL).
1121 * dwCoInit [I] One or more flags from the COINIT enumeration. See notes.
1124 * S_OK if successful,
1125 * S_FALSE if this function was called already.
1126 * RPC_E_CHANGED_MODE if a previous call to CoInitializeEx specified another
1131 * The behavior used to set the IMalloc used for memory management is
1133 * The dwCoInit parameter must specify one of the following apartment
1135 *| COINIT_APARTMENTTHREADED - A single-threaded apartment (STA).
1136 *| COINIT_MULTITHREADED - A multi-threaded apartment (MTA).
1137 * The parameter may also specify zero or more of the following flags:
1138 *| COINIT_DISABLE_OLE1DDE - Don't use DDE for OLE1 support.
1139 *| COINIT_SPEED_OVER_MEMORY - Trade memory for speed.
1144 HRESULT WINAPI
CoInitializeEx(LPVOID lpReserved
, DWORD dwCoInit
)
1146 struct oletls
*info
= COM_CurrentInfo();
1150 TRACE("(%p, %x)\n", lpReserved
, (int)dwCoInit
);
1152 if (lpReserved
!=NULL
)
1154 ERR("(%p, %x) - Bad parameter passed-in %p, must be an old Windows Application\n", lpReserved
, (int)dwCoInit
, lpReserved
);
1158 * Check the lock count. If this is the first time going through the initialize
1159 * process, we have to initialize the libraries.
1161 * And crank-up that lock count.
1163 if (InterlockedExchangeAdd(&s_COMLockCount
,1)==0)
1166 * Initialize the various COM libraries and data structures.
1168 TRACE("() - Initializing the COM libraries\n");
1170 /* we may need to defer this until after apartment initialisation */
1171 RunningObjectTableImpl_Initialize();
1175 IInitializeSpy_PreInitialize(info
->spy
, dwCoInit
, info
->inits
);
1177 if (!(apt
= info
->apt
))
1179 apt
= apartment_get_or_create(dwCoInit
);
1180 if (!apt
) return E_OUTOFMEMORY
;
1182 else if (!apartment_is_model(apt
, dwCoInit
))
1184 /* Changing the threading model after it's been set is illegal. If this warning is triggered by Wine
1185 code then we are probably using the wrong threading model to implement that API. */
1186 ERR("Attempt to change threading model of this apartment from %s to %s\n",
1187 apt
->multi_threaded
? "multi-threaded" : "apartment threaded",
1188 dwCoInit
& COINIT_APARTMENTTHREADED
? "apartment threaded" : "multi-threaded");
1189 return RPC_E_CHANGED_MODE
;
1197 IInitializeSpy_PostInitialize(info
->spy
, hr
, dwCoInit
, info
->inits
);
1202 /***********************************************************************
1203 * CoUninitialize [OLE32.@]
1205 * This method will decrement the refcount on the current apartment, freeing
1206 * the resources associated with it if it is the last thread in the apartment.
1207 * If the last apartment is freed, the function will additionally release
1208 * any COM resources associated with the process.
1218 void WINAPI
CoUninitialize(void)
1220 struct oletls
* info
= COM_CurrentInfo();
1225 /* will only happen on OOM */
1229 IInitializeSpy_PreUninitialize(info
->spy
, info
->inits
);
1234 ERR("Mismatched CoUninitialize\n");
1237 IInitializeSpy_PostUninitialize(info
->spy
, info
->inits
);
1243 apartment_release(info
->apt
);
1248 * Decrease the reference count.
1249 * If we are back to 0 locks on the COM library, make sure we free
1250 * all the associated data structures.
1252 lCOMRefCnt
= InterlockedExchangeAdd(&s_COMLockCount
,-1);
1255 TRACE("() - Releasing the COM libraries\n");
1257 RunningObjectTableImpl_UnInitialize();
1259 else if (lCOMRefCnt
<1) {
1260 ERR( "CoUninitialize() - not CoInitialized.\n" );
1261 InterlockedExchangeAdd(&s_COMLockCount
,1); /* restore the lock count. */
1264 IInitializeSpy_PostUninitialize(info
->spy
, info
->inits
);
1267 /******************************************************************************
1268 * CoDisconnectObject [OLE32.@]
1270 * Disconnects all connections to this object from remote processes. Dispatches
1271 * pending RPCs while blocking new RPCs from occurring, and then calls
1272 * IMarshal::DisconnectObject on the given object.
1274 * Typically called when the object server is forced to shut down, for instance by
1278 * lpUnk [I] The object whose stub should be disconnected.
1279 * reserved [I] Reserved. Should be set to 0.
1283 * Failure: HRESULT code.
1286 * CoMarshalInterface, CoReleaseMarshalData, CoLockObjectExternal
1288 HRESULT WINAPI
CoDisconnectObject( LPUNKNOWN lpUnk
, DWORD reserved
)
1294 TRACE("(%p, 0x%08x)\n", lpUnk
, reserved
);
1296 hr
= IUnknown_QueryInterface(lpUnk
, &IID_IMarshal
, (void **)&marshal
);
1299 hr
= IMarshal_DisconnectObject(marshal
, reserved
);
1300 IMarshal_Release(marshal
);
1304 apt
= COM_CurrentApt();
1306 return CO_E_NOTINITIALIZED
;
1308 apartment_disconnectobject(apt
, lpUnk
);
1310 /* Note: native is pretty broken here because it just silently
1311 * fails, without returning an appropriate error code if the object was
1312 * not found, making apps think that the object was disconnected, when
1313 * it actually wasn't */
1318 /******************************************************************************
1319 * CoCreateGuid [OLE32.@]
1321 * Simply forwards to UuidCreate in RPCRT4.
1324 * pguid [O] Points to the GUID to initialize.
1328 * Failure: HRESULT code.
1333 HRESULT WINAPI
CoCreateGuid(GUID
*pguid
)
1335 DWORD status
= UuidCreate(pguid
);
1336 if (status
== RPC_S_OK
|| status
== RPC_S_UUID_LOCAL_ONLY
) return S_OK
;
1337 return HRESULT_FROM_WIN32( status
);
1340 /******************************************************************************
1341 * CLSIDFromString [OLE32.@]
1342 * IIDFromString [OLE32.@]
1344 * Converts a unique identifier from its string representation into
1348 * idstr [I] The string representation of the GUID.
1349 * id [O] GUID converted from the string.
1353 * CO_E_CLASSSTRING if idstr is not a valid CLSID
1358 static HRESULT
__CLSIDFromString(LPCWSTR s
, CLSID
*id
)
1364 memset( id
, 0, sizeof (CLSID
) );
1368 /* validate the CLSID string */
1369 if (strlenW(s
) != 38)
1370 return CO_E_CLASSSTRING
;
1372 if ((s
[0]!='{') || (s
[9]!='-') || (s
[14]!='-') || (s
[19]!='-') || (s
[24]!='-') || (s
[37]!='}'))
1373 return CO_E_CLASSSTRING
;
1375 for (i
=1; i
<37; i
++) {
1376 if ((i
== 9)||(i
== 14)||(i
== 19)||(i
== 24)) continue;
1377 if (!(((s
[i
] >= '0') && (s
[i
] <= '9')) ||
1378 ((s
[i
] >= 'a') && (s
[i
] <= 'f')) ||
1379 ((s
[i
] >= 'A') && (s
[i
] <= 'F'))))
1380 return CO_E_CLASSSTRING
;
1383 TRACE("%s -> %p\n", debugstr_w(s
), id
);
1385 /* quick lookup table */
1386 memset(table
, 0, 256);
1388 for (i
= 0; i
< 10; i
++) {
1391 for (i
= 0; i
< 6; i
++) {
1392 table
['A' + i
] = i
+10;
1393 table
['a' + i
] = i
+10;
1396 /* in form {XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX} */
1398 id
->Data1
= (table
[s
[1]] << 28 | table
[s
[2]] << 24 | table
[s
[3]] << 20 | table
[s
[4]] << 16 |
1399 table
[s
[5]] << 12 | table
[s
[6]] << 8 | table
[s
[7]] << 4 | table
[s
[8]]);
1400 id
->Data2
= table
[s
[10]] << 12 | table
[s
[11]] << 8 | table
[s
[12]] << 4 | table
[s
[13]];
1401 id
->Data3
= table
[s
[15]] << 12 | table
[s
[16]] << 8 | table
[s
[17]] << 4 | table
[s
[18]];
1403 /* these are just sequential bytes */
1404 id
->Data4
[0] = table
[s
[20]] << 4 | table
[s
[21]];
1405 id
->Data4
[1] = table
[s
[22]] << 4 | table
[s
[23]];
1406 id
->Data4
[2] = table
[s
[25]] << 4 | table
[s
[26]];
1407 id
->Data4
[3] = table
[s
[27]] << 4 | table
[s
[28]];
1408 id
->Data4
[4] = table
[s
[29]] << 4 | table
[s
[30]];
1409 id
->Data4
[5] = table
[s
[31]] << 4 | table
[s
[32]];
1410 id
->Data4
[6] = table
[s
[33]] << 4 | table
[s
[34]];
1411 id
->Data4
[7] = table
[s
[35]] << 4 | table
[s
[36]];
1416 /*****************************************************************************/
1418 HRESULT WINAPI
CLSIDFromString(LPOLESTR idstr
, CLSID
*id
)
1423 return E_INVALIDARG
;
1425 ret
= __CLSIDFromString(idstr
, id
);
1426 if(ret
!= S_OK
) { /* It appears a ProgID is also valid */
1427 ret
= CLSIDFromProgID(idstr
, id
);
1433 /******************************************************************************
1434 * StringFromCLSID [OLE32.@]
1435 * StringFromIID [OLE32.@]
1437 * Converts a GUID into the respective string representation.
1438 * The target string is allocated using the OLE IMalloc.
1441 * id [I] the GUID to be converted.
1442 * idstr [O] A pointer to a to-be-allocated pointer pointing to the resulting string.
1449 * StringFromGUID2, CLSIDFromString
1451 HRESULT WINAPI
StringFromCLSID(REFCLSID id
, LPOLESTR
*idstr
)
1456 if ((ret
= CoGetMalloc(0,&mllc
))) return ret
;
1457 if (!(*idstr
= IMalloc_Alloc( mllc
, CHARS_IN_GUID
* sizeof(WCHAR
) ))) return E_OUTOFMEMORY
;
1458 StringFromGUID2( id
, *idstr
, CHARS_IN_GUID
);
1462 /******************************************************************************
1463 * StringFromGUID2 [OLE32.@]
1465 * Modified version of StringFromCLSID that allows you to specify max
1469 * id [I] GUID to convert to string.
1470 * str [O] Buffer where the result will be stored.
1471 * cmax [I] Size of the buffer in characters.
1474 * Success: The length of the resulting string in characters.
1477 INT WINAPI
StringFromGUID2(REFGUID id
, LPOLESTR str
, INT cmax
)
1479 static const WCHAR formatW
[] = { '{','%','0','8','X','-','%','0','4','X','-',
1480 '%','0','4','X','-','%','0','2','X','%','0','2','X','-',
1481 '%','0','2','X','%','0','2','X','%','0','2','X','%','0','2','X',
1482 '%','0','2','X','%','0','2','X','}',0 };
1483 if (cmax
< CHARS_IN_GUID
) return 0;
1484 sprintfW( str
, formatW
, id
->Data1
, id
->Data2
, id
->Data3
,
1485 id
->Data4
[0], id
->Data4
[1], id
->Data4
[2], id
->Data4
[3],
1486 id
->Data4
[4], id
->Data4
[5], id
->Data4
[6], id
->Data4
[7] );
1487 return CHARS_IN_GUID
;
1490 /* open HKCR\\CLSID\\{string form of clsid}\\{keyname} key */
1491 HRESULT
COM_OpenKeyForCLSID(REFCLSID clsid
, LPCWSTR keyname
, REGSAM access
, HKEY
*subkey
)
1493 static const WCHAR wszCLSIDSlash
[] = {'C','L','S','I','D','\\',0};
1494 WCHAR path
[CHARS_IN_GUID
+ ARRAYSIZE(wszCLSIDSlash
) - 1];
1498 strcpyW(path
, wszCLSIDSlash
);
1499 StringFromGUID2(clsid
, path
+ strlenW(wszCLSIDSlash
), CHARS_IN_GUID
);
1500 res
= RegOpenKeyExW(HKEY_CLASSES_ROOT
, path
, 0, keyname
? KEY_READ
: access
, &key
);
1501 if (res
== ERROR_FILE_NOT_FOUND
)
1502 return REGDB_E_CLASSNOTREG
;
1503 else if (res
!= ERROR_SUCCESS
)
1504 return REGDB_E_READREGDB
;
1512 res
= RegOpenKeyExW(key
, keyname
, 0, access
, subkey
);
1514 if (res
== ERROR_FILE_NOT_FOUND
)
1515 return REGDB_E_KEYMISSING
;
1516 else if (res
!= ERROR_SUCCESS
)
1517 return REGDB_E_READREGDB
;
1522 /* open HKCR\\AppId\\{string form of appid clsid} key */
1523 HRESULT
COM_OpenKeyForAppIdFromCLSID(REFCLSID clsid
, REGSAM access
, HKEY
*subkey
)
1525 static const WCHAR szAppId
[] = { 'A','p','p','I','d',0 };
1526 static const WCHAR szAppIdKey
[] = { 'A','p','p','I','d','\\',0 };
1528 WCHAR buf
[CHARS_IN_GUID
];
1529 WCHAR keyname
[ARRAYSIZE(szAppIdKey
) + CHARS_IN_GUID
];
1535 /* read the AppID value under the class's key */
1536 hr
= COM_OpenKeyForCLSID(clsid
, NULL
, KEY_READ
, &hkey
);
1541 res
= RegQueryValueExW(hkey
, szAppId
, NULL
, &type
, (LPBYTE
)buf
, &size
);
1543 if (res
== ERROR_FILE_NOT_FOUND
)
1544 return REGDB_E_KEYMISSING
;
1545 else if (res
!= ERROR_SUCCESS
|| type
!=REG_SZ
)
1546 return REGDB_E_READREGDB
;
1548 strcpyW(keyname
, szAppIdKey
);
1549 strcatW(keyname
, buf
);
1550 res
= RegOpenKeyExW(HKEY_CLASSES_ROOT
, keyname
, 0, access
, subkey
);
1551 if (res
== ERROR_FILE_NOT_FOUND
)
1552 return REGDB_E_KEYMISSING
;
1553 else if (res
!= ERROR_SUCCESS
)
1554 return REGDB_E_READREGDB
;
1559 /******************************************************************************
1560 * ProgIDFromCLSID [OLE32.@]
1562 * Converts a class id into the respective program ID.
1565 * clsid [I] Class ID, as found in registry.
1566 * ppszProgID [O] Associated ProgID.
1571 * REGDB_E_CLASSNOTREG if the given clsid has no associated ProgID
1573 HRESULT WINAPI
ProgIDFromCLSID(REFCLSID clsid
, LPOLESTR
*ppszProgID
)
1575 static const WCHAR wszProgID
[] = {'P','r','o','g','I','D',0};
1582 ERR("ppszProgId isn't optional\n");
1583 return E_INVALIDARG
;
1587 ret
= COM_OpenKeyForCLSID(clsid
, wszProgID
, KEY_READ
, &hkey
);
1591 if (RegQueryValueW(hkey
, NULL
, NULL
, &progidlen
))
1592 ret
= REGDB_E_CLASSNOTREG
;
1596 *ppszProgID
= CoTaskMemAlloc(progidlen
* sizeof(WCHAR
));
1599 if (RegQueryValueW(hkey
, NULL
, *ppszProgID
, &progidlen
))
1600 ret
= REGDB_E_CLASSNOTREG
;
1603 ret
= E_OUTOFMEMORY
;
1610 /******************************************************************************
1611 * CLSIDFromProgID [OLE32.@]
1613 * Converts a program id into the respective GUID.
1616 * progid [I] Unicode program ID, as found in registry.
1617 * clsid [O] Associated CLSID.
1621 * Failure: CO_E_CLASSSTRING - the given ProgID cannot be found.
1623 HRESULT WINAPI
CLSIDFromProgID(LPCOLESTR progid
, LPCLSID clsid
)
1625 static const WCHAR clsidW
[] = { '\\','C','L','S','I','D',0 };
1626 WCHAR buf2
[CHARS_IN_GUID
];
1627 LONG buf2len
= sizeof(buf2
);
1631 if (!progid
|| !clsid
)
1633 ERR("neither progid (%p) nor clsid (%p) are optional\n", progid
, clsid
);
1634 return E_INVALIDARG
;
1637 /* initialise clsid in case of failure */
1638 memset(clsid
, 0, sizeof(*clsid
));
1640 buf
= HeapAlloc( GetProcessHeap(),0,(strlenW(progid
)+8) * sizeof(WCHAR
) );
1641 strcpyW( buf
, progid
);
1642 strcatW( buf
, clsidW
);
1643 if (RegOpenKeyW(HKEY_CLASSES_ROOT
,buf
,&xhkey
))
1645 HeapFree(GetProcessHeap(),0,buf
);
1646 WARN("couldn't open key for ProgID %s\n", debugstr_w(progid
));
1647 return CO_E_CLASSSTRING
;
1649 HeapFree(GetProcessHeap(),0,buf
);
1651 if (RegQueryValueW(xhkey
,NULL
,buf2
,&buf2len
))
1654 WARN("couldn't query clsid value for ProgID %s\n", debugstr_w(progid
));
1655 return CO_E_CLASSSTRING
;
1658 return __CLSIDFromString(buf2
,clsid
);
1662 /*****************************************************************************
1663 * CoGetPSClsid [OLE32.@]
1665 * Retrieves the CLSID of the proxy/stub factory that implements
1666 * IPSFactoryBuffer for the specified interface.
1669 * riid [I] Interface whose proxy/stub CLSID is to be returned.
1670 * pclsid [O] Where to store returned proxy/stub CLSID.
1675 * REGDB_E_IIDNOTREG if no PSFactoryBuffer is associated with the IID, or it could not be parsed
1679 * The standard marshaller activates the object with the CLSID
1680 * returned and uses the CreateProxy and CreateStub methods on its
1681 * IPSFactoryBuffer interface to construct the proxies and stubs for a
1684 * CoGetPSClsid determines this CLSID by searching the
1685 * HKEY_CLASSES_ROOT\Interface\{string form of riid}\ProxyStubClsid32
1686 * in the registry and any interface id registered by
1687 * CoRegisterPSClsid within the current process.
1691 * Native returns S_OK for interfaces with a key in HKCR\Interface, but
1692 * without a ProxyStubClsid32 key and leaves garbage in pclsid. This should be
1693 * considered a bug in native unless an application depends on this (unlikely).
1696 * CoRegisterPSClsid.
1698 HRESULT WINAPI
CoGetPSClsid(REFIID riid
, CLSID
*pclsid
)
1700 static const WCHAR wszInterface
[] = {'I','n','t','e','r','f','a','c','e','\\',0};
1701 static const WCHAR wszPSC
[] = {'\\','P','r','o','x','y','S','t','u','b','C','l','s','i','d','3','2',0};
1702 WCHAR path
[ARRAYSIZE(wszInterface
) - 1 + CHARS_IN_GUID
- 1 + ARRAYSIZE(wszPSC
)];
1703 WCHAR value
[CHARS_IN_GUID
];
1706 APARTMENT
*apt
= COM_CurrentApt();
1707 struct registered_psclsid
*registered_psclsid
;
1709 TRACE("() riid=%s, pclsid=%p\n", debugstr_guid(riid
), pclsid
);
1713 ERR("apartment not initialised\n");
1714 return CO_E_NOTINITIALIZED
;
1719 ERR("pclsid isn't optional\n");
1720 return E_INVALIDARG
;
1723 EnterCriticalSection(&apt
->cs
);
1725 LIST_FOR_EACH_ENTRY(registered_psclsid
, &apt
->psclsids
, struct registered_psclsid
, entry
)
1726 if (IsEqualIID(®istered_psclsid
->iid
, riid
))
1728 *pclsid
= registered_psclsid
->clsid
;
1729 LeaveCriticalSection(&apt
->cs
);
1733 LeaveCriticalSection(&apt
->cs
);
1735 /* Interface\\{string form of riid}\\ProxyStubClsid32 */
1736 strcpyW(path
, wszInterface
);
1737 StringFromGUID2(riid
, path
+ ARRAYSIZE(wszInterface
) - 1, CHARS_IN_GUID
);
1738 strcpyW(path
+ ARRAYSIZE(wszInterface
) - 1 + CHARS_IN_GUID
- 1, wszPSC
);
1740 /* Open the key.. */
1741 if (RegOpenKeyExW(HKEY_CLASSES_ROOT
, path
, 0, KEY_READ
, &hkey
))
1743 WARN("No PSFactoryBuffer object is registered for IID %s\n", debugstr_guid(riid
));
1744 return REGDB_E_IIDNOTREG
;
1747 /* ... Once we have the key, query the registry to get the
1748 value of CLSID as a string, and convert it into a
1749 proper CLSID structure to be passed back to the app */
1750 len
= sizeof(value
);
1751 if (ERROR_SUCCESS
!= RegQueryValueW(hkey
, NULL
, value
, &len
))
1754 return REGDB_E_IIDNOTREG
;
1758 /* We have the CLSID we want back from the registry as a string, so
1759 let's convert it into a CLSID structure */
1760 if (CLSIDFromString(value
, pclsid
) != NOERROR
)
1761 return REGDB_E_IIDNOTREG
;
1763 TRACE ("() Returning CLSID=%s\n", debugstr_guid(pclsid
));
1767 /*****************************************************************************
1768 * CoRegisterPSClsid [OLE32.@]
1770 * Register a proxy/stub CLSID for the given interface in the current process
1774 * riid [I] Interface whose proxy/stub CLSID is to be registered.
1775 * rclsid [I] CLSID of the proxy/stub.
1779 * Failure: E_OUTOFMEMORY
1783 * This function does not add anything to the registry and the effects are
1784 * limited to the lifetime of the current process.
1789 HRESULT WINAPI
CoRegisterPSClsid(REFIID riid
, REFCLSID rclsid
)
1791 APARTMENT
*apt
= COM_CurrentApt();
1792 struct registered_psclsid
*registered_psclsid
;
1794 TRACE("(%s, %s)\n", debugstr_guid(riid
), debugstr_guid(rclsid
));
1798 ERR("apartment not initialised\n");
1799 return CO_E_NOTINITIALIZED
;
1802 EnterCriticalSection(&apt
->cs
);
1804 LIST_FOR_EACH_ENTRY(registered_psclsid
, &apt
->psclsids
, struct registered_psclsid
, entry
)
1805 if (IsEqualIID(®istered_psclsid
->iid
, riid
))
1807 registered_psclsid
->clsid
= *rclsid
;
1808 LeaveCriticalSection(&apt
->cs
);
1812 registered_psclsid
= HeapAlloc(GetProcessHeap(), 0, sizeof(struct registered_psclsid
));
1813 if (!registered_psclsid
)
1815 LeaveCriticalSection(&apt
->cs
);
1816 return E_OUTOFMEMORY
;
1819 registered_psclsid
->iid
= *riid
;
1820 registered_psclsid
->clsid
= *rclsid
;
1821 list_add_head(&apt
->psclsids
, ®istered_psclsid
->entry
);
1823 LeaveCriticalSection(&apt
->cs
);
1830 * COM_GetRegisteredClassObject
1832 * This internal method is used to scan the registered class list to
1833 * find a class object.
1836 * rclsid Class ID of the class to find.
1837 * dwClsContext Class context to match.
1838 * ppv [out] returns a pointer to the class object. Complying
1839 * to normal COM usage, this method will increase the
1840 * reference count on this object.
1842 static HRESULT
COM_GetRegisteredClassObject(const struct apartment
*apt
, REFCLSID rclsid
,
1843 DWORD dwClsContext
, LPUNKNOWN
* ppUnk
)
1845 HRESULT hr
= S_FALSE
;
1846 RegisteredClass
*curClass
;
1848 EnterCriticalSection( &csRegisteredClassList
);
1850 LIST_FOR_EACH_ENTRY(curClass
, &RegisteredClassList
, RegisteredClass
, entry
)
1853 * Check if we have a match on the class ID and context.
1855 if ((apt
->oxid
== curClass
->apartment_id
) &&
1856 (dwClsContext
& curClass
->runContext
) &&
1857 IsEqualGUID(&(curClass
->classIdentifier
), rclsid
))
1860 * We have a match, return the pointer to the class object.
1862 *ppUnk
= curClass
->classObject
;
1864 IUnknown_AddRef(curClass
->classObject
);
1871 LeaveCriticalSection( &csRegisteredClassList
);
1876 /******************************************************************************
1877 * CoRegisterClassObject [OLE32.@]
1879 * Registers the class object for a given class ID. Servers housed in EXE
1880 * files use this method instead of exporting DllGetClassObject to allow
1881 * other code to connect to their objects.
1884 * rclsid [I] CLSID of the object to register.
1885 * pUnk [I] IUnknown of the object.
1886 * dwClsContext [I] CLSCTX flags indicating the context in which to run the executable.
1887 * flags [I] REGCLS flags indicating how connections are made.
1888 * lpdwRegister [I] A unique cookie that can be passed to CoRevokeClassObject.
1892 * E_INVALIDARG if lpdwRegister or pUnk are NULL,
1893 * CO_E_OBJISREG if the object is already registered. We should not return this.
1896 * CoRevokeClassObject, CoGetClassObject
1899 * In-process objects are only registered for the current apartment.
1900 * CoGetClassObject() and CoCreateInstance() will not return objects registered
1901 * in other apartments.
1904 * MSDN claims that multiple interface registrations are legal, but we
1905 * can't do that with our current implementation.
1907 HRESULT WINAPI
CoRegisterClassObject(
1912 LPDWORD lpdwRegister
)
1914 RegisteredClass
* newClass
;
1915 LPUNKNOWN foundObject
;
1919 TRACE("(%s,%p,0x%08x,0x%08x,%p)\n",
1920 debugstr_guid(rclsid
),pUnk
,dwClsContext
,flags
,lpdwRegister
);
1922 if ( (lpdwRegister
==0) || (pUnk
==0) )
1923 return E_INVALIDARG
;
1925 apt
= COM_CurrentApt();
1928 ERR("COM was not initialized\n");
1929 return CO_E_NOTINITIALIZED
;
1934 /* REGCLS_MULTIPLEUSE implies registering as inproc server. This is what
1935 * differentiates the flag from REGCLS_MULTI_SEPARATE. */
1936 if (flags
& REGCLS_MULTIPLEUSE
)
1937 dwClsContext
|= CLSCTX_INPROC_SERVER
;
1940 * First, check if the class is already registered.
1941 * If it is, this should cause an error.
1943 hr
= COM_GetRegisteredClassObject(apt
, rclsid
, dwClsContext
, &foundObject
);
1945 if (flags
& REGCLS_MULTIPLEUSE
) {
1946 if (dwClsContext
& CLSCTX_LOCAL_SERVER
)
1947 hr
= CoLockObjectExternal(foundObject
, TRUE
, FALSE
);
1948 IUnknown_Release(foundObject
);
1951 IUnknown_Release(foundObject
);
1952 ERR("object already registered for class %s\n", debugstr_guid(rclsid
));
1953 return CO_E_OBJISREG
;
1956 newClass
= HeapAlloc(GetProcessHeap(), 0, sizeof(RegisteredClass
));
1957 if ( newClass
== NULL
)
1958 return E_OUTOFMEMORY
;
1960 newClass
->classIdentifier
= *rclsid
;
1961 newClass
->apartment_id
= apt
->oxid
;
1962 newClass
->runContext
= dwClsContext
;
1963 newClass
->connectFlags
= flags
;
1964 newClass
->pMarshaledData
= NULL
;
1965 newClass
->RpcRegistration
= NULL
;
1968 * Use the address of the chain node as the cookie since we are sure it's
1969 * unique. FIXME: not on 64-bit platforms.
1971 newClass
->dwCookie
= (DWORD
)newClass
;
1974 * Since we're making a copy of the object pointer, we have to increase its
1977 newClass
->classObject
= pUnk
;
1978 IUnknown_AddRef(newClass
->classObject
);
1980 EnterCriticalSection( &csRegisteredClassList
);
1981 list_add_tail(&RegisteredClassList
, &newClass
->entry
);
1982 LeaveCriticalSection( &csRegisteredClassList
);
1984 *lpdwRegister
= newClass
->dwCookie
;
1986 if (dwClsContext
& CLSCTX_LOCAL_SERVER
) {
1987 hr
= CreateStreamOnHGlobal(0, TRUE
, &newClass
->pMarshaledData
);
1989 FIXME("Failed to create stream on hglobal, %x\n", hr
);
1992 hr
= CoMarshalInterface(newClass
->pMarshaledData
, &IID_IClassFactory
,
1993 newClass
->classObject
, MSHCTX_LOCAL
, NULL
,
1994 MSHLFLAGS_TABLESTRONG
);
1996 FIXME("CoMarshalInterface failed, %x!\n",hr
);
2000 hr
= RPC_StartLocalServer(&newClass
->classIdentifier
,
2001 newClass
->pMarshaledData
,
2002 flags
& (REGCLS_MULTIPLEUSE
|REGCLS_MULTI_SEPARATE
),
2003 &newClass
->RpcRegistration
);
2008 static void COM_RevokeRegisteredClassObject(RegisteredClass
*curClass
)
2010 list_remove(&curClass
->entry
);
2012 if (curClass
->runContext
& CLSCTX_LOCAL_SERVER
)
2013 RPC_StopLocalServer(curClass
->RpcRegistration
);
2016 * Release the reference to the class object.
2018 IUnknown_Release(curClass
->classObject
);
2020 if (curClass
->pMarshaledData
)
2023 memset(&zero
, 0, sizeof(zero
));
2024 IStream_Seek(curClass
->pMarshaledData
, zero
, STREAM_SEEK_SET
, NULL
);
2025 CoReleaseMarshalData(curClass
->pMarshaledData
);
2026 IStream_Release(curClass
->pMarshaledData
);
2029 HeapFree(GetProcessHeap(), 0, curClass
);
2032 static void COM_RevokeAllClasses(const struct apartment
*apt
)
2034 RegisteredClass
*curClass
, *cursor
;
2036 EnterCriticalSection( &csRegisteredClassList
);
2038 LIST_FOR_EACH_ENTRY_SAFE(curClass
, cursor
, &RegisteredClassList
, RegisteredClass
, entry
)
2040 if (curClass
->apartment_id
== apt
->oxid
)
2041 COM_RevokeRegisteredClassObject(curClass
);
2044 LeaveCriticalSection( &csRegisteredClassList
);
2047 /***********************************************************************
2048 * CoRevokeClassObject [OLE32.@]
2050 * Removes a class object from the class registry.
2053 * dwRegister [I] Cookie returned from CoRegisterClassObject().
2057 * Failure: HRESULT code.
2060 * Must be called from the same apartment that called CoRegisterClassObject(),
2061 * otherwise it will fail with RPC_E_WRONG_THREAD.
2064 * CoRegisterClassObject
2066 HRESULT WINAPI
CoRevokeClassObject(
2069 HRESULT hr
= E_INVALIDARG
;
2070 RegisteredClass
*curClass
;
2073 TRACE("(%08x)\n",dwRegister
);
2075 apt
= COM_CurrentApt();
2078 ERR("COM was not initialized\n");
2079 return CO_E_NOTINITIALIZED
;
2082 EnterCriticalSection( &csRegisteredClassList
);
2084 LIST_FOR_EACH_ENTRY(curClass
, &RegisteredClassList
, RegisteredClass
, entry
)
2087 * Check if we have a match on the cookie.
2089 if (curClass
->dwCookie
== dwRegister
)
2091 if (curClass
->apartment_id
== apt
->oxid
)
2093 COM_RevokeRegisteredClassObject(curClass
);
2098 ERR("called from wrong apartment, should be called from %s\n",
2099 wine_dbgstr_longlong(curClass
->apartment_id
));
2100 hr
= RPC_E_WRONG_THREAD
;
2106 LeaveCriticalSection( &csRegisteredClassList
);
2111 /***********************************************************************
2112 * COM_RegReadPath [internal]
2114 * Reads a registry value and expands it when necessary
2116 static DWORD
COM_RegReadPath(HKEY hkeyroot
, const WCHAR
*keyname
, const WCHAR
*valuename
, WCHAR
* dst
, DWORD dstlen
)
2121 WCHAR src
[MAX_PATH
];
2122 DWORD dwLength
= dstlen
* sizeof(WCHAR
);
2124 if((ret
= RegOpenKeyExW(hkeyroot
, keyname
, 0, KEY_READ
, &key
)) == ERROR_SUCCESS
) {
2125 if( (ret
= RegQueryValueExW(key
, NULL
, NULL
, &keytype
, (LPBYTE
)src
, &dwLength
)) == ERROR_SUCCESS
) {
2126 if (keytype
== REG_EXPAND_SZ
) {
2127 if (dstlen
<= ExpandEnvironmentStringsW(src
, dst
, dstlen
)) ret
= ERROR_MORE_DATA
;
2129 lstrcpynW(dst
, src
, dstlen
);
2137 static void get_threading_model(HKEY key
, LPWSTR value
, DWORD len
)
2139 static const WCHAR wszThreadingModel
[] = {'T','h','r','e','a','d','i','n','g','M','o','d','e','l',0};
2142 DWORD dwLength
= len
* sizeof(WCHAR
);
2144 ret
= RegQueryValueExW(key
, wszThreadingModel
, NULL
, &keytype
, (LPBYTE
)value
, &dwLength
);
2145 if ((ret
!= ERROR_SUCCESS
) || (keytype
!= REG_SZ
))
2149 static HRESULT
get_inproc_class_object(APARTMENT
*apt
, HKEY hkeydll
,
2150 REFCLSID rclsid
, REFIID riid
,
2151 BOOL hostifnecessary
, void **ppv
)
2153 WCHAR dllpath
[MAX_PATH
+1];
2154 BOOL apartment_threaded
;
2156 if (hostifnecessary
)
2158 static const WCHAR wszApartment
[] = {'A','p','a','r','t','m','e','n','t',0};
2159 static const WCHAR wszFree
[] = {'F','r','e','e',0};
2160 static const WCHAR wszBoth
[] = {'B','o','t','h',0};
2161 WCHAR threading_model
[10 /* strlenW(L"apartment")+1 */];
2163 get_threading_model(hkeydll
, threading_model
, ARRAYSIZE(threading_model
));
2165 if (!strcmpiW(threading_model
, wszApartment
))
2167 apartment_threaded
= TRUE
;
2168 if (apt
->multi_threaded
)
2169 return apartment_hostobject_in_hostapt(apt
, FALSE
, FALSE
, hkeydll
, rclsid
, riid
, ppv
);
2172 else if (!strcmpiW(threading_model
, wszFree
))
2174 apartment_threaded
= FALSE
;
2175 if (!apt
->multi_threaded
)
2176 return apartment_hostobject_in_hostapt(apt
, TRUE
, FALSE
, hkeydll
, rclsid
, riid
, ppv
);
2178 /* everything except "Apartment", "Free" and "Both" */
2179 else if (strcmpiW(threading_model
, wszBoth
))
2181 apartment_threaded
= TRUE
;
2182 /* everything else is main-threaded */
2183 if (threading_model
[0])
2184 FIXME("unrecognised threading model %s for object %s, should be main-threaded?\n",
2185 debugstr_w(threading_model
), debugstr_guid(rclsid
));
2187 if (apt
->multi_threaded
|| !apt
->main
)
2188 return apartment_hostobject_in_hostapt(apt
, FALSE
, TRUE
, hkeydll
, rclsid
, riid
, ppv
);
2191 apartment_threaded
= FALSE
;
2194 apartment_threaded
= !apt
->multi_threaded
;
2196 if (COM_RegReadPath(hkeydll
, NULL
, NULL
, dllpath
, ARRAYSIZE(dllpath
)) != ERROR_SUCCESS
)
2198 /* failure: CLSID is not found in registry */
2199 WARN("class %s not registered inproc\n", debugstr_guid(rclsid
));
2200 return REGDB_E_CLASSNOTREG
;
2203 return apartment_getclassobject(apt
, dllpath
, apartment_threaded
,
2207 /***********************************************************************
2208 * CoGetClassObject [OLE32.@]
2210 * Creates an object of the specified class.
2213 * rclsid [I] Class ID to create an instance of.
2214 * dwClsContext [I] Flags to restrict the location of the created instance.
2215 * pServerInfo [I] Optional. Details for connecting to a remote server.
2216 * iid [I] The ID of the interface of the instance to return.
2217 * ppv [O] On returns, contains a pointer to the specified interface of the object.
2221 * Failure: HRESULT code.
2224 * The dwClsContext parameter can be one or more of the following:
2225 *| CLSCTX_INPROC_SERVER - Use an in-process server, such as from a DLL.
2226 *| CLSCTX_INPROC_HANDLER - Use an in-process object which handles certain functions for an object running in another process.
2227 *| CLSCTX_LOCAL_SERVER - Connect to an object running in another process.
2228 *| CLSCTX_REMOTE_SERVER - Connect to an object running on another machine.
2231 * CoCreateInstance()
2233 HRESULT WINAPI
CoGetClassObject(
2234 REFCLSID rclsid
, DWORD dwClsContext
, COSERVERINFO
*pServerInfo
,
2235 REFIID iid
, LPVOID
*ppv
)
2237 LPUNKNOWN regClassObject
;
2238 HRESULT hres
= E_UNEXPECTED
;
2241 TRACE("\n\tCLSID:\t%s,\n\tIID:\t%s\n", debugstr_guid(rclsid
), debugstr_guid(iid
));
2244 return E_INVALIDARG
;
2248 apt
= COM_CurrentApt();
2251 ERR("apartment not initialised\n");
2252 return CO_E_NOTINITIALIZED
;
2256 FIXME("\tpServerInfo: name=%s\n",debugstr_w(pServerInfo
->pwszName
));
2257 FIXME("\t\tpAuthInfo=%p\n",pServerInfo
->pAuthInfo
);
2261 * First, try and see if we can't match the class ID with one of the
2262 * registered classes.
2264 if (S_OK
== COM_GetRegisteredClassObject(apt
, rclsid
, dwClsContext
,
2267 /* Get the required interface from the retrieved pointer. */
2268 hres
= IUnknown_QueryInterface(regClassObject
, iid
, ppv
);
2271 * Since QI got another reference on the pointer, we want to release the
2272 * one we already have. If QI was unsuccessful, this will release the object. This
2273 * is good since we are not returning it in the "out" parameter.
2275 IUnknown_Release(regClassObject
);
2280 /* First try in-process server */
2281 if (CLSCTX_INPROC_SERVER
& dwClsContext
)
2283 static const WCHAR wszInprocServer32
[] = {'I','n','p','r','o','c','S','e','r','v','e','r','3','2',0};
2286 if (IsEqualCLSID(rclsid
, &CLSID_InProcFreeMarshaler
))
2287 return FTMarshalCF_Create(iid
, ppv
);
2289 hres
= COM_OpenKeyForCLSID(rclsid
, wszInprocServer32
, KEY_READ
, &hkey
);
2292 if (hres
== REGDB_E_CLASSNOTREG
)
2293 ERR("class %s not registered\n", debugstr_guid(rclsid
));
2294 else if (hres
== REGDB_E_KEYMISSING
)
2296 WARN("class %s not registered as in-proc server\n", debugstr_guid(rclsid
));
2297 hres
= REGDB_E_CLASSNOTREG
;
2301 if (SUCCEEDED(hres
))
2303 hres
= get_inproc_class_object(apt
, hkey
, rclsid
, iid
,
2304 !(dwClsContext
& WINE_CLSCTX_DONT_HOST
), ppv
);
2308 /* return if we got a class, otherwise fall through to one of the
2310 if (SUCCEEDED(hres
))
2314 /* Next try in-process handler */
2315 if (CLSCTX_INPROC_HANDLER
& dwClsContext
)
2317 static const WCHAR wszInprocHandler32
[] = {'I','n','p','r','o','c','H','a','n','d','l','e','r','3','2',0};
2320 hres
= COM_OpenKeyForCLSID(rclsid
, wszInprocHandler32
, KEY_READ
, &hkey
);
2323 if (hres
== REGDB_E_CLASSNOTREG
)
2324 ERR("class %s not registered\n", debugstr_guid(rclsid
));
2325 else if (hres
== REGDB_E_KEYMISSING
)
2327 WARN("class %s not registered in-proc handler\n", debugstr_guid(rclsid
));
2328 hres
= REGDB_E_CLASSNOTREG
;
2332 if (SUCCEEDED(hres
))
2334 hres
= get_inproc_class_object(apt
, hkey
, rclsid
, iid
,
2335 !(dwClsContext
& WINE_CLSCTX_DONT_HOST
), ppv
);
2339 /* return if we got a class, otherwise fall through to one of the
2341 if (SUCCEEDED(hres
))
2345 /* Next try out of process */
2346 if (CLSCTX_LOCAL_SERVER
& dwClsContext
)
2348 hres
= RPC_GetLocalClassObject(rclsid
,iid
,ppv
);
2349 if (SUCCEEDED(hres
))
2353 /* Finally try remote: this requires networked DCOM (a lot of work) */
2354 if (CLSCTX_REMOTE_SERVER
& dwClsContext
)
2356 FIXME ("CLSCTX_REMOTE_SERVER not supported\n");
2357 hres
= E_NOINTERFACE
;
2361 ERR("no class object %s could be created for context 0x%x\n",
2362 debugstr_guid(rclsid
), dwClsContext
);
2366 /***********************************************************************
2367 * CoResumeClassObjects (OLE32.@)
2369 * Resumes all class objects registered with REGCLS_SUSPENDED.
2373 * Failure: HRESULT code.
2375 HRESULT WINAPI
CoResumeClassObjects(void)
2381 /***********************************************************************
2382 * CoCreateInstance [OLE32.@]
2384 * Creates an instance of the specified class.
2387 * rclsid [I] Class ID to create an instance of.
2388 * pUnkOuter [I] Optional outer unknown to allow aggregation with another object.
2389 * dwClsContext [I] Flags to restrict the location of the created instance.
2390 * iid [I] The ID of the interface of the instance to return.
2391 * ppv [O] On returns, contains a pointer to the specified interface of the instance.
2395 * Failure: HRESULT code.
2398 * The dwClsContext parameter can be one or more of the following:
2399 *| CLSCTX_INPROC_SERVER - Use an in-process server, such as from a DLL.
2400 *| CLSCTX_INPROC_HANDLER - Use an in-process object which handles certain functions for an object running in another process.
2401 *| CLSCTX_LOCAL_SERVER - Connect to an object running in another process.
2402 *| CLSCTX_REMOTE_SERVER - Connect to an object running on another machine.
2404 * Aggregation is the concept of deferring the IUnknown of an object to another
2405 * object. This allows a separate object to behave as though it was part of
2406 * the object and to allow this the pUnkOuter parameter can be set. Note that
2407 * not all objects support having an outer of unknown.
2410 * CoGetClassObject()
2412 HRESULT WINAPI
CoCreateInstance(
2414 LPUNKNOWN pUnkOuter
,
2420 LPCLASSFACTORY lpclf
= 0;
2422 TRACE("(rclsid=%s, pUnkOuter=%p, dwClsContext=%08x, riid=%s, ppv=%p)\n", debugstr_guid(rclsid
),
2423 pUnkOuter
, dwClsContext
, debugstr_guid(iid
), ppv
);
2432 * Initialize the "out" parameter
2436 if (!COM_CurrentApt())
2438 ERR("apartment not initialised\n");
2439 return CO_E_NOTINITIALIZED
;
2443 * The Standard Global Interface Table (GIT) object is a process-wide singleton.
2444 * Rather than create a class factory, we can just check for it here
2446 if (IsEqualIID(rclsid
, &CLSID_StdGlobalInterfaceTable
)) {
2447 if (StdGlobalInterfaceTableInstance
== NULL
)
2448 StdGlobalInterfaceTableInstance
= StdGlobalInterfaceTable_Construct();
2449 hres
= IGlobalInterfaceTable_QueryInterface( (IGlobalInterfaceTable
*) StdGlobalInterfaceTableInstance
, iid
, ppv
);
2450 if (hres
) return hres
;
2452 TRACE("Retrieved GIT (%p)\n", *ppv
);
2457 * Get a class factory to construct the object we want.
2459 hres
= CoGetClassObject(rclsid
,
2469 * Create the object and don't forget to release the factory
2471 hres
= IClassFactory_CreateInstance(lpclf
, pUnkOuter
, iid
, ppv
);
2472 IClassFactory_Release(lpclf
);
2475 if (hres
== CLASS_E_NOAGGREGATION
&& pUnkOuter
)
2476 FIXME("Class %s does not support aggregation\n", debugstr_guid(rclsid
));
2478 FIXME("no instance created for interface %s of class %s, hres is 0x%08x\n", debugstr_guid(iid
), debugstr_guid(rclsid
),hres
);
2484 /***********************************************************************
2485 * CoCreateInstanceEx [OLE32.@]
2487 HRESULT WINAPI
CoCreateInstanceEx(
2489 LPUNKNOWN pUnkOuter
,
2491 COSERVERINFO
* pServerInfo
,
2495 IUnknown
* pUnk
= NULL
;
2498 ULONG successCount
= 0;
2503 if ( (cmq
==0) || (pResults
==NULL
))
2504 return E_INVALIDARG
;
2506 if (pServerInfo
!=NULL
)
2507 FIXME("() non-NULL pServerInfo not supported!\n");
2510 * Initialize all the "out" parameters.
2512 for (index
= 0; index
< cmq
; index
++)
2514 pResults
[index
].pItf
= NULL
;
2515 pResults
[index
].hr
= E_NOINTERFACE
;
2519 * Get the object and get its IUnknown pointer.
2521 hr
= CoCreateInstance(rclsid
,
2531 * Then, query for all the interfaces requested.
2533 for (index
= 0; index
< cmq
; index
++)
2535 pResults
[index
].hr
= IUnknown_QueryInterface(pUnk
,
2536 pResults
[index
].pIID
,
2537 (VOID
**)&(pResults
[index
].pItf
));
2539 if (pResults
[index
].hr
== S_OK
)
2544 * Release our temporary unknown pointer.
2546 IUnknown_Release(pUnk
);
2548 if (successCount
== 0)
2549 return E_NOINTERFACE
;
2551 if (successCount
!=cmq
)
2552 return CO_S_NOTALLINTERFACES
;
2557 /***********************************************************************
2558 * CoLoadLibrary (OLE32.@)
2563 * lpszLibName [I] Path to library.
2564 * bAutoFree [I] Whether the library should automatically be freed.
2567 * Success: Handle to loaded library.
2571 * CoFreeLibrary, CoFreeAllLibraries, CoFreeUnusedLibraries
2573 HINSTANCE WINAPI
CoLoadLibrary(LPOLESTR lpszLibName
, BOOL bAutoFree
)
2575 TRACE("(%s, %d)\n", debugstr_w(lpszLibName
), bAutoFree
);
2577 return LoadLibraryExW(lpszLibName
, 0, LOAD_WITH_ALTERED_SEARCH_PATH
);
2580 /***********************************************************************
2581 * CoFreeLibrary [OLE32.@]
2583 * Unloads a library from memory.
2586 * hLibrary [I] Handle to library to unload.
2592 * CoLoadLibrary, CoFreeAllLibraries, CoFreeUnusedLibraries
2594 void WINAPI
CoFreeLibrary(HINSTANCE hLibrary
)
2596 FreeLibrary(hLibrary
);
2600 /***********************************************************************
2601 * CoFreeAllLibraries [OLE32.@]
2603 * Function for backwards compatibility only. Does nothing.
2609 * CoLoadLibrary, CoFreeLibrary, CoFreeUnusedLibraries
2611 void WINAPI
CoFreeAllLibraries(void)
2616 /***********************************************************************
2617 * CoFreeUnusedLibrariesEx [OLE32.@]
2619 * Frees any previously unused libraries whose delay has expired and marks
2620 * currently unused libraries for unloading. Unused are identified as those that
2621 * return S_OK from their DllCanUnloadNow function.
2624 * dwUnloadDelay [I] Unload delay in milliseconds.
2625 * dwReserved [I] Reserved. Set to 0.
2631 * CoLoadLibrary, CoFreeAllLibraries, CoFreeLibrary
2633 void WINAPI
CoFreeUnusedLibrariesEx(DWORD dwUnloadDelay
, DWORD dwReserved
)
2635 struct apartment
*apt
= COM_CurrentApt();
2638 ERR("apartment not initialised\n");
2642 apartment_freeunusedlibraries(apt
, dwUnloadDelay
);
2645 /***********************************************************************
2646 * CoFreeUnusedLibraries [OLE32.@]
2648 * Frees any unused libraries. Unused are identified as those that return
2649 * S_OK from their DllCanUnloadNow function.
2655 * CoLoadLibrary, CoFreeAllLibraries, CoFreeLibrary
2657 void WINAPI
CoFreeUnusedLibraries(void)
2659 CoFreeUnusedLibrariesEx(INFINITE
, 0);
2662 /***********************************************************************
2663 * CoFileTimeNow [OLE32.@]
2665 * Retrieves the current time in FILETIME format.
2668 * lpFileTime [O] The current time.
2673 HRESULT WINAPI
CoFileTimeNow( FILETIME
*lpFileTime
)
2675 GetSystemTimeAsFileTime( lpFileTime
);
2679 /******************************************************************************
2680 * CoLockObjectExternal [OLE32.@]
2682 * Increments or decrements the external reference count of a stub object.
2685 * pUnk [I] Stub object.
2686 * fLock [I] If TRUE then increments the external ref-count,
2687 * otherwise decrements.
2688 * fLastUnlockReleases [I] If TRUE then the last unlock has the effect of
2689 * calling CoDisconnectObject.
2693 * Failure: HRESULT code.
2696 * If fLock is TRUE and an object is passed in that doesn't have a stub
2697 * manager then a new stub manager is created for the object.
2699 HRESULT WINAPI
CoLockObjectExternal(
2702 BOOL fLastUnlockReleases
)
2704 struct stub_manager
*stubmgr
;
2705 struct apartment
*apt
;
2707 TRACE("pUnk=%p, fLock=%s, fLastUnlockReleases=%s\n",
2708 pUnk
, fLock
? "TRUE" : "FALSE", fLastUnlockReleases
? "TRUE" : "FALSE");
2710 apt
= COM_CurrentApt();
2711 if (!apt
) return CO_E_NOTINITIALIZED
;
2713 stubmgr
= get_stub_manager_from_object(apt
, pUnk
);
2718 stub_manager_ext_addref(stubmgr
, 1, FALSE
);
2720 stub_manager_ext_release(stubmgr
, 1, FALSE
, fLastUnlockReleases
);
2722 stub_manager_int_release(stubmgr
);
2728 stubmgr
= new_stub_manager(apt
, pUnk
);
2732 stub_manager_ext_addref(stubmgr
, 1, FALSE
);
2733 stub_manager_int_release(stubmgr
);
2740 WARN("stub object not found %p\n", pUnk
);
2741 /* Note: native is pretty broken here because it just silently
2742 * fails, without returning an appropriate error code, making apps
2743 * think that the object was disconnected, when it actually wasn't */
2748 /***********************************************************************
2749 * CoInitializeWOW (OLE32.@)
2751 * WOW equivalent of CoInitialize?
2760 HRESULT WINAPI
CoInitializeWOW(DWORD x
,DWORD y
)
2762 FIXME("(0x%08x,0x%08x),stub!\n",x
,y
);
2766 /***********************************************************************
2767 * CoGetState [OLE32.@]
2769 * Retrieves the thread state object previously stored by CoSetState().
2772 * ppv [I] Address where pointer to object will be stored.
2776 * Failure: E_OUTOFMEMORY.
2779 * Crashes on all invalid ppv addresses, including NULL.
2780 * If the function returns a non-NULL object then the caller must release its
2781 * reference on the object when the object is no longer required.
2786 HRESULT WINAPI
CoGetState(IUnknown
** ppv
)
2788 struct oletls
*info
= COM_CurrentInfo();
2789 if (!info
) return E_OUTOFMEMORY
;
2795 IUnknown_AddRef(info
->state
);
2797 TRACE("apt->state=%p\n", info
->state
);
2803 /***********************************************************************
2804 * CoSetState [OLE32.@]
2806 * Sets the thread state object.
2809 * pv [I] Pointer to state object to be stored.
2812 * The system keeps a reference on the object while the object stored.
2816 * Failure: E_OUTOFMEMORY.
2818 HRESULT WINAPI
CoSetState(IUnknown
* pv
)
2820 struct oletls
*info
= COM_CurrentInfo();
2821 if (!info
) return E_OUTOFMEMORY
;
2823 if (pv
) IUnknown_AddRef(pv
);
2827 TRACE("-- release %p now\n", info
->state
);
2828 IUnknown_Release(info
->state
);
2837 /******************************************************************************
2838 * CoTreatAsClass [OLE32.@]
2840 * Sets the TreatAs value of a class.
2843 * clsidOld [I] Class to set TreatAs value on.
2844 * clsidNew [I] The class the clsidOld should be treated as.
2848 * Failure: HRESULT code.
2853 HRESULT WINAPI
CoTreatAsClass(REFCLSID clsidOld
, REFCLSID clsidNew
)
2855 static const WCHAR wszAutoTreatAs
[] = {'A','u','t','o','T','r','e','a','t','A','s',0};
2856 static const WCHAR wszTreatAs
[] = {'T','r','e','a','t','A','s',0};
2858 WCHAR szClsidNew
[CHARS_IN_GUID
];
2860 WCHAR auto_treat_as
[CHARS_IN_GUID
];
2861 LONG auto_treat_as_size
= sizeof(auto_treat_as
);
2864 res
= COM_OpenKeyForCLSID(clsidOld
, NULL
, KEY_READ
| KEY_WRITE
, &hkey
);
2867 if (!memcmp( clsidOld
, clsidNew
, sizeof(*clsidOld
) ))
2869 if (!RegQueryValueW(hkey
, wszAutoTreatAs
, auto_treat_as
, &auto_treat_as_size
) &&
2870 CLSIDFromString(auto_treat_as
, &id
) == S_OK
)
2872 if (RegSetValueW(hkey
, wszTreatAs
, REG_SZ
, auto_treat_as
, sizeof(auto_treat_as
)))
2874 res
= REGDB_E_WRITEREGDB
;
2880 RegDeleteKeyW(hkey
, wszTreatAs
);
2884 else if (!StringFromGUID2(clsidNew
, szClsidNew
, ARRAYSIZE(szClsidNew
)) &&
2885 !RegSetValueW(hkey
, wszTreatAs
, REG_SZ
, szClsidNew
, sizeof(szClsidNew
)))
2887 res
= REGDB_E_WRITEREGDB
;
2892 if (hkey
) RegCloseKey(hkey
);
2896 /******************************************************************************
2897 * CoGetTreatAsClass [OLE32.@]
2899 * Gets the TreatAs value of a class.
2902 * clsidOld [I] Class to get the TreatAs value of.
2903 * clsidNew [I] The class the clsidOld should be treated as.
2907 * Failure: HRESULT code.
2912 HRESULT WINAPI
CoGetTreatAsClass(REFCLSID clsidOld
, LPCLSID clsidNew
)
2914 static const WCHAR wszTreatAs
[] = {'T','r','e','a','t','A','s',0};
2916 WCHAR szClsidNew
[CHARS_IN_GUID
];
2918 LONG len
= sizeof(szClsidNew
);
2920 FIXME("(%s,%p)\n", debugstr_guid(clsidOld
), clsidNew
);
2921 *clsidNew
= *clsidOld
; /* copy over old value */
2923 res
= COM_OpenKeyForCLSID(clsidOld
, wszTreatAs
, KEY_READ
, &hkey
);
2926 if (RegQueryValueW(hkey
, NULL
, szClsidNew
, &len
))
2931 res
= CLSIDFromString(szClsidNew
,clsidNew
);
2933 ERR("Failed CLSIDFromStringA(%s), hres 0x%08x\n", debugstr_w(szClsidNew
), res
);
2935 if (hkey
) RegCloseKey(hkey
);
2939 /******************************************************************************
2940 * CoGetCurrentProcess [OLE32.@]
2942 * Gets the current process ID.
2945 * The current process ID.
2948 * Is DWORD really the correct return type for this function?
2950 DWORD WINAPI
CoGetCurrentProcess(void)
2952 return GetCurrentProcessId();
2955 /******************************************************************************
2956 * CoRegisterMessageFilter [OLE32.@]
2958 * Registers a message filter.
2961 * lpMessageFilter [I] Pointer to interface.
2962 * lplpMessageFilter [O] Indirect pointer to prior instance if non-NULL.
2966 * Failure: HRESULT code.
2969 * Both lpMessageFilter and lplpMessageFilter are optional. Passing in a NULL
2970 * lpMessageFilter removes the message filter.
2972 * If lplpMessageFilter is not NULL the previous message filter will be
2973 * returned in the memory pointer to this parameter and the caller is
2974 * responsible for releasing the object.
2976 * The current thread be in an apartment otherwise the function will crash.
2978 HRESULT WINAPI
CoRegisterMessageFilter(
2979 LPMESSAGEFILTER lpMessageFilter
,
2980 LPMESSAGEFILTER
*lplpMessageFilter
)
2982 struct apartment
*apt
;
2983 IMessageFilter
*lpOldMessageFilter
;
2985 TRACE("(%p, %p)\n", lpMessageFilter
, lplpMessageFilter
);
2987 apt
= COM_CurrentApt();
2989 /* can't set a message filter in a multi-threaded apartment */
2990 if (!apt
|| apt
->multi_threaded
)
2992 WARN("can't set message filter in MTA or uninitialized apt\n");
2993 return CO_E_NOT_SUPPORTED
;
2996 if (lpMessageFilter
)
2997 IMessageFilter_AddRef(lpMessageFilter
);
2999 EnterCriticalSection(&apt
->cs
);
3001 lpOldMessageFilter
= apt
->filter
;
3002 apt
->filter
= lpMessageFilter
;
3004 LeaveCriticalSection(&apt
->cs
);
3006 if (lplpMessageFilter
)
3007 *lplpMessageFilter
= lpOldMessageFilter
;
3008 else if (lpOldMessageFilter
)
3009 IMessageFilter_Release(lpOldMessageFilter
);
3014 /***********************************************************************
3015 * CoIsOle1Class [OLE32.@]
3017 * Determines whether the specified class an OLE v1 class.
3020 * clsid [I] Class to test.
3023 * TRUE if the class is an OLE v1 class, or FALSE otherwise.
3025 BOOL WINAPI
CoIsOle1Class(REFCLSID clsid
)
3027 FIXME("%s\n", debugstr_guid(clsid
));
3031 /***********************************************************************
3032 * IsEqualGUID [OLE32.@]
3034 * Compares two Unique Identifiers.
3037 * rguid1 [I] The first GUID to compare.
3038 * rguid2 [I] The other GUID to compare.
3044 BOOL WINAPI
IsEqualGUID(
3048 return !memcmp(rguid1
,rguid2
,sizeof(GUID
));
3051 /***********************************************************************
3052 * CoInitializeSecurity [OLE32.@]
3054 HRESULT WINAPI
CoInitializeSecurity(PSECURITY_DESCRIPTOR pSecDesc
, LONG cAuthSvc
,
3055 SOLE_AUTHENTICATION_SERVICE
* asAuthSvc
,
3056 void* pReserved1
, DWORD dwAuthnLevel
,
3057 DWORD dwImpLevel
, void* pReserved2
,
3058 DWORD dwCapabilities
, void* pReserved3
)
3060 FIXME("(%p,%d,%p,%p,%d,%d,%p,%d,%p) - stub!\n", pSecDesc
, cAuthSvc
,
3061 asAuthSvc
, pReserved1
, dwAuthnLevel
, dwImpLevel
, pReserved2
,
3062 dwCapabilities
, pReserved3
);
3066 /***********************************************************************
3067 * CoSuspendClassObjects [OLE32.@]
3069 * Suspends all registered class objects to prevent further requests coming in
3070 * for those objects.
3074 * Failure: HRESULT code.
3076 HRESULT WINAPI
CoSuspendClassObjects(void)
3082 /***********************************************************************
3083 * CoAddRefServerProcess [OLE32.@]
3085 * Helper function for incrementing the reference count of a local-server
3089 * New reference count.
3092 * CoReleaseServerProcess().
3094 ULONG WINAPI
CoAddRefServerProcess(void)
3100 EnterCriticalSection(&csRegisteredClassList
);
3101 refs
= ++s_COMServerProcessReferences
;
3102 LeaveCriticalSection(&csRegisteredClassList
);
3104 TRACE("refs before: %d\n", refs
- 1);
3109 /***********************************************************************
3110 * CoReleaseServerProcess [OLE32.@]
3112 * Helper function for decrementing the reference count of a local-server
3116 * New reference count.
3119 * When reference count reaches 0, this function suspends all registered
3120 * classes so no new connections are accepted.
3123 * CoAddRefServerProcess(), CoSuspendClassObjects().
3125 ULONG WINAPI
CoReleaseServerProcess(void)
3131 EnterCriticalSection(&csRegisteredClassList
);
3133 refs
= --s_COMServerProcessReferences
;
3134 /* FIXME: if (!refs) COM_SuspendClassObjects(); */
3136 LeaveCriticalSection(&csRegisteredClassList
);
3138 TRACE("refs after: %d\n", refs
);
3143 /***********************************************************************
3144 * CoIsHandlerConnected [OLE32.@]
3146 * Determines whether a proxy is connected to a remote stub.
3149 * pUnk [I] Pointer to object that may or may not be connected.
3152 * TRUE if pUnk is not a proxy or if pUnk is connected to a remote stub, or
3155 BOOL WINAPI
CoIsHandlerConnected(IUnknown
*pUnk
)
3157 FIXME("%p\n", pUnk
);
3162 /***********************************************************************
3163 * CoAllowSetForegroundWindow [OLE32.@]
3166 HRESULT WINAPI
CoAllowSetForegroundWindow(IUnknown
*pUnk
, void *pvReserved
)
3168 FIXME("(%p, %p): stub\n", pUnk
, pvReserved
);
3172 /***********************************************************************
3173 * CoQueryProxyBlanket [OLE32.@]
3175 * Retrieves the security settings being used by a proxy.
3178 * pProxy [I] Pointer to the proxy object.
3179 * pAuthnSvc [O] The type of authentication service.
3180 * pAuthzSvc [O] The type of authorization service.
3181 * ppServerPrincName [O] Optional. The server prinicple name.
3182 * pAuthnLevel [O] The authentication level.
3183 * pImpLevel [O] The impersonation level.
3184 * ppAuthInfo [O] Information specific to the authorization/authentication service.
3185 * pCapabilities [O] Flags affecting the security behaviour.
3189 * Failure: HRESULT code.
3192 * CoCopyProxy, CoSetProxyBlanket.
3194 HRESULT WINAPI
CoQueryProxyBlanket(IUnknown
*pProxy
, DWORD
*pAuthnSvc
,
3195 DWORD
*pAuthzSvc
, OLECHAR
**ppServerPrincName
, DWORD
*pAuthnLevel
,
3196 DWORD
*pImpLevel
, void **ppAuthInfo
, DWORD
*pCapabilities
)
3198 IClientSecurity
*pCliSec
;
3201 TRACE("%p\n", pProxy
);
3203 hr
= IUnknown_QueryInterface(pProxy
, &IID_IClientSecurity
, (void **)&pCliSec
);
3206 hr
= IClientSecurity_QueryBlanket(pCliSec
, pProxy
, pAuthnSvc
,
3207 pAuthzSvc
, ppServerPrincName
,
3208 pAuthnLevel
, pImpLevel
, ppAuthInfo
,
3210 IClientSecurity_Release(pCliSec
);
3213 if (FAILED(hr
)) ERR("-- failed with 0x%08x\n", hr
);
3217 /***********************************************************************
3218 * CoSetProxyBlanket [OLE32.@]
3220 * Sets the security settings for a proxy.
3223 * pProxy [I] Pointer to the proxy object.
3224 * AuthnSvc [I] The type of authentication service.
3225 * AuthzSvc [I] The type of authorization service.
3226 * pServerPrincName [I] The server prinicple name.
3227 * AuthnLevel [I] The authentication level.
3228 * ImpLevel [I] The impersonation level.
3229 * pAuthInfo [I] Information specific to the authorization/authentication service.
3230 * Capabilities [I] Flags affecting the security behaviour.
3234 * Failure: HRESULT code.
3237 * CoQueryProxyBlanket, CoCopyProxy.
3239 HRESULT WINAPI
CoSetProxyBlanket(IUnknown
*pProxy
, DWORD AuthnSvc
,
3240 DWORD AuthzSvc
, OLECHAR
*pServerPrincName
, DWORD AuthnLevel
,
3241 DWORD ImpLevel
, void *pAuthInfo
, DWORD Capabilities
)
3243 IClientSecurity
*pCliSec
;
3246 TRACE("%p\n", pProxy
);
3248 hr
= IUnknown_QueryInterface(pProxy
, &IID_IClientSecurity
, (void **)&pCliSec
);
3251 hr
= IClientSecurity_SetBlanket(pCliSec
, pProxy
, AuthnSvc
,
3252 AuthzSvc
, pServerPrincName
,
3253 AuthnLevel
, ImpLevel
, pAuthInfo
,
3255 IClientSecurity_Release(pCliSec
);
3258 if (FAILED(hr
)) ERR("-- failed with 0x%08x\n", hr
);
3262 /***********************************************************************
3263 * CoCopyProxy [OLE32.@]
3268 * pProxy [I] Pointer to the proxy object.
3269 * ppCopy [O] Copy of the proxy.
3273 * Failure: HRESULT code.
3276 * CoQueryProxyBlanket, CoSetProxyBlanket.
3278 HRESULT WINAPI
CoCopyProxy(IUnknown
*pProxy
, IUnknown
**ppCopy
)
3280 IClientSecurity
*pCliSec
;
3283 TRACE("%p\n", pProxy
);
3285 hr
= IUnknown_QueryInterface(pProxy
, &IID_IClientSecurity
, (void **)&pCliSec
);
3288 hr
= IClientSecurity_CopyProxy(pCliSec
, pProxy
, ppCopy
);
3289 IClientSecurity_Release(pCliSec
);
3292 if (FAILED(hr
)) ERR("-- failed with 0x%08x\n", hr
);
3297 /***********************************************************************
3298 * CoGetCallContext [OLE32.@]
3300 * Gets the context of the currently executing server call in the current
3304 * riid [I] Context interface to return.
3305 * ppv [O] Pointer to memory that will receive the context on return.
3309 * Failure: HRESULT code.
3311 HRESULT WINAPI
CoGetCallContext(REFIID riid
, void **ppv
)
3313 struct oletls
*info
= COM_CurrentInfo();
3315 TRACE("(%s, %p)\n", debugstr_guid(riid
), ppv
);
3318 return E_OUTOFMEMORY
;
3320 if (!info
->call_state
)
3321 return RPC_E_CALL_COMPLETE
;
3323 return IUnknown_QueryInterface(info
->call_state
, riid
, ppv
);
3326 /***********************************************************************
3327 * CoSwitchCallContext [OLE32.@]
3329 * Switches the context of the currently executing server call in the current
3333 * pObject [I] Pointer to new context object
3334 * ppOldObject [O] Pointer to memory that will receive old context object pointer
3338 * Failure: HRESULT code.
3340 HRESULT WINAPI
CoSwitchCallContext(IUnknown
*pObject
, IUnknown
**ppOldObject
)
3342 struct oletls
*info
= COM_CurrentInfo();
3344 TRACE("(%p, %p)\n", pObject
, ppOldObject
);
3347 return E_OUTOFMEMORY
;
3349 *ppOldObject
= info
->call_state
;
3350 info
->call_state
= pObject
; /* CoSwitchCallContext does not addref nor release objects */
3355 /***********************************************************************
3356 * CoQueryClientBlanket [OLE32.@]
3358 * Retrieves the authentication information about the client of the currently
3359 * executing server call in the current thread.
3362 * pAuthnSvc [O] Optional. The type of authentication service.
3363 * pAuthzSvc [O] Optional. The type of authorization service.
3364 * pServerPrincName [O] Optional. The server prinicple name.
3365 * pAuthnLevel [O] Optional. The authentication level.
3366 * pImpLevel [O] Optional. The impersonation level.
3367 * pPrivs [O] Optional. Information about the privileges of the client.
3368 * pCapabilities [IO] Optional. Flags affecting the security behaviour.
3372 * Failure: HRESULT code.
3375 * CoImpersonateClient, CoRevertToSelf, CoGetCallContext.
3377 HRESULT WINAPI
CoQueryClientBlanket(
3380 OLECHAR
**pServerPrincName
,
3383 RPC_AUTHZ_HANDLE
*pPrivs
,
3384 DWORD
*pCapabilities
)
3386 IServerSecurity
*pSrvSec
;
3389 TRACE("(%p, %p, %p, %p, %p, %p, %p)\n",
3390 pAuthnSvc
, pAuthzSvc
, pServerPrincName
, pAuthnLevel
, pImpLevel
,
3391 pPrivs
, pCapabilities
);
3393 hr
= CoGetCallContext(&IID_IServerSecurity
, (void **)&pSrvSec
);
3396 hr
= IServerSecurity_QueryBlanket(
3397 pSrvSec
, pAuthnSvc
, pAuthzSvc
, pServerPrincName
, pAuthnLevel
,
3398 pImpLevel
, pPrivs
, pCapabilities
);
3399 IServerSecurity_Release(pSrvSec
);
3405 /***********************************************************************
3406 * CoImpersonateClient [OLE32.@]
3408 * Impersonates the client of the currently executing server call in the
3416 * Failure: HRESULT code.
3419 * If this function fails then the current thread will not be impersonating
3420 * the client and all actions will take place on behalf of the server.
3421 * Therefore, it is important to check the return value from this function.
3424 * CoRevertToSelf, CoQueryClientBlanket, CoGetCallContext.
3426 HRESULT WINAPI
CoImpersonateClient(void)
3428 IServerSecurity
*pSrvSec
;
3433 hr
= CoGetCallContext(&IID_IServerSecurity
, (void **)&pSrvSec
);
3436 hr
= IServerSecurity_ImpersonateClient(pSrvSec
);
3437 IServerSecurity_Release(pSrvSec
);
3443 /***********************************************************************
3444 * CoRevertToSelf [OLE32.@]
3446 * Ends the impersonation of the client of the currently executing server
3447 * call in the current thread.
3454 * Failure: HRESULT code.
3457 * CoImpersonateClient, CoQueryClientBlanket, CoGetCallContext.
3459 HRESULT WINAPI
CoRevertToSelf(void)
3461 IServerSecurity
*pSrvSec
;
3466 hr
= CoGetCallContext(&IID_IServerSecurity
, (void **)&pSrvSec
);
3469 hr
= IServerSecurity_RevertToSelf(pSrvSec
);
3470 IServerSecurity_Release(pSrvSec
);
3476 static BOOL
COM_PeekMessage(struct apartment
*apt
, MSG
*msg
)
3478 /* first try to retrieve messages for incoming COM calls to the apartment window */
3479 return PeekMessageW(msg
, apt
->win
, WM_USER
, WM_APP
- 1, PM_REMOVE
|PM_NOYIELD
) ||
3480 /* next retrieve other messages necessary for the app to remain responsive */
3481 PeekMessageW(msg
, NULL
, 0, 0, PM_QS_PAINT
|PM_QS_POSTMESSAGE
|PM_REMOVE
|PM_NOYIELD
);
3484 /***********************************************************************
3485 * CoWaitForMultipleHandles [OLE32.@]
3487 * Waits for one or more handles to become signaled.
3490 * dwFlags [I] Flags. See notes.
3491 * dwTimeout [I] Timeout in milliseconds.
3492 * cHandles [I] Number of handles pointed to by pHandles.
3493 * pHandles [I] Handles to wait for.
3494 * lpdwindex [O] Index of handle that was signaled.
3498 * Failure: RPC_S_CALLPENDING on timeout.
3502 * The dwFlags parameter can be zero or more of the following:
3503 *| COWAIT_WAITALL - Wait for all of the handles to become signaled.
3504 *| COWAIT_ALERTABLE - Allows a queued APC to run during the wait.
3507 * MsgWaitForMultipleObjects, WaitForMultipleObjects.
3509 HRESULT WINAPI
CoWaitForMultipleHandles(DWORD dwFlags
, DWORD dwTimeout
,
3510 ULONG cHandles
, LPHANDLE pHandles
, LPDWORD lpdwindex
)
3513 DWORD start_time
= GetTickCount();
3514 APARTMENT
*apt
= COM_CurrentApt();
3515 BOOL message_loop
= apt
&& !apt
->multi_threaded
;
3517 TRACE("(0x%08x, 0x%08x, %d, %p, %p)\n", dwFlags
, dwTimeout
, cHandles
,
3518 pHandles
, lpdwindex
);
3522 DWORD now
= GetTickCount();
3525 if (now
- start_time
> dwTimeout
)
3527 hr
= RPC_S_CALLPENDING
;
3533 DWORD wait_flags
= ((dwFlags
& COWAIT_WAITALL
) ? MWMO_WAITALL
: 0) |
3534 ((dwFlags
& COWAIT_ALERTABLE
) ? MWMO_ALERTABLE
: 0);
3536 TRACE("waiting for rpc completion or window message\n");
3538 res
= MsgWaitForMultipleObjectsEx(cHandles
, pHandles
,
3539 (dwTimeout
== INFINITE
) ? INFINITE
: start_time
+ dwTimeout
- now
,
3540 QS_ALLINPUT
, wait_flags
);
3542 if (res
== WAIT_OBJECT_0
+ cHandles
) /* messages available */
3546 /* call message filter */
3548 if (COM_CurrentApt()->filter
)
3550 PENDINGTYPE pendingtype
=
3551 COM_CurrentInfo()->pending_call_count_server
?
3552 PENDINGTYPE_NESTED
: PENDINGTYPE_TOPLEVEL
;
3553 DWORD be_handled
= IMessageFilter_MessagePending(
3554 COM_CurrentApt()->filter
, 0 /* FIXME */,
3555 now
- start_time
, pendingtype
);
3556 TRACE("IMessageFilter_MessagePending returned %d\n", be_handled
);
3559 case PENDINGMSG_CANCELCALL
:
3560 WARN("call canceled\n");
3561 hr
= RPC_E_CALL_CANCELED
;
3563 case PENDINGMSG_WAITNOPROCESS
:
3564 case PENDINGMSG_WAITDEFPROCESS
:
3566 /* FIXME: MSDN is very vague about the difference
3567 * between WAITNOPROCESS and WAITDEFPROCESS - there
3568 * appears to be none, so it is possibly a left-over
3569 * from the 16-bit world. */
3574 /* note: using "if" here instead of "while" might seem less
3575 * efficient, but only if we are optimising for quick delivery
3576 * of pending messages, rather than quick completion of the
3578 if (COM_PeekMessage(apt
, &msg
))
3580 TRACE("received message whilst waiting for RPC: 0x%04x\n", msg
.message
);
3581 TranslateMessage(&msg
);
3582 DispatchMessageW(&msg
);
3583 if (msg
.message
== WM_QUIT
)
3585 TRACE("resending WM_QUIT to outer message loop\n");
3586 PostQuitMessage(msg
.wParam
);
3587 /* no longer need to process messages */
3588 message_loop
= FALSE
;
3596 TRACE("waiting for rpc completion\n");
3598 res
= WaitForMultipleObjectsEx(cHandles
, pHandles
,
3599 (dwFlags
& COWAIT_WAITALL
) ? TRUE
: FALSE
,
3600 (dwTimeout
== INFINITE
) ? INFINITE
: start_time
+ dwTimeout
- now
,
3601 (dwFlags
& COWAIT_ALERTABLE
) ? TRUE
: FALSE
);
3604 if (res
< WAIT_OBJECT_0
+ cHandles
)
3606 /* handle signaled, store index */
3607 *lpdwindex
= (res
- WAIT_OBJECT_0
);
3610 else if (res
== WAIT_TIMEOUT
)
3612 hr
= RPC_S_CALLPENDING
;
3617 ERR("Unexpected wait termination: %d, %d\n", res
, GetLastError());
3622 TRACE("-- 0x%08x\n", hr
);
3627 /***********************************************************************
3628 * CoGetObject [OLE32.@]
3630 * Gets the object named by converting the name to a moniker and binding to it.
3633 * pszName [I] String representing the object.
3634 * pBindOptions [I] Parameters affecting the binding to the named object.
3635 * riid [I] Interface to bind to on the objecct.
3636 * ppv [O] On output, the interface riid of the object represented
3641 * Failure: HRESULT code.
3644 * MkParseDisplayName.
3646 HRESULT WINAPI
CoGetObject(LPCWSTR pszName
, BIND_OPTS
*pBindOptions
,
3647 REFIID riid
, void **ppv
)
3654 hr
= CreateBindCtx(0, &pbc
);
3658 hr
= IBindCtx_SetBindOptions(pbc
, pBindOptions
);
3665 hr
= MkParseDisplayName(pbc
, pszName
, &chEaten
, &pmk
);
3668 hr
= IMoniker_BindToObject(pmk
, pbc
, NULL
, riid
, ppv
);
3669 IMoniker_Release(pmk
);
3673 IBindCtx_Release(pbc
);
3678 /***********************************************************************
3679 * CoRegisterChannelHook [OLE32.@]
3681 * Registers a process-wide hook that is called during ORPC calls.
3684 * guidExtension [I] GUID of the channel hook to register.
3685 * pChannelHook [I] Channel hook object to register.
3689 * Failure: HRESULT code.
3691 HRESULT WINAPI
CoRegisterChannelHook(REFGUID guidExtension
, IChannelHook
*pChannelHook
)
3693 TRACE("(%s, %p)\n", debugstr_guid(guidExtension
), pChannelHook
);
3695 return RPC_RegisterChannelHook(guidExtension
, pChannelHook
);
3698 typedef struct Context
3700 const IComThreadingInfoVtbl
*lpVtbl
;
3701 const IContextCallbackVtbl
*lpCallbackVtbl
;
3706 static inline Context
*impl_from_IComThreadingInfo( IComThreadingInfo
*iface
)
3708 return (Context
*)((char*)iface
- FIELD_OFFSET(Context
, lpVtbl
));
3711 static inline Context
*impl_from_IContextCallback( IContextCallback
*iface
)
3713 return (Context
*)((char*)iface
- FIELD_OFFSET(Context
, lpCallbackVtbl
));
3716 static HRESULT
Context_QueryInterface(Context
*iface
, REFIID riid
, LPVOID
*ppv
)
3720 if (IsEqualIID(riid
, &IID_IComThreadingInfo
) ||
3721 IsEqualIID(riid
, &IID_IUnknown
))
3723 *ppv
= &iface
->lpVtbl
;
3724 } else if (IsEqualIID(riid
, &IID_IContextCallback
))
3726 *ppv
= &iface
->lpCallbackVtbl
;
3731 IUnknown_AddRef((IUnknown
*)*ppv
);
3735 FIXME("interface not implemented %s\n", debugstr_guid(riid
));
3736 return E_NOINTERFACE
;
3739 static ULONG
Context_AddRef(Context
*This
)
3741 return InterlockedIncrement(&This
->refs
);
3744 static ULONG
Context_Release(Context
*This
)
3746 ULONG refs
= InterlockedDecrement(&This
->refs
);
3748 HeapFree(GetProcessHeap(), 0, This
);
3752 static HRESULT WINAPI
Context_CTI_QueryInterface(IComThreadingInfo
*iface
, REFIID riid
, LPVOID
*ppv
)
3754 Context
*This
= impl_from_IComThreadingInfo(iface
);
3755 return Context_QueryInterface(This
, riid
, ppv
);
3758 static ULONG WINAPI
Context_CTI_AddRef(IComThreadingInfo
*iface
)
3760 Context
*This
= impl_from_IComThreadingInfo(iface
);
3761 return Context_AddRef(This
);
3764 static ULONG WINAPI
Context_CTI_Release(IComThreadingInfo
*iface
)
3766 Context
*This
= impl_from_IComThreadingInfo(iface
);
3767 return Context_Release(This
);
3770 static HRESULT WINAPI
Context_CTI_GetCurrentApartmentType(IComThreadingInfo
*iface
, APTTYPE
*apttype
)
3772 Context
*This
= impl_from_IComThreadingInfo(iface
);
3774 TRACE("(%p)\n", apttype
);
3776 *apttype
= This
->apttype
;
3780 static HRESULT WINAPI
Context_CTI_GetCurrentThreadType(IComThreadingInfo
*iface
, THDTYPE
*thdtype
)
3782 Context
*This
= impl_from_IComThreadingInfo(iface
);
3784 TRACE("(%p)\n", thdtype
);
3786 switch (This
->apttype
)
3789 case APTTYPE_MAINSTA
:
3790 *thdtype
= THDTYPE_PROCESSMESSAGES
;
3793 *thdtype
= THDTYPE_BLOCKMESSAGES
;
3799 static HRESULT WINAPI
Context_CTI_GetCurrentLogicalThreadId(IComThreadingInfo
*iface
, GUID
*logical_thread_id
)
3801 FIXME("(%p): stub\n", logical_thread_id
);
3805 static HRESULT WINAPI
Context_CTI_SetCurrentLogicalThreadId(IComThreadingInfo
*iface
, REFGUID logical_thread_id
)
3807 FIXME("(%s): stub\n", debugstr_guid(logical_thread_id
));
3811 static const IComThreadingInfoVtbl Context_Threading_Vtbl
=
3813 Context_CTI_QueryInterface
,
3815 Context_CTI_Release
,
3816 Context_CTI_GetCurrentApartmentType
,
3817 Context_CTI_GetCurrentThreadType
,
3818 Context_CTI_GetCurrentLogicalThreadId
,
3819 Context_CTI_SetCurrentLogicalThreadId
3822 static HRESULT WINAPI
Context_CC_QueryInterface(IContextCallback
*iface
, REFIID riid
, LPVOID
*ppv
)
3824 Context
*This
= impl_from_IContextCallback(iface
);
3825 return Context_QueryInterface(This
, riid
, ppv
);
3828 static ULONG WINAPI
Context_CC_AddRef(IContextCallback
*iface
)
3830 Context
*This
= impl_from_IContextCallback(iface
);
3831 return Context_AddRef(This
);
3834 static ULONG WINAPI
Context_CC_Release(IContextCallback
*iface
)
3836 Context
*This
= impl_from_IContextCallback(iface
);
3837 return Context_Release(This
);
3840 static HRESULT WINAPI
Context_CC_ContextCallback(IContextCallback
*iface
, PFNCONTEXTCALL pCallback
,
3841 ComCallData
*param
, REFIID riid
, int method
, IUnknown
*punk
)
3843 Context
*This
= impl_from_IContextCallback(iface
);
3845 FIXME("(%p/%p)->(%p, %p, %s, %d, %p)\n", This
, iface
, pCallback
, param
, debugstr_guid(riid
), method
, punk
);
3849 static const IContextCallbackVtbl Context_Callback_Vtbl
=
3851 Context_CC_QueryInterface
,
3854 Context_CC_ContextCallback
3858 /***********************************************************************
3859 * CoGetObjectContext [OLE32.@]
3861 * Retrieves an object associated with the current context (i.e. apartment).
3864 * riid [I] ID of the interface of the object to retrieve.
3865 * ppv [O] Address where object will be stored on return.
3869 * Failure: HRESULT code.
3871 HRESULT WINAPI
CoGetObjectContext(REFIID riid
, void **ppv
)
3873 APARTMENT
*apt
= COM_CurrentApt();
3877 TRACE("(%s, %p)\n", debugstr_guid(riid
), ppv
);
3882 ERR("apartment not initialised\n");
3883 return CO_E_NOTINITIALIZED
;
3886 context
= HeapAlloc(GetProcessHeap(), 0, sizeof(*context
));
3888 return E_OUTOFMEMORY
;
3890 context
->lpVtbl
= &Context_Threading_Vtbl
;
3891 context
->lpCallbackVtbl
= &Context_Callback_Vtbl
;
3893 if (apt
->multi_threaded
)
3894 context
->apttype
= APTTYPE_MTA
;
3896 context
->apttype
= APTTYPE_MAINSTA
;
3898 context
->apttype
= APTTYPE_STA
;
3900 hr
= IUnknown_QueryInterface((IUnknown
*)&context
->lpVtbl
, riid
, ppv
);
3901 IUnknown_Release((IUnknown
*)&context
->lpVtbl
);
3907 /***********************************************************************
3908 * CoGetContextToken [OLE32.@]
3910 HRESULT WINAPI
CoGetContextToken( ULONG_PTR
*token
)
3912 struct oletls
*info
= COM_CurrentInfo();
3914 if(!(calls
++)) FIXME( "stub\n" );
3916 return E_OUTOFMEMORY
;
3917 if (token
) *token
= info
->context_token
;
3922 /***********************************************************************
3925 BOOL WINAPI
DllMain(HINSTANCE hinstDLL
, DWORD fdwReason
, LPVOID fImpLoad
)
3927 TRACE("%p 0x%x %p\n", hinstDLL
, fdwReason
, fImpLoad
);
3930 case DLL_PROCESS_ATTACH
:
3931 hProxyDll
= hinstDLL
;
3932 COMPOBJ_InitProcess();
3933 if (TRACE_ON(ole
)) CoRegisterMallocSpy((LPVOID
)-1);
3936 case DLL_PROCESS_DETACH
:
3937 if (TRACE_ON(ole
)) CoRevokeMallocSpy();
3938 OLEDD_UnInitialize();
3939 COMPOBJ_UninitProcess();
3940 RPC_UnregisterAllChannelHooks();
3941 COMPOBJ_DllList_Free();
3944 case DLL_THREAD_DETACH
:
3951 /* NOTE: DllRegisterServer and DllUnregisterServer are in regsvr.c */