4 * Copyright 1995 Martin von Loewis
5 * Copyright 1998 Justin Bradford
6 * Copyright 1999 Francis Beaudet
7 * Copyright 1999 Sylvain St-Germain
8 * Copyright 2002 Marcus Meissner
9 * Copyright 2004 Mike Hearn
10 * Copyright 2005-2006 Robert Shearman (for CodeWeavers)
12 * This library is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Lesser General Public
14 * License as published by the Free Software Foundation; either
15 * version 2.1 of the License, or (at your option) any later version.
17 * This library is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * Lesser General Public License for more details.
22 * You should have received a copy of the GNU Lesser General Public
23 * License along with this library; if not, write to the Free Software
24 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
27 * 1. COINIT_MULTITHREADED is 0; it is the lack of COINIT_APARTMENTTHREADED
28 * Therefore do not test against COINIT_MULTITHREADED
30 * TODO list: (items bunched together depend on each other)
32 * - Implement the service control manager (in rpcss) to keep track
33 * of registered class objects: ISCM::ServerRegisterClsid et al
34 * - Implement the OXID resolver so we don't need magic endpoint names for
35 * clients and servers to meet up
37 * - Make all ole interface marshaling use NDR to be wire compatible with
50 #define NONAMELESSUNION
51 #define NONAMELESSSTRUCT
62 #include "compobj_private.h"
64 #include "wine/unicode.h"
65 #include "wine/debug.h"
67 WINE_DEFAULT_DEBUG_CHANNEL(ole);
69 HINSTANCE OLE32_hInstance = 0; /* FIXME: make static ... */
71 #define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))
73 /****************************************************************************
74 * This section defines variables internal to the COM module.
76 * TODO: Most of these things will have to be made thread-safe.
79 static HRESULT COM_GetRegisteredClassObject(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 =
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
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
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;
125 LPSTREAM pMarshaledData; /* FIXME: only really need to store OXID and IPID */
126 struct tagRegisteredClass* nextClass;
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 {
153 struct tagOpenDll *next;
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 )
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
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;
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 /******************************************************************************
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)
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);
232 apt->remunk_exported = FALSE;
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;
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);
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();
266 if (model & COINIT_APARTMENTTHREADED)
268 EnterCriticalSection(&csApartment);
270 apt = apartment_construct(model);
275 TRACE("Created main-threaded apartment with OXID %s\n", wine_dbgstr_longlong(apt->oxid));
278 LeaveCriticalSection(&csApartment);
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
289 TRACE("entering the multithreaded apartment %s\n", wine_dbgstr_longlong(MTA->oxid));
290 apartment_addref(MTA);
293 MTA = apartment_construct(model);
297 LeaveCriticalSection(&csApartment);
299 COM_CurrentInfo()->apt = 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);
317 DWORD apartment_release(struct apartment *apt)
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 */
328 if (apt == MTA) MTA = NULL;
329 else if (apt == MainApartment) MainApartment = NULL;
330 list_remove(&apt->entry);
333 LeaveCriticalSection(&csApartment);
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(®istered_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);
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;
394 EnterCriticalSection(&csApartment);
395 LIST_FOR_EACH( cursor, &apts )
397 struct apartment *apt = LIST_ENTRY( cursor, struct apartment, entry );
398 if (apt->oxid == oxid)
401 if (ref) apartment_addref(result);
405 LeaveCriticalSection(&csApartment);
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;
418 EnterCriticalSection(&csApartment);
419 LIST_FOR_EACH( cursor, &apts )
421 struct apartment *apt = LIST_ENTRY( cursor, struct apartment, entry );
425 apartment_addref(result);
429 LeaveCriticalSection(&csApartment);
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);
452 LIST_FOR_EACH_ENTRY( apt, &apts, struct apartment, entry )
454 if (apt->multi_threaded == multi_threaded)
457 apartment_addref(result);
461 LeaveCriticalSection(&csApartment);
466 struct host_object_params
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)
478 static const LARGE_INTEGER llZero;
482 hr = get_inproc_class_object(params->hkeydll, ¶ms->clsid, ¶ms->iid, (void **)&object);
486 hr = CoMarshalInterface(params->stream, ¶ms->iid, object, MSHCTX_INPROC, NULL, MSHLFLAGS_NORMAL);
488 IUnknown_Release(object);
489 IStream_Seek(params->stream, llZero, STREAM_SEEK_SET, NULL);
494 static LRESULT CALLBACK apartment_wndproc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
499 RPC_ExecuteCall((struct dispatch_params *)lParam);
502 return apartment_hostobject((const struct host_object_params *)lParam);
504 return DefWindowProcW(hWnd, msg, wParam, lParam);
508 HRESULT apartment_createwindowifneeded(struct apartment *apt)
510 if (apt->multi_threaded)
515 HWND hwnd = CreateWindowW(wszAptWinClass, NULL, 0,
517 0, 0, OLE32_hInstance, NULL);
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 */
531 HWND apartment_getwindow(struct apartment *apt)
533 assert(!apt->multi_threaded);
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)
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;
562 /* search for this dll */
564 for (ptr = openDllList; ptr->next != NULL; ptr=ptr->next) {
565 if (ptr->hLibrary == hLibrary) {
571 /* dll not found, add it */
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;
590 EnterCriticalSection( &csOpenDllList );
592 for (curr = openDllList; curr != NULL; ) {
593 DllCanUnloadNow = (DllCanUnloadNowFunc) GetProcAddress(curr->hLibrary, "DllCanUnloadNow");
595 if ( (DllCanUnloadNow != NULL) && (DllCanUnloadNow() == S_OK) ) {
598 TRACE("freeing %p\n", curr->hLibrary);
599 FreeLibrary(curr->hLibrary);
601 HeapFree(GetProcessHeap(), 0, curr);
602 if (curr == openDllList) {
615 LeaveCriticalSection( &csOpenDllList );
618 /******************************************************************************
619 * CoBuildVersion [OLE32.@]
620 * CoBuildVersion [COMPOBJ.1]
622 * Gets the build version of the DLL.
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.
642 * lpReserved [I] Pointer to IMalloc interface (obsolete, should be NULL).
645 * Success: S_OK if not already initialized, S_FALSE otherwise.
646 * Failure: HRESULT code.
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.
665 * lpReserved [I] Pointer to IMalloc interface (obsolete, should be NULL).
666 * dwCoInit [I] One or more flags from the COINIT enumeration. See notes.
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
676 * The behavior used to set the IMalloc used for memory management is
678 * The dwCoInit parameter must specify one of the following apartment
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.
689 HRESULT WINAPI CoInitializeEx(LPVOID lpReserved, DWORD dwCoInit)
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;
735 COM_CurrentInfo()->inits++;
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)
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);
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.
781 void WINAPI CoUninitialize(void)
783 struct oletls * info = COM_CurrentInfo();
788 /* will only happen on OOM */
794 ERR("Mismatched CoUninitialize\n");
800 apartment_release(info->apt);
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);
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
843 * lpUnk [I] The object whose stub should be disconnected.
844 * reserved [I] Reserved. Should be set to 0.
848 * Failure: HRESULT code.
851 * CoMarshalInterface, CoReleaseMarshalData, CoLockObjectExternal
853 HRESULT WINAPI CoDisconnectObject( LPUNKNOWN lpUnk, DWORD reserved )
859 TRACE("(%p, 0x%08x)\n", lpUnk, reserved);
861 hr = IUnknown_QueryInterface(lpUnk, &IID_IMarshal, (void **)&marshal);
864 hr = IMarshal_DisconnectObject(marshal, reserved);
865 IMarshal_Release(marshal);
869 apt = COM_CurrentApt();
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 */
883 /******************************************************************************
884 * CoCreateGuid [OLE32.@]
886 * Simply forwards to UuidCreate in RPCRT4.
889 * pguid [O] Points to the GUID to initialize.
893 * Failure: HRESULT code.
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
911 * idstr [I] The string representation of the GUID.
912 * id [O] GUID converted from the string.
916 * CO_E_CLASSSTRING if idstr is not a valid CLSID
921 static HRESULT WINAPI __CLSIDFromString(LPCWSTR s, CLSID *id)
927 memset( id, 0, sizeof (CLSID) );
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++) {
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]];
979 /*****************************************************************************/
981 HRESULT WINAPI CLSIDFromString(LPOLESTR idstr, CLSID *id )
988 ret = __CLSIDFromString(idstr, id);
989 if(ret != S_OK) { /* It appears a ProgID is also valid */
990 ret = CLSIDFromProgID(idstr, id);
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";
1005 { ERR("called with id=Null\n");
1010 sprintf(idstr, "{%08X-%04X-%04X-%02X%02X-",
1011 id->Data1, id->Data2, id->Data3,
1012 id->Data4[0], id->Data4[1]);
1016 for (i = 2; i < 8; i++) {
1017 *s++ = hex[id->Data4[i]>>4];
1018 *s++ = hex[id->Data4[i] & 0xf];
1024 TRACE("%p->%s\n", id, idstr);
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.
1038 * id [I] the GUID to be converted.
1039 * idstr [O] A pointer to a to-be-allocated pointer pointing to the resulting string.
1046 * StringFromGUID2, CLSIDFromString
1048 HRESULT WINAPI StringFromCLSID(REFCLSID id, LPOLESTR *idstr)
1054 if ((ret = CoGetMalloc(0,&mllc)))
1057 ret=WINE_StringFromCLSID(id,buf);
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 );
1066 /******************************************************************************
1067 * StringFromGUID2 [OLE32.@]
1068 * StringFromGUID2 [COMPOBJ.76]
1070 * Modified version of StringFromCLSID that allows you to specify max
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.
1079 * Success: The length of the resulting string in characters.
1082 INT WINAPI StringFromGUID2(REFGUID id, LPOLESTR str, INT cmax)
1086 if (WINE_StringFromCLSID(id,xguid))
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];
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;
1113 res = RegOpenKeyExW(key, keyname, 0, access, subkey);
1115 if (res == ERROR_FILE_NOT_FOUND)
1116 return REGDB_E_KEYMISSING;
1117 else if (res != ERROR_SUCCESS)
1118 return REGDB_E_READREGDB;
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 };
1129 WCHAR buf[CHARS_IN_GUID];
1130 WCHAR keyname[ARRAYSIZE(szAppIdKey) + CHARS_IN_GUID];
1136 /* read the AppID value under the class's key */
1137 hr = COM_OpenKeyForCLSID(clsid, NULL, KEY_READ, &hkey);
1142 res = RegQueryValueExW(hkey, szAppId, NULL, &type, (LPBYTE)buf, &size);
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;
1160 /******************************************************************************
1161 * ProgIDFromCLSID [OLE32.@]
1163 * Converts a class id into the respective program ID.
1166 * clsid [I] Class ID, as found in registry.
1167 * ppszProgID [O] Associated ProgID.
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};
1183 ERR("ppszProgId isn't optional\n");
1184 return E_INVALIDARG;
1188 ret = COM_OpenKeyForCLSID(clsid, wszProgID, KEY_READ, &hkey);
1192 if (RegQueryValueW(hkey, NULL, NULL, &progidlen))
1193 ret = REGDB_E_CLASSNOTREG;
1197 *ppszProgID = CoTaskMemAlloc(progidlen * sizeof(WCHAR));
1200 if (RegQueryValueW(hkey, NULL, *ppszProgID, &progidlen))
1201 ret = REGDB_E_CLASSNOTREG;
1204 ret = E_OUTOFMEMORY;
1211 /******************************************************************************
1212 * CLSIDFromProgID [OLE32.@]
1214 * Converts a program id into the respective GUID.
1217 * progid [I] Unicode program ID, as found in registry.
1218 * clsid [O] Associated CLSID.
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);
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))
1254 return CO_E_CLASSSTRING;
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.
1268 * riid [I] Interface whose proxy/stub CLSID is to be returned.
1269 * pclsid [O] Where to store returned proxy/stub CLSID.
1274 * REGDB_E_IIDNOTREG if no PSFactoryBuffer is associated with the IID, or it could not be parsed
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
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.
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).
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];
1305 APARTMENT *apt = COM_CurrentApt();
1306 struct registered_psclsid *registered_psclsid;
1308 TRACE("() riid=%s, pclsid=%p\n", debugstr_guid(riid), pclsid);
1312 ERR("apartment not initialised\n");
1313 return CO_E_NOTINITIALIZED;
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(®istered_psclsid->iid, riid))
1327 *pclsid = registered_psclsid->clsid;
1328 LeaveCriticalSection(&apt->cs);
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))
1353 return REGDB_E_IIDNOTREG;
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));
1366 /*****************************************************************************
1367 * CoRegisterPSClsid [OLE32.@]
1369 * Register a proxy/stub CLSID for the given interface in the current process
1373 * riid [I] Interface whose proxy/stub CLSID is to be registered.
1374 * rclsid [I] CLSID of the proxy/stub.
1378 * Failure: E_OUTOFMEMORY
1382 * This function does not add anything to the registry and the effects are
1383 * limited to the lifetime of the current process.
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));
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(®istered_psclsid->iid, riid))
1406 registered_psclsid->clsid = *rclsid;
1407 LeaveCriticalSection(&apt->cs);
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, ®istered_psclsid->entry);
1422 LeaveCriticalSection(&apt->cs);
1429 * COM_GetRegisteredClassObject
1431 * This internal method is used to scan the registered class list to
1432 * find a class object.
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(
1446 HRESULT hr = S_FALSE;
1447 RegisteredClass* curClass;
1449 EnterCriticalSection( &csRegisteredClassList );
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
1474 * We have a match, return the pointer to the class object.
1476 *ppUnk = curClass->classObject;
1478 IUnknown_AddRef(curClass->classObject);
1485 * Step to the next class in the list.
1487 curClass = curClass->nextClass;
1491 LeaveCriticalSection( &csRegisteredClassList );
1493 * If we get to here, we haven't found our class.
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.
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.
1514 * E_INVALIDARG if lpdwRegister or pUnk are NULL,
1515 * CO_E_OBJISREG if the object is already registered. We should not return this.
1518 * CoRevokeClassObject, CoGetClassObject
1521 * MSDN claims that multiple interface registrations are legal, but we
1522 * can't do that with our current implementation.
1524 HRESULT WINAPI CoRegisterClassObject(
1529 LPDWORD lpdwRegister)
1531 RegisteredClass* newClass;
1532 LPUNKNOWN foundObject;
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;
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);
1555 if (flags & REGCLS_MULTIPLEUSE) {
1556 if (dwClsContext & CLSCTX_LOCAL_SERVER)
1557 hr = CoLockObjectExternal(foundObject, TRUE, FALSE);
1558 IUnknown_Release(foundObject);
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
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);
1603 hr = CreateStreamOnHGlobal(0, TRUE, &newClass->pMarshaledData);
1605 FIXME("Failed to create stream on hglobal, %x\n", hr);
1606 IUnknown_Release(classfac);
1609 hr = CoMarshalInterface(newClass->pMarshaledData, &IID_IClassFactory,
1610 (LPVOID)classfac, MSHCTX_LOCAL, NULL,
1611 MSHLFLAGS_TABLESTRONG);
1613 FIXME("CoMarshalInterface failed, %x!\n",hr);
1614 IUnknown_Release(classfac);
1618 IUnknown_Release(classfac);
1620 RPC_StartLocalServer(&newClass->classIdentifier, newClass->pMarshaledData);
1625 /***********************************************************************
1626 * CoRevokeClassObject [OLE32.@]
1628 * Removes a class object from the class registry.
1631 * dwRegister [I] Cookie returned from CoRegisterClassObject().
1635 * Failure: HRESULT code.
1638 * CoRegisterClassObject
1640 HRESULT WINAPI CoRevokeClassObject(
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)
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);
1693 * Step to the next class in the list.
1695 prevClassLink = &(curClass->nextClass);
1696 curClass = curClass->nextClass;
1700 LeaveCriticalSection( &csRegisteredClassList );
1702 * If we get to here, we haven't found our class.
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)
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;
1725 lstrcpynW(dst, src, dstlen);
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};
1738 DWORD dwLength = len * sizeof(WCHAR);
1740 ret = RegQueryValueExW(key, wszThreadingModel, NULL, &keytype, (LPBYTE)value, &dwLength);
1741 if ((ret != ERROR_SUCCESS) || (keytype != REG_SZ))
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};
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 */];
1757 get_threading_model(hkeydll, threading_model, ARRAYSIZE(threading_model));
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);
1767 FIXME("create a host apartment for apartment-threaded object %s\n", debugstr_guid(rclsid));
1770 struct host_object_params params;
1771 HWND hwnd = apartment_getwindow(host_apt);
1773 params.hkeydll = hkeydll;
1774 params.clsid = *rclsid;
1776 hr = CreateStreamOnHGlobal(NULL, TRUE, ¶ms.stream);
1779 hr = SendMessageW(hwnd, DM_HOSTOBJECT, 0, (LPARAM)¶ms);
1781 hr = CoUnmarshalInterface(params.stream, riid, ppv);
1782 IStream_Release(params.stream);
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);
1812 FIXME("create a host apartment for main-threaded object %s\n", debugstr_guid(rclsid));
1815 struct host_object_params params;
1816 HWND hwnd = apartment_getwindow(host_apt);
1818 params.hkeydll = hkeydll;
1819 params.clsid = *rclsid;
1821 hr = CreateStreamOnHGlobal(NULL, TRUE, ¶ms.stream);
1824 hr = SendMessageW(hwnd, DM_HOSTOBJECT, 0, (LPARAM)¶ms);
1826 hr = CoUnmarshalInterface(params.stream, riid, ppv);
1827 IStream_Release(params.stream);
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);
1860 ERR("DllGetClassObject returned error 0x%08x\n", 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));
1883 return E_INVALIDARG;
1887 if (!COM_CurrentApt())
1889 ERR("apartment not initialised\n");
1890 return CO_E_NOTINITIALIZED;
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, ®ClassObject))
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);
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};
1923 if (IsEqualCLSID(rclsid, &CLSID_InProcFreeMarshaler))
1924 return FTMarshalCF_Create(iid, ppv);
1926 hres = COM_OpenKeyForCLSID(rclsid, wszInprocServer32, KEY_READ, &hkey);
1929 if (hres == REGDB_E_CLASSNOTREG)
1930 ERR("class %s not registered\n", debugstr_guid(rclsid));
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);
1941 /* return if we got a class, otherwise fall through to one of the
1943 if (SUCCEEDED(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};
1953 hres = COM_OpenKeyForCLSID(rclsid, wszInprocHandler32, KEY_READ, &hkey);
1956 if (hres == REGDB_E_CLASSNOTREG)
1957 ERR("class %s not registered\n", debugstr_guid(rclsid));
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);
1968 /* return if we got a class, otherwise fall through to one of the
1970 if (SUCCEEDED(hres))
1974 /* Next try out of process */
1975 if (CLSCTX_LOCAL_SERVER & dwClsContext)
1977 hres = RPC_GetLocalClassObject(rclsid,iid,ppv);
1978 if (SUCCEEDED(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;
1990 ERR("no class object %s could be created for context 0x%x\n",
1991 debugstr_guid(rclsid), dwClsContext);
1995 /***********************************************************************
1996 * CoResumeClassObjects (OLE32.@)
1998 * Resumes all class objects registered with REGCLS_SUSPENDED.
2002 * Failure: HRESULT code.
2004 HRESULT WINAPI CoResumeClassObjects(void)
2010 /***********************************************************************
2011 * GetClassFile (OLE32.@)
2013 * This function supplies the CLSID associated with the given filename.
2015 HRESULT WINAPI GetClassFile(LPCOLESTR filePathName,CLSID *pclsid)
2019 int nbElm, length, i;
2021 LPOLESTR *pathDec=0,absFile=0,progId=0;
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);
2034 res=ReadClassStg(pstg,pclsid);
2036 IStorage_Release(pstg);
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
2044 for(i=0;i<nFileTypes;i++)
2046 for(i=0;j<nPatternsForType;j++){
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);
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 */
2075 length=lstrlenW(absFile);
2076 for(i = length-1; (i >= 0) && *(extension = &absFile[i]) != '.'; i--)
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)
2101 return MK_E_INVALIDEXTENSION;
2104 /***********************************************************************
2105 * CoCreateInstance [OLE32.@]
2107 * Creates an instance of the specified class.
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.
2118 * Failure: HRESULT code.
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.
2133 * CoGetClassObject()
2135 HRESULT WINAPI CoCreateInstance(
2137 LPUNKNOWN pUnkOuter,
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);
2155 * Initialize the "out" parameter
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);
2180 * Get a class factory to construct the object we want.
2182 hres = CoGetClassObject(rclsid,
2192 * Create the object and don't forget to release the factory
2194 hres = IClassFactory_CreateInstance(lpclf, pUnkOuter, iid, ppv);
2195 IClassFactory_Release(lpclf);
2197 FIXME("no instance created for interface %s of class %s, hres is 0x%08x\n",
2198 debugstr_guid(iid), debugstr_guid(rclsid),hres);
2203 /***********************************************************************
2204 * CoCreateInstanceEx [OLE32.@]
2206 HRESULT WINAPI CoCreateInstanceEx(
2208 LPUNKNOWN pUnkOuter,
2210 COSERVERINFO* pServerInfo,
2214 IUnknown* pUnk = NULL;
2217 ULONG successCount = 0;
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,
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)
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;
2276 /***********************************************************************
2277 * CoLoadLibrary (OLE32.@)
2282 * lpszLibName [I] Path to library.
2283 * bAutoFree [I] Whether the library should automatically be freed.
2286 * Success: Handle to loaded library.
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.
2305 * hLibrary [I] Handle to library to unload.
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.
2328 * CoLoadLibrary, CoFreeLibrary, CoFreeUnusedLibraries
2330 void WINAPI CoFreeAllLibraries(void)
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.
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.
2363 * lpFileTime [O] The current time.
2368 HRESULT WINAPI CoFileTimeNow( FILETIME *lpFileTime )
2370 GetSystemTimeAsFileTime( lpFileTime );
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.
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.
2400 * Failure: HRESULT code.
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(
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);
2425 stub_manager_ext_addref(stubmgr, 1);
2427 stub_manager_ext_release(stubmgr, 1, fLastUnlockReleases);
2429 stub_manager_int_release(stubmgr);
2435 stubmgr = new_stub_manager(apt, pUnk);
2439 stub_manager_ext_addref(stubmgr, 1);
2440 stub_manager_int_release(stubmgr);
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 */
2455 /***********************************************************************
2456 * CoInitializeWOW (OLE32.@)
2458 * WOW equivalent of CoInitialize?
2467 HRESULT WINAPI CoInitializeWOW(DWORD x,DWORD y)
2469 FIXME("(0x%08x,0x%08x),stub!\n",x,y);
2473 /***********************************************************************
2474 * CoGetState [OLE32.@]
2476 * Retrieves the thread state object previously stored by CoSetState().
2479 * ppv [I] Address where pointer to object will be stored.
2483 * Failure: E_OUTOFMEMORY.
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.
2493 HRESULT WINAPI CoGetState(IUnknown ** ppv)
2495 struct oletls *info = COM_CurrentInfo();
2496 if (!info) return E_OUTOFMEMORY;
2502 IUnknown_AddRef(info->state);
2504 TRACE("apt->state=%p\n", info->state);
2510 /***********************************************************************
2511 * CoSetState [OLE32.@]
2513 * Sets the thread state object.
2516 * pv [I] Pointer to state object to be stored.
2519 * The system keeps a reference on the object while the object stored.
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);
2534 TRACE("-- release %p now\n", info->state);
2535 IUnknown_Release(info->state);
2544 /******************************************************************************
2545 * CoTreatAsClass [OLE32.@]
2547 * Sets the TreatAs value of a class.
2550 * clsidOld [I] Class to set TreatAs value on.
2551 * clsidNew [I] The class the clsidOld should be treated as.
2555 * Failure: HRESULT code.
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};
2565 WCHAR szClsidNew[CHARS_IN_GUID];
2567 WCHAR auto_treat_as[CHARS_IN_GUID];
2568 LONG auto_treat_as_size = sizeof(auto_treat_as);
2571 res = COM_OpenKeyForCLSID(clsidOld, NULL, KEY_READ | KEY_WRITE, &hkey);
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;
2587 RegDeleteKeyW(hkey, wszTreatAs);
2591 else if (!StringFromGUID2(clsidNew, szClsidNew, ARRAYSIZE(szClsidNew)) &&
2592 !RegSetValueW(hkey, wszTreatAs, REG_SZ, szClsidNew, sizeof(szClsidNew)))
2594 res = REGDB_E_WRITEREGDB;
2599 if (hkey) RegCloseKey(hkey);
2603 /******************************************************************************
2604 * CoGetTreatAsClass [OLE32.@]
2606 * Gets the TreatAs value of a class.
2609 * clsidOld [I] Class to get the TreatAs value of.
2610 * clsidNew [I] The class the clsidOld should be treated as.
2614 * Failure: HRESULT code.
2619 HRESULT WINAPI CoGetTreatAsClass(REFCLSID clsidOld, LPCLSID clsidNew)
2621 static const WCHAR wszTreatAs[] = {'T','r','e','a','t','A','s',0};
2623 WCHAR szClsidNew[CHARS_IN_GUID];
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);
2633 if (RegQueryValueW(hkey, NULL, szClsidNew, &len))
2638 res = CLSIDFromString(szClsidNew,clsidNew);
2640 ERR("Failed CLSIDFromStringA(%s), hres 0x%08x\n", debugstr_w(szClsidNew), res);
2642 if (hkey) RegCloseKey(hkey);
2646 /******************************************************************************
2647 * CoGetCurrentProcess [OLE32.@]
2648 * CoGetCurrentProcess [COMPOBJ.34]
2650 * Gets the current process ID.
2653 * The current process ID.
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.
2669 * lpMessageFilter [I] Pointer to interface.
2670 * lplpMessageFilter [O] Indirect pointer to prior instance if non-NULL.
2674 * Failure: HRESULT code.
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);
2722 /***********************************************************************
2723 * CoIsOle1Class [OLE32.@]
2725 * Determines whether the specified class an OLE v1 class.
2728 * clsid [I] Class to test.
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));
2739 /***********************************************************************
2740 * IsEqualGUID [OLE32.@]
2742 * Compares two Unique Identifiers.
2745 * rguid1 [I] The first GUID to compare.
2746 * rguid2 [I] The other GUID to compare.
2752 BOOL WINAPI IsEqualGUID(
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);
2774 /***********************************************************************
2775 * CoSuspendClassObjects [OLE32.@]
2777 * Suspends all registered class objects to prevent further requests coming in
2778 * for those objects.
2782 * Failure: HRESULT code.
2784 HRESULT WINAPI CoSuspendClassObjects(void)
2790 /***********************************************************************
2791 * CoAddRefServerProcess [OLE32.@]
2793 * Helper function for incrementing the reference count of a local-server
2797 * New reference count.
2799 ULONG WINAPI CoAddRefServerProcess(void)
2805 /***********************************************************************
2806 * CoReleaseServerProcess [OLE32.@]
2808 * Helper function for decrementing the reference count of a local-server
2812 * New reference count.
2814 ULONG WINAPI CoReleaseServerProcess(void)
2820 /***********************************************************************
2821 * CoIsHandlerConnected [OLE32.@]
2823 * Determines whether a proxy is connected to a remote stub.
2826 * pUnk [I] Pointer to object that may or may not be connected.
2829 * TRUE if pUnk is not a proxy or if pUnk is connected to a remote stub, or
2832 BOOL WINAPI CoIsHandlerConnected(IUnknown *pUnk)
2834 FIXME("%p\n", pUnk);
2839 /***********************************************************************
2840 * CoAllowSetForegroundWindow [OLE32.@]
2843 HRESULT WINAPI CoAllowSetForegroundWindow(IUnknown *pUnk, void *pvReserved)
2845 FIXME("(%p, %p): stub\n", pUnk, pvReserved);
2849 /***********************************************************************
2850 * CoQueryProxyBlanket [OLE32.@]
2852 * Retrieves the security settings being used by a proxy.
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.
2866 * Failure: HRESULT code.
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;
2878 TRACE("%p\n", pProxy);
2880 hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
2883 hr = IClientSecurity_QueryBlanket(pCliSec, pProxy, pAuthnSvc,
2884 pAuthzSvc, ppServerPrincName,
2885 pAuthnLevel, pImpLevel, ppAuthInfo,
2887 IClientSecurity_Release(pCliSec);
2890 if (FAILED(hr)) ERR("-- failed with 0x%08x\n", hr);
2894 /***********************************************************************
2895 * CoSetProxyBlanket [OLE32.@]
2897 * Sets the security settings for a proxy.
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.
2911 * Failure: HRESULT code.
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;
2923 TRACE("%p\n", pProxy);
2925 hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
2928 hr = IClientSecurity_SetBlanket(pCliSec, pProxy, AuthnSvc,
2929 AuthzSvc, pServerPrincName,
2930 AuthnLevel, ImpLevel, pAuthInfo,
2932 IClientSecurity_Release(pCliSec);
2935 if (FAILED(hr)) ERR("-- failed with 0x%08x\n", hr);
2939 /***********************************************************************
2940 * CoCopyProxy [OLE32.@]
2945 * pProxy [I] Pointer to the proxy object.
2946 * ppCopy [O] Copy of the proxy.
2950 * Failure: HRESULT code.
2953 * CoQueryProxyBlanket, CoSetProxyBlanket.
2955 HRESULT WINAPI CoCopyProxy(IUnknown *pProxy, IUnknown **ppCopy)
2957 IClientSecurity *pCliSec;
2960 TRACE("%p\n", pProxy);
2962 hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
2965 hr = IClientSecurity_CopyProxy(pCliSec, pProxy, ppCopy);
2966 IClientSecurity_Release(pCliSec);
2969 if (FAILED(hr)) ERR("-- failed with 0x%08x\n", hr);
2974 /***********************************************************************
2975 * CoGetCallContext [OLE32.@]
2977 * Gets the context of the currently executing server call in the current
2981 * riid [I] Context interface to return.
2982 * ppv [O] Pointer to memory that will receive the context on return.
2986 * Failure: HRESULT code.
2988 HRESULT WINAPI CoGetCallContext(REFIID riid, void **ppv)
2990 FIXME("(%s, %p): stub\n", debugstr_guid(riid), ppv);
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.
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.
3013 * Failure: HRESULT code.
3016 * CoImpersonateClient, CoRevertToSelf, CoGetCallContext.
3018 HRESULT WINAPI CoQueryClientBlanket(
3021 OLECHAR **pServerPrincName,
3024 RPC_AUTHZ_HANDLE *pPrivs,
3025 DWORD *pCapabilities)
3027 IServerSecurity *pSrvSec;
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);
3037 hr = IServerSecurity_QueryBlanket(
3038 pSrvSec, pAuthnSvc, pAuthzSvc, pServerPrincName, pAuthnLevel,
3039 pImpLevel, pPrivs, pCapabilities);
3040 IServerSecurity_Release(pSrvSec);
3046 /***********************************************************************
3047 * CoImpersonateClient [OLE32.@]
3049 * Impersonates the client of the currently executing server call in the
3057 * Failure: HRESULT code.
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.
3065 * CoRevertToSelf, CoQueryClientBlanket, CoGetCallContext.
3067 HRESULT WINAPI CoImpersonateClient(void)
3069 IServerSecurity *pSrvSec;
3074 hr = CoGetCallContext(&IID_IServerSecurity, (void **)&pSrvSec);
3077 hr = IServerSecurity_ImpersonateClient(pSrvSec);
3078 IServerSecurity_Release(pSrvSec);
3084 /***********************************************************************
3085 * CoRevertToSelf [OLE32.@]
3087 * Ends the impersonation of the client of the currently executing server
3088 * call in the current thread.
3095 * Failure: HRESULT code.
3098 * CoImpersonateClient, CoQueryClientBlanket, CoGetCallContext.
3100 HRESULT WINAPI CoRevertToSelf(void)
3102 IServerSecurity *pSrvSec;
3107 hr = CoGetCallContext(&IID_IServerSecurity, (void **)&pSrvSec);
3110 hr = IServerSecurity_RevertToSelf(pSrvSec);
3111 IServerSecurity_Release(pSrvSec);
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.
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.
3139 * Failure: RPC_S_CALLPENDING on timeout.
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.
3148 * MsgWaitForMultipleObjects, WaitForMultipleObjects.
3150 HRESULT WINAPI CoWaitForMultipleHandles(DWORD dwFlags, DWORD dwTimeout,
3151 ULONG cHandles, const HANDLE* pHandles, LPDWORD lpdwindex)
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);
3163 DWORD now = GetTickCount();
3166 if ((dwTimeout != INFINITE) && (start_time + dwTimeout >= now))
3168 hr = RPC_S_CALLPENDING;
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 */
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);
3200 case PENDINGMSG_CANCELCALL:
3201 WARN("call canceled\n");
3202 hr = RPC_E_CALL_CANCELED;
3204 case PENDINGMSG_WAITNOPROCESS:
3205 case PENDINGMSG_WAITDEFPROCESS:
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. */
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
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;
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);
3251 else if (res == WAIT_TIMEOUT)
3253 hr = RPC_S_CALLPENDING;
3258 ERR("Unexpected wait termination: %d, %d\n", res, GetLastError());
3263 TRACE("-- 0x%08x\n", hr);
3268 /***********************************************************************
3269 * CoGetObject [OLE32.@]
3271 * Gets the object named by coverting the name to a moniker and binding to it.
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
3282 * Failure: HRESULT code.
3285 * MkParseDisplayName.
3287 HRESULT WINAPI CoGetObject(LPCWSTR pszName, BIND_OPTS *pBindOptions,
3288 REFIID riid, void **ppv)
3295 hr = CreateBindCtx(0, &pbc);
3299 hr = IBindCtx_SetBindOptions(pbc, pBindOptions);
3306 hr = MkParseDisplayName(pbc, pszName, &chEaten, &pmk);
3309 hr = IMoniker_BindToObject(pmk, pbc, NULL, riid, ppv);
3310 IMoniker_Release(pmk);
3314 IBindCtx_Release(pbc);
3319 /***********************************************************************
3320 * CoRegisterChannelHook [OLE32.@]
3322 * Registers a process-wide hook that is called during ORPC calls.
3325 * guidExtension [I] GUID of the channel hook to register.
3326 * pChannelHook [I] Channel hook object to register.
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 /***********************************************************************
3342 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID fImpLoad)
3344 TRACE("%p 0x%x %p\n", hinstDLL, fdwReason, fImpLoad);
3347 case DLL_PROCESS_ATTACH:
3348 OLE32_hInstance = hinstDLL;
3349 COMPOBJ_InitProcess();
3350 if (TRACE_ON(ole)) CoRegisterMallocSpy((LPVOID)-1);
3353 case DLL_PROCESS_DETACH:
3354 if (TRACE_ON(ole)) CoRevokeMallocSpy();
3355 COMPOBJ_UninitProcess();
3356 RPC_UnregisterAllChannelHooks();
3357 OLE32_hInstance = 0;
3360 case DLL_THREAD_DETACH:
3367 /* NOTE: DllRegisterServer and DllUnregisterServer are in regsvr.c */