Changes in crossover-wine-src-6.1.0 except for configure
[wine/hacks.git] / dlls / ole32 / compobj.c
blob2002df6fa8246ec7cbf4cb08687af7362871147a
1 /*
2 * COMPOBJ library
4 * Copyright 1995 Martin von Loewis
5 * Copyright 1998 Justin Bradford
6 * Copyright 1999 Francis Beaudet
7 * Copyright 1999 Sylvain St-Germain
8 * Copyright 2002 Marcus Meissner
9 * Copyright 2004 Mike Hearn
10 * Copyright 2005-2006 Robert Shearman (for CodeWeavers)
12 * This library is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Lesser General Public
14 * License as published by the Free Software Foundation; either
15 * version 2.1 of the License, or (at your option) any later version.
17 * This library is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * Lesser General Public License for more details.
22 * You should have received a copy of the GNU Lesser General Public
23 * License along with this library; if not, write to the Free Software
24 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
26 * Note
27 * 1. COINIT_MULTITHREADED is 0; it is the lack of COINIT_APARTMENTTHREADED
28 * Therefore do not test against COINIT_MULTITHREADED
30 * TODO list: (items bunched together depend on each other)
32 * - Implement the service control manager (in rpcss) to keep track
33 * of registered class objects: ISCM::ServerRegisterClsid et al
34 * - Implement the OXID resolver so we don't need magic endpoint names for
35 * clients and servers to meet up
37 * - Make all ole interface marshaling use NDR to be wire compatible with
38 * native DCOM
42 #include "config.h"
44 #include <stdarg.h>
45 #include <stdio.h>
46 #include <string.h>
47 #include <assert.h>
49 #define COBJMACROS
50 #define NONAMELESSUNION
51 #define NONAMELESSSTRUCT
53 #include "windef.h"
54 #include "winbase.h"
55 #include "winerror.h"
56 #include "winreg.h"
57 #include "winuser.h"
58 #include "objbase.h"
59 #include "ole2.h"
60 #include "ole2ver.h"
62 #include "compobj_private.h"
64 #include "wine/unicode.h"
65 #include "wine/debug.h"
67 WINE_DEFAULT_DEBUG_CHANNEL(ole);
69 HINSTANCE OLE32_hInstance = 0; /* FIXME: make static ... */
71 #define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))
73 /****************************************************************************
74 * This section defines variables internal to the COM module.
76 * TODO: Most of these things will have to be made thread-safe.
79 static HRESULT COM_GetRegisteredClassObject(REFCLSID rclsid, DWORD dwClsContext, LPUNKNOWN* ppUnk);
80 static void COM_RevokeAllClasses(void);
81 static HRESULT get_inproc_class_object(HKEY hkeydll, REFCLSID rclsid, REFIID riid, void **ppv);
83 static APARTMENT *MTA; /* protected by csApartment */
84 static APARTMENT *MainApartment; /* the first STA apartment */
85 static struct list apts = LIST_INIT( apts ); /* protected by csApartment */
87 static CRITICAL_SECTION csApartment;
88 static CRITICAL_SECTION_DEBUG critsect_debug =
90 0, 0, &csApartment,
91 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
92 0, 0, { (DWORD_PTR)(__FILE__ ": csApartment") }
94 static CRITICAL_SECTION csApartment = { &critsect_debug, -1, 0, 0, 0, 0 };
96 struct registered_psclsid
98 struct list entry;
99 IID iid;
100 CLSID clsid;
104 * This lock count counts the number of times CoInitialize is called. It is
105 * decreased every time CoUninitialize is called. When it hits 0, the COM
106 * libraries are freed
108 static LONG s_COMLockCount = 0;
109 /* Reference count used by CoAddRefServerProcess/CoReleaseServerProcess */
110 static LONG s_COMServerProcessReferences = 0;
113 * This linked list contains the list of registered class objects. These
114 * are mostly used to register the factories for out-of-proc servers of OLE
115 * objects.
117 * TODO: Make this data structure aware of inter-process communication. This
118 * means that parts of this will be exported to the Wine Server.
120 typedef struct tagRegisteredClass
122 struct list entry;
123 CLSID classIdentifier;
124 LPUNKNOWN classObject;
125 DWORD runContext;
126 DWORD connectFlags;
127 DWORD dwCookie;
128 LPSTREAM pMarshaledData; /* FIXME: only really need to store OXID and IPID */
129 void *RpcRegistration;
130 } RegisteredClass;
132 static struct list RegisteredClassList = LIST_INIT(RegisteredClassList);
134 static CRITICAL_SECTION csRegisteredClassList;
135 static CRITICAL_SECTION_DEBUG class_cs_debug =
137 0, 0, &csRegisteredClassList,
138 { &class_cs_debug.ProcessLocksList, &class_cs_debug.ProcessLocksList },
139 0, 0, { (DWORD_PTR)(__FILE__ ": csRegisteredClassList") }
141 static CRITICAL_SECTION csRegisteredClassList = { &class_cs_debug, -1, 0, 0, 0, 0 };
143 /*****************************************************************************
144 * This section contains OpenDllList definitions
146 * The OpenDllList contains only handles of dll loaded by CoGetClassObject or
147 * other functions that do LoadLibrary _without_ giving back a HMODULE.
148 * Without this list these handles would never be freed.
150 * FIXME: a DLL that says OK when asked for unloading is unloaded in the
151 * next unload-call but not before 600 sec.
154 typedef struct tagOpenDll {
155 HINSTANCE hLibrary;
156 struct tagOpenDll *next;
157 } OpenDll;
159 static OpenDll *openDllList = NULL; /* linked list of open dlls */
161 static CRITICAL_SECTION csOpenDllList;
162 static CRITICAL_SECTION_DEBUG dll_cs_debug =
164 0, 0, &csOpenDllList,
165 { &dll_cs_debug.ProcessLocksList, &dll_cs_debug.ProcessLocksList },
166 0, 0, { (DWORD_PTR)(__FILE__ ": csOpenDllList") }
168 static CRITICAL_SECTION csOpenDllList = { &dll_cs_debug, -1, 0, 0, 0, 0 };
170 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',' ',
171 '0','x','#','#','#','#','#','#','#','#',' ',0};
172 static LRESULT CALLBACK apartment_wndproc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
174 static void COMPOBJ_DLLList_Add(HANDLE hLibrary);
175 static void COMPOBJ_DllList_FreeUnused(int Timeout);
177 static void COMPOBJ_InitProcess( void )
179 WNDCLASSW wclass;
181 /* Dispatching to the correct thread in an apartment is done through
182 * window messages rather than RPC transports. When an interface is
183 * marshalled into another apartment in the same process, a window of the
184 * following class is created. The *caller* of CoMarshalInterface (ie the
185 * application) is responsible for pumping the message loop in that thread.
186 * The WM_USER messages which point to the RPCs are then dispatched to
187 * COM_AptWndProc by the user's code from the apartment in which the interface
188 * was unmarshalled.
190 memset(&wclass, 0, sizeof(wclass));
191 wclass.lpfnWndProc = apartment_wndproc;
192 wclass.hInstance = OLE32_hInstance;
193 wclass.lpszClassName = wszAptWinClass;
194 RegisterClassW(&wclass);
197 static void COMPOBJ_UninitProcess( void )
199 UnregisterClassW(wszAptWinClass, OLE32_hInstance);
202 static void COM_TlsDestroy(void)
204 struct oletls *info = NtCurrentTeb()->ReservedForOle;
205 if (info)
207 if (info->apt) apartment_release(info->apt);
208 if (info->errorinfo) IErrorInfo_Release(info->errorinfo);
209 if (info->state) IUnknown_Release(info->state);
210 HeapFree(GetProcessHeap(), 0, info);
211 NtCurrentTeb()->ReservedForOle = NULL;
215 /******************************************************************************
216 * Manage apartments.
219 /* allocates memory and fills in the necessary fields for a new apartment
220 * object. must be called inside apartment cs */
221 static APARTMENT *apartment_construct(DWORD model)
223 APARTMENT *apt;
225 TRACE("creating new apartment, model=%d\n", model);
227 apt = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*apt));
228 apt->tid = GetCurrentThreadId();
230 list_init(&apt->proxies);
231 list_init(&apt->stubmgrs);
232 list_init(&apt->psclsids);
233 apt->ipidc = 0;
234 apt->refs = 1;
235 apt->remunk_exported = FALSE;
236 apt->oidc = 1;
237 InitializeCriticalSection(&apt->cs);
238 DEBUG_SET_CRITSEC_NAME(&apt->cs, "apartment");
240 apt->multi_threaded = !(model & COINIT_APARTMENTTHREADED);
242 if (apt->multi_threaded)
244 /* FIXME: should be randomly generated by in an RPC call to rpcss */
245 apt->oxid = ((OXID)GetCurrentProcessId() << 32) | 0xcafe;
247 else
249 /* FIXME: should be randomly generated by in an RPC call to rpcss */
250 apt->oxid = ((OXID)GetCurrentProcessId() << 32) | GetCurrentThreadId();
253 TRACE("Created apartment on OXID %s\n", wine_dbgstr_longlong(apt->oxid));
255 list_add_head(&apts, &apt->entry);
257 return apt;
260 /* gets and existing apartment if one exists or otherwise creates an apartment
261 * structure which stores OLE apartment-local information and stores a pointer
262 * to it in the thread-local storage */
263 static APARTMENT *apartment_get_or_create(DWORD model)
265 APARTMENT *apt = COM_CurrentApt();
267 if (!apt)
269 if (model & COINIT_APARTMENTTHREADED)
271 EnterCriticalSection(&csApartment);
273 apt = apartment_construct(model);
274 if (!MainApartment)
276 MainApartment = apt;
277 apt->main = TRUE;
278 TRACE("Created main-threaded apartment with OXID %s\n", wine_dbgstr_longlong(apt->oxid));
281 LeaveCriticalSection(&csApartment);
283 else
285 EnterCriticalSection(&csApartment);
287 /* The multi-threaded apartment (MTA) contains zero or more threads interacting
288 * with free threaded (ie thread safe) COM objects. There is only ever one MTA
289 * in a process */
290 if (MTA)
292 TRACE("entering the multithreaded apartment %s\n", wine_dbgstr_longlong(MTA->oxid));
293 apartment_addref(MTA);
295 else
296 MTA = apartment_construct(model);
298 apt = MTA;
300 LeaveCriticalSection(&csApartment);
302 COM_CurrentInfo()->apt = apt;
305 return apt;
308 static inline BOOL apartment_is_model(APARTMENT *apt, DWORD model)
310 return (apt->multi_threaded == !(model & COINIT_APARTMENTTHREADED));
313 DWORD apartment_addref(struct apartment *apt)
315 DWORD refs = InterlockedIncrement(&apt->refs);
316 TRACE("%s: before = %d\n", wine_dbgstr_longlong(apt->oxid), refs - 1);
317 return refs;
320 DWORD apartment_release(struct apartment *apt)
322 DWORD ret;
324 EnterCriticalSection(&csApartment);
326 ret = InterlockedDecrement(&apt->refs);
327 TRACE("%s: after = %d\n", wine_dbgstr_longlong(apt->oxid), ret);
328 /* destruction stuff that needs to happen under csApartment CS */
329 if (ret == 0)
331 if (apt == MTA) MTA = NULL;
332 else if (apt == MainApartment) MainApartment = NULL;
333 list_remove(&apt->entry);
336 LeaveCriticalSection(&csApartment);
338 if (ret == 0)
340 struct list *cursor, *cursor2;
342 TRACE("destroying apartment %p, oxid %s\n", apt, wine_dbgstr_longlong(apt->oxid));
344 /* no locking is needed for this apartment, because no other thread
345 * can access it at this point */
347 apartment_disconnectproxies(apt);
349 if (apt->win) DestroyWindow(apt->win);
351 LIST_FOR_EACH_SAFE(cursor, cursor2, &apt->stubmgrs)
353 struct stub_manager *stubmgr = LIST_ENTRY(cursor, struct stub_manager, entry);
354 /* release the implicit reference given by the fact that the
355 * stub has external references (it must do since it is in the
356 * stub manager list in the apartment and all non-apartment users
357 * must have a ref on the apartment and so it cannot be destroyed).
359 stub_manager_int_release(stubmgr);
362 LIST_FOR_EACH_SAFE(cursor, cursor2, &apt->psclsids)
364 struct registered_psclsid *registered_psclsid =
365 LIST_ENTRY(cursor, struct registered_psclsid, entry);
367 list_remove(&registered_psclsid->entry);
368 HeapFree(GetProcessHeap(), 0, registered_psclsid);
371 /* if this assert fires, then another thread took a reference to a
372 * stub manager without taking a reference to the containing
373 * apartment, which it must do. */
374 assert(list_empty(&apt->stubmgrs));
376 if (apt->filter) IUnknown_Release(apt->filter);
378 DEBUG_CLEAR_CRITSEC_NAME(&apt->cs);
379 DeleteCriticalSection(&apt->cs);
381 HeapFree(GetProcessHeap(), 0, apt);
384 return ret;
387 /* The given OXID must be local to this process:
389 * The ref parameter is here mostly to ensure people remember that
390 * they get one, you should normally take a ref for thread safety.
392 APARTMENT *apartment_findfromoxid(OXID oxid, BOOL ref)
394 APARTMENT *result = NULL;
395 struct list *cursor;
397 EnterCriticalSection(&csApartment);
398 LIST_FOR_EACH( cursor, &apts )
400 struct apartment *apt = LIST_ENTRY( cursor, struct apartment, entry );
401 if (apt->oxid == oxid)
403 result = apt;
404 if (ref) apartment_addref(result);
405 break;
408 LeaveCriticalSection(&csApartment);
410 return result;
413 /* gets the apartment which has a given creator thread ID. The caller must
414 * release the reference from the apartment as soon as the apartment pointer
415 * is no longer required. */
416 APARTMENT *apartment_findfromtid(DWORD tid)
418 APARTMENT *result = NULL;
419 struct list *cursor;
421 EnterCriticalSection(&csApartment);
422 LIST_FOR_EACH( cursor, &apts )
424 struct apartment *apt = LIST_ENTRY( cursor, struct apartment, entry );
425 if (apt->tid == tid)
427 result = apt;
428 apartment_addref(result);
429 break;
432 LeaveCriticalSection(&csApartment);
434 return result;
437 /* gets an apartment which has a given type. The caller must
438 * release the reference from the apartment as soon as the apartment pointer
439 * is no longer required. */
440 static APARTMENT *apartment_findfromtype(BOOL multi_threaded, BOOL main_apartment)
442 APARTMENT *result = NULL;
443 struct apartment *apt;
445 EnterCriticalSection(&csApartment);
447 if (!multi_threaded && main_apartment)
449 result = MainApartment;
450 if (result) apartment_addref(result);
451 LeaveCriticalSection(&csApartment);
452 return result;
455 LIST_FOR_EACH_ENTRY( apt, &apts, struct apartment, entry )
457 if (apt->multi_threaded == multi_threaded)
459 result = apt;
460 apartment_addref(result);
461 break;
464 LeaveCriticalSection(&csApartment);
466 return result;
469 struct host_object_params
471 HKEY hkeydll;
472 CLSID clsid; /* clsid of object to marshal */
473 IID iid; /* interface to marshal */
474 IStream *stream; /* stream that the object will be marshaled into */
477 static HRESULT apartment_hostobject(const struct host_object_params *params)
479 IUnknown *object;
480 HRESULT hr;
481 static const LARGE_INTEGER llZero;
483 TRACE("\n");
485 hr = get_inproc_class_object(params->hkeydll, &params->clsid, &params->iid, (void **)&object);
486 if (FAILED(hr))
487 return hr;
489 hr = CoMarshalInterface(params->stream, &params->iid, object, MSHCTX_INPROC, NULL, MSHLFLAGS_NORMAL);
490 if (FAILED(hr))
491 IUnknown_Release(object);
492 IStream_Seek(params->stream, llZero, STREAM_SEEK_SET, NULL);
494 return hr;
497 static LRESULT CALLBACK apartment_wndproc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
499 switch (msg)
501 case DM_EXECUTERPC:
502 RPC_ExecuteCall((struct dispatch_params *)lParam);
503 return 0;
504 case DM_HOSTOBJECT:
505 return apartment_hostobject((const struct host_object_params *)lParam);
506 default:
507 return DefWindowProcW(hWnd, msg, wParam, lParam);
511 HRESULT apartment_createwindowifneeded(struct apartment *apt)
513 if (apt->multi_threaded)
514 return S_OK;
516 if (!apt->win)
518 HWND hwnd = CreateWindowW(wszAptWinClass, NULL, 0,
519 0, 0, 0, 0,
520 0, 0, OLE32_hInstance, NULL);
521 if (!hwnd)
523 ERR("CreateWindow failed with error %d\n", GetLastError());
524 return HRESULT_FROM_WIN32(GetLastError());
526 if (InterlockedCompareExchangePointer((PVOID *)&apt->win, hwnd, NULL))
527 /* someone beat us to it */
528 DestroyWindow(hwnd);
531 return S_OK;
534 HWND apartment_getwindow(struct apartment *apt)
536 assert(!apt->multi_threaded);
537 return apt->win;
540 void apartment_joinmta(void)
542 apartment_addref(MTA);
543 COM_CurrentInfo()->apt = MTA;
546 /*****************************************************************************
547 * This section contains OpenDllList implementation
550 static void COMPOBJ_DLLList_Add(HANDLE hLibrary)
552 OpenDll *ptr;
553 OpenDll *tmp;
555 TRACE("\n");
557 EnterCriticalSection( &csOpenDllList );
559 if (openDllList == NULL) {
560 /* empty list -- add first node */
561 openDllList = HeapAlloc(GetProcessHeap(),0, sizeof(OpenDll));
562 openDllList->hLibrary=hLibrary;
563 openDllList->next = NULL;
564 } else {
565 /* search for this dll */
566 int found = FALSE;
567 for (ptr = openDllList; ptr->next != NULL; ptr=ptr->next) {
568 if (ptr->hLibrary == hLibrary) {
569 found = TRUE;
570 break;
573 if (!found) {
574 /* dll not found, add it */
575 tmp = openDllList;
576 openDllList = HeapAlloc(GetProcessHeap(),0, sizeof(OpenDll));
577 openDllList->hLibrary = hLibrary;
578 openDllList->next = tmp;
582 LeaveCriticalSection( &csOpenDllList );
585 static void COMPOBJ_DllList_FreeUnused(int Timeout)
587 OpenDll *curr, *next, *prev = NULL;
588 typedef HRESULT (WINAPI *DllCanUnloadNowFunc)(void);
589 DllCanUnloadNowFunc DllCanUnloadNow;
591 TRACE("\n");
593 EnterCriticalSection( &csOpenDllList );
595 for (curr = openDllList; curr != NULL; ) {
596 DllCanUnloadNow = (DllCanUnloadNowFunc) GetProcAddress(curr->hLibrary, "DllCanUnloadNow");
598 if ( (DllCanUnloadNow != NULL) && (DllCanUnloadNow() == S_OK) ) {
599 next = curr->next;
601 TRACE("freeing %p\n", curr->hLibrary);
602 FreeLibrary(curr->hLibrary);
604 HeapFree(GetProcessHeap(), 0, curr);
605 if (curr == openDllList) {
606 openDllList = next;
607 } else {
608 prev->next = next;
611 curr = next;
612 } else {
613 prev = curr;
614 curr = curr->next;
618 LeaveCriticalSection( &csOpenDllList );
621 /******************************************************************************
622 * CoBuildVersion [OLE32.@]
623 * CoBuildVersion [COMPOBJ.1]
625 * Gets the build version of the DLL.
627 * PARAMS
629 * RETURNS
630 * Current build version, hiword is majornumber, loword is minornumber
632 DWORD WINAPI CoBuildVersion(void)
634 TRACE("Returning version %d, build %d.\n", rmm, rup);
635 return (rmm<<16)+rup;
638 /******************************************************************************
639 * CoInitialize [OLE32.@]
641 * Initializes the COM libraries by calling CoInitializeEx with
642 * COINIT_APARTMENTTHREADED, ie it enters a STA thread.
644 * PARAMS
645 * lpReserved [I] Pointer to IMalloc interface (obsolete, should be NULL).
647 * RETURNS
648 * Success: S_OK if not already initialized, S_FALSE otherwise.
649 * Failure: HRESULT code.
651 * SEE ALSO
652 * CoInitializeEx
654 HRESULT WINAPI CoInitialize(LPVOID lpReserved)
657 * Just delegate to the newer method.
659 return CoInitializeEx(lpReserved, COINIT_APARTMENTTHREADED);
662 /******************************************************************************
663 * CoInitializeEx [OLE32.@]
665 * Initializes the COM libraries.
667 * PARAMS
668 * lpReserved [I] Pointer to IMalloc interface (obsolete, should be NULL).
669 * dwCoInit [I] One or more flags from the COINIT enumeration. See notes.
671 * RETURNS
672 * S_OK if successful,
673 * S_FALSE if this function was called already.
674 * RPC_E_CHANGED_MODE if a previous call to CoInitializeEx specified another
675 * threading model.
677 * NOTES
679 * The behavior used to set the IMalloc used for memory management is
680 * obsolete.
681 * The dwCoInit parameter must specify one of the following apartment
682 * threading models:
683 *| COINIT_APARTMENTTHREADED - A single-threaded apartment (STA).
684 *| COINIT_MULTITHREADED - A multi-threaded apartment (MTA).
685 * The parameter may also specify zero or more of the following flags:
686 *| COINIT_DISABLE_OLE1DDE - Don't use DDE for OLE1 support.
687 *| COINIT_SPEED_OVER_MEMORY - Trade memory for speed.
689 * SEE ALSO
690 * CoUninitialize
692 HRESULT WINAPI CoInitializeEx(LPVOID lpReserved, DWORD dwCoInit)
694 HRESULT hr = S_OK;
695 APARTMENT *apt;
697 TRACE("(%p, %x)\n", lpReserved, (int)dwCoInit);
699 if (lpReserved!=NULL)
701 ERR("(%p, %x) - Bad parameter passed-in %p, must be an old Windows Application\n", lpReserved, (int)dwCoInit, lpReserved);
705 * Check the lock count. If this is the first time going through the initialize
706 * process, we have to initialize the libraries.
708 * And crank-up that lock count.
710 if (InterlockedExchangeAdd(&s_COMLockCount,1)==0)
713 * Initialize the various COM libraries and data structures.
715 TRACE("() - Initializing the COM libraries\n");
717 /* we may need to defer this until after apartment initialisation */
718 RunningObjectTableImpl_Initialize();
721 if (!(apt = COM_CurrentInfo()->apt))
723 apt = apartment_get_or_create(dwCoInit);
724 if (!apt) return E_OUTOFMEMORY;
726 else if (!apartment_is_model(apt, dwCoInit))
728 /* Changing the threading model after it's been set is illegal. If this warning is triggered by Wine
729 code then we are probably using the wrong threading model to implement that API. */
730 ERR("Attempt to change threading model of this apartment from %s to %s\n",
731 apt->multi_threaded ? "multi-threaded" : "apartment threaded",
732 dwCoInit & COINIT_APARTMENTTHREADED ? "apartment threaded" : "multi-threaded");
733 return RPC_E_CHANGED_MODE;
735 else
736 hr = S_FALSE;
738 COM_CurrentInfo()->inits++;
740 return hr;
743 /* On COM finalization for a STA thread, the message queue is flushed to ensure no
744 pending RPCs are ignored. Non-COM messages are discarded at this point.
746 static void COM_FlushMessageQueue(void)
748 MSG message;
749 APARTMENT *apt = COM_CurrentApt();
751 if (!apt || !apt->win) return;
753 TRACE("Flushing STA message queue\n");
755 while (PeekMessageA(&message, NULL, 0, 0, PM_REMOVE))
757 if (message.hwnd != apt->win)
759 WARN("discarding message 0x%x for window %p\n", message.message, message.hwnd);
760 continue;
763 TranslateMessage(&message);
764 DispatchMessageA(&message);
768 /***********************************************************************
769 * CoUninitialize [OLE32.@]
771 * This method will decrement the refcount on the current apartment, freeing
772 * the resources associated with it if it is the last thread in the apartment.
773 * If the last apartment is freed, the function will additionally release
774 * any COM resources associated with the process.
776 * PARAMS
778 * RETURNS
779 * Nothing.
781 * SEE ALSO
782 * CoInitializeEx
784 void WINAPI CoUninitialize(void)
786 struct oletls * info = COM_CurrentInfo();
787 LONG lCOMRefCnt;
789 TRACE("()\n");
791 /* will only happen on OOM */
792 if (!info) return;
794 /* sanity check */
795 if (!info->inits)
797 ERR("Mismatched CoUninitialize\n");
798 return;
801 if (!--info->inits)
803 apartment_release(info->apt);
804 info->apt = NULL;
808 * Decrease the reference count.
809 * If we are back to 0 locks on the COM library, make sure we free
810 * all the associated data structures.
812 lCOMRefCnt = InterlockedExchangeAdd(&s_COMLockCount,-1);
813 if (lCOMRefCnt==1)
815 TRACE("() - Releasing the COM libraries\n");
817 RunningObjectTableImpl_UnInitialize();
819 /* Release the references to the registered class objects */
820 COM_RevokeAllClasses();
822 /* This will free the loaded COM Dlls */
823 CoFreeAllLibraries();
825 /* This ensures we deal with any pending RPCs */
826 COM_FlushMessageQueue();
828 else if (lCOMRefCnt<1) {
829 ERR( "CoUninitialize() - not CoInitialized.\n" );
830 InterlockedExchangeAdd(&s_COMLockCount,1); /* restore the lock count. */
834 /******************************************************************************
835 * CoDisconnectObject [OLE32.@]
837 * Disconnects all connections to this object from remote processes. Dispatches
838 * pending RPCs while blocking new RPCs from occurring, and then calls
839 * IMarshal::DisconnectObject on the given object.
841 * Typically called when the object server is forced to shut down, for instance by
842 * the user.
844 * PARAMS
845 * lpUnk [I] The object whose stub should be disconnected.
846 * reserved [I] Reserved. Should be set to 0.
848 * RETURNS
849 * Success: S_OK.
850 * Failure: HRESULT code.
852 * SEE ALSO
853 * CoMarshalInterface, CoReleaseMarshalData, CoLockObjectExternal
855 HRESULT WINAPI CoDisconnectObject( LPUNKNOWN lpUnk, DWORD reserved )
857 HRESULT hr;
858 IMarshal *marshal;
859 APARTMENT *apt;
861 TRACE("(%p, 0x%08x)\n", lpUnk, reserved);
863 hr = IUnknown_QueryInterface(lpUnk, &IID_IMarshal, (void **)&marshal);
864 if (hr == S_OK)
866 hr = IMarshal_DisconnectObject(marshal, reserved);
867 IMarshal_Release(marshal);
868 return hr;
871 apt = COM_CurrentApt();
872 if (!apt)
873 return CO_E_NOTINITIALIZED;
875 apartment_disconnectobject(apt, lpUnk);
877 /* Note: native is pretty broken here because it just silently
878 * fails, without returning an appropriate error code if the object was
879 * not found, making apps think that the object was disconnected, when
880 * it actually wasn't */
882 return S_OK;
885 /******************************************************************************
886 * CoCreateGuid [OLE32.@]
888 * Simply forwards to UuidCreate in RPCRT4.
890 * PARAMS
891 * pguid [O] Points to the GUID to initialize.
893 * RETURNS
894 * Success: S_OK.
895 * Failure: HRESULT code.
897 * SEE ALSO
898 * UuidCreate
900 HRESULT WINAPI CoCreateGuid(GUID *pguid)
902 return UuidCreate(pguid);
905 /******************************************************************************
906 * CLSIDFromString [OLE32.@]
907 * IIDFromString [OLE32.@]
909 * Converts a unique identifier from its string representation into
910 * the GUID struct.
912 * PARAMS
913 * idstr [I] The string representation of the GUID.
914 * id [O] GUID converted from the string.
916 * RETURNS
917 * S_OK on success
918 * CO_E_CLASSSTRING if idstr is not a valid CLSID
920 * SEE ALSO
921 * StringFromCLSID
923 static HRESULT WINAPI __CLSIDFromString(LPCWSTR s, CLSID *id)
925 int i;
926 BYTE table[256];
928 if (!s) {
929 memset( id, 0, sizeof (CLSID) );
930 return S_OK;
933 /* validate the CLSID string */
934 if (strlenW(s) != 38)
935 return CO_E_CLASSSTRING;
937 if ((s[0]!='{') || (s[9]!='-') || (s[14]!='-') || (s[19]!='-') || (s[24]!='-') || (s[37]!='}'))
938 return CO_E_CLASSSTRING;
940 for (i=1; i<37; i++) {
941 if ((i == 9)||(i == 14)||(i == 19)||(i == 24)) continue;
942 if (!(((s[i] >= '0') && (s[i] <= '9')) ||
943 ((s[i] >= 'a') && (s[i] <= 'f')) ||
944 ((s[i] >= 'A') && (s[i] <= 'F'))))
945 return CO_E_CLASSSTRING;
948 TRACE("%s -> %p\n", debugstr_w(s), id);
950 /* quick lookup table */
951 memset(table, 0, 256);
953 for (i = 0; i < 10; i++) {
954 table['0' + i] = i;
956 for (i = 0; i < 6; i++) {
957 table['A' + i] = i+10;
958 table['a' + i] = i+10;
961 /* in form {XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX} */
963 id->Data1 = (table[s[1]] << 28 | table[s[2]] << 24 | table[s[3]] << 20 | table[s[4]] << 16 |
964 table[s[5]] << 12 | table[s[6]] << 8 | table[s[7]] << 4 | table[s[8]]);
965 id->Data2 = table[s[10]] << 12 | table[s[11]] << 8 | table[s[12]] << 4 | table[s[13]];
966 id->Data3 = table[s[15]] << 12 | table[s[16]] << 8 | table[s[17]] << 4 | table[s[18]];
968 /* these are just sequential bytes */
969 id->Data4[0] = table[s[20]] << 4 | table[s[21]];
970 id->Data4[1] = table[s[22]] << 4 | table[s[23]];
971 id->Data4[2] = table[s[25]] << 4 | table[s[26]];
972 id->Data4[3] = table[s[27]] << 4 | table[s[28]];
973 id->Data4[4] = table[s[29]] << 4 | table[s[30]];
974 id->Data4[5] = table[s[31]] << 4 | table[s[32]];
975 id->Data4[6] = table[s[33]] << 4 | table[s[34]];
976 id->Data4[7] = table[s[35]] << 4 | table[s[36]];
978 return S_OK;
981 /*****************************************************************************/
983 HRESULT WINAPI CLSIDFromString(LPOLESTR idstr, CLSID *id )
985 HRESULT ret;
987 if (!id)
988 return E_INVALIDARG;
990 ret = __CLSIDFromString(idstr, id);
991 if(ret != S_OK) { /* It appears a ProgID is also valid */
992 ret = CLSIDFromProgID(idstr, id);
994 return ret;
997 /* Converts a GUID into the respective string representation. */
998 HRESULT WINE_StringFromCLSID(
999 const CLSID *id, /* [in] GUID to be converted */
1000 LPSTR idstr /* [out] pointer to buffer to contain converted guid */
1002 static const char hex[] = "0123456789ABCDEF";
1003 char *s;
1004 int i;
1006 if (!id)
1007 { ERR("called with id=Null\n");
1008 *idstr = 0x00;
1009 return E_FAIL;
1012 sprintf(idstr, "{%08X-%04X-%04X-%02X%02X-",
1013 id->Data1, id->Data2, id->Data3,
1014 id->Data4[0], id->Data4[1]);
1015 s = &idstr[25];
1017 /* 6 hex bytes */
1018 for (i = 2; i < 8; i++) {
1019 *s++ = hex[id->Data4[i]>>4];
1020 *s++ = hex[id->Data4[i] & 0xf];
1023 *s++ = '}';
1024 *s++ = '\0';
1026 TRACE("%p->%s\n", id, idstr);
1028 return S_OK;
1032 /******************************************************************************
1033 * StringFromCLSID [OLE32.@]
1034 * StringFromIID [OLE32.@]
1036 * Converts a GUID into the respective string representation.
1037 * The target string is allocated using the OLE IMalloc.
1039 * PARAMS
1040 * id [I] the GUID to be converted.
1041 * idstr [O] A pointer to a to-be-allocated pointer pointing to the resulting string.
1043 * RETURNS
1044 * S_OK
1045 * E_FAIL
1047 * SEE ALSO
1048 * StringFromGUID2, CLSIDFromString
1050 HRESULT WINAPI StringFromCLSID(REFCLSID id, LPOLESTR *idstr)
1052 char buf[80];
1053 HRESULT ret;
1054 LPMALLOC mllc;
1056 if ((ret = CoGetMalloc(0,&mllc)))
1057 return ret;
1059 ret=WINE_StringFromCLSID(id,buf);
1060 if (!ret) {
1061 DWORD len = MultiByteToWideChar( CP_ACP, 0, buf, -1, NULL, 0 );
1062 *idstr = IMalloc_Alloc( mllc, len * sizeof(WCHAR) );
1063 MultiByteToWideChar( CP_ACP, 0, buf, -1, *idstr, len );
1065 return ret;
1068 /******************************************************************************
1069 * StringFromGUID2 [OLE32.@]
1070 * StringFromGUID2 [COMPOBJ.76]
1072 * Modified version of StringFromCLSID that allows you to specify max
1073 * buffer size.
1075 * PARAMS
1076 * id [I] GUID to convert to string.
1077 * str [O] Buffer where the result will be stored.
1078 * cmax [I] Size of the buffer in characters.
1080 * RETURNS
1081 * Success: The length of the resulting string in characters.
1082 * Failure: 0.
1084 INT WINAPI StringFromGUID2(REFGUID id, LPOLESTR str, INT cmax)
1086 char xguid[80];
1088 if (WINE_StringFromCLSID(id,xguid))
1089 return 0;
1090 return MultiByteToWideChar( CP_ACP, 0, xguid, -1, str, cmax );
1093 /* open HKCR\\CLSID\\{string form of clsid}\\{keyname} key */
1094 HRESULT COM_OpenKeyForCLSID(REFCLSID clsid, LPCWSTR keyname, REGSAM access, HKEY *subkey)
1096 static const WCHAR wszCLSIDSlash[] = {'C','L','S','I','D','\\',0};
1097 WCHAR path[CHARS_IN_GUID + ARRAYSIZE(wszCLSIDSlash) - 1];
1098 LONG res;
1099 HKEY key;
1101 strcpyW(path, wszCLSIDSlash);
1102 StringFromGUID2(clsid, path + strlenW(wszCLSIDSlash), CHARS_IN_GUID);
1103 res = RegOpenKeyExW(HKEY_CLASSES_ROOT, path, 0, keyname ? KEY_READ : access, &key);
1104 if (res == ERROR_FILE_NOT_FOUND)
1105 return REGDB_E_CLASSNOTREG;
1106 else if (res != ERROR_SUCCESS)
1107 return REGDB_E_READREGDB;
1109 if (!keyname)
1111 *subkey = key;
1112 return S_OK;
1115 res = RegOpenKeyExW(key, keyname, 0, access, subkey);
1116 RegCloseKey(key);
1117 if (res == ERROR_FILE_NOT_FOUND)
1118 return REGDB_E_KEYMISSING;
1119 else if (res != ERROR_SUCCESS)
1120 return REGDB_E_READREGDB;
1122 return S_OK;
1125 /* open HKCR\\AppId\\{string form of appid clsid} key */
1126 HRESULT COM_OpenKeyForAppIdFromCLSID(REFCLSID clsid, REGSAM access, HKEY *subkey)
1128 static const WCHAR szAppId[] = { 'A','p','p','I','d',0 };
1129 static const WCHAR szAppIdKey[] = { 'A','p','p','I','d','\\',0 };
1130 DWORD res;
1131 WCHAR buf[CHARS_IN_GUID];
1132 WCHAR keyname[ARRAYSIZE(szAppIdKey) + CHARS_IN_GUID];
1133 DWORD size;
1134 HKEY hkey;
1135 DWORD type;
1136 HRESULT hr;
1138 /* read the AppID value under the class's key */
1139 hr = COM_OpenKeyForCLSID(clsid, NULL, KEY_READ, &hkey);
1140 if (FAILED(hr))
1141 return hr;
1143 size = sizeof(buf);
1144 res = RegQueryValueExW(hkey, szAppId, NULL, &type, (LPBYTE)buf, &size);
1145 RegCloseKey(hkey);
1146 if (res == ERROR_FILE_NOT_FOUND)
1147 return REGDB_E_KEYMISSING;
1148 else if (res != ERROR_SUCCESS || type!=REG_SZ)
1149 return REGDB_E_READREGDB;
1151 strcpyW(keyname, szAppIdKey);
1152 strcatW(keyname, buf);
1153 res = RegOpenKeyExW(HKEY_CLASSES_ROOT, keyname, 0, access, subkey);
1154 if (res == ERROR_FILE_NOT_FOUND)
1155 return REGDB_E_KEYMISSING;
1156 else if (res != ERROR_SUCCESS)
1157 return REGDB_E_READREGDB;
1159 return S_OK;
1162 /******************************************************************************
1163 * ProgIDFromCLSID [OLE32.@]
1165 * Converts a class id into the respective program ID.
1167 * PARAMS
1168 * clsid [I] Class ID, as found in registry.
1169 * ppszProgID [O] Associated ProgID.
1171 * RETURNS
1172 * S_OK
1173 * E_OUTOFMEMORY
1174 * REGDB_E_CLASSNOTREG if the given clsid has no associated ProgID
1176 HRESULT WINAPI ProgIDFromCLSID(REFCLSID clsid, LPOLESTR *ppszProgID)
1178 static const WCHAR wszProgID[] = {'P','r','o','g','I','D',0};
1179 HKEY hkey;
1180 HRESULT ret;
1181 LONG progidlen = 0;
1183 if (!ppszProgID)
1185 ERR("ppszProgId isn't optional\n");
1186 return E_INVALIDARG;
1189 *ppszProgID = NULL;
1190 ret = COM_OpenKeyForCLSID(clsid, wszProgID, KEY_READ, &hkey);
1191 if (FAILED(ret))
1192 return ret;
1194 if (RegQueryValueW(hkey, NULL, NULL, &progidlen))
1195 ret = REGDB_E_CLASSNOTREG;
1197 if (ret == S_OK)
1199 *ppszProgID = CoTaskMemAlloc(progidlen * sizeof(WCHAR));
1200 if (*ppszProgID)
1202 if (RegQueryValueW(hkey, NULL, *ppszProgID, &progidlen))
1203 ret = REGDB_E_CLASSNOTREG;
1205 else
1206 ret = E_OUTOFMEMORY;
1209 RegCloseKey(hkey);
1210 return ret;
1213 /******************************************************************************
1214 * CLSIDFromProgID [OLE32.@]
1216 * Converts a program id into the respective GUID.
1218 * PARAMS
1219 * progid [I] Unicode program ID, as found in registry.
1220 * clsid [O] Associated CLSID.
1222 * RETURNS
1223 * Success: S_OK
1224 * Failure: CO_E_CLASSSTRING - the given ProgID cannot be found.
1226 HRESULT WINAPI CLSIDFromProgID(LPCOLESTR progid, LPCLSID clsid)
1228 static const WCHAR clsidW[] = { '\\','C','L','S','I','D',0 };
1229 WCHAR buf2[CHARS_IN_GUID];
1230 LONG buf2len = sizeof(buf2);
1231 HKEY xhkey;
1232 WCHAR *buf;
1234 if (!progid || !clsid)
1236 ERR("neither progid (%p) nor clsid (%p) are optional\n", progid, clsid);
1237 return E_INVALIDARG;
1240 /* initialise clsid in case of failure */
1241 memset(clsid, 0, sizeof(*clsid));
1243 buf = HeapAlloc( GetProcessHeap(),0,(strlenW(progid)+8) * sizeof(WCHAR) );
1244 strcpyW( buf, progid );
1245 strcatW( buf, clsidW );
1246 if (RegOpenKeyW(HKEY_CLASSES_ROOT,buf,&xhkey))
1248 HeapFree(GetProcessHeap(),0,buf);
1249 WARN("couldn't open key for ProgID %s\n", debugstr_w(progid));
1250 return CO_E_CLASSSTRING;
1252 HeapFree(GetProcessHeap(),0,buf);
1254 if (RegQueryValueW(xhkey,NULL,buf2,&buf2len))
1256 RegCloseKey(xhkey);
1257 WARN("couldn't query clsid value for ProgID %s\n", debugstr_w(progid));
1258 return CO_E_CLASSSTRING;
1260 RegCloseKey(xhkey);
1261 return CLSIDFromString(buf2,clsid);
1265 /*****************************************************************************
1266 * CoGetPSClsid [OLE32.@]
1268 * Retrieves the CLSID of the proxy/stub factory that implements
1269 * IPSFactoryBuffer for the specified interface.
1271 * PARAMS
1272 * riid [I] Interface whose proxy/stub CLSID is to be returned.
1273 * pclsid [O] Where to store returned proxy/stub CLSID.
1275 * RETURNS
1276 * S_OK
1277 * E_OUTOFMEMORY
1278 * REGDB_E_IIDNOTREG if no PSFactoryBuffer is associated with the IID, or it could not be parsed
1280 * NOTES
1282 * The standard marshaller activates the object with the CLSID
1283 * returned and uses the CreateProxy and CreateStub methods on its
1284 * IPSFactoryBuffer interface to construct the proxies and stubs for a
1285 * given object.
1287 * CoGetPSClsid determines this CLSID by searching the
1288 * HKEY_CLASSES_ROOT\Interface\{string form of riid}\ProxyStubClsid32
1289 * in the registry and any interface id registered by
1290 * CoRegisterPSClsid within the current process.
1292 * BUGS
1294 * Native returns S_OK for interfaces with a key in HKCR\Interface, but
1295 * without a ProxyStubClsid32 key and leaves garbage in pclsid. This should be
1296 * considered a bug in native unless an application depends on this (unlikely).
1298 * SEE ALSO
1299 * CoRegisterPSClsid.
1301 HRESULT WINAPI CoGetPSClsid(REFIID riid, CLSID *pclsid)
1303 static const WCHAR wszInterface[] = {'I','n','t','e','r','f','a','c','e','\\',0};
1304 static const WCHAR wszPSC[] = {'\\','P','r','o','x','y','S','t','u','b','C','l','s','i','d','3','2',0};
1305 WCHAR path[ARRAYSIZE(wszInterface) - 1 + CHARS_IN_GUID - 1 + ARRAYSIZE(wszPSC)];
1306 WCHAR value[CHARS_IN_GUID];
1307 LONG len;
1308 HKEY hkey;
1309 APARTMENT *apt = COM_CurrentApt();
1310 struct registered_psclsid *registered_psclsid;
1312 TRACE("() riid=%s, pclsid=%p\n", debugstr_guid(riid), pclsid);
1314 if (!apt)
1316 ERR("apartment not initialised\n");
1317 return CO_E_NOTINITIALIZED;
1320 if (!pclsid)
1322 ERR("pclsid isn't optional\n");
1323 return E_INVALIDARG;
1326 EnterCriticalSection(&apt->cs);
1328 LIST_FOR_EACH_ENTRY(registered_psclsid, &apt->psclsids, struct registered_psclsid, entry)
1329 if (IsEqualIID(&registered_psclsid->iid, riid))
1331 *pclsid = registered_psclsid->clsid;
1332 LeaveCriticalSection(&apt->cs);
1333 return S_OK;
1336 LeaveCriticalSection(&apt->cs);
1338 /* Interface\\{string form of riid}\\ProxyStubClsid32 */
1339 strcpyW(path, wszInterface);
1340 StringFromGUID2(riid, path + ARRAYSIZE(wszInterface) - 1, CHARS_IN_GUID);
1341 strcpyW(path + ARRAYSIZE(wszInterface) - 1 + CHARS_IN_GUID - 1, wszPSC);
1343 /* Open the key.. */
1344 if (RegOpenKeyExW(HKEY_CLASSES_ROOT, path, 0, KEY_READ, &hkey))
1346 WARN("No PSFactoryBuffer object is registered for IID %s\n", debugstr_guid(riid));
1347 return REGDB_E_IIDNOTREG;
1350 /* ... Once we have the key, query the registry to get the
1351 value of CLSID as a string, and convert it into a
1352 proper CLSID structure to be passed back to the app */
1353 len = sizeof(value);
1354 if (ERROR_SUCCESS != RegQueryValueW(hkey, NULL, value, &len))
1356 RegCloseKey(hkey);
1357 return REGDB_E_IIDNOTREG;
1359 RegCloseKey(hkey);
1361 /* We have the CLSid we want back from the registry as a string, so
1362 lets convert it into a CLSID structure */
1363 if (CLSIDFromString(value, pclsid) != NOERROR)
1364 return REGDB_E_IIDNOTREG;
1366 TRACE ("() Returning CLSID=%s\n", debugstr_guid(pclsid));
1367 return S_OK;
1370 /*****************************************************************************
1371 * CoRegisterPSClsid [OLE32.@]
1373 * Register a proxy/stub CLSID for the given interface in the current process
1374 * only.
1376 * PARAMS
1377 * riid [I] Interface whose proxy/stub CLSID is to be registered.
1378 * rclsid [I] CLSID of the proxy/stub.
1380 * RETURNS
1381 * Success: S_OK
1382 * Failure: E_OUTOFMEMORY
1384 * NOTES
1386 * This function does not add anything to the registry and the effects are
1387 * limited to the lifetime of the current process.
1389 * SEE ALSO
1390 * CoGetPSClsid.
1392 HRESULT WINAPI CoRegisterPSClsid(REFIID riid, REFCLSID rclsid)
1394 APARTMENT *apt = COM_CurrentApt();
1395 struct registered_psclsid *registered_psclsid;
1397 TRACE("(%s, %s)\n", debugstr_guid(riid), debugstr_guid(rclsid));
1399 if (!apt)
1401 ERR("apartment not initialised\n");
1402 return CO_E_NOTINITIALIZED;
1405 EnterCriticalSection(&apt->cs);
1407 LIST_FOR_EACH_ENTRY(registered_psclsid, &apt->psclsids, struct registered_psclsid, entry)
1408 if (IsEqualIID(&registered_psclsid->iid, riid))
1410 registered_psclsid->clsid = *rclsid;
1411 LeaveCriticalSection(&apt->cs);
1412 return S_OK;
1415 registered_psclsid = HeapAlloc(GetProcessHeap(), 0, sizeof(struct registered_psclsid));
1416 if (!registered_psclsid)
1418 LeaveCriticalSection(&apt->cs);
1419 return E_OUTOFMEMORY;
1422 registered_psclsid->iid = *riid;
1423 registered_psclsid->clsid = *rclsid;
1424 list_add_head(&apt->psclsids, &registered_psclsid->entry);
1426 LeaveCriticalSection(&apt->cs);
1428 return S_OK;
1432 /***
1433 * COM_GetRegisteredClassObject
1435 * This internal method is used to scan the registered class list to
1436 * find a class object.
1438 * Params:
1439 * rclsid Class ID of the class to find.
1440 * dwClsContext Class context to match.
1441 * ppv [out] returns a pointer to the class object. Complying
1442 * to normal COM usage, this method will increase the
1443 * reference count on this object.
1445 static HRESULT COM_GetRegisteredClassObject(
1446 REFCLSID rclsid,
1447 DWORD dwClsContext,
1448 LPUNKNOWN* ppUnk)
1450 HRESULT hr = S_FALSE;
1451 RegisteredClass *curClass;
1454 * Sanity check
1456 assert(ppUnk!=0);
1458 EnterCriticalSection( &csRegisteredClassList );
1460 LIST_FOR_EACH_ENTRY(curClass, &RegisteredClassList, RegisteredClass, entry)
1463 * Check if we have a match on the class ID and context.
1465 if ((dwClsContext & curClass->runContext) &&
1466 IsEqualGUID(&(curClass->classIdentifier), rclsid))
1469 * We have a match, return the pointer to the class object.
1471 *ppUnk = curClass->classObject;
1473 IUnknown_AddRef(curClass->classObject);
1475 hr = S_OK;
1476 break;
1480 LeaveCriticalSection( &csRegisteredClassList );
1482 return hr;
1485 /******************************************************************************
1486 * CoRegisterClassObject [OLE32.@]
1488 * Registers the class object for a given class ID. Servers housed in EXE
1489 * files use this method instead of exporting DllGetClassObject to allow
1490 * other code to connect to their objects.
1492 * PARAMS
1493 * rclsid [I] CLSID of the object to register.
1494 * pUnk [I] IUnknown of the object.
1495 * dwClsContext [I] CLSCTX flags indicating the context in which to run the executable.
1496 * flags [I] REGCLS flags indicating how connections are made.
1497 * lpdwRegister [I] A unique cookie that can be passed to CoRevokeClassObject.
1499 * RETURNS
1500 * S_OK on success,
1501 * E_INVALIDARG if lpdwRegister or pUnk are NULL,
1502 * CO_E_OBJISREG if the object is already registered. We should not return this.
1504 * SEE ALSO
1505 * CoRevokeClassObject, CoGetClassObject
1507 * BUGS
1508 * MSDN claims that multiple interface registrations are legal, but we
1509 * can't do that with our current implementation.
1511 HRESULT WINAPI CoRegisterClassObject(
1512 REFCLSID rclsid,
1513 LPUNKNOWN pUnk,
1514 DWORD dwClsContext,
1515 DWORD flags,
1516 LPDWORD lpdwRegister)
1518 RegisteredClass* newClass;
1519 LPUNKNOWN foundObject;
1520 HRESULT hr;
1522 TRACE("(%s,%p,0x%08x,0x%08x,%p)\n",
1523 debugstr_guid(rclsid),pUnk,dwClsContext,flags,lpdwRegister);
1525 if ( (lpdwRegister==0) || (pUnk==0) )
1526 return E_INVALIDARG;
1528 if (!COM_CurrentApt())
1530 ERR("COM was not initialized\n");
1531 return CO_E_NOTINITIALIZED;
1534 *lpdwRegister = 0;
1536 /* REGCLS_MULTIPLEUSE implies registering as inproc server. This is what
1537 * differentiates the flag from REGCLS_MULTI_SEPARATE. */
1538 if (flags & REGCLS_MULTIPLEUSE)
1539 dwClsContext |= CLSCTX_INPROC_SERVER;
1542 * First, check if the class is already registered.
1543 * If it is, this should cause an error.
1545 hr = COM_GetRegisteredClassObject(rclsid, dwClsContext, &foundObject);
1546 if (hr == S_OK) {
1547 if (flags & REGCLS_MULTIPLEUSE) {
1548 if (dwClsContext & CLSCTX_LOCAL_SERVER)
1549 hr = CoLockObjectExternal(foundObject, TRUE, FALSE);
1550 IUnknown_Release(foundObject);
1551 return hr;
1553 IUnknown_Release(foundObject);
1554 ERR("object already registered for class %s\n", debugstr_guid(rclsid));
1555 return CO_E_OBJISREG;
1558 newClass = HeapAlloc(GetProcessHeap(), 0, sizeof(RegisteredClass));
1559 if ( newClass == NULL )
1560 return E_OUTOFMEMORY;
1562 newClass->classIdentifier = *rclsid;
1563 newClass->runContext = dwClsContext;
1564 newClass->connectFlags = flags;
1565 newClass->pMarshaledData = NULL;
1566 newClass->RpcRegistration = NULL;
1569 * Use the address of the chain node as the cookie since we are sure it's
1570 * unique. FIXME: not on 64-bit platforms.
1572 newClass->dwCookie = (DWORD)newClass;
1575 * Since we're making a copy of the object pointer, we have to increase its
1576 * reference count.
1578 newClass->classObject = pUnk;
1579 IUnknown_AddRef(newClass->classObject);
1581 EnterCriticalSection( &csRegisteredClassList );
1582 list_add_tail(&RegisteredClassList, &newClass->entry);
1583 LeaveCriticalSection( &csRegisteredClassList );
1585 *lpdwRegister = newClass->dwCookie;
1587 if (dwClsContext & CLSCTX_LOCAL_SERVER) {
1588 IClassFactory *classfac;
1590 hr = IUnknown_QueryInterface(newClass->classObject, &IID_IClassFactory,
1591 (LPVOID*)&classfac);
1592 if (hr) return hr;
1594 hr = CreateStreamOnHGlobal(0, TRUE, &newClass->pMarshaledData);
1595 if (hr) {
1596 FIXME("Failed to create stream on hglobal, %x\n", hr);
1597 IUnknown_Release(classfac);
1598 return hr;
1600 hr = CoMarshalInterface(newClass->pMarshaledData, &IID_IClassFactory,
1601 (LPVOID)classfac, MSHCTX_LOCAL, NULL,
1602 MSHLFLAGS_TABLESTRONG);
1603 if (hr) {
1604 FIXME("CoMarshalInterface failed, %x!\n",hr);
1605 IUnknown_Release(classfac);
1606 return hr;
1609 IUnknown_Release(classfac);
1611 hr = RPC_StartLocalServer(&newClass->classIdentifier,
1612 newClass->pMarshaledData,
1613 flags & (REGCLS_MULTIPLEUSE|REGCLS_MULTI_SEPARATE),
1614 &newClass->RpcRegistration);
1616 return S_OK;
1619 /***********************************************************************
1620 * CoRevokeClassObject [OLE32.@]
1622 * Removes a class object from the class registry.
1624 * PARAMS
1625 * dwRegister [I] Cookie returned from CoRegisterClassObject().
1627 * RETURNS
1628 * Success: S_OK.
1629 * Failure: HRESULT code.
1631 * SEE ALSO
1632 * CoRegisterClassObject
1634 HRESULT WINAPI CoRevokeClassObject(
1635 DWORD dwRegister)
1637 HRESULT hr = E_INVALIDARG;
1638 RegisteredClass *curClass;
1640 TRACE("(%08x)\n",dwRegister);
1642 EnterCriticalSection( &csRegisteredClassList );
1644 LIST_FOR_EACH_ENTRY(curClass, &RegisteredClassList, RegisteredClass, entry)
1647 * Check if we have a match on the cookie.
1649 if (curClass->dwCookie == dwRegister)
1651 list_remove(&curClass->entry);
1653 if (curClass->runContext & CLSCTX_LOCAL_SERVER)
1654 RPC_StopLocalServer(curClass->RpcRegistration);
1657 * Release the reference to the class object.
1659 IUnknown_Release(curClass->classObject);
1661 if (curClass->pMarshaledData)
1663 LARGE_INTEGER zero;
1664 memset(&zero, 0, sizeof(zero));
1665 IStream_Seek(curClass->pMarshaledData, zero, STREAM_SEEK_SET, NULL);
1666 CoReleaseMarshalData(curClass->pMarshaledData);
1670 * Free the memory used by the chain node.
1672 HeapFree(GetProcessHeap(), 0, curClass);
1674 hr = S_OK;
1675 break;
1679 LeaveCriticalSection( &csRegisteredClassList );
1681 return hr;
1684 /***********************************************************************
1685 * COM_RegReadPath [internal]
1687 * Reads a registry value and expands it when necessary
1689 static DWORD COM_RegReadPath(HKEY hkeyroot, const WCHAR *keyname, const WCHAR *valuename, WCHAR * dst, DWORD dstlen)
1691 DWORD ret;
1692 HKEY key;
1693 DWORD keytype;
1694 WCHAR src[MAX_PATH];
1695 DWORD dwLength = dstlen * sizeof(WCHAR);
1697 if((ret = RegOpenKeyExW(hkeyroot, keyname, 0, KEY_READ, &key)) == ERROR_SUCCESS) {
1698 if( (ret = RegQueryValueExW(key, NULL, NULL, &keytype, (LPBYTE)src, &dwLength)) == ERROR_SUCCESS ) {
1699 if (keytype == REG_EXPAND_SZ) {
1700 if (dstlen <= ExpandEnvironmentStringsW(src, dst, dstlen)) ret = ERROR_MORE_DATA;
1701 } else {
1702 lstrcpynW(dst, src, dstlen);
1705 RegCloseKey (key);
1707 return ret;
1710 static void get_threading_model(HKEY key, LPWSTR value, DWORD len)
1712 static const WCHAR wszThreadingModel[] = {'T','h','r','e','a','d','i','n','g','M','o','d','e','l',0};
1713 DWORD keytype;
1714 DWORD ret;
1715 DWORD dwLength = len * sizeof(WCHAR);
1717 ret = RegQueryValueExW(key, wszThreadingModel, NULL, &keytype, (LPBYTE)value, &dwLength);
1718 if ((ret != ERROR_SUCCESS) || (keytype != REG_SZ))
1719 value[0] = '\0';
1722 static HRESULT get_inproc_class_object(HKEY hkeydll, REFCLSID rclsid, REFIID riid, void **ppv)
1724 static const WCHAR wszApartment[] = {'A','p','a','r','t','m','e','n','t',0};
1725 static const WCHAR wszFree[] = {'F','r','e','e',0};
1726 static const WCHAR wszBoth[] = {'B','o','t','h',0};
1727 HINSTANCE hLibrary;
1728 typedef HRESULT (CALLBACK *DllGetClassObjectFunc)(REFCLSID clsid, REFIID iid, LPVOID *ppv);
1729 DllGetClassObjectFunc DllGetClassObject;
1730 WCHAR dllpath[MAX_PATH+1];
1731 WCHAR threading_model[10 /* strlenW(L"apartment")+1 */];
1732 HRESULT hr;
1734 get_threading_model(hkeydll, threading_model, ARRAYSIZE(threading_model));
1735 /* "Apartment" */
1736 if (!strcmpiW(threading_model, wszApartment))
1738 APARTMENT *apt = COM_CurrentApt();
1739 if (apt->multi_threaded)
1741 /* try to find an STA */
1742 APARTMENT *host_apt = apartment_findfromtype(FALSE, FALSE);
1743 if (!host_apt)
1744 FIXME("create a host apartment for apartment-threaded object %s\n", debugstr_guid(rclsid));
1745 if (host_apt)
1747 struct host_object_params params;
1748 HWND hwnd = apartment_getwindow(host_apt);
1750 params.hkeydll = hkeydll;
1751 params.clsid = *rclsid;
1752 params.iid = *riid;
1753 hr = CreateStreamOnHGlobal(NULL, TRUE, &params.stream);
1754 if (FAILED(hr))
1755 return hr;
1756 hr = SendMessageW(hwnd, DM_HOSTOBJECT, 0, (LPARAM)&params);
1757 if (SUCCEEDED(hr))
1758 hr = CoUnmarshalInterface(params.stream, riid, ppv);
1759 IStream_Release(params.stream);
1760 return hr;
1764 /* "Free" */
1765 else if (!strcmpiW(threading_model, wszFree))
1767 APARTMENT *apt = COM_CurrentApt();
1768 if (!apt->multi_threaded)
1770 FIXME("should create object %s in multi-threaded apartment\n",
1771 debugstr_guid(rclsid));
1774 /* everything except "Apartment", "Free" and "Both" */
1775 else if (strcmpiW(threading_model, wszBoth))
1777 APARTMENT *apt = COM_CurrentApt();
1779 /* everything else is main-threaded */
1780 if (threading_model[0])
1781 FIXME("unrecognised threading model %s for object %s, should be main-threaded?\n",
1782 debugstr_w(threading_model), debugstr_guid(rclsid));
1784 if (apt->multi_threaded || !apt->main)
1786 /* try to find an STA */
1787 APARTMENT *host_apt = apartment_findfromtype(FALSE, TRUE);
1788 if (!host_apt)
1789 FIXME("create a host apartment for main-threaded object %s\n", debugstr_guid(rclsid));
1790 if (host_apt)
1792 struct host_object_params params;
1793 HWND hwnd = apartment_getwindow(host_apt);
1795 params.hkeydll = hkeydll;
1796 params.clsid = *rclsid;
1797 params.iid = *riid;
1798 hr = CreateStreamOnHGlobal(NULL, TRUE, &params.stream);
1799 if (FAILED(hr))
1800 return hr;
1801 hr = SendMessageW(hwnd, DM_HOSTOBJECT, 0, (LPARAM)&params);
1802 if (SUCCEEDED(hr))
1803 hr = CoUnmarshalInterface(params.stream, riid, ppv);
1804 IStream_Release(params.stream);
1805 return hr;
1810 if (COM_RegReadPath(hkeydll, NULL, NULL, dllpath, ARRAYSIZE(dllpath)) != ERROR_SUCCESS)
1812 /* failure: CLSID is not found in registry */
1813 WARN("class %s not registered inproc\n", debugstr_guid(rclsid));
1814 return REGDB_E_CLASSNOTREG;
1817 if ((hLibrary = LoadLibraryExW(dllpath, 0, LOAD_WITH_ALTERED_SEARCH_PATH)) == 0)
1819 /* failure: DLL could not be loaded */
1820 ERR("couldn't load in-process dll %s\n", debugstr_w(dllpath));
1821 return E_ACCESSDENIED; /* FIXME: or should this be CO_E_DLLNOTFOUND? */
1824 if (!(DllGetClassObject = (DllGetClassObjectFunc)GetProcAddress(hLibrary, "DllGetClassObject")))
1826 /* failure: the dll did not export DllGetClassObject */
1827 ERR("couldn't find function DllGetClassObject in %s\n", debugstr_w(dllpath));
1828 FreeLibrary( hLibrary );
1829 return CO_E_DLLNOTFOUND;
1832 /* OK: get the ClassObject */
1833 COMPOBJ_DLLList_Add( hLibrary );
1834 hr = DllGetClassObject(rclsid, riid, ppv);
1836 if (hr != S_OK)
1837 ERR("DllGetClassObject returned error 0x%08x\n", hr);
1839 return hr;
1842 /***********************************************************************
1843 * CoGetClassObject [OLE32.@]
1845 * Creates an object of the specified class.
1847 * PARAMS
1848 * rclsid [I] Class ID to create an instance of.
1849 * dwClsContext [I] Flags to restrict the location of the created instance.
1850 * pServerInfo [I] Optional. Details for connecting to a remote server.
1851 * iid [I] The ID of the interface of the instance to return.
1852 * ppv [O] On returns, contains a pointer to the specified interface of the object.
1854 * RETURNS
1855 * Success: S_OK
1856 * Failure: HRESULT code.
1858 * NOTES
1859 * The dwClsContext parameter can be one or more of the following:
1860 *| CLSCTX_INPROC_SERVER - Use an in-process server, such as from a DLL.
1861 *| CLSCTX_INPROC_HANDLER - Use an in-process object which handles certain functions for an object running in another process.
1862 *| CLSCTX_LOCAL_SERVER - Connect to an object running in another process.
1863 *| CLSCTX_REMOTE_SERVER - Connect to an object running on another machine.
1865 * SEE ALSO
1866 * CoCreateInstance()
1868 HRESULT WINAPI CoGetClassObject(
1869 REFCLSID rclsid, DWORD dwClsContext, COSERVERINFO *pServerInfo,
1870 REFIID iid, LPVOID *ppv)
1872 LPUNKNOWN regClassObject;
1873 HRESULT hres = E_UNEXPECTED;
1875 TRACE("\n\tCLSID:\t%s,\n\tIID:\t%s\n", debugstr_guid(rclsid), debugstr_guid(iid));
1877 if (!ppv)
1878 return E_INVALIDARG;
1880 *ppv = NULL;
1882 if (!COM_CurrentApt())
1884 ERR("apartment not initialised\n");
1885 return CO_E_NOTINITIALIZED;
1888 if (pServerInfo) {
1889 FIXME("\tpServerInfo: name=%s\n",debugstr_w(pServerInfo->pwszName));
1890 FIXME("\t\tpAuthInfo=%p\n",pServerInfo->pAuthInfo);
1894 * First, try and see if we can't match the class ID with one of the
1895 * registered classes.
1897 if (S_OK == COM_GetRegisteredClassObject(rclsid, dwClsContext, &regClassObject))
1899 /* Get the required interface from the retrieved pointer. */
1900 hres = IUnknown_QueryInterface(regClassObject, iid, ppv);
1903 * Since QI got another reference on the pointer, we want to release the
1904 * one we already have. If QI was unsuccessful, this will release the object. This
1905 * is good since we are not returning it in the "out" parameter.
1907 IUnknown_Release(regClassObject);
1909 return hres;
1912 /* First try in-process server */
1913 if (CLSCTX_INPROC_SERVER & dwClsContext)
1915 static const WCHAR wszInprocServer32[] = {'I','n','p','r','o','c','S','e','r','v','e','r','3','2',0};
1916 HKEY hkey;
1918 if (IsEqualCLSID(rclsid, &CLSID_InProcFreeMarshaler))
1919 return FTMarshalCF_Create(iid, ppv);
1921 hres = COM_OpenKeyForCLSID(rclsid, wszInprocServer32, KEY_READ, &hkey);
1922 if (FAILED(hres))
1924 if (hres == REGDB_E_CLASSNOTREG)
1925 ERR("class %s not registered\n", debugstr_guid(rclsid));
1926 else
1927 WARN("class %s not registered as in-proc server\n", debugstr_guid(rclsid));
1930 if (SUCCEEDED(hres))
1932 hres = get_inproc_class_object(hkey, rclsid, iid, ppv);
1933 RegCloseKey(hkey);
1936 /* return if we got a class, otherwise fall through to one of the
1937 * other types */
1938 if (SUCCEEDED(hres))
1939 return hres;
1942 /* Next try in-process handler */
1943 if (CLSCTX_INPROC_HANDLER & dwClsContext)
1945 static const WCHAR wszInprocHandler32[] = {'I','n','p','r','o','c','H','a','n','d','l','e','r','3','2',0};
1946 HKEY hkey;
1948 hres = COM_OpenKeyForCLSID(rclsid, wszInprocHandler32, KEY_READ, &hkey);
1949 if (FAILED(hres))
1951 if (hres == REGDB_E_CLASSNOTREG)
1952 ERR("class %s not registered\n", debugstr_guid(rclsid));
1953 else
1954 WARN("class %s not registered in-proc handler\n", debugstr_guid(rclsid));
1957 if (SUCCEEDED(hres))
1959 hres = get_inproc_class_object(hkey, rclsid, iid, ppv);
1960 RegCloseKey(hkey);
1963 /* return if we got a class, otherwise fall through to one of the
1964 * other types */
1965 if (SUCCEEDED(hres))
1966 return hres;
1969 /* Next try out of process */
1970 if (CLSCTX_LOCAL_SERVER & dwClsContext)
1972 hres = RPC_GetLocalClassObject(rclsid,iid,ppv);
1973 if (SUCCEEDED(hres))
1974 return hres;
1977 /* Finally try remote: this requires networked DCOM (a lot of work) */
1978 if (CLSCTX_REMOTE_SERVER & dwClsContext)
1980 FIXME ("CLSCTX_REMOTE_SERVER not supported\n");
1981 hres = E_NOINTERFACE;
1984 if (FAILED(hres))
1985 ERR("no class object %s could be created for context 0x%x\n",
1986 debugstr_guid(rclsid), dwClsContext);
1987 return hres;
1990 /***********************************************************************
1991 * CoResumeClassObjects (OLE32.@)
1993 * Resumes all class objects registered with REGCLS_SUSPENDED.
1995 * RETURNS
1996 * Success: S_OK.
1997 * Failure: HRESULT code.
1999 HRESULT WINAPI CoResumeClassObjects(void)
2001 FIXME("stub\n");
2002 return S_OK;
2005 /***********************************************************************
2006 * CoCreateInstance [OLE32.@]
2008 * Creates an instance of the specified class.
2010 * PARAMS
2011 * rclsid [I] Class ID to create an instance of.
2012 * pUnkOuter [I] Optional outer unknown to allow aggregation with another object.
2013 * dwClsContext [I] Flags to restrict the location of the created instance.
2014 * iid [I] The ID of the interface of the instance to return.
2015 * ppv [O] On returns, contains a pointer to the specified interface of the instance.
2017 * RETURNS
2018 * Success: S_OK
2019 * Failure: HRESULT code.
2021 * NOTES
2022 * The dwClsContext parameter can be one or more of the following:
2023 *| CLSCTX_INPROC_SERVER - Use an in-process server, such as from a DLL.
2024 *| CLSCTX_INPROC_HANDLER - Use an in-process object which handles certain functions for an object running in another process.
2025 *| CLSCTX_LOCAL_SERVER - Connect to an object running in another process.
2026 *| CLSCTX_REMOTE_SERVER - Connect to an object running on another machine.
2028 * Aggregation is the concept of deferring the IUnknown of an object to another
2029 * object. This allows a separate object to behave as though it was part of
2030 * the object and to allow this the pUnkOuter parameter can be set. Note that
2031 * not all objects support having an outer of unknown.
2033 * SEE ALSO
2034 * CoGetClassObject()
2036 HRESULT WINAPI CoCreateInstance(
2037 REFCLSID rclsid,
2038 LPUNKNOWN pUnkOuter,
2039 DWORD dwClsContext,
2040 REFIID iid,
2041 LPVOID *ppv)
2043 HRESULT hres;
2044 LPCLASSFACTORY lpclf = 0;
2046 TRACE("(rclsid=%s, pUnkOuter=%p, dwClsContext=%08x, riid=%s, ppv=%p)\n", debugstr_guid(rclsid),
2047 pUnkOuter, dwClsContext, debugstr_guid(iid), ppv);
2050 * Sanity check
2052 if (ppv==0)
2053 return E_POINTER;
2056 * Initialize the "out" parameter
2058 *ppv = 0;
2060 if (!COM_CurrentApt())
2062 ERR("apartment not initialised\n");
2063 return CO_E_NOTINITIALIZED;
2067 * The Standard Global Interface Table (GIT) object is a process-wide singleton.
2068 * Rather than create a class factory, we can just check for it here
2070 if (IsEqualIID(rclsid, &CLSID_StdGlobalInterfaceTable)) {
2071 if (StdGlobalInterfaceTableInstance == NULL)
2072 StdGlobalInterfaceTableInstance = StdGlobalInterfaceTable_Construct();
2073 hres = IGlobalInterfaceTable_QueryInterface( (IGlobalInterfaceTable*) StdGlobalInterfaceTableInstance, iid, ppv);
2074 if (hres) return hres;
2076 TRACE("Retrieved GIT (%p)\n", *ppv);
2077 return S_OK;
2081 * Get a class factory to construct the object we want.
2083 hres = CoGetClassObject(rclsid,
2084 dwClsContext,
2085 NULL,
2086 &IID_IClassFactory,
2087 (LPVOID)&lpclf);
2089 if (FAILED(hres))
2090 return hres;
2093 * Create the object and don't forget to release the factory
2095 hres = IClassFactory_CreateInstance(lpclf, pUnkOuter, iid, ppv);
2096 IClassFactory_Release(lpclf);
2097 if(FAILED(hres))
2098 FIXME("no instance created for interface %s of class %s, hres is 0x%08x\n",
2099 debugstr_guid(iid), debugstr_guid(rclsid),hres);
2101 return hres;
2104 /***********************************************************************
2105 * CoCreateInstanceEx [OLE32.@]
2107 HRESULT WINAPI CoCreateInstanceEx(
2108 REFCLSID rclsid,
2109 LPUNKNOWN pUnkOuter,
2110 DWORD dwClsContext,
2111 COSERVERINFO* pServerInfo,
2112 ULONG cmq,
2113 MULTI_QI* pResults)
2115 IUnknown* pUnk = NULL;
2116 HRESULT hr;
2117 ULONG index;
2118 ULONG successCount = 0;
2121 * Sanity check
2123 if ( (cmq==0) || (pResults==NULL))
2124 return E_INVALIDARG;
2126 if (pServerInfo!=NULL)
2127 FIXME("() non-NULL pServerInfo not supported!\n");
2130 * Initialize all the "out" parameters.
2132 for (index = 0; index < cmq; index++)
2134 pResults[index].pItf = NULL;
2135 pResults[index].hr = E_NOINTERFACE;
2139 * Get the object and get its IUnknown pointer.
2141 hr = CoCreateInstance(rclsid,
2142 pUnkOuter,
2143 dwClsContext,
2144 &IID_IUnknown,
2145 (VOID**)&pUnk);
2147 if (hr)
2148 return hr;
2151 * Then, query for all the interfaces requested.
2153 for (index = 0; index < cmq; index++)
2155 pResults[index].hr = IUnknown_QueryInterface(pUnk,
2156 pResults[index].pIID,
2157 (VOID**)&(pResults[index].pItf));
2159 if (pResults[index].hr == S_OK)
2160 successCount++;
2164 * Release our temporary unknown pointer.
2166 IUnknown_Release(pUnk);
2168 if (successCount == 0)
2169 return E_NOINTERFACE;
2171 if (successCount!=cmq)
2172 return CO_S_NOTALLINTERFACES;
2174 return S_OK;
2177 /***********************************************************************
2178 * CoLoadLibrary (OLE32.@)
2180 * Loads a library.
2182 * PARAMS
2183 * lpszLibName [I] Path to library.
2184 * bAutoFree [I] Whether the library should automatically be freed.
2186 * RETURNS
2187 * Success: Handle to loaded library.
2188 * Failure: NULL.
2190 * SEE ALSO
2191 * CoFreeLibrary, CoFreeAllLibraries, CoFreeUnusedLibraries
2193 HINSTANCE WINAPI CoLoadLibrary(LPOLESTR lpszLibName, BOOL bAutoFree)
2195 TRACE("(%s, %d)\n", debugstr_w(lpszLibName), bAutoFree);
2197 return LoadLibraryExW(lpszLibName, 0, LOAD_WITH_ALTERED_SEARCH_PATH);
2200 /***********************************************************************
2201 * CoFreeLibrary [OLE32.@]
2203 * Unloads a library from memory.
2205 * PARAMS
2206 * hLibrary [I] Handle to library to unload.
2208 * RETURNS
2209 * Nothing
2211 * SEE ALSO
2212 * CoLoadLibrary, CoFreeAllLibraries, CoFreeUnusedLibraries
2214 void WINAPI CoFreeLibrary(HINSTANCE hLibrary)
2216 FreeLibrary(hLibrary);
2220 /***********************************************************************
2221 * CoFreeAllLibraries [OLE32.@]
2223 * Function for backwards compatibility only. Does nothing.
2225 * RETURNS
2226 * Nothing.
2228 * SEE ALSO
2229 * CoLoadLibrary, CoFreeLibrary, CoFreeUnusedLibraries
2231 void WINAPI CoFreeAllLibraries(void)
2233 /* NOP */
2237 /***********************************************************************
2238 * CoFreeUnusedLibraries [OLE32.@]
2239 * CoFreeUnusedLibraries [COMPOBJ.17]
2241 * Frees any unused libraries. Unused are identified as those that return
2242 * S_OK from their DllCanUnloadNow function.
2244 * RETURNS
2245 * Nothing.
2247 * SEE ALSO
2248 * CoLoadLibrary, CoFreeAllLibraries, CoFreeLibrary
2250 void WINAPI CoFreeUnusedLibraries(void)
2252 /* CODEWEAVERS HACK for Office 2003: Don't call
2253 * COMPOBJ_DllList_FreeUnused as it appears to do something the app
2254 * doesn't expect and free a module that is in-use */
2255 /* FIXME: Calls to CoFreeUnusedLibraries from any thread always route
2256 * through the main apartment's thread to call DllCanUnloadNow */
2257 if (0) COMPOBJ_DllList_FreeUnused(0);
2260 /***********************************************************************
2261 * CoFileTimeNow [OLE32.@]
2262 * CoFileTimeNow [COMPOBJ.82]
2264 * Retrieves the current time in FILETIME format.
2266 * PARAMS
2267 * lpFileTime [O] The current time.
2269 * RETURNS
2270 * S_OK.
2272 HRESULT WINAPI CoFileTimeNow( FILETIME *lpFileTime )
2274 GetSystemTimeAsFileTime( lpFileTime );
2275 return S_OK;
2278 static void COM_RevokeAllClasses(void)
2280 EnterCriticalSection( &csRegisteredClassList );
2282 while (list_head(&RegisteredClassList))
2284 RegisteredClass *curClass = LIST_ENTRY(list_head(&RegisteredClassList),
2285 RegisteredClass, entry);
2286 CoRevokeClassObject(curClass->dwCookie);
2289 LeaveCriticalSection( &csRegisteredClassList );
2292 /******************************************************************************
2293 * CoLockObjectExternal [OLE32.@]
2295 * Increments or decrements the external reference count of a stub object.
2297 * PARAMS
2298 * pUnk [I] Stub object.
2299 * fLock [I] If TRUE then increments the external ref-count,
2300 * otherwise decrements.
2301 * fLastUnlockReleases [I] If TRUE then the last unlock has the effect of
2302 * calling CoDisconnectObject.
2304 * RETURNS
2305 * Success: S_OK.
2306 * Failure: HRESULT code.
2308 * NOTES
2309 * If fLock is TRUE and an object is passed in that doesn't have a stub
2310 * manager then a new stub manager is created for the object.
2312 HRESULT WINAPI CoLockObjectExternal(
2313 LPUNKNOWN pUnk,
2314 BOOL fLock,
2315 BOOL fLastUnlockReleases)
2317 struct stub_manager *stubmgr;
2318 struct apartment *apt;
2320 TRACE("pUnk=%p, fLock=%s, fLastUnlockReleases=%s\n",
2321 pUnk, fLock ? "TRUE" : "FALSE", fLastUnlockReleases ? "TRUE" : "FALSE");
2323 apt = COM_CurrentApt();
2324 if (!apt) return CO_E_NOTINITIALIZED;
2326 stubmgr = get_stub_manager_from_object(apt, pUnk);
2328 if (stubmgr)
2330 if (fLock)
2331 stub_manager_ext_addref(stubmgr, 1);
2332 else
2333 stub_manager_ext_release(stubmgr, 1, fLastUnlockReleases);
2335 stub_manager_int_release(stubmgr);
2337 return S_OK;
2339 else if (fLock)
2341 stubmgr = new_stub_manager(apt, pUnk);
2343 if (stubmgr)
2345 stub_manager_ext_addref(stubmgr, 1);
2346 stub_manager_int_release(stubmgr);
2349 return S_OK;
2351 else
2353 WARN("stub object not found %p\n", pUnk);
2354 /* Note: native is pretty broken here because it just silently
2355 * fails, without returning an appropriate error code, making apps
2356 * think that the object was disconnected, when it actually wasn't */
2357 return S_OK;
2361 /***********************************************************************
2362 * CoInitializeWOW (OLE32.@)
2364 * WOW equivalent of CoInitialize?
2366 * PARAMS
2367 * x [I] Unknown.
2368 * y [I] Unknown.
2370 * RETURNS
2371 * Unknown.
2373 HRESULT WINAPI CoInitializeWOW(DWORD x,DWORD y)
2375 FIXME("(0x%08x,0x%08x),stub!\n",x,y);
2376 return 0;
2379 /***********************************************************************
2380 * CoGetState [OLE32.@]
2382 * Retrieves the thread state object previously stored by CoSetState().
2384 * PARAMS
2385 * ppv [I] Address where pointer to object will be stored.
2387 * RETURNS
2388 * Success: S_OK.
2389 * Failure: E_OUTOFMEMORY.
2391 * NOTES
2392 * Crashes on all invalid ppv addresses, including NULL.
2393 * If the function returns a non-NULL object then the caller must release its
2394 * reference on the object when the object is no longer required.
2396 * SEE ALSO
2397 * CoSetState().
2399 HRESULT WINAPI CoGetState(IUnknown ** ppv)
2401 struct oletls *info = COM_CurrentInfo();
2402 if (!info) return E_OUTOFMEMORY;
2404 *ppv = NULL;
2406 if (info->state)
2408 IUnknown_AddRef(info->state);
2409 *ppv = info->state;
2410 TRACE("apt->state=%p\n", info->state);
2413 return S_OK;
2416 /***********************************************************************
2417 * CoSetState [OLE32.@]
2419 * Sets the thread state object.
2421 * PARAMS
2422 * pv [I] Pointer to state object to be stored.
2424 * NOTES
2425 * The system keeps a reference on the object while the object stored.
2427 * RETURNS
2428 * Success: S_OK.
2429 * Failure: E_OUTOFMEMORY.
2431 HRESULT WINAPI CoSetState(IUnknown * pv)
2433 struct oletls *info = COM_CurrentInfo();
2434 if (!info) return E_OUTOFMEMORY;
2436 if (pv) IUnknown_AddRef(pv);
2438 if (info->state)
2440 TRACE("-- release %p now\n", info->state);
2441 IUnknown_Release(info->state);
2444 info->state = pv;
2446 return S_OK;
2450 /******************************************************************************
2451 * CoTreatAsClass [OLE32.@]
2453 * Sets the TreatAs value of a class.
2455 * PARAMS
2456 * clsidOld [I] Class to set TreatAs value on.
2457 * clsidNew [I] The class the clsidOld should be treated as.
2459 * RETURNS
2460 * Success: S_OK.
2461 * Failure: HRESULT code.
2463 * SEE ALSO
2464 * CoGetTreatAsClass
2466 HRESULT WINAPI CoTreatAsClass(REFCLSID clsidOld, REFCLSID clsidNew)
2468 static const WCHAR wszAutoTreatAs[] = {'A','u','t','o','T','r','e','a','t','A','s',0};
2469 static const WCHAR wszTreatAs[] = {'T','r','e','a','t','A','s',0};
2470 HKEY hkey = NULL;
2471 WCHAR szClsidNew[CHARS_IN_GUID];
2472 HRESULT res = S_OK;
2473 WCHAR auto_treat_as[CHARS_IN_GUID];
2474 LONG auto_treat_as_size = sizeof(auto_treat_as);
2475 CLSID id;
2477 res = COM_OpenKeyForCLSID(clsidOld, NULL, KEY_READ | KEY_WRITE, &hkey);
2478 if (FAILED(res))
2479 goto done;
2480 if (!memcmp( clsidOld, clsidNew, sizeof(*clsidOld) ))
2482 if (!RegQueryValueW(hkey, wszAutoTreatAs, auto_treat_as, &auto_treat_as_size) &&
2483 !CLSIDFromString(auto_treat_as, &id))
2485 if (RegSetValueW(hkey, wszTreatAs, REG_SZ, auto_treat_as, sizeof(auto_treat_as)))
2487 res = REGDB_E_WRITEREGDB;
2488 goto done;
2491 else
2493 RegDeleteKeyW(hkey, wszTreatAs);
2494 goto done;
2497 else if (!StringFromGUID2(clsidNew, szClsidNew, ARRAYSIZE(szClsidNew)) &&
2498 !RegSetValueW(hkey, wszTreatAs, REG_SZ, szClsidNew, sizeof(szClsidNew)))
2500 res = REGDB_E_WRITEREGDB;
2501 goto done;
2504 done:
2505 if (hkey) RegCloseKey(hkey);
2506 return res;
2509 /******************************************************************************
2510 * CoGetTreatAsClass [OLE32.@]
2512 * Gets the TreatAs value of a class.
2514 * PARAMS
2515 * clsidOld [I] Class to get the TreatAs value of.
2516 * clsidNew [I] The class the clsidOld should be treated as.
2518 * RETURNS
2519 * Success: S_OK.
2520 * Failure: HRESULT code.
2522 * SEE ALSO
2523 * CoSetTreatAsClass
2525 HRESULT WINAPI CoGetTreatAsClass(REFCLSID clsidOld, LPCLSID clsidNew)
2527 static const WCHAR wszTreatAs[] = {'T','r','e','a','t','A','s',0};
2528 HKEY hkey = NULL;
2529 WCHAR szClsidNew[CHARS_IN_GUID];
2530 HRESULT res = S_OK;
2531 LONG len = sizeof(szClsidNew);
2533 FIXME("(%s,%p)\n", debugstr_guid(clsidOld), clsidNew);
2534 memcpy(clsidNew,clsidOld,sizeof(CLSID)); /* copy over old value */
2536 res = COM_OpenKeyForCLSID(clsidOld, wszTreatAs, KEY_READ, &hkey);
2537 if (FAILED(res))
2538 goto done;
2539 if (RegQueryValueW(hkey, NULL, szClsidNew, &len))
2541 res = S_FALSE;
2542 goto done;
2544 res = CLSIDFromString(szClsidNew,clsidNew);
2545 if (FAILED(res))
2546 ERR("Failed CLSIDFromStringA(%s), hres 0x%08x\n", debugstr_w(szClsidNew), res);
2547 done:
2548 if (hkey) RegCloseKey(hkey);
2549 return res;
2552 /******************************************************************************
2553 * CoGetCurrentProcess [OLE32.@]
2554 * CoGetCurrentProcess [COMPOBJ.34]
2556 * Gets the current process ID.
2558 * RETURNS
2559 * The current process ID.
2561 * NOTES
2562 * Is DWORD really the correct return type for this function?
2564 DWORD WINAPI CoGetCurrentProcess(void)
2566 return GetCurrentProcessId();
2569 /******************************************************************************
2570 * CoRegisterMessageFilter [OLE32.@]
2572 * Registers a message filter.
2574 * PARAMS
2575 * lpMessageFilter [I] Pointer to interface.
2576 * lplpMessageFilter [O] Indirect pointer to prior instance if non-NULL.
2578 * RETURNS
2579 * Success: S_OK.
2580 * Failure: HRESULT code.
2582 * NOTES
2583 * Both lpMessageFilter and lplpMessageFilter are optional. Passing in a NULL
2584 * lpMessageFilter removes the message filter.
2586 * If lplpMessageFilter is not NULL the previous message filter will be
2587 * returned in the memory pointer to this parameter and the caller is
2588 * responsible for releasing the object.
2590 * The current thread be in an apartment otherwise the function will crash.
2592 HRESULT WINAPI CoRegisterMessageFilter(
2593 LPMESSAGEFILTER lpMessageFilter,
2594 LPMESSAGEFILTER *lplpMessageFilter)
2596 struct apartment *apt;
2597 IMessageFilter *lpOldMessageFilter;
2599 TRACE("(%p, %p)\n", lpMessageFilter, lplpMessageFilter);
2601 apt = COM_CurrentApt();
2603 /* can't set a message filter in a multi-threaded apartment */
2604 if (!apt || apt->multi_threaded)
2606 WARN("can't set message filter in MTA or uninitialized apt\n");
2607 return CO_E_NOT_SUPPORTED;
2610 if (lpMessageFilter)
2611 IMessageFilter_AddRef(lpMessageFilter);
2613 EnterCriticalSection(&apt->cs);
2615 lpOldMessageFilter = apt->filter;
2616 apt->filter = lpMessageFilter;
2618 LeaveCriticalSection(&apt->cs);
2620 if (lplpMessageFilter)
2621 *lplpMessageFilter = lpOldMessageFilter;
2622 else if (lpOldMessageFilter)
2623 IMessageFilter_Release(lpOldMessageFilter);
2625 return S_OK;
2628 /***********************************************************************
2629 * CoIsOle1Class [OLE32.@]
2631 * Determines whether the specified class an OLE v1 class.
2633 * PARAMS
2634 * clsid [I] Class to test.
2636 * RETURNS
2637 * TRUE if the class is an OLE v1 class, or FALSE otherwise.
2639 BOOL WINAPI CoIsOle1Class(REFCLSID clsid)
2641 FIXME("%s\n", debugstr_guid(clsid));
2642 return FALSE;
2645 /***********************************************************************
2646 * IsEqualGUID [OLE32.@]
2648 * Compares two Unique Identifiers.
2650 * PARAMS
2651 * rguid1 [I] The first GUID to compare.
2652 * rguid2 [I] The other GUID to compare.
2654 * RETURNS
2655 * TRUE if equal
2657 #undef IsEqualGUID
2658 BOOL WINAPI IsEqualGUID(
2659 REFGUID rguid1,
2660 REFGUID rguid2)
2662 return !memcmp(rguid1,rguid2,sizeof(GUID));
2665 /***********************************************************************
2666 * CoInitializeSecurity [OLE32.@]
2668 HRESULT WINAPI CoInitializeSecurity(PSECURITY_DESCRIPTOR pSecDesc, LONG cAuthSvc,
2669 SOLE_AUTHENTICATION_SERVICE* asAuthSvc,
2670 void* pReserved1, DWORD dwAuthnLevel,
2671 DWORD dwImpLevel, void* pReserved2,
2672 DWORD dwCapabilities, void* pReserved3)
2674 FIXME("(%p,%d,%p,%p,%d,%d,%p,%d,%p) - stub!\n", pSecDesc, cAuthSvc,
2675 asAuthSvc, pReserved1, dwAuthnLevel, dwImpLevel, pReserved2,
2676 dwCapabilities, pReserved3);
2677 return S_OK;
2680 /***********************************************************************
2681 * CoSuspendClassObjects [OLE32.@]
2683 * Suspends all registered class objects to prevent further requests coming in
2684 * for those objects.
2686 * RETURNS
2687 * Success: S_OK.
2688 * Failure: HRESULT code.
2690 HRESULT WINAPI CoSuspendClassObjects(void)
2692 FIXME("\n");
2693 return S_OK;
2696 /***********************************************************************
2697 * CoAddRefServerProcess [OLE32.@]
2699 * Helper function for incrementing the reference count of a local-server
2700 * process.
2702 * RETURNS
2703 * New reference count.
2705 * SEE ALSO
2706 * CoReleaseServerProcess().
2708 ULONG WINAPI CoAddRefServerProcess(void)
2710 ULONG refs;
2712 TRACE("\n");
2714 EnterCriticalSection(&csRegisteredClassList);
2715 refs = ++s_COMServerProcessReferences;
2716 LeaveCriticalSection(&csRegisteredClassList);
2718 TRACE("refs before: %d\n", refs - 1);
2720 return refs;
2723 /***********************************************************************
2724 * CoReleaseServerProcess [OLE32.@]
2726 * Helper function for decrementing the reference count of a local-server
2727 * process.
2729 * RETURNS
2730 * New reference count.
2732 * NOTES
2733 * When reference count reaches 0, this function suspends all registered
2734 * classes so no new connections are accepted.
2736 * SEE ALSO
2737 * CoAddRefServerProcess(), CoSuspendClassObjects().
2739 ULONG WINAPI CoReleaseServerProcess(void)
2741 ULONG refs;
2743 TRACE("\n");
2745 EnterCriticalSection(&csRegisteredClassList);
2747 refs = --s_COMServerProcessReferences;
2748 /* FIXME: if (!refs) COM_SuspendClassObjects(); */
2750 LeaveCriticalSection(&csRegisteredClassList);
2752 TRACE("refs after: %d\n", refs);
2754 return refs;
2757 /***********************************************************************
2758 * CoIsHandlerConnected [OLE32.@]
2760 * Determines whether a proxy is connected to a remote stub.
2762 * PARAMS
2763 * pUnk [I] Pointer to object that may or may not be connected.
2765 * RETURNS
2766 * TRUE if pUnk is not a proxy or if pUnk is connected to a remote stub, or
2767 * FALSE otherwise.
2769 BOOL WINAPI CoIsHandlerConnected(IUnknown *pUnk)
2771 FIXME("%p\n", pUnk);
2773 return TRUE;
2776 /***********************************************************************
2777 * CoAllowSetForegroundWindow [OLE32.@]
2780 HRESULT WINAPI CoAllowSetForegroundWindow(IUnknown *pUnk, void *pvReserved)
2782 FIXME("(%p, %p): stub\n", pUnk, pvReserved);
2783 return S_OK;
2786 /***********************************************************************
2787 * CoQueryProxyBlanket [OLE32.@]
2789 * Retrieves the security settings being used by a proxy.
2791 * PARAMS
2792 * pProxy [I] Pointer to the proxy object.
2793 * pAuthnSvc [O] The type of authentication service.
2794 * pAuthzSvc [O] The type of authorization service.
2795 * ppServerPrincName [O] Optional. The server prinicple name.
2796 * pAuthnLevel [O] The authentication level.
2797 * pImpLevel [O] The impersonation level.
2798 * ppAuthInfo [O] Information specific to the authorization/authentication service.
2799 * pCapabilities [O] Flags affecting the security behaviour.
2801 * RETURNS
2802 * Success: S_OK.
2803 * Failure: HRESULT code.
2805 * SEE ALSO
2806 * CoCopyProxy, CoSetProxyBlanket.
2808 HRESULT WINAPI CoQueryProxyBlanket(IUnknown *pProxy, DWORD *pAuthnSvc,
2809 DWORD *pAuthzSvc, OLECHAR **ppServerPrincName, DWORD *pAuthnLevel,
2810 DWORD *pImpLevel, void **ppAuthInfo, DWORD *pCapabilities)
2812 IClientSecurity *pCliSec;
2813 HRESULT hr;
2815 TRACE("%p\n", pProxy);
2817 hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
2818 if (SUCCEEDED(hr))
2820 hr = IClientSecurity_QueryBlanket(pCliSec, pProxy, pAuthnSvc,
2821 pAuthzSvc, ppServerPrincName,
2822 pAuthnLevel, pImpLevel, ppAuthInfo,
2823 pCapabilities);
2824 IClientSecurity_Release(pCliSec);
2827 if (FAILED(hr)) ERR("-- failed with 0x%08x\n", hr);
2828 return hr;
2831 /***********************************************************************
2832 * CoSetProxyBlanket [OLE32.@]
2834 * Sets the security settings for a proxy.
2836 * PARAMS
2837 * pProxy [I] Pointer to the proxy object.
2838 * AuthnSvc [I] The type of authentication service.
2839 * AuthzSvc [I] The type of authorization service.
2840 * pServerPrincName [I] The server prinicple name.
2841 * AuthnLevel [I] The authentication level.
2842 * ImpLevel [I] The impersonation level.
2843 * pAuthInfo [I] Information specific to the authorization/authentication service.
2844 * Capabilities [I] Flags affecting the security behaviour.
2846 * RETURNS
2847 * Success: S_OK.
2848 * Failure: HRESULT code.
2850 * SEE ALSO
2851 * CoQueryProxyBlanket, CoCopyProxy.
2853 HRESULT WINAPI CoSetProxyBlanket(IUnknown *pProxy, DWORD AuthnSvc,
2854 DWORD AuthzSvc, OLECHAR *pServerPrincName, DWORD AuthnLevel,
2855 DWORD ImpLevel, void *pAuthInfo, DWORD Capabilities)
2857 IClientSecurity *pCliSec;
2858 HRESULT hr;
2860 TRACE("%p\n", pProxy);
2862 hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
2863 if (SUCCEEDED(hr))
2865 hr = IClientSecurity_SetBlanket(pCliSec, pProxy, AuthnSvc,
2866 AuthzSvc, pServerPrincName,
2867 AuthnLevel, ImpLevel, pAuthInfo,
2868 Capabilities);
2869 IClientSecurity_Release(pCliSec);
2872 if (FAILED(hr)) ERR("-- failed with 0x%08x\n", hr);
2873 return hr;
2876 /***********************************************************************
2877 * CoCopyProxy [OLE32.@]
2879 * Copies a proxy.
2881 * PARAMS
2882 * pProxy [I] Pointer to the proxy object.
2883 * ppCopy [O] Copy of the proxy.
2885 * RETURNS
2886 * Success: S_OK.
2887 * Failure: HRESULT code.
2889 * SEE ALSO
2890 * CoQueryProxyBlanket, CoSetProxyBlanket.
2892 HRESULT WINAPI CoCopyProxy(IUnknown *pProxy, IUnknown **ppCopy)
2894 IClientSecurity *pCliSec;
2895 HRESULT hr;
2897 TRACE("%p\n", pProxy);
2899 hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
2900 if (SUCCEEDED(hr))
2902 hr = IClientSecurity_CopyProxy(pCliSec, pProxy, ppCopy);
2903 IClientSecurity_Release(pCliSec);
2906 if (FAILED(hr)) ERR("-- failed with 0x%08x\n", hr);
2907 return hr;
2911 /***********************************************************************
2912 * CoGetCallContext [OLE32.@]
2914 * Gets the context of the currently executing server call in the current
2915 * thread.
2917 * PARAMS
2918 * riid [I] Context interface to return.
2919 * ppv [O] Pointer to memory that will receive the context on return.
2921 * RETURNS
2922 * Success: S_OK.
2923 * Failure: HRESULT code.
2925 HRESULT WINAPI CoGetCallContext(REFIID riid, void **ppv)
2927 FIXME("(%s, %p): stub\n", debugstr_guid(riid), ppv);
2929 *ppv = NULL;
2930 return E_NOINTERFACE;
2933 /***********************************************************************
2934 * CoQueryClientBlanket [OLE32.@]
2936 * Retrieves the authentication information about the client of the currently
2937 * executing server call in the current thread.
2939 * PARAMS
2940 * pAuthnSvc [O] Optional. The type of authentication service.
2941 * pAuthzSvc [O] Optional. The type of authorization service.
2942 * pServerPrincName [O] Optional. The server prinicple name.
2943 * pAuthnLevel [O] Optional. The authentication level.
2944 * pImpLevel [O] Optional. The impersonation level.
2945 * pPrivs [O] Optional. Information about the privileges of the client.
2946 * pCapabilities [IO] Optional. Flags affecting the security behaviour.
2948 * RETURNS
2949 * Success: S_OK.
2950 * Failure: HRESULT code.
2952 * SEE ALSO
2953 * CoImpersonateClient, CoRevertToSelf, CoGetCallContext.
2955 HRESULT WINAPI CoQueryClientBlanket(
2956 DWORD *pAuthnSvc,
2957 DWORD *pAuthzSvc,
2958 OLECHAR **pServerPrincName,
2959 DWORD *pAuthnLevel,
2960 DWORD *pImpLevel,
2961 RPC_AUTHZ_HANDLE *pPrivs,
2962 DWORD *pCapabilities)
2964 IServerSecurity *pSrvSec;
2965 HRESULT hr;
2967 TRACE("(%p, %p, %p, %p, %p, %p, %p)\n",
2968 pAuthnSvc, pAuthzSvc, pServerPrincName, pAuthnLevel, pImpLevel,
2969 pPrivs, pCapabilities);
2971 hr = CoGetCallContext(&IID_IServerSecurity, (void **)&pSrvSec);
2972 if (SUCCEEDED(hr))
2974 hr = IServerSecurity_QueryBlanket(
2975 pSrvSec, pAuthnSvc, pAuthzSvc, pServerPrincName, pAuthnLevel,
2976 pImpLevel, pPrivs, pCapabilities);
2977 IServerSecurity_Release(pSrvSec);
2980 return hr;
2983 /***********************************************************************
2984 * CoImpersonateClient [OLE32.@]
2986 * Impersonates the client of the currently executing server call in the
2987 * current thread.
2989 * PARAMS
2990 * None.
2992 * RETURNS
2993 * Success: S_OK.
2994 * Failure: HRESULT code.
2996 * NOTES
2997 * If this function fails then the current thread will not be impersonating
2998 * the client and all actions will take place on behalf of the server.
2999 * Therefore, it is important to check the return value from this function.
3001 * SEE ALSO
3002 * CoRevertToSelf, CoQueryClientBlanket, CoGetCallContext.
3004 HRESULT WINAPI CoImpersonateClient(void)
3006 IServerSecurity *pSrvSec;
3007 HRESULT hr;
3009 TRACE("\n");
3011 hr = CoGetCallContext(&IID_IServerSecurity, (void **)&pSrvSec);
3012 if (SUCCEEDED(hr))
3014 hr = IServerSecurity_ImpersonateClient(pSrvSec);
3015 IServerSecurity_Release(pSrvSec);
3018 return hr;
3021 /***********************************************************************
3022 * CoRevertToSelf [OLE32.@]
3024 * Ends the impersonation of the client of the currently executing server
3025 * call in the current thread.
3027 * PARAMS
3028 * None.
3030 * RETURNS
3031 * Success: S_OK.
3032 * Failure: HRESULT code.
3034 * SEE ALSO
3035 * CoImpersonateClient, CoQueryClientBlanket, CoGetCallContext.
3037 HRESULT WINAPI CoRevertToSelf(void)
3039 IServerSecurity *pSrvSec;
3040 HRESULT hr;
3042 TRACE("\n");
3044 hr = CoGetCallContext(&IID_IServerSecurity, (void **)&pSrvSec);
3045 if (SUCCEEDED(hr))
3047 hr = IServerSecurity_RevertToSelf(pSrvSec);
3048 IServerSecurity_Release(pSrvSec);
3051 return hr;
3054 static BOOL COM_PeekMessage(struct apartment *apt, MSG *msg)
3056 /* first try to retrieve messages for incoming COM calls to the apartment window */
3057 return PeekMessageW(msg, apt->win, WM_USER, WM_APP - 1, PM_REMOVE|PM_NOYIELD) ||
3058 /* next retrieve other messages necessary for the app to remain responsive */
3059 PeekMessageW(msg, NULL, 0, 0, PM_QS_PAINT|PM_QS_POSTMESSAGE|PM_REMOVE|PM_NOYIELD);
3062 /***********************************************************************
3063 * CoWaitForMultipleHandles [OLE32.@]
3065 * Waits for one or more handles to become signaled.
3067 * PARAMS
3068 * dwFlags [I] Flags. See notes.
3069 * dwTimeout [I] Timeout in milliseconds.
3070 * cHandles [I] Number of handles pointed to by pHandles.
3071 * pHandles [I] Handles to wait for.
3072 * lpdwindex [O] Index of handle that was signaled.
3074 * RETURNS
3075 * Success: S_OK.
3076 * Failure: RPC_S_CALLPENDING on timeout.
3078 * NOTES
3080 * The dwFlags parameter can be zero or more of the following:
3081 *| COWAIT_WAITALL - Wait for all of the handles to become signaled.
3082 *| COWAIT_ALERTABLE - Allows a queued APC to run during the wait.
3084 * SEE ALSO
3085 * MsgWaitForMultipleObjects, WaitForMultipleObjects.
3087 HRESULT WINAPI CoWaitForMultipleHandles(DWORD dwFlags, DWORD dwTimeout,
3088 ULONG cHandles, LPHANDLE pHandles, LPDWORD lpdwindex)
3090 HRESULT hr = S_OK;
3091 DWORD start_time = GetTickCount();
3092 APARTMENT *apt = COM_CurrentApt();
3093 BOOL message_loop = apt && !apt->multi_threaded;
3095 TRACE("(0x%08x, 0x%08x, %d, %p, %p)\n", dwFlags, dwTimeout, cHandles,
3096 pHandles, lpdwindex);
3098 while (TRUE)
3100 DWORD now = GetTickCount();
3101 DWORD res;
3103 if ((dwTimeout != INFINITE) && (start_time + dwTimeout >= now))
3105 hr = RPC_S_CALLPENDING;
3106 break;
3109 if (message_loop)
3111 DWORD wait_flags = (dwFlags & COWAIT_WAITALL) ? MWMO_WAITALL : 0 |
3112 (dwFlags & COWAIT_ALERTABLE ) ? MWMO_ALERTABLE : 0;
3114 TRACE("waiting for rpc completion or window message\n");
3116 res = MsgWaitForMultipleObjectsEx(cHandles, pHandles,
3117 (dwTimeout == INFINITE) ? INFINITE : start_time + dwTimeout - now,
3118 QS_ALLINPUT, wait_flags);
3120 if (res == WAIT_OBJECT_0 + cHandles) /* messages available */
3122 MSG msg;
3124 /* call message filter */
3126 if (COM_CurrentApt()->filter)
3128 PENDINGTYPE pendingtype =
3129 COM_CurrentInfo()->pending_call_count_server ?
3130 PENDINGTYPE_NESTED : PENDINGTYPE_TOPLEVEL;
3131 DWORD be_handled = IMessageFilter_MessagePending(
3132 COM_CurrentApt()->filter, 0 /* FIXME */,
3133 now - start_time, pendingtype);
3134 TRACE("IMessageFilter_MessagePending returned %d\n", be_handled);
3135 switch (be_handled)
3137 case PENDINGMSG_CANCELCALL:
3138 WARN("call canceled\n");
3139 hr = RPC_E_CALL_CANCELED;
3140 break;
3141 case PENDINGMSG_WAITNOPROCESS:
3142 case PENDINGMSG_WAITDEFPROCESS:
3143 default:
3144 /* FIXME: MSDN is very vague about the difference
3145 * between WAITNOPROCESS and WAITDEFPROCESS - there
3146 * appears to be none, so it is possibly a left-over
3147 * from the 16-bit world. */
3148 break;
3152 /* note: using "if" here instead of "while" might seem less
3153 * efficient, but only if we are optimising for quick delivery
3154 * of pending messages, rather than quick completion of the
3155 * COM call */
3156 if (COM_PeekMessage(apt, &msg))
3158 TRACE("received message whilst waiting for RPC: 0x%04x\n", msg.message);
3159 TranslateMessage(&msg);
3160 DispatchMessageW(&msg);
3161 if (msg.message == WM_QUIT)
3163 TRACE("resending WM_QUIT to outer message loop\n");
3164 PostQuitMessage(msg.wParam);
3165 /* no longer need to process messages */
3166 message_loop = FALSE;
3169 continue;
3172 else
3174 TRACE("waiting for rpc completion\n");
3176 res = WaitForMultipleObjectsEx(cHandles, pHandles,
3177 (dwFlags & COWAIT_WAITALL) ? TRUE : FALSE,
3178 (dwTimeout == INFINITE) ? INFINITE : start_time + dwTimeout - now,
3179 (dwFlags & COWAIT_ALERTABLE) ? TRUE : FALSE);
3182 if ((res >= WAIT_OBJECT_0) && (res < WAIT_OBJECT_0 + cHandles))
3184 /* handle signaled, store index */
3185 *lpdwindex = (res - WAIT_OBJECT_0);
3186 break;
3188 else if (res == WAIT_TIMEOUT)
3190 hr = RPC_S_CALLPENDING;
3191 break;
3193 else
3195 ERR("Unexpected wait termination: %d, %d\n", res, GetLastError());
3196 hr = E_UNEXPECTED;
3197 break;
3200 TRACE("-- 0x%08x\n", hr);
3201 return hr;
3205 /***********************************************************************
3206 * CoGetObject [OLE32.@]
3208 * Gets the object named by coverting the name to a moniker and binding to it.
3210 * PARAMS
3211 * pszName [I] String representing the object.
3212 * pBindOptions [I] Parameters affecting the binding to the named object.
3213 * riid [I] Interface to bind to on the objecct.
3214 * ppv [O] On output, the interface riid of the object represented
3215 * by pszName.
3217 * RETURNS
3218 * Success: S_OK.
3219 * Failure: HRESULT code.
3221 * SEE ALSO
3222 * MkParseDisplayName.
3224 HRESULT WINAPI CoGetObject(LPCWSTR pszName, BIND_OPTS *pBindOptions,
3225 REFIID riid, void **ppv)
3227 IBindCtx *pbc;
3228 HRESULT hr;
3230 *ppv = NULL;
3232 hr = CreateBindCtx(0, &pbc);
3233 if (SUCCEEDED(hr))
3235 if (pBindOptions)
3236 hr = IBindCtx_SetBindOptions(pbc, pBindOptions);
3238 if (SUCCEEDED(hr))
3240 ULONG chEaten;
3241 IMoniker *pmk;
3243 hr = MkParseDisplayName(pbc, pszName, &chEaten, &pmk);
3244 if (SUCCEEDED(hr))
3246 hr = IMoniker_BindToObject(pmk, pbc, NULL, riid, ppv);
3247 IMoniker_Release(pmk);
3251 IBindCtx_Release(pbc);
3253 return hr;
3256 /***********************************************************************
3257 * CoRegisterChannelHook [OLE32.@]
3259 * Registers a process-wide hook that is called during ORPC calls.
3261 * PARAMS
3262 * guidExtension [I] GUID of the channel hook to register.
3263 * pChannelHook [I] Channel hook object to register.
3265 * RETURNS
3266 * Success: S_OK.
3267 * Failure: HRESULT code.
3269 HRESULT WINAPI CoRegisterChannelHook(REFGUID guidExtension, IChannelHook *pChannelHook)
3271 TRACE("(%s, %p)\n", debugstr_guid(guidExtension), pChannelHook);
3273 return RPC_RegisterChannelHook(guidExtension, pChannelHook);
3276 /***********************************************************************
3277 * DllMain (OLE32.@)
3279 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID fImpLoad)
3281 TRACE("%p 0x%x %p\n", hinstDLL, fdwReason, fImpLoad);
3283 switch(fdwReason) {
3284 case DLL_PROCESS_ATTACH:
3285 OLE32_hInstance = hinstDLL;
3286 COMPOBJ_InitProcess();
3287 if (TRACE_ON(ole)) CoRegisterMallocSpy((LPVOID)-1);
3288 break;
3290 case DLL_PROCESS_DETACH:
3291 if (TRACE_ON(ole)) CoRevokeMallocSpy();
3292 COMPOBJ_UninitProcess();
3293 RPC_UnregisterAllChannelHooks();
3294 OLE32_hInstance = 0;
3295 break;
3297 case DLL_THREAD_DETACH:
3298 COM_TlsDestroy();
3299 break;
3301 return TRUE;
3304 /* NOTE: DllRegisterServer and DllUnregisterServer are in regsvr.c */