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
51 #define NONAMELESSUNION
52 #define NONAMELESSSTRUCT
63 #include "compobj_private.h"
65 #include "wine/unicode.h"
66 #include "wine/debug.h"
68 WINE_DEFAULT_DEBUG_CHANNEL(ole);
70 HINSTANCE OLE32_hInstance = 0; /* FIXME: make static ... */
72 #define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))
74 /****************************************************************************
75 * This section defines variables internal to the COM module.
77 * TODO: Most of these things will have to be made thread-safe.
80 static HRESULT COM_GetRegisteredClassObject(REFCLSID rclsid, DWORD dwClsContext, LPUNKNOWN* ppUnk);
81 static void COM_RevokeAllClasses(void);
82 static HRESULT get_inproc_class_object(HKEY hkeydll, REFCLSID rclsid, REFIID riid, void **ppv);
84 static APARTMENT *MTA; /* protected by csApartment */
85 static APARTMENT *MainApartment; /* the first STA apartment */
86 static struct list apts = LIST_INIT( apts ); /* protected by csApartment */
88 static CRITICAL_SECTION csApartment;
89 static CRITICAL_SECTION_DEBUG critsect_debug =
92 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
93 0, 0, { (DWORD_PTR)(__FILE__ ": csApartment") }
95 static CRITICAL_SECTION csApartment = { &critsect_debug, -1, 0, 0, 0, 0 };
97 struct registered_psclsid
105 * This lock count counts the number of times CoInitialize is called. It is
106 * decreased every time CoUninitialize is called. When it hits 0, the COM
107 * libraries are freed
109 static LONG s_COMLockCount = 0;
112 * This linked list contains the list of registered class objects. These
113 * are mostly used to register the factories for out-of-proc servers of OLE
116 * TODO: Make this data structure aware of inter-process communication. This
117 * means that parts of this will be exported to the Wine Server.
119 typedef struct tagRegisteredClass
121 CLSID classIdentifier;
122 LPUNKNOWN classObject;
126 LPSTREAM pMarshaledData; /* FIXME: only really need to store OXID and IPID */
127 struct tagRegisteredClass* nextClass;
130 static RegisteredClass* firstRegisteredClass = NULL;
132 static CRITICAL_SECTION csRegisteredClassList;
133 static CRITICAL_SECTION_DEBUG class_cs_debug =
135 0, 0, &csRegisteredClassList,
136 { &class_cs_debug.ProcessLocksList, &class_cs_debug.ProcessLocksList },
137 0, 0, { (DWORD_PTR)(__FILE__ ": csRegisteredClassList") }
139 static CRITICAL_SECTION csRegisteredClassList = { &class_cs_debug, -1, 0, 0, 0, 0 };
141 /*****************************************************************************
142 * This section contains OpenDllList definitions
144 * The OpenDllList contains only handles of dll loaded by CoGetClassObject or
145 * other functions that do LoadLibrary _without_ giving back a HMODULE.
146 * Without this list these handles would never be freed.
148 * FIXME: a DLL that says OK when asked for unloading is unloaded in the
149 * next unload-call but not before 600 sec.
152 typedef struct tagOpenDll {
154 struct tagOpenDll *next;
157 static OpenDll *openDllList = NULL; /* linked list of open dlls */
159 static CRITICAL_SECTION csOpenDllList;
160 static CRITICAL_SECTION_DEBUG dll_cs_debug =
162 0, 0, &csOpenDllList,
163 { &dll_cs_debug.ProcessLocksList, &dll_cs_debug.ProcessLocksList },
164 0, 0, { (DWORD_PTR)(__FILE__ ": csOpenDllList") }
166 static CRITICAL_SECTION csOpenDllList = { &dll_cs_debug, -1, 0, 0, 0, 0 };
168 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',' ',
169 '0','x','#','#','#','#','#','#','#','#',' ',0};
170 static LRESULT CALLBACK apartment_wndproc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
172 static void COMPOBJ_DLLList_Add(HANDLE hLibrary);
173 static void COMPOBJ_DllList_FreeUnused(int Timeout);
175 static void COMPOBJ_InitProcess( void )
179 /* Dispatching to the correct thread in an apartment is done through
180 * window messages rather than RPC transports. When an interface is
181 * marshalled into another apartment in the same process, a window of the
182 * following class is created. The *caller* of CoMarshalInterface (ie the
183 * application) is responsible for pumping the message loop in that thread.
184 * The WM_USER messages which point to the RPCs are then dispatched to
185 * COM_AptWndProc by the user's code from the apartment in which the interface
188 memset(&wclass, 0, sizeof(wclass));
189 wclass.lpfnWndProc = apartment_wndproc;
190 wclass.hInstance = OLE32_hInstance;
191 wclass.lpszClassName = wszAptWinClass;
192 RegisterClassW(&wclass);
195 static void COMPOBJ_UninitProcess( void )
197 UnregisterClassW(wszAptWinClass, OLE32_hInstance);
200 static void COM_TlsDestroy(void)
202 struct oletls *info = NtCurrentTeb()->ReservedForOle;
205 if (info->apt) apartment_release(info->apt);
206 if (info->errorinfo) IErrorInfo_Release(info->errorinfo);
207 if (info->state) IUnknown_Release(info->state);
208 HeapFree(GetProcessHeap(), 0, info);
209 NtCurrentTeb()->ReservedForOle = NULL;
213 /******************************************************************************
217 /* allocates memory and fills in the necessary fields for a new apartment
218 * object. must be called inside apartment cs */
219 static APARTMENT *apartment_construct(DWORD model)
223 TRACE("creating new apartment, model=%d\n", model);
225 apt = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*apt));
226 apt->tid = GetCurrentThreadId();
228 list_init(&apt->proxies);
229 list_init(&apt->stubmgrs);
230 list_init(&apt->psclsids);
233 apt->remunk_exported = FALSE;
235 InitializeCriticalSection(&apt->cs);
236 DEBUG_SET_CRITSEC_NAME(&apt->cs, "apartment");
238 apt->multi_threaded = !(model & COINIT_APARTMENTTHREADED);
240 if (apt->multi_threaded)
242 /* FIXME: should be randomly generated by in an RPC call to rpcss */
243 apt->oxid = ((OXID)GetCurrentProcessId() << 32) | 0xcafe;
247 /* FIXME: should be randomly generated by in an RPC call to rpcss */
248 apt->oxid = ((OXID)GetCurrentProcessId() << 32) | GetCurrentThreadId();
251 TRACE("Created apartment on OXID %s\n", wine_dbgstr_longlong(apt->oxid));
253 list_add_head(&apts, &apt->entry);
258 /* gets and existing apartment if one exists or otherwise creates an apartment
259 * structure which stores OLE apartment-local information and stores a pointer
260 * to it in the thread-local storage */
261 static APARTMENT *apartment_get_or_create(DWORD model)
263 APARTMENT *apt = COM_CurrentApt();
267 if (model & COINIT_APARTMENTTHREADED)
269 EnterCriticalSection(&csApartment);
271 apt = apartment_construct(model);
276 TRACE("Created main-threaded apartment with OXID %s\n", wine_dbgstr_longlong(apt->oxid));
279 LeaveCriticalSection(&csApartment);
283 EnterCriticalSection(&csApartment);
285 /* The multi-threaded apartment (MTA) contains zero or more threads interacting
286 * with free threaded (ie thread safe) COM objects. There is only ever one MTA
290 TRACE("entering the multithreaded apartment %s\n", wine_dbgstr_longlong(MTA->oxid));
291 apartment_addref(MTA);
294 MTA = apartment_construct(model);
298 LeaveCriticalSection(&csApartment);
300 COM_CurrentInfo()->apt = apt;
306 static inline BOOL apartment_is_model(APARTMENT *apt, DWORD model)
308 return (apt->multi_threaded == !(model & COINIT_APARTMENTTHREADED));
311 DWORD apartment_addref(struct apartment *apt)
313 DWORD refs = InterlockedIncrement(&apt->refs);
314 TRACE("%s: before = %d\n", wine_dbgstr_longlong(apt->oxid), refs - 1);
318 DWORD apartment_release(struct apartment *apt)
322 EnterCriticalSection(&csApartment);
324 ret = InterlockedDecrement(&apt->refs);
325 TRACE("%s: after = %d\n", wine_dbgstr_longlong(apt->oxid), ret);
326 /* destruction stuff that needs to happen under csApartment CS */
329 if (apt == MTA) MTA = NULL;
330 else if (apt == MainApartment) MainApartment = NULL;
331 list_remove(&apt->entry);
334 LeaveCriticalSection(&csApartment);
338 struct list *cursor, *cursor2;
340 TRACE("destroying apartment %p, oxid %s\n", apt, wine_dbgstr_longlong(apt->oxid));
342 /* no locking is needed for this apartment, because no other thread
343 * can access it at this point */
345 apartment_disconnectproxies(apt);
347 if (apt->win) DestroyWindow(apt->win);
349 LIST_FOR_EACH_SAFE(cursor, cursor2, &apt->stubmgrs)
351 struct stub_manager *stubmgr = LIST_ENTRY(cursor, struct stub_manager, entry);
352 /* release the implicit reference given by the fact that the
353 * stub has external references (it must do since it is in the
354 * stub manager list in the apartment and all non-apartment users
355 * must have a ref on the apartment and so it cannot be destroyed).
357 stub_manager_int_release(stubmgr);
360 LIST_FOR_EACH_SAFE(cursor, cursor2, &apt->psclsids)
362 struct registered_psclsid *registered_psclsid =
363 LIST_ENTRY(cursor, struct registered_psclsid, entry);
365 list_remove(®istered_psclsid->entry);
366 HeapFree(GetProcessHeap(), 0, registered_psclsid);
369 /* if this assert fires, then another thread took a reference to a
370 * stub manager without taking a reference to the containing
371 * apartment, which it must do. */
372 assert(list_empty(&apt->stubmgrs));
374 if (apt->filter) IUnknown_Release(apt->filter);
376 DEBUG_CLEAR_CRITSEC_NAME(&apt->cs);
377 DeleteCriticalSection(&apt->cs);
379 HeapFree(GetProcessHeap(), 0, apt);
385 /* The given OXID must be local to this process:
387 * The ref parameter is here mostly to ensure people remember that
388 * they get one, you should normally take a ref for thread safety.
390 APARTMENT *apartment_findfromoxid(OXID oxid, BOOL ref)
392 APARTMENT *result = NULL;
395 EnterCriticalSection(&csApartment);
396 LIST_FOR_EACH( cursor, &apts )
398 struct apartment *apt = LIST_ENTRY( cursor, struct apartment, entry );
399 if (apt->oxid == oxid)
402 if (ref) apartment_addref(result);
406 LeaveCriticalSection(&csApartment);
411 /* gets the apartment which has a given creator thread ID. The caller must
412 * release the reference from the apartment as soon as the apartment pointer
413 * is no longer required. */
414 APARTMENT *apartment_findfromtid(DWORD tid)
416 APARTMENT *result = NULL;
419 EnterCriticalSection(&csApartment);
420 LIST_FOR_EACH( cursor, &apts )
422 struct apartment *apt = LIST_ENTRY( cursor, struct apartment, entry );
426 apartment_addref(result);
430 LeaveCriticalSection(&csApartment);
435 /* gets an apartment which has a given type. The caller must
436 * release the reference from the apartment as soon as the apartment pointer
437 * is no longer required. */
438 static APARTMENT *apartment_findfromtype(BOOL multi_threaded, BOOL main_apartment)
440 APARTMENT *result = NULL;
441 struct apartment *apt;
443 EnterCriticalSection(&csApartment);
445 if (!multi_threaded && main_apartment)
447 result = MainApartment;
448 if (result) apartment_addref(result);
449 LeaveCriticalSection(&csApartment);
453 LIST_FOR_EACH_ENTRY( apt, &apts, struct apartment, entry )
455 if (apt->multi_threaded == multi_threaded)
458 apartment_addref(result);
462 LeaveCriticalSection(&csApartment);
467 struct host_object_params
470 CLSID clsid; /* clsid of object to marshal */
471 IID iid; /* interface to marshal */
472 IStream *stream; /* stream that the object will be marshaled into */
475 static HRESULT apartment_hostobject(const struct host_object_params *params)
479 static const LARGE_INTEGER llZero;
483 hr = get_inproc_class_object(params->hkeydll, ¶ms->clsid, ¶ms->iid, (void **)&object);
487 hr = CoMarshalInterface(params->stream, ¶ms->iid, object, MSHCTX_INPROC, NULL, MSHLFLAGS_NORMAL);
489 IUnknown_Release(object);
490 IStream_Seek(params->stream, llZero, STREAM_SEEK_SET, NULL);
495 static LRESULT CALLBACK apartment_wndproc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
500 RPC_ExecuteCall((struct dispatch_params *)lParam);
503 return apartment_hostobject((const struct host_object_params *)lParam);
505 return DefWindowProcW(hWnd, msg, wParam, lParam);
509 HRESULT apartment_createwindowifneeded(struct apartment *apt)
511 if (apt->multi_threaded)
516 HWND hwnd = CreateWindowW(wszAptWinClass, NULL, 0,
518 0, 0, OLE32_hInstance, NULL);
521 ERR("CreateWindow failed with error %d\n", GetLastError());
522 return HRESULT_FROM_WIN32(GetLastError());
524 if (InterlockedCompareExchangePointer((PVOID *)&apt->win, hwnd, NULL))
525 /* someone beat us to it */
532 HWND apartment_getwindow(struct apartment *apt)
534 assert(!apt->multi_threaded);
538 void apartment_joinmta(void)
540 apartment_addref(MTA);
541 COM_CurrentInfo()->apt = MTA;
544 /*****************************************************************************
545 * This section contains OpenDllList implementation
548 static void COMPOBJ_DLLList_Add(HANDLE hLibrary)
555 EnterCriticalSection( &csOpenDllList );
557 if (openDllList == NULL) {
558 /* empty list -- add first node */
559 openDllList = HeapAlloc(GetProcessHeap(),0, sizeof(OpenDll));
560 openDllList->hLibrary=hLibrary;
561 openDllList->next = NULL;
563 /* search for this dll */
565 for (ptr = openDllList; ptr->next != NULL; ptr=ptr->next) {
566 if (ptr->hLibrary == hLibrary) {
572 /* dll not found, add it */
574 openDllList = HeapAlloc(GetProcessHeap(),0, sizeof(OpenDll));
575 openDllList->hLibrary = hLibrary;
576 openDllList->next = tmp;
580 LeaveCriticalSection( &csOpenDllList );
583 static void COMPOBJ_DllList_FreeUnused(int Timeout)
585 OpenDll *curr, *next, *prev = NULL;
586 typedef HRESULT (WINAPI *DllCanUnloadNowFunc)(void);
587 DllCanUnloadNowFunc DllCanUnloadNow;
591 EnterCriticalSection( &csOpenDllList );
593 for (curr = openDllList; curr != NULL; ) {
594 DllCanUnloadNow = (DllCanUnloadNowFunc) GetProcAddress(curr->hLibrary, "DllCanUnloadNow");
596 if ( (DllCanUnloadNow != NULL) && (DllCanUnloadNow() == S_OK) ) {
599 TRACE("freeing %p\n", curr->hLibrary);
600 FreeLibrary(curr->hLibrary);
602 HeapFree(GetProcessHeap(), 0, curr);
603 if (curr == openDllList) {
616 LeaveCriticalSection( &csOpenDllList );
619 /******************************************************************************
620 * CoBuildVersion [OLE32.@]
621 * CoBuildVersion [COMPOBJ.1]
623 * Gets the build version of the DLL.
628 * Current build version, hiword is majornumber, loword is minornumber
630 DWORD WINAPI CoBuildVersion(void)
632 TRACE("Returning version %d, build %d.\n", rmm, rup);
633 return (rmm<<16)+rup;
636 /******************************************************************************
637 * CoInitialize [OLE32.@]
639 * Initializes the COM libraries by calling CoInitializeEx with
640 * COINIT_APARTMENTTHREADED, ie it enters a STA thread.
643 * lpReserved [I] Pointer to IMalloc interface (obsolete, should be NULL).
646 * Success: S_OK if not already initialized, S_FALSE otherwise.
647 * Failure: HRESULT code.
652 HRESULT WINAPI CoInitialize(LPVOID lpReserved)
655 * Just delegate to the newer method.
657 return CoInitializeEx(lpReserved, COINIT_APARTMENTTHREADED);
660 /******************************************************************************
661 * CoInitializeEx [OLE32.@]
663 * Initializes the COM libraries.
666 * lpReserved [I] Pointer to IMalloc interface (obsolete, should be NULL).
667 * dwCoInit [I] One or more flags from the COINIT enumeration. See notes.
670 * S_OK if successful,
671 * S_FALSE if this function was called already.
672 * RPC_E_CHANGED_MODE if a previous call to CoInitializeEx specified another
677 * The behavior used to set the IMalloc used for memory management is
679 * The dwCoInit parameter must specify one of the following apartment
681 *| COINIT_APARTMENTTHREADED - A single-threaded apartment (STA).
682 *| COINIT_MULTITHREADED - A multi-threaded apartment (MTA).
683 * The parameter may also specify zero or more of the following flags:
684 *| COINIT_DISABLE_OLE1DDE - Don't use DDE for OLE1 support.
685 *| COINIT_SPEED_OVER_MEMORY - Trade memory for speed.
690 HRESULT WINAPI CoInitializeEx(LPVOID lpReserved, DWORD dwCoInit)
695 TRACE("(%p, %x)\n", lpReserved, (int)dwCoInit);
697 if (lpReserved!=NULL)
699 ERR("(%p, %x) - Bad parameter passed-in %p, must be an old Windows Application\n", lpReserved, (int)dwCoInit, lpReserved);
703 * Check the lock count. If this is the first time going through the initialize
704 * process, we have to initialize the libraries.
706 * And crank-up that lock count.
708 if (InterlockedExchangeAdd(&s_COMLockCount,1)==0)
711 * Initialize the various COM libraries and data structures.
713 TRACE("() - Initializing the COM libraries\n");
715 /* we may need to defer this until after apartment initialisation */
716 RunningObjectTableImpl_Initialize();
719 if (!(apt = COM_CurrentInfo()->apt))
721 apt = apartment_get_or_create(dwCoInit);
722 if (!apt) return E_OUTOFMEMORY;
724 else if (!apartment_is_model(apt, dwCoInit))
726 /* Changing the threading model after it's been set is illegal. If this warning is triggered by Wine
727 code then we are probably using the wrong threading model to implement that API. */
728 ERR("Attempt to change threading model of this apartment from %s to %s\n",
729 apt->multi_threaded ? "multi-threaded" : "apartment threaded",
730 dwCoInit & COINIT_APARTMENTTHREADED ? "apartment threaded" : "multi-threaded");
731 return RPC_E_CHANGED_MODE;
736 COM_CurrentInfo()->inits++;
741 /* On COM finalization for a STA thread, the message queue is flushed to ensure no
742 pending RPCs are ignored. Non-COM messages are discarded at this point.
744 static void COM_FlushMessageQueue(void)
747 APARTMENT *apt = COM_CurrentApt();
749 if (!apt || !apt->win) return;
751 TRACE("Flushing STA message queue\n");
753 while (PeekMessageA(&message, NULL, 0, 0, PM_REMOVE))
755 if (message.hwnd != apt->win)
757 WARN("discarding message 0x%x for window %p\n", message.message, message.hwnd);
761 TranslateMessage(&message);
762 DispatchMessageA(&message);
766 /***********************************************************************
767 * CoUninitialize [OLE32.@]
769 * This method will decrement the refcount on the current apartment, freeing
770 * the resources associated with it if it is the last thread in the apartment.
771 * If the last apartment is freed, the function will additionally release
772 * any COM resources associated with the process.
782 void WINAPI CoUninitialize(void)
784 struct oletls * info = COM_CurrentInfo();
789 /* will only happen on OOM */
795 ERR("Mismatched CoUninitialize\n");
801 apartment_release(info->apt);
806 * Decrease the reference count.
807 * If we are back to 0 locks on the COM library, make sure we free
808 * all the associated data structures.
810 lCOMRefCnt = InterlockedExchangeAdd(&s_COMLockCount,-1);
813 TRACE("() - Releasing the COM libraries\n");
815 RunningObjectTableImpl_UnInitialize();
817 /* Release the references to the registered class objects */
818 COM_RevokeAllClasses();
820 /* This will free the loaded COM Dlls */
821 CoFreeAllLibraries();
823 /* This ensures we deal with any pending RPCs */
824 COM_FlushMessageQueue();
826 else if (lCOMRefCnt<1) {
827 ERR( "CoUninitialize() - not CoInitialized.\n" );
828 InterlockedExchangeAdd(&s_COMLockCount,1); /* restore the lock count. */
832 /******************************************************************************
833 * CoDisconnectObject [OLE32.@]
834 * CoDisconnectObject [COMPOBJ.15]
836 * Disconnects all connections to this object from remote processes. Dispatches
837 * pending RPCs while blocking new RPCs from occurring, and then calls
838 * IMarshal::DisconnectObject on the given object.
840 * Typically called when the object server is forced to shut down, for instance by
844 * lpUnk [I] The object whose stub should be disconnected.
845 * reserved [I] Reserved. Should be set to 0.
849 * Failure: HRESULT code.
852 * CoMarshalInterface, CoReleaseMarshalData, CoLockObjectExternal
854 HRESULT WINAPI CoDisconnectObject( LPUNKNOWN lpUnk, DWORD reserved )
860 TRACE("(%p, 0x%08x)\n", lpUnk, reserved);
862 hr = IUnknown_QueryInterface(lpUnk, &IID_IMarshal, (void **)&marshal);
865 hr = IMarshal_DisconnectObject(marshal, reserved);
866 IMarshal_Release(marshal);
870 apt = COM_CurrentApt();
872 return CO_E_NOTINITIALIZED;
874 apartment_disconnectobject(apt, lpUnk);
876 /* Note: native is pretty broken here because it just silently
877 * fails, without returning an appropriate error code if the object was
878 * not found, making apps think that the object was disconnected, when
879 * it actually wasn't */
884 /******************************************************************************
885 * CoCreateGuid [OLE32.@]
887 * Simply forwards to UuidCreate in RPCRT4.
890 * pguid [O] Points to the GUID to initialize.
894 * Failure: HRESULT code.
899 HRESULT WINAPI CoCreateGuid(GUID *pguid)
901 return UuidCreate(pguid);
904 /******************************************************************************
905 * CLSIDFromString [OLE32.@]
906 * IIDFromString [OLE32.@]
908 * Converts a unique identifier from its string representation into
912 * idstr [I] The string representation of the GUID.
913 * id [O] GUID converted from the string.
917 * CO_E_CLASSSTRING if idstr is not a valid CLSID
922 static HRESULT WINAPI __CLSIDFromString(LPCWSTR s, CLSID *id)
928 memset( id, 0, sizeof (CLSID) );
932 /* validate the CLSID string */
933 if (strlenW(s) != 38)
934 return CO_E_CLASSSTRING;
936 if ((s[0]!='{') || (s[9]!='-') || (s[14]!='-') || (s[19]!='-') || (s[24]!='-') || (s[37]!='}'))
937 return CO_E_CLASSSTRING;
939 for (i=1; i<37; i++) {
940 if ((i == 9)||(i == 14)||(i == 19)||(i == 24)) continue;
941 if (!(((s[i] >= '0') && (s[i] <= '9')) ||
942 ((s[i] >= 'a') && (s[i] <= 'f')) ||
943 ((s[i] >= 'A') && (s[i] <= 'F'))))
944 return CO_E_CLASSSTRING;
947 TRACE("%s -> %p\n", debugstr_w(s), id);
949 /* quick lookup table */
950 memset(table, 0, 256);
952 for (i = 0; i < 10; i++) {
955 for (i = 0; i < 6; i++) {
956 table['A' + i] = i+10;
957 table['a' + i] = i+10;
960 /* in form {XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX} */
962 id->Data1 = (table[s[1]] << 28 | table[s[2]] << 24 | table[s[3]] << 20 | table[s[4]] << 16 |
963 table[s[5]] << 12 | table[s[6]] << 8 | table[s[7]] << 4 | table[s[8]]);
964 id->Data2 = table[s[10]] << 12 | table[s[11]] << 8 | table[s[12]] << 4 | table[s[13]];
965 id->Data3 = table[s[15]] << 12 | table[s[16]] << 8 | table[s[17]] << 4 | table[s[18]];
967 /* these are just sequential bytes */
968 id->Data4[0] = table[s[20]] << 4 | table[s[21]];
969 id->Data4[1] = table[s[22]] << 4 | table[s[23]];
970 id->Data4[2] = table[s[25]] << 4 | table[s[26]];
971 id->Data4[3] = table[s[27]] << 4 | table[s[28]];
972 id->Data4[4] = table[s[29]] << 4 | table[s[30]];
973 id->Data4[5] = table[s[31]] << 4 | table[s[32]];
974 id->Data4[6] = table[s[33]] << 4 | table[s[34]];
975 id->Data4[7] = table[s[35]] << 4 | table[s[36]];
980 /*****************************************************************************/
982 HRESULT WINAPI CLSIDFromString(LPOLESTR idstr, CLSID *id )
989 ret = __CLSIDFromString(idstr, id);
990 if(ret != S_OK) { /* It appears a ProgID is also valid */
991 ret = CLSIDFromProgID(idstr, id);
996 /* Converts a GUID into the respective string representation. */
997 HRESULT WINE_StringFromCLSID(
998 const CLSID *id, /* [in] GUID to be converted */
999 LPSTR idstr /* [out] pointer to buffer to contain converted guid */
1001 static const char hex[] = "0123456789ABCDEF";
1006 { ERR("called with id=Null\n");
1011 sprintf(idstr, "{%08X-%04X-%04X-%02X%02X-",
1012 id->Data1, id->Data2, id->Data3,
1013 id->Data4[0], id->Data4[1]);
1017 for (i = 2; i < 8; i++) {
1018 *s++ = hex[id->Data4[i]>>4];
1019 *s++ = hex[id->Data4[i] & 0xf];
1025 TRACE("%p->%s\n", id, idstr);
1031 /******************************************************************************
1032 * StringFromCLSID [OLE32.@]
1033 * StringFromIID [OLE32.@]
1035 * Converts a GUID into the respective string representation.
1036 * The target string is allocated using the OLE IMalloc.
1039 * id [I] the GUID to be converted.
1040 * idstr [O] A pointer to a to-be-allocated pointer pointing to the resulting string.
1047 * StringFromGUID2, CLSIDFromString
1049 HRESULT WINAPI StringFromCLSID(REFCLSID id, LPOLESTR *idstr)
1055 if ((ret = CoGetMalloc(0,&mllc)))
1058 ret=WINE_StringFromCLSID(id,buf);
1060 DWORD len = MultiByteToWideChar( CP_ACP, 0, buf, -1, NULL, 0 );
1061 *idstr = IMalloc_Alloc( mllc, len * sizeof(WCHAR) );
1062 MultiByteToWideChar( CP_ACP, 0, buf, -1, *idstr, len );
1067 /******************************************************************************
1068 * StringFromGUID2 [OLE32.@]
1069 * StringFromGUID2 [COMPOBJ.76]
1071 * Modified version of StringFromCLSID that allows you to specify max
1075 * id [I] GUID to convert to string.
1076 * str [O] Buffer where the result will be stored.
1077 * cmax [I] Size of the buffer in characters.
1080 * Success: The length of the resulting string in characters.
1083 INT WINAPI StringFromGUID2(REFGUID id, LPOLESTR str, INT cmax)
1087 if (WINE_StringFromCLSID(id,xguid))
1089 return MultiByteToWideChar( CP_ACP, 0, xguid, -1, str, cmax );
1092 /* open HKCR\\CLSID\\{string form of clsid}\\{keyname} key */
1093 HRESULT COM_OpenKeyForCLSID(REFCLSID clsid, LPCWSTR keyname, REGSAM access, HKEY *subkey)
1095 static const WCHAR wszCLSIDSlash[] = {'C','L','S','I','D','\\',0};
1096 WCHAR path[CHARS_IN_GUID + ARRAYSIZE(wszCLSIDSlash) - 1];
1100 strcpyW(path, wszCLSIDSlash);
1101 StringFromGUID2(clsid, path + strlenW(wszCLSIDSlash), CHARS_IN_GUID);
1102 res = RegOpenKeyExW(HKEY_CLASSES_ROOT, path, 0, keyname ? KEY_READ : access, &key);
1103 if (res == ERROR_FILE_NOT_FOUND)
1104 return REGDB_E_CLASSNOTREG;
1105 else if (res != ERROR_SUCCESS)
1106 return REGDB_E_READREGDB;
1114 res = RegOpenKeyExW(key, keyname, 0, access, subkey);
1116 if (res == ERROR_FILE_NOT_FOUND)
1117 return REGDB_E_KEYMISSING;
1118 else if (res != ERROR_SUCCESS)
1119 return REGDB_E_READREGDB;
1124 /* open HKCR\\AppId\\{string form of appid clsid} key */
1125 HRESULT COM_OpenKeyForAppIdFromCLSID(REFCLSID clsid, REGSAM access, HKEY *subkey)
1127 static const WCHAR szAppId[] = { 'A','p','p','I','d',0 };
1128 static const WCHAR szAppIdKey[] = { 'A','p','p','I','d','\\',0 };
1130 WCHAR buf[CHARS_IN_GUID];
1131 WCHAR keyname[ARRAYSIZE(szAppIdKey) + CHARS_IN_GUID];
1137 /* read the AppID value under the class's key */
1138 hr = COM_OpenKeyForCLSID(clsid, NULL, KEY_READ, &hkey);
1143 res = RegQueryValueExW(hkey, szAppId, NULL, &type, (LPBYTE)buf, &size);
1145 if (res == ERROR_FILE_NOT_FOUND)
1146 return REGDB_E_KEYMISSING;
1147 else if (res != ERROR_SUCCESS || type!=REG_SZ)
1148 return REGDB_E_READREGDB;
1150 strcpyW(keyname, szAppIdKey);
1151 strcatW(keyname, buf);
1152 res = RegOpenKeyExW(HKEY_CLASSES_ROOT, keyname, 0, access, subkey);
1153 if (res == ERROR_FILE_NOT_FOUND)
1154 return REGDB_E_KEYMISSING;
1155 else if (res != ERROR_SUCCESS)
1156 return REGDB_E_READREGDB;
1161 /******************************************************************************
1162 * ProgIDFromCLSID [OLE32.@]
1164 * Converts a class id into the respective program ID.
1167 * clsid [I] Class ID, as found in registry.
1168 * ppszProgID [O] Associated ProgID.
1173 * REGDB_E_CLASSNOTREG if the given clsid has no associated ProgID
1175 HRESULT WINAPI ProgIDFromCLSID(REFCLSID clsid, LPOLESTR *ppszProgID)
1177 static const WCHAR wszProgID[] = {'P','r','o','g','I','D',0};
1184 ERR("ppszProgId isn't optional\n");
1185 return E_INVALIDARG;
1189 ret = COM_OpenKeyForCLSID(clsid, wszProgID, KEY_READ, &hkey);
1193 if (RegQueryValueW(hkey, NULL, NULL, &progidlen))
1194 ret = REGDB_E_CLASSNOTREG;
1198 *ppszProgID = CoTaskMemAlloc(progidlen * sizeof(WCHAR));
1201 if (RegQueryValueW(hkey, NULL, *ppszProgID, &progidlen))
1202 ret = REGDB_E_CLASSNOTREG;
1205 ret = E_OUTOFMEMORY;
1212 /******************************************************************************
1213 * CLSIDFromProgID [OLE32.@]
1215 * Converts a program id into the respective GUID.
1218 * progid [I] Unicode program ID, as found in registry.
1219 * clsid [O] Associated CLSID.
1223 * Failure: CO_E_CLASSSTRING - the given ProgID cannot be found.
1225 HRESULT WINAPI CLSIDFromProgID(LPCOLESTR progid, LPCLSID clsid)
1227 static const WCHAR clsidW[] = { '\\','C','L','S','I','D',0 };
1228 WCHAR buf2[CHARS_IN_GUID];
1229 LONG buf2len = sizeof(buf2);
1233 if (!progid || !clsid)
1235 ERR("neither progid (%p) nor clsid (%p) are optional\n", progid, clsid);
1236 return E_INVALIDARG;
1239 /* initialise clsid in case of failure */
1240 memset(clsid, 0, sizeof(*clsid));
1242 buf = HeapAlloc( GetProcessHeap(),0,(strlenW(progid)+8) * sizeof(WCHAR) );
1243 strcpyW( buf, progid );
1244 strcatW( buf, clsidW );
1245 if (RegOpenKeyW(HKEY_CLASSES_ROOT,buf,&xhkey))
1247 HeapFree(GetProcessHeap(),0,buf);
1248 return CO_E_CLASSSTRING;
1250 HeapFree(GetProcessHeap(),0,buf);
1252 if (RegQueryValueW(xhkey,NULL,buf2,&buf2len))
1255 return CO_E_CLASSSTRING;
1258 return CLSIDFromString(buf2,clsid);
1262 /*****************************************************************************
1263 * CoGetPSClsid [OLE32.@]
1265 * Retrieves the CLSID of the proxy/stub factory that implements
1266 * IPSFactoryBuffer for the specified interface.
1269 * riid [I] Interface whose proxy/stub CLSID is to be returned.
1270 * pclsid [O] Where to store returned proxy/stub CLSID.
1275 * REGDB_E_IIDNOTREG if no PSFactoryBuffer is associated with the IID, or it could not be parsed
1279 * The standard marshaller activates the object with the CLSID
1280 * returned and uses the CreateProxy and CreateStub methods on its
1281 * IPSFactoryBuffer interface to construct the proxies and stubs for a
1284 * CoGetPSClsid determines this CLSID by searching the
1285 * HKEY_CLASSES_ROOT\Interface\{string form of riid}\ProxyStubClsid32
1286 * in the registry and any interface id registered by
1287 * CoRegisterPSClsid within the current process.
1291 * Native returns S_OK for interfaces with a key in HKCR\Interface, but
1292 * without a ProxyStubClsid32 key and leaves garbage in pclsid. This should be
1293 * considered a bug in native unless an application depends on this (unlikely).
1296 * CoRegisterPSClsid.
1298 HRESULT WINAPI CoGetPSClsid(REFIID riid, CLSID *pclsid)
1300 static const WCHAR wszInterface[] = {'I','n','t','e','r','f','a','c','e','\\',0};
1301 static const WCHAR wszPSC[] = {'\\','P','r','o','x','y','S','t','u','b','C','l','s','i','d','3','2',0};
1302 WCHAR path[ARRAYSIZE(wszInterface) - 1 + CHARS_IN_GUID - 1 + ARRAYSIZE(wszPSC)];
1303 WCHAR value[CHARS_IN_GUID];
1306 APARTMENT *apt = COM_CurrentApt();
1307 struct registered_psclsid *registered_psclsid;
1309 TRACE("() riid=%s, pclsid=%p\n", debugstr_guid(riid), pclsid);
1313 ERR("apartment not initialised\n");
1314 return CO_E_NOTINITIALIZED;
1319 ERR("pclsid isn't optional\n");
1320 return E_INVALIDARG;
1323 EnterCriticalSection(&apt->cs);
1325 LIST_FOR_EACH_ENTRY(registered_psclsid, &apt->psclsids, struct registered_psclsid, entry)
1326 if (IsEqualIID(®istered_psclsid->iid, riid))
1328 *pclsid = registered_psclsid->clsid;
1329 LeaveCriticalSection(&apt->cs);
1333 LeaveCriticalSection(&apt->cs);
1335 /* Interface\\{string form of riid}\\ProxyStubClsid32 */
1336 strcpyW(path, wszInterface);
1337 StringFromGUID2(riid, path + ARRAYSIZE(wszInterface) - 1, CHARS_IN_GUID);
1338 strcpyW(path + ARRAYSIZE(wszInterface) - 1 + CHARS_IN_GUID - 1, wszPSC);
1340 /* Open the key.. */
1341 if (RegOpenKeyExW(HKEY_CLASSES_ROOT, path, 0, KEY_READ, &hkey))
1343 WARN("No PSFactoryBuffer object is registered for IID %s\n", debugstr_guid(riid));
1344 return REGDB_E_IIDNOTREG;
1347 /* ... Once we have the key, query the registry to get the
1348 value of CLSID as a string, and convert it into a
1349 proper CLSID structure to be passed back to the app */
1350 len = sizeof(value);
1351 if (ERROR_SUCCESS != RegQueryValueW(hkey, NULL, value, &len))
1354 return REGDB_E_IIDNOTREG;
1358 /* We have the CLSid we want back from the registry as a string, so
1359 lets convert it into a CLSID structure */
1360 if (CLSIDFromString(value, pclsid) != NOERROR)
1361 return REGDB_E_IIDNOTREG;
1363 TRACE ("() Returning CLSID=%s\n", debugstr_guid(pclsid));
1367 /*****************************************************************************
1368 * CoRegisterPSClsid [OLE32.@]
1370 * Register a proxy/stub CLSID for the given interface in the current process
1374 * riid [I] Interface whose proxy/stub CLSID is to be registered.
1375 * rclsid [I] CLSID of the proxy/stub.
1379 * Failure: E_OUTOFMEMORY
1383 * This function does not add anything to the registry and the effects are
1384 * limited to the lifetime of the current process.
1389 HRESULT WINAPI CoRegisterPSClsid(REFIID riid, REFCLSID rclsid)
1391 APARTMENT *apt = COM_CurrentApt();
1392 struct registered_psclsid *registered_psclsid;
1394 TRACE("(%s, %s)\n", debugstr_guid(riid), debugstr_guid(rclsid));
1398 ERR("apartment not initialised\n");
1399 return CO_E_NOTINITIALIZED;
1402 EnterCriticalSection(&apt->cs);
1404 LIST_FOR_EACH_ENTRY(registered_psclsid, &apt->psclsids, struct registered_psclsid, entry)
1405 if (IsEqualIID(®istered_psclsid->iid, riid))
1407 registered_psclsid->clsid = *rclsid;
1408 LeaveCriticalSection(&apt->cs);
1412 registered_psclsid = HeapAlloc(GetProcessHeap(), 0, sizeof(struct registered_psclsid));
1413 if (!registered_psclsid)
1415 LeaveCriticalSection(&apt->cs);
1416 return E_OUTOFMEMORY;
1419 registered_psclsid->iid = *riid;
1420 registered_psclsid->clsid = *rclsid;
1421 list_add_head(&apt->psclsids, ®istered_psclsid->entry);
1423 LeaveCriticalSection(&apt->cs);
1430 * COM_GetRegisteredClassObject
1432 * This internal method is used to scan the registered class list to
1433 * find a class object.
1436 * rclsid Class ID of the class to find.
1437 * dwClsContext Class context to match.
1438 * ppv [out] returns a pointer to the class object. Complying
1439 * to normal COM usage, this method will increase the
1440 * reference count on this object.
1442 static HRESULT COM_GetRegisteredClassObject(
1447 HRESULT hr = S_FALSE;
1448 RegisteredClass* curClass;
1450 EnterCriticalSection( &csRegisteredClassList );
1458 * Iterate through the whole list and try to match the class ID.
1460 curClass = firstRegisteredClass;
1462 while (curClass != 0)
1465 * Check if we have a match on the class ID.
1467 if (IsEqualGUID(&(curClass->classIdentifier), rclsid))
1470 * Since we don't do out-of process or DCOM just right away, let's ignore the
1475 * We have a match, return the pointer to the class object.
1477 *ppUnk = curClass->classObject;
1479 IUnknown_AddRef(curClass->classObject);
1486 * Step to the next class in the list.
1488 curClass = curClass->nextClass;
1492 LeaveCriticalSection( &csRegisteredClassList );
1494 * If we get to here, we haven't found our class.
1499 /******************************************************************************
1500 * CoRegisterClassObject [OLE32.@]
1502 * Registers the class object for a given class ID. Servers housed in EXE
1503 * files use this method instead of exporting DllGetClassObject to allow
1504 * other code to connect to their objects.
1507 * rclsid [I] CLSID of the object to register.
1508 * pUnk [I] IUnknown of the object.
1509 * dwClsContext [I] CLSCTX flags indicating the context in which to run the executable.
1510 * flags [I] REGCLS flags indicating how connections are made.
1511 * lpdwRegister [I] A unique cookie that can be passed to CoRevokeClassObject.
1515 * E_INVALIDARG if lpdwRegister or pUnk are NULL,
1516 * CO_E_OBJISREG if the object is already registered. We should not return this.
1519 * CoRevokeClassObject, CoGetClassObject
1522 * MSDN claims that multiple interface registrations are legal, but we
1523 * can't do that with our current implementation.
1525 HRESULT WINAPI CoRegisterClassObject(
1530 LPDWORD lpdwRegister)
1532 RegisteredClass* newClass;
1533 LPUNKNOWN foundObject;
1536 TRACE("(%s,%p,0x%08x,0x%08x,%p)\n",
1537 debugstr_guid(rclsid),pUnk,dwClsContext,flags,lpdwRegister);
1539 if ( (lpdwRegister==0) || (pUnk==0) )
1540 return E_INVALIDARG;
1542 if (!COM_CurrentApt())
1544 ERR("COM was not initialized\n");
1545 return CO_E_NOTINITIALIZED;
1551 * First, check if the class is already registered.
1552 * If it is, this should cause an error.
1554 hr = COM_GetRegisteredClassObject(rclsid, dwClsContext, &foundObject);
1556 if (flags & REGCLS_MULTIPLEUSE) {
1557 if (dwClsContext & CLSCTX_LOCAL_SERVER)
1558 hr = CoLockObjectExternal(foundObject, TRUE, FALSE);
1559 IUnknown_Release(foundObject);
1562 IUnknown_Release(foundObject);
1563 ERR("object already registered for class %s\n", debugstr_guid(rclsid));
1564 return CO_E_OBJISREG;
1567 newClass = HeapAlloc(GetProcessHeap(), 0, sizeof(RegisteredClass));
1568 if ( newClass == NULL )
1569 return E_OUTOFMEMORY;
1571 EnterCriticalSection( &csRegisteredClassList );
1573 newClass->classIdentifier = *rclsid;
1574 newClass->runContext = dwClsContext;
1575 newClass->connectFlags = flags;
1576 newClass->pMarshaledData = NULL;
1579 * Use the address of the chain node as the cookie since we are sure it's
1580 * unique. FIXME: not on 64-bit platforms.
1582 newClass->dwCookie = (DWORD)newClass;
1583 newClass->nextClass = firstRegisteredClass;
1586 * Since we're making a copy of the object pointer, we have to increase its
1589 newClass->classObject = pUnk;
1590 IUnknown_AddRef(newClass->classObject);
1592 firstRegisteredClass = newClass;
1593 LeaveCriticalSection( &csRegisteredClassList );
1595 *lpdwRegister = newClass->dwCookie;
1597 if (dwClsContext & CLSCTX_LOCAL_SERVER) {
1598 IClassFactory *classfac;
1600 hr = IUnknown_QueryInterface(newClass->classObject, &IID_IClassFactory,
1601 (LPVOID*)&classfac);
1604 hr = CreateStreamOnHGlobal(0, TRUE, &newClass->pMarshaledData);
1606 FIXME("Failed to create stream on hglobal, %x\n", hr);
1607 IUnknown_Release(classfac);
1610 hr = CoMarshalInterface(newClass->pMarshaledData, &IID_IClassFactory,
1611 (LPVOID)classfac, MSHCTX_LOCAL, NULL,
1612 MSHLFLAGS_TABLESTRONG);
1614 FIXME("CoMarshalInterface failed, %x!\n",hr);
1615 IUnknown_Release(classfac);
1619 IUnknown_Release(classfac);
1621 RPC_StartLocalServer(&newClass->classIdentifier, newClass->pMarshaledData);
1626 /***********************************************************************
1627 * CoRevokeClassObject [OLE32.@]
1629 * Removes a class object from the class registry.
1632 * dwRegister [I] Cookie returned from CoRegisterClassObject().
1636 * Failure: HRESULT code.
1639 * CoRegisterClassObject
1641 HRESULT WINAPI CoRevokeClassObject(
1644 HRESULT hr = E_INVALIDARG;
1645 RegisteredClass** prevClassLink;
1646 RegisteredClass* curClass;
1648 TRACE("(%08x)\n",dwRegister);
1650 EnterCriticalSection( &csRegisteredClassList );
1653 * Iterate through the whole list and try to match the cookie.
1655 curClass = firstRegisteredClass;
1656 prevClassLink = &firstRegisteredClass;
1658 while (curClass != 0)
1661 * Check if we have a match on the cookie.
1663 if (curClass->dwCookie == dwRegister)
1666 * Remove the class from the chain.
1668 *prevClassLink = curClass->nextClass;
1671 * Release the reference to the class object.
1673 IUnknown_Release(curClass->classObject);
1675 if (curClass->pMarshaledData)
1678 memset(&zero, 0, sizeof(zero));
1679 /* FIXME: stop local server thread */
1680 IStream_Seek(curClass->pMarshaledData, zero, SEEK_SET, NULL);
1681 CoReleaseMarshalData(curClass->pMarshaledData);
1685 * Free the memory used by the chain node.
1687 HeapFree(GetProcessHeap(), 0, curClass);
1694 * Step to the next class in the list.
1696 prevClassLink = &(curClass->nextClass);
1697 curClass = curClass->nextClass;
1701 LeaveCriticalSection( &csRegisteredClassList );
1703 * If we get to here, we haven't found our class.
1708 /***********************************************************************
1709 * COM_RegReadPath [internal]
1711 * Reads a registry value and expands it when necessary
1713 static DWORD COM_RegReadPath(HKEY hkeyroot, const WCHAR *keyname, const WCHAR *valuename, WCHAR * dst, DWORD dstlen)
1718 WCHAR src[MAX_PATH];
1719 DWORD dwLength = dstlen * sizeof(WCHAR);
1721 if((ret = RegOpenKeyExW(hkeyroot, keyname, 0, KEY_READ, &key)) == ERROR_SUCCESS) {
1722 if( (ret = RegQueryValueExW(key, NULL, NULL, &keytype, (LPBYTE)src, &dwLength)) == ERROR_SUCCESS ) {
1723 if (keytype == REG_EXPAND_SZ) {
1724 if (dstlen <= ExpandEnvironmentStringsW(src, dst, dstlen)) ret = ERROR_MORE_DATA;
1726 lstrcpynW(dst, src, dstlen);
1734 static void get_threading_model(HKEY key, LPWSTR value, DWORD len)
1736 static const WCHAR wszThreadingModel[] = {'T','h','r','e','a','d','i','n','g','M','o','d','e','l',0};
1739 DWORD dwLength = len * sizeof(WCHAR);
1741 ret = RegQueryValueExW(key, wszThreadingModel, NULL, &keytype, (LPBYTE)value, &dwLength);
1742 if ((ret != ERROR_SUCCESS) || (keytype != REG_SZ))
1746 static HRESULT get_inproc_class_object(HKEY hkeydll, REFCLSID rclsid, REFIID riid, void **ppv)
1748 static const WCHAR wszApartment[] = {'A','p','a','r','t','m','e','n','t',0};
1749 static const WCHAR wszFree[] = {'F','r','e','e',0};
1750 static const WCHAR wszBoth[] = {'B','o','t','h',0};
1752 typedef HRESULT (CALLBACK *DllGetClassObjectFunc)(REFCLSID clsid, REFIID iid, LPVOID *ppv);
1753 DllGetClassObjectFunc DllGetClassObject;
1754 WCHAR dllpath[MAX_PATH+1];
1755 WCHAR threading_model[10 /* strlenW(L"apartment")+1 */];
1758 get_threading_model(hkeydll, threading_model, ARRAYSIZE(threading_model));
1760 if (!strcmpiW(threading_model, wszApartment))
1762 APARTMENT *apt = COM_CurrentApt();
1763 if (apt->multi_threaded)
1765 /* try to find an STA */
1766 APARTMENT *host_apt = apartment_findfromtype(FALSE, FALSE);
1768 FIXME("create a host apartment for apartment-threaded object %s\n", debugstr_guid(rclsid));
1771 struct host_object_params params;
1772 HWND hwnd = apartment_getwindow(host_apt);
1774 params.hkeydll = hkeydll;
1775 params.clsid = *rclsid;
1777 hr = CreateStreamOnHGlobal(NULL, TRUE, ¶ms.stream);
1780 hr = SendMessageW(hwnd, DM_HOSTOBJECT, 0, (LPARAM)¶ms);
1782 hr = CoUnmarshalInterface(params.stream, riid, ppv);
1783 IStream_Release(params.stream);
1789 else if (!strcmpiW(threading_model, wszFree))
1791 APARTMENT *apt = COM_CurrentApt();
1792 if (!apt->multi_threaded)
1794 FIXME("should create object %s in multi-threaded apartment\n",
1795 debugstr_guid(rclsid));
1798 /* everything except "Apartment", "Free" and "Both" */
1799 else if (strcmpiW(threading_model, wszBoth))
1801 APARTMENT *apt = COM_CurrentApt();
1803 /* everything else is main-threaded */
1804 if (threading_model[0])
1805 FIXME("unrecognised threading model %s for object %s, should be main-threaded?\n",
1806 debugstr_w(threading_model), debugstr_guid(rclsid));
1808 if (apt->multi_threaded || !apt->main)
1810 /* try to find an STA */
1811 APARTMENT *host_apt = apartment_findfromtype(FALSE, TRUE);
1813 FIXME("create a host apartment for main-threaded object %s\n", debugstr_guid(rclsid));
1816 struct host_object_params params;
1817 HWND hwnd = apartment_getwindow(host_apt);
1819 params.hkeydll = hkeydll;
1820 params.clsid = *rclsid;
1822 hr = CreateStreamOnHGlobal(NULL, TRUE, ¶ms.stream);
1825 hr = SendMessageW(hwnd, DM_HOSTOBJECT, 0, (LPARAM)¶ms);
1827 hr = CoUnmarshalInterface(params.stream, riid, ppv);
1828 IStream_Release(params.stream);
1834 if (COM_RegReadPath(hkeydll, NULL, NULL, dllpath, ARRAYSIZE(dllpath)) != ERROR_SUCCESS)
1836 /* failure: CLSID is not found in registry */
1837 WARN("class %s not registered inproc\n", debugstr_guid(rclsid));
1838 return REGDB_E_CLASSNOTREG;
1841 if ((hLibrary = LoadLibraryExW(dllpath, 0, LOAD_WITH_ALTERED_SEARCH_PATH)) == 0)
1843 /* failure: DLL could not be loaded */
1844 ERR("couldn't load in-process dll %s\n", debugstr_w(dllpath));
1845 return E_ACCESSDENIED; /* FIXME: or should this be CO_E_DLLNOTFOUND? */
1848 if (!(DllGetClassObject = (DllGetClassObjectFunc)GetProcAddress(hLibrary, "DllGetClassObject")))
1850 /* failure: the dll did not export DllGetClassObject */
1851 ERR("couldn't find function DllGetClassObject in %s\n", debugstr_w(dllpath));
1852 FreeLibrary( hLibrary );
1853 return CO_E_DLLNOTFOUND;
1856 /* OK: get the ClassObject */
1857 COMPOBJ_DLLList_Add( hLibrary );
1858 hr = DllGetClassObject(rclsid, riid, ppv);
1861 ERR("DllGetClassObject returned error 0x%08x\n", hr);
1866 /***********************************************************************
1867 * CoGetClassObject [OLE32.@]
1869 * FIXME. If request allows of several options and there is a failure
1870 * with one (other than not being registered) do we try the
1871 * others or return failure? (E.g. inprocess is registered but
1872 * the DLL is not found but the server version works)
1874 HRESULT WINAPI CoGetClassObject(
1875 REFCLSID rclsid, DWORD dwClsContext, COSERVERINFO *pServerInfo,
1876 REFIID iid, LPVOID *ppv)
1878 LPUNKNOWN regClassObject;
1879 HRESULT hres = E_UNEXPECTED;
1881 TRACE("\n\tCLSID:\t%s,\n\tIID:\t%s\n", debugstr_guid(rclsid), debugstr_guid(iid));
1884 return E_INVALIDARG;
1888 if (!COM_CurrentApt())
1890 ERR("apartment not initialised\n");
1891 return CO_E_NOTINITIALIZED;
1895 FIXME("\tpServerInfo: name=%s\n",debugstr_w(pServerInfo->pwszName));
1896 FIXME("\t\tpAuthInfo=%p\n",pServerInfo->pAuthInfo);
1900 * First, try and see if we can't match the class ID with one of the
1901 * registered classes.
1903 if (S_OK == COM_GetRegisteredClassObject(rclsid, dwClsContext, ®ClassObject))
1905 /* Get the required interface from the retrieved pointer. */
1906 hres = IUnknown_QueryInterface(regClassObject, iid, ppv);
1909 * Since QI got another reference on the pointer, we want to release the
1910 * one we already have. If QI was unsuccessful, this will release the object. This
1911 * is good since we are not returning it in the "out" parameter.
1913 IUnknown_Release(regClassObject);
1918 /* First try in-process server */
1919 if (CLSCTX_INPROC_SERVER & dwClsContext)
1921 static const WCHAR wszInprocServer32[] = {'I','n','p','r','o','c','S','e','r','v','e','r','3','2',0};
1924 if (IsEqualCLSID(rclsid, &CLSID_InProcFreeMarshaler))
1925 return FTMarshalCF_Create(iid, ppv);
1927 hres = COM_OpenKeyForCLSID(rclsid, wszInprocServer32, KEY_READ, &hkey);
1930 if (hres == REGDB_E_CLASSNOTREG)
1931 ERR("class %s not registered\n", debugstr_guid(rclsid));
1933 WARN("class %s not registered as in-proc server\n", debugstr_guid(rclsid));
1936 if (SUCCEEDED(hres))
1938 hres = get_inproc_class_object(hkey, rclsid, iid, ppv);
1942 /* return if we got a class, otherwise fall through to one of the
1944 if (SUCCEEDED(hres))
1948 /* Next try in-process handler */
1949 if (CLSCTX_INPROC_HANDLER & dwClsContext)
1951 static const WCHAR wszInprocHandler32[] = {'I','n','p','r','o','c','H','a','n','d','l','e','r','3','2',0};
1954 hres = COM_OpenKeyForCLSID(rclsid, wszInprocHandler32, KEY_READ, &hkey);
1957 if (hres == REGDB_E_CLASSNOTREG)
1958 ERR("class %s not registered\n", debugstr_guid(rclsid));
1960 WARN("class %s not registered in-proc handler\n", debugstr_guid(rclsid));
1963 if (SUCCEEDED(hres))
1965 hres = get_inproc_class_object(hkey, rclsid, iid, ppv);
1969 /* return if we got a class, otherwise fall through to one of the
1971 if (SUCCEEDED(hres))
1975 /* Next try out of process */
1976 if (CLSCTX_LOCAL_SERVER & dwClsContext)
1978 hres = RPC_GetLocalClassObject(rclsid,iid,ppv);
1979 if (SUCCEEDED(hres))
1983 /* Finally try remote: this requires networked DCOM (a lot of work) */
1984 if (CLSCTX_REMOTE_SERVER & dwClsContext)
1986 FIXME ("CLSCTX_REMOTE_SERVER not supported\n");
1987 hres = E_NOINTERFACE;
1991 ERR("no class object %s could be created for context 0x%x\n",
1992 debugstr_guid(rclsid), dwClsContext);
1996 /***********************************************************************
1997 * CoResumeClassObjects (OLE32.@)
1999 * Resumes all class objects registered with REGCLS_SUSPENDED.
2003 * Failure: HRESULT code.
2005 HRESULT WINAPI CoResumeClassObjects(void)
2011 /***********************************************************************
2012 * GetClassFile (OLE32.@)
2014 * This function supplies the CLSID associated with the given filename.
2016 HRESULT WINAPI GetClassFile(LPCOLESTR filePathName,CLSID *pclsid)
2020 int nbElm, length, i;
2022 LPOLESTR *pathDec=0,absFile=0,progId=0;
2024 static const WCHAR bkslashW[] = {'\\',0};
2025 static const WCHAR dotW[] = {'.',0};
2027 TRACE("%s, %p\n", debugstr_w(filePathName), pclsid);
2029 /* if the file contain a storage object the return the CLSID written by IStorage_SetClass method*/
2030 if((StgIsStorageFile(filePathName))==S_OK){
2032 res=StgOpenStorage(filePathName,NULL,STGM_READ | STGM_SHARE_DENY_WRITE,NULL,0,&pstg);
2035 res=ReadClassStg(pstg,pclsid);
2037 IStorage_Release(pstg);
2041 /* if the file is not a storage object then attemps to match various bits in the file against a
2042 pattern in the registry. this case is not frequently used ! so I present only the psodocode for
2045 for(i=0;i<nFileTypes;i++)
2047 for(i=0;j<nPatternsForType;j++){
2052 pat=ReadPatternFromRegistry(i,j);
2053 hFile=CreateFileW(filePathName,,,,,,hFile);
2054 SetFilePosition(hFile,pat.offset);
2055 ReadFile(hFile,buf,pat.size,&r,NULL);
2056 if (memcmp(buf&pat.mask,pat.pattern.pat.size)==0){
2058 *pclsid=ReadCLSIDFromRegistry(i);
2064 /* if the above strategies fail then search for the extension key in the registry */
2066 /* get the last element (absolute file) in the path name */
2067 nbElm=FileMonikerImpl_DecomposePath(filePathName,&pathDec);
2068 absFile=pathDec[nbElm-1];
2070 /* failed if the path represente a directory and not an absolute file name*/
2071 if (!lstrcmpW(absFile, bkslashW))
2072 return MK_E_INVALIDEXTENSION;
2074 /* get the extension of the file */
2076 length=lstrlenW(absFile);
2077 for(i = length-1; (i >= 0) && *(extension = &absFile[i]) != '.'; i--)
2080 if (!extension || !lstrcmpW(extension, dotW))
2081 return MK_E_INVALIDEXTENSION;
2083 res=RegQueryValueW(HKEY_CLASSES_ROOT, extension, NULL, &sizeProgId);
2085 /* get the progId associated to the extension */
2086 progId = CoTaskMemAlloc(sizeProgId);
2087 res = RegQueryValueW(HKEY_CLASSES_ROOT, extension, progId, &sizeProgId);
2089 if (res==ERROR_SUCCESS)
2090 /* return the clsid associated to the progId */
2091 res= CLSIDFromProgID(progId,pclsid);
2093 for(i=0; pathDec[i]!=NULL;i++)
2094 CoTaskMemFree(pathDec[i]);
2095 CoTaskMemFree(pathDec);
2097 CoTaskMemFree(progId);
2099 if (res==ERROR_SUCCESS)
2102 return MK_E_INVALIDEXTENSION;
2105 /***********************************************************************
2106 * CoCreateInstance [OLE32.@]
2108 * Creates an instance of the specified class.
2111 * rclsid [I] Class ID to create an instance of.
2112 * pUnkOuter [I] Optional outer unknown to allow aggregation with another object.
2113 * dwClsContext [I] Flags to restrict the location of the created instance.
2114 * iid [I] The ID of the interface of the instance to return.
2115 * ppv [O] On returns, contains a pointer to the specified interface of the instance.
2119 * Failure: HRESULT code.
2122 * The dwClsContext parameter can be one or more of the following:
2123 *| CLSCTX_INPROC_SERVER - Use an in-process server, such as from a DLL.
2124 *| CLSCTX_INPROC_HANDLER - Use an in-process object which handles certain functions for an object running in another process.
2125 *| CLSCTX_LOCAL_SERVER - Connect to an object running in another process.
2126 *| CLSCTX_REMOTE_SERVER - Connect to an object running on another machine.
2128 * Aggregation is the concept of deferring the IUnknown of an object to another
2129 * object. This allows a separate object to behave as though it was part of
2130 * the object and to allow this the pUnkOuter parameter can be set. Note that
2131 * not all objects support having an outer of unknown.
2134 * CoGetClassObject()
2136 HRESULT WINAPI CoCreateInstance(
2138 LPUNKNOWN pUnkOuter,
2144 LPCLASSFACTORY lpclf = 0;
2146 TRACE("(rclsid=%s, pUnkOuter=%p, dwClsContext=%08x, riid=%s, ppv=%p)\n", debugstr_guid(rclsid),
2147 pUnkOuter, dwClsContext, debugstr_guid(iid), ppv);
2156 * Initialize the "out" parameter
2160 if (!COM_CurrentApt())
2162 ERR("apartment not initialised\n");
2163 return CO_E_NOTINITIALIZED;
2167 * The Standard Global Interface Table (GIT) object is a process-wide singleton.
2168 * Rather than create a class factory, we can just check for it here
2170 if (IsEqualIID(rclsid, &CLSID_StdGlobalInterfaceTable)) {
2171 if (StdGlobalInterfaceTableInstance == NULL)
2172 StdGlobalInterfaceTableInstance = StdGlobalInterfaceTable_Construct();
2173 hres = IGlobalInterfaceTable_QueryInterface( (IGlobalInterfaceTable*) StdGlobalInterfaceTableInstance, iid, ppv);
2174 if (hres) return hres;
2176 TRACE("Retrieved GIT (%p)\n", *ppv);
2181 * Get a class factory to construct the object we want.
2183 hres = CoGetClassObject(rclsid,
2193 * Create the object and don't forget to release the factory
2195 hres = IClassFactory_CreateInstance(lpclf, pUnkOuter, iid, ppv);
2196 IClassFactory_Release(lpclf);
2198 FIXME("no instance created for interface %s of class %s, hres is 0x%08x\n",
2199 debugstr_guid(iid), debugstr_guid(rclsid),hres);
2204 /***********************************************************************
2205 * CoCreateInstanceEx [OLE32.@]
2207 HRESULT WINAPI CoCreateInstanceEx(
2209 LPUNKNOWN pUnkOuter,
2211 COSERVERINFO* pServerInfo,
2215 IUnknown* pUnk = NULL;
2218 ULONG successCount = 0;
2223 if ( (cmq==0) || (pResults==NULL))
2224 return E_INVALIDARG;
2226 if (pServerInfo!=NULL)
2227 FIXME("() non-NULL pServerInfo not supported!\n");
2230 * Initialize all the "out" parameters.
2232 for (index = 0; index < cmq; index++)
2234 pResults[index].pItf = NULL;
2235 pResults[index].hr = E_NOINTERFACE;
2239 * Get the object and get its IUnknown pointer.
2241 hr = CoCreateInstance(rclsid,
2251 * Then, query for all the interfaces requested.
2253 for (index = 0; index < cmq; index++)
2255 pResults[index].hr = IUnknown_QueryInterface(pUnk,
2256 pResults[index].pIID,
2257 (VOID**)&(pResults[index].pItf));
2259 if (pResults[index].hr == S_OK)
2264 * Release our temporary unknown pointer.
2266 IUnknown_Release(pUnk);
2268 if (successCount == 0)
2269 return E_NOINTERFACE;
2271 if (successCount!=cmq)
2272 return CO_S_NOTALLINTERFACES;
2277 /***********************************************************************
2278 * CoLoadLibrary (OLE32.@)
2283 * lpszLibName [I] Path to library.
2284 * bAutoFree [I] Whether the library should automatically be freed.
2287 * Success: Handle to loaded library.
2291 * CoFreeLibrary, CoFreeAllLibraries, CoFreeUnusedLibraries
2293 HINSTANCE WINAPI CoLoadLibrary(LPOLESTR lpszLibName, BOOL bAutoFree)
2295 TRACE("(%s, %d)\n", debugstr_w(lpszLibName), bAutoFree);
2297 return LoadLibraryExW(lpszLibName, 0, LOAD_WITH_ALTERED_SEARCH_PATH);
2300 /***********************************************************************
2301 * CoFreeLibrary [OLE32.@]
2303 * Unloads a library from memory.
2306 * hLibrary [I] Handle to library to unload.
2312 * CoLoadLibrary, CoFreeAllLibraries, CoFreeUnusedLibraries
2314 void WINAPI CoFreeLibrary(HINSTANCE hLibrary)
2316 FreeLibrary(hLibrary);
2320 /***********************************************************************
2321 * CoFreeAllLibraries [OLE32.@]
2323 * Function for backwards compatibility only. Does nothing.
2329 * CoLoadLibrary, CoFreeLibrary, CoFreeUnusedLibraries
2331 void WINAPI CoFreeAllLibraries(void)
2337 /***********************************************************************
2338 * CoFreeUnusedLibraries [OLE32.@]
2339 * CoFreeUnusedLibraries [COMPOBJ.17]
2341 * Frees any unused libraries. Unused are identified as those that return
2342 * S_OK from their DllCanUnloadNow function.
2348 * CoLoadLibrary, CoFreeAllLibraries, CoFreeLibrary
2350 void WINAPI CoFreeUnusedLibraries(void)
2352 /* FIXME: Calls to CoFreeUnusedLibraries from any thread always route
2353 * through the main apartment's thread to call DllCanUnloadNow */
2354 COMPOBJ_DllList_FreeUnused(0);
2357 /***********************************************************************
2358 * CoFileTimeNow [OLE32.@]
2359 * CoFileTimeNow [COMPOBJ.82]
2361 * Retrieves the current time in FILETIME format.
2364 * lpFileTime [O] The current time.
2369 HRESULT WINAPI CoFileTimeNow( FILETIME *lpFileTime )
2371 GetSystemTimeAsFileTime( lpFileTime );
2375 static void COM_RevokeAllClasses(void)
2377 EnterCriticalSection( &csRegisteredClassList );
2379 while (firstRegisteredClass!=0)
2381 CoRevokeClassObject(firstRegisteredClass->dwCookie);
2384 LeaveCriticalSection( &csRegisteredClassList );
2387 /******************************************************************************
2388 * CoLockObjectExternal [OLE32.@]
2390 * Increments or decrements the external reference count of a stub object.
2393 * pUnk [I] Stub object.
2394 * fLock [I] If TRUE then increments the external ref-count,
2395 * otherwise decrements.
2396 * fLastUnlockReleases [I] If TRUE then the last unlock has the effect of
2397 * calling CoDisconnectObject.
2401 * Failure: HRESULT code.
2404 * If fLock is TRUE and an object is passed in that doesn't have a stub
2405 * manager then a new stub manager is created for the object.
2407 HRESULT WINAPI CoLockObjectExternal(
2410 BOOL fLastUnlockReleases)
2412 struct stub_manager *stubmgr;
2413 struct apartment *apt;
2415 TRACE("pUnk=%p, fLock=%s, fLastUnlockReleases=%s\n",
2416 pUnk, fLock ? "TRUE" : "FALSE", fLastUnlockReleases ? "TRUE" : "FALSE");
2418 apt = COM_CurrentApt();
2419 if (!apt) return CO_E_NOTINITIALIZED;
2421 stubmgr = get_stub_manager_from_object(apt, pUnk);
2426 stub_manager_ext_addref(stubmgr, 1);
2428 stub_manager_ext_release(stubmgr, 1, fLastUnlockReleases);
2430 stub_manager_int_release(stubmgr);
2436 stubmgr = new_stub_manager(apt, pUnk);
2440 stub_manager_ext_addref(stubmgr, 1);
2441 stub_manager_int_release(stubmgr);
2448 WARN("stub object not found %p\n", pUnk);
2449 /* Note: native is pretty broken here because it just silently
2450 * fails, without returning an appropriate error code, making apps
2451 * think that the object was disconnected, when it actually wasn't */
2456 /***********************************************************************
2457 * CoInitializeWOW (OLE32.@)
2459 * WOW equivalent of CoInitialize?
2468 HRESULT WINAPI CoInitializeWOW(DWORD x,DWORD y)
2470 FIXME("(0x%08x,0x%08x),stub!\n",x,y);
2474 /***********************************************************************
2475 * CoGetState [OLE32.@]
2477 * Retrieves the thread state object previously stored by CoSetState().
2480 * ppv [I] Address where pointer to object will be stored.
2484 * Failure: E_OUTOFMEMORY.
2487 * Crashes on all invalid ppv addresses, including NULL.
2488 * If the function returns a non-NULL object then the caller must release its
2489 * reference on the object when the object is no longer required.
2494 HRESULT WINAPI CoGetState(IUnknown ** ppv)
2496 struct oletls *info = COM_CurrentInfo();
2497 if (!info) return E_OUTOFMEMORY;
2503 IUnknown_AddRef(info->state);
2505 TRACE("apt->state=%p\n", info->state);
2511 /***********************************************************************
2512 * CoSetState [OLE32.@]
2514 * Sets the thread state object.
2517 * pv [I] Pointer to state object to be stored.
2520 * The system keeps a reference on the object while the object stored.
2524 * Failure: E_OUTOFMEMORY.
2526 HRESULT WINAPI CoSetState(IUnknown * pv)
2528 struct oletls *info = COM_CurrentInfo();
2529 if (!info) return E_OUTOFMEMORY;
2531 if (pv) IUnknown_AddRef(pv);
2535 TRACE("-- release %p now\n", info->state);
2536 IUnknown_Release(info->state);
2545 /******************************************************************************
2546 * CoTreatAsClass [OLE32.@]
2548 * Sets the TreatAs value of a class.
2551 * clsidOld [I] Class to set TreatAs value on.
2552 * clsidNew [I] The class the clsidOld should be treated as.
2556 * Failure: HRESULT code.
2561 HRESULT WINAPI CoTreatAsClass(REFCLSID clsidOld, REFCLSID clsidNew)
2563 static const WCHAR wszAutoTreatAs[] = {'A','u','t','o','T','r','e','a','t','A','s',0};
2564 static const WCHAR wszTreatAs[] = {'T','r','e','a','t','A','s',0};
2566 WCHAR szClsidNew[CHARS_IN_GUID];
2568 WCHAR auto_treat_as[CHARS_IN_GUID];
2569 LONG auto_treat_as_size = sizeof(auto_treat_as);
2572 res = COM_OpenKeyForCLSID(clsidOld, NULL, KEY_READ | KEY_WRITE, &hkey);
2575 if (!memcmp( clsidOld, clsidNew, sizeof(*clsidOld) ))
2577 if (!RegQueryValueW(hkey, wszAutoTreatAs, auto_treat_as, &auto_treat_as_size) &&
2578 !CLSIDFromString(auto_treat_as, &id))
2580 if (RegSetValueW(hkey, wszTreatAs, REG_SZ, auto_treat_as, sizeof(auto_treat_as)))
2582 res = REGDB_E_WRITEREGDB;
2588 RegDeleteKeyW(hkey, wszTreatAs);
2592 else if (!StringFromGUID2(clsidNew, szClsidNew, ARRAYSIZE(szClsidNew)) &&
2593 !RegSetValueW(hkey, wszTreatAs, REG_SZ, szClsidNew, sizeof(szClsidNew)))
2595 res = REGDB_E_WRITEREGDB;
2600 if (hkey) RegCloseKey(hkey);
2604 /******************************************************************************
2605 * CoGetTreatAsClass [OLE32.@]
2607 * Gets the TreatAs value of a class.
2610 * clsidOld [I] Class to get the TreatAs value of.
2611 * clsidNew [I] The class the clsidOld should be treated as.
2615 * Failure: HRESULT code.
2620 HRESULT WINAPI CoGetTreatAsClass(REFCLSID clsidOld, LPCLSID clsidNew)
2622 static const WCHAR wszTreatAs[] = {'T','r','e','a','t','A','s',0};
2624 WCHAR szClsidNew[CHARS_IN_GUID];
2626 LONG len = sizeof(szClsidNew);
2628 FIXME("(%s,%p)\n", debugstr_guid(clsidOld), clsidNew);
2629 memcpy(clsidNew,clsidOld,sizeof(CLSID)); /* copy over old value */
2631 res = COM_OpenKeyForCLSID(clsidOld, wszTreatAs, KEY_READ, &hkey);
2634 if (RegQueryValueW(hkey, NULL, szClsidNew, &len))
2639 res = CLSIDFromString(szClsidNew,clsidNew);
2641 ERR("Failed CLSIDFromStringA(%s), hres 0x%08x\n", debugstr_w(szClsidNew), res);
2643 if (hkey) RegCloseKey(hkey);
2647 /******************************************************************************
2648 * CoGetCurrentProcess [OLE32.@]
2649 * CoGetCurrentProcess [COMPOBJ.34]
2651 * Gets the current process ID.
2654 * The current process ID.
2657 * Is DWORD really the correct return type for this function?
2659 DWORD WINAPI CoGetCurrentProcess(void)
2661 return GetCurrentProcessId();
2664 /******************************************************************************
2665 * CoRegisterMessageFilter [OLE32.@]
2667 * Registers a message filter.
2670 * lpMessageFilter [I] Pointer to interface.
2671 * lplpMessageFilter [O] Indirect pointer to prior instance if non-NULL.
2675 * Failure: HRESULT code.
2678 * Both lpMessageFilter and lplpMessageFilter are optional. Passing in a NULL
2679 * lpMessageFilter removes the message filter.
2681 * If lplpMessageFilter is not NULL the previous message filter will be
2682 * returned in the memory pointer to this parameter and the caller is
2683 * responsible for releasing the object.
2685 * The current thread be in an apartment otherwise the function will crash.
2687 HRESULT WINAPI CoRegisterMessageFilter(
2688 LPMESSAGEFILTER lpMessageFilter,
2689 LPMESSAGEFILTER *lplpMessageFilter)
2691 struct apartment *apt;
2692 IMessageFilter *lpOldMessageFilter;
2694 TRACE("(%p, %p)\n", lpMessageFilter, lplpMessageFilter);
2696 apt = COM_CurrentApt();
2698 /* can't set a message filter in a multi-threaded apartment */
2699 if (!apt || apt->multi_threaded)
2701 WARN("can't set message filter in MTA or uninitialized apt\n");
2702 return CO_E_NOT_SUPPORTED;
2705 if (lpMessageFilter)
2706 IMessageFilter_AddRef(lpMessageFilter);
2708 EnterCriticalSection(&apt->cs);
2710 lpOldMessageFilter = apt->filter;
2711 apt->filter = lpMessageFilter;
2713 LeaveCriticalSection(&apt->cs);
2715 if (lplpMessageFilter)
2716 *lplpMessageFilter = lpOldMessageFilter;
2717 else if (lpOldMessageFilter)
2718 IMessageFilter_Release(lpOldMessageFilter);
2723 /***********************************************************************
2724 * CoIsOle1Class [OLE32.@]
2726 * Determines whether the specified class an OLE v1 class.
2729 * clsid [I] Class to test.
2732 * TRUE if the class is an OLE v1 class, or FALSE otherwise.
2734 BOOL WINAPI CoIsOle1Class(REFCLSID clsid)
2736 FIXME("%s\n", debugstr_guid(clsid));
2740 /***********************************************************************
2741 * IsEqualGUID [OLE32.@]
2743 * Compares two Unique Identifiers.
2746 * rguid1 [I] The first GUID to compare.
2747 * rguid2 [I] The other GUID to compare.
2753 BOOL WINAPI IsEqualGUID(
2757 return !memcmp(rguid1,rguid2,sizeof(GUID));
2760 /***********************************************************************
2761 * CoInitializeSecurity [OLE32.@]
2763 HRESULT WINAPI CoInitializeSecurity(PSECURITY_DESCRIPTOR pSecDesc, LONG cAuthSvc,
2764 SOLE_AUTHENTICATION_SERVICE* asAuthSvc,
2765 void* pReserved1, DWORD dwAuthnLevel,
2766 DWORD dwImpLevel, void* pReserved2,
2767 DWORD dwCapabilities, void* pReserved3)
2769 FIXME("(%p,%d,%p,%p,%d,%d,%p,%d,%p) - stub!\n", pSecDesc, cAuthSvc,
2770 asAuthSvc, pReserved1, dwAuthnLevel, dwImpLevel, pReserved2,
2771 dwCapabilities, pReserved3);
2775 /***********************************************************************
2776 * CoSuspendClassObjects [OLE32.@]
2778 * Suspends all registered class objects to prevent further requests coming in
2779 * for those objects.
2783 * Failure: HRESULT code.
2785 HRESULT WINAPI CoSuspendClassObjects(void)
2791 /***********************************************************************
2792 * CoAddRefServerProcess [OLE32.@]
2794 * Helper function for incrementing the reference count of a local-server
2798 * New reference count.
2800 ULONG WINAPI CoAddRefServerProcess(void)
2806 /***********************************************************************
2807 * CoReleaseServerProcess [OLE32.@]
2809 * Helper function for decrementing the reference count of a local-server
2813 * New reference count.
2815 ULONG WINAPI CoReleaseServerProcess(void)
2821 /***********************************************************************
2822 * CoIsHandlerConnected [OLE32.@]
2824 * Determines whether a proxy is connected to a remote stub.
2827 * pUnk [I] Pointer to object that may or may not be connected.
2830 * TRUE if pUnk is not a proxy or if pUnk is connected to a remote stub, or
2833 BOOL WINAPI CoIsHandlerConnected(IUnknown *pUnk)
2835 FIXME("%p\n", pUnk);
2840 /***********************************************************************
2841 * CoAllowSetForegroundWindow [OLE32.@]
2844 HRESULT WINAPI CoAllowSetForegroundWindow(IUnknown *pUnk, void *pvReserved)
2846 FIXME("(%p, %p): stub\n", pUnk, pvReserved);
2850 /***********************************************************************
2851 * CoQueryProxyBlanket [OLE32.@]
2853 * Retrieves the security settings being used by a proxy.
2856 * pProxy [I] Pointer to the proxy object.
2857 * pAuthnSvc [O] The type of authentication service.
2858 * pAuthzSvc [O] The type of authorization service.
2859 * ppServerPrincName [O] Optional. The server prinicple name.
2860 * pAuthnLevel [O] The authentication level.
2861 * pImpLevel [O] The impersonation level.
2862 * ppAuthInfo [O] Information specific to the authorization/authentication service.
2863 * pCapabilities [O] Flags affecting the security behaviour.
2867 * Failure: HRESULT code.
2870 * CoCopyProxy, CoSetProxyBlanket.
2872 HRESULT WINAPI CoQueryProxyBlanket(IUnknown *pProxy, DWORD *pAuthnSvc,
2873 DWORD *pAuthzSvc, OLECHAR **ppServerPrincName, DWORD *pAuthnLevel,
2874 DWORD *pImpLevel, void **ppAuthInfo, DWORD *pCapabilities)
2876 IClientSecurity *pCliSec;
2879 TRACE("%p\n", pProxy);
2881 hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
2884 hr = IClientSecurity_QueryBlanket(pCliSec, pProxy, pAuthnSvc,
2885 pAuthzSvc, ppServerPrincName,
2886 pAuthnLevel, pImpLevel, ppAuthInfo,
2888 IClientSecurity_Release(pCliSec);
2891 if (FAILED(hr)) ERR("-- failed with 0x%08x\n", hr);
2895 /***********************************************************************
2896 * CoSetProxyBlanket [OLE32.@]
2898 * Sets the security settings for a proxy.
2901 * pProxy [I] Pointer to the proxy object.
2902 * AuthnSvc [I] The type of authentication service.
2903 * AuthzSvc [I] The type of authorization service.
2904 * pServerPrincName [I] The server prinicple name.
2905 * AuthnLevel [I] The authentication level.
2906 * ImpLevel [I] The impersonation level.
2907 * pAuthInfo [I] Information specific to the authorization/authentication service.
2908 * Capabilities [I] Flags affecting the security behaviour.
2912 * Failure: HRESULT code.
2915 * CoQueryProxyBlanket, CoCopyProxy.
2917 HRESULT WINAPI CoSetProxyBlanket(IUnknown *pProxy, DWORD AuthnSvc,
2918 DWORD AuthzSvc, OLECHAR *pServerPrincName, DWORD AuthnLevel,
2919 DWORD ImpLevel, void *pAuthInfo, DWORD Capabilities)
2921 IClientSecurity *pCliSec;
2924 TRACE("%p\n", pProxy);
2926 hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
2929 hr = IClientSecurity_SetBlanket(pCliSec, pProxy, AuthnSvc,
2930 AuthzSvc, pServerPrincName,
2931 AuthnLevel, ImpLevel, pAuthInfo,
2933 IClientSecurity_Release(pCliSec);
2936 if (FAILED(hr)) ERR("-- failed with 0x%08x\n", hr);
2940 /***********************************************************************
2941 * CoCopyProxy [OLE32.@]
2946 * pProxy [I] Pointer to the proxy object.
2947 * ppCopy [O] Copy of the proxy.
2951 * Failure: HRESULT code.
2954 * CoQueryProxyBlanket, CoSetProxyBlanket.
2956 HRESULT WINAPI CoCopyProxy(IUnknown *pProxy, IUnknown **ppCopy)
2958 IClientSecurity *pCliSec;
2961 TRACE("%p\n", pProxy);
2963 hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
2966 hr = IClientSecurity_CopyProxy(pCliSec, pProxy, ppCopy);
2967 IClientSecurity_Release(pCliSec);
2970 if (FAILED(hr)) ERR("-- failed with 0x%08x\n", hr);
2975 /***********************************************************************
2976 * CoGetCallContext [OLE32.@]
2978 * Gets the context of the currently executing server call in the current
2982 * riid [I] Context interface to return.
2983 * ppv [O] Pointer to memory that will receive the context on return.
2987 * Failure: HRESULT code.
2989 HRESULT WINAPI CoGetCallContext(REFIID riid, void **ppv)
2991 FIXME("(%s, %p): stub\n", debugstr_guid(riid), ppv);
2994 return E_NOINTERFACE;
2997 /***********************************************************************
2998 * CoQueryClientBlanket [OLE32.@]
3000 * Retrieves the authentication information about the client of the currently
3001 * executing server call in the current thread.
3004 * pAuthnSvc [O] Optional. The type of authentication service.
3005 * pAuthzSvc [O] Optional. The type of authorization service.
3006 * pServerPrincName [O] Optional. The server prinicple name.
3007 * pAuthnLevel [O] Optional. The authentication level.
3008 * pImpLevel [O] Optional. The impersonation level.
3009 * pPrivs [O] Optional. Information about the privileges of the client.
3010 * pCapabilities [IO] Optional. Flags affecting the security behaviour.
3014 * Failure: HRESULT code.
3017 * CoImpersonateClient, CoRevertToSelf, CoGetCallContext.
3019 HRESULT WINAPI CoQueryClientBlanket(
3022 OLECHAR **pServerPrincName,
3025 RPC_AUTHZ_HANDLE *pPrivs,
3026 DWORD *pCapabilities)
3028 IServerSecurity *pSrvSec;
3031 TRACE("(%p, %p, %p, %p, %p, %p, %p)\n",
3032 pAuthnSvc, pAuthzSvc, pServerPrincName, pAuthnLevel, pImpLevel,
3033 pPrivs, pCapabilities);
3035 hr = CoGetCallContext(&IID_IServerSecurity, (void **)&pSrvSec);
3038 hr = IServerSecurity_QueryBlanket(
3039 pSrvSec, pAuthnSvc, pAuthzSvc, pServerPrincName, pAuthnLevel,
3040 pImpLevel, pPrivs, pCapabilities);
3041 IServerSecurity_Release(pSrvSec);
3047 /***********************************************************************
3048 * CoImpersonateClient [OLE32.@]
3050 * Impersonates the client of the currently executing server call in the
3058 * Failure: HRESULT code.
3061 * If this function fails then the current thread will not be impersonating
3062 * the client and all actions will take place on behalf of the server.
3063 * Therefore, it is important to check the return value from this function.
3066 * CoRevertToSelf, CoQueryClientBlanket, CoGetCallContext.
3068 HRESULT WINAPI CoImpersonateClient(void)
3070 IServerSecurity *pSrvSec;
3075 hr = CoGetCallContext(&IID_IServerSecurity, (void **)&pSrvSec);
3078 hr = IServerSecurity_ImpersonateClient(pSrvSec);
3079 IServerSecurity_Release(pSrvSec);
3085 /***********************************************************************
3086 * CoRevertToSelf [OLE32.@]
3088 * Ends the impersonation of the client of the currently executing server
3089 * call in the current thread.
3096 * Failure: HRESULT code.
3099 * CoImpersonateClient, CoQueryClientBlanket, CoGetCallContext.
3101 HRESULT WINAPI CoRevertToSelf(void)
3103 IServerSecurity *pSrvSec;
3108 hr = CoGetCallContext(&IID_IServerSecurity, (void **)&pSrvSec);
3111 hr = IServerSecurity_RevertToSelf(pSrvSec);
3112 IServerSecurity_Release(pSrvSec);
3118 static BOOL COM_PeekMessage(struct apartment *apt, MSG *msg)
3120 /* first try to retrieve messages for incoming COM calls to the apartment window */
3121 return PeekMessageW(msg, apt->win, WM_USER, WM_APP - 1, PM_REMOVE|PM_NOYIELD) ||
3122 /* next retrieve other messages necessary for the app to remain responsive */
3123 PeekMessageW(msg, NULL, 0, WM_USER - 1, PM_REMOVE|PM_NOYIELD);
3126 /***********************************************************************
3127 * CoWaitForMultipleHandles [OLE32.@]
3129 * Waits for one or more handles to become signaled.
3132 * dwFlags [I] Flags. See notes.
3133 * dwTimeout [I] Timeout in milliseconds.
3134 * cHandles [I] Number of handles pointed to by pHandles.
3135 * pHandles [I] Handles to wait for.
3136 * lpdwindex [O] Index of handle that was signaled.
3140 * Failure: RPC_S_CALLPENDING on timeout.
3144 * The dwFlags parameter can be zero or more of the following:
3145 *| COWAIT_WAITALL - Wait for all of the handles to become signaled.
3146 *| COWAIT_ALERTABLE - Allows a queued APC to run during the wait.
3149 * MsgWaitForMultipleObjects, WaitForMultipleObjects.
3151 HRESULT WINAPI CoWaitForMultipleHandles(DWORD dwFlags, DWORD dwTimeout,
3152 ULONG cHandles, const HANDLE* pHandles, LPDWORD lpdwindex)
3155 DWORD start_time = GetTickCount();
3156 APARTMENT *apt = COM_CurrentApt();
3157 BOOL message_loop = apt && !apt->multi_threaded;
3159 TRACE("(0x%08x, 0x%08x, %d, %p, %p)\n", dwFlags, dwTimeout, cHandles,
3160 pHandles, lpdwindex);
3164 DWORD now = GetTickCount();
3167 if ((dwTimeout != INFINITE) && (start_time + dwTimeout >= now))
3169 hr = RPC_S_CALLPENDING;
3175 DWORD wait_flags = (dwFlags & COWAIT_WAITALL) ? MWMO_WAITALL : 0 |
3176 (dwFlags & COWAIT_ALERTABLE ) ? MWMO_ALERTABLE : 0;
3178 TRACE("waiting for rpc completion or window message\n");
3180 res = MsgWaitForMultipleObjectsEx(cHandles, pHandles,
3181 (dwTimeout == INFINITE) ? INFINITE : start_time + dwTimeout - now,
3182 QS_ALLINPUT, wait_flags);
3184 if (res == WAIT_OBJECT_0 + cHandles) /* messages available */
3188 /* call message filter */
3190 if (COM_CurrentApt()->filter)
3192 PENDINGTYPE pendingtype =
3193 COM_CurrentInfo()->pending_call_count_server ?
3194 PENDINGTYPE_NESTED : PENDINGTYPE_TOPLEVEL;
3195 DWORD be_handled = IMessageFilter_MessagePending(
3196 COM_CurrentApt()->filter, 0 /* FIXME */,
3197 now - start_time, pendingtype);
3198 TRACE("IMessageFilter_MessagePending returned %d\n", be_handled);
3201 case PENDINGMSG_CANCELCALL:
3202 WARN("call canceled\n");
3203 hr = RPC_E_CALL_CANCELED;
3205 case PENDINGMSG_WAITNOPROCESS:
3206 case PENDINGMSG_WAITDEFPROCESS:
3208 /* FIXME: MSDN is very vague about the difference
3209 * between WAITNOPROCESS and WAITDEFPROCESS - there
3210 * appears to be none, so it is possibly a left-over
3211 * from the 16-bit world. */
3216 /* note: using "if" here instead of "while" might seem less
3217 * efficient, but only if we are optimising for quick delivery
3218 * of pending messages, rather than quick completion of the
3220 if (COM_PeekMessage(apt, &msg))
3222 /* FIXME: filter the messages here */
3223 TRACE("received message whilst waiting for RPC: 0x%04x\n", msg.message);
3224 TranslateMessage(&msg);
3225 DispatchMessageW(&msg);
3226 if (msg.message == WM_QUIT)
3228 TRACE("resending WM_QUIT to outer message loop\n");
3229 PostQuitMessage(msg.wParam);
3230 /* no longer need to process messages */
3231 message_loop = FALSE;
3239 TRACE("waiting for rpc completion\n");
3241 res = WaitForMultipleObjectsEx(cHandles, pHandles,
3242 (dwFlags & COWAIT_WAITALL) ? TRUE : FALSE,
3243 (dwTimeout == INFINITE) ? INFINITE : start_time + dwTimeout - now,
3244 (dwFlags & COWAIT_ALERTABLE) ? TRUE : FALSE);
3247 if ((res >= WAIT_OBJECT_0) && (res < WAIT_OBJECT_0 + cHandles))
3249 /* handle signaled, store index */
3250 *lpdwindex = (res - WAIT_OBJECT_0);
3253 else if (res == WAIT_TIMEOUT)
3255 hr = RPC_S_CALLPENDING;
3260 ERR("Unexpected wait termination: %d, %d\n", res, GetLastError());
3265 TRACE("-- 0x%08x\n", hr);
3270 /***********************************************************************
3271 * CoGetObject [OLE32.@]
3273 * Gets the object named by coverting the name to a moniker and binding to it.
3276 * pszName [I] String representing the object.
3277 * pBindOptions [I] Parameters affecting the binding to the named object.
3278 * riid [I] Interface to bind to on the objecct.
3279 * ppv [O] On output, the interface riid of the object represented
3284 * Failure: HRESULT code.
3287 * MkParseDisplayName.
3289 HRESULT WINAPI CoGetObject(LPCWSTR pszName, BIND_OPTS *pBindOptions,
3290 REFIID riid, void **ppv)
3297 hr = CreateBindCtx(0, &pbc);
3301 hr = IBindCtx_SetBindOptions(pbc, pBindOptions);
3308 hr = MkParseDisplayName(pbc, pszName, &chEaten, &pmk);
3311 hr = IMoniker_BindToObject(pmk, pbc, NULL, riid, ppv);
3312 IMoniker_Release(pmk);
3316 IBindCtx_Release(pbc);
3321 /***********************************************************************
3322 * CoRegisterChannelHook [OLE32.@]
3324 * Registers a process-wide hook that is called during ORPC calls.
3327 * guidExtension [I] GUID of the channel hook to register.
3328 * pChannelHook [I] Channel hook object to register.
3332 * Failure: HRESULT code.
3334 HRESULT WINAPI CoRegisterChannelHook(REFGUID guidExtension, IChannelHook *pChannelHook)
3336 TRACE("(%s, %p)\n", debugstr_guid(guidExtension), pChannelHook);
3338 return RPC_RegisterChannelHook(guidExtension, pChannelHook);
3341 /***********************************************************************
3344 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID fImpLoad)
3346 TRACE("%p 0x%x %p\n", hinstDLL, fdwReason, fImpLoad);
3349 case DLL_PROCESS_ATTACH:
3350 OLE32_hInstance = hinstDLL;
3351 COMPOBJ_InitProcess();
3352 if (TRACE_ON(ole)) CoRegisterMallocSpy((LPVOID)-1);
3355 case DLL_PROCESS_DETACH:
3356 if (TRACE_ON(ole)) CoRevokeMallocSpy();
3357 COMPOBJ_UninitProcess();
3358 RPC_UnregisterAllChannelHooks();
3359 OLE32_hInstance = 0;
3362 case DLL_THREAD_DETACH:
3369 /* NOTE: DllRegisterServer and DllUnregisterServer are in regsvr.c */