gdi32: Revert 1440eb5a35dc95dea1836d9035b51e2b15d83703 and add the test showing that...
[wine/hacks.git] / dlls / ole32 / compobj.c
blobf1c6ebe7c7a903c85604cb7209f7175129705515
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;
111 * This linked list contains the list of registered class objects. These
112 * are mostly used to register the factories for out-of-proc servers of OLE
113 * objects.
115 * TODO: Make this data structure aware of inter-process communication. This
116 * means that parts of this will be exported to the Wine Server.
118 typedef struct tagRegisteredClass
120 CLSID classIdentifier;
121 LPUNKNOWN classObject;
122 DWORD runContext;
123 DWORD connectFlags;
124 DWORD dwCookie;
125 LPSTREAM pMarshaledData; /* FIXME: only really need to store OXID and IPID */
126 struct tagRegisteredClass* nextClass;
127 } RegisteredClass;
129 static RegisteredClass* firstRegisteredClass = NULL;
131 static CRITICAL_SECTION csRegisteredClassList;
132 static CRITICAL_SECTION_DEBUG class_cs_debug =
134 0, 0, &csRegisteredClassList,
135 { &class_cs_debug.ProcessLocksList, &class_cs_debug.ProcessLocksList },
136 0, 0, { (DWORD_PTR)(__FILE__ ": csRegisteredClassList") }
138 static CRITICAL_SECTION csRegisteredClassList = { &class_cs_debug, -1, 0, 0, 0, 0 };
140 /*****************************************************************************
141 * This section contains OpenDllList definitions
143 * The OpenDllList contains only handles of dll loaded by CoGetClassObject or
144 * other functions that do LoadLibrary _without_ giving back a HMODULE.
145 * Without this list these handles would never be freed.
147 * FIXME: a DLL that says OK when asked for unloading is unloaded in the
148 * next unload-call but not before 600 sec.
151 typedef struct tagOpenDll {
152 HINSTANCE hLibrary;
153 struct tagOpenDll *next;
154 } OpenDll;
156 static OpenDll *openDllList = NULL; /* linked list of open dlls */
158 static CRITICAL_SECTION csOpenDllList;
159 static CRITICAL_SECTION_DEBUG dll_cs_debug =
161 0, 0, &csOpenDllList,
162 { &dll_cs_debug.ProcessLocksList, &dll_cs_debug.ProcessLocksList },
163 0, 0, { (DWORD_PTR)(__FILE__ ": csOpenDllList") }
165 static CRITICAL_SECTION csOpenDllList = { &dll_cs_debug, -1, 0, 0, 0, 0 };
167 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',' ',
168 '0','x','#','#','#','#','#','#','#','#',' ',0};
169 static LRESULT CALLBACK apartment_wndproc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
171 static void COMPOBJ_DLLList_Add(HANDLE hLibrary);
172 static void COMPOBJ_DllList_FreeUnused(int Timeout);
174 static void COMPOBJ_InitProcess( void )
176 WNDCLASSW wclass;
178 /* Dispatching to the correct thread in an apartment is done through
179 * window messages rather than RPC transports. When an interface is
180 * marshalled into another apartment in the same process, a window of the
181 * following class is created. The *caller* of CoMarshalInterface (ie the
182 * application) is responsible for pumping the message loop in that thread.
183 * The WM_USER messages which point to the RPCs are then dispatched to
184 * COM_AptWndProc by the user's code from the apartment in which the interface
185 * was unmarshalled.
187 memset(&wclass, 0, sizeof(wclass));
188 wclass.lpfnWndProc = apartment_wndproc;
189 wclass.hInstance = OLE32_hInstance;
190 wclass.lpszClassName = wszAptWinClass;
191 RegisterClassW(&wclass);
194 static void COMPOBJ_UninitProcess( void )
196 UnregisterClassW(wszAptWinClass, OLE32_hInstance);
199 static void COM_TlsDestroy(void)
201 struct oletls *info = NtCurrentTeb()->ReservedForOle;
202 if (info)
204 if (info->apt) apartment_release(info->apt);
205 if (info->errorinfo) IErrorInfo_Release(info->errorinfo);
206 if (info->state) IUnknown_Release(info->state);
207 HeapFree(GetProcessHeap(), 0, info);
208 NtCurrentTeb()->ReservedForOle = NULL;
212 /******************************************************************************
213 * Manage apartments.
216 /* allocates memory and fills in the necessary fields for a new apartment
217 * object. must be called inside apartment cs */
218 static APARTMENT *apartment_construct(DWORD model)
220 APARTMENT *apt;
222 TRACE("creating new apartment, model=%d\n", model);
224 apt = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*apt));
225 apt->tid = GetCurrentThreadId();
227 list_init(&apt->proxies);
228 list_init(&apt->stubmgrs);
229 list_init(&apt->psclsids);
230 apt->ipidc = 0;
231 apt->refs = 1;
232 apt->remunk_exported = FALSE;
233 apt->oidc = 1;
234 InitializeCriticalSection(&apt->cs);
235 DEBUG_SET_CRITSEC_NAME(&apt->cs, "apartment");
237 apt->multi_threaded = !(model & COINIT_APARTMENTTHREADED);
239 if (apt->multi_threaded)
241 /* FIXME: should be randomly generated by in an RPC call to rpcss */
242 apt->oxid = ((OXID)GetCurrentProcessId() << 32) | 0xcafe;
244 else
246 /* FIXME: should be randomly generated by in an RPC call to rpcss */
247 apt->oxid = ((OXID)GetCurrentProcessId() << 32) | GetCurrentThreadId();
250 TRACE("Created apartment on OXID %s\n", wine_dbgstr_longlong(apt->oxid));
252 list_add_head(&apts, &apt->entry);
254 return apt;
257 /* gets and existing apartment if one exists or otherwise creates an apartment
258 * structure which stores OLE apartment-local information and stores a pointer
259 * to it in the thread-local storage */
260 static APARTMENT *apartment_get_or_create(DWORD model)
262 APARTMENT *apt = COM_CurrentApt();
264 if (!apt)
266 if (model & COINIT_APARTMENTTHREADED)
268 EnterCriticalSection(&csApartment);
270 apt = apartment_construct(model);
271 if (!MainApartment)
273 MainApartment = apt;
274 apt->main = TRUE;
275 TRACE("Created main-threaded apartment with OXID %s\n", wine_dbgstr_longlong(apt->oxid));
278 LeaveCriticalSection(&csApartment);
280 else
282 EnterCriticalSection(&csApartment);
284 /* The multi-threaded apartment (MTA) contains zero or more threads interacting
285 * with free threaded (ie thread safe) COM objects. There is only ever one MTA
286 * in a process */
287 if (MTA)
289 TRACE("entering the multithreaded apartment %s\n", wine_dbgstr_longlong(MTA->oxid));
290 apartment_addref(MTA);
292 else
293 MTA = apartment_construct(model);
295 apt = MTA;
297 LeaveCriticalSection(&csApartment);
299 COM_CurrentInfo()->apt = apt;
302 return apt;
305 static inline BOOL apartment_is_model(APARTMENT *apt, DWORD model)
307 return (apt->multi_threaded == !(model & COINIT_APARTMENTTHREADED));
310 DWORD apartment_addref(struct apartment *apt)
312 DWORD refs = InterlockedIncrement(&apt->refs);
313 TRACE("%s: before = %d\n", wine_dbgstr_longlong(apt->oxid), refs - 1);
314 return refs;
317 DWORD apartment_release(struct apartment *apt)
319 DWORD ret;
321 EnterCriticalSection(&csApartment);
323 ret = InterlockedDecrement(&apt->refs);
324 TRACE("%s: after = %d\n", wine_dbgstr_longlong(apt->oxid), ret);
325 /* destruction stuff that needs to happen under csApartment CS */
326 if (ret == 0)
328 if (apt == MTA) MTA = NULL;
329 else if (apt == MainApartment) MainApartment = NULL;
330 list_remove(&apt->entry);
333 LeaveCriticalSection(&csApartment);
335 if (ret == 0)
337 struct list *cursor, *cursor2;
339 TRACE("destroying apartment %p, oxid %s\n", apt, wine_dbgstr_longlong(apt->oxid));
341 /* no locking is needed for this apartment, because no other thread
342 * can access it at this point */
344 apartment_disconnectproxies(apt);
346 if (apt->win) DestroyWindow(apt->win);
348 LIST_FOR_EACH_SAFE(cursor, cursor2, &apt->stubmgrs)
350 struct stub_manager *stubmgr = LIST_ENTRY(cursor, struct stub_manager, entry);
351 /* release the implicit reference given by the fact that the
352 * stub has external references (it must do since it is in the
353 * stub manager list in the apartment and all non-apartment users
354 * must have a ref on the apartment and so it cannot be destroyed).
356 stub_manager_int_release(stubmgr);
359 LIST_FOR_EACH_SAFE(cursor, cursor2, &apt->psclsids)
361 struct registered_psclsid *registered_psclsid =
362 LIST_ENTRY(cursor, struct registered_psclsid, entry);
364 list_remove(&registered_psclsid->entry);
365 HeapFree(GetProcessHeap(), 0, registered_psclsid);
368 /* if this assert fires, then another thread took a reference to a
369 * stub manager without taking a reference to the containing
370 * apartment, which it must do. */
371 assert(list_empty(&apt->stubmgrs));
373 if (apt->filter) IUnknown_Release(apt->filter);
375 DEBUG_CLEAR_CRITSEC_NAME(&apt->cs);
376 DeleteCriticalSection(&apt->cs);
378 HeapFree(GetProcessHeap(), 0, apt);
381 return ret;
384 /* The given OXID must be local to this process:
386 * The ref parameter is here mostly to ensure people remember that
387 * they get one, you should normally take a ref for thread safety.
389 APARTMENT *apartment_findfromoxid(OXID oxid, BOOL ref)
391 APARTMENT *result = NULL;
392 struct list *cursor;
394 EnterCriticalSection(&csApartment);
395 LIST_FOR_EACH( cursor, &apts )
397 struct apartment *apt = LIST_ENTRY( cursor, struct apartment, entry );
398 if (apt->oxid == oxid)
400 result = apt;
401 if (ref) apartment_addref(result);
402 break;
405 LeaveCriticalSection(&csApartment);
407 return result;
410 /* gets the apartment which has a given creator thread ID. The caller must
411 * release the reference from the apartment as soon as the apartment pointer
412 * is no longer required. */
413 APARTMENT *apartment_findfromtid(DWORD tid)
415 APARTMENT *result = NULL;
416 struct list *cursor;
418 EnterCriticalSection(&csApartment);
419 LIST_FOR_EACH( cursor, &apts )
421 struct apartment *apt = LIST_ENTRY( cursor, struct apartment, entry );
422 if (apt->tid == tid)
424 result = apt;
425 apartment_addref(result);
426 break;
429 LeaveCriticalSection(&csApartment);
431 return result;
434 /* gets an apartment which has a given type. The caller must
435 * release the reference from the apartment as soon as the apartment pointer
436 * is no longer required. */
437 static APARTMENT *apartment_findfromtype(BOOL multi_threaded, BOOL main_apartment)
439 APARTMENT *result = NULL;
440 struct apartment *apt;
442 EnterCriticalSection(&csApartment);
444 if (!multi_threaded && main_apartment)
446 result = MainApartment;
447 if (result) apartment_addref(result);
448 LeaveCriticalSection(&csApartment);
449 return result;
452 LIST_FOR_EACH_ENTRY( apt, &apts, struct apartment, entry )
454 if (apt->multi_threaded == multi_threaded)
456 result = apt;
457 apartment_addref(result);
458 break;
461 LeaveCriticalSection(&csApartment);
463 return result;
466 struct host_object_params
468 HKEY hkeydll;
469 CLSID clsid; /* clsid of object to marshal */
470 IID iid; /* interface to marshal */
471 IStream *stream; /* stream that the object will be marshaled into */
474 static HRESULT apartment_hostobject(const struct host_object_params *params)
476 IUnknown *object;
477 HRESULT hr;
478 static const LARGE_INTEGER llZero;
480 TRACE("\n");
482 hr = get_inproc_class_object(params->hkeydll, &params->clsid, &params->iid, (void **)&object);
483 if (FAILED(hr))
484 return hr;
486 hr = CoMarshalInterface(params->stream, &params->iid, object, MSHCTX_INPROC, NULL, MSHLFLAGS_NORMAL);
487 if (FAILED(hr))
488 IUnknown_Release(object);
489 IStream_Seek(params->stream, llZero, STREAM_SEEK_SET, NULL);
491 return hr;
494 static LRESULT CALLBACK apartment_wndproc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
496 switch (msg)
498 case DM_EXECUTERPC:
499 RPC_ExecuteCall((struct dispatch_params *)lParam);
500 return 0;
501 case DM_HOSTOBJECT:
502 return apartment_hostobject((const struct host_object_params *)lParam);
503 default:
504 return DefWindowProcW(hWnd, msg, wParam, lParam);
508 HRESULT apartment_createwindowifneeded(struct apartment *apt)
510 if (apt->multi_threaded)
511 return S_OK;
513 if (!apt->win)
515 HWND hwnd = CreateWindowW(wszAptWinClass, NULL, 0,
516 0, 0, 0, 0,
517 0, 0, OLE32_hInstance, NULL);
518 if (!hwnd)
520 ERR("CreateWindow failed with error %d\n", GetLastError());
521 return HRESULT_FROM_WIN32(GetLastError());
523 if (InterlockedCompareExchangePointer((PVOID *)&apt->win, hwnd, NULL))
524 /* someone beat us to it */
525 DestroyWindow(hwnd);
528 return S_OK;
531 HWND apartment_getwindow(struct apartment *apt)
533 assert(!apt->multi_threaded);
534 return apt->win;
537 void apartment_joinmta(void)
539 apartment_addref(MTA);
540 COM_CurrentInfo()->apt = MTA;
543 /*****************************************************************************
544 * This section contains OpenDllList implementation
547 static void COMPOBJ_DLLList_Add(HANDLE hLibrary)
549 OpenDll *ptr;
550 OpenDll *tmp;
552 TRACE("\n");
554 EnterCriticalSection( &csOpenDllList );
556 if (openDllList == NULL) {
557 /* empty list -- add first node */
558 openDllList = HeapAlloc(GetProcessHeap(),0, sizeof(OpenDll));
559 openDllList->hLibrary=hLibrary;
560 openDllList->next = NULL;
561 } else {
562 /* search for this dll */
563 int found = FALSE;
564 for (ptr = openDllList; ptr->next != NULL; ptr=ptr->next) {
565 if (ptr->hLibrary == hLibrary) {
566 found = TRUE;
567 break;
570 if (!found) {
571 /* dll not found, add it */
572 tmp = openDllList;
573 openDllList = HeapAlloc(GetProcessHeap(),0, sizeof(OpenDll));
574 openDllList->hLibrary = hLibrary;
575 openDllList->next = tmp;
579 LeaveCriticalSection( &csOpenDllList );
582 static void COMPOBJ_DllList_FreeUnused(int Timeout)
584 OpenDll *curr, *next, *prev = NULL;
585 typedef HRESULT (WINAPI *DllCanUnloadNowFunc)(void);
586 DllCanUnloadNowFunc DllCanUnloadNow;
588 TRACE("\n");
590 EnterCriticalSection( &csOpenDllList );
592 for (curr = openDllList; curr != NULL; ) {
593 DllCanUnloadNow = (DllCanUnloadNowFunc) GetProcAddress(curr->hLibrary, "DllCanUnloadNow");
595 if ( (DllCanUnloadNow != NULL) && (DllCanUnloadNow() == S_OK) ) {
596 next = curr->next;
598 TRACE("freeing %p\n", curr->hLibrary);
599 FreeLibrary(curr->hLibrary);
601 HeapFree(GetProcessHeap(), 0, curr);
602 if (curr == openDllList) {
603 openDllList = next;
604 } else {
605 prev->next = next;
608 curr = next;
609 } else {
610 prev = curr;
611 curr = curr->next;
615 LeaveCriticalSection( &csOpenDllList );
618 /******************************************************************************
619 * CoBuildVersion [OLE32.@]
620 * CoBuildVersion [COMPOBJ.1]
622 * Gets the build version of the DLL.
624 * PARAMS
626 * RETURNS
627 * Current build version, hiword is majornumber, loword is minornumber
629 DWORD WINAPI CoBuildVersion(void)
631 TRACE("Returning version %d, build %d.\n", rmm, rup);
632 return (rmm<<16)+rup;
635 /******************************************************************************
636 * CoInitialize [OLE32.@]
638 * Initializes the COM libraries by calling CoInitializeEx with
639 * COINIT_APARTMENTTHREADED, ie it enters a STA thread.
641 * PARAMS
642 * lpReserved [I] Pointer to IMalloc interface (obsolete, should be NULL).
644 * RETURNS
645 * Success: S_OK if not already initialized, S_FALSE otherwise.
646 * Failure: HRESULT code.
648 * SEE ALSO
649 * CoInitializeEx
651 HRESULT WINAPI CoInitialize(LPVOID lpReserved)
654 * Just delegate to the newer method.
656 return CoInitializeEx(lpReserved, COINIT_APARTMENTTHREADED);
659 /******************************************************************************
660 * CoInitializeEx [OLE32.@]
662 * Initializes the COM libraries.
664 * PARAMS
665 * lpReserved [I] Pointer to IMalloc interface (obsolete, should be NULL).
666 * dwCoInit [I] One or more flags from the COINIT enumeration. See notes.
668 * RETURNS
669 * S_OK if successful,
670 * S_FALSE if this function was called already.
671 * RPC_E_CHANGED_MODE if a previous call to CoInitializeEx specified another
672 * threading model.
674 * NOTES
676 * The behavior used to set the IMalloc used for memory management is
677 * obsolete.
678 * The dwCoInit parameter must specify one of the following apartment
679 * threading models:
680 *| COINIT_APARTMENTTHREADED - A single-threaded apartment (STA).
681 *| COINIT_MULTITHREADED - A multi-threaded apartment (MTA).
682 * The parameter may also specify zero or more of the following flags:
683 *| COINIT_DISABLE_OLE1DDE - Don't use DDE for OLE1 support.
684 *| COINIT_SPEED_OVER_MEMORY - Trade memory for speed.
686 * SEE ALSO
687 * CoUninitialize
689 HRESULT WINAPI CoInitializeEx(LPVOID lpReserved, DWORD dwCoInit)
691 HRESULT hr = S_OK;
692 APARTMENT *apt;
694 TRACE("(%p, %x)\n", lpReserved, (int)dwCoInit);
696 if (lpReserved!=NULL)
698 ERR("(%p, %x) - Bad parameter passed-in %p, must be an old Windows Application\n", lpReserved, (int)dwCoInit, lpReserved);
702 * Check the lock count. If this is the first time going through the initialize
703 * process, we have to initialize the libraries.
705 * And crank-up that lock count.
707 if (InterlockedExchangeAdd(&s_COMLockCount,1)==0)
710 * Initialize the various COM libraries and data structures.
712 TRACE("() - Initializing the COM libraries\n");
714 /* we may need to defer this until after apartment initialisation */
715 RunningObjectTableImpl_Initialize();
718 if (!(apt = COM_CurrentInfo()->apt))
720 apt = apartment_get_or_create(dwCoInit);
721 if (!apt) return E_OUTOFMEMORY;
723 else if (!apartment_is_model(apt, dwCoInit))
725 /* Changing the threading model after it's been set is illegal. If this warning is triggered by Wine
726 code then we are probably using the wrong threading model to implement that API. */
727 ERR("Attempt to change threading model of this apartment from %s to %s\n",
728 apt->multi_threaded ? "multi-threaded" : "apartment threaded",
729 dwCoInit & COINIT_APARTMENTTHREADED ? "apartment threaded" : "multi-threaded");
730 return RPC_E_CHANGED_MODE;
732 else
733 hr = S_FALSE;
735 COM_CurrentInfo()->inits++;
737 return hr;
740 /* On COM finalization for a STA thread, the message queue is flushed to ensure no
741 pending RPCs are ignored. Non-COM messages are discarded at this point.
743 static void COM_FlushMessageQueue(void)
745 MSG message;
746 APARTMENT *apt = COM_CurrentApt();
748 if (!apt || !apt->win) return;
750 TRACE("Flushing STA message queue\n");
752 while (PeekMessageA(&message, NULL, 0, 0, PM_REMOVE))
754 if (message.hwnd != apt->win)
756 WARN("discarding message 0x%x for window %p\n", message.message, message.hwnd);
757 continue;
760 TranslateMessage(&message);
761 DispatchMessageA(&message);
765 /***********************************************************************
766 * CoUninitialize [OLE32.@]
768 * This method will decrement the refcount on the current apartment, freeing
769 * the resources associated with it if it is the last thread in the apartment.
770 * If the last apartment is freed, the function will additionally release
771 * any COM resources associated with the process.
773 * PARAMS
775 * RETURNS
776 * Nothing.
778 * SEE ALSO
779 * CoInitializeEx
781 void WINAPI CoUninitialize(void)
783 struct oletls * info = COM_CurrentInfo();
784 LONG lCOMRefCnt;
786 TRACE("()\n");
788 /* will only happen on OOM */
789 if (!info) return;
791 /* sanity check */
792 if (!info->inits)
794 ERR("Mismatched CoUninitialize\n");
795 return;
798 if (!--info->inits)
800 apartment_release(info->apt);
801 info->apt = NULL;
805 * Decrease the reference count.
806 * If we are back to 0 locks on the COM library, make sure we free
807 * all the associated data structures.
809 lCOMRefCnt = InterlockedExchangeAdd(&s_COMLockCount,-1);
810 if (lCOMRefCnt==1)
812 TRACE("() - Releasing the COM libraries\n");
814 RunningObjectTableImpl_UnInitialize();
816 /* Release the references to the registered class objects */
817 COM_RevokeAllClasses();
819 /* This will free the loaded COM Dlls */
820 CoFreeAllLibraries();
822 /* This ensures we deal with any pending RPCs */
823 COM_FlushMessageQueue();
825 else if (lCOMRefCnt<1) {
826 ERR( "CoUninitialize() - not CoInitialized.\n" );
827 InterlockedExchangeAdd(&s_COMLockCount,1); /* restore the lock count. */
831 /******************************************************************************
832 * CoDisconnectObject [OLE32.@]
833 * CoDisconnectObject [COMPOBJ.15]
835 * Disconnects all connections to this object from remote processes. Dispatches
836 * pending RPCs while blocking new RPCs from occurring, and then calls
837 * IMarshal::DisconnectObject on the given object.
839 * Typically called when the object server is forced to shut down, for instance by
840 * the user.
842 * PARAMS
843 * lpUnk [I] The object whose stub should be disconnected.
844 * reserved [I] Reserved. Should be set to 0.
846 * RETURNS
847 * Success: S_OK.
848 * Failure: HRESULT code.
850 * SEE ALSO
851 * CoMarshalInterface, CoReleaseMarshalData, CoLockObjectExternal
853 HRESULT WINAPI CoDisconnectObject( LPUNKNOWN lpUnk, DWORD reserved )
855 HRESULT hr;
856 IMarshal *marshal;
857 APARTMENT *apt;
859 TRACE("(%p, 0x%08x)\n", lpUnk, reserved);
861 hr = IUnknown_QueryInterface(lpUnk, &IID_IMarshal, (void **)&marshal);
862 if (hr == S_OK)
864 hr = IMarshal_DisconnectObject(marshal, reserved);
865 IMarshal_Release(marshal);
866 return hr;
869 apt = COM_CurrentApt();
870 if (!apt)
871 return CO_E_NOTINITIALIZED;
873 apartment_disconnectobject(apt, lpUnk);
875 /* Note: native is pretty broken here because it just silently
876 * fails, without returning an appropriate error code if the object was
877 * not found, making apps think that the object was disconnected, when
878 * it actually wasn't */
880 return S_OK;
883 /******************************************************************************
884 * CoCreateGuid [OLE32.@]
886 * Simply forwards to UuidCreate in RPCRT4.
888 * PARAMS
889 * pguid [O] Points to the GUID to initialize.
891 * RETURNS
892 * Success: S_OK.
893 * Failure: HRESULT code.
895 * SEE ALSO
896 * UuidCreate
898 HRESULT WINAPI CoCreateGuid(GUID *pguid)
900 return UuidCreate(pguid);
903 /******************************************************************************
904 * CLSIDFromString [OLE32.@]
905 * IIDFromString [OLE32.@]
907 * Converts a unique identifier from its string representation into
908 * the GUID struct.
910 * PARAMS
911 * idstr [I] The string representation of the GUID.
912 * id [O] GUID converted from the string.
914 * RETURNS
915 * S_OK on success
916 * CO_E_CLASSSTRING if idstr is not a valid CLSID
918 * SEE ALSO
919 * StringFromCLSID
921 static HRESULT WINAPI __CLSIDFromString(LPCWSTR s, CLSID *id)
923 int i;
924 BYTE table[256];
926 if (!s) {
927 memset( id, 0, sizeof (CLSID) );
928 return S_OK;
931 /* validate the CLSID string */
932 if (strlenW(s) != 38)
933 return CO_E_CLASSSTRING;
935 if ((s[0]!='{') || (s[9]!='-') || (s[14]!='-') || (s[19]!='-') || (s[24]!='-') || (s[37]!='}'))
936 return CO_E_CLASSSTRING;
938 for (i=1; i<37; i++) {
939 if ((i == 9)||(i == 14)||(i == 19)||(i == 24)) continue;
940 if (!(((s[i] >= '0') && (s[i] <= '9')) ||
941 ((s[i] >= 'a') && (s[i] <= 'f')) ||
942 ((s[i] >= 'A') && (s[i] <= 'F'))))
943 return CO_E_CLASSSTRING;
946 TRACE("%s -> %p\n", debugstr_w(s), id);
948 /* quick lookup table */
949 memset(table, 0, 256);
951 for (i = 0; i < 10; i++) {
952 table['0' + i] = i;
954 for (i = 0; i < 6; i++) {
955 table['A' + i] = i+10;
956 table['a' + i] = i+10;
959 /* in form {XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX} */
961 id->Data1 = (table[s[1]] << 28 | table[s[2]] << 24 | table[s[3]] << 20 | table[s[4]] << 16 |
962 table[s[5]] << 12 | table[s[6]] << 8 | table[s[7]] << 4 | table[s[8]]);
963 id->Data2 = table[s[10]] << 12 | table[s[11]] << 8 | table[s[12]] << 4 | table[s[13]];
964 id->Data3 = table[s[15]] << 12 | table[s[16]] << 8 | table[s[17]] << 4 | table[s[18]];
966 /* these are just sequential bytes */
967 id->Data4[0] = table[s[20]] << 4 | table[s[21]];
968 id->Data4[1] = table[s[22]] << 4 | table[s[23]];
969 id->Data4[2] = table[s[25]] << 4 | table[s[26]];
970 id->Data4[3] = table[s[27]] << 4 | table[s[28]];
971 id->Data4[4] = table[s[29]] << 4 | table[s[30]];
972 id->Data4[5] = table[s[31]] << 4 | table[s[32]];
973 id->Data4[6] = table[s[33]] << 4 | table[s[34]];
974 id->Data4[7] = table[s[35]] << 4 | table[s[36]];
976 return S_OK;
979 /*****************************************************************************/
981 HRESULT WINAPI CLSIDFromString(LPOLESTR idstr, CLSID *id )
983 HRESULT ret;
985 if (!id)
986 return E_INVALIDARG;
988 ret = __CLSIDFromString(idstr, id);
989 if(ret != S_OK) { /* It appears a ProgID is also valid */
990 ret = CLSIDFromProgID(idstr, id);
992 return ret;
995 /* Converts a GUID into the respective string representation. */
996 HRESULT WINE_StringFromCLSID(
997 const CLSID *id, /* [in] GUID to be converted */
998 LPSTR idstr /* [out] pointer to buffer to contain converted guid */
1000 static const char hex[] = "0123456789ABCDEF";
1001 char *s;
1002 int i;
1004 if (!id)
1005 { ERR("called with id=Null\n");
1006 *idstr = 0x00;
1007 return E_FAIL;
1010 sprintf(idstr, "{%08X-%04X-%04X-%02X%02X-",
1011 id->Data1, id->Data2, id->Data3,
1012 id->Data4[0], id->Data4[1]);
1013 s = &idstr[25];
1015 /* 6 hex bytes */
1016 for (i = 2; i < 8; i++) {
1017 *s++ = hex[id->Data4[i]>>4];
1018 *s++ = hex[id->Data4[i] & 0xf];
1021 *s++ = '}';
1022 *s++ = '\0';
1024 TRACE("%p->%s\n", id, idstr);
1026 return S_OK;
1030 /******************************************************************************
1031 * StringFromCLSID [OLE32.@]
1032 * StringFromIID [OLE32.@]
1034 * Converts a GUID into the respective string representation.
1035 * The target string is allocated using the OLE IMalloc.
1037 * PARAMS
1038 * id [I] the GUID to be converted.
1039 * idstr [O] A pointer to a to-be-allocated pointer pointing to the resulting string.
1041 * RETURNS
1042 * S_OK
1043 * E_FAIL
1045 * SEE ALSO
1046 * StringFromGUID2, CLSIDFromString
1048 HRESULT WINAPI StringFromCLSID(REFCLSID id, LPOLESTR *idstr)
1050 char buf[80];
1051 HRESULT ret;
1052 LPMALLOC mllc;
1054 if ((ret = CoGetMalloc(0,&mllc)))
1055 return ret;
1057 ret=WINE_StringFromCLSID(id,buf);
1058 if (!ret) {
1059 DWORD len = MultiByteToWideChar( CP_ACP, 0, buf, -1, NULL, 0 );
1060 *idstr = IMalloc_Alloc( mllc, len * sizeof(WCHAR) );
1061 MultiByteToWideChar( CP_ACP, 0, buf, -1, *idstr, len );
1063 return ret;
1066 /******************************************************************************
1067 * StringFromGUID2 [OLE32.@]
1068 * StringFromGUID2 [COMPOBJ.76]
1070 * Modified version of StringFromCLSID that allows you to specify max
1071 * buffer size.
1073 * PARAMS
1074 * id [I] GUID to convert to string.
1075 * str [O] Buffer where the result will be stored.
1076 * cmax [I] Size of the buffer in characters.
1078 * RETURNS
1079 * Success: The length of the resulting string in characters.
1080 * Failure: 0.
1082 INT WINAPI StringFromGUID2(REFGUID id, LPOLESTR str, INT cmax)
1084 char xguid[80];
1086 if (WINE_StringFromCLSID(id,xguid))
1087 return 0;
1088 return MultiByteToWideChar( CP_ACP, 0, xguid, -1, str, cmax );
1091 /* open HKCR\\CLSID\\{string form of clsid}\\{keyname} key */
1092 HRESULT COM_OpenKeyForCLSID(REFCLSID clsid, LPCWSTR keyname, REGSAM access, HKEY *subkey)
1094 static const WCHAR wszCLSIDSlash[] = {'C','L','S','I','D','\\',0};
1095 WCHAR path[CHARS_IN_GUID + ARRAYSIZE(wszCLSIDSlash) - 1];
1096 LONG res;
1097 HKEY key;
1099 strcpyW(path, wszCLSIDSlash);
1100 StringFromGUID2(clsid, path + strlenW(wszCLSIDSlash), CHARS_IN_GUID);
1101 res = RegOpenKeyExW(HKEY_CLASSES_ROOT, path, 0, keyname ? KEY_READ : access, &key);
1102 if (res == ERROR_FILE_NOT_FOUND)
1103 return REGDB_E_CLASSNOTREG;
1104 else if (res != ERROR_SUCCESS)
1105 return REGDB_E_READREGDB;
1107 if (!keyname)
1109 *subkey = key;
1110 return S_OK;
1113 res = RegOpenKeyExW(key, keyname, 0, access, subkey);
1114 RegCloseKey(key);
1115 if (res == ERROR_FILE_NOT_FOUND)
1116 return REGDB_E_KEYMISSING;
1117 else if (res != ERROR_SUCCESS)
1118 return REGDB_E_READREGDB;
1120 return S_OK;
1123 /* open HKCR\\AppId\\{string form of appid clsid} key */
1124 HRESULT COM_OpenKeyForAppIdFromCLSID(REFCLSID clsid, REGSAM access, HKEY *subkey)
1126 static const WCHAR szAppId[] = { 'A','p','p','I','d',0 };
1127 static const WCHAR szAppIdKey[] = { 'A','p','p','I','d','\\',0 };
1128 DWORD res;
1129 WCHAR buf[CHARS_IN_GUID];
1130 WCHAR keyname[ARRAYSIZE(szAppIdKey) + CHARS_IN_GUID];
1131 DWORD size;
1132 HKEY hkey;
1133 DWORD type;
1134 HRESULT hr;
1136 /* read the AppID value under the class's key */
1137 hr = COM_OpenKeyForCLSID(clsid, NULL, KEY_READ, &hkey);
1138 if (FAILED(hr))
1139 return hr;
1141 size = sizeof(buf);
1142 res = RegQueryValueExW(hkey, szAppId, NULL, &type, (LPBYTE)buf, &size);
1143 RegCloseKey(hkey);
1144 if (res == ERROR_FILE_NOT_FOUND)
1145 return REGDB_E_KEYMISSING;
1146 else if (res != ERROR_SUCCESS || type!=REG_SZ)
1147 return REGDB_E_READREGDB;
1149 strcpyW(keyname, szAppIdKey);
1150 strcatW(keyname, buf);
1151 res = RegOpenKeyExW(HKEY_CLASSES_ROOT, keyname, 0, access, subkey);
1152 if (res == ERROR_FILE_NOT_FOUND)
1153 return REGDB_E_KEYMISSING;
1154 else if (res != ERROR_SUCCESS)
1155 return REGDB_E_READREGDB;
1157 return S_OK;
1160 /******************************************************************************
1161 * ProgIDFromCLSID [OLE32.@]
1163 * Converts a class id into the respective program ID.
1165 * PARAMS
1166 * clsid [I] Class ID, as found in registry.
1167 * ppszProgID [O] Associated ProgID.
1169 * RETURNS
1170 * S_OK
1171 * E_OUTOFMEMORY
1172 * REGDB_E_CLASSNOTREG if the given clsid has no associated ProgID
1174 HRESULT WINAPI ProgIDFromCLSID(REFCLSID clsid, LPOLESTR *ppszProgID)
1176 static const WCHAR wszProgID[] = {'P','r','o','g','I','D',0};
1177 HKEY hkey;
1178 HRESULT ret;
1179 LONG progidlen = 0;
1181 if (!ppszProgID)
1183 ERR("ppszProgId isn't optional\n");
1184 return E_INVALIDARG;
1187 *ppszProgID = NULL;
1188 ret = COM_OpenKeyForCLSID(clsid, wszProgID, KEY_READ, &hkey);
1189 if (FAILED(ret))
1190 return ret;
1192 if (RegQueryValueW(hkey, NULL, NULL, &progidlen))
1193 ret = REGDB_E_CLASSNOTREG;
1195 if (ret == S_OK)
1197 *ppszProgID = CoTaskMemAlloc(progidlen * sizeof(WCHAR));
1198 if (*ppszProgID)
1200 if (RegQueryValueW(hkey, NULL, *ppszProgID, &progidlen))
1201 ret = REGDB_E_CLASSNOTREG;
1203 else
1204 ret = E_OUTOFMEMORY;
1207 RegCloseKey(hkey);
1208 return ret;
1211 /******************************************************************************
1212 * CLSIDFromProgID [OLE32.@]
1214 * Converts a program id into the respective GUID.
1216 * PARAMS
1217 * progid [I] Unicode program ID, as found in registry.
1218 * clsid [O] Associated CLSID.
1220 * RETURNS
1221 * Success: S_OK
1222 * Failure: CO_E_CLASSSTRING - the given ProgID cannot be found.
1224 HRESULT WINAPI CLSIDFromProgID(LPCOLESTR progid, LPCLSID clsid)
1226 static const WCHAR clsidW[] = { '\\','C','L','S','I','D',0 };
1227 WCHAR buf2[CHARS_IN_GUID];
1228 LONG buf2len = sizeof(buf2);
1229 HKEY xhkey;
1230 WCHAR *buf;
1232 if (!progid || !clsid)
1234 ERR("neither progid (%p) nor clsid (%p) are optional\n", progid, clsid);
1235 return E_INVALIDARG;
1238 /* initialise clsid in case of failure */
1239 memset(clsid, 0, sizeof(*clsid));
1241 buf = HeapAlloc( GetProcessHeap(),0,(strlenW(progid)+8) * sizeof(WCHAR) );
1242 strcpyW( buf, progid );
1243 strcatW( buf, clsidW );
1244 if (RegOpenKeyW(HKEY_CLASSES_ROOT,buf,&xhkey))
1246 HeapFree(GetProcessHeap(),0,buf);
1247 return CO_E_CLASSSTRING;
1249 HeapFree(GetProcessHeap(),0,buf);
1251 if (RegQueryValueW(xhkey,NULL,buf2,&buf2len))
1253 RegCloseKey(xhkey);
1254 return CO_E_CLASSSTRING;
1256 RegCloseKey(xhkey);
1257 return CLSIDFromString(buf2,clsid);
1261 /*****************************************************************************
1262 * CoGetPSClsid [OLE32.@]
1264 * Retrieves the CLSID of the proxy/stub factory that implements
1265 * IPSFactoryBuffer for the specified interface.
1267 * PARAMS
1268 * riid [I] Interface whose proxy/stub CLSID is to be returned.
1269 * pclsid [O] Where to store returned proxy/stub CLSID.
1271 * RETURNS
1272 * S_OK
1273 * E_OUTOFMEMORY
1274 * REGDB_E_IIDNOTREG if no PSFactoryBuffer is associated with the IID, or it could not be parsed
1276 * NOTES
1278 * The standard marshaller activates the object with the CLSID
1279 * returned and uses the CreateProxy and CreateStub methods on its
1280 * IPSFactoryBuffer interface to construct the proxies and stubs for a
1281 * given object.
1283 * CoGetPSClsid determines this CLSID by searching the
1284 * HKEY_CLASSES_ROOT\Interface\{string form of riid}\ProxyStubClsid32
1285 * in the registry and any interface id registered by
1286 * CoRegisterPSClsid within the current process.
1288 * BUGS
1290 * Native returns S_OK for interfaces with a key in HKCR\Interface, but
1291 * without a ProxyStubClsid32 key and leaves garbage in pclsid. This should be
1292 * considered a bug in native unless an application depends on this (unlikely).
1294 * SEE ALSO
1295 * CoRegisterPSClsid.
1297 HRESULT WINAPI CoGetPSClsid(REFIID riid, CLSID *pclsid)
1299 static const WCHAR wszInterface[] = {'I','n','t','e','r','f','a','c','e','\\',0};
1300 static const WCHAR wszPSC[] = {'\\','P','r','o','x','y','S','t','u','b','C','l','s','i','d','3','2',0};
1301 WCHAR path[ARRAYSIZE(wszInterface) - 1 + CHARS_IN_GUID - 1 + ARRAYSIZE(wszPSC)];
1302 WCHAR value[CHARS_IN_GUID];
1303 LONG len;
1304 HKEY hkey;
1305 APARTMENT *apt = COM_CurrentApt();
1306 struct registered_psclsid *registered_psclsid;
1308 TRACE("() riid=%s, pclsid=%p\n", debugstr_guid(riid), pclsid);
1310 if (!apt)
1312 ERR("apartment not initialised\n");
1313 return CO_E_NOTINITIALIZED;
1316 if (!pclsid)
1318 ERR("pclsid isn't optional\n");
1319 return E_INVALIDARG;
1322 EnterCriticalSection(&apt->cs);
1324 LIST_FOR_EACH_ENTRY(registered_psclsid, &apt->psclsids, struct registered_psclsid, entry)
1325 if (IsEqualIID(&registered_psclsid->iid, riid))
1327 *pclsid = registered_psclsid->clsid;
1328 LeaveCriticalSection(&apt->cs);
1329 return S_OK;
1332 LeaveCriticalSection(&apt->cs);
1334 /* Interface\\{string form of riid}\\ProxyStubClsid32 */
1335 strcpyW(path, wszInterface);
1336 StringFromGUID2(riid, path + ARRAYSIZE(wszInterface) - 1, CHARS_IN_GUID);
1337 strcpyW(path + ARRAYSIZE(wszInterface) - 1 + CHARS_IN_GUID - 1, wszPSC);
1339 /* Open the key.. */
1340 if (RegOpenKeyExW(HKEY_CLASSES_ROOT, path, 0, KEY_READ, &hkey))
1342 WARN("No PSFactoryBuffer object is registered for IID %s\n", debugstr_guid(riid));
1343 return REGDB_E_IIDNOTREG;
1346 /* ... Once we have the key, query the registry to get the
1347 value of CLSID as a string, and convert it into a
1348 proper CLSID structure to be passed back to the app */
1349 len = sizeof(value);
1350 if (ERROR_SUCCESS != RegQueryValueW(hkey, NULL, value, &len))
1352 RegCloseKey(hkey);
1353 return REGDB_E_IIDNOTREG;
1355 RegCloseKey(hkey);
1357 /* We have the CLSid we want back from the registry as a string, so
1358 lets convert it into a CLSID structure */
1359 if (CLSIDFromString(value, pclsid) != NOERROR)
1360 return REGDB_E_IIDNOTREG;
1362 TRACE ("() Returning CLSID=%s\n", debugstr_guid(pclsid));
1363 return S_OK;
1366 /*****************************************************************************
1367 * CoRegisterPSClsid [OLE32.@]
1369 * Register a proxy/stub CLSID for the given interface in the current process
1370 * only.
1372 * PARAMS
1373 * riid [I] Interface whose proxy/stub CLSID is to be registered.
1374 * rclsid [I] CLSID of the proxy/stub.
1376 * RETURNS
1377 * Success: S_OK
1378 * Failure: E_OUTOFMEMORY
1380 * NOTES
1382 * This function does not add anything to the registry and the effects are
1383 * limited to the lifetime of the current process.
1385 * SEE ALSO
1386 * CoGetPSClsid.
1388 HRESULT WINAPI CoRegisterPSClsid(REFIID riid, REFCLSID rclsid)
1390 APARTMENT *apt = COM_CurrentApt();
1391 struct registered_psclsid *registered_psclsid;
1393 TRACE("(%s, %s)\n", debugstr_guid(riid), debugstr_guid(rclsid));
1395 if (!apt)
1397 ERR("apartment not initialised\n");
1398 return CO_E_NOTINITIALIZED;
1401 EnterCriticalSection(&apt->cs);
1403 LIST_FOR_EACH_ENTRY(registered_psclsid, &apt->psclsids, struct registered_psclsid, entry)
1404 if (IsEqualIID(&registered_psclsid->iid, riid))
1406 registered_psclsid->clsid = *rclsid;
1407 LeaveCriticalSection(&apt->cs);
1408 return S_OK;
1411 registered_psclsid = HeapAlloc(GetProcessHeap(), 0, sizeof(struct registered_psclsid));
1412 if (!registered_psclsid)
1414 LeaveCriticalSection(&apt->cs);
1415 return E_OUTOFMEMORY;
1418 registered_psclsid->iid = *riid;
1419 registered_psclsid->clsid = *rclsid;
1420 list_add_head(&apt->psclsids, &registered_psclsid->entry);
1422 LeaveCriticalSection(&apt->cs);
1424 return S_OK;
1428 /***
1429 * COM_GetRegisteredClassObject
1431 * This internal method is used to scan the registered class list to
1432 * find a class object.
1434 * Params:
1435 * rclsid Class ID of the class to find.
1436 * dwClsContext Class context to match.
1437 * ppv [out] returns a pointer to the class object. Complying
1438 * to normal COM usage, this method will increase the
1439 * reference count on this object.
1441 static HRESULT COM_GetRegisteredClassObject(
1442 REFCLSID rclsid,
1443 DWORD dwClsContext,
1444 LPUNKNOWN* ppUnk)
1446 HRESULT hr = S_FALSE;
1447 RegisteredClass* curClass;
1449 EnterCriticalSection( &csRegisteredClassList );
1452 * Sanity check
1454 assert(ppUnk!=0);
1457 * Iterate through the whole list and try to match the class ID.
1459 curClass = firstRegisteredClass;
1461 while (curClass != 0)
1464 * Check if we have a match on the class ID.
1466 if (IsEqualGUID(&(curClass->classIdentifier), rclsid))
1469 * Since we don't do out-of process or DCOM just right away, let's ignore the
1470 * class context.
1474 * We have a match, return the pointer to the class object.
1476 *ppUnk = curClass->classObject;
1478 IUnknown_AddRef(curClass->classObject);
1480 hr = S_OK;
1481 goto end;
1485 * Step to the next class in the list.
1487 curClass = curClass->nextClass;
1490 end:
1491 LeaveCriticalSection( &csRegisteredClassList );
1493 * If we get to here, we haven't found our class.
1495 return hr;
1498 /******************************************************************************
1499 * CoRegisterClassObject [OLE32.@]
1501 * Registers the class object for a given class ID. Servers housed in EXE
1502 * files use this method instead of exporting DllGetClassObject to allow
1503 * other code to connect to their objects.
1505 * PARAMS
1506 * rclsid [I] CLSID of the object to register.
1507 * pUnk [I] IUnknown of the object.
1508 * dwClsContext [I] CLSCTX flags indicating the context in which to run the executable.
1509 * flags [I] REGCLS flags indicating how connections are made.
1510 * lpdwRegister [I] A unique cookie that can be passed to CoRevokeClassObject.
1512 * RETURNS
1513 * S_OK on success,
1514 * E_INVALIDARG if lpdwRegister or pUnk are NULL,
1515 * CO_E_OBJISREG if the object is already registered. We should not return this.
1517 * SEE ALSO
1518 * CoRevokeClassObject, CoGetClassObject
1520 * BUGS
1521 * MSDN claims that multiple interface registrations are legal, but we
1522 * can't do that with our current implementation.
1524 HRESULT WINAPI CoRegisterClassObject(
1525 REFCLSID rclsid,
1526 LPUNKNOWN pUnk,
1527 DWORD dwClsContext,
1528 DWORD flags,
1529 LPDWORD lpdwRegister)
1531 RegisteredClass* newClass;
1532 LPUNKNOWN foundObject;
1533 HRESULT hr;
1535 TRACE("(%s,%p,0x%08x,0x%08x,%p)\n",
1536 debugstr_guid(rclsid),pUnk,dwClsContext,flags,lpdwRegister);
1538 if ( (lpdwRegister==0) || (pUnk==0) )
1539 return E_INVALIDARG;
1541 if (!COM_CurrentApt())
1543 ERR("COM was not initialized\n");
1544 return CO_E_NOTINITIALIZED;
1547 *lpdwRegister = 0;
1550 * First, check if the class is already registered.
1551 * If it is, this should cause an error.
1553 hr = COM_GetRegisteredClassObject(rclsid, dwClsContext, &foundObject);
1554 if (hr == S_OK) {
1555 if (flags & REGCLS_MULTIPLEUSE) {
1556 if (dwClsContext & CLSCTX_LOCAL_SERVER)
1557 hr = CoLockObjectExternal(foundObject, TRUE, FALSE);
1558 IUnknown_Release(foundObject);
1559 return hr;
1561 IUnknown_Release(foundObject);
1562 ERR("object already registered for class %s\n", debugstr_guid(rclsid));
1563 return CO_E_OBJISREG;
1566 newClass = HeapAlloc(GetProcessHeap(), 0, sizeof(RegisteredClass));
1567 if ( newClass == NULL )
1568 return E_OUTOFMEMORY;
1570 EnterCriticalSection( &csRegisteredClassList );
1572 newClass->classIdentifier = *rclsid;
1573 newClass->runContext = dwClsContext;
1574 newClass->connectFlags = flags;
1575 newClass->pMarshaledData = NULL;
1578 * Use the address of the chain node as the cookie since we are sure it's
1579 * unique. FIXME: not on 64-bit platforms.
1581 newClass->dwCookie = (DWORD)newClass;
1582 newClass->nextClass = firstRegisteredClass;
1585 * Since we're making a copy of the object pointer, we have to increase its
1586 * reference count.
1588 newClass->classObject = pUnk;
1589 IUnknown_AddRef(newClass->classObject);
1591 firstRegisteredClass = newClass;
1592 LeaveCriticalSection( &csRegisteredClassList );
1594 *lpdwRegister = newClass->dwCookie;
1596 if (dwClsContext & CLSCTX_LOCAL_SERVER) {
1597 IClassFactory *classfac;
1599 hr = IUnknown_QueryInterface(newClass->classObject, &IID_IClassFactory,
1600 (LPVOID*)&classfac);
1601 if (hr) return hr;
1603 hr = CreateStreamOnHGlobal(0, TRUE, &newClass->pMarshaledData);
1604 if (hr) {
1605 FIXME("Failed to create stream on hglobal, %x\n", hr);
1606 IUnknown_Release(classfac);
1607 return hr;
1609 hr = CoMarshalInterface(newClass->pMarshaledData, &IID_IClassFactory,
1610 (LPVOID)classfac, MSHCTX_LOCAL, NULL,
1611 MSHLFLAGS_TABLESTRONG);
1612 if (hr) {
1613 FIXME("CoMarshalInterface failed, %x!\n",hr);
1614 IUnknown_Release(classfac);
1615 return hr;
1618 IUnknown_Release(classfac);
1620 RPC_StartLocalServer(&newClass->classIdentifier, newClass->pMarshaledData);
1622 return S_OK;
1625 /***********************************************************************
1626 * CoRevokeClassObject [OLE32.@]
1628 * Removes a class object from the class registry.
1630 * PARAMS
1631 * dwRegister [I] Cookie returned from CoRegisterClassObject().
1633 * RETURNS
1634 * Success: S_OK.
1635 * Failure: HRESULT code.
1637 * SEE ALSO
1638 * CoRegisterClassObject
1640 HRESULT WINAPI CoRevokeClassObject(
1641 DWORD dwRegister)
1643 HRESULT hr = E_INVALIDARG;
1644 RegisteredClass** prevClassLink;
1645 RegisteredClass* curClass;
1647 TRACE("(%08x)\n",dwRegister);
1649 EnterCriticalSection( &csRegisteredClassList );
1652 * Iterate through the whole list and try to match the cookie.
1654 curClass = firstRegisteredClass;
1655 prevClassLink = &firstRegisteredClass;
1657 while (curClass != 0)
1660 * Check if we have a match on the cookie.
1662 if (curClass->dwCookie == dwRegister)
1665 * Remove the class from the chain.
1667 *prevClassLink = curClass->nextClass;
1670 * Release the reference to the class object.
1672 IUnknown_Release(curClass->classObject);
1674 if (curClass->pMarshaledData)
1676 LARGE_INTEGER zero;
1677 memset(&zero, 0, sizeof(zero));
1678 /* FIXME: stop local server thread */
1679 IStream_Seek(curClass->pMarshaledData, zero, STREAM_SEEK_SET, NULL);
1680 CoReleaseMarshalData(curClass->pMarshaledData);
1684 * Free the memory used by the chain node.
1686 HeapFree(GetProcessHeap(), 0, curClass);
1688 hr = S_OK;
1689 goto end;
1693 * Step to the next class in the list.
1695 prevClassLink = &(curClass->nextClass);
1696 curClass = curClass->nextClass;
1699 end:
1700 LeaveCriticalSection( &csRegisteredClassList );
1702 * If we get to here, we haven't found our class.
1704 return hr;
1707 /***********************************************************************
1708 * COM_RegReadPath [internal]
1710 * Reads a registry value and expands it when necessary
1712 static DWORD COM_RegReadPath(HKEY hkeyroot, const WCHAR *keyname, const WCHAR *valuename, WCHAR * dst, DWORD dstlen)
1714 DWORD ret;
1715 HKEY key;
1716 DWORD keytype;
1717 WCHAR src[MAX_PATH];
1718 DWORD dwLength = dstlen * sizeof(WCHAR);
1720 if((ret = RegOpenKeyExW(hkeyroot, keyname, 0, KEY_READ, &key)) == ERROR_SUCCESS) {
1721 if( (ret = RegQueryValueExW(key, NULL, NULL, &keytype, (LPBYTE)src, &dwLength)) == ERROR_SUCCESS ) {
1722 if (keytype == REG_EXPAND_SZ) {
1723 if (dstlen <= ExpandEnvironmentStringsW(src, dst, dstlen)) ret = ERROR_MORE_DATA;
1724 } else {
1725 lstrcpynW(dst, src, dstlen);
1728 RegCloseKey (key);
1730 return ret;
1733 static void get_threading_model(HKEY key, LPWSTR value, DWORD len)
1735 static const WCHAR wszThreadingModel[] = {'T','h','r','e','a','d','i','n','g','M','o','d','e','l',0};
1736 DWORD keytype;
1737 DWORD ret;
1738 DWORD dwLength = len * sizeof(WCHAR);
1740 ret = RegQueryValueExW(key, wszThreadingModel, NULL, &keytype, (LPBYTE)value, &dwLength);
1741 if ((ret != ERROR_SUCCESS) || (keytype != REG_SZ))
1742 value[0] = '\0';
1745 static HRESULT get_inproc_class_object(HKEY hkeydll, REFCLSID rclsid, REFIID riid, void **ppv)
1747 static const WCHAR wszApartment[] = {'A','p','a','r','t','m','e','n','t',0};
1748 static const WCHAR wszFree[] = {'F','r','e','e',0};
1749 static const WCHAR wszBoth[] = {'B','o','t','h',0};
1750 HINSTANCE hLibrary;
1751 typedef HRESULT (CALLBACK *DllGetClassObjectFunc)(REFCLSID clsid, REFIID iid, LPVOID *ppv);
1752 DllGetClassObjectFunc DllGetClassObject;
1753 WCHAR dllpath[MAX_PATH+1];
1754 WCHAR threading_model[10 /* strlenW(L"apartment")+1 */];
1755 HRESULT hr;
1757 get_threading_model(hkeydll, threading_model, ARRAYSIZE(threading_model));
1758 /* "Apartment" */
1759 if (!strcmpiW(threading_model, wszApartment))
1761 APARTMENT *apt = COM_CurrentApt();
1762 if (apt->multi_threaded)
1764 /* try to find an STA */
1765 APARTMENT *host_apt = apartment_findfromtype(FALSE, FALSE);
1766 if (!host_apt)
1767 FIXME("create a host apartment for apartment-threaded object %s\n", debugstr_guid(rclsid));
1768 if (host_apt)
1770 struct host_object_params params;
1771 HWND hwnd = apartment_getwindow(host_apt);
1773 params.hkeydll = hkeydll;
1774 params.clsid = *rclsid;
1775 params.iid = *riid;
1776 hr = CreateStreamOnHGlobal(NULL, TRUE, &params.stream);
1777 if (FAILED(hr))
1778 return hr;
1779 hr = SendMessageW(hwnd, DM_HOSTOBJECT, 0, (LPARAM)&params);
1780 if (SUCCEEDED(hr))
1781 hr = CoUnmarshalInterface(params.stream, riid, ppv);
1782 IStream_Release(params.stream);
1783 return hr;
1787 /* "Free" */
1788 else if (!strcmpiW(threading_model, wszFree))
1790 APARTMENT *apt = COM_CurrentApt();
1791 if (!apt->multi_threaded)
1793 FIXME("should create object %s in multi-threaded apartment\n",
1794 debugstr_guid(rclsid));
1797 /* everything except "Apartment", "Free" and "Both" */
1798 else if (strcmpiW(threading_model, wszBoth))
1800 APARTMENT *apt = COM_CurrentApt();
1802 /* everything else is main-threaded */
1803 if (threading_model[0])
1804 FIXME("unrecognised threading model %s for object %s, should be main-threaded?\n",
1805 debugstr_w(threading_model), debugstr_guid(rclsid));
1807 if (apt->multi_threaded || !apt->main)
1809 /* try to find an STA */
1810 APARTMENT *host_apt = apartment_findfromtype(FALSE, TRUE);
1811 if (!host_apt)
1812 FIXME("create a host apartment for main-threaded object %s\n", debugstr_guid(rclsid));
1813 if (host_apt)
1815 struct host_object_params params;
1816 HWND hwnd = apartment_getwindow(host_apt);
1818 params.hkeydll = hkeydll;
1819 params.clsid = *rclsid;
1820 params.iid = *riid;
1821 hr = CreateStreamOnHGlobal(NULL, TRUE, &params.stream);
1822 if (FAILED(hr))
1823 return hr;
1824 hr = SendMessageW(hwnd, DM_HOSTOBJECT, 0, (LPARAM)&params);
1825 if (SUCCEEDED(hr))
1826 hr = CoUnmarshalInterface(params.stream, riid, ppv);
1827 IStream_Release(params.stream);
1828 return hr;
1833 if (COM_RegReadPath(hkeydll, NULL, NULL, dllpath, ARRAYSIZE(dllpath)) != ERROR_SUCCESS)
1835 /* failure: CLSID is not found in registry */
1836 WARN("class %s not registered inproc\n", debugstr_guid(rclsid));
1837 return REGDB_E_CLASSNOTREG;
1840 if ((hLibrary = LoadLibraryExW(dllpath, 0, LOAD_WITH_ALTERED_SEARCH_PATH)) == 0)
1842 /* failure: DLL could not be loaded */
1843 ERR("couldn't load in-process dll %s\n", debugstr_w(dllpath));
1844 return E_ACCESSDENIED; /* FIXME: or should this be CO_E_DLLNOTFOUND? */
1847 if (!(DllGetClassObject = (DllGetClassObjectFunc)GetProcAddress(hLibrary, "DllGetClassObject")))
1849 /* failure: the dll did not export DllGetClassObject */
1850 ERR("couldn't find function DllGetClassObject in %s\n", debugstr_w(dllpath));
1851 FreeLibrary( hLibrary );
1852 return CO_E_DLLNOTFOUND;
1855 /* OK: get the ClassObject */
1856 COMPOBJ_DLLList_Add( hLibrary );
1857 hr = DllGetClassObject(rclsid, riid, ppv);
1859 if (hr != S_OK)
1860 ERR("DllGetClassObject returned error 0x%08x\n", hr);
1862 return hr;
1865 /***********************************************************************
1866 * CoGetClassObject [OLE32.@]
1868 * FIXME. If request allows of several options and there is a failure
1869 * with one (other than not being registered) do we try the
1870 * others or return failure? (E.g. inprocess is registered but
1871 * the DLL is not found but the server version works)
1873 HRESULT WINAPI CoGetClassObject(
1874 REFCLSID rclsid, DWORD dwClsContext, COSERVERINFO *pServerInfo,
1875 REFIID iid, LPVOID *ppv)
1877 LPUNKNOWN regClassObject;
1878 HRESULT hres = E_UNEXPECTED;
1880 TRACE("\n\tCLSID:\t%s,\n\tIID:\t%s\n", debugstr_guid(rclsid), debugstr_guid(iid));
1882 if (!ppv)
1883 return E_INVALIDARG;
1885 *ppv = NULL;
1887 if (!COM_CurrentApt())
1889 ERR("apartment not initialised\n");
1890 return CO_E_NOTINITIALIZED;
1893 if (pServerInfo) {
1894 FIXME("\tpServerInfo: name=%s\n",debugstr_w(pServerInfo->pwszName));
1895 FIXME("\t\tpAuthInfo=%p\n",pServerInfo->pAuthInfo);
1899 * First, try and see if we can't match the class ID with one of the
1900 * registered classes.
1902 if (S_OK == COM_GetRegisteredClassObject(rclsid, dwClsContext, &regClassObject))
1904 /* Get the required interface from the retrieved pointer. */
1905 hres = IUnknown_QueryInterface(regClassObject, iid, ppv);
1908 * Since QI got another reference on the pointer, we want to release the
1909 * one we already have. If QI was unsuccessful, this will release the object. This
1910 * is good since we are not returning it in the "out" parameter.
1912 IUnknown_Release(regClassObject);
1914 return hres;
1917 /* First try in-process server */
1918 if (CLSCTX_INPROC_SERVER & dwClsContext)
1920 static const WCHAR wszInprocServer32[] = {'I','n','p','r','o','c','S','e','r','v','e','r','3','2',0};
1921 HKEY hkey;
1923 if (IsEqualCLSID(rclsid, &CLSID_InProcFreeMarshaler))
1924 return FTMarshalCF_Create(iid, ppv);
1926 hres = COM_OpenKeyForCLSID(rclsid, wszInprocServer32, KEY_READ, &hkey);
1927 if (FAILED(hres))
1929 if (hres == REGDB_E_CLASSNOTREG)
1930 ERR("class %s not registered\n", debugstr_guid(rclsid));
1931 else
1932 WARN("class %s not registered as in-proc server\n", debugstr_guid(rclsid));
1935 if (SUCCEEDED(hres))
1937 hres = get_inproc_class_object(hkey, rclsid, iid, ppv);
1938 RegCloseKey(hkey);
1941 /* return if we got a class, otherwise fall through to one of the
1942 * other types */
1943 if (SUCCEEDED(hres))
1944 return hres;
1947 /* Next try in-process handler */
1948 if (CLSCTX_INPROC_HANDLER & dwClsContext)
1950 static const WCHAR wszInprocHandler32[] = {'I','n','p','r','o','c','H','a','n','d','l','e','r','3','2',0};
1951 HKEY hkey;
1953 hres = COM_OpenKeyForCLSID(rclsid, wszInprocHandler32, KEY_READ, &hkey);
1954 if (FAILED(hres))
1956 if (hres == REGDB_E_CLASSNOTREG)
1957 ERR("class %s not registered\n", debugstr_guid(rclsid));
1958 else
1959 WARN("class %s not registered in-proc handler\n", debugstr_guid(rclsid));
1962 if (SUCCEEDED(hres))
1964 hres = get_inproc_class_object(hkey, rclsid, iid, ppv);
1965 RegCloseKey(hkey);
1968 /* return if we got a class, otherwise fall through to one of the
1969 * other types */
1970 if (SUCCEEDED(hres))
1971 return hres;
1974 /* Next try out of process */
1975 if (CLSCTX_LOCAL_SERVER & dwClsContext)
1977 hres = RPC_GetLocalClassObject(rclsid,iid,ppv);
1978 if (SUCCEEDED(hres))
1979 return hres;
1982 /* Finally try remote: this requires networked DCOM (a lot of work) */
1983 if (CLSCTX_REMOTE_SERVER & dwClsContext)
1985 FIXME ("CLSCTX_REMOTE_SERVER not supported\n");
1986 hres = E_NOINTERFACE;
1989 if (FAILED(hres))
1990 ERR("no class object %s could be created for context 0x%x\n",
1991 debugstr_guid(rclsid), dwClsContext);
1992 return hres;
1995 /***********************************************************************
1996 * CoResumeClassObjects (OLE32.@)
1998 * Resumes all class objects registered with REGCLS_SUSPENDED.
2000 * RETURNS
2001 * Success: S_OK.
2002 * Failure: HRESULT code.
2004 HRESULT WINAPI CoResumeClassObjects(void)
2006 FIXME("stub\n");
2007 return S_OK;
2010 /***********************************************************************
2011 * GetClassFile (OLE32.@)
2013 * This function supplies the CLSID associated with the given filename.
2015 HRESULT WINAPI GetClassFile(LPCOLESTR filePathName,CLSID *pclsid)
2017 IStorage *pstg=0;
2018 HRESULT res;
2019 int nbElm, length, i;
2020 LONG sizeProgId;
2021 LPOLESTR *pathDec=0,absFile=0,progId=0;
2022 LPWSTR extension;
2023 static const WCHAR bkslashW[] = {'\\',0};
2024 static const WCHAR dotW[] = {'.',0};
2026 TRACE("%s, %p\n", debugstr_w(filePathName), pclsid);
2028 /* if the file contain a storage object the return the CLSID written by IStorage_SetClass method*/
2029 if((StgIsStorageFile(filePathName))==S_OK){
2031 res=StgOpenStorage(filePathName,NULL,STGM_READ | STGM_SHARE_DENY_WRITE,NULL,0,&pstg);
2033 if (SUCCEEDED(res))
2034 res=ReadClassStg(pstg,pclsid);
2036 IStorage_Release(pstg);
2038 return res;
2040 /* if the file is not a storage object then attemps to match various bits in the file against a
2041 pattern in the registry. this case is not frequently used ! so I present only the psodocode for
2042 this case
2044 for(i=0;i<nFileTypes;i++)
2046 for(i=0;j<nPatternsForType;j++){
2048 PATTERN pat;
2049 HANDLE hFile;
2051 pat=ReadPatternFromRegistry(i,j);
2052 hFile=CreateFileW(filePathName,,,,,,hFile);
2053 SetFilePosition(hFile,pat.offset);
2054 ReadFile(hFile,buf,pat.size,&r,NULL);
2055 if (memcmp(buf&pat.mask,pat.pattern.pat.size)==0){
2057 *pclsid=ReadCLSIDFromRegistry(i);
2058 return S_OK;
2063 /* if the above strategies fail then search for the extension key in the registry */
2065 /* get the last element (absolute file) in the path name */
2066 nbElm=FileMonikerImpl_DecomposePath(filePathName,&pathDec);
2067 absFile=pathDec[nbElm-1];
2069 /* failed if the path represente a directory and not an absolute file name*/
2070 if (!lstrcmpW(absFile, bkslashW))
2071 return MK_E_INVALIDEXTENSION;
2073 /* get the extension of the file */
2074 extension = NULL;
2075 length=lstrlenW(absFile);
2076 for(i = length-1; (i >= 0) && *(extension = &absFile[i]) != '.'; i--)
2077 /* nothing */;
2079 if (!extension || !lstrcmpW(extension, dotW))
2080 return MK_E_INVALIDEXTENSION;
2082 res=RegQueryValueW(HKEY_CLASSES_ROOT, extension, NULL, &sizeProgId);
2084 /* get the progId associated to the extension */
2085 progId = CoTaskMemAlloc(sizeProgId);
2086 res = RegQueryValueW(HKEY_CLASSES_ROOT, extension, progId, &sizeProgId);
2088 if (res==ERROR_SUCCESS)
2089 /* return the clsid associated to the progId */
2090 res= CLSIDFromProgID(progId,pclsid);
2092 for(i=0; pathDec[i]!=NULL;i++)
2093 CoTaskMemFree(pathDec[i]);
2094 CoTaskMemFree(pathDec);
2096 CoTaskMemFree(progId);
2098 if (res==ERROR_SUCCESS)
2099 return res;
2101 return MK_E_INVALIDEXTENSION;
2104 /***********************************************************************
2105 * CoCreateInstance [OLE32.@]
2107 * Creates an instance of the specified class.
2109 * PARAMS
2110 * rclsid [I] Class ID to create an instance of.
2111 * pUnkOuter [I] Optional outer unknown to allow aggregation with another object.
2112 * dwClsContext [I] Flags to restrict the location of the created instance.
2113 * iid [I] The ID of the interface of the instance to return.
2114 * ppv [O] On returns, contains a pointer to the specified interface of the instance.
2116 * RETURNS
2117 * Success: S_OK
2118 * Failure: HRESULT code.
2120 * NOTES
2121 * The dwClsContext parameter can be one or more of the following:
2122 *| CLSCTX_INPROC_SERVER - Use an in-process server, such as from a DLL.
2123 *| CLSCTX_INPROC_HANDLER - Use an in-process object which handles certain functions for an object running in another process.
2124 *| CLSCTX_LOCAL_SERVER - Connect to an object running in another process.
2125 *| CLSCTX_REMOTE_SERVER - Connect to an object running on another machine.
2127 * Aggregation is the concept of deferring the IUnknown of an object to another
2128 * object. This allows a separate object to behave as though it was part of
2129 * the object and to allow this the pUnkOuter parameter can be set. Note that
2130 * not all objects support having an outer of unknown.
2132 * SEE ALSO
2133 * CoGetClassObject()
2135 HRESULT WINAPI CoCreateInstance(
2136 REFCLSID rclsid,
2137 LPUNKNOWN pUnkOuter,
2138 DWORD dwClsContext,
2139 REFIID iid,
2140 LPVOID *ppv)
2142 HRESULT hres;
2143 LPCLASSFACTORY lpclf = 0;
2145 TRACE("(rclsid=%s, pUnkOuter=%p, dwClsContext=%08x, riid=%s, ppv=%p)\n", debugstr_guid(rclsid),
2146 pUnkOuter, dwClsContext, debugstr_guid(iid), ppv);
2149 * Sanity check
2151 if (ppv==0)
2152 return E_POINTER;
2155 * Initialize the "out" parameter
2157 *ppv = 0;
2159 if (!COM_CurrentApt())
2161 ERR("apartment not initialised\n");
2162 return CO_E_NOTINITIALIZED;
2166 * The Standard Global Interface Table (GIT) object is a process-wide singleton.
2167 * Rather than create a class factory, we can just check for it here
2169 if (IsEqualIID(rclsid, &CLSID_StdGlobalInterfaceTable)) {
2170 if (StdGlobalInterfaceTableInstance == NULL)
2171 StdGlobalInterfaceTableInstance = StdGlobalInterfaceTable_Construct();
2172 hres = IGlobalInterfaceTable_QueryInterface( (IGlobalInterfaceTable*) StdGlobalInterfaceTableInstance, iid, ppv);
2173 if (hres) return hres;
2175 TRACE("Retrieved GIT (%p)\n", *ppv);
2176 return S_OK;
2180 * Get a class factory to construct the object we want.
2182 hres = CoGetClassObject(rclsid,
2183 dwClsContext,
2184 NULL,
2185 &IID_IClassFactory,
2186 (LPVOID)&lpclf);
2188 if (FAILED(hres))
2189 return hres;
2192 * Create the object and don't forget to release the factory
2194 hres = IClassFactory_CreateInstance(lpclf, pUnkOuter, iid, ppv);
2195 IClassFactory_Release(lpclf);
2196 if(FAILED(hres))
2197 FIXME("no instance created for interface %s of class %s, hres is 0x%08x\n",
2198 debugstr_guid(iid), debugstr_guid(rclsid),hres);
2200 return hres;
2203 /***********************************************************************
2204 * CoCreateInstanceEx [OLE32.@]
2206 HRESULT WINAPI CoCreateInstanceEx(
2207 REFCLSID rclsid,
2208 LPUNKNOWN pUnkOuter,
2209 DWORD dwClsContext,
2210 COSERVERINFO* pServerInfo,
2211 ULONG cmq,
2212 MULTI_QI* pResults)
2214 IUnknown* pUnk = NULL;
2215 HRESULT hr;
2216 ULONG index;
2217 ULONG successCount = 0;
2220 * Sanity check
2222 if ( (cmq==0) || (pResults==NULL))
2223 return E_INVALIDARG;
2225 if (pServerInfo!=NULL)
2226 FIXME("() non-NULL pServerInfo not supported!\n");
2229 * Initialize all the "out" parameters.
2231 for (index = 0; index < cmq; index++)
2233 pResults[index].pItf = NULL;
2234 pResults[index].hr = E_NOINTERFACE;
2238 * Get the object and get its IUnknown pointer.
2240 hr = CoCreateInstance(rclsid,
2241 pUnkOuter,
2242 dwClsContext,
2243 &IID_IUnknown,
2244 (VOID**)&pUnk);
2246 if (hr)
2247 return hr;
2250 * Then, query for all the interfaces requested.
2252 for (index = 0; index < cmq; index++)
2254 pResults[index].hr = IUnknown_QueryInterface(pUnk,
2255 pResults[index].pIID,
2256 (VOID**)&(pResults[index].pItf));
2258 if (pResults[index].hr == S_OK)
2259 successCount++;
2263 * Release our temporary unknown pointer.
2265 IUnknown_Release(pUnk);
2267 if (successCount == 0)
2268 return E_NOINTERFACE;
2270 if (successCount!=cmq)
2271 return CO_S_NOTALLINTERFACES;
2273 return S_OK;
2276 /***********************************************************************
2277 * CoLoadLibrary (OLE32.@)
2279 * Loads a library.
2281 * PARAMS
2282 * lpszLibName [I] Path to library.
2283 * bAutoFree [I] Whether the library should automatically be freed.
2285 * RETURNS
2286 * Success: Handle to loaded library.
2287 * Failure: NULL.
2289 * SEE ALSO
2290 * CoFreeLibrary, CoFreeAllLibraries, CoFreeUnusedLibraries
2292 HINSTANCE WINAPI CoLoadLibrary(LPOLESTR lpszLibName, BOOL bAutoFree)
2294 TRACE("(%s, %d)\n", debugstr_w(lpszLibName), bAutoFree);
2296 return LoadLibraryExW(lpszLibName, 0, LOAD_WITH_ALTERED_SEARCH_PATH);
2299 /***********************************************************************
2300 * CoFreeLibrary [OLE32.@]
2302 * Unloads a library from memory.
2304 * PARAMS
2305 * hLibrary [I] Handle to library to unload.
2307 * RETURNS
2308 * Nothing
2310 * SEE ALSO
2311 * CoLoadLibrary, CoFreeAllLibraries, CoFreeUnusedLibraries
2313 void WINAPI CoFreeLibrary(HINSTANCE hLibrary)
2315 FreeLibrary(hLibrary);
2319 /***********************************************************************
2320 * CoFreeAllLibraries [OLE32.@]
2322 * Function for backwards compatibility only. Does nothing.
2324 * RETURNS
2325 * Nothing.
2327 * SEE ALSO
2328 * CoLoadLibrary, CoFreeLibrary, CoFreeUnusedLibraries
2330 void WINAPI CoFreeAllLibraries(void)
2332 /* NOP */
2336 /***********************************************************************
2337 * CoFreeUnusedLibraries [OLE32.@]
2338 * CoFreeUnusedLibraries [COMPOBJ.17]
2340 * Frees any unused libraries. Unused are identified as those that return
2341 * S_OK from their DllCanUnloadNow function.
2343 * RETURNS
2344 * Nothing.
2346 * SEE ALSO
2347 * CoLoadLibrary, CoFreeAllLibraries, CoFreeLibrary
2349 void WINAPI CoFreeUnusedLibraries(void)
2351 /* FIXME: Calls to CoFreeUnusedLibraries from any thread always route
2352 * through the main apartment's thread to call DllCanUnloadNow */
2353 COMPOBJ_DllList_FreeUnused(0);
2356 /***********************************************************************
2357 * CoFileTimeNow [OLE32.@]
2358 * CoFileTimeNow [COMPOBJ.82]
2360 * Retrieves the current time in FILETIME format.
2362 * PARAMS
2363 * lpFileTime [O] The current time.
2365 * RETURNS
2366 * S_OK.
2368 HRESULT WINAPI CoFileTimeNow( FILETIME *lpFileTime )
2370 GetSystemTimeAsFileTime( lpFileTime );
2371 return S_OK;
2374 static void COM_RevokeAllClasses(void)
2376 EnterCriticalSection( &csRegisteredClassList );
2378 while (firstRegisteredClass!=0)
2380 CoRevokeClassObject(firstRegisteredClass->dwCookie);
2383 LeaveCriticalSection( &csRegisteredClassList );
2386 /******************************************************************************
2387 * CoLockObjectExternal [OLE32.@]
2389 * Increments or decrements the external reference count of a stub object.
2391 * PARAMS
2392 * pUnk [I] Stub object.
2393 * fLock [I] If TRUE then increments the external ref-count,
2394 * otherwise decrements.
2395 * fLastUnlockReleases [I] If TRUE then the last unlock has the effect of
2396 * calling CoDisconnectObject.
2398 * RETURNS
2399 * Success: S_OK.
2400 * Failure: HRESULT code.
2402 * NOTES
2403 * If fLock is TRUE and an object is passed in that doesn't have a stub
2404 * manager then a new stub manager is created for the object.
2406 HRESULT WINAPI CoLockObjectExternal(
2407 LPUNKNOWN pUnk,
2408 BOOL fLock,
2409 BOOL fLastUnlockReleases)
2411 struct stub_manager *stubmgr;
2412 struct apartment *apt;
2414 TRACE("pUnk=%p, fLock=%s, fLastUnlockReleases=%s\n",
2415 pUnk, fLock ? "TRUE" : "FALSE", fLastUnlockReleases ? "TRUE" : "FALSE");
2417 apt = COM_CurrentApt();
2418 if (!apt) return CO_E_NOTINITIALIZED;
2420 stubmgr = get_stub_manager_from_object(apt, pUnk);
2422 if (stubmgr)
2424 if (fLock)
2425 stub_manager_ext_addref(stubmgr, 1);
2426 else
2427 stub_manager_ext_release(stubmgr, 1, fLastUnlockReleases);
2429 stub_manager_int_release(stubmgr);
2431 return S_OK;
2433 else if (fLock)
2435 stubmgr = new_stub_manager(apt, pUnk);
2437 if (stubmgr)
2439 stub_manager_ext_addref(stubmgr, 1);
2440 stub_manager_int_release(stubmgr);
2443 return S_OK;
2445 else
2447 WARN("stub object not found %p\n", pUnk);
2448 /* Note: native is pretty broken here because it just silently
2449 * fails, without returning an appropriate error code, making apps
2450 * think that the object was disconnected, when it actually wasn't */
2451 return S_OK;
2455 /***********************************************************************
2456 * CoInitializeWOW (OLE32.@)
2458 * WOW equivalent of CoInitialize?
2460 * PARAMS
2461 * x [I] Unknown.
2462 * y [I] Unknown.
2464 * RETURNS
2465 * Unknown.
2467 HRESULT WINAPI CoInitializeWOW(DWORD x,DWORD y)
2469 FIXME("(0x%08x,0x%08x),stub!\n",x,y);
2470 return 0;
2473 /***********************************************************************
2474 * CoGetState [OLE32.@]
2476 * Retrieves the thread state object previously stored by CoSetState().
2478 * PARAMS
2479 * ppv [I] Address where pointer to object will be stored.
2481 * RETURNS
2482 * Success: S_OK.
2483 * Failure: E_OUTOFMEMORY.
2485 * NOTES
2486 * Crashes on all invalid ppv addresses, including NULL.
2487 * If the function returns a non-NULL object then the caller must release its
2488 * reference on the object when the object is no longer required.
2490 * SEE ALSO
2491 * CoSetState().
2493 HRESULT WINAPI CoGetState(IUnknown ** ppv)
2495 struct oletls *info = COM_CurrentInfo();
2496 if (!info) return E_OUTOFMEMORY;
2498 *ppv = NULL;
2500 if (info->state)
2502 IUnknown_AddRef(info->state);
2503 *ppv = info->state;
2504 TRACE("apt->state=%p\n", info->state);
2507 return S_OK;
2510 /***********************************************************************
2511 * CoSetState [OLE32.@]
2513 * Sets the thread state object.
2515 * PARAMS
2516 * pv [I] Pointer to state object to be stored.
2518 * NOTES
2519 * The system keeps a reference on the object while the object stored.
2521 * RETURNS
2522 * Success: S_OK.
2523 * Failure: E_OUTOFMEMORY.
2525 HRESULT WINAPI CoSetState(IUnknown * pv)
2527 struct oletls *info = COM_CurrentInfo();
2528 if (!info) return E_OUTOFMEMORY;
2530 if (pv) IUnknown_AddRef(pv);
2532 if (info->state)
2534 TRACE("-- release %p now\n", info->state);
2535 IUnknown_Release(info->state);
2538 info->state = pv;
2540 return S_OK;
2544 /******************************************************************************
2545 * CoTreatAsClass [OLE32.@]
2547 * Sets the TreatAs value of a class.
2549 * PARAMS
2550 * clsidOld [I] Class to set TreatAs value on.
2551 * clsidNew [I] The class the clsidOld should be treated as.
2553 * RETURNS
2554 * Success: S_OK.
2555 * Failure: HRESULT code.
2557 * SEE ALSO
2558 * CoGetTreatAsClass
2560 HRESULT WINAPI CoTreatAsClass(REFCLSID clsidOld, REFCLSID clsidNew)
2562 static const WCHAR wszAutoTreatAs[] = {'A','u','t','o','T','r','e','a','t','A','s',0};
2563 static const WCHAR wszTreatAs[] = {'T','r','e','a','t','A','s',0};
2564 HKEY hkey = NULL;
2565 WCHAR szClsidNew[CHARS_IN_GUID];
2566 HRESULT res = S_OK;
2567 WCHAR auto_treat_as[CHARS_IN_GUID];
2568 LONG auto_treat_as_size = sizeof(auto_treat_as);
2569 CLSID id;
2571 res = COM_OpenKeyForCLSID(clsidOld, NULL, KEY_READ | KEY_WRITE, &hkey);
2572 if (FAILED(res))
2573 goto done;
2574 if (!memcmp( clsidOld, clsidNew, sizeof(*clsidOld) ))
2576 if (!RegQueryValueW(hkey, wszAutoTreatAs, auto_treat_as, &auto_treat_as_size) &&
2577 !CLSIDFromString(auto_treat_as, &id))
2579 if (RegSetValueW(hkey, wszTreatAs, REG_SZ, auto_treat_as, sizeof(auto_treat_as)))
2581 res = REGDB_E_WRITEREGDB;
2582 goto done;
2585 else
2587 RegDeleteKeyW(hkey, wszTreatAs);
2588 goto done;
2591 else if (!StringFromGUID2(clsidNew, szClsidNew, ARRAYSIZE(szClsidNew)) &&
2592 !RegSetValueW(hkey, wszTreatAs, REG_SZ, szClsidNew, sizeof(szClsidNew)))
2594 res = REGDB_E_WRITEREGDB;
2595 goto done;
2598 done:
2599 if (hkey) RegCloseKey(hkey);
2600 return res;
2603 /******************************************************************************
2604 * CoGetTreatAsClass [OLE32.@]
2606 * Gets the TreatAs value of a class.
2608 * PARAMS
2609 * clsidOld [I] Class to get the TreatAs value of.
2610 * clsidNew [I] The class the clsidOld should be treated as.
2612 * RETURNS
2613 * Success: S_OK.
2614 * Failure: HRESULT code.
2616 * SEE ALSO
2617 * CoSetTreatAsClass
2619 HRESULT WINAPI CoGetTreatAsClass(REFCLSID clsidOld, LPCLSID clsidNew)
2621 static const WCHAR wszTreatAs[] = {'T','r','e','a','t','A','s',0};
2622 HKEY hkey = NULL;
2623 WCHAR szClsidNew[CHARS_IN_GUID];
2624 HRESULT res = S_OK;
2625 LONG len = sizeof(szClsidNew);
2627 FIXME("(%s,%p)\n", debugstr_guid(clsidOld), clsidNew);
2628 memcpy(clsidNew,clsidOld,sizeof(CLSID)); /* copy over old value */
2630 res = COM_OpenKeyForCLSID(clsidOld, wszTreatAs, KEY_READ, &hkey);
2631 if (FAILED(res))
2632 goto done;
2633 if (RegQueryValueW(hkey, NULL, szClsidNew, &len))
2635 res = S_FALSE;
2636 goto done;
2638 res = CLSIDFromString(szClsidNew,clsidNew);
2639 if (FAILED(res))
2640 ERR("Failed CLSIDFromStringA(%s), hres 0x%08x\n", debugstr_w(szClsidNew), res);
2641 done:
2642 if (hkey) RegCloseKey(hkey);
2643 return res;
2646 /******************************************************************************
2647 * CoGetCurrentProcess [OLE32.@]
2648 * CoGetCurrentProcess [COMPOBJ.34]
2650 * Gets the current process ID.
2652 * RETURNS
2653 * The current process ID.
2655 * NOTES
2656 * Is DWORD really the correct return type for this function?
2658 DWORD WINAPI CoGetCurrentProcess(void)
2660 return GetCurrentProcessId();
2663 /******************************************************************************
2664 * CoRegisterMessageFilter [OLE32.@]
2666 * Registers a message filter.
2668 * PARAMS
2669 * lpMessageFilter [I] Pointer to interface.
2670 * lplpMessageFilter [O] Indirect pointer to prior instance if non-NULL.
2672 * RETURNS
2673 * Success: S_OK.
2674 * Failure: HRESULT code.
2676 * NOTES
2677 * Both lpMessageFilter and lplpMessageFilter are optional. Passing in a NULL
2678 * lpMessageFilter removes the message filter.
2680 * If lplpMessageFilter is not NULL the previous message filter will be
2681 * returned in the memory pointer to this parameter and the caller is
2682 * responsible for releasing the object.
2684 * The current thread be in an apartment otherwise the function will crash.
2686 HRESULT WINAPI CoRegisterMessageFilter(
2687 LPMESSAGEFILTER lpMessageFilter,
2688 LPMESSAGEFILTER *lplpMessageFilter)
2690 struct apartment *apt;
2691 IMessageFilter *lpOldMessageFilter;
2693 TRACE("(%p, %p)\n", lpMessageFilter, lplpMessageFilter);
2695 apt = COM_CurrentApt();
2697 /* can't set a message filter in a multi-threaded apartment */
2698 if (!apt || apt->multi_threaded)
2700 WARN("can't set message filter in MTA or uninitialized apt\n");
2701 return CO_E_NOT_SUPPORTED;
2704 if (lpMessageFilter)
2705 IMessageFilter_AddRef(lpMessageFilter);
2707 EnterCriticalSection(&apt->cs);
2709 lpOldMessageFilter = apt->filter;
2710 apt->filter = lpMessageFilter;
2712 LeaveCriticalSection(&apt->cs);
2714 if (lplpMessageFilter)
2715 *lplpMessageFilter = lpOldMessageFilter;
2716 else if (lpOldMessageFilter)
2717 IMessageFilter_Release(lpOldMessageFilter);
2719 return S_OK;
2722 /***********************************************************************
2723 * CoIsOle1Class [OLE32.@]
2725 * Determines whether the specified class an OLE v1 class.
2727 * PARAMS
2728 * clsid [I] Class to test.
2730 * RETURNS
2731 * TRUE if the class is an OLE v1 class, or FALSE otherwise.
2733 BOOL WINAPI CoIsOle1Class(REFCLSID clsid)
2735 FIXME("%s\n", debugstr_guid(clsid));
2736 return FALSE;
2739 /***********************************************************************
2740 * IsEqualGUID [OLE32.@]
2742 * Compares two Unique Identifiers.
2744 * PARAMS
2745 * rguid1 [I] The first GUID to compare.
2746 * rguid2 [I] The other GUID to compare.
2748 * RETURNS
2749 * TRUE if equal
2751 #undef IsEqualGUID
2752 BOOL WINAPI IsEqualGUID(
2753 REFGUID rguid1,
2754 REFGUID rguid2)
2756 return !memcmp(rguid1,rguid2,sizeof(GUID));
2759 /***********************************************************************
2760 * CoInitializeSecurity [OLE32.@]
2762 HRESULT WINAPI CoInitializeSecurity(PSECURITY_DESCRIPTOR pSecDesc, LONG cAuthSvc,
2763 SOLE_AUTHENTICATION_SERVICE* asAuthSvc,
2764 void* pReserved1, DWORD dwAuthnLevel,
2765 DWORD dwImpLevel, void* pReserved2,
2766 DWORD dwCapabilities, void* pReserved3)
2768 FIXME("(%p,%d,%p,%p,%d,%d,%p,%d,%p) - stub!\n", pSecDesc, cAuthSvc,
2769 asAuthSvc, pReserved1, dwAuthnLevel, dwImpLevel, pReserved2,
2770 dwCapabilities, pReserved3);
2771 return S_OK;
2774 /***********************************************************************
2775 * CoSuspendClassObjects [OLE32.@]
2777 * Suspends all registered class objects to prevent further requests coming in
2778 * for those objects.
2780 * RETURNS
2781 * Success: S_OK.
2782 * Failure: HRESULT code.
2784 HRESULT WINAPI CoSuspendClassObjects(void)
2786 FIXME("\n");
2787 return S_OK;
2790 /***********************************************************************
2791 * CoAddRefServerProcess [OLE32.@]
2793 * Helper function for incrementing the reference count of a local-server
2794 * process.
2796 * RETURNS
2797 * New reference count.
2799 ULONG WINAPI CoAddRefServerProcess(void)
2801 FIXME("\n");
2802 return 2;
2805 /***********************************************************************
2806 * CoReleaseServerProcess [OLE32.@]
2808 * Helper function for decrementing the reference count of a local-server
2809 * process.
2811 * RETURNS
2812 * New reference count.
2814 ULONG WINAPI CoReleaseServerProcess(void)
2816 FIXME("\n");
2817 return 1;
2820 /***********************************************************************
2821 * CoIsHandlerConnected [OLE32.@]
2823 * Determines whether a proxy is connected to a remote stub.
2825 * PARAMS
2826 * pUnk [I] Pointer to object that may or may not be connected.
2828 * RETURNS
2829 * TRUE if pUnk is not a proxy or if pUnk is connected to a remote stub, or
2830 * FALSE otherwise.
2832 BOOL WINAPI CoIsHandlerConnected(IUnknown *pUnk)
2834 FIXME("%p\n", pUnk);
2836 return TRUE;
2839 /***********************************************************************
2840 * CoAllowSetForegroundWindow [OLE32.@]
2843 HRESULT WINAPI CoAllowSetForegroundWindow(IUnknown *pUnk, void *pvReserved)
2845 FIXME("(%p, %p): stub\n", pUnk, pvReserved);
2846 return S_OK;
2849 /***********************************************************************
2850 * CoQueryProxyBlanket [OLE32.@]
2852 * Retrieves the security settings being used by a proxy.
2854 * PARAMS
2855 * pProxy [I] Pointer to the proxy object.
2856 * pAuthnSvc [O] The type of authentication service.
2857 * pAuthzSvc [O] The type of authorization service.
2858 * ppServerPrincName [O] Optional. The server prinicple name.
2859 * pAuthnLevel [O] The authentication level.
2860 * pImpLevel [O] The impersonation level.
2861 * ppAuthInfo [O] Information specific to the authorization/authentication service.
2862 * pCapabilities [O] Flags affecting the security behaviour.
2864 * RETURNS
2865 * Success: S_OK.
2866 * Failure: HRESULT code.
2868 * SEE ALSO
2869 * CoCopyProxy, CoSetProxyBlanket.
2871 HRESULT WINAPI CoQueryProxyBlanket(IUnknown *pProxy, DWORD *pAuthnSvc,
2872 DWORD *pAuthzSvc, OLECHAR **ppServerPrincName, DWORD *pAuthnLevel,
2873 DWORD *pImpLevel, void **ppAuthInfo, DWORD *pCapabilities)
2875 IClientSecurity *pCliSec;
2876 HRESULT hr;
2878 TRACE("%p\n", pProxy);
2880 hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
2881 if (SUCCEEDED(hr))
2883 hr = IClientSecurity_QueryBlanket(pCliSec, pProxy, pAuthnSvc,
2884 pAuthzSvc, ppServerPrincName,
2885 pAuthnLevel, pImpLevel, ppAuthInfo,
2886 pCapabilities);
2887 IClientSecurity_Release(pCliSec);
2890 if (FAILED(hr)) ERR("-- failed with 0x%08x\n", hr);
2891 return hr;
2894 /***********************************************************************
2895 * CoSetProxyBlanket [OLE32.@]
2897 * Sets the security settings for a proxy.
2899 * PARAMS
2900 * pProxy [I] Pointer to the proxy object.
2901 * AuthnSvc [I] The type of authentication service.
2902 * AuthzSvc [I] The type of authorization service.
2903 * pServerPrincName [I] The server prinicple name.
2904 * AuthnLevel [I] The authentication level.
2905 * ImpLevel [I] The impersonation level.
2906 * pAuthInfo [I] Information specific to the authorization/authentication service.
2907 * Capabilities [I] Flags affecting the security behaviour.
2909 * RETURNS
2910 * Success: S_OK.
2911 * Failure: HRESULT code.
2913 * SEE ALSO
2914 * CoQueryProxyBlanket, CoCopyProxy.
2916 HRESULT WINAPI CoSetProxyBlanket(IUnknown *pProxy, DWORD AuthnSvc,
2917 DWORD AuthzSvc, OLECHAR *pServerPrincName, DWORD AuthnLevel,
2918 DWORD ImpLevel, void *pAuthInfo, DWORD Capabilities)
2920 IClientSecurity *pCliSec;
2921 HRESULT hr;
2923 TRACE("%p\n", pProxy);
2925 hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
2926 if (SUCCEEDED(hr))
2928 hr = IClientSecurity_SetBlanket(pCliSec, pProxy, AuthnSvc,
2929 AuthzSvc, pServerPrincName,
2930 AuthnLevel, ImpLevel, pAuthInfo,
2931 Capabilities);
2932 IClientSecurity_Release(pCliSec);
2935 if (FAILED(hr)) ERR("-- failed with 0x%08x\n", hr);
2936 return hr;
2939 /***********************************************************************
2940 * CoCopyProxy [OLE32.@]
2942 * Copies a proxy.
2944 * PARAMS
2945 * pProxy [I] Pointer to the proxy object.
2946 * ppCopy [O] Copy of the proxy.
2948 * RETURNS
2949 * Success: S_OK.
2950 * Failure: HRESULT code.
2952 * SEE ALSO
2953 * CoQueryProxyBlanket, CoSetProxyBlanket.
2955 HRESULT WINAPI CoCopyProxy(IUnknown *pProxy, IUnknown **ppCopy)
2957 IClientSecurity *pCliSec;
2958 HRESULT hr;
2960 TRACE("%p\n", pProxy);
2962 hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
2963 if (SUCCEEDED(hr))
2965 hr = IClientSecurity_CopyProxy(pCliSec, pProxy, ppCopy);
2966 IClientSecurity_Release(pCliSec);
2969 if (FAILED(hr)) ERR("-- failed with 0x%08x\n", hr);
2970 return hr;
2974 /***********************************************************************
2975 * CoGetCallContext [OLE32.@]
2977 * Gets the context of the currently executing server call in the current
2978 * thread.
2980 * PARAMS
2981 * riid [I] Context interface to return.
2982 * ppv [O] Pointer to memory that will receive the context on return.
2984 * RETURNS
2985 * Success: S_OK.
2986 * Failure: HRESULT code.
2988 HRESULT WINAPI CoGetCallContext(REFIID riid, void **ppv)
2990 FIXME("(%s, %p): stub\n", debugstr_guid(riid), ppv);
2992 *ppv = NULL;
2993 return E_NOINTERFACE;
2996 /***********************************************************************
2997 * CoQueryClientBlanket [OLE32.@]
2999 * Retrieves the authentication information about the client of the currently
3000 * executing server call in the current thread.
3002 * PARAMS
3003 * pAuthnSvc [O] Optional. The type of authentication service.
3004 * pAuthzSvc [O] Optional. The type of authorization service.
3005 * pServerPrincName [O] Optional. The server prinicple name.
3006 * pAuthnLevel [O] Optional. The authentication level.
3007 * pImpLevel [O] Optional. The impersonation level.
3008 * pPrivs [O] Optional. Information about the privileges of the client.
3009 * pCapabilities [IO] Optional. Flags affecting the security behaviour.
3011 * RETURNS
3012 * Success: S_OK.
3013 * Failure: HRESULT code.
3015 * SEE ALSO
3016 * CoImpersonateClient, CoRevertToSelf, CoGetCallContext.
3018 HRESULT WINAPI CoQueryClientBlanket(
3019 DWORD *pAuthnSvc,
3020 DWORD *pAuthzSvc,
3021 OLECHAR **pServerPrincName,
3022 DWORD *pAuthnLevel,
3023 DWORD *pImpLevel,
3024 RPC_AUTHZ_HANDLE *pPrivs,
3025 DWORD *pCapabilities)
3027 IServerSecurity *pSrvSec;
3028 HRESULT hr;
3030 TRACE("(%p, %p, %p, %p, %p, %p, %p)\n",
3031 pAuthnSvc, pAuthzSvc, pServerPrincName, pAuthnLevel, pImpLevel,
3032 pPrivs, pCapabilities);
3034 hr = CoGetCallContext(&IID_IServerSecurity, (void **)&pSrvSec);
3035 if (SUCCEEDED(hr))
3037 hr = IServerSecurity_QueryBlanket(
3038 pSrvSec, pAuthnSvc, pAuthzSvc, pServerPrincName, pAuthnLevel,
3039 pImpLevel, pPrivs, pCapabilities);
3040 IServerSecurity_Release(pSrvSec);
3043 return hr;
3046 /***********************************************************************
3047 * CoImpersonateClient [OLE32.@]
3049 * Impersonates the client of the currently executing server call in the
3050 * current thread.
3052 * PARAMS
3053 * None.
3055 * RETURNS
3056 * Success: S_OK.
3057 * Failure: HRESULT code.
3059 * NOTES
3060 * If this function fails then the current thread will not be impersonating
3061 * the client and all actions will take place on behalf of the server.
3062 * Therefore, it is important to check the return value from this function.
3064 * SEE ALSO
3065 * CoRevertToSelf, CoQueryClientBlanket, CoGetCallContext.
3067 HRESULT WINAPI CoImpersonateClient(void)
3069 IServerSecurity *pSrvSec;
3070 HRESULT hr;
3072 TRACE("\n");
3074 hr = CoGetCallContext(&IID_IServerSecurity, (void **)&pSrvSec);
3075 if (SUCCEEDED(hr))
3077 hr = IServerSecurity_ImpersonateClient(pSrvSec);
3078 IServerSecurity_Release(pSrvSec);
3081 return hr;
3084 /***********************************************************************
3085 * CoRevertToSelf [OLE32.@]
3087 * Ends the impersonation of the client of the currently executing server
3088 * call in the current thread.
3090 * PARAMS
3091 * None.
3093 * RETURNS
3094 * Success: S_OK.
3095 * Failure: HRESULT code.
3097 * SEE ALSO
3098 * CoImpersonateClient, CoQueryClientBlanket, CoGetCallContext.
3100 HRESULT WINAPI CoRevertToSelf(void)
3102 IServerSecurity *pSrvSec;
3103 HRESULT hr;
3105 TRACE("\n");
3107 hr = CoGetCallContext(&IID_IServerSecurity, (void **)&pSrvSec);
3108 if (SUCCEEDED(hr))
3110 hr = IServerSecurity_RevertToSelf(pSrvSec);
3111 IServerSecurity_Release(pSrvSec);
3114 return hr;
3117 static BOOL COM_PeekMessage(struct apartment *apt, MSG *msg)
3119 /* first try to retrieve messages for incoming COM calls to the apartment window */
3120 return PeekMessageW(msg, apt->win, WM_USER, WM_APP - 1, PM_REMOVE|PM_NOYIELD) ||
3121 /* next retrieve other messages necessary for the app to remain responsive */
3122 PeekMessageW(msg, NULL, 0, WM_USER - 1, PM_REMOVE|PM_NOYIELD);
3125 /***********************************************************************
3126 * CoWaitForMultipleHandles [OLE32.@]
3128 * Waits for one or more handles to become signaled.
3130 * PARAMS
3131 * dwFlags [I] Flags. See notes.
3132 * dwTimeout [I] Timeout in milliseconds.
3133 * cHandles [I] Number of handles pointed to by pHandles.
3134 * pHandles [I] Handles to wait for.
3135 * lpdwindex [O] Index of handle that was signaled.
3137 * RETURNS
3138 * Success: S_OK.
3139 * Failure: RPC_S_CALLPENDING on timeout.
3141 * NOTES
3143 * The dwFlags parameter can be zero or more of the following:
3144 *| COWAIT_WAITALL - Wait for all of the handles to become signaled.
3145 *| COWAIT_ALERTABLE - Allows a queued APC to run during the wait.
3147 * SEE ALSO
3148 * MsgWaitForMultipleObjects, WaitForMultipleObjects.
3150 HRESULT WINAPI CoWaitForMultipleHandles(DWORD dwFlags, DWORD dwTimeout,
3151 ULONG cHandles, const HANDLE* pHandles, LPDWORD lpdwindex)
3153 HRESULT hr = S_OK;
3154 DWORD start_time = GetTickCount();
3155 APARTMENT *apt = COM_CurrentApt();
3156 BOOL message_loop = apt && !apt->multi_threaded;
3158 TRACE("(0x%08x, 0x%08x, %d, %p, %p)\n", dwFlags, dwTimeout, cHandles,
3159 pHandles, lpdwindex);
3161 while (TRUE)
3163 DWORD now = GetTickCount();
3164 DWORD res;
3166 if ((dwTimeout != INFINITE) && (start_time + dwTimeout >= now))
3168 hr = RPC_S_CALLPENDING;
3169 break;
3172 if (message_loop)
3174 DWORD wait_flags = (dwFlags & COWAIT_WAITALL) ? MWMO_WAITALL : 0 |
3175 (dwFlags & COWAIT_ALERTABLE ) ? MWMO_ALERTABLE : 0;
3177 TRACE("waiting for rpc completion or window message\n");
3179 res = MsgWaitForMultipleObjectsEx(cHandles, pHandles,
3180 (dwTimeout == INFINITE) ? INFINITE : start_time + dwTimeout - now,
3181 QS_ALLINPUT, wait_flags);
3183 if (res == WAIT_OBJECT_0 + cHandles) /* messages available */
3185 MSG msg;
3187 /* call message filter */
3189 if (COM_CurrentApt()->filter)
3191 PENDINGTYPE pendingtype =
3192 COM_CurrentInfo()->pending_call_count_server ?
3193 PENDINGTYPE_NESTED : PENDINGTYPE_TOPLEVEL;
3194 DWORD be_handled = IMessageFilter_MessagePending(
3195 COM_CurrentApt()->filter, 0 /* FIXME */,
3196 now - start_time, pendingtype);
3197 TRACE("IMessageFilter_MessagePending returned %d\n", be_handled);
3198 switch (be_handled)
3200 case PENDINGMSG_CANCELCALL:
3201 WARN("call canceled\n");
3202 hr = RPC_E_CALL_CANCELED;
3203 break;
3204 case PENDINGMSG_WAITNOPROCESS:
3205 case PENDINGMSG_WAITDEFPROCESS:
3206 default:
3207 /* FIXME: MSDN is very vague about the difference
3208 * between WAITNOPROCESS and WAITDEFPROCESS - there
3209 * appears to be none, so it is possibly a left-over
3210 * from the 16-bit world. */
3211 break;
3215 /* note: using "if" here instead of "while" might seem less
3216 * efficient, but only if we are optimising for quick delivery
3217 * of pending messages, rather than quick completion of the
3218 * COM call */
3219 if (COM_PeekMessage(apt, &msg))
3221 TRACE("received message whilst waiting for RPC: 0x%04x\n", msg.message);
3222 TranslateMessage(&msg);
3223 DispatchMessageW(&msg);
3224 if (msg.message == WM_QUIT)
3226 TRACE("resending WM_QUIT to outer message loop\n");
3227 PostQuitMessage(msg.wParam);
3228 /* no longer need to process messages */
3229 message_loop = FALSE;
3232 continue;
3235 else
3237 TRACE("waiting for rpc completion\n");
3239 res = WaitForMultipleObjectsEx(cHandles, pHandles,
3240 (dwFlags & COWAIT_WAITALL) ? TRUE : FALSE,
3241 (dwTimeout == INFINITE) ? INFINITE : start_time + dwTimeout - now,
3242 (dwFlags & COWAIT_ALERTABLE) ? TRUE : FALSE);
3245 if ((res >= WAIT_OBJECT_0) && (res < WAIT_OBJECT_0 + cHandles))
3247 /* handle signaled, store index */
3248 *lpdwindex = (res - WAIT_OBJECT_0);
3249 break;
3251 else if (res == WAIT_TIMEOUT)
3253 hr = RPC_S_CALLPENDING;
3254 break;
3256 else
3258 ERR("Unexpected wait termination: %d, %d\n", res, GetLastError());
3259 hr = E_UNEXPECTED;
3260 break;
3263 TRACE("-- 0x%08x\n", hr);
3264 return hr;
3268 /***********************************************************************
3269 * CoGetObject [OLE32.@]
3271 * Gets the object named by coverting the name to a moniker and binding to it.
3273 * PARAMS
3274 * pszName [I] String representing the object.
3275 * pBindOptions [I] Parameters affecting the binding to the named object.
3276 * riid [I] Interface to bind to on the objecct.
3277 * ppv [O] On output, the interface riid of the object represented
3278 * by pszName.
3280 * RETURNS
3281 * Success: S_OK.
3282 * Failure: HRESULT code.
3284 * SEE ALSO
3285 * MkParseDisplayName.
3287 HRESULT WINAPI CoGetObject(LPCWSTR pszName, BIND_OPTS *pBindOptions,
3288 REFIID riid, void **ppv)
3290 IBindCtx *pbc;
3291 HRESULT hr;
3293 *ppv = NULL;
3295 hr = CreateBindCtx(0, &pbc);
3296 if (SUCCEEDED(hr))
3298 if (pBindOptions)
3299 hr = IBindCtx_SetBindOptions(pbc, pBindOptions);
3301 if (SUCCEEDED(hr))
3303 ULONG chEaten;
3304 IMoniker *pmk;
3306 hr = MkParseDisplayName(pbc, pszName, &chEaten, &pmk);
3307 if (SUCCEEDED(hr))
3309 hr = IMoniker_BindToObject(pmk, pbc, NULL, riid, ppv);
3310 IMoniker_Release(pmk);
3314 IBindCtx_Release(pbc);
3316 return hr;
3319 /***********************************************************************
3320 * CoRegisterChannelHook [OLE32.@]
3322 * Registers a process-wide hook that is called during ORPC calls.
3324 * PARAMS
3325 * guidExtension [I] GUID of the channel hook to register.
3326 * pChannelHook [I] Channel hook object to register.
3328 * RETURNS
3329 * Success: S_OK.
3330 * Failure: HRESULT code.
3332 HRESULT WINAPI CoRegisterChannelHook(REFGUID guidExtension, IChannelHook *pChannelHook)
3334 TRACE("(%s, %p)\n", debugstr_guid(guidExtension), pChannelHook);
3336 return RPC_RegisterChannelHook(guidExtension, pChannelHook);
3339 /***********************************************************************
3340 * DllMain (OLE32.@)
3342 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID fImpLoad)
3344 TRACE("%p 0x%x %p\n", hinstDLL, fdwReason, fImpLoad);
3346 switch(fdwReason) {
3347 case DLL_PROCESS_ATTACH:
3348 OLE32_hInstance = hinstDLL;
3349 COMPOBJ_InitProcess();
3350 if (TRACE_ON(ole)) CoRegisterMallocSpy((LPVOID)-1);
3351 break;
3353 case DLL_PROCESS_DETACH:
3354 if (TRACE_ON(ole)) CoRevokeMallocSpy();
3355 COMPOBJ_UninitProcess();
3356 RPC_UnregisterAllChannelHooks();
3357 OLE32_hInstance = 0;
3358 break;
3360 case DLL_THREAD_DETACH:
3361 COM_TlsDestroy();
3362 break;
3364 return TRUE;
3367 /* NOTE: DllRegisterServer and DllUnregisterServer are in regsvr.c */