Enhance uxtheme to store the themed system metrics in the registry and
[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 [COMPOBJ.7]
1566  *           CoGetClassObject [OLE32.@]
1567  *
1568  * FIXME.  If request allows of several options and there is a failure
1569  *         with one (other than not being registered) do we try the
1570  *         others or return failure?  (E.g. inprocess is registered but
1571  *         the DLL is not found but the server version works)
1572  */
1573 HRESULT WINAPI CoGetClassObject(
1574     REFCLSID rclsid, DWORD dwClsContext, COSERVERINFO *pServerInfo,
1575     REFIID iid, LPVOID *ppv)
1576 {
1577     LPUNKNOWN   regClassObject;
1578     HRESULT     hres = E_UNEXPECTED;
1579
1580     TRACE("\n\tCLSID:\t%s,\n\tIID:\t%s\n", debugstr_guid(rclsid), debugstr_guid(iid));
1581
1582     if (pServerInfo) {
1583         FIXME("\tpServerInfo: name=%s\n",debugstr_w(pServerInfo->pwszName));
1584         FIXME("\t\tpAuthInfo=%p\n",pServerInfo->pAuthInfo);
1585     }
1586
1587     /*
1588      * First, try and see if we can't match the class ID with one of the
1589      * registered classes.
1590      */
1591     if (S_OK == COM_GetRegisteredClassObject(rclsid, dwClsContext, &regClassObject))
1592     {
1593       /* Get the required interface from the retrieved pointer. */
1594       hres = IUnknown_QueryInterface(regClassObject, iid, ppv);
1595
1596       /*
1597        * Since QI got another reference on the pointer, we want to release the
1598        * one we already have. If QI was unsuccessful, this will release the object. This
1599        * is good since we are not returning it in the "out" parameter.
1600        */
1601       IUnknown_Release(regClassObject);
1602
1603       return hres;
1604     }
1605
1606     /* first try: in-process */
1607     if ((CLSCTX_INPROC_SERVER | CLSCTX_INPROC_HANDLER) & dwClsContext)
1608     {
1609         static const WCHAR wszInprocServer32[] = {'I','n','p','r','o','c','S','e','r','v','e','r','3','2',0};
1610         HINSTANCE hLibrary;
1611         typedef HRESULT (CALLBACK *DllGetClassObjectFunc)(REFCLSID clsid, REFIID iid, LPVOID *ppv);
1612         DllGetClassObjectFunc DllGetClassObject;
1613         WCHAR dllpath[MAX_PATH+1];
1614         HKEY hkey;
1615
1616         if (ERROR_SUCCESS != COM_OpenKeyForCLSID(rclsid, KEY_READ, &hkey))
1617         {
1618             ERR("class %s not registered\n", debugstr_guid(rclsid));
1619             hres = REGDB_E_CLASSNOTREG;
1620         }
1621
1622         if (COM_RegReadPath(hkey, wszInprocServer32, NULL, dllpath, ARRAYSIZE(dllpath)) != ERROR_SUCCESS)
1623         {
1624             /* failure: CLSID is not found in registry */
1625             WARN("class %s not registered inproc\n", debugstr_guid(rclsid));
1626             hres = REGDB_E_CLASSNOTREG;
1627         }
1628         else
1629         {
1630             if ((hLibrary = LoadLibraryExW(dllpath, 0, LOAD_WITH_ALTERED_SEARCH_PATH)) == 0)
1631             {
1632                 /* failure: DLL could not be loaded */
1633                 ERR("couldn't load InprocServer32 dll %s\n", debugstr_w(dllpath));
1634                 hres = E_ACCESSDENIED; /* FIXME: or should this be CO_E_DLLNOTFOUND? */
1635             }
1636             else if (!(DllGetClassObject = (DllGetClassObjectFunc)GetProcAddress(hLibrary, "DllGetClassObject")))
1637             {
1638                 /* failure: the dll did not export DllGetClassObject */
1639                 ERR("couldn't find function DllGetClassObject in %s\n", debugstr_w(dllpath));
1640                 FreeLibrary( hLibrary );
1641                 hres = CO_E_DLLNOTFOUND;
1642             }
1643             else
1644             {
1645                 /* OK: get the ClassObject */
1646                 COMPOBJ_DLLList_Add( hLibrary );
1647                 return DllGetClassObject(rclsid, iid, ppv);
1648             }
1649         }
1650     }
1651
1652     /* Next try out of process */
1653     if (CLSCTX_LOCAL_SERVER & dwClsContext)
1654     {
1655         return RPC_GetLocalClassObject(rclsid,iid,ppv);
1656     }
1657
1658     /* Finally try remote: this requires networked DCOM (a lot of work) */
1659     if (CLSCTX_REMOTE_SERVER & dwClsContext)
1660     {
1661         FIXME ("CLSCTX_REMOTE_SERVER not supported\n");
1662         hres = E_NOINTERFACE;
1663     }
1664
1665     return hres;
1666 }
1667 /***********************************************************************
1668  *        CoResumeClassObjects (OLE32.@)
1669  *
1670  * Resumes all class objects registered with REGCLS_SUSPENDED.
1671  *
1672  * RETURNS
1673  *  Success: S_OK.
1674  *  Failure: HRESULT code.
1675  */
1676 HRESULT WINAPI CoResumeClassObjects(void)
1677 {
1678        FIXME("stub\n");
1679         return S_OK;
1680 }
1681
1682 /***********************************************************************
1683  *        GetClassFile (OLE32.@)
1684  *
1685  * This function supplies the CLSID associated with the given filename.
1686  */
1687 HRESULT WINAPI GetClassFile(LPCOLESTR filePathName,CLSID *pclsid)
1688 {
1689     IStorage *pstg=0;
1690     HRESULT res;
1691     int nbElm, length, i;
1692     LONG sizeProgId;
1693     LPOLESTR *pathDec=0,absFile=0,progId=0;
1694     LPWSTR extension;
1695     static const WCHAR bkslashW[] = {'\\',0};
1696     static const WCHAR dotW[] = {'.',0};
1697
1698     TRACE("%s, %p\n", debugstr_w(filePathName), pclsid);
1699
1700     /* if the file contain a storage object the return the CLSID written by IStorage_SetClass method*/
1701     if((StgIsStorageFile(filePathName))==S_OK){
1702
1703         res=StgOpenStorage(filePathName,NULL,STGM_READ | STGM_SHARE_DENY_WRITE,NULL,0,&pstg);
1704
1705         if (SUCCEEDED(res))
1706             res=ReadClassStg(pstg,pclsid);
1707
1708         IStorage_Release(pstg);
1709
1710         return res;
1711     }
1712     /* if the file is not a storage object then attemps to match various bits in the file against a
1713        pattern in the registry. this case is not frequently used ! so I present only the psodocode for
1714        this case
1715
1716      for(i=0;i<nFileTypes;i++)
1717
1718         for(i=0;j<nPatternsForType;j++){
1719
1720             PATTERN pat;
1721             HANDLE  hFile;
1722
1723             pat=ReadPatternFromRegistry(i,j);
1724             hFile=CreateFileW(filePathName,,,,,,hFile);
1725             SetFilePosition(hFile,pat.offset);
1726             ReadFile(hFile,buf,pat.size,&r,NULL);
1727             if (memcmp(buf&pat.mask,pat.pattern.pat.size)==0){
1728
1729                 *pclsid=ReadCLSIDFromRegistry(i);
1730                 return S_OK;
1731             }
1732         }
1733      */
1734
1735     /* if the above strategies fail then search for the extension key in the registry */
1736
1737     /* get the last element (absolute file) in the path name */
1738     nbElm=FileMonikerImpl_DecomposePath(filePathName,&pathDec);
1739     absFile=pathDec[nbElm-1];
1740
1741     /* failed if the path represente a directory and not an absolute file name*/
1742     if (!lstrcmpW(absFile, bkslashW))
1743         return MK_E_INVALIDEXTENSION;
1744
1745     /* get the extension of the file */
1746     extension = NULL;
1747     length=lstrlenW(absFile);
1748     for(i = length-1; (i >= 0) && *(extension = &absFile[i]) != '.'; i--)
1749         /* nothing */;
1750
1751     if (!extension || !lstrcmpW(extension, dotW))
1752         return MK_E_INVALIDEXTENSION;
1753
1754     res=RegQueryValueW(HKEY_CLASSES_ROOT, extension, NULL, &sizeProgId);
1755
1756     /* get the progId associated to the extension */
1757     progId = CoTaskMemAlloc(sizeProgId);
1758     res = RegQueryValueW(HKEY_CLASSES_ROOT, extension, progId, &sizeProgId);
1759
1760     if (res==ERROR_SUCCESS)
1761         /* return the clsid associated to the progId */
1762         res= CLSIDFromProgID(progId,pclsid);
1763
1764     for(i=0; pathDec[i]!=NULL;i++)
1765         CoTaskMemFree(pathDec[i]);
1766     CoTaskMemFree(pathDec);
1767
1768     CoTaskMemFree(progId);
1769
1770     if (res==ERROR_SUCCESS)
1771         return res;
1772
1773     return MK_E_INVALIDEXTENSION;
1774 }
1775 /***********************************************************************
1776  *           CoCreateInstance [COMPOBJ.13]
1777  *           CoCreateInstance [OLE32.@]
1778  */
1779 HRESULT WINAPI CoCreateInstance(
1780         REFCLSID rclsid,
1781         LPUNKNOWN pUnkOuter,
1782         DWORD dwClsContext,
1783         REFIID iid,
1784         LPVOID *ppv)
1785 {
1786   HRESULT hres;
1787   LPCLASSFACTORY lpclf = 0;
1788
1789   if (!COM_CurrentApt()) return CO_E_NOTINITIALIZED;
1790
1791   /*
1792    * Sanity check
1793    */
1794   if (ppv==0)
1795     return E_POINTER;
1796
1797   /*
1798    * Initialize the "out" parameter
1799    */
1800   *ppv = 0;
1801
1802   /*
1803    * The Standard Global Interface Table (GIT) object is a process-wide singleton.
1804    * Rather than create a class factory, we can just check for it here
1805    */
1806   if (IsEqualIID(rclsid, &CLSID_StdGlobalInterfaceTable)) {
1807     if (StdGlobalInterfaceTableInstance == NULL)
1808       StdGlobalInterfaceTableInstance = StdGlobalInterfaceTable_Construct();
1809     hres = IGlobalInterfaceTable_QueryInterface( (IGlobalInterfaceTable*) StdGlobalInterfaceTableInstance, iid, ppv);
1810     if (hres) return hres;
1811
1812     TRACE("Retrieved GIT (%p)\n", *ppv);
1813     return S_OK;
1814   }
1815
1816   /*
1817    * Get a class factory to construct the object we want.
1818    */
1819   hres = CoGetClassObject(rclsid,
1820                           dwClsContext,
1821                           NULL,
1822                           &IID_IClassFactory,
1823                           (LPVOID)&lpclf);
1824
1825   if (FAILED(hres)) {
1826     FIXME("no classfactory created for CLSID %s, hres is 0x%08lx\n",
1827           debugstr_guid(rclsid),hres);
1828     return hres;
1829   }
1830
1831   /*
1832    * Create the object and don't forget to release the factory
1833    */
1834         hres = IClassFactory_CreateInstance(lpclf, pUnkOuter, iid, ppv);
1835         IClassFactory_Release(lpclf);
1836         if(FAILED(hres))
1837           FIXME("no instance created for interface %s of class %s, hres is 0x%08lx\n",
1838                 debugstr_guid(iid), debugstr_guid(rclsid),hres);
1839
1840         return hres;
1841 }
1842
1843 /***********************************************************************
1844  *           CoCreateInstanceEx [OLE32.@]
1845  */
1846 HRESULT WINAPI CoCreateInstanceEx(
1847   REFCLSID      rclsid,
1848   LPUNKNOWN     pUnkOuter,
1849   DWORD         dwClsContext,
1850   COSERVERINFO* pServerInfo,
1851   ULONG         cmq,
1852   MULTI_QI*     pResults)
1853 {
1854   IUnknown* pUnk = NULL;
1855   HRESULT   hr;
1856   ULONG     index;
1857   ULONG     successCount = 0;
1858
1859   /*
1860    * Sanity check
1861    */
1862   if ( (cmq==0) || (pResults==NULL))
1863     return E_INVALIDARG;
1864
1865   if (pServerInfo!=NULL)
1866     FIXME("() non-NULL pServerInfo not supported!\n");
1867
1868   /*
1869    * Initialize all the "out" parameters.
1870    */
1871   for (index = 0; index < cmq; index++)
1872   {
1873     pResults[index].pItf = NULL;
1874     pResults[index].hr   = E_NOINTERFACE;
1875   }
1876
1877   /*
1878    * Get the object and get its IUnknown pointer.
1879    */
1880   hr = CoCreateInstance(rclsid,
1881                         pUnkOuter,
1882                         dwClsContext,
1883                         &IID_IUnknown,
1884                         (VOID**)&pUnk);
1885
1886   if (hr)
1887     return hr;
1888
1889   /*
1890    * Then, query for all the interfaces requested.
1891    */
1892   for (index = 0; index < cmq; index++)
1893   {
1894     pResults[index].hr = IUnknown_QueryInterface(pUnk,
1895                                                  pResults[index].pIID,
1896                                                  (VOID**)&(pResults[index].pItf));
1897
1898     if (pResults[index].hr == S_OK)
1899       successCount++;
1900   }
1901
1902   /*
1903    * Release our temporary unknown pointer.
1904    */
1905   IUnknown_Release(pUnk);
1906
1907   if (successCount == 0)
1908     return E_NOINTERFACE;
1909
1910   if (successCount!=cmq)
1911     return CO_S_NOTALLINTERFACES;
1912
1913   return S_OK;
1914 }
1915
1916 /***********************************************************************
1917  *           CoLoadLibrary (OLE32.@)
1918  *
1919  * Loads a library.
1920  *
1921  * PARAMS
1922  *  lpszLibName [I] Path to library.
1923  *  bAutoFree   [I] Whether the library should automatically be freed.
1924  *
1925  * RETURNS
1926  *  Success: Handle to loaded library.
1927  *  Failure: NULL.
1928  *
1929  * SEE ALSO
1930  *  CoFreeLibrary, CoFreeAllLibraries, CoFreeUnusedLibraries
1931  */
1932 HINSTANCE WINAPI CoLoadLibrary(LPOLESTR lpszLibName, BOOL bAutoFree)
1933 {
1934     TRACE("(%s, %d)\n", debugstr_w(lpszLibName), bAutoFree);
1935
1936     return LoadLibraryExW(lpszLibName, 0, LOAD_WITH_ALTERED_SEARCH_PATH);
1937 }
1938
1939 /***********************************************************************
1940  *           CoFreeLibrary [OLE32.@]
1941  *
1942  * Unloads a library from memory.
1943  *
1944  * PARAMS
1945  *  hLibrary [I] Handle to library to unload.
1946  *
1947  * RETURNS
1948  *  Nothing
1949  *
1950  * SEE ALSO
1951  *  CoLoadLibrary, CoFreeAllLibraries, CoFreeUnusedLibraries
1952  */
1953 void WINAPI CoFreeLibrary(HINSTANCE hLibrary)
1954 {
1955     FreeLibrary(hLibrary);
1956 }
1957
1958
1959 /***********************************************************************
1960  *           CoFreeAllLibraries [OLE32.@]
1961  *
1962  * Function for backwards compatibility only. Does nothing.
1963  *
1964  * RETURNS
1965  *  Nothing.
1966  *
1967  * SEE ALSO
1968  *  CoLoadLibrary, CoFreeLibrary, CoFreeUnusedLibraries
1969  */
1970 void WINAPI CoFreeAllLibraries(void)
1971 {
1972     /* NOP */
1973 }
1974
1975
1976 /***********************************************************************
1977  *           CoFreeUnusedLibraries [OLE32.@]
1978  *           CoFreeUnusedLibraries [COMPOBJ.17]
1979  *
1980  * Frees any unused libraries. Unused are identified as those that return
1981  * S_OK from their DllCanUnloadNow function.
1982  *
1983  * RETURNS
1984  *  Nothing.
1985  *
1986  * SEE ALSO
1987  *  CoLoadLibrary, CoFreeAllLibraries, CoFreeLibrary
1988  */
1989 void WINAPI CoFreeUnusedLibraries(void)
1990 {
1991     /* FIXME: Calls to CoFreeUnusedLibraries from any thread always route
1992      * through the main apartment's thread to call DllCanUnloadNow */
1993     COMPOBJ_DllList_FreeUnused(0);
1994 }
1995
1996 /***********************************************************************
1997  *           CoFileTimeNow [OLE32.@]
1998  *           CoFileTimeNow [COMPOBJ.82]
1999  *
2000  * Retrieves the current time in FILETIME format.
2001  *
2002  * PARAMS
2003  *  lpFileTime [O] The current time.
2004  *
2005  * RETURNS
2006  *      S_OK.
2007  */
2008 HRESULT WINAPI CoFileTimeNow( FILETIME *lpFileTime )
2009 {
2010     GetSystemTimeAsFileTime( lpFileTime );
2011     return S_OK;
2012 }
2013
2014 static void COM_RevokeAllClasses()
2015 {
2016   EnterCriticalSection( &csRegisteredClassList );
2017
2018   while (firstRegisteredClass!=0)
2019   {
2020     CoRevokeClassObject(firstRegisteredClass->dwCookie);
2021   }
2022
2023   LeaveCriticalSection( &csRegisteredClassList );
2024 }
2025
2026 /******************************************************************************
2027  *              CoLockObjectExternal    [OLE32.@]
2028  *
2029  * Increments or decrements the external reference count of a stub object.
2030  *
2031  * PARAMS
2032  *  pUnk                [I] Stub object.
2033  *  fLock               [I] If TRUE then increments the external ref-count,
2034  *                          otherwise decrements.
2035  *  fLastUnlockReleases [I] If TRUE then the last unlock has the effect of
2036  *                          calling CoDisconnectObject.
2037  *
2038  * RETURNS
2039  *  Success: S_OK.
2040  *  Failure: HRESULT code.
2041  */
2042 HRESULT WINAPI CoLockObjectExternal(
2043     LPUNKNOWN pUnk,
2044     BOOL fLock,
2045     BOOL fLastUnlockReleases)
2046 {
2047     struct stub_manager *stubmgr;
2048     struct apartment *apt;
2049
2050     TRACE("pUnk=%p, fLock=%s, fLastUnlockReleases=%s\n",
2051           pUnk, fLock ? "TRUE" : "FALSE", fLastUnlockReleases ? "TRUE" : "FALSE");
2052
2053     apt = COM_CurrentApt();
2054     if (!apt) return CO_E_NOTINITIALIZED;
2055
2056     stubmgr = get_stub_manager_from_object(apt, pUnk);
2057     
2058     if (stubmgr)
2059     {
2060         if (fLock)
2061             stub_manager_ext_addref(stubmgr, 1);
2062         else
2063             stub_manager_ext_release(stubmgr, 1);
2064         
2065         stub_manager_int_release(stubmgr);
2066
2067         return S_OK;
2068     }
2069     else
2070     {
2071         WARN("stub object not found %p\n", pUnk);
2072         /* Note: native is pretty broken here because it just silently
2073          * fails, without returning an appropriate error code, making apps
2074          * think that the object was disconnected, when it actually wasn't */
2075         return S_OK;
2076     }
2077 }
2078
2079 /***********************************************************************
2080  *           CoInitializeWOW (OLE32.@)
2081  *
2082  * WOW equivalent of CoInitialize?
2083  *
2084  * PARAMS
2085  *  x [I] Unknown.
2086  *  y [I] Unknown.
2087  *
2088  * RETURNS
2089  *  Unknown.
2090  */
2091 HRESULT WINAPI CoInitializeWOW(DWORD x,DWORD y)
2092 {
2093     FIXME("(0x%08lx,0x%08lx),stub!\n",x,y);
2094     return 0;
2095 }
2096
2097 /***********************************************************************
2098  *           CoGetState [OLE32.@]
2099  *
2100  * Retrieves the thread state object previously stored by CoSetState().
2101  *
2102  * PARAMS
2103  *  ppv [I] Address where pointer to object will be stored.
2104  *
2105  * RETURNS
2106  *  Success: S_OK.
2107  *  Failure: E_OUTOFMEMORY.
2108  *
2109  * NOTES
2110  *  Crashes on all invalid ppv addresses, including NULL.
2111  *  If the function returns a non-NULL object then the caller must release its
2112  *  reference on the object when the object is no longer required.
2113  *
2114  * SEE ALSO
2115  *  CoSetState().
2116  */
2117 HRESULT WINAPI CoGetState(IUnknown ** ppv)
2118 {
2119     struct oletls *info = COM_CurrentInfo();
2120     if (!info) return E_OUTOFMEMORY;
2121
2122     *ppv = NULL;
2123
2124     if (info->state)
2125     {
2126         IUnknown_AddRef(info->state);
2127         *ppv = info->state;
2128         TRACE("apt->state=%p\n", info->state);
2129     }
2130
2131     return S_OK;
2132 }
2133
2134 /***********************************************************************
2135  *           CoSetState [OLE32.@]
2136  *
2137  * Sets the thread state object.
2138  *
2139  * PARAMS
2140  *  pv [I] Pointer to state object to be stored.
2141  *
2142  * NOTES
2143  *  The system keeps a reference on the object while the object stored.
2144  *
2145  * RETURNS
2146  *  Success: S_OK.
2147  *  Failure: E_OUTOFMEMORY.
2148  */
2149 HRESULT WINAPI CoSetState(IUnknown * pv)
2150 {
2151     struct oletls *info = COM_CurrentInfo();
2152     if (!info) return E_OUTOFMEMORY;
2153
2154     if (pv) IUnknown_AddRef(pv);
2155
2156     if (info->state)
2157     {
2158         TRACE("-- release %p now\n", info->state);
2159         IUnknown_Release(info->state);
2160     }
2161
2162     info->state = pv;
2163
2164     return S_OK;
2165 }
2166
2167
2168 /******************************************************************************
2169  *              OleGetAutoConvert        [OLE32.@]
2170  */
2171 HRESULT WINAPI OleGetAutoConvert(REFCLSID clsidOld, LPCLSID pClsidNew)
2172 {
2173     static const WCHAR wszAutoConvertTo[] = {'A','u','t','o','C','o','n','v','e','r','t','T','o',0};
2174     HKEY hkey = NULL;
2175     WCHAR buf[CHARS_IN_GUID];
2176     DWORD len;
2177     HRESULT res = S_OK;
2178
2179     if (ERROR_SUCCESS != COM_OpenKeyForCLSID(clsidOld, KEY_READ, &hkey))
2180     {
2181         res = REGDB_E_CLASSNOTREG;
2182         goto done;
2183     }
2184
2185     len = sizeof(buf);
2186     /* we can just query for the default value of AutoConvertTo key like that,
2187        without opening the AutoConvertTo key and querying for NULL (default) */
2188     if (RegQueryValueW(hkey, wszAutoConvertTo, buf, &len))
2189     {
2190         res = REGDB_E_KEYMISSING;
2191         goto done;
2192     }
2193     res = CLSIDFromString(buf, pClsidNew);
2194 done:
2195     if (hkey) RegCloseKey(hkey);
2196     return res;
2197 }
2198
2199 /******************************************************************************
2200  *              CoTreatAsClass        [OLE32.@]
2201  *
2202  * Sets the TreatAs value of a class.
2203  *
2204  * PARAMS
2205  *  clsidOld [I] Class to set TreatAs value on.
2206  *  clsidNew [I] The class the clsidOld should be treated as.
2207  *
2208  * RETURNS
2209  *  Success: S_OK.
2210  *  Failure: HRESULT code.
2211  *
2212  * SEE ALSO
2213  *  CoGetTreatAsClass
2214  */
2215 HRESULT WINAPI CoTreatAsClass(REFCLSID clsidOld, REFCLSID clsidNew)
2216 {
2217     static const WCHAR wszAutoTreatAs[] = {'A','u','t','o','T','r','e','a','t','A','s',0};
2218     static const WCHAR wszTreatAs[] = {'T','r','e','a','t','A','s',0};
2219     HKEY hkey = NULL;
2220     WCHAR szClsidNew[CHARS_IN_GUID];
2221     HRESULT res = S_OK;
2222     WCHAR auto_treat_as[CHARS_IN_GUID];
2223     LONG auto_treat_as_size = sizeof(auto_treat_as);
2224     CLSID id;
2225
2226     if (ERROR_SUCCESS != COM_OpenKeyForCLSID(clsidOld, KEY_READ | KEY_WRITE, &hkey))
2227     {
2228         res = REGDB_E_CLASSNOTREG;
2229         goto done;
2230     }
2231     if (!memcmp( clsidOld, clsidNew, sizeof(*clsidOld) ))
2232     {
2233        if (!RegQueryValueW(hkey, wszAutoTreatAs, auto_treat_as, &auto_treat_as_size) &&
2234            !CLSIDFromString(auto_treat_as, &id))
2235        {
2236            if (RegSetValueW(hkey, wszTreatAs, REG_SZ, auto_treat_as, sizeof(auto_treat_as)))
2237            {
2238                res = REGDB_E_WRITEREGDB;
2239                goto done;
2240            }
2241        }
2242        else
2243        {
2244            RegDeleteKeyW(hkey, wszTreatAs);
2245            goto done;
2246        }
2247     }
2248     else if (!StringFromGUID2(clsidNew, szClsidNew, ARRAYSIZE(szClsidNew)) &&
2249              !RegSetValueW(hkey, wszTreatAs, REG_SZ, szClsidNew, sizeof(szClsidNew)))
2250     {
2251         res = REGDB_E_WRITEREGDB;
2252         goto done;
2253     }
2254
2255 done:
2256     if (hkey) RegCloseKey(hkey);
2257     return res;
2258 }
2259
2260 /******************************************************************************
2261  *              CoGetTreatAsClass        [OLE32.@]
2262  *
2263  * Gets the TreatAs value of a class.
2264  *
2265  * PARAMS
2266  *  clsidOld [I] Class to get the TreatAs value of.
2267  *  clsidNew [I] The class the clsidOld should be treated as.
2268  *
2269  * RETURNS
2270  *  Success: S_OK.
2271  *  Failure: HRESULT code.
2272  *
2273  * SEE ALSO
2274  *  CoSetTreatAsClass
2275  */
2276 HRESULT WINAPI CoGetTreatAsClass(REFCLSID clsidOld, LPCLSID clsidNew)
2277 {
2278     static const WCHAR wszTreatAs[] = {'T','r','e','a','t','A','s',0};
2279     HKEY hkey = NULL;
2280     WCHAR szClsidNew[CHARS_IN_GUID];
2281     HRESULT res = S_OK;
2282     LONG len = sizeof(szClsidNew);
2283
2284     FIXME("(%s,%p)\n", debugstr_guid(clsidOld), clsidNew);
2285     memcpy(clsidNew,clsidOld,sizeof(CLSID)); /* copy over old value */
2286
2287     if (COM_OpenKeyForCLSID(clsidOld, KEY_READ, &hkey))
2288     {
2289         res = REGDB_E_CLASSNOTREG;
2290         goto done;
2291     }
2292     if (RegQueryValueW(hkey, wszTreatAs, szClsidNew, &len))
2293     {
2294         res = S_FALSE;
2295         goto done;
2296     }
2297     res = CLSIDFromString(szClsidNew,clsidNew);
2298     if (FAILED(res))
2299         ERR("Failed CLSIDFromStringA(%s), hres 0x%08lx\n", debugstr_w(szClsidNew), res);
2300 done:
2301     if (hkey) RegCloseKey(hkey);
2302     return res;
2303 }
2304
2305 /******************************************************************************
2306  *              CoGetCurrentProcess     [OLE32.@]
2307  *              CoGetCurrentProcess     [COMPOBJ.34]
2308  *
2309  * Gets the current process ID.
2310  *
2311  * RETURNS
2312  *  The current process ID.
2313  *
2314  * NOTES
2315  *   Is DWORD really the correct return type for this function?
2316  */
2317 DWORD WINAPI CoGetCurrentProcess(void)
2318 {
2319         return GetCurrentProcessId();
2320 }
2321
2322 /******************************************************************************
2323  *              CoRegisterMessageFilter [OLE32.@]
2324  *
2325  * Registers a message filter.
2326  *
2327  * PARAMS
2328  *  lpMessageFilter [I] Pointer to interface.
2329  *  lplpMessageFilter [O] Indirect pointer to prior instance if non-NULL.
2330  *
2331  * RETURNS
2332  *  Success: S_OK.
2333  *  Failure: HRESULT code.
2334  */
2335 HRESULT WINAPI CoRegisterMessageFilter(
2336     LPMESSAGEFILTER lpMessageFilter,
2337     LPMESSAGEFILTER *lplpMessageFilter)
2338 {
2339     FIXME("stub\n");
2340     if (lplpMessageFilter) {
2341         *lplpMessageFilter = NULL;
2342     }
2343     return S_OK;
2344 }
2345
2346 /***********************************************************************
2347  *           CoIsOle1Class [OLE32.@]
2348  *
2349  * Determines whether the specified class an OLE v1 class.
2350  *
2351  * PARAMS
2352  *  clsid [I] Class to test.
2353  *
2354  * RETURNS
2355  *  TRUE if the class is an OLE v1 class, or FALSE otherwise.
2356  */
2357 BOOL WINAPI CoIsOle1Class(REFCLSID clsid)
2358 {
2359   FIXME("%s\n", debugstr_guid(clsid));
2360   return FALSE;
2361 }
2362
2363 /***********************************************************************
2364  *           IsEqualGUID [OLE32.@]
2365  *
2366  * Compares two Unique Identifiers.
2367  *
2368  * PARAMS
2369  *  rguid1 [I] The first GUID to compare.
2370  *  rguid2 [I] The other GUID to compare.
2371  *
2372  * RETURNS
2373  *      TRUE if equal
2374  */
2375 #undef IsEqualGUID
2376 BOOL WINAPI IsEqualGUID(
2377      REFGUID rguid1,
2378      REFGUID rguid2)
2379 {
2380     return !memcmp(rguid1,rguid2,sizeof(GUID));
2381 }
2382
2383 /***********************************************************************
2384  *           CoInitializeSecurity [OLE32.@]
2385  */
2386 HRESULT WINAPI CoInitializeSecurity(PSECURITY_DESCRIPTOR pSecDesc, LONG cAuthSvc,
2387                                     SOLE_AUTHENTICATION_SERVICE* asAuthSvc,
2388                                     void* pReserved1, DWORD dwAuthnLevel,
2389                                     DWORD dwImpLevel, void* pReserved2,
2390                                     DWORD dwCapabilities, void* pReserved3)
2391 {
2392   FIXME("(%p,%ld,%p,%p,%ld,%ld,%p,%ld,%p) - stub!\n", pSecDesc, cAuthSvc,
2393         asAuthSvc, pReserved1, dwAuthnLevel, dwImpLevel, pReserved2,
2394         dwCapabilities, pReserved3);
2395   return S_OK;
2396 }
2397
2398 /***********************************************************************
2399  *           CoSuspendClassObjects [OLE32.@]
2400  *
2401  * Suspends all registered class objects to prevent further requests coming in
2402  * for those objects.
2403  *
2404  * RETURNS
2405  *  Success: S_OK.
2406  *  Failure: HRESULT code.
2407  */
2408 HRESULT WINAPI CoSuspendClassObjects(void)
2409 {
2410     FIXME("\n");
2411     return S_OK;
2412 }
2413
2414 /***********************************************************************
2415  *           CoAddRefServerProcess [OLE32.@]
2416  *
2417  * Helper function for incrementing the reference count of a local-server
2418  * process.
2419  *
2420  * RETURNS
2421  *  New reference count.
2422  */
2423 ULONG WINAPI CoAddRefServerProcess(void)
2424 {
2425     FIXME("\n");
2426     return 2;
2427 }
2428
2429 /***********************************************************************
2430  *           CoReleaseServerProcess [OLE32.@]
2431  *
2432  * Helper function for decrementing the reference count of a local-server
2433  * process.
2434  *
2435  * RETURNS
2436  *  New reference count.
2437  */
2438 ULONG WINAPI CoReleaseServerProcess(void)
2439 {
2440     FIXME("\n");
2441     return 1;
2442 }
2443
2444 /***********************************************************************
2445  *           CoIsHandlerConnected [OLE32.@]
2446  *
2447  * Determines whether a proxy is connected to a remote stub.
2448  *
2449  * PARAMS
2450  *  pUnk [I] Pointer to object that may or may not be connected.
2451  *
2452  * RETURNS
2453  *  TRUE if pUnk is not a proxy or if pUnk is connected to a remote stub, or
2454  *  FALSE otherwise.
2455  */
2456 BOOL WINAPI CoIsHandlerConnected(IUnknown *pUnk)
2457 {
2458     FIXME("%p\n", pUnk);
2459
2460     return TRUE;
2461 }
2462  
2463 /***********************************************************************
2464  *           CoQueryProxyBlanket [OLE32.@]
2465  *
2466  * Retrieves the security settings being used by a proxy.
2467  *
2468  * PARAMS
2469  *  pProxy        [I] Pointer to the proxy object.
2470  *  pAuthnSvc     [O] The type of authentication service.
2471  *  pAuthzSvc     [O] The type of authorization service.
2472  *  ppServerPrincName [O] Optional. The server prinicple name.
2473  *  pAuthnLevel   [O] The authentication level.
2474  *  pImpLevel     [O] The impersonation level.
2475  *  ppAuthInfo    [O] Information specific to the authorization/authentication service.
2476  *  pCapabilities [O] Flags affecting the security behaviour.
2477  *
2478  * RETURNS
2479  *  Success: S_OK.
2480  *  Failure: HRESULT code.
2481  *
2482  * SEE ALSO
2483  *  CoCopyProxy, CoSetProxyBlanket.
2484  */
2485 HRESULT WINAPI CoQueryProxyBlanket(IUnknown *pProxy, DWORD *pAuthnSvc,
2486     DWORD *pAuthzSvc, OLECHAR **ppServerPrincName, DWORD *pAuthnLevel,
2487     DWORD *pImpLevel, void **ppAuthInfo, DWORD *pCapabilities)
2488 {
2489     IClientSecurity *pCliSec;
2490     HRESULT hr;
2491
2492     TRACE("%p\n", pProxy);
2493
2494     hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
2495     if (SUCCEEDED(hr))
2496     {
2497         hr = IClientSecurity_QueryBlanket(pCliSec, pProxy, pAuthnSvc,
2498                                           pAuthzSvc, ppServerPrincName,
2499                                           pAuthnLevel, pImpLevel, ppAuthInfo,
2500                                           pCapabilities);
2501         IClientSecurity_Release(pCliSec);
2502     }
2503
2504     if (FAILED(hr)) ERR("-- failed with 0x%08lx\n", hr);
2505     return hr;
2506 }
2507
2508 /***********************************************************************
2509  *           CoSetProxyBlanket [OLE32.@]
2510  *
2511  * Sets the security settings for a proxy.
2512  *
2513  * PARAMS
2514  *  pProxy       [I] Pointer to the proxy object.
2515  *  AuthnSvc     [I] The type of authentication service.
2516  *  AuthzSvc     [I] The type of authorization service.
2517  *  pServerPrincName [I] The server prinicple name.
2518  *  AuthnLevel   [I] The authentication level.
2519  *  ImpLevel     [I] The impersonation level.
2520  *  pAuthInfo    [I] Information specific to the authorization/authentication service.
2521  *  Capabilities [I] Flags affecting the security behaviour.
2522  *
2523  * RETURNS
2524  *  Success: S_OK.
2525  *  Failure: HRESULT code.
2526  *
2527  * SEE ALSO
2528  *  CoQueryProxyBlanket, CoCopyProxy.
2529  */
2530 HRESULT WINAPI CoSetProxyBlanket(IUnknown *pProxy, DWORD AuthnSvc,
2531     DWORD AuthzSvc, OLECHAR *pServerPrincName, DWORD AuthnLevel,
2532     DWORD ImpLevel, void *pAuthInfo, DWORD Capabilities)
2533 {
2534     IClientSecurity *pCliSec;
2535     HRESULT hr;
2536
2537     TRACE("%p\n", pProxy);
2538
2539     hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
2540     if (SUCCEEDED(hr))
2541     {
2542         hr = IClientSecurity_SetBlanket(pCliSec, pProxy, AuthnSvc,
2543                                         AuthzSvc, pServerPrincName,
2544                                         AuthnLevel, ImpLevel, pAuthInfo,
2545                                         Capabilities);
2546         IClientSecurity_Release(pCliSec);
2547     }
2548
2549     if (FAILED(hr)) ERR("-- failed with 0x%08lx\n", hr);
2550     return hr;
2551 }
2552
2553 /***********************************************************************
2554  *           CoCopyProxy [OLE32.@]
2555  *
2556  * Copies a proxy.
2557  *
2558  * PARAMS
2559  *  pProxy [I] Pointer to the proxy object.
2560  *  ppCopy [O] Copy of the proxy.
2561  *
2562  * RETURNS
2563  *  Success: S_OK.
2564  *  Failure: HRESULT code.
2565  *
2566  * SEE ALSO
2567  *  CoQueryProxyBlanket, CoSetProxyBlanket.
2568  */
2569 HRESULT WINAPI CoCopyProxy(IUnknown *pProxy, IUnknown **ppCopy)
2570 {
2571     IClientSecurity *pCliSec;
2572     HRESULT hr;
2573
2574     TRACE("%p\n", pProxy);
2575
2576     hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
2577     if (SUCCEEDED(hr))
2578     {
2579         hr = IClientSecurity_CopyProxy(pCliSec, pProxy, ppCopy);
2580         IClientSecurity_Release(pCliSec);
2581     }
2582
2583     if (FAILED(hr)) ERR("-- failed with 0x%08lx\n", hr);
2584     return hr;
2585 }
2586
2587
2588 /***********************************************************************
2589  *           CoWaitForMultipleHandles [OLE32.@]
2590  *
2591  * Waits for one or more handles to become signaled.
2592  *
2593  * PARAMS
2594  *  dwFlags   [I] Flags. See notes.
2595  *  dwTimeout [I] Timeout in milliseconds.
2596  *  cHandles  [I] Number of handles pointed to by pHandles.
2597  *  pHandles  [I] Handles to wait for.
2598  *  lpdwindex [O] Index of handle that was signaled.
2599  *
2600  * RETURNS
2601  *  Success: S_OK.
2602  *  Failure: RPC_S_CALLPENDING on timeout.
2603  *
2604  * NOTES
2605  *
2606  * The dwFlags parameter can be zero or more of the following:
2607  *| COWAIT_WAITALL - Wait for all of the handles to become signaled.
2608  *| COWAIT_ALERTABLE - Allows a queued APC to run during the wait.
2609  *
2610  * SEE ALSO
2611  *  MsgWaitForMultipleObjects, WaitForMultipleObjects.
2612  */
2613 HRESULT WINAPI CoWaitForMultipleHandles(DWORD dwFlags, DWORD dwTimeout,
2614     ULONG cHandles, const HANDLE* pHandles, LPDWORD lpdwindex)
2615 {
2616     HRESULT hr = S_OK;
2617     DWORD wait_flags = (dwFlags & COWAIT_WAITALL) ? MWMO_WAITALL : 0 |
2618                        (dwFlags & COWAIT_ALERTABLE ) ? MWMO_ALERTABLE : 0;
2619     DWORD start_time = GetTickCount();
2620
2621     TRACE("(0x%08lx, 0x%08lx, %ld, %p, %p)\n", dwFlags, dwTimeout, cHandles,
2622         pHandles, lpdwindex);
2623
2624     while (TRUE)
2625     {
2626         DWORD now = GetTickCount();
2627         DWORD res;
2628         
2629         if ((dwTimeout != INFINITE) && (start_time + dwTimeout >= now))
2630         {
2631             hr = RPC_S_CALLPENDING;
2632             break;
2633         }
2634
2635         TRACE("waiting for rpc completion or window message\n");
2636
2637         res = MsgWaitForMultipleObjectsEx(cHandles, pHandles,
2638             (dwTimeout == INFINITE) ? INFINITE : start_time + dwTimeout - now,
2639             QS_ALLINPUT, wait_flags);
2640
2641         if (res == WAIT_OBJECT_0 + cHandles)  /* messages available */
2642         {
2643             MSG msg;
2644             while (PeekMessageW(&msg, NULL, 0, 0, PM_REMOVE))
2645             {
2646                 /* FIXME: filter the messages here */
2647                 TRACE("received message whilst waiting for RPC: 0x%04x\n", msg.message);
2648                 TranslateMessage(&msg);
2649                 DispatchMessageW(&msg);
2650             }
2651         }
2652         else if ((res >= WAIT_OBJECT_0) && (res < WAIT_OBJECT_0 + cHandles))
2653         {
2654             /* handle signaled, store index */
2655             *lpdwindex = (res - WAIT_OBJECT_0);
2656             break;
2657         }
2658         else if (res == WAIT_TIMEOUT)
2659         {
2660             hr = RPC_S_CALLPENDING;
2661             break;
2662         }
2663         else
2664         {
2665             ERR("Unexpected wait termination: %ld, %ld\n", res, GetLastError());
2666             hr = E_UNEXPECTED;
2667             break;
2668         }
2669     }
2670     TRACE("-- 0x%08lx\n", hr);
2671     return hr;
2672 }
2673
2674 /***********************************************************************
2675  *              DllMain (OLE32.@)
2676  */
2677 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID fImpLoad)
2678 {
2679     TRACE("%p 0x%lx %p\n", hinstDLL, fdwReason, fImpLoad);
2680
2681     switch(fdwReason) {
2682     case DLL_PROCESS_ATTACH:
2683         OLE32_hInstance = hinstDLL;
2684         COMPOBJ_InitProcess();
2685         if (TRACE_ON(ole)) CoRegisterMallocSpy((LPVOID)-1);
2686         break;
2687
2688     case DLL_PROCESS_DETACH:
2689         if (TRACE_ON(ole)) CoRevokeMallocSpy();
2690         COMPOBJ_UninitProcess();
2691         OLE32_hInstance = 0;
2692         break;
2693
2694     case DLL_THREAD_DETACH:
2695         COM_TlsDestroy();
2696         break;
2697     }
2698     return TRUE;
2699 }
2700
2701 /* NOTE: DllRegisterServer and DllUnregisterServer are in regsvr.c */