Compare result of RegQueryValueExW() with ERROR_SUCCESS.
[wine] / dlls / ole32 / compobj.c
1 /*
2  *      COMPOBJ library
3  *
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  *
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.
15  *
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.
20  *
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
24  *
25  * Note
26  * 1. COINIT_MULTITHREADED is 0; it is the lack of COINIT_APARTMENTTHREADED
27  *    Therefore do not test against COINIT_MULTITHREADED
28  *
29  * TODO list:           (items bunched together depend on each other)
30  *
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
35  *
36  *   - Pump the message loop during RPC calls.
37  *   - Call IMessageFilter functions.
38  *
39  *   - Make all ole interface marshaling use NDR to be wire compatible with
40  *     native DCOM
41  *   - Use & interpret ORPCTHIS & ORPCTHAT.
42  *
43  */
44
45 #include "config.h"
46
47 #include <stdlib.h>
48 #include <stdarg.h>
49 #include <stdio.h>
50 #include <string.h>
51 #include <assert.h>
52
53 #define COBJMACROS
54 #define NONAMELESSUNION
55 #define NONAMELESSSTRUCT
56
57 #include "windef.h"
58 #include "winbase.h"
59 #include "winuser.h"
60 #include "objbase.h"
61 #include "ole2.h"
62 #include "ole2ver.h"
63 #include "rpc.h"
64 #include "winerror.h"
65 #include "winreg.h"
66 #include "wownt32.h"
67 #include "wine/unicode.h"
68 #include "objbase.h"
69 #include "compobj_private.h"
70
71 #include "wine/debug.h"
72
73 WINE_DEFAULT_DEBUG_CHANNEL(ole);
74
75 typedef LPCSTR LPCOLESTR16;
76
77 HINSTANCE OLE32_hInstance = 0; /* FIXME: make static ... */
78
79 #define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))
80
81 /****************************************************************************
82  * This section defines variables internal to the COM module.
83  *
84  * TODO: Most of these things will have to be made thread-safe.
85  */
86
87 static HRESULT COM_GetRegisteredClassObject(REFCLSID rclsid, DWORD dwClsContext, LPUNKNOWN*  ppUnk);
88 static void COM_RevokeAllClasses(void);
89
90 const CLSID CLSID_StdGlobalInterfaceTable = { 0x00000323, 0, 0, {0xc0, 0, 0, 0, 0, 0, 0, 0x46} };
91
92 APARTMENT *MTA; /* protected by csApartment */
93 static struct list apts = LIST_INIT( apts ); /* protected by csApartment */
94
95 static CRITICAL_SECTION csApartment;
96 static CRITICAL_SECTION_DEBUG critsect_debug =
97 {
98     0, 0, &csApartment,
99     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
100       0, 0, { 0, (DWORD)(__FILE__ ": csApartment") }
101 };
102 static CRITICAL_SECTION csApartment = { &critsect_debug, -1, 0, 0, 0, 0 };
103
104 /*
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
108  */
109 static LONG s_COMLockCount = 0;
110
111 /*
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
114  * objects.
115  *
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.
118  */
119 typedef struct tagRegisteredClass
120 {
121   CLSID     classIdentifier;
122   LPUNKNOWN classObject;
123   DWORD     runContext;
124   DWORD     connectFlags;
125   DWORD     dwCookie;
126   LPSTREAM  pMarshaledData; /* FIXME: only really need to store OXID and IPID */
127   struct tagRegisteredClass* nextClass;
128 } RegisteredClass;
129
130 static RegisteredClass* firstRegisteredClass = NULL;
131
132 static CRITICAL_SECTION csRegisteredClassList;
133 static CRITICAL_SECTION_DEBUG class_cs_debug =
134 {
135     0, 0, &csRegisteredClassList,
136     { &class_cs_debug.ProcessLocksList, &class_cs_debug.ProcessLocksList },
137       0, 0, { 0, (DWORD)(__FILE__ ": csRegisteredClassList") }
138 };
139 static CRITICAL_SECTION csRegisteredClassList = { &class_cs_debug, -1, 0, 0, 0, 0 };
140
141 /*****************************************************************************
142  * This section contains OpenDllList definitions
143  *
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.
147  *
148  * FIXME: a DLL that says OK when asked for unloading is unloaded in the
149  * next unload-call but not before 600 sec.
150  */
151
152 typedef struct tagOpenDll {
153   HINSTANCE hLibrary;
154   struct tagOpenDll *next;
155 } OpenDll;
156
157 static OpenDll *openDllList = NULL; /* linked list of open dlls */
158
159 static CRITICAL_SECTION csOpenDllList;
160 static CRITICAL_SECTION_DEBUG dll_cs_debug =
161 {
162     0, 0, &csOpenDllList,
163     { &dll_cs_debug.ProcessLocksList, &dll_cs_debug.ProcessLocksList },
164       0, 0, { 0, (DWORD)(__FILE__ ": csOpenDllList") }
165 };
166 static CRITICAL_SECTION csOpenDllList = { &dll_cs_debug, -1, 0, 0, 0, 0 };
167
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);
171
172 static void COMPOBJ_DLLList_Add(HANDLE hLibrary);
173 static void COMPOBJ_DllList_FreeUnused(int Timeout);
174
175 static void COMPOBJ_InitProcess( void )
176 {
177     WNDCLASSW wclass;
178
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
186      * was unmarshalled.
187      */
188     memset(&wclass, 0, sizeof(wclass));
189     wclass.lpfnWndProc = apartment_wndproc;
190     wclass.hInstance = OLE32_hInstance;
191     wclass.lpszClassName = wszAptWinClass;
192     RegisterClassW(&wclass);
193 }
194
195 static void COMPOBJ_UninitProcess( void )
196 {
197     UnregisterClassW(wszAptWinClass, OLE32_hInstance);
198 }
199
200 static void COM_TlsDestroy(void)
201 {
202     struct oletls *info = NtCurrentTeb()->ReservedForOle;
203     if (info)
204     {
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;
210     }
211 }
212
213 /******************************************************************************
214  * Manage apartments.
215  */
216
217 /* allocates memory and fills in the necessary fields for a new apartment
218  * object */
219 static APARTMENT *apartment_construct(DWORD model)
220 {
221     APARTMENT *apt;
222
223     TRACE("creating new apartment, model=%ld\n", model);
224
225     apt = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*apt));
226     apt->tid = GetCurrentThreadId();
227     DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
228                     GetCurrentProcess(), &apt->thread,
229                     THREAD_ALL_ACCESS, FALSE, 0);
230
231     list_init(&apt->proxies);
232     list_init(&apt->stubmgrs);
233     apt->ipidc = 0;
234     apt->refs = 1;
235     apt->remunk_exported = FALSE;
236     apt->oidc = 1;
237     InitializeCriticalSection(&apt->cs);
238     DEBUG_SET_CRITSEC_NAME(&apt->cs, "apartment");
239
240     apt->model = model;
241
242     if (model & COINIT_APARTMENTTHREADED)
243     {
244         /* FIXME: should be randomly generated by in an RPC call to rpcss */
245         apt->oxid = ((OXID)GetCurrentProcessId() << 32) | GetCurrentThreadId();
246         apt->win = CreateWindowW(wszAptWinClass, NULL, 0,
247                                  0, 0, 0, 0,
248                                  0, 0, OLE32_hInstance, NULL);
249     }
250     else
251     {
252         /* FIXME: should be randomly generated by in an RPC call to rpcss */
253         apt->oxid = ((OXID)GetCurrentProcessId() << 32) | 0xcafe;
254     }
255
256     TRACE("Created apartment on OXID %s\n", wine_dbgstr_longlong(apt->oxid));
257
258     /* the locking here is not currently needed for the MTA case, but it
259      * doesn't hurt and makes the code simpler */
260     EnterCriticalSection(&csApartment);
261     list_add_head(&apts, &apt->entry);
262     LeaveCriticalSection(&csApartment);
263
264     return apt;
265 }
266
267 /* gets and existing apartment if one exists or otherwise creates an apartment
268  * structure which stores OLE apartment-local information and stores a pointer
269  * to it in the thread-local storage */
270 static APARTMENT *apartment_get_or_create(DWORD model)
271 {
272     APARTMENT *apt = COM_CurrentApt();
273
274     if (!apt)
275     {
276         if (model & COINIT_APARTMENTTHREADED)
277         {
278             apt = apartment_construct(model);
279             COM_CurrentInfo()->apt = apt;
280         }
281         else
282         {
283             EnterCriticalSection(&csApartment);
284
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
287              * in a process */
288             if (MTA)
289             {
290                 TRACE("entering the multithreaded apartment %s\n", wine_dbgstr_longlong(MTA->oxid));
291                 apartment_addref(MTA);
292             }
293             else
294                 MTA = apartment_construct(model);
295
296             apt = MTA;
297             COM_CurrentInfo()->apt = apt;
298
299             LeaveCriticalSection(&csApartment);
300         }
301     }
302
303     return apt;
304 }
305
306 DWORD apartment_addref(struct apartment *apt)
307 {
308     DWORD refs = InterlockedIncrement(&apt->refs);
309     TRACE("%s: before = %ld\n", wine_dbgstr_longlong(apt->oxid), refs - 1);
310     return refs;
311 }
312
313 DWORD apartment_release(struct apartment *apt)
314 {
315     DWORD ret;
316
317     EnterCriticalSection(&csApartment);
318
319     ret = InterlockedDecrement(&apt->refs);
320     TRACE("%s: after = %ld\n", wine_dbgstr_longlong(apt->oxid), ret);
321     /* destruction stuff that needs to happen under csApartment CS */
322     if (ret == 0)
323     {
324         if (apt == MTA) MTA = NULL;
325         list_remove(&apt->entry);
326     }
327
328     LeaveCriticalSection(&csApartment);
329
330     if (ret == 0)
331     {
332         struct list *cursor, *cursor2;
333
334         TRACE("destroying apartment %p, oxid %s\n", apt, wine_dbgstr_longlong(apt->oxid));
335
336         /* no locking is needed for this apartment, because no other thread
337          * can access it at this point */
338
339         apartment_disconnectproxies(apt);
340
341         if (apt->win) DestroyWindow(apt->win);
342
343         LIST_FOR_EACH_SAFE(cursor, cursor2, &apt->stubmgrs)
344         {
345             struct stub_manager *stubmgr = LIST_ENTRY(cursor, struct stub_manager, entry);
346             /* release the implicit reference given by the fact that the
347              * stub has external references (it must do since it is in the
348              * stub manager list in the apartment and all non-apartment users
349              * must have a ref on the apartment and so it cannot be destroyed).
350              */
351             stub_manager_int_release(stubmgr);
352         }
353
354         /* if this assert fires, then another thread took a reference to a
355          * stub manager without taking a reference to the containing
356          * apartment, which it must do. */
357         assert(list_empty(&apt->stubmgrs));
358
359         if (apt->filter) IUnknown_Release(apt->filter);
360
361         DEBUG_CLEAR_CRITSEC_NAME(&apt->cs);
362         DeleteCriticalSection(&apt->cs);
363         CloseHandle(apt->thread);
364
365         HeapFree(GetProcessHeap(), 0, apt);
366     }
367
368     return ret;
369 }
370
371 /* The given OXID must be local to this process: 
372  *
373  * The ref parameter is here mostly to ensure people remember that
374  * they get one, you should normally take a ref for thread safety.
375  */
376 APARTMENT *apartment_findfromoxid(OXID oxid, BOOL ref)
377 {
378     APARTMENT *result = NULL;
379     struct list *cursor;
380
381     EnterCriticalSection(&csApartment);
382     LIST_FOR_EACH( cursor, &apts )
383     {
384         struct apartment *apt = LIST_ENTRY( cursor, struct apartment, entry );
385         if (apt->oxid == oxid)
386         {
387             result = apt;
388             if (ref) apartment_addref(result);
389             break;
390         }
391     }
392     LeaveCriticalSection(&csApartment);
393
394     return result;
395 }
396
397 /* gets the apartment which has a given creator thread ID. The caller must
398  * release the reference from the apartment as soon as the apartment pointer
399  * is no longer required. */
400 APARTMENT *apartment_findfromtid(DWORD tid)
401 {
402     APARTMENT *result = NULL;
403     struct list *cursor;
404
405     EnterCriticalSection(&csApartment);
406     LIST_FOR_EACH( cursor, &apts )
407     {
408         struct apartment *apt = LIST_ENTRY( cursor, struct apartment, entry );
409         if (apt->tid == tid)
410         {
411             result = apt;
412             apartment_addref(result);
413             break;
414         }
415     }
416     LeaveCriticalSection(&csApartment);
417
418     return result;
419 }
420
421 static LRESULT CALLBACK apartment_wndproc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
422 {
423     switch (msg)
424     {
425     case DM_EXECUTERPC:
426         return RPC_ExecuteCall((struct dispatch_params *)lParam);
427     default:
428         return DefWindowProcW(hWnd, msg, wParam, lParam);
429     }
430 }
431
432 /*****************************************************************************
433  * This section contains OpenDllList implemantation
434  */
435
436 static void COMPOBJ_DLLList_Add(HANDLE hLibrary)
437 {
438     OpenDll *ptr;
439     OpenDll *tmp;
440
441     TRACE("\n");
442
443     EnterCriticalSection( &csOpenDllList );
444
445     if (openDllList == NULL) {
446         /* empty list -- add first node */
447         openDllList = HeapAlloc(GetProcessHeap(),0, sizeof(OpenDll));
448         openDllList->hLibrary=hLibrary;
449         openDllList->next = NULL;
450     } else {
451         /* search for this dll */
452         int found = FALSE;
453         for (ptr = openDllList; ptr->next != NULL; ptr=ptr->next) {
454             if (ptr->hLibrary == hLibrary) {
455                 found = TRUE;
456                 break;
457             }
458         }
459         if (!found) {
460             /* dll not found, add it */
461             tmp = openDllList;
462             openDllList = HeapAlloc(GetProcessHeap(),0, sizeof(OpenDll));
463             openDllList->hLibrary = hLibrary;
464             openDllList->next = tmp;
465         }
466     }
467
468     LeaveCriticalSection( &csOpenDllList );
469 }
470
471 static void COMPOBJ_DllList_FreeUnused(int Timeout)
472 {
473     OpenDll *curr, *next, *prev = NULL;
474     typedef HRESULT (WINAPI *DllCanUnloadNowFunc)(void);
475     DllCanUnloadNowFunc DllCanUnloadNow;
476
477     TRACE("\n");
478
479     EnterCriticalSection( &csOpenDllList );
480
481     for (curr = openDllList; curr != NULL; ) {
482         DllCanUnloadNow = (DllCanUnloadNowFunc) GetProcAddress(curr->hLibrary, "DllCanUnloadNow");
483
484         if ( (DllCanUnloadNow != NULL) && (DllCanUnloadNow() == S_OK) ) {
485             next = curr->next;
486
487             TRACE("freeing %p\n", curr->hLibrary);
488             FreeLibrary(curr->hLibrary);
489
490             HeapFree(GetProcessHeap(), 0, curr);
491             if (curr == openDllList) {
492                 openDllList = next;
493             } else {
494               prev->next = next;
495             }
496
497             curr = next;
498         } else {
499             prev = curr;
500             curr = curr->next;
501         }
502     }
503
504     LeaveCriticalSection( &csOpenDllList );
505 }
506
507 /******************************************************************************
508  *           CoBuildVersion [OLE32.@]
509  *           CoBuildVersion [COMPOBJ.1]
510  *
511  * Gets the build version of the DLL.
512  *
513  * PARAMS
514  *
515  * RETURNS
516  *      Current build version, hiword is majornumber, loword is minornumber
517  */
518 DWORD WINAPI CoBuildVersion(void)
519 {
520     TRACE("Returning version %d, build %d.\n", rmm, rup);
521     return (rmm<<16)+rup;
522 }
523
524 /******************************************************************************
525  *              CoInitialize    [OLE32.@]
526  *
527  * Initializes the COM libraries by calling CoInitializeEx with
528  * COINIT_APARTMENTTHREADED, ie it enters a STA thread.
529  *
530  * PARAMS
531  *  lpReserved [I] Pointer to IMalloc interface (obsolete, should be NULL).
532  *
533  * RETURNS
534  *  Success: S_OK if not already initialized, S_FALSE otherwise.
535  *  Failure: HRESULT code.
536  *
537  * SEE ALSO
538  *   CoInitializeEx
539  */
540 HRESULT WINAPI CoInitialize(LPVOID lpReserved)
541 {
542   /*
543    * Just delegate to the newer method.
544    */
545   return CoInitializeEx(lpReserved, COINIT_APARTMENTTHREADED);
546 }
547
548 /******************************************************************************
549  *              CoInitializeEx  [OLE32.@]
550  *
551  * Initializes the COM libraries.
552  *
553  * PARAMS
554  *  lpReserved [I] Pointer to IMalloc interface (obsolete, should be NULL).
555  *  dwCoInit   [I] One or more flags from the COINIT enumeration. See notes.
556  *
557  * RETURNS
558  *  S_OK               if successful,
559  *  S_FALSE            if this function was called already.
560  *  RPC_E_CHANGED_MODE if a previous call to CoInitializeEx specified another
561  *                     threading model.
562  *
563  * NOTES
564  *
565  * The behavior used to set the IMalloc used for memory management is
566  * obsolete.
567  * The dwCoInit parameter must specify of of the following apartment
568  * threading models:
569  *| COINIT_APARTMENTTHREADED - A single-threaded apartment (STA).
570  *| COINIT_MULTITHREADED - A multi-threaded apartment (MTA).
571  * The parameter may also specify zero or more of the following flags:
572  *| COINIT_DISABLE_OLE1DDE - Don't use DDE for OLE1 support.
573  *| COINIT_SPEED_OVER_MEMORY - Trade memory for speed.
574  *
575  * SEE ALSO
576  *   CoUninitialize
577  */
578 HRESULT WINAPI CoInitializeEx(LPVOID lpReserved, DWORD dwCoInit)
579 {
580   HRESULT hr = S_OK;
581   APARTMENT *apt;
582
583   TRACE("(%p, %x)\n", lpReserved, (int)dwCoInit);
584
585   if (lpReserved!=NULL)
586   {
587     ERR("(%p, %x) - Bad parameter passed-in %p, must be an old Windows Application\n", lpReserved, (int)dwCoInit, lpReserved);
588   }
589
590   /*
591    * Check the lock count. If this is the first time going through the initialize
592    * process, we have to initialize the libraries.
593    *
594    * And crank-up that lock count.
595    */
596   if (InterlockedExchangeAdd(&s_COMLockCount,1)==0)
597   {
598     /*
599      * Initialize the various COM libraries and data structures.
600      */
601     TRACE("() - Initializing the COM libraries\n");
602
603     /* we may need to defer this until after apartment initialisation */
604     RunningObjectTableImpl_Initialize();
605   }
606
607   if (!(apt = COM_CurrentInfo()->apt))
608   {
609     apt = apartment_get_or_create(dwCoInit);
610     if (!apt) return E_OUTOFMEMORY;
611   }
612   else if (dwCoInit != apt->model)
613   {
614     /* Changing the threading model after it's been set is illegal. If this warning is triggered by Wine
615        code then we are probably using the wrong threading model to implement that API. */
616     ERR("Attempt to change threading model of this apartment from 0x%lx to 0x%lx\n", apt->model, dwCoInit);
617     return RPC_E_CHANGED_MODE;
618   }
619   else
620     hr = S_FALSE;
621
622   COM_CurrentInfo()->inits++;
623
624   return hr;
625 }
626
627 /* On COM finalization for a STA thread, the message queue is flushed to ensure no
628    pending RPCs are ignored. Non-COM messages are discarded at this point.
629  */
630 static void COM_FlushMessageQueue(void)
631 {
632     MSG message;
633     APARTMENT *apt = COM_CurrentApt();
634
635     if (!apt || !apt->win) return;
636
637     TRACE("Flushing STA message queue\n");
638
639     while (PeekMessageA(&message, NULL, 0, 0, PM_REMOVE))
640     {
641         if (message.hwnd != apt->win)
642         {
643             WARN("discarding message 0x%x for window %p\n", message.message, message.hwnd);
644             continue;
645         }
646
647         TranslateMessage(&message);
648         DispatchMessageA(&message);
649     }
650 }
651
652 /***********************************************************************
653  *           CoUninitialize   [OLE32.@]
654  *
655  * This method will decrement the refcount on the current apartment, freeing
656  * the resources associated with it if it is the last thread in the apartment.
657  * If the last apartment is freed, the function will additionally release
658  * any COM resources associated with the process.
659  *
660  * PARAMS
661  *
662  * RETURNS
663  *  Nothing.
664  *
665  * SEE ALSO
666  *   CoInitializeEx
667  */
668 void WINAPI CoUninitialize(void)
669 {
670   struct oletls * info = COM_CurrentInfo();
671   LONG lCOMRefCnt;
672
673   TRACE("()\n");
674
675   /* will only happen on OOM */
676   if (!info) return;
677
678   /* sanity check */
679   if (!info->inits)
680   {
681     ERR("Mismatched CoUninitialize\n");
682     return;
683   }
684
685   if (!--info->inits)
686   {
687     apartment_release(info->apt);
688     info->apt = NULL;
689   }
690
691   /*
692    * Decrease the reference count.
693    * If we are back to 0 locks on the COM library, make sure we free
694    * all the associated data structures.
695    */
696   lCOMRefCnt = InterlockedExchangeAdd(&s_COMLockCount,-1);
697   if (lCOMRefCnt==1)
698   {
699     TRACE("() - Releasing the COM libraries\n");
700
701     RunningObjectTableImpl_UnInitialize();
702
703     /* Release the references to the registered class objects */
704     COM_RevokeAllClasses();
705
706     /* This will free the loaded COM Dlls  */
707     CoFreeAllLibraries();
708
709     /* This ensures we deal with any pending RPCs */
710     COM_FlushMessageQueue();
711   }
712   else if (lCOMRefCnt<1) {
713     ERR( "CoUninitialize() - not CoInitialized.\n" );
714     InterlockedExchangeAdd(&s_COMLockCount,1); /* restore the lock count. */
715   }
716 }
717
718 /******************************************************************************
719  *              CoDisconnectObject      [OLE32.@]
720  *              CoDisconnectObject      [COMPOBJ.15]
721  *
722  * Disconnects all connections to this object from remote processes. Dispatches
723  * pending RPCs while blocking new RPCs from occurring, and then calls
724  * IMarshal::DisconnectObject on the given object.
725  *
726  * Typically called when the object server is forced to shut down, for instance by
727  * the user.
728  *
729  * PARAMS
730  *  lpUnk    [I] The object whose stub should be disconnected.
731  *  reserved [I] Reserved. Should be set to 0.
732  *
733  * RETURNS
734  *  Success: S_OK.
735  *  Failure: HRESULT code.
736  *
737  * SEE ALSO
738  *  CoMarshalInterface, CoReleaseMarshalData, CoLockObjectExternal
739  */
740 HRESULT WINAPI CoDisconnectObject( LPUNKNOWN lpUnk, DWORD reserved )
741 {
742     HRESULT hr;
743     IMarshal *marshal;
744     APARTMENT *apt;
745
746     TRACE("(%p, 0x%08lx)\n", lpUnk, reserved);
747
748     hr = IUnknown_QueryInterface(lpUnk, &IID_IMarshal, (void **)&marshal);
749     if (hr == S_OK)
750     {
751         hr = IMarshal_DisconnectObject(marshal, reserved);
752         IMarshal_Release(marshal);
753         return hr;
754     }
755
756     apt = COM_CurrentApt();
757     if (!apt)
758         return CO_E_NOTINITIALIZED;
759
760     apartment_disconnectobject(apt, lpUnk);
761
762     /* Note: native is pretty broken here because it just silently
763      * fails, without returning an appropriate error code if the object was
764      * not found, making apps think that the object was disconnected, when
765      * it actually wasn't */
766
767     return S_OK;
768 }
769
770 /******************************************************************************
771  *              CoCreateGuid [OLE32.@]
772  *
773  * Simply forwards to UuidCreate in RPCRT4.
774  *
775  * PARAMS
776  *  pguid [O] Points to the GUID to initialize.
777  *
778  * RETURNS
779  *  Success: S_OK.
780  *  Failure: HRESULT code.
781  *
782  * SEE ALSO
783  *   UuidCreate
784  */
785 HRESULT WINAPI CoCreateGuid(GUID *pguid)
786 {
787     return UuidCreate(pguid);
788 }
789
790 /******************************************************************************
791  *              CLSIDFromString [OLE32.@]
792  *              IIDFromString   [OLE32.@]
793  *
794  * Converts a unique identifier from its string representation into
795  * the GUID struct.
796  *
797  * PARAMS
798  *  idstr [I] The string representation of the GUID.
799  *  id    [O] GUID converted from the string.
800  *
801  * RETURNS
802  *   S_OK on success
803  *   CO_E_CLASSSTRING if idstr is not a valid CLSID
804  *
805  * BUGS
806  *
807  * In Windows, if idstr is not a valid CLSID string then it gets
808  * treated as a ProgID. Wine currently doesn't do this. If idstr is
809  * NULL it's treated as an all-zero GUID.
810  *
811  * SEE ALSO
812  *  StringFromCLSID
813  */
814 HRESULT WINAPI __CLSIDFromStringA(LPCSTR idstr, CLSID *id)
815 {
816   const BYTE *s = (const BYTE *) idstr;
817   int   i;
818   BYTE table[256];
819
820   if (!s)
821           s = "{00000000-0000-0000-0000-000000000000}";
822   else {  /* validate the CLSID string */
823
824       if (strlen(s) != 38)
825           return CO_E_CLASSSTRING;
826
827       if ((s[0]!='{') || (s[9]!='-') || (s[14]!='-') || (s[19]!='-') || (s[24]!='-') || (s[37]!='}'))
828           return CO_E_CLASSSTRING;
829
830       for (i=1; i<37; i++) {
831           if ((i == 9)||(i == 14)||(i == 19)||(i == 24)) continue;
832           if (!(((s[i] >= '0') && (s[i] <= '9'))  ||
833                 ((s[i] >= 'a') && (s[i] <= 'f'))  ||
834                 ((s[i] >= 'A') && (s[i] <= 'F'))))
835               return CO_E_CLASSSTRING;
836       }
837   }
838
839   TRACE("%s -> %p\n", s, id);
840
841   /* quick lookup table */
842   memset(table, 0, 256);
843
844   for (i = 0; i < 10; i++) {
845     table['0' + i] = i;
846   }
847   for (i = 0; i < 6; i++) {
848     table['A' + i] = i+10;
849     table['a' + i] = i+10;
850   }
851
852   /* in form {XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX} */
853
854   id->Data1 = (table[s[1]] << 28 | table[s[2]] << 24 | table[s[3]] << 20 | table[s[4]] << 16 |
855                table[s[5]] << 12 | table[s[6]] << 8  | table[s[7]] << 4  | table[s[8]]);
856   id->Data2 = table[s[10]] << 12 | table[s[11]] << 8 | table[s[12]] << 4 | table[s[13]];
857   id->Data3 = table[s[15]] << 12 | table[s[16]] << 8 | table[s[17]] << 4 | table[s[18]];
858
859   /* these are just sequential bytes */
860   id->Data4[0] = table[s[20]] << 4 | table[s[21]];
861   id->Data4[1] = table[s[22]] << 4 | table[s[23]];
862   id->Data4[2] = table[s[25]] << 4 | table[s[26]];
863   id->Data4[3] = table[s[27]] << 4 | table[s[28]];
864   id->Data4[4] = table[s[29]] << 4 | table[s[30]];
865   id->Data4[5] = table[s[31]] << 4 | table[s[32]];
866   id->Data4[6] = table[s[33]] << 4 | table[s[34]];
867   id->Data4[7] = table[s[35]] << 4 | table[s[36]];
868
869   return S_OK;
870 }
871
872 /*****************************************************************************/
873
874 HRESULT WINAPI CLSIDFromString(LPOLESTR idstr, CLSID *id )
875 {
876     char xid[40];
877     HRESULT ret;
878
879     if (!WideCharToMultiByte( CP_ACP, 0, idstr, -1, xid, sizeof(xid), NULL, NULL ))
880         return CO_E_CLASSSTRING;
881
882
883     ret = __CLSIDFromStringA(xid,id);
884     if(ret != S_OK) { /* It appears a ProgID is also valid */
885         ret = CLSIDFromProgID(idstr, id);
886     }
887     return ret;
888 }
889
890 /* Converts a GUID into the respective string representation. */
891 HRESULT WINE_StringFromCLSID(
892         const CLSID *id,        /* [in] GUID to be converted */
893         LPSTR idstr             /* [out] pointer to buffer to contain converted guid */
894 ) {
895   static const char *hex = "0123456789ABCDEF";
896   char *s;
897   int   i;
898
899   if (!id)
900         { ERR("called with id=Null\n");
901           *idstr = 0x00;
902           return E_FAIL;
903         }
904
905   sprintf(idstr, "{%08lX-%04X-%04X-%02X%02X-",
906           id->Data1, id->Data2, id->Data3,
907           id->Data4[0], id->Data4[1]);
908   s = &idstr[25];
909
910   /* 6 hex bytes */
911   for (i = 2; i < 8; i++) {
912     *s++ = hex[id->Data4[i]>>4];
913     *s++ = hex[id->Data4[i] & 0xf];
914   }
915
916   *s++ = '}';
917   *s++ = '\0';
918
919   TRACE("%p->%s\n", id, idstr);
920
921   return S_OK;
922 }
923
924
925 /******************************************************************************
926  *              StringFromCLSID [OLE32.@]
927  *              StringFromIID   [OLE32.@]
928  *
929  * Converts a GUID into the respective string representation.
930  * The target string is allocated using the OLE IMalloc.
931  *
932  * PARAMS
933  *  id    [I] the GUID to be converted.
934  *  idstr [O] A pointer to a to-be-allocated pointer pointing to the resulting string.
935  *
936  * RETURNS
937  *   S_OK
938  *   E_FAIL
939  *
940  * SEE ALSO
941  *  StringFromGUID2, CLSIDFromString
942  */
943 HRESULT WINAPI StringFromCLSID(REFCLSID id, LPOLESTR *idstr)
944 {
945         char            buf[80];
946         HRESULT       ret;
947         LPMALLOC        mllc;
948
949         if ((ret = CoGetMalloc(0,&mllc)))
950                 return ret;
951
952         ret=WINE_StringFromCLSID(id,buf);
953         if (!ret) {
954             DWORD len = MultiByteToWideChar( CP_ACP, 0, buf, -1, NULL, 0 );
955             *idstr = IMalloc_Alloc( mllc, len * sizeof(WCHAR) );
956             MultiByteToWideChar( CP_ACP, 0, buf, -1, *idstr, len );
957         }
958         return ret;
959 }
960
961 /******************************************************************************
962  *              StringFromGUID2 [OLE32.@]
963  *              StringFromGUID2 [COMPOBJ.76]
964  *
965  * Modified version of StringFromCLSID that allows you to specify max
966  * buffer size.
967  *
968  * PARAMS
969  *  id   [I] GUID to convert to string.
970  *  str  [O] Buffer where the result will be stored.
971  *  cmax [I] Size of the buffer in characters.
972  *
973  * RETURNS
974  *      Success: The length of the resulting string in characters.
975  *  Failure: 0.
976  */
977 INT WINAPI StringFromGUID2(REFGUID id, LPOLESTR str, INT cmax)
978 {
979   char          xguid[80];
980
981   if (WINE_StringFromCLSID(id,xguid))
982         return 0;
983   return MultiByteToWideChar( CP_ACP, 0, xguid, -1, str, cmax );
984 }
985
986 /* open HKCR\\CLSID\\{string form of clsid} key */
987 DWORD COM_OpenKeyForCLSID(REFCLSID clsid, REGSAM access, HKEY *key)
988 {
989     static const WCHAR wszCLSIDSlash[] = {'C','L','S','I','D','\\',0};
990     WCHAR path[CHARS_IN_GUID + ARRAYSIZE(wszCLSIDSlash) - 1];
991     strcpyW(path, wszCLSIDSlash);
992     StringFromGUID2(clsid, path + strlenW(wszCLSIDSlash), CHARS_IN_GUID);
993     return RegOpenKeyExW(HKEY_CLASSES_ROOT, path, 0, access, key);
994 }
995
996 /******************************************************************************
997  *               ProgIDFromCLSID [OLE32.@]
998  *
999  * Converts a class id into the respective program ID.
1000  *
1001  * PARAMS
1002  *  clsid        [I] Class ID, as found in registry.
1003  *  lplpszProgID [O] Associated ProgID.
1004  *
1005  * RETURNS
1006  *   S_OK
1007  *   E_OUTOFMEMORY
1008  *   REGDB_E_CLASSNOTREG if the given clsid has no associated ProgID
1009  */
1010 HRESULT WINAPI ProgIDFromCLSID(REFCLSID clsid, LPOLESTR *lplpszProgID)
1011 {
1012   static const WCHAR wszProgID[] = {'P','r','o','g','I','D',0};
1013   HKEY     hkey = NULL;
1014   HKEY     hkey_clsid;
1015   HRESULT  ret = S_OK;
1016
1017   if (ERROR_SUCCESS != COM_OpenKeyForCLSID(clsid, KEY_READ, &hkey_clsid))
1018     ret = REGDB_E_CLASSNOTREG;
1019
1020   if (ret == S_OK)
1021   {
1022     if (RegOpenKeyExW(hkey_clsid, wszProgID, 0, KEY_READ, &hkey))
1023       ret = REGDB_E_CLASSNOTREG;
1024     RegCloseKey(hkey_clsid);
1025   }
1026
1027   if (ret == S_OK)
1028   {
1029     DWORD progidlen = 0;
1030
1031     if (RegQueryValueW(hkey, NULL, NULL, &progidlen))
1032       ret = REGDB_E_CLASSNOTREG;
1033
1034     if (ret == S_OK)
1035     {
1036       *lplpszProgID = CoTaskMemAlloc(progidlen * sizeof(WCHAR));
1037       if (*lplpszProgID)
1038       {
1039         if (RegQueryValueW(hkey, NULL, *lplpszProgID, &progidlen))
1040           ret = REGDB_E_CLASSNOTREG;
1041       }
1042       else
1043         ret = E_OUTOFMEMORY;
1044     }
1045   }
1046
1047   RegCloseKey(hkey);
1048   return ret;
1049 }
1050
1051 /******************************************************************************
1052  *              CLSIDFromProgID [COMPOBJ.61]
1053  *
1054  * Converts a program ID into the respective GUID.
1055  *
1056  * PARAMS
1057  *  progid       [I] program id as found in registry
1058  *  riid         [O] associated CLSID
1059  *
1060  * RETURNS
1061  *      Success: S_OK
1062  *  Failure: CO_E_CLASSSTRING - the given ProgID cannot be found.
1063  */
1064 HRESULT WINAPI CLSIDFromProgID16(LPCOLESTR16 progid, LPCLSID riid)
1065 {
1066         char    *buf,buf2[80];
1067         DWORD   buf2len;
1068         HRESULT err;
1069         HKEY    xhkey;
1070
1071         buf = HeapAlloc(GetProcessHeap(),0,strlen(progid)+8);
1072         sprintf(buf,"%s\\CLSID",progid);
1073         if ((err=RegOpenKeyA(HKEY_CLASSES_ROOT,buf,&xhkey))) {
1074                 HeapFree(GetProcessHeap(),0,buf);
1075                 return CO_E_CLASSSTRING;
1076         }
1077         HeapFree(GetProcessHeap(),0,buf);
1078         buf2len = sizeof(buf2);
1079         if ((err=RegQueryValueA(xhkey,NULL,buf2,&buf2len))) {
1080                 RegCloseKey(xhkey);
1081                 return CO_E_CLASSSTRING;
1082         }
1083         RegCloseKey(xhkey);
1084         return __CLSIDFromStringA(buf2,riid);
1085 }
1086
1087 /******************************************************************************
1088  *              CLSIDFromProgID [OLE32.@]
1089  *
1090  * Converts a program id into the respective GUID.
1091  *
1092  * PARAMS
1093  *  progid [I] Unicode program ID, as found in registry.
1094  *  riid   [O] Associated CLSID.
1095  *
1096  * RETURNS
1097  *      Success: S_OK
1098  *  Failure: CO_E_CLASSSTRING - the given ProgID cannot be found.
1099  */
1100 HRESULT WINAPI CLSIDFromProgID(LPCOLESTR progid, LPCLSID riid)
1101 {
1102     static const WCHAR clsidW[] = { '\\','C','L','S','I','D',0 };
1103     WCHAR buf2[CHARS_IN_GUID];
1104     DWORD buf2len = sizeof(buf2);
1105     HKEY xhkey;
1106
1107     WCHAR *buf = HeapAlloc( GetProcessHeap(),0,(strlenW(progid)+8) * sizeof(WCHAR) );
1108     strcpyW( buf, progid );
1109     strcatW( buf, clsidW );
1110     if (RegOpenKeyW(HKEY_CLASSES_ROOT,buf,&xhkey))
1111     {
1112         HeapFree(GetProcessHeap(),0,buf);
1113         return CO_E_CLASSSTRING;
1114     }
1115     HeapFree(GetProcessHeap(),0,buf);
1116
1117     if (RegQueryValueW(xhkey,NULL,buf2,&buf2len))
1118     {
1119         RegCloseKey(xhkey);
1120         return CO_E_CLASSSTRING;
1121     }
1122     RegCloseKey(xhkey);
1123     return CLSIDFromString(buf2,riid);
1124 }
1125
1126
1127
1128 /*****************************************************************************
1129  *             CoGetPSClsid [OLE32.@]
1130  *
1131  * Retrieves the CLSID of the proxy/stub factory that implements
1132  * IPSFactoryBuffer for the specified interface.
1133  *
1134  * PARAMS
1135  *  riid   [I] Interface whose proxy/stub CLSID is to be returned.
1136  *  pclsid [O] Where to store returned proxy/stub CLSID.
1137  * 
1138  * RETURNS
1139  *   S_OK
1140  *   E_OUTOFMEMORY
1141  *   REGDB_E_IIDNOTREG if no PSFactoryBuffer is associated with the IID, or it could not be parsed
1142  *
1143  * NOTES
1144  *
1145  * The standard marshaller activates the object with the CLSID
1146  * returned and uses the CreateProxy and CreateStub methods on its
1147  * IPSFactoryBuffer interface to construct the proxies and stubs for a
1148  * given object.
1149  *
1150  * CoGetPSClsid determines this CLSID by searching the
1151  * HKEY_CLASSES_ROOT\Interface\{string form of riid}\ProxyStubClsid32
1152  * in the registry and any interface id registered by
1153  * CoRegisterPSClsid within the current process.
1154  *
1155  * BUGS
1156  *
1157  * We only search the registry, not ids registered with
1158  * CoRegisterPSClsid.
1159  * Also, native returns S_OK for interfaces with a key in HKCR\Interface, but
1160  * without a ProxyStubClsid32 key and leaves garbage in pclsid. This should be
1161  * considered a bug in native unless an application depends on this (unlikely).
1162  */
1163 HRESULT WINAPI CoGetPSClsid(REFIID riid, CLSID *pclsid)
1164 {
1165     static const WCHAR wszInterface[] = {'I','n','t','e','r','f','a','c','e','\\',0};
1166     static const WCHAR wszPSC[] = {'\\','P','r','o','x','y','S','t','u','b','C','l','s','i','d','3','2',0};
1167     WCHAR path[ARRAYSIZE(wszInterface) - 1 + CHARS_IN_GUID - 1 + ARRAYSIZE(wszPSC)];
1168     WCHAR value[CHARS_IN_GUID];
1169     DWORD len;
1170     HKEY hkey;
1171
1172     TRACE("() riid=%s, pclsid=%p\n", debugstr_guid(riid), pclsid);
1173
1174     /* Interface\\{string form of riid}\\ProxyStubClsid32 */
1175     strcpyW(path, wszInterface);
1176     StringFromGUID2(riid, path + ARRAYSIZE(wszInterface) - 1, CHARS_IN_GUID);
1177     strcpyW(path + ARRAYSIZE(wszInterface) - 1 + CHARS_IN_GUID - 1, wszPSC);
1178
1179     /* Open the key.. */
1180     if (RegOpenKeyExW(HKEY_CLASSES_ROOT, path, 0, KEY_READ, &hkey))
1181     {
1182         WARN("No PSFactoryBuffer object is registered for IID %s\n", debugstr_guid(riid));
1183         return REGDB_E_IIDNOTREG;
1184     }
1185
1186     /* ... Once we have the key, query the registry to get the
1187        value of CLSID as a string, and convert it into a
1188        proper CLSID structure to be passed back to the app */
1189     len = sizeof(value);
1190     if (ERROR_SUCCESS != RegQueryValueW(hkey, NULL, value, &len))
1191     {
1192         RegCloseKey(hkey);
1193         return REGDB_E_IIDNOTREG;
1194     }
1195     RegCloseKey(hkey);
1196
1197     /* We have the CLSid we want back from the registry as a string, so
1198        lets convert it into a CLSID structure */
1199     if (CLSIDFromString(value, pclsid) != NOERROR)
1200         return REGDB_E_IIDNOTREG;
1201
1202     TRACE ("() Returning CLSID=%s\n", debugstr_guid(pclsid));
1203     return S_OK;
1204 }
1205
1206
1207
1208 /***********************************************************************
1209  *              WriteClassStm (OLE32.@)
1210  *
1211  * Writes a CLSID to a stream.
1212  *
1213  * PARAMS
1214  *  pStm   [I] Stream to write to.
1215  *  rclsid [I] CLSID to write.
1216  *
1217  * RETURNS
1218  *  Success: S_OK.
1219  *  Failure: HRESULT code.
1220  */
1221 HRESULT WINAPI WriteClassStm(IStream *pStm,REFCLSID rclsid)
1222 {
1223     TRACE("(%p,%p)\n",pStm,rclsid);
1224
1225     if (rclsid==NULL)
1226         return E_INVALIDARG;
1227
1228     return IStream_Write(pStm,rclsid,sizeof(CLSID),NULL);
1229 }
1230
1231 /***********************************************************************
1232  *              ReadClassStm (OLE32.@)
1233  *
1234  * Reads a CLSID from a stream.
1235  *
1236  * PARAMS
1237  *  pStm   [I] Stream to read from.
1238  *  rclsid [O] CLSID to read.
1239  *
1240  * RETURNS
1241  *  Success: S_OK.
1242  *  Failure: HRESULT code.
1243  */
1244 HRESULT WINAPI ReadClassStm(IStream *pStm,CLSID *pclsid)
1245 {
1246     ULONG nbByte;
1247     HRESULT res;
1248
1249     TRACE("(%p,%p)\n",pStm,pclsid);
1250
1251     if (pclsid==NULL)
1252         return E_INVALIDARG;
1253
1254     res = IStream_Read(pStm,(void*)pclsid,sizeof(CLSID),&nbByte);
1255
1256     if (FAILED(res))
1257         return res;
1258
1259     if (nbByte != sizeof(CLSID))
1260         return S_FALSE;
1261     else
1262         return S_OK;
1263 }
1264
1265
1266 /***
1267  * COM_GetRegisteredClassObject
1268  *
1269  * This internal method is used to scan the registered class list to
1270  * find a class object.
1271  *
1272  * Params:
1273  *   rclsid        Class ID of the class to find.
1274  *   dwClsContext  Class context to match.
1275  *   ppv           [out] returns a pointer to the class object. Complying
1276  *                 to normal COM usage, this method will increase the
1277  *                 reference count on this object.
1278  */
1279 static HRESULT COM_GetRegisteredClassObject(
1280         REFCLSID    rclsid,
1281         DWORD       dwClsContext,
1282         LPUNKNOWN*  ppUnk)
1283 {
1284   HRESULT hr = S_FALSE;
1285   RegisteredClass* curClass;
1286
1287   EnterCriticalSection( &csRegisteredClassList );
1288
1289   /*
1290    * Sanity check
1291    */
1292   assert(ppUnk!=0);
1293
1294   /*
1295    * Iterate through the whole list and try to match the class ID.
1296    */
1297   curClass = firstRegisteredClass;
1298
1299   while (curClass != 0)
1300   {
1301     /*
1302      * Check if we have a match on the class ID.
1303      */
1304     if (IsEqualGUID(&(curClass->classIdentifier), rclsid))
1305     {
1306       /*
1307        * Since we don't do out-of process or DCOM just right away, let's ignore the
1308        * class context.
1309        */
1310
1311       /*
1312        * We have a match, return the pointer to the class object.
1313        */
1314       *ppUnk = curClass->classObject;
1315
1316       IUnknown_AddRef(curClass->classObject);
1317
1318       hr = S_OK;
1319       goto end;
1320     }
1321
1322     /*
1323      * Step to the next class in the list.
1324      */
1325     curClass = curClass->nextClass;
1326   }
1327
1328 end:
1329   LeaveCriticalSection( &csRegisteredClassList );
1330   /*
1331    * If we get to here, we haven't found our class.
1332    */
1333   return hr;
1334 }
1335
1336 /******************************************************************************
1337  *              CoRegisterClassObject   [OLE32.@]
1338  *
1339  * Registers the class object for a given class ID. Servers housed in EXE
1340  * files use this method instead of exporting DllGetClassObject to allow
1341  * other code to connect to their objects.
1342  *
1343  * PARAMS
1344  *  rclsid       [I] CLSID of the object to register.
1345  *  pUnk         [I] IUnknown of the object.
1346  *  dwClsContext [I] CLSCTX flags indicating the context in which to run the executable.
1347  *  flags        [I] REGCLS flags indicating how connections are made.
1348  *  lpdwRegister [I] A unique cookie that can be passed to CoRevokeClassObject.
1349  *
1350  * RETURNS
1351  *   S_OK on success,
1352  *   E_INVALIDARG if lpdwRegister or pUnk are NULL,
1353  *   CO_E_OBJISREG if the object is already registered. We should not return this.
1354  *
1355  * SEE ALSO
1356  *   CoRevokeClassObject, CoGetClassObject
1357  *
1358  * BUGS
1359  *  MSDN claims that multiple interface registrations are legal, but we
1360  *  can't do that with our current implementation.
1361  */
1362 HRESULT WINAPI CoRegisterClassObject(
1363     REFCLSID rclsid,
1364     LPUNKNOWN pUnk,
1365     DWORD dwClsContext,
1366     DWORD flags,
1367     LPDWORD lpdwRegister)
1368 {
1369   RegisteredClass* newClass;
1370   LPUNKNOWN        foundObject;
1371   HRESULT          hr;
1372
1373   TRACE("(%s,%p,0x%08lx,0x%08lx,%p)\n",
1374         debugstr_guid(rclsid),pUnk,dwClsContext,flags,lpdwRegister);
1375
1376   if ( (lpdwRegister==0) || (pUnk==0) )
1377     return E_INVALIDARG;
1378
1379   if (!COM_CurrentApt())
1380   {
1381       ERR("COM was not initialized\n");
1382       return CO_E_NOTINITIALIZED;
1383   }
1384
1385   *lpdwRegister = 0;
1386
1387   /*
1388    * First, check if the class is already registered.
1389    * If it is, this should cause an error.
1390    */
1391   hr = COM_GetRegisteredClassObject(rclsid, dwClsContext, &foundObject);
1392   if (hr == S_OK) {
1393     IUnknown_Release(foundObject);
1394     return CO_E_OBJISREG;
1395   }
1396
1397   newClass = HeapAlloc(GetProcessHeap(), 0, sizeof(RegisteredClass));
1398   if ( newClass == NULL )
1399     return E_OUTOFMEMORY;
1400
1401   EnterCriticalSection( &csRegisteredClassList );
1402
1403   newClass->classIdentifier = *rclsid;
1404   newClass->runContext      = dwClsContext;
1405   newClass->connectFlags    = flags;
1406   newClass->pMarshaledData  = NULL;
1407
1408   /*
1409    * Use the address of the chain node as the cookie since we are sure it's
1410    * unique. FIXME: not on 64-bit platforms.
1411    */
1412   newClass->dwCookie        = (DWORD)newClass;
1413   newClass->nextClass       = firstRegisteredClass;
1414
1415   /*
1416    * Since we're making a copy of the object pointer, we have to increase its
1417    * reference count.
1418    */
1419   newClass->classObject     = pUnk;
1420   IUnknown_AddRef(newClass->classObject);
1421
1422   firstRegisteredClass = newClass;
1423   LeaveCriticalSection( &csRegisteredClassList );
1424
1425   *lpdwRegister = newClass->dwCookie;
1426
1427   if (dwClsContext & CLSCTX_LOCAL_SERVER) {
1428       IClassFactory *classfac;
1429
1430       hr = IUnknown_QueryInterface(newClass->classObject, &IID_IClassFactory,
1431                                    (LPVOID*)&classfac);
1432       if (hr) return hr;
1433
1434       hr = CreateStreamOnHGlobal(0, TRUE, &newClass->pMarshaledData);
1435       if (hr) {
1436           FIXME("Failed to create stream on hglobal, %lx\n", hr);
1437           IUnknown_Release(classfac);
1438           return hr;
1439       }
1440       hr = CoMarshalInterface(newClass->pMarshaledData, &IID_IClassFactory,
1441                               (LPVOID)classfac, MSHCTX_LOCAL, NULL,
1442                               MSHLFLAGS_TABLESTRONG);
1443       if (hr) {
1444           FIXME("CoMarshalInterface failed, %lx!\n",hr);
1445           IUnknown_Release(classfac);
1446           return hr;
1447       }
1448
1449       IUnknown_Release(classfac);
1450
1451       RPC_StartLocalServer(&newClass->classIdentifier, newClass->pMarshaledData);
1452   }
1453   return S_OK;
1454 }
1455
1456 /***********************************************************************
1457  *           CoRevokeClassObject [OLE32.@]
1458  *
1459  * Removes a class object from the class registry.
1460  *
1461  * PARAMS
1462  *  dwRegister [I] Cookie returned from CoRegisterClassObject().
1463  *
1464  * RETURNS
1465  *  Success: S_OK.
1466  *  Failure: HRESULT code.
1467  *
1468  * SEE ALSO
1469  *  CoRegisterClassObject
1470  */
1471 HRESULT WINAPI CoRevokeClassObject(
1472         DWORD dwRegister)
1473 {
1474   HRESULT hr = E_INVALIDARG;
1475   RegisteredClass** prevClassLink;
1476   RegisteredClass*  curClass;
1477
1478   TRACE("(%08lx)\n",dwRegister);
1479
1480   EnterCriticalSection( &csRegisteredClassList );
1481
1482   /*
1483    * Iterate through the whole list and try to match the cookie.
1484    */
1485   curClass      = firstRegisteredClass;
1486   prevClassLink = &firstRegisteredClass;
1487
1488   while (curClass != 0)
1489   {
1490     /*
1491      * Check if we have a match on the cookie.
1492      */
1493     if (curClass->dwCookie == dwRegister)
1494     {
1495       /*
1496        * Remove the class from the chain.
1497        */
1498       *prevClassLink = curClass->nextClass;
1499
1500       /*
1501        * Release the reference to the class object.
1502        */
1503       IUnknown_Release(curClass->classObject);
1504
1505       if (curClass->pMarshaledData)
1506       {
1507         LARGE_INTEGER zero;
1508         memset(&zero, 0, sizeof(zero));
1509         /* FIXME: stop local server thread */
1510         IStream_Seek(curClass->pMarshaledData, zero, SEEK_SET, NULL);
1511         CoReleaseMarshalData(curClass->pMarshaledData);
1512       }
1513
1514       /*
1515        * Free the memory used by the chain node.
1516        */
1517       HeapFree(GetProcessHeap(), 0, curClass);
1518
1519       hr = S_OK;
1520       goto end;
1521     }
1522
1523     /*
1524      * Step to the next class in the list.
1525      */
1526     prevClassLink = &(curClass->nextClass);
1527     curClass      = curClass->nextClass;
1528   }
1529
1530 end:
1531   LeaveCriticalSection( &csRegisteredClassList );
1532   /*
1533    * If we get to here, we haven't found our class.
1534    */
1535   return hr;
1536 }
1537
1538 /***********************************************************************
1539  *      COM_RegReadPath [internal]
1540  *
1541  *      Reads a registry value and expands it when necessary
1542  */
1543 HRESULT COM_RegReadPath(HKEY hkeyroot, const WCHAR *keyname, const WCHAR *valuename, WCHAR * dst, DWORD dstlen)
1544 {
1545         HRESULT hres;
1546         HKEY key;
1547         DWORD keytype;
1548         WCHAR src[MAX_PATH];
1549         DWORD dwLength = dstlen * sizeof(WCHAR);
1550
1551         if((hres = RegOpenKeyExW(hkeyroot, keyname, 0, KEY_READ, &key)) == ERROR_SUCCESS) {
1552           if( (hres = RegQueryValueExW(key, NULL, NULL, &keytype, (LPBYTE)src, &dwLength)) == ERROR_SUCCESS ) {
1553             if (keytype == REG_EXPAND_SZ) {
1554               if (dstlen <= ExpandEnvironmentStringsW(src, dst, dstlen)) hres = ERROR_MORE_DATA;
1555             } else {
1556               lstrcpynW(dst, src, dstlen);
1557             }
1558           }
1559           RegCloseKey (key);
1560         }
1561         return hres;
1562 }
1563
1564 /***********************************************************************
1565  *           CoGetClassObject [OLE32.@]
1566  *
1567  * FIXME.  If request allows of several options and there is a failure
1568  *         with one (other than not being registered) do we try the
1569  *         others or return failure?  (E.g. inprocess is registered but
1570  *         the DLL is not found but the server version works)
1571  */
1572 HRESULT WINAPI CoGetClassObject(
1573     REFCLSID rclsid, DWORD dwClsContext, COSERVERINFO *pServerInfo,
1574     REFIID iid, LPVOID *ppv)
1575 {
1576     LPUNKNOWN   regClassObject;
1577     HRESULT     hres = E_UNEXPECTED;
1578
1579     TRACE("\n\tCLSID:\t%s,\n\tIID:\t%s\n", debugstr_guid(rclsid), debugstr_guid(iid));
1580
1581     if (pServerInfo) {
1582         FIXME("\tpServerInfo: name=%s\n",debugstr_w(pServerInfo->pwszName));
1583         FIXME("\t\tpAuthInfo=%p\n",pServerInfo->pAuthInfo);
1584     }
1585
1586     /*
1587      * First, try and see if we can't match the class ID with one of the
1588      * registered classes.
1589      */
1590     if (S_OK == COM_GetRegisteredClassObject(rclsid, dwClsContext, &regClassObject))
1591     {
1592       /* Get the required interface from the retrieved pointer. */
1593       hres = IUnknown_QueryInterface(regClassObject, iid, ppv);
1594
1595       /*
1596        * Since QI got another reference on the pointer, we want to release the
1597        * one we already have. If QI was unsuccessful, this will release the object. This
1598        * is good since we are not returning it in the "out" parameter.
1599        */
1600       IUnknown_Release(regClassObject);
1601
1602       return hres;
1603     }
1604
1605     /* first try: in-process */
1606     if ((CLSCTX_INPROC_SERVER | CLSCTX_INPROC_HANDLER) & dwClsContext)
1607     {
1608         static const WCHAR wszInprocServer32[] = {'I','n','p','r','o','c','S','e','r','v','e','r','3','2',0};
1609         HINSTANCE hLibrary;
1610         typedef HRESULT (CALLBACK *DllGetClassObjectFunc)(REFCLSID clsid, REFIID iid, LPVOID *ppv);
1611         DllGetClassObjectFunc DllGetClassObject;
1612         WCHAR dllpath[MAX_PATH+1];
1613         HKEY hkey;
1614
1615         if (ERROR_SUCCESS != COM_OpenKeyForCLSID(rclsid, KEY_READ, &hkey))
1616         {
1617             ERR("class %s not registered\n", debugstr_guid(rclsid));
1618             hres = REGDB_E_CLASSNOTREG;
1619         }
1620
1621         if (COM_RegReadPath(hkey, wszInprocServer32, NULL, dllpath, ARRAYSIZE(dllpath)) != ERROR_SUCCESS)
1622         {
1623             /* failure: CLSID is not found in registry */
1624             WARN("class %s not registered inproc\n", debugstr_guid(rclsid));
1625             hres = REGDB_E_CLASSNOTREG;
1626         }
1627         else
1628         {
1629             if ((hLibrary = LoadLibraryExW(dllpath, 0, LOAD_WITH_ALTERED_SEARCH_PATH)) == 0)
1630             {
1631                 /* failure: DLL could not be loaded */
1632                 ERR("couldn't load InprocServer32 dll %s\n", debugstr_w(dllpath));
1633                 hres = E_ACCESSDENIED; /* FIXME: or should this be CO_E_DLLNOTFOUND? */
1634             }
1635             else if (!(DllGetClassObject = (DllGetClassObjectFunc)GetProcAddress(hLibrary, "DllGetClassObject")))
1636             {
1637                 /* failure: the dll did not export DllGetClassObject */
1638                 ERR("couldn't find function DllGetClassObject in %s\n", debugstr_w(dllpath));
1639                 FreeLibrary( hLibrary );
1640                 hres = CO_E_DLLNOTFOUND;
1641             }
1642             else
1643             {
1644                 /* OK: get the ClassObject */
1645                 COMPOBJ_DLLList_Add( hLibrary );
1646                 return DllGetClassObject(rclsid, iid, ppv);
1647             }
1648         }
1649     }
1650
1651     /* Next try out of process */
1652     if (CLSCTX_LOCAL_SERVER & dwClsContext)
1653     {
1654         return RPC_GetLocalClassObject(rclsid,iid,ppv);
1655     }
1656
1657     /* Finally try remote: this requires networked DCOM (a lot of work) */
1658     if (CLSCTX_REMOTE_SERVER & dwClsContext)
1659     {
1660         FIXME ("CLSCTX_REMOTE_SERVER not supported\n");
1661         hres = E_NOINTERFACE;
1662     }
1663
1664     return hres;
1665 }
1666
1667 /***********************************************************************
1668  *           CoGetClassObject [COMPOBJ.7]
1669  *
1670  */
1671 HRESULT WINAPI CoGetClassObject16(
1672     REFCLSID rclsid, DWORD dwClsContext, COSERVERINFO *pServerInfo,
1673     REFIID iid, LPVOID *ppv)
1674 {
1675     FIXME(", stub!\n\tCLSID:\t%s,\n\tIID:\t%s\n", debugstr_guid(rclsid), debugstr_guid(iid));
1676
1677     if (pServerInfo) {
1678         FIXME("\tpServerInfo: name=%s\n",debugstr_w(pServerInfo->pwszName));
1679         FIXME("\t\tpAuthInfo=%p\n",pServerInfo->pAuthInfo);
1680     }
1681     return E_NOTIMPL;
1682 }
1683 /***********************************************************************
1684  *        CoResumeClassObjects (OLE32.@)
1685  *
1686  * Resumes all class objects registered with REGCLS_SUSPENDED.
1687  *
1688  * RETURNS
1689  *  Success: S_OK.
1690  *  Failure: HRESULT code.
1691  */
1692 HRESULT WINAPI CoResumeClassObjects(void)
1693 {
1694        FIXME("stub\n");
1695         return S_OK;
1696 }
1697
1698 /***********************************************************************
1699  *        GetClassFile (OLE32.@)
1700  *
1701  * This function supplies the CLSID associated with the given filename.
1702  */
1703 HRESULT WINAPI GetClassFile(LPCOLESTR filePathName,CLSID *pclsid)
1704 {
1705     IStorage *pstg=0;
1706     HRESULT res;
1707     int nbElm, length, i;
1708     LONG sizeProgId;
1709     LPOLESTR *pathDec=0,absFile=0,progId=0;
1710     LPWSTR extension;
1711     static const WCHAR bkslashW[] = {'\\',0};
1712     static const WCHAR dotW[] = {'.',0};
1713
1714     TRACE("%s, %p\n", debugstr_w(filePathName), pclsid);
1715
1716     /* if the file contain a storage object the return the CLSID written by IStorage_SetClass method*/
1717     if((StgIsStorageFile(filePathName))==S_OK){
1718
1719         res=StgOpenStorage(filePathName,NULL,STGM_READ | STGM_SHARE_DENY_WRITE,NULL,0,&pstg);
1720
1721         if (SUCCEEDED(res))
1722             res=ReadClassStg(pstg,pclsid);
1723
1724         IStorage_Release(pstg);
1725
1726         return res;
1727     }
1728     /* if the file is not a storage object then attemps to match various bits in the file against a
1729        pattern in the registry. this case is not frequently used ! so I present only the psodocode for
1730        this case
1731
1732      for(i=0;i<nFileTypes;i++)
1733
1734         for(i=0;j<nPatternsForType;j++){
1735
1736             PATTERN pat;
1737             HANDLE  hFile;
1738
1739             pat=ReadPatternFromRegistry(i,j);
1740             hFile=CreateFileW(filePathName,,,,,,hFile);
1741             SetFilePosition(hFile,pat.offset);
1742             ReadFile(hFile,buf,pat.size,&r,NULL);
1743             if (memcmp(buf&pat.mask,pat.pattern.pat.size)==0){
1744
1745                 *pclsid=ReadCLSIDFromRegistry(i);
1746                 return S_OK;
1747             }
1748         }
1749      */
1750
1751     /* if the above strategies fail then search for the extension key in the registry */
1752
1753     /* get the last element (absolute file) in the path name */
1754     nbElm=FileMonikerImpl_DecomposePath(filePathName,&pathDec);
1755     absFile=pathDec[nbElm-1];
1756
1757     /* failed if the path represente a directory and not an absolute file name*/
1758     if (!lstrcmpW(absFile, bkslashW))
1759         return MK_E_INVALIDEXTENSION;
1760
1761     /* get the extension of the file */
1762     extension = NULL;
1763     length=lstrlenW(absFile);
1764     for(i = length-1; (i >= 0) && *(extension = &absFile[i]) != '.'; i--)
1765         /* nothing */;
1766
1767     if (!extension || !lstrcmpW(extension, dotW))
1768         return MK_E_INVALIDEXTENSION;
1769
1770     res=RegQueryValueW(HKEY_CLASSES_ROOT, extension, NULL, &sizeProgId);
1771
1772     /* get the progId associated to the extension */
1773     progId = CoTaskMemAlloc(sizeProgId);
1774     res = RegQueryValueW(HKEY_CLASSES_ROOT, extension, progId, &sizeProgId);
1775
1776     if (res==ERROR_SUCCESS)
1777         /* return the clsid associated to the progId */
1778         res= CLSIDFromProgID(progId,pclsid);
1779
1780     for(i=0; pathDec[i]!=NULL;i++)
1781         CoTaskMemFree(pathDec[i]);
1782     CoTaskMemFree(pathDec);
1783
1784     CoTaskMemFree(progId);
1785
1786     if (res==ERROR_SUCCESS)
1787         return res;
1788
1789     return MK_E_INVALIDEXTENSION;
1790 }
1791
1792 /***********************************************************************
1793  *           CoCreateInstance [OLE32.@]
1794  */
1795 HRESULT WINAPI CoCreateInstance(
1796         REFCLSID rclsid,
1797         LPUNKNOWN pUnkOuter,
1798         DWORD dwClsContext,
1799         REFIID iid,
1800         LPVOID *ppv)
1801 {
1802   HRESULT hres;
1803   LPCLASSFACTORY lpclf = 0;
1804
1805   if (!COM_CurrentApt()) return CO_E_NOTINITIALIZED;
1806
1807   /*
1808    * Sanity check
1809    */
1810   if (ppv==0)
1811     return E_POINTER;
1812
1813   /*
1814    * Initialize the "out" parameter
1815    */
1816   *ppv = 0;
1817
1818   /*
1819    * The Standard Global Interface Table (GIT) object is a process-wide singleton.
1820    * Rather than create a class factory, we can just check for it here
1821    */
1822   if (IsEqualIID(rclsid, &CLSID_StdGlobalInterfaceTable)) {
1823     if (StdGlobalInterfaceTableInstance == NULL)
1824       StdGlobalInterfaceTableInstance = StdGlobalInterfaceTable_Construct();
1825     hres = IGlobalInterfaceTable_QueryInterface( (IGlobalInterfaceTable*) StdGlobalInterfaceTableInstance, iid, ppv);
1826     if (hres) return hres;
1827
1828     TRACE("Retrieved GIT (%p)\n", *ppv);
1829     return S_OK;
1830   }
1831
1832   /*
1833    * Get a class factory to construct the object we want.
1834    */
1835   hres = CoGetClassObject(rclsid,
1836                           dwClsContext,
1837                           NULL,
1838                           &IID_IClassFactory,
1839                           (LPVOID)&lpclf);
1840
1841   if (FAILED(hres)) {
1842     FIXME("no classfactory created for CLSID %s, hres is 0x%08lx\n",
1843           debugstr_guid(rclsid),hres);
1844     return hres;
1845   }
1846
1847   /*
1848    * Create the object and don't forget to release the factory
1849    */
1850         hres = IClassFactory_CreateInstance(lpclf, pUnkOuter, iid, ppv);
1851         IClassFactory_Release(lpclf);
1852         if(FAILED(hres))
1853           FIXME("no instance created for interface %s of class %s, hres is 0x%08lx\n",
1854                 debugstr_guid(iid), debugstr_guid(rclsid),hres);
1855
1856         return hres;
1857 }
1858
1859 /***********************************************************************
1860  *           CoCreateInstance [COMPOBJ.13]
1861  */
1862 HRESULT WINAPI CoCreateInstance16(
1863         REFCLSID rclsid,
1864         LPUNKNOWN pUnkOuter,
1865         DWORD dwClsContext,
1866         REFIID iid,
1867         LPVOID *ppv)
1868 {
1869   FIXME("(%s, %p, %lx, %s, %p), stub!\n", 
1870         debugstr_guid(rclsid), pUnkOuter, dwClsContext, debugstr_guid(iid),
1871         ppv
1872   );
1873   return E_NOTIMPL;
1874 }
1875
1876 /***********************************************************************
1877  *           CoCreateInstanceEx [OLE32.@]
1878  */
1879 HRESULT WINAPI CoCreateInstanceEx(
1880   REFCLSID      rclsid,
1881   LPUNKNOWN     pUnkOuter,
1882   DWORD         dwClsContext,
1883   COSERVERINFO* pServerInfo,
1884   ULONG         cmq,
1885   MULTI_QI*     pResults)
1886 {
1887   IUnknown* pUnk = NULL;
1888   HRESULT   hr;
1889   ULONG     index;
1890   ULONG     successCount = 0;
1891
1892   /*
1893    * Sanity check
1894    */
1895   if ( (cmq==0) || (pResults==NULL))
1896     return E_INVALIDARG;
1897
1898   if (pServerInfo!=NULL)
1899     FIXME("() non-NULL pServerInfo not supported!\n");
1900
1901   /*
1902    * Initialize all the "out" parameters.
1903    */
1904   for (index = 0; index < cmq; index++)
1905   {
1906     pResults[index].pItf = NULL;
1907     pResults[index].hr   = E_NOINTERFACE;
1908   }
1909
1910   /*
1911    * Get the object and get its IUnknown pointer.
1912    */
1913   hr = CoCreateInstance(rclsid,
1914                         pUnkOuter,
1915                         dwClsContext,
1916                         &IID_IUnknown,
1917                         (VOID**)&pUnk);
1918
1919   if (hr)
1920     return hr;
1921
1922   /*
1923    * Then, query for all the interfaces requested.
1924    */
1925   for (index = 0; index < cmq; index++)
1926   {
1927     pResults[index].hr = IUnknown_QueryInterface(pUnk,
1928                                                  pResults[index].pIID,
1929                                                  (VOID**)&(pResults[index].pItf));
1930
1931     if (pResults[index].hr == S_OK)
1932       successCount++;
1933   }
1934
1935   /*
1936    * Release our temporary unknown pointer.
1937    */
1938   IUnknown_Release(pUnk);
1939
1940   if (successCount == 0)
1941     return E_NOINTERFACE;
1942
1943   if (successCount!=cmq)
1944     return CO_S_NOTALLINTERFACES;
1945
1946   return S_OK;
1947 }
1948
1949 /***********************************************************************
1950  *           CoLoadLibrary (OLE32.@)
1951  *
1952  * Loads a library.
1953  *
1954  * PARAMS
1955  *  lpszLibName [I] Path to library.
1956  *  bAutoFree   [I] Whether the library should automatically be freed.
1957  *
1958  * RETURNS
1959  *  Success: Handle to loaded library.
1960  *  Failure: NULL.
1961  *
1962  * SEE ALSO
1963  *  CoFreeLibrary, CoFreeAllLibraries, CoFreeUnusedLibraries
1964  */
1965 HINSTANCE WINAPI CoLoadLibrary(LPOLESTR lpszLibName, BOOL bAutoFree)
1966 {
1967     TRACE("(%s, %d)\n", debugstr_w(lpszLibName), bAutoFree);
1968
1969     return LoadLibraryExW(lpszLibName, 0, LOAD_WITH_ALTERED_SEARCH_PATH);
1970 }
1971
1972 /***********************************************************************
1973  *           CoFreeLibrary [OLE32.@]
1974  *
1975  * Unloads a library from memory.
1976  *
1977  * PARAMS
1978  *  hLibrary [I] Handle to library to unload.
1979  *
1980  * RETURNS
1981  *  Nothing
1982  *
1983  * SEE ALSO
1984  *  CoLoadLibrary, CoFreeAllLibraries, CoFreeUnusedLibraries
1985  */
1986 void WINAPI CoFreeLibrary(HINSTANCE hLibrary)
1987 {
1988     FreeLibrary(hLibrary);
1989 }
1990
1991
1992 /***********************************************************************
1993  *           CoFreeAllLibraries [OLE32.@]
1994  *
1995  * Function for backwards compatibility only. Does nothing.
1996  *
1997  * RETURNS
1998  *  Nothing.
1999  *
2000  * SEE ALSO
2001  *  CoLoadLibrary, CoFreeLibrary, CoFreeUnusedLibraries
2002  */
2003 void WINAPI CoFreeAllLibraries(void)
2004 {
2005     /* NOP */
2006 }
2007
2008
2009 /***********************************************************************
2010  *           CoFreeUnusedLibraries [OLE32.@]
2011  *           CoFreeUnusedLibraries [COMPOBJ.17]
2012  *
2013  * Frees any unused libraries. Unused are identified as those that return
2014  * S_OK from their DllCanUnloadNow function.
2015  *
2016  * RETURNS
2017  *  Nothing.
2018  *
2019  * SEE ALSO
2020  *  CoLoadLibrary, CoFreeAllLibraries, CoFreeLibrary
2021  */
2022 void WINAPI CoFreeUnusedLibraries(void)
2023 {
2024     /* FIXME: Calls to CoFreeUnusedLibraries from any thread always route
2025      * through the main apartment's thread to call DllCanUnloadNow */
2026     COMPOBJ_DllList_FreeUnused(0);
2027 }
2028
2029 /***********************************************************************
2030  *           CoFileTimeNow [OLE32.@]
2031  *           CoFileTimeNow [COMPOBJ.82]
2032  *
2033  * Retrieves the current time in FILETIME format.
2034  *
2035  * PARAMS
2036  *  lpFileTime [O] The current time.
2037  *
2038  * RETURNS
2039  *      S_OK.
2040  */
2041 HRESULT WINAPI CoFileTimeNow( FILETIME *lpFileTime )
2042 {
2043     GetSystemTimeAsFileTime( lpFileTime );
2044     return S_OK;
2045 }
2046
2047 static void COM_RevokeAllClasses()
2048 {
2049   EnterCriticalSection( &csRegisteredClassList );
2050
2051   while (firstRegisteredClass!=0)
2052   {
2053     CoRevokeClassObject(firstRegisteredClass->dwCookie);
2054   }
2055
2056   LeaveCriticalSection( &csRegisteredClassList );
2057 }
2058
2059 /******************************************************************************
2060  *              CoLockObjectExternal    [OLE32.@]
2061  *
2062  * Increments or decrements the external reference count of a stub object.
2063  *
2064  * PARAMS
2065  *  pUnk                [I] Stub object.
2066  *  fLock               [I] If TRUE then increments the external ref-count,
2067  *                          otherwise decrements.
2068  *  fLastUnlockReleases [I] If TRUE then the last unlock has the effect of
2069  *                          calling CoDisconnectObject.
2070  *
2071  * RETURNS
2072  *  Success: S_OK.
2073  *  Failure: HRESULT code.
2074  */
2075 HRESULT WINAPI CoLockObjectExternal(
2076     LPUNKNOWN pUnk,
2077     BOOL fLock,
2078     BOOL fLastUnlockReleases)
2079 {
2080     struct stub_manager *stubmgr;
2081     struct apartment *apt;
2082
2083     TRACE("pUnk=%p, fLock=%s, fLastUnlockReleases=%s\n",
2084           pUnk, fLock ? "TRUE" : "FALSE", fLastUnlockReleases ? "TRUE" : "FALSE");
2085
2086     apt = COM_CurrentApt();
2087     if (!apt) return CO_E_NOTINITIALIZED;
2088
2089     stubmgr = get_stub_manager_from_object(apt, pUnk);
2090     
2091     if (stubmgr)
2092     {
2093         if (fLock)
2094             stub_manager_ext_addref(stubmgr, 1);
2095         else
2096             stub_manager_ext_release(stubmgr, 1);
2097         
2098         stub_manager_int_release(stubmgr);
2099
2100         return S_OK;
2101     }
2102     else
2103     {
2104         WARN("stub object not found %p\n", pUnk);
2105         /* Note: native is pretty broken here because it just silently
2106          * fails, without returning an appropriate error code, making apps
2107          * think that the object was disconnected, when it actually wasn't */
2108         return S_OK;
2109     }
2110 }
2111
2112 /***********************************************************************
2113  *           CoInitializeWOW (OLE32.@)
2114  *
2115  * WOW equivalent of CoInitialize?
2116  *
2117  * PARAMS
2118  *  x [I] Unknown.
2119  *  y [I] Unknown.
2120  *
2121  * RETURNS
2122  *  Unknown.
2123  */
2124 HRESULT WINAPI CoInitializeWOW(DWORD x,DWORD y)
2125 {
2126     FIXME("(0x%08lx,0x%08lx),stub!\n",x,y);
2127     return 0;
2128 }
2129
2130 /***********************************************************************
2131  *           CoGetState [OLE32.@]
2132  *
2133  * Retrieves the thread state object previously stored by CoSetState().
2134  *
2135  * PARAMS
2136  *  ppv [I] Address where pointer to object will be stored.
2137  *
2138  * RETURNS
2139  *  Success: S_OK.
2140  *  Failure: E_OUTOFMEMORY.
2141  *
2142  * NOTES
2143  *  Crashes on all invalid ppv addresses, including NULL.
2144  *  If the function returns a non-NULL object then the caller must release its
2145  *  reference on the object when the object is no longer required.
2146  *
2147  * SEE ALSO
2148  *  CoSetState().
2149  */
2150 HRESULT WINAPI CoGetState(IUnknown ** ppv)
2151 {
2152     struct oletls *info = COM_CurrentInfo();
2153     if (!info) return E_OUTOFMEMORY;
2154
2155     *ppv = NULL;
2156
2157     if (info->state)
2158     {
2159         IUnknown_AddRef(info->state);
2160         *ppv = info->state;
2161         TRACE("apt->state=%p\n", info->state);
2162     }
2163
2164     return S_OK;
2165 }
2166
2167 /***********************************************************************
2168  *           CoSetState [OLE32.@]
2169  *
2170  * Sets the thread state object.
2171  *
2172  * PARAMS
2173  *  pv [I] Pointer to state object to be stored.
2174  *
2175  * NOTES
2176  *  The system keeps a reference on the object while the object stored.
2177  *
2178  * RETURNS
2179  *  Success: S_OK.
2180  *  Failure: E_OUTOFMEMORY.
2181  */
2182 HRESULT WINAPI CoSetState(IUnknown * pv)
2183 {
2184     struct oletls *info = COM_CurrentInfo();
2185     if (!info) return E_OUTOFMEMORY;
2186
2187     if (pv) IUnknown_AddRef(pv);
2188
2189     if (info->state)
2190     {
2191         TRACE("-- release %p now\n", info->state);
2192         IUnknown_Release(info->state);
2193     }
2194
2195     info->state = pv;
2196
2197     return S_OK;
2198 }
2199
2200
2201 /******************************************************************************
2202  *              OleGetAutoConvert        [OLE32.@]
2203  */
2204 HRESULT WINAPI OleGetAutoConvert(REFCLSID clsidOld, LPCLSID pClsidNew)
2205 {
2206     static const WCHAR wszAutoConvertTo[] = {'A','u','t','o','C','o','n','v','e','r','t','T','o',0};
2207     HKEY hkey = NULL;
2208     WCHAR buf[CHARS_IN_GUID];
2209     DWORD len;
2210     HRESULT res = S_OK;
2211
2212     if (ERROR_SUCCESS != COM_OpenKeyForCLSID(clsidOld, KEY_READ, &hkey))
2213     {
2214         res = REGDB_E_CLASSNOTREG;
2215         goto done;
2216     }
2217
2218     len = sizeof(buf);
2219     /* we can just query for the default value of AutoConvertTo key like that,
2220        without opening the AutoConvertTo key and querying for NULL (default) */
2221     if (RegQueryValueW(hkey, wszAutoConvertTo, buf, &len))
2222     {
2223         res = REGDB_E_KEYMISSING;
2224         goto done;
2225     }
2226     res = CLSIDFromString(buf, pClsidNew);
2227 done:
2228     if (hkey) RegCloseKey(hkey);
2229     return res;
2230 }
2231
2232 /******************************************************************************
2233  *              CoTreatAsClass        [OLE32.@]
2234  *
2235  * Sets the TreatAs value of a class.
2236  *
2237  * PARAMS
2238  *  clsidOld [I] Class to set TreatAs value on.
2239  *  clsidNew [I] The class the clsidOld should be treated as.
2240  *
2241  * RETURNS
2242  *  Success: S_OK.
2243  *  Failure: HRESULT code.
2244  *
2245  * SEE ALSO
2246  *  CoGetTreatAsClass
2247  */
2248 HRESULT WINAPI CoTreatAsClass(REFCLSID clsidOld, REFCLSID clsidNew)
2249 {
2250     static const WCHAR wszAutoTreatAs[] = {'A','u','t','o','T','r','e','a','t','A','s',0};
2251     static const WCHAR wszTreatAs[] = {'T','r','e','a','t','A','s',0};
2252     HKEY hkey = NULL;
2253     WCHAR szClsidNew[CHARS_IN_GUID];
2254     HRESULT res = S_OK;
2255     WCHAR auto_treat_as[CHARS_IN_GUID];
2256     LONG auto_treat_as_size = sizeof(auto_treat_as);
2257     CLSID id;
2258
2259     if (ERROR_SUCCESS != COM_OpenKeyForCLSID(clsidOld, KEY_READ | KEY_WRITE, &hkey))
2260     {
2261         res = REGDB_E_CLASSNOTREG;
2262         goto done;
2263     }
2264     if (!memcmp( clsidOld, clsidNew, sizeof(*clsidOld) ))
2265     {
2266        if (!RegQueryValueW(hkey, wszAutoTreatAs, auto_treat_as, &auto_treat_as_size) &&
2267            !CLSIDFromString(auto_treat_as, &id))
2268        {
2269            if (RegSetValueW(hkey, wszTreatAs, REG_SZ, auto_treat_as, sizeof(auto_treat_as)))
2270            {
2271                res = REGDB_E_WRITEREGDB;
2272                goto done;
2273            }
2274        }
2275        else
2276        {
2277            RegDeleteKeyW(hkey, wszTreatAs);
2278            goto done;
2279        }
2280     }
2281     else if (!StringFromGUID2(clsidNew, szClsidNew, ARRAYSIZE(szClsidNew)) &&
2282              !RegSetValueW(hkey, wszTreatAs, REG_SZ, szClsidNew, sizeof(szClsidNew)))
2283     {
2284         res = REGDB_E_WRITEREGDB;
2285         goto done;
2286     }
2287
2288 done:
2289     if (hkey) RegCloseKey(hkey);
2290     return res;
2291 }
2292
2293 /******************************************************************************
2294  *              CoGetTreatAsClass        [OLE32.@]
2295  *
2296  * Gets the TreatAs value of a class.
2297  *
2298  * PARAMS
2299  *  clsidOld [I] Class to get the TreatAs value of.
2300  *  clsidNew [I] The class the clsidOld should be treated as.
2301  *
2302  * RETURNS
2303  *  Success: S_OK.
2304  *  Failure: HRESULT code.
2305  *
2306  * SEE ALSO
2307  *  CoSetTreatAsClass
2308  */
2309 HRESULT WINAPI CoGetTreatAsClass(REFCLSID clsidOld, LPCLSID clsidNew)
2310 {
2311     static const WCHAR wszTreatAs[] = {'T','r','e','a','t','A','s',0};
2312     HKEY hkey = NULL;
2313     WCHAR szClsidNew[CHARS_IN_GUID];
2314     HRESULT res = S_OK;
2315     LONG len = sizeof(szClsidNew);
2316
2317     FIXME("(%s,%p)\n", debugstr_guid(clsidOld), clsidNew);
2318     memcpy(clsidNew,clsidOld,sizeof(CLSID)); /* copy over old value */
2319
2320     if (COM_OpenKeyForCLSID(clsidOld, KEY_READ, &hkey))
2321     {
2322         res = REGDB_E_CLASSNOTREG;
2323         goto done;
2324     }
2325     if (RegQueryValueW(hkey, wszTreatAs, szClsidNew, &len))
2326     {
2327         res = S_FALSE;
2328         goto done;
2329     }
2330     res = CLSIDFromString(szClsidNew,clsidNew);
2331     if (FAILED(res))
2332         ERR("Failed CLSIDFromStringA(%s), hres 0x%08lx\n", debugstr_w(szClsidNew), res);
2333 done:
2334     if (hkey) RegCloseKey(hkey);
2335     return res;
2336 }
2337
2338 /******************************************************************************
2339  *              CoGetCurrentProcess     [OLE32.@]
2340  *              CoGetCurrentProcess     [COMPOBJ.34]
2341  *
2342  * Gets the current process ID.
2343  *
2344  * RETURNS
2345  *  The current process ID.
2346  *
2347  * NOTES
2348  *   Is DWORD really the correct return type for this function?
2349  */
2350 DWORD WINAPI CoGetCurrentProcess(void)
2351 {
2352         return GetCurrentProcessId();
2353 }
2354
2355 /******************************************************************************
2356  *              CoRegisterMessageFilter [OLE32.@]
2357  *
2358  * Registers a message filter.
2359  *
2360  * PARAMS
2361  *  lpMessageFilter [I] Pointer to interface.
2362  *  lplpMessageFilter [O] Indirect pointer to prior instance if non-NULL.
2363  *
2364  * RETURNS
2365  *  Success: S_OK.
2366  *  Failure: HRESULT code.
2367  */
2368 HRESULT WINAPI CoRegisterMessageFilter(
2369     LPMESSAGEFILTER lpMessageFilter,
2370     LPMESSAGEFILTER *lplpMessageFilter)
2371 {
2372     FIXME("stub\n");
2373     if (lplpMessageFilter) {
2374         *lplpMessageFilter = NULL;
2375     }
2376     return S_OK;
2377 }
2378
2379 /***********************************************************************
2380  *           CoIsOle1Class [OLE32.@]
2381  *
2382  * Determines whether the specified class an OLE v1 class.
2383  *
2384  * PARAMS
2385  *  clsid [I] Class to test.
2386  *
2387  * RETURNS
2388  *  TRUE if the class is an OLE v1 class, or FALSE otherwise.
2389  */
2390 BOOL WINAPI CoIsOle1Class(REFCLSID clsid)
2391 {
2392   FIXME("%s\n", debugstr_guid(clsid));
2393   return FALSE;
2394 }
2395
2396 /***********************************************************************
2397  *           IsEqualGUID [OLE32.@]
2398  *
2399  * Compares two Unique Identifiers.
2400  *
2401  * PARAMS
2402  *  rguid1 [I] The first GUID to compare.
2403  *  rguid2 [I] The other GUID to compare.
2404  *
2405  * RETURNS
2406  *      TRUE if equal
2407  */
2408 #undef IsEqualGUID
2409 BOOL WINAPI IsEqualGUID(
2410      REFGUID rguid1,
2411      REFGUID rguid2)
2412 {
2413     return !memcmp(rguid1,rguid2,sizeof(GUID));
2414 }
2415
2416 /***********************************************************************
2417  *           CoInitializeSecurity [OLE32.@]
2418  */
2419 HRESULT WINAPI CoInitializeSecurity(PSECURITY_DESCRIPTOR pSecDesc, LONG cAuthSvc,
2420                                     SOLE_AUTHENTICATION_SERVICE* asAuthSvc,
2421                                     void* pReserved1, DWORD dwAuthnLevel,
2422                                     DWORD dwImpLevel, void* pReserved2,
2423                                     DWORD dwCapabilities, void* pReserved3)
2424 {
2425   FIXME("(%p,%ld,%p,%p,%ld,%ld,%p,%ld,%p) - stub!\n", pSecDesc, cAuthSvc,
2426         asAuthSvc, pReserved1, dwAuthnLevel, dwImpLevel, pReserved2,
2427         dwCapabilities, pReserved3);
2428   return S_OK;
2429 }
2430
2431 /***********************************************************************
2432  *           CoSuspendClassObjects [OLE32.@]
2433  *
2434  * Suspends all registered class objects to prevent further requests coming in
2435  * for those objects.
2436  *
2437  * RETURNS
2438  *  Success: S_OK.
2439  *  Failure: HRESULT code.
2440  */
2441 HRESULT WINAPI CoSuspendClassObjects(void)
2442 {
2443     FIXME("\n");
2444     return S_OK;
2445 }
2446
2447 /***********************************************************************
2448  *           CoAddRefServerProcess [OLE32.@]
2449  *
2450  * Helper function for incrementing the reference count of a local-server
2451  * process.
2452  *
2453  * RETURNS
2454  *  New reference count.
2455  */
2456 ULONG WINAPI CoAddRefServerProcess(void)
2457 {
2458     FIXME("\n");
2459     return 2;
2460 }
2461
2462 /***********************************************************************
2463  *           CoReleaseServerProcess [OLE32.@]
2464  *
2465  * Helper function for decrementing the reference count of a local-server
2466  * process.
2467  *
2468  * RETURNS
2469  *  New reference count.
2470  */
2471 ULONG WINAPI CoReleaseServerProcess(void)
2472 {
2473     FIXME("\n");
2474     return 1;
2475 }
2476
2477 /***********************************************************************
2478  *           CoIsHandlerConnected [OLE32.@]
2479  *
2480  * Determines whether a proxy is connected to a remote stub.
2481  *
2482  * PARAMS
2483  *  pUnk [I] Pointer to object that may or may not be connected.
2484  *
2485  * RETURNS
2486  *  TRUE if pUnk is not a proxy or if pUnk is connected to a remote stub, or
2487  *  FALSE otherwise.
2488  */
2489 BOOL WINAPI CoIsHandlerConnected(IUnknown *pUnk)
2490 {
2491     FIXME("%p\n", pUnk);
2492
2493     return TRUE;
2494 }
2495  
2496 /***********************************************************************
2497  *           CoQueryProxyBlanket [OLE32.@]
2498  *
2499  * Retrieves the security settings being used by a proxy.
2500  *
2501  * PARAMS
2502  *  pProxy        [I] Pointer to the proxy object.
2503  *  pAuthnSvc     [O] The type of authentication service.
2504  *  pAuthzSvc     [O] The type of authorization service.
2505  *  ppServerPrincName [O] Optional. The server prinicple name.
2506  *  pAuthnLevel   [O] The authentication level.
2507  *  pImpLevel     [O] The impersonation level.
2508  *  ppAuthInfo    [O] Information specific to the authorization/authentication service.
2509  *  pCapabilities [O] Flags affecting the security behaviour.
2510  *
2511  * RETURNS
2512  *  Success: S_OK.
2513  *  Failure: HRESULT code.
2514  *
2515  * SEE ALSO
2516  *  CoCopyProxy, CoSetProxyBlanket.
2517  */
2518 HRESULT WINAPI CoQueryProxyBlanket(IUnknown *pProxy, DWORD *pAuthnSvc,
2519     DWORD *pAuthzSvc, OLECHAR **ppServerPrincName, DWORD *pAuthnLevel,
2520     DWORD *pImpLevel, void **ppAuthInfo, DWORD *pCapabilities)
2521 {
2522     IClientSecurity *pCliSec;
2523     HRESULT hr;
2524
2525     TRACE("%p\n", pProxy);
2526
2527     hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
2528     if (SUCCEEDED(hr))
2529     {
2530         hr = IClientSecurity_QueryBlanket(pCliSec, pProxy, pAuthnSvc,
2531                                           pAuthzSvc, ppServerPrincName,
2532                                           pAuthnLevel, pImpLevel, ppAuthInfo,
2533                                           pCapabilities);
2534         IClientSecurity_Release(pCliSec);
2535     }
2536
2537     if (FAILED(hr)) ERR("-- failed with 0x%08lx\n", hr);
2538     return hr;
2539 }
2540
2541 /***********************************************************************
2542  *           CoSetProxyBlanket [OLE32.@]
2543  *
2544  * Sets the security settings for a proxy.
2545  *
2546  * PARAMS
2547  *  pProxy       [I] Pointer to the proxy object.
2548  *  AuthnSvc     [I] The type of authentication service.
2549  *  AuthzSvc     [I] The type of authorization service.
2550  *  pServerPrincName [I] The server prinicple name.
2551  *  AuthnLevel   [I] The authentication level.
2552  *  ImpLevel     [I] The impersonation level.
2553  *  pAuthInfo    [I] Information specific to the authorization/authentication service.
2554  *  Capabilities [I] Flags affecting the security behaviour.
2555  *
2556  * RETURNS
2557  *  Success: S_OK.
2558  *  Failure: HRESULT code.
2559  *
2560  * SEE ALSO
2561  *  CoQueryProxyBlanket, CoCopyProxy.
2562  */
2563 HRESULT WINAPI CoSetProxyBlanket(IUnknown *pProxy, DWORD AuthnSvc,
2564     DWORD AuthzSvc, OLECHAR *pServerPrincName, DWORD AuthnLevel,
2565     DWORD ImpLevel, void *pAuthInfo, DWORD Capabilities)
2566 {
2567     IClientSecurity *pCliSec;
2568     HRESULT hr;
2569
2570     TRACE("%p\n", pProxy);
2571
2572     hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
2573     if (SUCCEEDED(hr))
2574     {
2575         hr = IClientSecurity_SetBlanket(pCliSec, pProxy, AuthnSvc,
2576                                         AuthzSvc, pServerPrincName,
2577                                         AuthnLevel, ImpLevel, pAuthInfo,
2578                                         Capabilities);
2579         IClientSecurity_Release(pCliSec);
2580     }
2581
2582     if (FAILED(hr)) ERR("-- failed with 0x%08lx\n", hr);
2583     return hr;
2584 }
2585
2586 /***********************************************************************
2587  *           CoCopyProxy [OLE32.@]
2588  *
2589  * Copies a proxy.
2590  *
2591  * PARAMS
2592  *  pProxy [I] Pointer to the proxy object.
2593  *  ppCopy [O] Copy of the proxy.
2594  *
2595  * RETURNS
2596  *  Success: S_OK.
2597  *  Failure: HRESULT code.
2598  *
2599  * SEE ALSO
2600  *  CoQueryProxyBlanket, CoSetProxyBlanket.
2601  */
2602 HRESULT WINAPI CoCopyProxy(IUnknown *pProxy, IUnknown **ppCopy)
2603 {
2604     IClientSecurity *pCliSec;
2605     HRESULT hr;
2606
2607     TRACE("%p\n", pProxy);
2608
2609     hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
2610     if (SUCCEEDED(hr))
2611     {
2612         hr = IClientSecurity_CopyProxy(pCliSec, pProxy, ppCopy);
2613         IClientSecurity_Release(pCliSec);
2614     }
2615
2616     if (FAILED(hr)) ERR("-- failed with 0x%08lx\n", hr);
2617     return hr;
2618 }
2619
2620
2621 /***********************************************************************
2622  *           CoWaitForMultipleHandles [OLE32.@]
2623  *
2624  * Waits for one or more handles to become signaled.
2625  *
2626  * PARAMS
2627  *  dwFlags   [I] Flags. See notes.
2628  *  dwTimeout [I] Timeout in milliseconds.
2629  *  cHandles  [I] Number of handles pointed to by pHandles.
2630  *  pHandles  [I] Handles to wait for.
2631  *  lpdwindex [O] Index of handle that was signaled.
2632  *
2633  * RETURNS
2634  *  Success: S_OK.
2635  *  Failure: RPC_S_CALLPENDING on timeout.
2636  *
2637  * NOTES
2638  *
2639  * The dwFlags parameter can be zero or more of the following:
2640  *| COWAIT_WAITALL - Wait for all of the handles to become signaled.
2641  *| COWAIT_ALERTABLE - Allows a queued APC to run during the wait.
2642  *
2643  * SEE ALSO
2644  *  MsgWaitForMultipleObjects, WaitForMultipleObjects.
2645  */
2646 HRESULT WINAPI CoWaitForMultipleHandles(DWORD dwFlags, DWORD dwTimeout,
2647     ULONG cHandles, const HANDLE* pHandles, LPDWORD lpdwindex)
2648 {
2649     HRESULT hr = S_OK;
2650     DWORD wait_flags = (dwFlags & COWAIT_WAITALL) ? MWMO_WAITALL : 0 |
2651                        (dwFlags & COWAIT_ALERTABLE ) ? MWMO_ALERTABLE : 0;
2652     DWORD start_time = GetTickCount();
2653
2654     TRACE("(0x%08lx, 0x%08lx, %ld, %p, %p)\n", dwFlags, dwTimeout, cHandles,
2655         pHandles, lpdwindex);
2656
2657     while (TRUE)
2658     {
2659         DWORD now = GetTickCount();
2660         DWORD res;
2661         
2662         if ((dwTimeout != INFINITE) && (start_time + dwTimeout >= now))
2663         {
2664             hr = RPC_S_CALLPENDING;
2665             break;
2666         }
2667
2668         TRACE("waiting for rpc completion or window message\n");
2669
2670         res = MsgWaitForMultipleObjectsEx(cHandles, pHandles,
2671             (dwTimeout == INFINITE) ? INFINITE : start_time + dwTimeout - now,
2672             QS_ALLINPUT, wait_flags);
2673
2674         if (res == WAIT_OBJECT_0 + cHandles)  /* messages available */
2675         {
2676             MSG msg;
2677             while (PeekMessageW(&msg, NULL, 0, 0, PM_REMOVE))
2678             {
2679                 /* FIXME: filter the messages here */
2680                 TRACE("received message whilst waiting for RPC: 0x%04x\n", msg.message);
2681                 TranslateMessage(&msg);
2682                 DispatchMessageW(&msg);
2683             }
2684         }
2685         else if ((res >= WAIT_OBJECT_0) && (res < WAIT_OBJECT_0 + cHandles))
2686         {
2687             /* handle signaled, store index */
2688             *lpdwindex = (res - WAIT_OBJECT_0);
2689             break;
2690         }
2691         else if (res == WAIT_TIMEOUT)
2692         {
2693             hr = RPC_S_CALLPENDING;
2694             break;
2695         }
2696         else
2697         {
2698             ERR("Unexpected wait termination: %ld, %ld\n", res, GetLastError());
2699             hr = E_UNEXPECTED;
2700             break;
2701         }
2702     }
2703     TRACE("-- 0x%08lx\n", hr);
2704     return hr;
2705 }
2706
2707 /***********************************************************************
2708  *              DllMain (OLE32.@)
2709  */
2710 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID fImpLoad)
2711 {
2712     TRACE("%p 0x%lx %p\n", hinstDLL, fdwReason, fImpLoad);
2713
2714     switch(fdwReason) {
2715     case DLL_PROCESS_ATTACH:
2716         OLE32_hInstance = hinstDLL;
2717         COMPOBJ_InitProcess();
2718         if (TRACE_ON(ole)) CoRegisterMallocSpy((LPVOID)-1);
2719         break;
2720
2721     case DLL_PROCESS_DETACH:
2722         if (TRACE_ON(ole)) CoRevokeMallocSpy();
2723         COMPOBJ_UninitProcess();
2724         OLE32_hInstance = 0;
2725         break;
2726
2727     case DLL_THREAD_DETACH:
2728         COM_TlsDestroy();
2729         break;
2730     }
2731     return TRUE;
2732 }
2733
2734 /* NOTE: DllRegisterServer and DllUnregisterServer are in regsvr.c */