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 and context.
1466 if ((dwClsContext & curClass->runContext) &&
1467 IsEqualGUID(&(curClass->classIdentifier), rclsid))
1470 * We have a match, return the pointer to the class object.
1472 *ppUnk = curClass->classObject;
1474 IUnknown_AddRef(curClass->classObject);
1481 * Step to the next class in the list.
1483 curClass = curClass->nextClass;
1487 LeaveCriticalSection( &csRegisteredClassList );
1489 * If we get to here, we haven't found our class.
1494 /******************************************************************************
1495 * CoRegisterClassObject [OLE32.@]
1497 * Registers the class object for a given class ID. Servers housed in EXE
1498 * files use this method instead of exporting DllGetClassObject to allow
1499 * other code to connect to their objects.
1502 * rclsid [I] CLSID of the object to register.
1503 * pUnk [I] IUnknown of the object.
1504 * dwClsContext [I] CLSCTX flags indicating the context in which to run the executable.
1505 * flags [I] REGCLS flags indicating how connections are made.
1506 * lpdwRegister [I] A unique cookie that can be passed to CoRevokeClassObject.
1510 * E_INVALIDARG if lpdwRegister or pUnk are NULL,
1511 * CO_E_OBJISREG if the object is already registered. We should not return this.
1514 * CoRevokeClassObject, CoGetClassObject
1517 * MSDN claims that multiple interface registrations are legal, but we
1518 * can't do that with our current implementation.
1520 HRESULT WINAPI CoRegisterClassObject(
1525 LPDWORD lpdwRegister)
1527 RegisteredClass* newClass;
1528 LPUNKNOWN foundObject;
1531 TRACE("(%s,%p,0x%08x,0x%08x,%p)\n",
1532 debugstr_guid(rclsid),pUnk,dwClsContext,flags,lpdwRegister);
1534 if ( (lpdwRegister==0) || (pUnk==0) )
1535 return E_INVALIDARG;
1537 if (!COM_CurrentApt())
1539 ERR("COM was not initialized\n");
1540 return CO_E_NOTINITIALIZED;
1546 * First, check if the class is already registered.
1547 * If it is, this should cause an error.
1549 hr = COM_GetRegisteredClassObject(rclsid, dwClsContext, &foundObject);
1551 if (flags & REGCLS_MULTIPLEUSE) {
1552 if (dwClsContext & CLSCTX_LOCAL_SERVER)
1553 hr = CoLockObjectExternal(foundObject, TRUE, FALSE);
1554 IUnknown_Release(foundObject);
1557 IUnknown_Release(foundObject);
1558 ERR("object already registered for class %s\n", debugstr_guid(rclsid));
1559 return CO_E_OBJISREG;
1562 newClass = HeapAlloc(GetProcessHeap(), 0, sizeof(RegisteredClass));
1563 if ( newClass == NULL )
1564 return E_OUTOFMEMORY;
1566 EnterCriticalSection( &csRegisteredClassList );
1568 newClass->classIdentifier = *rclsid;
1569 newClass->runContext = dwClsContext;
1570 newClass->connectFlags = flags;
1571 newClass->pMarshaledData = NULL;
1574 * Use the address of the chain node as the cookie since we are sure it's
1575 * unique. FIXME: not on 64-bit platforms.
1577 newClass->dwCookie = (DWORD)newClass;
1578 newClass->nextClass = firstRegisteredClass;
1581 * Since we're making a copy of the object pointer, we have to increase its
1584 newClass->classObject = pUnk;
1585 IUnknown_AddRef(newClass->classObject);
1587 firstRegisteredClass = newClass;
1588 LeaveCriticalSection( &csRegisteredClassList );
1590 *lpdwRegister = newClass->dwCookie;
1592 if (dwClsContext & CLSCTX_LOCAL_SERVER) {
1593 IClassFactory *classfac;
1595 hr = IUnknown_QueryInterface(newClass->classObject, &IID_IClassFactory,
1596 (LPVOID*)&classfac);
1599 hr = CreateStreamOnHGlobal(0, TRUE, &newClass->pMarshaledData);
1601 FIXME("Failed to create stream on hglobal, %x\n", hr);
1602 IUnknown_Release(classfac);
1605 hr = CoMarshalInterface(newClass->pMarshaledData, &IID_IClassFactory,
1606 (LPVOID)classfac, MSHCTX_LOCAL, NULL,
1607 MSHLFLAGS_TABLESTRONG);
1609 FIXME("CoMarshalInterface failed, %x!\n",hr);
1610 IUnknown_Release(classfac);
1614 IUnknown_Release(classfac);
1616 RPC_StartLocalServer(&newClass->classIdentifier, newClass->pMarshaledData);
1621 /***********************************************************************
1622 * CoRevokeClassObject [OLE32.@]
1624 * Removes a class object from the class registry.
1627 * dwRegister [I] Cookie returned from CoRegisterClassObject().
1631 * Failure: HRESULT code.
1634 * CoRegisterClassObject
1636 HRESULT WINAPI CoRevokeClassObject(
1639 HRESULT hr = E_INVALIDARG;
1640 RegisteredClass** prevClassLink;
1641 RegisteredClass* curClass;
1643 TRACE("(%08x)\n",dwRegister);
1645 EnterCriticalSection( &csRegisteredClassList );
1648 * Iterate through the whole list and try to match the cookie.
1650 curClass = firstRegisteredClass;
1651 prevClassLink = &firstRegisteredClass;
1653 while (curClass != 0)
1656 * Check if we have a match on the cookie.
1658 if (curClass->dwCookie == dwRegister)
1661 * Remove the class from the chain.
1663 *prevClassLink = curClass->nextClass;
1666 * Release the reference to the class object.
1668 IUnknown_Release(curClass->classObject);
1670 if (curClass->pMarshaledData)
1673 memset(&zero, 0, sizeof(zero));
1674 /* FIXME: stop local server thread */
1675 IStream_Seek(curClass->pMarshaledData, zero, STREAM_SEEK_SET, NULL);
1676 CoReleaseMarshalData(curClass->pMarshaledData);
1680 * Free the memory used by the chain node.
1682 HeapFree(GetProcessHeap(), 0, curClass);
1689 * Step to the next class in the list.
1691 prevClassLink = &(curClass->nextClass);
1692 curClass = curClass->nextClass;
1696 LeaveCriticalSection( &csRegisteredClassList );
1698 * If we get to here, we haven't found our class.
1703 /***********************************************************************
1704 * COM_RegReadPath [internal]
1706 * Reads a registry value and expands it when necessary
1708 static DWORD COM_RegReadPath(HKEY hkeyroot, const WCHAR *keyname, const WCHAR *valuename, WCHAR * dst, DWORD dstlen)
1713 WCHAR src[MAX_PATH];
1714 DWORD dwLength = dstlen * sizeof(WCHAR);
1716 if((ret = RegOpenKeyExW(hkeyroot, keyname, 0, KEY_READ, &key)) == ERROR_SUCCESS) {
1717 if( (ret = RegQueryValueExW(key, NULL, NULL, &keytype, (LPBYTE)src, &dwLength)) == ERROR_SUCCESS ) {
1718 if (keytype == REG_EXPAND_SZ) {
1719 if (dstlen <= ExpandEnvironmentStringsW(src, dst, dstlen)) ret = ERROR_MORE_DATA;
1721 lstrcpynW(dst, src, dstlen);
1729 static void get_threading_model(HKEY key, LPWSTR value, DWORD len)
1731 static const WCHAR wszThreadingModel[] = {'T','h','r','e','a','d','i','n','g','M','o','d','e','l',0};
1734 DWORD dwLength = len * sizeof(WCHAR);
1736 ret = RegQueryValueExW(key, wszThreadingModel, NULL, &keytype, (LPBYTE)value, &dwLength);
1737 if ((ret != ERROR_SUCCESS) || (keytype != REG_SZ))
1741 static HRESULT get_inproc_class_object(HKEY hkeydll, REFCLSID rclsid, REFIID riid, void **ppv)
1743 static const WCHAR wszApartment[] = {'A','p','a','r','t','m','e','n','t',0};
1744 static const WCHAR wszFree[] = {'F','r','e','e',0};
1745 static const WCHAR wszBoth[] = {'B','o','t','h',0};
1747 typedef HRESULT (CALLBACK *DllGetClassObjectFunc)(REFCLSID clsid, REFIID iid, LPVOID *ppv);
1748 DllGetClassObjectFunc DllGetClassObject;
1749 WCHAR dllpath[MAX_PATH+1];
1750 WCHAR threading_model[10 /* strlenW(L"apartment")+1 */];
1753 get_threading_model(hkeydll, threading_model, ARRAYSIZE(threading_model));
1755 if (!strcmpiW(threading_model, wszApartment))
1757 APARTMENT *apt = COM_CurrentApt();
1758 if (apt->multi_threaded)
1760 /* try to find an STA */
1761 APARTMENT *host_apt = apartment_findfromtype(FALSE, FALSE);
1763 FIXME("create a host apartment for apartment-threaded object %s\n", debugstr_guid(rclsid));
1766 struct host_object_params params;
1767 HWND hwnd = apartment_getwindow(host_apt);
1769 params.hkeydll = hkeydll;
1770 params.clsid = *rclsid;
1772 hr = CreateStreamOnHGlobal(NULL, TRUE, ¶ms.stream);
1775 hr = SendMessageW(hwnd, DM_HOSTOBJECT, 0, (LPARAM)¶ms);
1777 hr = CoUnmarshalInterface(params.stream, riid, ppv);
1778 IStream_Release(params.stream);
1784 else if (!strcmpiW(threading_model, wszFree))
1786 APARTMENT *apt = COM_CurrentApt();
1787 if (!apt->multi_threaded)
1789 FIXME("should create object %s in multi-threaded apartment\n",
1790 debugstr_guid(rclsid));
1793 /* everything except "Apartment", "Free" and "Both" */
1794 else if (strcmpiW(threading_model, wszBoth))
1796 APARTMENT *apt = COM_CurrentApt();
1798 /* everything else is main-threaded */
1799 if (threading_model[0])
1800 FIXME("unrecognised threading model %s for object %s, should be main-threaded?\n",
1801 debugstr_w(threading_model), debugstr_guid(rclsid));
1803 if (apt->multi_threaded || !apt->main)
1805 /* try to find an STA */
1806 APARTMENT *host_apt = apartment_findfromtype(FALSE, TRUE);
1808 FIXME("create a host apartment for main-threaded object %s\n", debugstr_guid(rclsid));
1811 struct host_object_params params;
1812 HWND hwnd = apartment_getwindow(host_apt);
1814 params.hkeydll = hkeydll;
1815 params.clsid = *rclsid;
1817 hr = CreateStreamOnHGlobal(NULL, TRUE, ¶ms.stream);
1820 hr = SendMessageW(hwnd, DM_HOSTOBJECT, 0, (LPARAM)¶ms);
1822 hr = CoUnmarshalInterface(params.stream, riid, ppv);
1823 IStream_Release(params.stream);
1829 if (COM_RegReadPath(hkeydll, NULL, NULL, dllpath, ARRAYSIZE(dllpath)) != ERROR_SUCCESS)
1831 /* failure: CLSID is not found in registry */
1832 WARN("class %s not registered inproc\n", debugstr_guid(rclsid));
1833 return REGDB_E_CLASSNOTREG;
1836 if ((hLibrary = LoadLibraryExW(dllpath, 0, LOAD_WITH_ALTERED_SEARCH_PATH)) == 0)
1838 /* failure: DLL could not be loaded */
1839 ERR("couldn't load in-process dll %s\n", debugstr_w(dllpath));
1840 return E_ACCESSDENIED; /* FIXME: or should this be CO_E_DLLNOTFOUND? */
1843 if (!(DllGetClassObject = (DllGetClassObjectFunc)GetProcAddress(hLibrary, "DllGetClassObject")))
1845 /* failure: the dll did not export DllGetClassObject */
1846 ERR("couldn't find function DllGetClassObject in %s\n", debugstr_w(dllpath));
1847 FreeLibrary( hLibrary );
1848 return CO_E_DLLNOTFOUND;
1851 /* OK: get the ClassObject */
1852 COMPOBJ_DLLList_Add( hLibrary );
1853 hr = DllGetClassObject(rclsid, riid, ppv);
1856 ERR("DllGetClassObject returned error 0x%08x\n", hr);
1861 /***********************************************************************
1862 * CoGetClassObject [OLE32.@]
1864 * FIXME. If request allows of several options and there is a failure
1865 * with one (other than not being registered) do we try the
1866 * others or return failure? (E.g. inprocess is registered but
1867 * the DLL is not found but the server version works)
1869 HRESULT WINAPI CoGetClassObject(
1870 REFCLSID rclsid, DWORD dwClsContext, COSERVERINFO *pServerInfo,
1871 REFIID iid, LPVOID *ppv)
1873 LPUNKNOWN regClassObject;
1874 HRESULT hres = E_UNEXPECTED;
1876 TRACE("\n\tCLSID:\t%s,\n\tIID:\t%s\n", debugstr_guid(rclsid), debugstr_guid(iid));
1879 return E_INVALIDARG;
1883 if (!COM_CurrentApt())
1885 ERR("apartment not initialised\n");
1886 return CO_E_NOTINITIALIZED;
1890 FIXME("\tpServerInfo: name=%s\n",debugstr_w(pServerInfo->pwszName));
1891 FIXME("\t\tpAuthInfo=%p\n",pServerInfo->pAuthInfo);
1895 * First, try and see if we can't match the class ID with one of the
1896 * registered classes.
1898 if (S_OK == COM_GetRegisteredClassObject(rclsid, dwClsContext, ®ClassObject))
1900 /* Get the required interface from the retrieved pointer. */
1901 hres = IUnknown_QueryInterface(regClassObject, iid, ppv);
1904 * Since QI got another reference on the pointer, we want to release the
1905 * one we already have. If QI was unsuccessful, this will release the object. This
1906 * is good since we are not returning it in the "out" parameter.
1908 IUnknown_Release(regClassObject);
1913 /* First try in-process server */
1914 if (CLSCTX_INPROC_SERVER & dwClsContext)
1916 static const WCHAR wszInprocServer32[] = {'I','n','p','r','o','c','S','e','r','v','e','r','3','2',0};
1919 if (IsEqualCLSID(rclsid, &CLSID_InProcFreeMarshaler))
1920 return FTMarshalCF_Create(iid, ppv);
1922 hres = COM_OpenKeyForCLSID(rclsid, wszInprocServer32, KEY_READ, &hkey);
1925 if (hres == REGDB_E_CLASSNOTREG)
1926 ERR("class %s not registered\n", debugstr_guid(rclsid));
1928 WARN("class %s not registered as in-proc server\n", debugstr_guid(rclsid));
1931 if (SUCCEEDED(hres))
1933 hres = get_inproc_class_object(hkey, rclsid, iid, ppv);
1937 /* return if we got a class, otherwise fall through to one of the
1939 if (SUCCEEDED(hres))
1943 /* Next try in-process handler */
1944 if (CLSCTX_INPROC_HANDLER & dwClsContext)
1946 static const WCHAR wszInprocHandler32[] = {'I','n','p','r','o','c','H','a','n','d','l','e','r','3','2',0};
1949 hres = COM_OpenKeyForCLSID(rclsid, wszInprocHandler32, KEY_READ, &hkey);
1952 if (hres == REGDB_E_CLASSNOTREG)
1953 ERR("class %s not registered\n", debugstr_guid(rclsid));
1955 WARN("class %s not registered in-proc handler\n", debugstr_guid(rclsid));
1958 if (SUCCEEDED(hres))
1960 hres = get_inproc_class_object(hkey, rclsid, iid, ppv);
1964 /* return if we got a class, otherwise fall through to one of the
1966 if (SUCCEEDED(hres))
1970 /* Next try out of process */
1971 if (CLSCTX_LOCAL_SERVER & dwClsContext)
1973 hres = RPC_GetLocalClassObject(rclsid,iid,ppv);
1974 if (SUCCEEDED(hres))
1978 /* Finally try remote: this requires networked DCOM (a lot of work) */
1979 if (CLSCTX_REMOTE_SERVER & dwClsContext)
1981 FIXME ("CLSCTX_REMOTE_SERVER not supported\n");
1982 hres = E_NOINTERFACE;
1986 ERR("no class object %s could be created for context 0x%x\n",
1987 debugstr_guid(rclsid), dwClsContext);
1991 /***********************************************************************
1992 * CoResumeClassObjects (OLE32.@)
1994 * Resumes all class objects registered with REGCLS_SUSPENDED.
1998 * Failure: HRESULT code.
2000 HRESULT WINAPI CoResumeClassObjects(void)
2006 /***********************************************************************
2007 * GetClassFile (OLE32.@)
2009 * This function supplies the CLSID associated with the given filename.
2011 HRESULT WINAPI GetClassFile(LPCOLESTR filePathName,CLSID *pclsid)
2015 int nbElm, length, i;
2017 LPOLESTR *pathDec=0,absFile=0,progId=0;
2019 static const WCHAR bkslashW[] = {'\\',0};
2020 static const WCHAR dotW[] = {'.',0};
2022 TRACE("%s, %p\n", debugstr_w(filePathName), pclsid);
2024 /* if the file contain a storage object the return the CLSID written by IStorage_SetClass method*/
2025 if((StgIsStorageFile(filePathName))==S_OK){
2027 res=StgOpenStorage(filePathName,NULL,STGM_READ | STGM_SHARE_DENY_WRITE,NULL,0,&pstg);
2030 res=ReadClassStg(pstg,pclsid);
2032 IStorage_Release(pstg);
2036 /* if the file is not a storage object then attemps to match various bits in the file against a
2037 pattern in the registry. this case is not frequently used ! so I present only the psodocode for
2040 for(i=0;i<nFileTypes;i++)
2042 for(i=0;j<nPatternsForType;j++){
2047 pat=ReadPatternFromRegistry(i,j);
2048 hFile=CreateFileW(filePathName,,,,,,hFile);
2049 SetFilePosition(hFile,pat.offset);
2050 ReadFile(hFile,buf,pat.size,&r,NULL);
2051 if (memcmp(buf&pat.mask,pat.pattern.pat.size)==0){
2053 *pclsid=ReadCLSIDFromRegistry(i);
2059 /* if the above strategies fail then search for the extension key in the registry */
2061 /* get the last element (absolute file) in the path name */
2062 nbElm=FileMonikerImpl_DecomposePath(filePathName,&pathDec);
2063 absFile=pathDec[nbElm-1];
2065 /* failed if the path represente a directory and not an absolute file name*/
2066 if (!lstrcmpW(absFile, bkslashW))
2067 return MK_E_INVALIDEXTENSION;
2069 /* get the extension of the file */
2071 length=lstrlenW(absFile);
2072 for(i = length-1; (i >= 0) && *(extension = &absFile[i]) != '.'; i--)
2075 if (!extension || !lstrcmpW(extension, dotW))
2076 return MK_E_INVALIDEXTENSION;
2078 res=RegQueryValueW(HKEY_CLASSES_ROOT, extension, NULL, &sizeProgId);
2080 /* get the progId associated to the extension */
2081 progId = CoTaskMemAlloc(sizeProgId);
2082 res = RegQueryValueW(HKEY_CLASSES_ROOT, extension, progId, &sizeProgId);
2084 if (res==ERROR_SUCCESS)
2085 /* return the clsid associated to the progId */
2086 res= CLSIDFromProgID(progId,pclsid);
2088 for(i=0; pathDec[i]!=NULL;i++)
2089 CoTaskMemFree(pathDec[i]);
2090 CoTaskMemFree(pathDec);
2092 CoTaskMemFree(progId);
2094 if (res==ERROR_SUCCESS)
2097 return MK_E_INVALIDEXTENSION;
2100 /***********************************************************************
2101 * CoCreateInstance [OLE32.@]
2103 * Creates an instance of the specified class.
2106 * rclsid [I] Class ID to create an instance of.
2107 * pUnkOuter [I] Optional outer unknown to allow aggregation with another object.
2108 * dwClsContext [I] Flags to restrict the location of the created instance.
2109 * iid [I] The ID of the interface of the instance to return.
2110 * ppv [O] On returns, contains a pointer to the specified interface of the instance.
2114 * Failure: HRESULT code.
2117 * The dwClsContext parameter can be one or more of the following:
2118 *| CLSCTX_INPROC_SERVER - Use an in-process server, such as from a DLL.
2119 *| CLSCTX_INPROC_HANDLER - Use an in-process object which handles certain functions for an object running in another process.
2120 *| CLSCTX_LOCAL_SERVER - Connect to an object running in another process.
2121 *| CLSCTX_REMOTE_SERVER - Connect to an object running on another machine.
2123 * Aggregation is the concept of deferring the IUnknown of an object to another
2124 * object. This allows a separate object to behave as though it was part of
2125 * the object and to allow this the pUnkOuter parameter can be set. Note that
2126 * not all objects support having an outer of unknown.
2129 * CoGetClassObject()
2131 HRESULT WINAPI CoCreateInstance(
2133 LPUNKNOWN pUnkOuter,
2139 LPCLASSFACTORY lpclf = 0;
2141 TRACE("(rclsid=%s, pUnkOuter=%p, dwClsContext=%08x, riid=%s, ppv=%p)\n", debugstr_guid(rclsid),
2142 pUnkOuter, dwClsContext, debugstr_guid(iid), ppv);
2151 * Initialize the "out" parameter
2155 if (!COM_CurrentApt())
2157 ERR("apartment not initialised\n");
2158 return CO_E_NOTINITIALIZED;
2162 * The Standard Global Interface Table (GIT) object is a process-wide singleton.
2163 * Rather than create a class factory, we can just check for it here
2165 if (IsEqualIID(rclsid, &CLSID_StdGlobalInterfaceTable)) {
2166 if (StdGlobalInterfaceTableInstance == NULL)
2167 StdGlobalInterfaceTableInstance = StdGlobalInterfaceTable_Construct();
2168 hres = IGlobalInterfaceTable_QueryInterface( (IGlobalInterfaceTable*) StdGlobalInterfaceTableInstance, iid, ppv);
2169 if (hres) return hres;
2171 TRACE("Retrieved GIT (%p)\n", *ppv);
2176 * Get a class factory to construct the object we want.
2178 hres = CoGetClassObject(rclsid,
2188 * Create the object and don't forget to release the factory
2190 hres = IClassFactory_CreateInstance(lpclf, pUnkOuter, iid, ppv);
2191 IClassFactory_Release(lpclf);
2193 FIXME("no instance created for interface %s of class %s, hres is 0x%08x\n",
2194 debugstr_guid(iid), debugstr_guid(rclsid),hres);
2199 /***********************************************************************
2200 * CoCreateInstanceEx [OLE32.@]
2202 HRESULT WINAPI CoCreateInstanceEx(
2204 LPUNKNOWN pUnkOuter,
2206 COSERVERINFO* pServerInfo,
2210 IUnknown* pUnk = NULL;
2213 ULONG successCount = 0;
2218 if ( (cmq==0) || (pResults==NULL))
2219 return E_INVALIDARG;
2221 if (pServerInfo!=NULL)
2222 FIXME("() non-NULL pServerInfo not supported!\n");
2225 * Initialize all the "out" parameters.
2227 for (index = 0; index < cmq; index++)
2229 pResults[index].pItf = NULL;
2230 pResults[index].hr = E_NOINTERFACE;
2234 * Get the object and get its IUnknown pointer.
2236 hr = CoCreateInstance(rclsid,
2246 * Then, query for all the interfaces requested.
2248 for (index = 0; index < cmq; index++)
2250 pResults[index].hr = IUnknown_QueryInterface(pUnk,
2251 pResults[index].pIID,
2252 (VOID**)&(pResults[index].pItf));
2254 if (pResults[index].hr == S_OK)
2259 * Release our temporary unknown pointer.
2261 IUnknown_Release(pUnk);
2263 if (successCount == 0)
2264 return E_NOINTERFACE;
2266 if (successCount!=cmq)
2267 return CO_S_NOTALLINTERFACES;
2272 /***********************************************************************
2273 * CoLoadLibrary (OLE32.@)
2278 * lpszLibName [I] Path to library.
2279 * bAutoFree [I] Whether the library should automatically be freed.
2282 * Success: Handle to loaded library.
2286 * CoFreeLibrary, CoFreeAllLibraries, CoFreeUnusedLibraries
2288 HINSTANCE WINAPI CoLoadLibrary(LPOLESTR lpszLibName, BOOL bAutoFree)
2290 TRACE("(%s, %d)\n", debugstr_w(lpszLibName), bAutoFree);
2292 return LoadLibraryExW(lpszLibName, 0, LOAD_WITH_ALTERED_SEARCH_PATH);
2295 /***********************************************************************
2296 * CoFreeLibrary [OLE32.@]
2298 * Unloads a library from memory.
2301 * hLibrary [I] Handle to library to unload.
2307 * CoLoadLibrary, CoFreeAllLibraries, CoFreeUnusedLibraries
2309 void WINAPI CoFreeLibrary(HINSTANCE hLibrary)
2311 FreeLibrary(hLibrary);
2315 /***********************************************************************
2316 * CoFreeAllLibraries [OLE32.@]
2318 * Function for backwards compatibility only. Does nothing.
2324 * CoLoadLibrary, CoFreeLibrary, CoFreeUnusedLibraries
2326 void WINAPI CoFreeAllLibraries(void)
2332 /***********************************************************************
2333 * CoFreeUnusedLibraries [OLE32.@]
2334 * CoFreeUnusedLibraries [COMPOBJ.17]
2336 * Frees any unused libraries. Unused are identified as those that return
2337 * S_OK from their DllCanUnloadNow function.
2343 * CoLoadLibrary, CoFreeAllLibraries, CoFreeLibrary
2345 void WINAPI CoFreeUnusedLibraries(void)
2347 /* FIXME: Calls to CoFreeUnusedLibraries from any thread always route
2348 * through the main apartment's thread to call DllCanUnloadNow */
2349 COMPOBJ_DllList_FreeUnused(0);
2352 /***********************************************************************
2353 * CoFileTimeNow [OLE32.@]
2354 * CoFileTimeNow [COMPOBJ.82]
2356 * Retrieves the current time in FILETIME format.
2359 * lpFileTime [O] The current time.
2364 HRESULT WINAPI CoFileTimeNow( FILETIME *lpFileTime )
2366 GetSystemTimeAsFileTime( lpFileTime );
2370 static void COM_RevokeAllClasses(void)
2372 EnterCriticalSection( &csRegisteredClassList );
2374 while (firstRegisteredClass!=0)
2376 CoRevokeClassObject(firstRegisteredClass->dwCookie);
2379 LeaveCriticalSection( &csRegisteredClassList );
2382 /******************************************************************************
2383 * CoLockObjectExternal [OLE32.@]
2385 * Increments or decrements the external reference count of a stub object.
2388 * pUnk [I] Stub object.
2389 * fLock [I] If TRUE then increments the external ref-count,
2390 * otherwise decrements.
2391 * fLastUnlockReleases [I] If TRUE then the last unlock has the effect of
2392 * calling CoDisconnectObject.
2396 * Failure: HRESULT code.
2399 * If fLock is TRUE and an object is passed in that doesn't have a stub
2400 * manager then a new stub manager is created for the object.
2402 HRESULT WINAPI CoLockObjectExternal(
2405 BOOL fLastUnlockReleases)
2407 struct stub_manager *stubmgr;
2408 struct apartment *apt;
2410 TRACE("pUnk=%p, fLock=%s, fLastUnlockReleases=%s\n",
2411 pUnk, fLock ? "TRUE" : "FALSE", fLastUnlockReleases ? "TRUE" : "FALSE");
2413 apt = COM_CurrentApt();
2414 if (!apt) return CO_E_NOTINITIALIZED;
2416 stubmgr = get_stub_manager_from_object(apt, pUnk);
2421 stub_manager_ext_addref(stubmgr, 1);
2423 stub_manager_ext_release(stubmgr, 1, fLastUnlockReleases);
2425 stub_manager_int_release(stubmgr);
2431 stubmgr = new_stub_manager(apt, pUnk);
2435 stub_manager_ext_addref(stubmgr, 1);
2436 stub_manager_int_release(stubmgr);
2443 WARN("stub object not found %p\n", pUnk);
2444 /* Note: native is pretty broken here because it just silently
2445 * fails, without returning an appropriate error code, making apps
2446 * think that the object was disconnected, when it actually wasn't */
2451 /***********************************************************************
2452 * CoInitializeWOW (OLE32.@)
2454 * WOW equivalent of CoInitialize?
2463 HRESULT WINAPI CoInitializeWOW(DWORD x,DWORD y)
2465 FIXME("(0x%08x,0x%08x),stub!\n",x,y);
2469 /***********************************************************************
2470 * CoGetState [OLE32.@]
2472 * Retrieves the thread state object previously stored by CoSetState().
2475 * ppv [I] Address where pointer to object will be stored.
2479 * Failure: E_OUTOFMEMORY.
2482 * Crashes on all invalid ppv addresses, including NULL.
2483 * If the function returns a non-NULL object then the caller must release its
2484 * reference on the object when the object is no longer required.
2489 HRESULT WINAPI CoGetState(IUnknown ** ppv)
2491 struct oletls *info = COM_CurrentInfo();
2492 if (!info) return E_OUTOFMEMORY;
2498 IUnknown_AddRef(info->state);
2500 TRACE("apt->state=%p\n", info->state);
2506 /***********************************************************************
2507 * CoSetState [OLE32.@]
2509 * Sets the thread state object.
2512 * pv [I] Pointer to state object to be stored.
2515 * The system keeps a reference on the object while the object stored.
2519 * Failure: E_OUTOFMEMORY.
2521 HRESULT WINAPI CoSetState(IUnknown * pv)
2523 struct oletls *info = COM_CurrentInfo();
2524 if (!info) return E_OUTOFMEMORY;
2526 if (pv) IUnknown_AddRef(pv);
2530 TRACE("-- release %p now\n", info->state);
2531 IUnknown_Release(info->state);
2540 /******************************************************************************
2541 * CoTreatAsClass [OLE32.@]
2543 * Sets the TreatAs value of a class.
2546 * clsidOld [I] Class to set TreatAs value on.
2547 * clsidNew [I] The class the clsidOld should be treated as.
2551 * Failure: HRESULT code.
2556 HRESULT WINAPI CoTreatAsClass(REFCLSID clsidOld, REFCLSID clsidNew)
2558 static const WCHAR wszAutoTreatAs[] = {'A','u','t','o','T','r','e','a','t','A','s',0};
2559 static const WCHAR wszTreatAs[] = {'T','r','e','a','t','A','s',0};
2561 WCHAR szClsidNew[CHARS_IN_GUID];
2563 WCHAR auto_treat_as[CHARS_IN_GUID];
2564 LONG auto_treat_as_size = sizeof(auto_treat_as);
2567 res = COM_OpenKeyForCLSID(clsidOld, NULL, KEY_READ | KEY_WRITE, &hkey);
2570 if (!memcmp( clsidOld, clsidNew, sizeof(*clsidOld) ))
2572 if (!RegQueryValueW(hkey, wszAutoTreatAs, auto_treat_as, &auto_treat_as_size) &&
2573 !CLSIDFromString(auto_treat_as, &id))
2575 if (RegSetValueW(hkey, wszTreatAs, REG_SZ, auto_treat_as, sizeof(auto_treat_as)))
2577 res = REGDB_E_WRITEREGDB;
2583 RegDeleteKeyW(hkey, wszTreatAs);
2587 else if (!StringFromGUID2(clsidNew, szClsidNew, ARRAYSIZE(szClsidNew)) &&
2588 !RegSetValueW(hkey, wszTreatAs, REG_SZ, szClsidNew, sizeof(szClsidNew)))
2590 res = REGDB_E_WRITEREGDB;
2595 if (hkey) RegCloseKey(hkey);
2599 /******************************************************************************
2600 * CoGetTreatAsClass [OLE32.@]
2602 * Gets the TreatAs value of a class.
2605 * clsidOld [I] Class to get the TreatAs value of.
2606 * clsidNew [I] The class the clsidOld should be treated as.
2610 * Failure: HRESULT code.
2615 HRESULT WINAPI CoGetTreatAsClass(REFCLSID clsidOld, LPCLSID clsidNew)
2617 static const WCHAR wszTreatAs[] = {'T','r','e','a','t','A','s',0};
2619 WCHAR szClsidNew[CHARS_IN_GUID];
2621 LONG len = sizeof(szClsidNew);
2623 FIXME("(%s,%p)\n", debugstr_guid(clsidOld), clsidNew);
2624 memcpy(clsidNew,clsidOld,sizeof(CLSID)); /* copy over old value */
2626 res = COM_OpenKeyForCLSID(clsidOld, wszTreatAs, KEY_READ, &hkey);
2629 if (RegQueryValueW(hkey, NULL, szClsidNew, &len))
2634 res = CLSIDFromString(szClsidNew,clsidNew);
2636 ERR("Failed CLSIDFromStringA(%s), hres 0x%08x\n", debugstr_w(szClsidNew), res);
2638 if (hkey) RegCloseKey(hkey);
2642 /******************************************************************************
2643 * CoGetCurrentProcess [OLE32.@]
2644 * CoGetCurrentProcess [COMPOBJ.34]
2646 * Gets the current process ID.
2649 * The current process ID.
2652 * Is DWORD really the correct return type for this function?
2654 DWORD WINAPI CoGetCurrentProcess(void)
2656 return GetCurrentProcessId();
2659 /******************************************************************************
2660 * CoRegisterMessageFilter [OLE32.@]
2662 * Registers a message filter.
2665 * lpMessageFilter [I] Pointer to interface.
2666 * lplpMessageFilter [O] Indirect pointer to prior instance if non-NULL.
2670 * Failure: HRESULT code.
2673 * Both lpMessageFilter and lplpMessageFilter are optional. Passing in a NULL
2674 * lpMessageFilter removes the message filter.
2676 * If lplpMessageFilter is not NULL the previous message filter will be
2677 * returned in the memory pointer to this parameter and the caller is
2678 * responsible for releasing the object.
2680 * The current thread be in an apartment otherwise the function will crash.
2682 HRESULT WINAPI CoRegisterMessageFilter(
2683 LPMESSAGEFILTER lpMessageFilter,
2684 LPMESSAGEFILTER *lplpMessageFilter)
2686 struct apartment *apt;
2687 IMessageFilter *lpOldMessageFilter;
2689 TRACE("(%p, %p)\n", lpMessageFilter, lplpMessageFilter);
2691 apt = COM_CurrentApt();
2693 /* can't set a message filter in a multi-threaded apartment */
2694 if (!apt || apt->multi_threaded)
2696 WARN("can't set message filter in MTA or uninitialized apt\n");
2697 return CO_E_NOT_SUPPORTED;
2700 if (lpMessageFilter)
2701 IMessageFilter_AddRef(lpMessageFilter);
2703 EnterCriticalSection(&apt->cs);
2705 lpOldMessageFilter = apt->filter;
2706 apt->filter = lpMessageFilter;
2708 LeaveCriticalSection(&apt->cs);
2710 if (lplpMessageFilter)
2711 *lplpMessageFilter = lpOldMessageFilter;
2712 else if (lpOldMessageFilter)
2713 IMessageFilter_Release(lpOldMessageFilter);
2718 /***********************************************************************
2719 * CoIsOle1Class [OLE32.@]
2721 * Determines whether the specified class an OLE v1 class.
2724 * clsid [I] Class to test.
2727 * TRUE if the class is an OLE v1 class, or FALSE otherwise.
2729 BOOL WINAPI CoIsOle1Class(REFCLSID clsid)
2731 FIXME("%s\n", debugstr_guid(clsid));
2735 /***********************************************************************
2736 * IsEqualGUID [OLE32.@]
2738 * Compares two Unique Identifiers.
2741 * rguid1 [I] The first GUID to compare.
2742 * rguid2 [I] The other GUID to compare.
2748 BOOL WINAPI IsEqualGUID(
2752 return !memcmp(rguid1,rguid2,sizeof(GUID));
2755 /***********************************************************************
2756 * CoInitializeSecurity [OLE32.@]
2758 HRESULT WINAPI CoInitializeSecurity(PSECURITY_DESCRIPTOR pSecDesc, LONG cAuthSvc,
2759 SOLE_AUTHENTICATION_SERVICE* asAuthSvc,
2760 void* pReserved1, DWORD dwAuthnLevel,
2761 DWORD dwImpLevel, void* pReserved2,
2762 DWORD dwCapabilities, void* pReserved3)
2764 FIXME("(%p,%d,%p,%p,%d,%d,%p,%d,%p) - stub!\n", pSecDesc, cAuthSvc,
2765 asAuthSvc, pReserved1, dwAuthnLevel, dwImpLevel, pReserved2,
2766 dwCapabilities, pReserved3);
2770 /***********************************************************************
2771 * CoSuspendClassObjects [OLE32.@]
2773 * Suspends all registered class objects to prevent further requests coming in
2774 * for those objects.
2778 * Failure: HRESULT code.
2780 HRESULT WINAPI CoSuspendClassObjects(void)
2786 /***********************************************************************
2787 * CoAddRefServerProcess [OLE32.@]
2789 * Helper function for incrementing the reference count of a local-server
2793 * New reference count.
2795 ULONG WINAPI CoAddRefServerProcess(void)
2801 /***********************************************************************
2802 * CoReleaseServerProcess [OLE32.@]
2804 * Helper function for decrementing the reference count of a local-server
2808 * New reference count.
2810 ULONG WINAPI CoReleaseServerProcess(void)
2816 /***********************************************************************
2817 * CoIsHandlerConnected [OLE32.@]
2819 * Determines whether a proxy is connected to a remote stub.
2822 * pUnk [I] Pointer to object that may or may not be connected.
2825 * TRUE if pUnk is not a proxy or if pUnk is connected to a remote stub, or
2828 BOOL WINAPI CoIsHandlerConnected(IUnknown *pUnk)
2830 FIXME("%p\n", pUnk);
2835 /***********************************************************************
2836 * CoAllowSetForegroundWindow [OLE32.@]
2839 HRESULT WINAPI CoAllowSetForegroundWindow(IUnknown *pUnk, void *pvReserved)
2841 FIXME("(%p, %p): stub\n", pUnk, pvReserved);
2845 /***********************************************************************
2846 * CoQueryProxyBlanket [OLE32.@]
2848 * Retrieves the security settings being used by a proxy.
2851 * pProxy [I] Pointer to the proxy object.
2852 * pAuthnSvc [O] The type of authentication service.
2853 * pAuthzSvc [O] The type of authorization service.
2854 * ppServerPrincName [O] Optional. The server prinicple name.
2855 * pAuthnLevel [O] The authentication level.
2856 * pImpLevel [O] The impersonation level.
2857 * ppAuthInfo [O] Information specific to the authorization/authentication service.
2858 * pCapabilities [O] Flags affecting the security behaviour.
2862 * Failure: HRESULT code.
2865 * CoCopyProxy, CoSetProxyBlanket.
2867 HRESULT WINAPI CoQueryProxyBlanket(IUnknown *pProxy, DWORD *pAuthnSvc,
2868 DWORD *pAuthzSvc, OLECHAR **ppServerPrincName, DWORD *pAuthnLevel,
2869 DWORD *pImpLevel, void **ppAuthInfo, DWORD *pCapabilities)
2871 IClientSecurity *pCliSec;
2874 TRACE("%p\n", pProxy);
2876 hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
2879 hr = IClientSecurity_QueryBlanket(pCliSec, pProxy, pAuthnSvc,
2880 pAuthzSvc, ppServerPrincName,
2881 pAuthnLevel, pImpLevel, ppAuthInfo,
2883 IClientSecurity_Release(pCliSec);
2886 if (FAILED(hr)) ERR("-- failed with 0x%08x\n", hr);
2890 /***********************************************************************
2891 * CoSetProxyBlanket [OLE32.@]
2893 * Sets the security settings for a proxy.
2896 * pProxy [I] Pointer to the proxy object.
2897 * AuthnSvc [I] The type of authentication service.
2898 * AuthzSvc [I] The type of authorization service.
2899 * pServerPrincName [I] The server prinicple name.
2900 * AuthnLevel [I] The authentication level.
2901 * ImpLevel [I] The impersonation level.
2902 * pAuthInfo [I] Information specific to the authorization/authentication service.
2903 * Capabilities [I] Flags affecting the security behaviour.
2907 * Failure: HRESULT code.
2910 * CoQueryProxyBlanket, CoCopyProxy.
2912 HRESULT WINAPI CoSetProxyBlanket(IUnknown *pProxy, DWORD AuthnSvc,
2913 DWORD AuthzSvc, OLECHAR *pServerPrincName, DWORD AuthnLevel,
2914 DWORD ImpLevel, void *pAuthInfo, DWORD Capabilities)
2916 IClientSecurity *pCliSec;
2919 TRACE("%p\n", pProxy);
2921 hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
2924 hr = IClientSecurity_SetBlanket(pCliSec, pProxy, AuthnSvc,
2925 AuthzSvc, pServerPrincName,
2926 AuthnLevel, ImpLevel, pAuthInfo,
2928 IClientSecurity_Release(pCliSec);
2931 if (FAILED(hr)) ERR("-- failed with 0x%08x\n", hr);
2935 /***********************************************************************
2936 * CoCopyProxy [OLE32.@]
2941 * pProxy [I] Pointer to the proxy object.
2942 * ppCopy [O] Copy of the proxy.
2946 * Failure: HRESULT code.
2949 * CoQueryProxyBlanket, CoSetProxyBlanket.
2951 HRESULT WINAPI CoCopyProxy(IUnknown *pProxy, IUnknown **ppCopy)
2953 IClientSecurity *pCliSec;
2956 TRACE("%p\n", pProxy);
2958 hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
2961 hr = IClientSecurity_CopyProxy(pCliSec, pProxy, ppCopy);
2962 IClientSecurity_Release(pCliSec);
2965 if (FAILED(hr)) ERR("-- failed with 0x%08x\n", hr);
2970 /***********************************************************************
2971 * CoGetCallContext [OLE32.@]
2973 * Gets the context of the currently executing server call in the current
2977 * riid [I] Context interface to return.
2978 * ppv [O] Pointer to memory that will receive the context on return.
2982 * Failure: HRESULT code.
2984 HRESULT WINAPI CoGetCallContext(REFIID riid, void **ppv)
2986 FIXME("(%s, %p): stub\n", debugstr_guid(riid), ppv);
2989 return E_NOINTERFACE;
2992 /***********************************************************************
2993 * CoQueryClientBlanket [OLE32.@]
2995 * Retrieves the authentication information about the client of the currently
2996 * executing server call in the current thread.
2999 * pAuthnSvc [O] Optional. The type of authentication service.
3000 * pAuthzSvc [O] Optional. The type of authorization service.
3001 * pServerPrincName [O] Optional. The server prinicple name.
3002 * pAuthnLevel [O] Optional. The authentication level.
3003 * pImpLevel [O] Optional. The impersonation level.
3004 * pPrivs [O] Optional. Information about the privileges of the client.
3005 * pCapabilities [IO] Optional. Flags affecting the security behaviour.
3009 * Failure: HRESULT code.
3012 * CoImpersonateClient, CoRevertToSelf, CoGetCallContext.
3014 HRESULT WINAPI CoQueryClientBlanket(
3017 OLECHAR **pServerPrincName,
3020 RPC_AUTHZ_HANDLE *pPrivs,
3021 DWORD *pCapabilities)
3023 IServerSecurity *pSrvSec;
3026 TRACE("(%p, %p, %p, %p, %p, %p, %p)\n",
3027 pAuthnSvc, pAuthzSvc, pServerPrincName, pAuthnLevel, pImpLevel,
3028 pPrivs, pCapabilities);
3030 hr = CoGetCallContext(&IID_IServerSecurity, (void **)&pSrvSec);
3033 hr = IServerSecurity_QueryBlanket(
3034 pSrvSec, pAuthnSvc, pAuthzSvc, pServerPrincName, pAuthnLevel,
3035 pImpLevel, pPrivs, pCapabilities);
3036 IServerSecurity_Release(pSrvSec);
3042 /***********************************************************************
3043 * CoImpersonateClient [OLE32.@]
3045 * Impersonates the client of the currently executing server call in the
3053 * Failure: HRESULT code.
3056 * If this function fails then the current thread will not be impersonating
3057 * the client and all actions will take place on behalf of the server.
3058 * Therefore, it is important to check the return value from this function.
3061 * CoRevertToSelf, CoQueryClientBlanket, CoGetCallContext.
3063 HRESULT WINAPI CoImpersonateClient(void)
3065 IServerSecurity *pSrvSec;
3070 hr = CoGetCallContext(&IID_IServerSecurity, (void **)&pSrvSec);
3073 hr = IServerSecurity_ImpersonateClient(pSrvSec);
3074 IServerSecurity_Release(pSrvSec);
3080 /***********************************************************************
3081 * CoRevertToSelf [OLE32.@]
3083 * Ends the impersonation of the client of the currently executing server
3084 * call in the current thread.
3091 * Failure: HRESULT code.
3094 * CoImpersonateClient, CoQueryClientBlanket, CoGetCallContext.
3096 HRESULT WINAPI CoRevertToSelf(void)
3098 IServerSecurity *pSrvSec;
3103 hr = CoGetCallContext(&IID_IServerSecurity, (void **)&pSrvSec);
3106 hr = IServerSecurity_RevertToSelf(pSrvSec);
3107 IServerSecurity_Release(pSrvSec);
3113 static BOOL COM_PeekMessage(struct apartment *apt, MSG *msg)
3115 /* first try to retrieve messages for incoming COM calls to the apartment window */
3116 return PeekMessageW(msg, apt->win, WM_USER, WM_APP - 1, PM_REMOVE|PM_NOYIELD) ||
3117 /* next retrieve other messages necessary for the app to remain responsive */
3118 PeekMessageW(msg, NULL, 0, WM_USER - 1, PM_REMOVE|PM_NOYIELD);
3121 /***********************************************************************
3122 * CoWaitForMultipleHandles [OLE32.@]
3124 * Waits for one or more handles to become signaled.
3127 * dwFlags [I] Flags. See notes.
3128 * dwTimeout [I] Timeout in milliseconds.
3129 * cHandles [I] Number of handles pointed to by pHandles.
3130 * pHandles [I] Handles to wait for.
3131 * lpdwindex [O] Index of handle that was signaled.
3135 * Failure: RPC_S_CALLPENDING on timeout.
3139 * The dwFlags parameter can be zero or more of the following:
3140 *| COWAIT_WAITALL - Wait for all of the handles to become signaled.
3141 *| COWAIT_ALERTABLE - Allows a queued APC to run during the wait.
3144 * MsgWaitForMultipleObjects, WaitForMultipleObjects.
3146 HRESULT WINAPI CoWaitForMultipleHandles(DWORD dwFlags, DWORD dwTimeout,
3147 ULONG cHandles, LPHANDLE pHandles, LPDWORD lpdwindex)
3150 DWORD start_time = GetTickCount();
3151 APARTMENT *apt = COM_CurrentApt();
3152 BOOL message_loop = apt && !apt->multi_threaded;
3154 TRACE("(0x%08x, 0x%08x, %d, %p, %p)\n", dwFlags, dwTimeout, cHandles,
3155 pHandles, lpdwindex);
3159 DWORD now = GetTickCount();
3162 if ((dwTimeout != INFINITE) && (start_time + dwTimeout >= now))
3164 hr = RPC_S_CALLPENDING;
3170 DWORD wait_flags = (dwFlags & COWAIT_WAITALL) ? MWMO_WAITALL : 0 |
3171 (dwFlags & COWAIT_ALERTABLE ) ? MWMO_ALERTABLE : 0;
3173 TRACE("waiting for rpc completion or window message\n");
3175 res = MsgWaitForMultipleObjectsEx(cHandles, pHandles,
3176 (dwTimeout == INFINITE) ? INFINITE : start_time + dwTimeout - now,
3177 QS_ALLINPUT, wait_flags);
3179 if (res == WAIT_OBJECT_0 + cHandles) /* messages available */
3183 /* call message filter */
3185 if (COM_CurrentApt()->filter)
3187 PENDINGTYPE pendingtype =
3188 COM_CurrentInfo()->pending_call_count_server ?
3189 PENDINGTYPE_NESTED : PENDINGTYPE_TOPLEVEL;
3190 DWORD be_handled = IMessageFilter_MessagePending(
3191 COM_CurrentApt()->filter, 0 /* FIXME */,
3192 now - start_time, pendingtype);
3193 TRACE("IMessageFilter_MessagePending returned %d\n", be_handled);
3196 case PENDINGMSG_CANCELCALL:
3197 WARN("call canceled\n");
3198 hr = RPC_E_CALL_CANCELED;
3200 case PENDINGMSG_WAITNOPROCESS:
3201 case PENDINGMSG_WAITDEFPROCESS:
3203 /* FIXME: MSDN is very vague about the difference
3204 * between WAITNOPROCESS and WAITDEFPROCESS - there
3205 * appears to be none, so it is possibly a left-over
3206 * from the 16-bit world. */
3211 /* note: using "if" here instead of "while" might seem less
3212 * efficient, but only if we are optimising for quick delivery
3213 * of pending messages, rather than quick completion of the
3215 if (COM_PeekMessage(apt, &msg))
3217 TRACE("received message whilst waiting for RPC: 0x%04x\n", msg.message);
3218 TranslateMessage(&msg);
3219 DispatchMessageW(&msg);
3220 if (msg.message == WM_QUIT)
3222 TRACE("resending WM_QUIT to outer message loop\n");
3223 PostQuitMessage(msg.wParam);
3224 /* no longer need to process messages */
3225 message_loop = FALSE;
3233 TRACE("waiting for rpc completion\n");
3235 res = WaitForMultipleObjectsEx(cHandles, pHandles,
3236 (dwFlags & COWAIT_WAITALL) ? TRUE : FALSE,
3237 (dwTimeout == INFINITE) ? INFINITE : start_time + dwTimeout - now,
3238 (dwFlags & COWAIT_ALERTABLE) ? TRUE : FALSE);
3241 if ((res >= WAIT_OBJECT_0) && (res < WAIT_OBJECT_0 + cHandles))
3243 /* handle signaled, store index */
3244 *lpdwindex = (res - WAIT_OBJECT_0);
3247 else if (res == WAIT_TIMEOUT)
3249 hr = RPC_S_CALLPENDING;
3254 ERR("Unexpected wait termination: %d, %d\n", res, GetLastError());
3259 TRACE("-- 0x%08x\n", hr);
3264 /***********************************************************************
3265 * CoGetObject [OLE32.@]
3267 * Gets the object named by coverting the name to a moniker and binding to it.
3270 * pszName [I] String representing the object.
3271 * pBindOptions [I] Parameters affecting the binding to the named object.
3272 * riid [I] Interface to bind to on the objecct.
3273 * ppv [O] On output, the interface riid of the object represented
3278 * Failure: HRESULT code.
3281 * MkParseDisplayName.
3283 HRESULT WINAPI CoGetObject(LPCWSTR pszName, BIND_OPTS *pBindOptions,
3284 REFIID riid, void **ppv)
3291 hr = CreateBindCtx(0, &pbc);
3295 hr = IBindCtx_SetBindOptions(pbc, pBindOptions);
3302 hr = MkParseDisplayName(pbc, pszName, &chEaten, &pmk);
3305 hr = IMoniker_BindToObject(pmk, pbc, NULL, riid, ppv);
3306 IMoniker_Release(pmk);
3310 IBindCtx_Release(pbc);
3315 /***********************************************************************
3316 * CoRegisterChannelHook [OLE32.@]
3318 * Registers a process-wide hook that is called during ORPC calls.
3321 * guidExtension [I] GUID of the channel hook to register.
3322 * pChannelHook [I] Channel hook object to register.
3326 * Failure: HRESULT code.
3328 HRESULT WINAPI CoRegisterChannelHook(REFGUID guidExtension, IChannelHook *pChannelHook)
3330 TRACE("(%s, %p)\n", debugstr_guid(guidExtension), pChannelHook);
3332 return RPC_RegisterChannelHook(guidExtension, pChannelHook);
3335 /***********************************************************************
3338 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID fImpLoad)
3340 TRACE("%p 0x%x %p\n", hinstDLL, fdwReason, fImpLoad);
3343 case DLL_PROCESS_ATTACH:
3344 OLE32_hInstance = hinstDLL;
3345 COMPOBJ_InitProcess();
3346 if (TRACE_ON(ole)) CoRegisterMallocSpy((LPVOID)-1);
3349 case DLL_PROCESS_DETACH:
3350 if (TRACE_ON(ole)) CoRevokeMallocSpy();
3351 COMPOBJ_UninitProcess();
3352 RPC_UnregisterAllChannelHooks();
3353 OLE32_hInstance = 0;
3356 case DLL_THREAD_DETACH:
3363 /* NOTE: DllRegisterServer and DllUnregisterServer are in regsvr.c */