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
11 * This library is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public
13 * License as published by the Free Software Foundation; either
14 * version 2.1 of the License, or (at your option) any later version.
16 * This library is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with this library; if not, write to the Free Software
23 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
26 * 1. COINIT_MULTITHREADED is 0; it is the lack of COINIT_APARTMENTTHREADED
27 * Therefore do not test against COINIT_MULTITHREADED
29 * TODO list: (items bunched together depend on each other)
31 * - Implement the service control manager (in rpcss) to keep track
32 * of registered class objects: ISCM::ServerRegisterClsid et al
33 * - Implement the OXID resolver so we don't need magic endpoint names for
34 * clients and servers to meet up
36 * - Call IMessageFilter functions.
38 * - Make all ole interface marshaling use NDR to be wire compatible with
40 * - Use & interpret ORPCTHIS & ORPCTHAT.
53 #define NONAMELESSUNION
54 #define NONAMELESSSTRUCT
65 #include "compobj_private.h"
67 #include "wine/unicode.h"
68 #include "wine/debug.h"
70 WINE_DEFAULT_DEBUG_CHANNEL(ole);
72 HINSTANCE OLE32_hInstance = 0; /* FIXME: make static ... */
74 #define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))
76 /****************************************************************************
77 * This section defines variables internal to the COM module.
79 * TODO: Most of these things will have to be made thread-safe.
82 static HRESULT COM_GetRegisteredClassObject(REFCLSID rclsid, DWORD dwClsContext, LPUNKNOWN* ppUnk);
83 static void COM_RevokeAllClasses(void);
85 const CLSID CLSID_StdGlobalInterfaceTable = { 0x00000323, 0, 0, {0xc0, 0, 0, 0, 0, 0, 0, 0x46} };
87 APARTMENT *MTA; /* protected by csApartment */
88 static struct list apts = LIST_INIT( apts ); /* protected by csApartment */
90 static CRITICAL_SECTION csApartment;
91 static CRITICAL_SECTION_DEBUG critsect_debug =
94 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
95 0, 0, { (DWORD_PTR)(__FILE__ ": csApartment") }
97 static CRITICAL_SECTION csApartment = { &critsect_debug, -1, 0, 0, 0, 0 };
100 * This lock count counts the number of times CoInitialize is called. It is
101 * decreased every time CoUninitialize is called. When it hits 0, the COM
102 * libraries are freed
104 static LONG s_COMLockCount = 0;
107 * This linked list contains the list of registered class objects. These
108 * are mostly used to register the factories for out-of-proc servers of OLE
111 * TODO: Make this data structure aware of inter-process communication. This
112 * means that parts of this will be exported to the Wine Server.
114 typedef struct tagRegisteredClass
116 CLSID classIdentifier;
117 LPUNKNOWN classObject;
121 LPSTREAM pMarshaledData; /* FIXME: only really need to store OXID and IPID */
122 struct tagRegisteredClass* nextClass;
125 static RegisteredClass* firstRegisteredClass = NULL;
127 static CRITICAL_SECTION csRegisteredClassList;
128 static CRITICAL_SECTION_DEBUG class_cs_debug =
130 0, 0, &csRegisteredClassList,
131 { &class_cs_debug.ProcessLocksList, &class_cs_debug.ProcessLocksList },
132 0, 0, { (DWORD_PTR)(__FILE__ ": csRegisteredClassList") }
134 static CRITICAL_SECTION csRegisteredClassList = { &class_cs_debug, -1, 0, 0, 0, 0 };
136 /*****************************************************************************
137 * This section contains OpenDllList definitions
139 * The OpenDllList contains only handles of dll loaded by CoGetClassObject or
140 * other functions that do LoadLibrary _without_ giving back a HMODULE.
141 * Without this list these handles would never be freed.
143 * FIXME: a DLL that says OK when asked for unloading is unloaded in the
144 * next unload-call but not before 600 sec.
147 typedef struct tagOpenDll {
149 struct tagOpenDll *next;
152 static OpenDll *openDllList = NULL; /* linked list of open dlls */
154 static CRITICAL_SECTION csOpenDllList;
155 static CRITICAL_SECTION_DEBUG dll_cs_debug =
157 0, 0, &csOpenDllList,
158 { &dll_cs_debug.ProcessLocksList, &dll_cs_debug.ProcessLocksList },
159 0, 0, { (DWORD_PTR)(__FILE__ ": csOpenDllList") }
161 static CRITICAL_SECTION csOpenDllList = { &dll_cs_debug, -1, 0, 0, 0, 0 };
163 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',' ',
164 '0','x','#','#','#','#','#','#','#','#',' ',0};
165 static LRESULT CALLBACK apartment_wndproc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
167 static void COMPOBJ_DLLList_Add(HANDLE hLibrary);
168 static void COMPOBJ_DllList_FreeUnused(int Timeout);
170 static void COMPOBJ_InitProcess( void )
174 /* Dispatching to the correct thread in an apartment is done through
175 * window messages rather than RPC transports. When an interface is
176 * marshalled into another apartment in the same process, a window of the
177 * following class is created. The *caller* of CoMarshalInterface (ie the
178 * application) is responsible for pumping the message loop in that thread.
179 * The WM_USER messages which point to the RPCs are then dispatched to
180 * COM_AptWndProc by the user's code from the apartment in which the interface
183 memset(&wclass, 0, sizeof(wclass));
184 wclass.lpfnWndProc = apartment_wndproc;
185 wclass.hInstance = OLE32_hInstance;
186 wclass.lpszClassName = wszAptWinClass;
187 RegisterClassW(&wclass);
190 static void COMPOBJ_UninitProcess( void )
192 UnregisterClassW(wszAptWinClass, OLE32_hInstance);
195 static void COM_TlsDestroy(void)
197 struct oletls *info = NtCurrentTeb()->ReservedForOle;
200 if (info->apt) apartment_release(info->apt);
201 if (info->errorinfo) IErrorInfo_Release(info->errorinfo);
202 if (info->state) IUnknown_Release(info->state);
203 HeapFree(GetProcessHeap(), 0, info);
204 NtCurrentTeb()->ReservedForOle = NULL;
208 /******************************************************************************
212 /* allocates memory and fills in the necessary fields for a new apartment
214 static APARTMENT *apartment_construct(DWORD model)
218 TRACE("creating new apartment, model=%ld\n", model);
220 apt = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*apt));
221 apt->tid = GetCurrentThreadId();
223 list_init(&apt->proxies);
224 list_init(&apt->stubmgrs);
227 apt->remunk_exported = FALSE;
229 InitializeCriticalSection(&apt->cs);
230 DEBUG_SET_CRITSEC_NAME(&apt->cs, "apartment");
232 apt->multi_threaded = !(model & COINIT_APARTMENTTHREADED);
234 if (apt->multi_threaded)
236 /* FIXME: should be randomly generated by in an RPC call to rpcss */
237 apt->oxid = ((OXID)GetCurrentProcessId() << 32) | 0xcafe;
241 /* FIXME: should be randomly generated by in an RPC call to rpcss */
242 apt->oxid = ((OXID)GetCurrentProcessId() << 32) | GetCurrentThreadId();
245 TRACE("Created apartment on OXID %s\n", wine_dbgstr_longlong(apt->oxid));
247 /* the locking here is not currently needed for the MTA case, but it
248 * doesn't hurt and makes the code simpler */
249 EnterCriticalSection(&csApartment);
250 list_add_head(&apts, &apt->entry);
251 LeaveCriticalSection(&csApartment);
256 /* gets and existing apartment if one exists or otherwise creates an apartment
257 * structure which stores OLE apartment-local information and stores a pointer
258 * to it in the thread-local storage */
259 static APARTMENT *apartment_get_or_create(DWORD model)
261 APARTMENT *apt = COM_CurrentApt();
265 if (model & COINIT_APARTMENTTHREADED)
267 apt = apartment_construct(model);
268 COM_CurrentInfo()->apt = apt;
272 EnterCriticalSection(&csApartment);
274 /* The multi-threaded apartment (MTA) contains zero or more threads interacting
275 * with free threaded (ie thread safe) COM objects. There is only ever one MTA
279 TRACE("entering the multithreaded apartment %s\n", wine_dbgstr_longlong(MTA->oxid));
280 apartment_addref(MTA);
283 MTA = apartment_construct(model);
286 COM_CurrentInfo()->apt = apt;
288 LeaveCriticalSection(&csApartment);
295 static inline BOOL apartment_is_model(APARTMENT *apt, DWORD model)
297 return (apt->multi_threaded == !(model & COINIT_APARTMENTTHREADED));
300 DWORD apartment_addref(struct apartment *apt)
302 DWORD refs = InterlockedIncrement(&apt->refs);
303 TRACE("%s: before = %ld\n", wine_dbgstr_longlong(apt->oxid), refs - 1);
307 DWORD apartment_release(struct apartment *apt)
311 EnterCriticalSection(&csApartment);
313 ret = InterlockedDecrement(&apt->refs);
314 TRACE("%s: after = %ld\n", wine_dbgstr_longlong(apt->oxid), ret);
315 /* destruction stuff that needs to happen under csApartment CS */
318 if (apt == MTA) MTA = NULL;
319 list_remove(&apt->entry);
322 LeaveCriticalSection(&csApartment);
326 struct list *cursor, *cursor2;
328 TRACE("destroying apartment %p, oxid %s\n", apt, wine_dbgstr_longlong(apt->oxid));
330 /* no locking is needed for this apartment, because no other thread
331 * can access it at this point */
333 apartment_disconnectproxies(apt);
335 if (apt->win) DestroyWindow(apt->win);
337 LIST_FOR_EACH_SAFE(cursor, cursor2, &apt->stubmgrs)
339 struct stub_manager *stubmgr = LIST_ENTRY(cursor, struct stub_manager, entry);
340 /* release the implicit reference given by the fact that the
341 * stub has external references (it must do since it is in the
342 * stub manager list in the apartment and all non-apartment users
343 * must have a ref on the apartment and so it cannot be destroyed).
345 stub_manager_int_release(stubmgr);
348 /* if this assert fires, then another thread took a reference to a
349 * stub manager without taking a reference to the containing
350 * apartment, which it must do. */
351 assert(list_empty(&apt->stubmgrs));
353 if (apt->filter) IUnknown_Release(apt->filter);
355 DEBUG_CLEAR_CRITSEC_NAME(&apt->cs);
356 DeleteCriticalSection(&apt->cs);
358 HeapFree(GetProcessHeap(), 0, apt);
364 /* The given OXID must be local to this process:
366 * The ref parameter is here mostly to ensure people remember that
367 * they get one, you should normally take a ref for thread safety.
369 APARTMENT *apartment_findfromoxid(OXID oxid, BOOL ref)
371 APARTMENT *result = NULL;
374 EnterCriticalSection(&csApartment);
375 LIST_FOR_EACH( cursor, &apts )
377 struct apartment *apt = LIST_ENTRY( cursor, struct apartment, entry );
378 if (apt->oxid == oxid)
381 if (ref) apartment_addref(result);
385 LeaveCriticalSection(&csApartment);
390 /* gets the apartment which has a given creator thread ID. The caller must
391 * release the reference from the apartment as soon as the apartment pointer
392 * is no longer required. */
393 APARTMENT *apartment_findfromtid(DWORD tid)
395 APARTMENT *result = NULL;
398 EnterCriticalSection(&csApartment);
399 LIST_FOR_EACH( cursor, &apts )
401 struct apartment *apt = LIST_ENTRY( cursor, struct apartment, entry );
405 apartment_addref(result);
409 LeaveCriticalSection(&csApartment);
414 static LRESULT CALLBACK apartment_wndproc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
419 RPC_ExecuteCall((struct dispatch_params *)lParam);
422 return DefWindowProcW(hWnd, msg, wParam, lParam);
426 HRESULT apartment_createwindowifneeded(struct apartment *apt)
428 if (apt->multi_threaded)
433 HWND hwnd = CreateWindowW(wszAptWinClass, NULL, 0,
435 0, 0, OLE32_hInstance, NULL);
438 ERR("CreateWindow failed with error %ld\n", GetLastError());
439 return HRESULT_FROM_WIN32(GetLastError());
441 if (InterlockedCompareExchangePointer((PVOID *)&apt->win, hwnd, NULL))
442 /* someone beat us to it */
449 HWND apartment_getwindow(struct apartment *apt)
451 assert(!apt->multi_threaded);
455 void apartment_joinmta(void)
457 apartment_addref(MTA);
458 COM_CurrentInfo()->apt = MTA;
461 /*****************************************************************************
462 * This section contains OpenDllList implemantation
465 static void COMPOBJ_DLLList_Add(HANDLE hLibrary)
472 EnterCriticalSection( &csOpenDllList );
474 if (openDllList == NULL) {
475 /* empty list -- add first node */
476 openDllList = HeapAlloc(GetProcessHeap(),0, sizeof(OpenDll));
477 openDllList->hLibrary=hLibrary;
478 openDllList->next = NULL;
480 /* search for this dll */
482 for (ptr = openDllList; ptr->next != NULL; ptr=ptr->next) {
483 if (ptr->hLibrary == hLibrary) {
489 /* dll not found, add it */
491 openDllList = HeapAlloc(GetProcessHeap(),0, sizeof(OpenDll));
492 openDllList->hLibrary = hLibrary;
493 openDllList->next = tmp;
497 LeaveCriticalSection( &csOpenDllList );
500 static void COMPOBJ_DllList_FreeUnused(int Timeout)
502 OpenDll *curr, *next, *prev = NULL;
503 typedef HRESULT (WINAPI *DllCanUnloadNowFunc)(void);
504 DllCanUnloadNowFunc DllCanUnloadNow;
508 EnterCriticalSection( &csOpenDllList );
510 for (curr = openDllList; curr != NULL; ) {
511 DllCanUnloadNow = (DllCanUnloadNowFunc) GetProcAddress(curr->hLibrary, "DllCanUnloadNow");
513 if ( (DllCanUnloadNow != NULL) && (DllCanUnloadNow() == S_OK) ) {
516 TRACE("freeing %p\n", curr->hLibrary);
517 FreeLibrary(curr->hLibrary);
519 HeapFree(GetProcessHeap(), 0, curr);
520 if (curr == openDllList) {
533 LeaveCriticalSection( &csOpenDllList );
536 /******************************************************************************
537 * CoBuildVersion [OLE32.@]
538 * CoBuildVersion [COMPOBJ.1]
540 * Gets the build version of the DLL.
545 * Current build version, hiword is majornumber, loword is minornumber
547 DWORD WINAPI CoBuildVersion(void)
549 TRACE("Returning version %d, build %d.\n", rmm, rup);
550 return (rmm<<16)+rup;
553 /******************************************************************************
554 * CoInitialize [OLE32.@]
556 * Initializes the COM libraries by calling CoInitializeEx with
557 * COINIT_APARTMENTTHREADED, ie it enters a STA thread.
560 * lpReserved [I] Pointer to IMalloc interface (obsolete, should be NULL).
563 * Success: S_OK if not already initialized, S_FALSE otherwise.
564 * Failure: HRESULT code.
569 HRESULT WINAPI CoInitialize(LPVOID lpReserved)
572 * Just delegate to the newer method.
574 return CoInitializeEx(lpReserved, COINIT_APARTMENTTHREADED);
577 /******************************************************************************
578 * CoInitializeEx [OLE32.@]
580 * Initializes the COM libraries.
583 * lpReserved [I] Pointer to IMalloc interface (obsolete, should be NULL).
584 * dwCoInit [I] One or more flags from the COINIT enumeration. See notes.
587 * S_OK if successful,
588 * S_FALSE if this function was called already.
589 * RPC_E_CHANGED_MODE if a previous call to CoInitializeEx specified another
594 * The behavior used to set the IMalloc used for memory management is
596 * The dwCoInit parameter must specify of of the following apartment
598 *| COINIT_APARTMENTTHREADED - A single-threaded apartment (STA).
599 *| COINIT_MULTITHREADED - A multi-threaded apartment (MTA).
600 * The parameter may also specify zero or more of the following flags:
601 *| COINIT_DISABLE_OLE1DDE - Don't use DDE for OLE1 support.
602 *| COINIT_SPEED_OVER_MEMORY - Trade memory for speed.
607 HRESULT WINAPI CoInitializeEx(LPVOID lpReserved, DWORD dwCoInit)
612 TRACE("(%p, %x)\n", lpReserved, (int)dwCoInit);
614 if (lpReserved!=NULL)
616 ERR("(%p, %x) - Bad parameter passed-in %p, must be an old Windows Application\n", lpReserved, (int)dwCoInit, lpReserved);
620 * Check the lock count. If this is the first time going through the initialize
621 * process, we have to initialize the libraries.
623 * And crank-up that lock count.
625 if (InterlockedExchangeAdd(&s_COMLockCount,1)==0)
628 * Initialize the various COM libraries and data structures.
630 TRACE("() - Initializing the COM libraries\n");
632 /* we may need to defer this until after apartment initialisation */
633 RunningObjectTableImpl_Initialize();
636 if (!(apt = COM_CurrentInfo()->apt))
638 apt = apartment_get_or_create(dwCoInit);
639 if (!apt) return E_OUTOFMEMORY;
641 else if (!apartment_is_model(apt, dwCoInit))
643 /* Changing the threading model after it's been set is illegal. If this warning is triggered by Wine
644 code then we are probably using the wrong threading model to implement that API. */
645 ERR("Attempt to change threading model of this apartment from %s to %s\n",
646 apt->multi_threaded ? "multi-threaded" : "apartment threaded",
647 dwCoInit & COINIT_APARTMENTTHREADED ? "apartment threaded" : "multi-threaded");
648 return RPC_E_CHANGED_MODE;
653 COM_CurrentInfo()->inits++;
658 /* On COM finalization for a STA thread, the message queue is flushed to ensure no
659 pending RPCs are ignored. Non-COM messages are discarded at this point.
661 static void COM_FlushMessageQueue(void)
664 APARTMENT *apt = COM_CurrentApt();
666 if (!apt || !apt->win) return;
668 TRACE("Flushing STA message queue\n");
670 while (PeekMessageA(&message, NULL, 0, 0, PM_REMOVE))
672 if (message.hwnd != apt->win)
674 WARN("discarding message 0x%x for window %p\n", message.message, message.hwnd);
678 TranslateMessage(&message);
679 DispatchMessageA(&message);
683 /***********************************************************************
684 * CoUninitialize [OLE32.@]
686 * This method will decrement the refcount on the current apartment, freeing
687 * the resources associated with it if it is the last thread in the apartment.
688 * If the last apartment is freed, the function will additionally release
689 * any COM resources associated with the process.
699 void WINAPI CoUninitialize(void)
701 struct oletls * info = COM_CurrentInfo();
706 /* will only happen on OOM */
712 ERR("Mismatched CoUninitialize\n");
718 apartment_release(info->apt);
723 * Decrease the reference count.
724 * If we are back to 0 locks on the COM library, make sure we free
725 * all the associated data structures.
727 lCOMRefCnt = InterlockedExchangeAdd(&s_COMLockCount,-1);
730 TRACE("() - Releasing the COM libraries\n");
732 RunningObjectTableImpl_UnInitialize();
734 /* Release the references to the registered class objects */
735 COM_RevokeAllClasses();
737 /* This will free the loaded COM Dlls */
738 CoFreeAllLibraries();
740 /* This ensures we deal with any pending RPCs */
741 COM_FlushMessageQueue();
743 else if (lCOMRefCnt<1) {
744 ERR( "CoUninitialize() - not CoInitialized.\n" );
745 InterlockedExchangeAdd(&s_COMLockCount,1); /* restore the lock count. */
749 /******************************************************************************
750 * CoDisconnectObject [OLE32.@]
751 * CoDisconnectObject [COMPOBJ.15]
753 * Disconnects all connections to this object from remote processes. Dispatches
754 * pending RPCs while blocking new RPCs from occurring, and then calls
755 * IMarshal::DisconnectObject on the given object.
757 * Typically called when the object server is forced to shut down, for instance by
761 * lpUnk [I] The object whose stub should be disconnected.
762 * reserved [I] Reserved. Should be set to 0.
766 * Failure: HRESULT code.
769 * CoMarshalInterface, CoReleaseMarshalData, CoLockObjectExternal
771 HRESULT WINAPI CoDisconnectObject( LPUNKNOWN lpUnk, DWORD reserved )
777 TRACE("(%p, 0x%08lx)\n", lpUnk, reserved);
779 hr = IUnknown_QueryInterface(lpUnk, &IID_IMarshal, (void **)&marshal);
782 hr = IMarshal_DisconnectObject(marshal, reserved);
783 IMarshal_Release(marshal);
787 apt = COM_CurrentApt();
789 return CO_E_NOTINITIALIZED;
791 apartment_disconnectobject(apt, lpUnk);
793 /* Note: native is pretty broken here because it just silently
794 * fails, without returning an appropriate error code if the object was
795 * not found, making apps think that the object was disconnected, when
796 * it actually wasn't */
801 /******************************************************************************
802 * CoCreateGuid [OLE32.@]
804 * Simply forwards to UuidCreate in RPCRT4.
807 * pguid [O] Points to the GUID to initialize.
811 * Failure: HRESULT code.
816 HRESULT WINAPI CoCreateGuid(GUID *pguid)
818 return UuidCreate(pguid);
821 /******************************************************************************
822 * CLSIDFromString [OLE32.@]
823 * IIDFromString [OLE32.@]
825 * Converts a unique identifier from its string representation into
829 * idstr [I] The string representation of the GUID.
830 * id [O] GUID converted from the string.
834 * CO_E_CLASSSTRING if idstr is not a valid CLSID
839 static HRESULT WINAPI __CLSIDFromString(LPCWSTR s, CLSID *id)
845 memset( id, 0, sizeof (CLSID) );
849 /* validate the CLSID string */
850 if (strlenW(s) != 38)
851 return CO_E_CLASSSTRING;
853 if ((s[0]!='{') || (s[9]!='-') || (s[14]!='-') || (s[19]!='-') || (s[24]!='-') || (s[37]!='}'))
854 return CO_E_CLASSSTRING;
856 for (i=1; i<37; i++) {
857 if ((i == 9)||(i == 14)||(i == 19)||(i == 24)) continue;
858 if (!(((s[i] >= '0') && (s[i] <= '9')) ||
859 ((s[i] >= 'a') && (s[i] <= 'f')) ||
860 ((s[i] >= 'A') && (s[i] <= 'F'))))
861 return CO_E_CLASSSTRING;
864 TRACE("%s -> %p\n", debugstr_w(s), id);
866 /* quick lookup table */
867 memset(table, 0, 256);
869 for (i = 0; i < 10; i++) {
872 for (i = 0; i < 6; i++) {
873 table['A' + i] = i+10;
874 table['a' + i] = i+10;
877 /* in form {XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX} */
879 id->Data1 = (table[s[1]] << 28 | table[s[2]] << 24 | table[s[3]] << 20 | table[s[4]] << 16 |
880 table[s[5]] << 12 | table[s[6]] << 8 | table[s[7]] << 4 | table[s[8]]);
881 id->Data2 = table[s[10]] << 12 | table[s[11]] << 8 | table[s[12]] << 4 | table[s[13]];
882 id->Data3 = table[s[15]] << 12 | table[s[16]] << 8 | table[s[17]] << 4 | table[s[18]];
884 /* these are just sequential bytes */
885 id->Data4[0] = table[s[20]] << 4 | table[s[21]];
886 id->Data4[1] = table[s[22]] << 4 | table[s[23]];
887 id->Data4[2] = table[s[25]] << 4 | table[s[26]];
888 id->Data4[3] = table[s[27]] << 4 | table[s[28]];
889 id->Data4[4] = table[s[29]] << 4 | table[s[30]];
890 id->Data4[5] = table[s[31]] << 4 | table[s[32]];
891 id->Data4[6] = table[s[33]] << 4 | table[s[34]];
892 id->Data4[7] = table[s[35]] << 4 | table[s[36]];
897 /*****************************************************************************/
899 HRESULT WINAPI CLSIDFromString(LPOLESTR idstr, CLSID *id )
903 ret = __CLSIDFromString(idstr, id);
904 if(ret != S_OK) { /* It appears a ProgID is also valid */
905 ret = CLSIDFromProgID(idstr, id);
910 /* Converts a GUID into the respective string representation. */
911 HRESULT WINE_StringFromCLSID(
912 const CLSID *id, /* [in] GUID to be converted */
913 LPSTR idstr /* [out] pointer to buffer to contain converted guid */
915 static const char *hex = "0123456789ABCDEF";
920 { ERR("called with id=Null\n");
925 sprintf(idstr, "{%08lX-%04X-%04X-%02X%02X-",
926 id->Data1, id->Data2, id->Data3,
927 id->Data4[0], id->Data4[1]);
931 for (i = 2; i < 8; i++) {
932 *s++ = hex[id->Data4[i]>>4];
933 *s++ = hex[id->Data4[i] & 0xf];
939 TRACE("%p->%s\n", id, idstr);
945 /******************************************************************************
946 * StringFromCLSID [OLE32.@]
947 * StringFromIID [OLE32.@]
949 * Converts a GUID into the respective string representation.
950 * The target string is allocated using the OLE IMalloc.
953 * id [I] the GUID to be converted.
954 * idstr [O] A pointer to a to-be-allocated pointer pointing to the resulting string.
961 * StringFromGUID2, CLSIDFromString
963 HRESULT WINAPI StringFromCLSID(REFCLSID id, LPOLESTR *idstr)
969 if ((ret = CoGetMalloc(0,&mllc)))
972 ret=WINE_StringFromCLSID(id,buf);
974 DWORD len = MultiByteToWideChar( CP_ACP, 0, buf, -1, NULL, 0 );
975 *idstr = IMalloc_Alloc( mllc, len * sizeof(WCHAR) );
976 MultiByteToWideChar( CP_ACP, 0, buf, -1, *idstr, len );
981 /******************************************************************************
982 * StringFromGUID2 [OLE32.@]
983 * StringFromGUID2 [COMPOBJ.76]
985 * Modified version of StringFromCLSID that allows you to specify max
989 * id [I] GUID to convert to string.
990 * str [O] Buffer where the result will be stored.
991 * cmax [I] Size of the buffer in characters.
994 * Success: The length of the resulting string in characters.
997 INT WINAPI StringFromGUID2(REFGUID id, LPOLESTR str, INT cmax)
1001 if (WINE_StringFromCLSID(id,xguid))
1003 return MultiByteToWideChar( CP_ACP, 0, xguid, -1, str, cmax );
1006 /* open HKCR\\CLSID\\{string form of clsid}\\{keyname} key */
1007 HRESULT COM_OpenKeyForCLSID(REFCLSID clsid, LPCWSTR keyname, REGSAM access, HKEY *subkey)
1009 static const WCHAR wszCLSIDSlash[] = {'C','L','S','I','D','\\',0};
1010 WCHAR path[CHARS_IN_GUID + ARRAYSIZE(wszCLSIDSlash) - 1];
1014 strcpyW(path, wszCLSIDSlash);
1015 StringFromGUID2(clsid, path + strlenW(wszCLSIDSlash), CHARS_IN_GUID);
1016 res = RegOpenKeyExW(HKEY_CLASSES_ROOT, path, 0, keyname ? KEY_READ : access, &key);
1017 if (res == ERROR_FILE_NOT_FOUND)
1018 return REGDB_E_CLASSNOTREG;
1019 else if (res != ERROR_SUCCESS)
1020 return REGDB_E_READREGDB;
1028 res = RegOpenKeyExW(key, keyname, 0, access, subkey);
1030 if (res == ERROR_FILE_NOT_FOUND)
1031 return REGDB_E_KEYMISSING;
1032 else if (res != ERROR_SUCCESS)
1033 return REGDB_E_READREGDB;
1038 /******************************************************************************
1039 * ProgIDFromCLSID [OLE32.@]
1041 * Converts a class id into the respective program ID.
1044 * clsid [I] Class ID, as found in registry.
1045 * lplpszProgID [O] Associated ProgID.
1050 * REGDB_E_CLASSNOTREG if the given clsid has no associated ProgID
1052 HRESULT WINAPI ProgIDFromCLSID(REFCLSID clsid, LPOLESTR *lplpszProgID)
1054 static const WCHAR wszProgID[] = {'P','r','o','g','I','D',0};
1059 *lplpszProgID = NULL;
1060 ret = COM_OpenKeyForCLSID(clsid, wszProgID, KEY_READ, &hkey);
1064 if (RegQueryValueW(hkey, NULL, NULL, &progidlen))
1065 ret = REGDB_E_CLASSNOTREG;
1069 *lplpszProgID = CoTaskMemAlloc(progidlen * sizeof(WCHAR));
1072 if (RegQueryValueW(hkey, NULL, *lplpszProgID, &progidlen))
1073 ret = REGDB_E_CLASSNOTREG;
1076 ret = E_OUTOFMEMORY;
1083 /******************************************************************************
1084 * CLSIDFromProgID [OLE32.@]
1086 * Converts a program id into the respective GUID.
1089 * progid [I] Unicode program ID, as found in registry.
1090 * riid [O] Associated CLSID.
1094 * Failure: CO_E_CLASSSTRING - the given ProgID cannot be found.
1096 HRESULT WINAPI CLSIDFromProgID(LPCOLESTR progid, LPCLSID riid)
1098 static const WCHAR clsidW[] = { '\\','C','L','S','I','D',0 };
1099 WCHAR buf2[CHARS_IN_GUID];
1100 LONG buf2len = sizeof(buf2);
1103 WCHAR *buf = HeapAlloc( GetProcessHeap(),0,(strlenW(progid)+8) * sizeof(WCHAR) );
1104 strcpyW( buf, progid );
1105 strcatW( buf, clsidW );
1106 if (RegOpenKeyW(HKEY_CLASSES_ROOT,buf,&xhkey))
1108 HeapFree(GetProcessHeap(),0,buf);
1109 return CO_E_CLASSSTRING;
1111 HeapFree(GetProcessHeap(),0,buf);
1113 if (RegQueryValueW(xhkey,NULL,buf2,&buf2len))
1116 return CO_E_CLASSSTRING;
1119 return CLSIDFromString(buf2,riid);
1123 /*****************************************************************************
1124 * CoGetPSClsid [OLE32.@]
1126 * Retrieves the CLSID of the proxy/stub factory that implements
1127 * IPSFactoryBuffer for the specified interface.
1130 * riid [I] Interface whose proxy/stub CLSID is to be returned.
1131 * pclsid [O] Where to store returned proxy/stub CLSID.
1136 * REGDB_E_IIDNOTREG if no PSFactoryBuffer is associated with the IID, or it could not be parsed
1140 * The standard marshaller activates the object with the CLSID
1141 * returned and uses the CreateProxy and CreateStub methods on its
1142 * IPSFactoryBuffer interface to construct the proxies and stubs for a
1145 * CoGetPSClsid determines this CLSID by searching the
1146 * HKEY_CLASSES_ROOT\Interface\{string form of riid}\ProxyStubClsid32
1147 * in the registry and any interface id registered by
1148 * CoRegisterPSClsid within the current process.
1152 * We only search the registry, not ids registered with
1153 * CoRegisterPSClsid.
1154 * Also, native returns S_OK for interfaces with a key in HKCR\Interface, but
1155 * without a ProxyStubClsid32 key and leaves garbage in pclsid. This should be
1156 * considered a bug in native unless an application depends on this (unlikely).
1158 HRESULT WINAPI CoGetPSClsid(REFIID riid, CLSID *pclsid)
1160 static const WCHAR wszInterface[] = {'I','n','t','e','r','f','a','c','e','\\',0};
1161 static const WCHAR wszPSC[] = {'\\','P','r','o','x','y','S','t','u','b','C','l','s','i','d','3','2',0};
1162 WCHAR path[ARRAYSIZE(wszInterface) - 1 + CHARS_IN_GUID - 1 + ARRAYSIZE(wszPSC)];
1163 WCHAR value[CHARS_IN_GUID];
1167 TRACE("() riid=%s, pclsid=%p\n", debugstr_guid(riid), pclsid);
1169 /* Interface\\{string form of riid}\\ProxyStubClsid32 */
1170 strcpyW(path, wszInterface);
1171 StringFromGUID2(riid, path + ARRAYSIZE(wszInterface) - 1, CHARS_IN_GUID);
1172 strcpyW(path + ARRAYSIZE(wszInterface) - 1 + CHARS_IN_GUID - 1, wszPSC);
1174 /* Open the key.. */
1175 if (RegOpenKeyExW(HKEY_CLASSES_ROOT, path, 0, KEY_READ, &hkey))
1177 WARN("No PSFactoryBuffer object is registered for IID %s\n", debugstr_guid(riid));
1178 return REGDB_E_IIDNOTREG;
1181 /* ... Once we have the key, query the registry to get the
1182 value of CLSID as a string, and convert it into a
1183 proper CLSID structure to be passed back to the app */
1184 len = sizeof(value);
1185 if (ERROR_SUCCESS != RegQueryValueW(hkey, NULL, value, &len))
1188 return REGDB_E_IIDNOTREG;
1192 /* We have the CLSid we want back from the registry as a string, so
1193 lets convert it into a CLSID structure */
1194 if (CLSIDFromString(value, pclsid) != NOERROR)
1195 return REGDB_E_IIDNOTREG;
1197 TRACE ("() Returning CLSID=%s\n", debugstr_guid(pclsid));
1203 /***********************************************************************
1204 * WriteClassStm (OLE32.@)
1206 * Writes a CLSID to a stream.
1209 * pStm [I] Stream to write to.
1210 * rclsid [I] CLSID to write.
1214 * Failure: HRESULT code.
1216 HRESULT WINAPI WriteClassStm(IStream *pStm,REFCLSID rclsid)
1218 TRACE("(%p,%p)\n",pStm,rclsid);
1221 return E_INVALIDARG;
1223 return IStream_Write(pStm,rclsid,sizeof(CLSID),NULL);
1226 /***********************************************************************
1227 * ReadClassStm (OLE32.@)
1229 * Reads a CLSID from a stream.
1232 * pStm [I] Stream to read from.
1233 * rclsid [O] CLSID to read.
1237 * Failure: HRESULT code.
1239 HRESULT WINAPI ReadClassStm(IStream *pStm,CLSID *pclsid)
1244 TRACE("(%p,%p)\n",pStm,pclsid);
1247 return E_INVALIDARG;
1249 res = IStream_Read(pStm,(void*)pclsid,sizeof(CLSID),&nbByte);
1254 if (nbByte != sizeof(CLSID))
1262 * COM_GetRegisteredClassObject
1264 * This internal method is used to scan the registered class list to
1265 * find a class object.
1268 * rclsid Class ID of the class to find.
1269 * dwClsContext Class context to match.
1270 * ppv [out] returns a pointer to the class object. Complying
1271 * to normal COM usage, this method will increase the
1272 * reference count on this object.
1274 static HRESULT COM_GetRegisteredClassObject(
1279 HRESULT hr = S_FALSE;
1280 RegisteredClass* curClass;
1282 EnterCriticalSection( &csRegisteredClassList );
1290 * Iterate through the whole list and try to match the class ID.
1292 curClass = firstRegisteredClass;
1294 while (curClass != 0)
1297 * Check if we have a match on the class ID.
1299 if (IsEqualGUID(&(curClass->classIdentifier), rclsid))
1302 * Since we don't do out-of process or DCOM just right away, let's ignore the
1307 * We have a match, return the pointer to the class object.
1309 *ppUnk = curClass->classObject;
1311 IUnknown_AddRef(curClass->classObject);
1318 * Step to the next class in the list.
1320 curClass = curClass->nextClass;
1324 LeaveCriticalSection( &csRegisteredClassList );
1326 * If we get to here, we haven't found our class.
1331 /******************************************************************************
1332 * CoRegisterClassObject [OLE32.@]
1334 * Registers the class object for a given class ID. Servers housed in EXE
1335 * files use this method instead of exporting DllGetClassObject to allow
1336 * other code to connect to their objects.
1339 * rclsid [I] CLSID of the object to register.
1340 * pUnk [I] IUnknown of the object.
1341 * dwClsContext [I] CLSCTX flags indicating the context in which to run the executable.
1342 * flags [I] REGCLS flags indicating how connections are made.
1343 * lpdwRegister [I] A unique cookie that can be passed to CoRevokeClassObject.
1347 * E_INVALIDARG if lpdwRegister or pUnk are NULL,
1348 * CO_E_OBJISREG if the object is already registered. We should not return this.
1351 * CoRevokeClassObject, CoGetClassObject
1354 * MSDN claims that multiple interface registrations are legal, but we
1355 * can't do that with our current implementation.
1357 HRESULT WINAPI CoRegisterClassObject(
1362 LPDWORD lpdwRegister)
1364 RegisteredClass* newClass;
1365 LPUNKNOWN foundObject;
1368 TRACE("(%s,%p,0x%08lx,0x%08lx,%p)\n",
1369 debugstr_guid(rclsid),pUnk,dwClsContext,flags,lpdwRegister);
1371 if ( (lpdwRegister==0) || (pUnk==0) )
1372 return E_INVALIDARG;
1374 if (!COM_CurrentApt())
1376 ERR("COM was not initialized\n");
1377 return CO_E_NOTINITIALIZED;
1383 * First, check if the class is already registered.
1384 * If it is, this should cause an error.
1386 hr = COM_GetRegisteredClassObject(rclsid, dwClsContext, &foundObject);
1388 if (flags & REGCLS_MULTIPLEUSE) {
1389 if (dwClsContext & CLSCTX_LOCAL_SERVER)
1390 hr = CoLockObjectExternal(foundObject, TRUE, FALSE);
1391 IUnknown_Release(foundObject);
1394 IUnknown_Release(foundObject);
1395 ERR("object already registered for class %s\n", debugstr_guid(rclsid));
1396 return CO_E_OBJISREG;
1399 newClass = HeapAlloc(GetProcessHeap(), 0, sizeof(RegisteredClass));
1400 if ( newClass == NULL )
1401 return E_OUTOFMEMORY;
1403 EnterCriticalSection( &csRegisteredClassList );
1405 newClass->classIdentifier = *rclsid;
1406 newClass->runContext = dwClsContext;
1407 newClass->connectFlags = flags;
1408 newClass->pMarshaledData = NULL;
1411 * Use the address of the chain node as the cookie since we are sure it's
1412 * unique. FIXME: not on 64-bit platforms.
1414 newClass->dwCookie = (DWORD)newClass;
1415 newClass->nextClass = firstRegisteredClass;
1418 * Since we're making a copy of the object pointer, we have to increase its
1421 newClass->classObject = pUnk;
1422 IUnknown_AddRef(newClass->classObject);
1424 firstRegisteredClass = newClass;
1425 LeaveCriticalSection( &csRegisteredClassList );
1427 *lpdwRegister = newClass->dwCookie;
1429 if (dwClsContext & CLSCTX_LOCAL_SERVER) {
1430 IClassFactory *classfac;
1432 hr = IUnknown_QueryInterface(newClass->classObject, &IID_IClassFactory,
1433 (LPVOID*)&classfac);
1436 hr = CreateStreamOnHGlobal(0, TRUE, &newClass->pMarshaledData);
1438 FIXME("Failed to create stream on hglobal, %lx\n", hr);
1439 IUnknown_Release(classfac);
1442 hr = CoMarshalInterface(newClass->pMarshaledData, &IID_IClassFactory,
1443 (LPVOID)classfac, MSHCTX_LOCAL, NULL,
1444 MSHLFLAGS_TABLESTRONG);
1446 FIXME("CoMarshalInterface failed, %lx!\n",hr);
1447 IUnknown_Release(classfac);
1451 IUnknown_Release(classfac);
1453 RPC_StartLocalServer(&newClass->classIdentifier, newClass->pMarshaledData);
1458 /***********************************************************************
1459 * CoRevokeClassObject [OLE32.@]
1461 * Removes a class object from the class registry.
1464 * dwRegister [I] Cookie returned from CoRegisterClassObject().
1468 * Failure: HRESULT code.
1471 * CoRegisterClassObject
1473 HRESULT WINAPI CoRevokeClassObject(
1476 HRESULT hr = E_INVALIDARG;
1477 RegisteredClass** prevClassLink;
1478 RegisteredClass* curClass;
1480 TRACE("(%08lx)\n",dwRegister);
1482 EnterCriticalSection( &csRegisteredClassList );
1485 * Iterate through the whole list and try to match the cookie.
1487 curClass = firstRegisteredClass;
1488 prevClassLink = &firstRegisteredClass;
1490 while (curClass != 0)
1493 * Check if we have a match on the cookie.
1495 if (curClass->dwCookie == dwRegister)
1498 * Remove the class from the chain.
1500 *prevClassLink = curClass->nextClass;
1503 * Release the reference to the class object.
1505 IUnknown_Release(curClass->classObject);
1507 if (curClass->pMarshaledData)
1510 memset(&zero, 0, sizeof(zero));
1511 /* FIXME: stop local server thread */
1512 IStream_Seek(curClass->pMarshaledData, zero, SEEK_SET, NULL);
1513 CoReleaseMarshalData(curClass->pMarshaledData);
1517 * Free the memory used by the chain node.
1519 HeapFree(GetProcessHeap(), 0, curClass);
1526 * Step to the next class in the list.
1528 prevClassLink = &(curClass->nextClass);
1529 curClass = curClass->nextClass;
1533 LeaveCriticalSection( &csRegisteredClassList );
1535 * If we get to here, we haven't found our class.
1540 /***********************************************************************
1541 * COM_RegReadPath [internal]
1543 * Reads a registry value and expands it when necessary
1545 HRESULT COM_RegReadPath(HKEY hkeyroot, const WCHAR *keyname, const WCHAR *valuename, WCHAR * dst, DWORD dstlen)
1550 WCHAR src[MAX_PATH];
1551 DWORD dwLength = dstlen * sizeof(WCHAR);
1553 if((hres = RegOpenKeyExW(hkeyroot, keyname, 0, KEY_READ, &key)) == ERROR_SUCCESS) {
1554 if( (hres = RegQueryValueExW(key, NULL, NULL, &keytype, (LPBYTE)src, &dwLength)) == ERROR_SUCCESS ) {
1555 if (keytype == REG_EXPAND_SZ) {
1556 if (dstlen <= ExpandEnvironmentStringsW(src, dst, dstlen)) hres = ERROR_MORE_DATA;
1558 lstrcpynW(dst, src, dstlen);
1566 static HRESULT get_inproc_class_object(HKEY hkeydll, REFCLSID rclsid, REFIID riid, void **ppv)
1569 typedef HRESULT (CALLBACK *DllGetClassObjectFunc)(REFCLSID clsid, REFIID iid, LPVOID *ppv);
1570 DllGetClassObjectFunc DllGetClassObject;
1571 WCHAR dllpath[MAX_PATH+1];
1573 if (COM_RegReadPath(hkeydll, NULL, NULL, dllpath, ARRAYSIZE(dllpath)) != ERROR_SUCCESS)
1575 /* failure: CLSID is not found in registry */
1576 WARN("class %s not registered inproc\n", debugstr_guid(rclsid));
1577 return REGDB_E_CLASSNOTREG;
1580 if ((hLibrary = LoadLibraryExW(dllpath, 0, LOAD_WITH_ALTERED_SEARCH_PATH)) == 0)
1582 /* failure: DLL could not be loaded */
1583 ERR("couldn't load in-process dll %s\n", debugstr_w(dllpath));
1584 return E_ACCESSDENIED; /* FIXME: or should this be CO_E_DLLNOTFOUND? */
1587 if (!(DllGetClassObject = (DllGetClassObjectFunc)GetProcAddress(hLibrary, "DllGetClassObject")))
1589 /* failure: the dll did not export DllGetClassObject */
1590 ERR("couldn't find function DllGetClassObject in %s\n", debugstr_w(dllpath));
1591 FreeLibrary( hLibrary );
1592 return CO_E_DLLNOTFOUND;
1595 /* OK: get the ClassObject */
1596 COMPOBJ_DLLList_Add( hLibrary );
1597 return DllGetClassObject(rclsid, riid, ppv);
1600 /***********************************************************************
1601 * CoGetClassObject [OLE32.@]
1603 * FIXME. If request allows of several options and there is a failure
1604 * with one (other than not being registered) do we try the
1605 * others or return failure? (E.g. inprocess is registered but
1606 * the DLL is not found but the server version works)
1608 HRESULT WINAPI CoGetClassObject(
1609 REFCLSID rclsid, DWORD dwClsContext, COSERVERINFO *pServerInfo,
1610 REFIID iid, LPVOID *ppv)
1612 LPUNKNOWN regClassObject;
1613 HRESULT hres = E_UNEXPECTED;
1615 TRACE("\n\tCLSID:\t%s,\n\tIID:\t%s\n", debugstr_guid(rclsid), debugstr_guid(iid));
1618 FIXME("\tpServerInfo: name=%s\n",debugstr_w(pServerInfo->pwszName));
1619 FIXME("\t\tpAuthInfo=%p\n",pServerInfo->pAuthInfo);
1623 * First, try and see if we can't match the class ID with one of the
1624 * registered classes.
1626 if (S_OK == COM_GetRegisteredClassObject(rclsid, dwClsContext, ®ClassObject))
1628 /* Get the required interface from the retrieved pointer. */
1629 hres = IUnknown_QueryInterface(regClassObject, iid, ppv);
1632 * Since QI got another reference on the pointer, we want to release the
1633 * one we already have. If QI was unsuccessful, this will release the object. This
1634 * is good since we are not returning it in the "out" parameter.
1636 IUnknown_Release(regClassObject);
1641 /* First try in-process server */
1642 if (CLSCTX_INPROC_SERVER & dwClsContext)
1644 static const WCHAR wszInprocServer32[] = {'I','n','p','r','o','c','S','e','r','v','e','r','3','2',0};
1647 hres = COM_OpenKeyForCLSID(rclsid, wszInprocServer32, KEY_READ, &hkey);
1650 if (hres == REGDB_E_CLASSNOTREG)
1651 ERR("class %s not registered\n", debugstr_guid(rclsid));
1653 WARN("class %s not registered as in-proc server\n", debugstr_guid(rclsid));
1656 if (SUCCEEDED(hres))
1658 hres = get_inproc_class_object(hkey, rclsid, iid, ppv);
1662 /* return if we got a class, otherwise fall through to one of the
1664 if (SUCCEEDED(hres))
1668 /* Next try in-process handler */
1669 if (CLSCTX_INPROC_HANDLER & dwClsContext)
1671 static const WCHAR wszInprocHandler32[] = {'I','n','p','r','o','c','H','a','n','d','l','e','r','3','2',0};
1674 hres = COM_OpenKeyForCLSID(rclsid, wszInprocHandler32, KEY_READ, &hkey);
1677 if (hres == REGDB_E_CLASSNOTREG)
1678 ERR("class %s not registered\n", debugstr_guid(rclsid));
1680 WARN("class %s not registered in-proc handler\n", debugstr_guid(rclsid));
1683 if (SUCCEEDED(hres))
1685 hres = get_inproc_class_object(hkey, rclsid, iid, ppv);
1689 /* return if we got a class, otherwise fall through to one of the
1691 if (SUCCEEDED(hres))
1695 /* Next try out of process */
1696 if (CLSCTX_LOCAL_SERVER & dwClsContext)
1698 return RPC_GetLocalClassObject(rclsid,iid,ppv);
1701 /* Finally try remote: this requires networked DCOM (a lot of work) */
1702 if (CLSCTX_REMOTE_SERVER & dwClsContext)
1704 FIXME ("CLSCTX_REMOTE_SERVER not supported\n");
1705 hres = E_NOINTERFACE;
1709 ERR("no class object %s could be created for for context 0x%lx\n",
1710 debugstr_guid(rclsid), dwClsContext);
1714 /***********************************************************************
1715 * CoResumeClassObjects (OLE32.@)
1717 * Resumes all class objects registered with REGCLS_SUSPENDED.
1721 * Failure: HRESULT code.
1723 HRESULT WINAPI CoResumeClassObjects(void)
1729 /***********************************************************************
1730 * GetClassFile (OLE32.@)
1732 * This function supplies the CLSID associated with the given filename.
1734 HRESULT WINAPI GetClassFile(LPCOLESTR filePathName,CLSID *pclsid)
1738 int nbElm, length, i;
1740 LPOLESTR *pathDec=0,absFile=0,progId=0;
1742 static const WCHAR bkslashW[] = {'\\',0};
1743 static const WCHAR dotW[] = {'.',0};
1745 TRACE("%s, %p\n", debugstr_w(filePathName), pclsid);
1747 /* if the file contain a storage object the return the CLSID written by IStorage_SetClass method*/
1748 if((StgIsStorageFile(filePathName))==S_OK){
1750 res=StgOpenStorage(filePathName,NULL,STGM_READ | STGM_SHARE_DENY_WRITE,NULL,0,&pstg);
1753 res=ReadClassStg(pstg,pclsid);
1755 IStorage_Release(pstg);
1759 /* if the file is not a storage object then attemps to match various bits in the file against a
1760 pattern in the registry. this case is not frequently used ! so I present only the psodocode for
1763 for(i=0;i<nFileTypes;i++)
1765 for(i=0;j<nPatternsForType;j++){
1770 pat=ReadPatternFromRegistry(i,j);
1771 hFile=CreateFileW(filePathName,,,,,,hFile);
1772 SetFilePosition(hFile,pat.offset);
1773 ReadFile(hFile,buf,pat.size,&r,NULL);
1774 if (memcmp(buf&pat.mask,pat.pattern.pat.size)==0){
1776 *pclsid=ReadCLSIDFromRegistry(i);
1782 /* if the above strategies fail then search for the extension key in the registry */
1784 /* get the last element (absolute file) in the path name */
1785 nbElm=FileMonikerImpl_DecomposePath(filePathName,&pathDec);
1786 absFile=pathDec[nbElm-1];
1788 /* failed if the path represente a directory and not an absolute file name*/
1789 if (!lstrcmpW(absFile, bkslashW))
1790 return MK_E_INVALIDEXTENSION;
1792 /* get the extension of the file */
1794 length=lstrlenW(absFile);
1795 for(i = length-1; (i >= 0) && *(extension = &absFile[i]) != '.'; i--)
1798 if (!extension || !lstrcmpW(extension, dotW))
1799 return MK_E_INVALIDEXTENSION;
1801 res=RegQueryValueW(HKEY_CLASSES_ROOT, extension, NULL, &sizeProgId);
1803 /* get the progId associated to the extension */
1804 progId = CoTaskMemAlloc(sizeProgId);
1805 res = RegQueryValueW(HKEY_CLASSES_ROOT, extension, progId, &sizeProgId);
1807 if (res==ERROR_SUCCESS)
1808 /* return the clsid associated to the progId */
1809 res= CLSIDFromProgID(progId,pclsid);
1811 for(i=0; pathDec[i]!=NULL;i++)
1812 CoTaskMemFree(pathDec[i]);
1813 CoTaskMemFree(pathDec);
1815 CoTaskMemFree(progId);
1817 if (res==ERROR_SUCCESS)
1820 return MK_E_INVALIDEXTENSION;
1823 /***********************************************************************
1824 * CoCreateInstance [OLE32.@]
1826 HRESULT WINAPI CoCreateInstance(
1828 LPUNKNOWN pUnkOuter,
1834 LPCLASSFACTORY lpclf = 0;
1836 TRACE("(rclsid=%s, pUnkOuter=%p, dwClsContext=%08lx, riid=%s, ppv=%p)\n", debugstr_guid(rclsid),
1837 pUnkOuter, dwClsContext, debugstr_guid(iid), ppv);
1846 * Initialize the "out" parameter
1850 if (!COM_CurrentApt())
1852 ERR("apartment not initialised\n");
1853 return CO_E_NOTINITIALIZED;
1857 * The Standard Global Interface Table (GIT) object is a process-wide singleton.
1858 * Rather than create a class factory, we can just check for it here
1860 if (IsEqualIID(rclsid, &CLSID_StdGlobalInterfaceTable)) {
1861 if (StdGlobalInterfaceTableInstance == NULL)
1862 StdGlobalInterfaceTableInstance = StdGlobalInterfaceTable_Construct();
1863 hres = IGlobalInterfaceTable_QueryInterface( (IGlobalInterfaceTable*) StdGlobalInterfaceTableInstance, iid, ppv);
1864 if (hres) return hres;
1866 TRACE("Retrieved GIT (%p)\n", *ppv);
1871 * Get a class factory to construct the object we want.
1873 hres = CoGetClassObject(rclsid,
1880 FIXME("no classfactory created for CLSID %s, hres is 0x%08lx\n",
1881 debugstr_guid(rclsid),hres);
1886 * Create the object and don't forget to release the factory
1888 hres = IClassFactory_CreateInstance(lpclf, pUnkOuter, iid, ppv);
1889 IClassFactory_Release(lpclf);
1891 FIXME("no instance created for interface %s of class %s, hres is 0x%08lx\n",
1892 debugstr_guid(iid), debugstr_guid(rclsid),hres);
1897 /***********************************************************************
1898 * CoCreateInstanceEx [OLE32.@]
1900 HRESULT WINAPI CoCreateInstanceEx(
1902 LPUNKNOWN pUnkOuter,
1904 COSERVERINFO* pServerInfo,
1908 IUnknown* pUnk = NULL;
1911 ULONG successCount = 0;
1916 if ( (cmq==0) || (pResults==NULL))
1917 return E_INVALIDARG;
1919 if (pServerInfo!=NULL)
1920 FIXME("() non-NULL pServerInfo not supported!\n");
1923 * Initialize all the "out" parameters.
1925 for (index = 0; index < cmq; index++)
1927 pResults[index].pItf = NULL;
1928 pResults[index].hr = E_NOINTERFACE;
1932 * Get the object and get its IUnknown pointer.
1934 hr = CoCreateInstance(rclsid,
1944 * Then, query for all the interfaces requested.
1946 for (index = 0; index < cmq; index++)
1948 pResults[index].hr = IUnknown_QueryInterface(pUnk,
1949 pResults[index].pIID,
1950 (VOID**)&(pResults[index].pItf));
1952 if (pResults[index].hr == S_OK)
1957 * Release our temporary unknown pointer.
1959 IUnknown_Release(pUnk);
1961 if (successCount == 0)
1962 return E_NOINTERFACE;
1964 if (successCount!=cmq)
1965 return CO_S_NOTALLINTERFACES;
1970 /***********************************************************************
1971 * CoLoadLibrary (OLE32.@)
1976 * lpszLibName [I] Path to library.
1977 * bAutoFree [I] Whether the library should automatically be freed.
1980 * Success: Handle to loaded library.
1984 * CoFreeLibrary, CoFreeAllLibraries, CoFreeUnusedLibraries
1986 HINSTANCE WINAPI CoLoadLibrary(LPOLESTR lpszLibName, BOOL bAutoFree)
1988 TRACE("(%s, %d)\n", debugstr_w(lpszLibName), bAutoFree);
1990 return LoadLibraryExW(lpszLibName, 0, LOAD_WITH_ALTERED_SEARCH_PATH);
1993 /***********************************************************************
1994 * CoFreeLibrary [OLE32.@]
1996 * Unloads a library from memory.
1999 * hLibrary [I] Handle to library to unload.
2005 * CoLoadLibrary, CoFreeAllLibraries, CoFreeUnusedLibraries
2007 void WINAPI CoFreeLibrary(HINSTANCE hLibrary)
2009 FreeLibrary(hLibrary);
2013 /***********************************************************************
2014 * CoFreeAllLibraries [OLE32.@]
2016 * Function for backwards compatibility only. Does nothing.
2022 * CoLoadLibrary, CoFreeLibrary, CoFreeUnusedLibraries
2024 void WINAPI CoFreeAllLibraries(void)
2030 /***********************************************************************
2031 * CoFreeUnusedLibraries [OLE32.@]
2032 * CoFreeUnusedLibraries [COMPOBJ.17]
2034 * Frees any unused libraries. Unused are identified as those that return
2035 * S_OK from their DllCanUnloadNow function.
2041 * CoLoadLibrary, CoFreeAllLibraries, CoFreeLibrary
2043 void WINAPI CoFreeUnusedLibraries(void)
2045 /* FIXME: Calls to CoFreeUnusedLibraries from any thread always route
2046 * through the main apartment's thread to call DllCanUnloadNow */
2047 COMPOBJ_DllList_FreeUnused(0);
2050 /***********************************************************************
2051 * CoFileTimeNow [OLE32.@]
2052 * CoFileTimeNow [COMPOBJ.82]
2054 * Retrieves the current time in FILETIME format.
2057 * lpFileTime [O] The current time.
2062 HRESULT WINAPI CoFileTimeNow( FILETIME *lpFileTime )
2064 GetSystemTimeAsFileTime( lpFileTime );
2068 static void COM_RevokeAllClasses()
2070 EnterCriticalSection( &csRegisteredClassList );
2072 while (firstRegisteredClass!=0)
2074 CoRevokeClassObject(firstRegisteredClass->dwCookie);
2077 LeaveCriticalSection( &csRegisteredClassList );
2080 /******************************************************************************
2081 * CoLockObjectExternal [OLE32.@]
2083 * Increments or decrements the external reference count of a stub object.
2086 * pUnk [I] Stub object.
2087 * fLock [I] If TRUE then increments the external ref-count,
2088 * otherwise decrements.
2089 * fLastUnlockReleases [I] If TRUE then the last unlock has the effect of
2090 * calling CoDisconnectObject.
2094 * Failure: HRESULT code.
2096 HRESULT WINAPI CoLockObjectExternal(
2099 BOOL fLastUnlockReleases)
2101 struct stub_manager *stubmgr;
2102 struct apartment *apt;
2104 TRACE("pUnk=%p, fLock=%s, fLastUnlockReleases=%s\n",
2105 pUnk, fLock ? "TRUE" : "FALSE", fLastUnlockReleases ? "TRUE" : "FALSE");
2107 apt = COM_CurrentApt();
2108 if (!apt) return CO_E_NOTINITIALIZED;
2110 stubmgr = get_stub_manager_from_object(apt, pUnk);
2115 stub_manager_ext_addref(stubmgr, 1);
2117 stub_manager_ext_release(stubmgr, 1);
2119 stub_manager_int_release(stubmgr);
2125 WARN("stub object not found %p\n", pUnk);
2126 /* Note: native is pretty broken here because it just silently
2127 * fails, without returning an appropriate error code, making apps
2128 * think that the object was disconnected, when it actually wasn't */
2133 /***********************************************************************
2134 * CoInitializeWOW (OLE32.@)
2136 * WOW equivalent of CoInitialize?
2145 HRESULT WINAPI CoInitializeWOW(DWORD x,DWORD y)
2147 FIXME("(0x%08lx,0x%08lx),stub!\n",x,y);
2151 /***********************************************************************
2152 * CoGetState [OLE32.@]
2154 * Retrieves the thread state object previously stored by CoSetState().
2157 * ppv [I] Address where pointer to object will be stored.
2161 * Failure: E_OUTOFMEMORY.
2164 * Crashes on all invalid ppv addresses, including NULL.
2165 * If the function returns a non-NULL object then the caller must release its
2166 * reference on the object when the object is no longer required.
2171 HRESULT WINAPI CoGetState(IUnknown ** ppv)
2173 struct oletls *info = COM_CurrentInfo();
2174 if (!info) return E_OUTOFMEMORY;
2180 IUnknown_AddRef(info->state);
2182 TRACE("apt->state=%p\n", info->state);
2188 /***********************************************************************
2189 * CoSetState [OLE32.@]
2191 * Sets the thread state object.
2194 * pv [I] Pointer to state object to be stored.
2197 * The system keeps a reference on the object while the object stored.
2201 * Failure: E_OUTOFMEMORY.
2203 HRESULT WINAPI CoSetState(IUnknown * pv)
2205 struct oletls *info = COM_CurrentInfo();
2206 if (!info) return E_OUTOFMEMORY;
2208 if (pv) IUnknown_AddRef(pv);
2212 TRACE("-- release %p now\n", info->state);
2213 IUnknown_Release(info->state);
2222 /******************************************************************************
2223 * OleGetAutoConvert [OLE32.@]
2225 HRESULT WINAPI OleGetAutoConvert(REFCLSID clsidOld, LPCLSID pClsidNew)
2227 static const WCHAR wszAutoConvertTo[] = {'A','u','t','o','C','o','n','v','e','r','t','T','o',0};
2229 WCHAR buf[CHARS_IN_GUID];
2233 res = COM_OpenKeyForCLSID(clsidOld, wszAutoConvertTo, KEY_READ, &hkey);
2238 if (RegQueryValueW(hkey, NULL, buf, &len))
2240 res = REGDB_E_KEYMISSING;
2243 res = CLSIDFromString(buf, pClsidNew);
2245 if (hkey) RegCloseKey(hkey);
2249 /******************************************************************************
2250 * CoTreatAsClass [OLE32.@]
2252 * Sets the TreatAs value of a class.
2255 * clsidOld [I] Class to set TreatAs value on.
2256 * clsidNew [I] The class the clsidOld should be treated as.
2260 * Failure: HRESULT code.
2265 HRESULT WINAPI CoTreatAsClass(REFCLSID clsidOld, REFCLSID clsidNew)
2267 static const WCHAR wszAutoTreatAs[] = {'A','u','t','o','T','r','e','a','t','A','s',0};
2268 static const WCHAR wszTreatAs[] = {'T','r','e','a','t','A','s',0};
2270 WCHAR szClsidNew[CHARS_IN_GUID];
2272 WCHAR auto_treat_as[CHARS_IN_GUID];
2273 LONG auto_treat_as_size = sizeof(auto_treat_as);
2276 res = COM_OpenKeyForCLSID(clsidOld, NULL, KEY_READ | KEY_WRITE, &hkey);
2279 if (!memcmp( clsidOld, clsidNew, sizeof(*clsidOld) ))
2281 if (!RegQueryValueW(hkey, wszAutoTreatAs, auto_treat_as, &auto_treat_as_size) &&
2282 !CLSIDFromString(auto_treat_as, &id))
2284 if (RegSetValueW(hkey, wszTreatAs, REG_SZ, auto_treat_as, sizeof(auto_treat_as)))
2286 res = REGDB_E_WRITEREGDB;
2292 RegDeleteKeyW(hkey, wszTreatAs);
2296 else if (!StringFromGUID2(clsidNew, szClsidNew, ARRAYSIZE(szClsidNew)) &&
2297 !RegSetValueW(hkey, wszTreatAs, REG_SZ, szClsidNew, sizeof(szClsidNew)))
2299 res = REGDB_E_WRITEREGDB;
2304 if (hkey) RegCloseKey(hkey);
2308 /******************************************************************************
2309 * CoGetTreatAsClass [OLE32.@]
2311 * Gets the TreatAs value of a class.
2314 * clsidOld [I] Class to get the TreatAs value of.
2315 * clsidNew [I] The class the clsidOld should be treated as.
2319 * Failure: HRESULT code.
2324 HRESULT WINAPI CoGetTreatAsClass(REFCLSID clsidOld, LPCLSID clsidNew)
2326 static const WCHAR wszTreatAs[] = {'T','r','e','a','t','A','s',0};
2328 WCHAR szClsidNew[CHARS_IN_GUID];
2330 LONG len = sizeof(szClsidNew);
2332 FIXME("(%s,%p)\n", debugstr_guid(clsidOld), clsidNew);
2333 memcpy(clsidNew,clsidOld,sizeof(CLSID)); /* copy over old value */
2335 res = COM_OpenKeyForCLSID(clsidOld, wszTreatAs, KEY_READ, &hkey);
2338 if (RegQueryValueW(hkey, NULL, szClsidNew, &len))
2343 res = CLSIDFromString(szClsidNew,clsidNew);
2345 ERR("Failed CLSIDFromStringA(%s), hres 0x%08lx\n", debugstr_w(szClsidNew), res);
2347 if (hkey) RegCloseKey(hkey);
2351 /******************************************************************************
2352 * CoGetCurrentProcess [OLE32.@]
2353 * CoGetCurrentProcess [COMPOBJ.34]
2355 * Gets the current process ID.
2358 * The current process ID.
2361 * Is DWORD really the correct return type for this function?
2363 DWORD WINAPI CoGetCurrentProcess(void)
2365 return GetCurrentProcessId();
2368 /******************************************************************************
2369 * CoRegisterMessageFilter [OLE32.@]
2371 * Registers a message filter.
2374 * lpMessageFilter [I] Pointer to interface.
2375 * lplpMessageFilter [O] Indirect pointer to prior instance if non-NULL.
2379 * Failure: HRESULT code.
2381 HRESULT WINAPI CoRegisterMessageFilter(
2382 LPMESSAGEFILTER lpMessageFilter,
2383 LPMESSAGEFILTER *lplpMessageFilter)
2386 if (lplpMessageFilter) {
2387 *lplpMessageFilter = NULL;
2392 /***********************************************************************
2393 * CoIsOle1Class [OLE32.@]
2395 * Determines whether the specified class an OLE v1 class.
2398 * clsid [I] Class to test.
2401 * TRUE if the class is an OLE v1 class, or FALSE otherwise.
2403 BOOL WINAPI CoIsOle1Class(REFCLSID clsid)
2405 FIXME("%s\n", debugstr_guid(clsid));
2409 /***********************************************************************
2410 * IsEqualGUID [OLE32.@]
2412 * Compares two Unique Identifiers.
2415 * rguid1 [I] The first GUID to compare.
2416 * rguid2 [I] The other GUID to compare.
2422 BOOL WINAPI IsEqualGUID(
2426 return !memcmp(rguid1,rguid2,sizeof(GUID));
2429 /***********************************************************************
2430 * CoInitializeSecurity [OLE32.@]
2432 HRESULT WINAPI CoInitializeSecurity(PSECURITY_DESCRIPTOR pSecDesc, LONG cAuthSvc,
2433 SOLE_AUTHENTICATION_SERVICE* asAuthSvc,
2434 void* pReserved1, DWORD dwAuthnLevel,
2435 DWORD dwImpLevel, void* pReserved2,
2436 DWORD dwCapabilities, void* pReserved3)
2438 FIXME("(%p,%ld,%p,%p,%ld,%ld,%p,%ld,%p) - stub!\n", pSecDesc, cAuthSvc,
2439 asAuthSvc, pReserved1, dwAuthnLevel, dwImpLevel, pReserved2,
2440 dwCapabilities, pReserved3);
2444 /***********************************************************************
2445 * CoSuspendClassObjects [OLE32.@]
2447 * Suspends all registered class objects to prevent further requests coming in
2448 * for those objects.
2452 * Failure: HRESULT code.
2454 HRESULT WINAPI CoSuspendClassObjects(void)
2460 /***********************************************************************
2461 * CoAddRefServerProcess [OLE32.@]
2463 * Helper function for incrementing the reference count of a local-server
2467 * New reference count.
2469 ULONG WINAPI CoAddRefServerProcess(void)
2475 /***********************************************************************
2476 * CoReleaseServerProcess [OLE32.@]
2478 * Helper function for decrementing the reference count of a local-server
2482 * New reference count.
2484 ULONG WINAPI CoReleaseServerProcess(void)
2490 /***********************************************************************
2491 * CoIsHandlerConnected [OLE32.@]
2493 * Determines whether a proxy is connected to a remote stub.
2496 * pUnk [I] Pointer to object that may or may not be connected.
2499 * TRUE if pUnk is not a proxy or if pUnk is connected to a remote stub, or
2502 BOOL WINAPI CoIsHandlerConnected(IUnknown *pUnk)
2504 FIXME("%p\n", pUnk);
2509 /***********************************************************************
2510 * CoAllowSetForegroundWindow [OLE32.@]
2513 HRESULT WINAPI CoAllowSetForegroundWindow(IUnknown *pUnk, void *pvReserved)
2515 FIXME("(%p, %p): stub\n", pUnk, pvReserved);
2519 /***********************************************************************
2520 * CoQueryProxyBlanket [OLE32.@]
2522 * Retrieves the security settings being used by a proxy.
2525 * pProxy [I] Pointer to the proxy object.
2526 * pAuthnSvc [O] The type of authentication service.
2527 * pAuthzSvc [O] The type of authorization service.
2528 * ppServerPrincName [O] Optional. The server prinicple name.
2529 * pAuthnLevel [O] The authentication level.
2530 * pImpLevel [O] The impersonation level.
2531 * ppAuthInfo [O] Information specific to the authorization/authentication service.
2532 * pCapabilities [O] Flags affecting the security behaviour.
2536 * Failure: HRESULT code.
2539 * CoCopyProxy, CoSetProxyBlanket.
2541 HRESULT WINAPI CoQueryProxyBlanket(IUnknown *pProxy, DWORD *pAuthnSvc,
2542 DWORD *pAuthzSvc, OLECHAR **ppServerPrincName, DWORD *pAuthnLevel,
2543 DWORD *pImpLevel, void **ppAuthInfo, DWORD *pCapabilities)
2545 IClientSecurity *pCliSec;
2548 TRACE("%p\n", pProxy);
2550 hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
2553 hr = IClientSecurity_QueryBlanket(pCliSec, pProxy, pAuthnSvc,
2554 pAuthzSvc, ppServerPrincName,
2555 pAuthnLevel, pImpLevel, ppAuthInfo,
2557 IClientSecurity_Release(pCliSec);
2560 if (FAILED(hr)) ERR("-- failed with 0x%08lx\n", hr);
2564 /***********************************************************************
2565 * CoSetProxyBlanket [OLE32.@]
2567 * Sets the security settings for a proxy.
2570 * pProxy [I] Pointer to the proxy object.
2571 * AuthnSvc [I] The type of authentication service.
2572 * AuthzSvc [I] The type of authorization service.
2573 * pServerPrincName [I] The server prinicple name.
2574 * AuthnLevel [I] The authentication level.
2575 * ImpLevel [I] The impersonation level.
2576 * pAuthInfo [I] Information specific to the authorization/authentication service.
2577 * Capabilities [I] Flags affecting the security behaviour.
2581 * Failure: HRESULT code.
2584 * CoQueryProxyBlanket, CoCopyProxy.
2586 HRESULT WINAPI CoSetProxyBlanket(IUnknown *pProxy, DWORD AuthnSvc,
2587 DWORD AuthzSvc, OLECHAR *pServerPrincName, DWORD AuthnLevel,
2588 DWORD ImpLevel, void *pAuthInfo, DWORD Capabilities)
2590 IClientSecurity *pCliSec;
2593 TRACE("%p\n", pProxy);
2595 hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
2598 hr = IClientSecurity_SetBlanket(pCliSec, pProxy, AuthnSvc,
2599 AuthzSvc, pServerPrincName,
2600 AuthnLevel, ImpLevel, pAuthInfo,
2602 IClientSecurity_Release(pCliSec);
2605 if (FAILED(hr)) ERR("-- failed with 0x%08lx\n", hr);
2609 /***********************************************************************
2610 * CoCopyProxy [OLE32.@]
2615 * pProxy [I] Pointer to the proxy object.
2616 * ppCopy [O] Copy of the proxy.
2620 * Failure: HRESULT code.
2623 * CoQueryProxyBlanket, CoSetProxyBlanket.
2625 HRESULT WINAPI CoCopyProxy(IUnknown *pProxy, IUnknown **ppCopy)
2627 IClientSecurity *pCliSec;
2630 TRACE("%p\n", pProxy);
2632 hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
2635 hr = IClientSecurity_CopyProxy(pCliSec, pProxy, ppCopy);
2636 IClientSecurity_Release(pCliSec);
2639 if (FAILED(hr)) ERR("-- failed with 0x%08lx\n", hr);
2644 /***********************************************************************
2645 * CoWaitForMultipleHandles [OLE32.@]
2647 * Waits for one or more handles to become signaled.
2650 * dwFlags [I] Flags. See notes.
2651 * dwTimeout [I] Timeout in milliseconds.
2652 * cHandles [I] Number of handles pointed to by pHandles.
2653 * pHandles [I] Handles to wait for.
2654 * lpdwindex [O] Index of handle that was signaled.
2658 * Failure: RPC_S_CALLPENDING on timeout.
2662 * The dwFlags parameter can be zero or more of the following:
2663 *| COWAIT_WAITALL - Wait for all of the handles to become signaled.
2664 *| COWAIT_ALERTABLE - Allows a queued APC to run during the wait.
2667 * MsgWaitForMultipleObjects, WaitForMultipleObjects.
2669 HRESULT WINAPI CoWaitForMultipleHandles(DWORD dwFlags, DWORD dwTimeout,
2670 ULONG cHandles, const HANDLE* pHandles, LPDWORD lpdwindex)
2673 DWORD start_time = GetTickCount();
2674 BOOL message_loop = TRUE;
2676 TRACE("(0x%08lx, 0x%08lx, %ld, %p, %p)\n", dwFlags, dwTimeout, cHandles,
2677 pHandles, lpdwindex);
2681 DWORD now = GetTickCount();
2684 if ((dwTimeout != INFINITE) && (start_time + dwTimeout >= now))
2686 hr = RPC_S_CALLPENDING;
2692 DWORD wait_flags = (dwFlags & COWAIT_WAITALL) ? MWMO_WAITALL : 0 |
2693 (dwFlags & COWAIT_ALERTABLE ) ? MWMO_ALERTABLE : 0;
2695 TRACE("waiting for rpc completion or window message\n");
2697 res = MsgWaitForMultipleObjectsEx(cHandles, pHandles,
2698 (dwTimeout == INFINITE) ? INFINITE : start_time + dwTimeout - now,
2699 QS_ALLINPUT, wait_flags);
2701 if (res == WAIT_OBJECT_0 + cHandles) /* messages available */
2704 while (PeekMessageW(&msg, NULL, 0, 0, PM_REMOVE))
2706 /* FIXME: filter the messages here */
2707 TRACE("received message whilst waiting for RPC: 0x%04x\n", msg.message);
2708 TranslateMessage(&msg);
2709 DispatchMessageW(&msg);
2710 if (msg.message == WM_QUIT)
2712 TRACE("resending WM_QUIT to outer message loop\n");
2713 PostQuitMessage(msg.wParam);
2714 /* no longer need to process messages */
2715 message_loop = FALSE;
2724 TRACE("waiting for rpc completion\n");
2726 res = WaitForMultipleObjectsEx(cHandles, pHandles,
2727 (dwFlags & COWAIT_WAITALL) ? TRUE : FALSE,
2728 (dwTimeout == INFINITE) ? INFINITE : start_time + dwTimeout - now,
2729 (dwFlags & COWAIT_ALERTABLE) ? TRUE : FALSE);
2732 if ((res >= WAIT_OBJECT_0) && (res < WAIT_OBJECT_0 + cHandles))
2734 /* handle signaled, store index */
2735 *lpdwindex = (res - WAIT_OBJECT_0);
2738 else if (res == WAIT_TIMEOUT)
2740 hr = RPC_S_CALLPENDING;
2745 ERR("Unexpected wait termination: %ld, %ld\n", res, GetLastError());
2750 TRACE("-- 0x%08lx\n", hr);
2754 /***********************************************************************
2757 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID fImpLoad)
2759 TRACE("%p 0x%lx %p\n", hinstDLL, fdwReason, fImpLoad);
2762 case DLL_PROCESS_ATTACH:
2763 OLE32_hInstance = hinstDLL;
2764 COMPOBJ_InitProcess();
2765 if (TRACE_ON(ole)) CoRegisterMallocSpy((LPVOID)-1);
2768 case DLL_PROCESS_DETACH:
2769 if (TRACE_ON(ole)) CoRevokeMallocSpy();
2770 COMPOBJ_UninitProcess();
2771 OLE32_hInstance = 0;
2774 case DLL_THREAD_DETACH:
2781 /* NOTE: DllRegisterServer and DllUnregisterServer are in regsvr.c */