wined3d: Handle the sampler type shift in the frontend.
[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  *      Copyright 2005-2006 Robert Shearman (for CodeWeavers)
11  *
12  * This library is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU Lesser General Public
14  * License as published by the Free Software Foundation; either
15  * version 2.1 of the License, or (at your option) any later version.
16  *
17  * This library is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20  * Lesser General Public License for more details.
21  *
22  * You should have received a copy of the GNU Lesser General Public
23  * License along with this library; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
25  *
26  * Note
27  * 1. COINIT_MULTITHREADED is 0; it is the lack of COINIT_APARTMENTTHREADED
28  *    Therefore do not test against COINIT_MULTITHREADED
29  *
30  * TODO list:           (items bunched together depend on each other)
31  *
32  *   - Implement the service control manager (in rpcss) to keep track
33  *     of registered class objects: ISCM::ServerRegisterClsid et al
34  *   - Implement the OXID resolver so we don't need magic endpoint names for
35  *     clients and servers to meet up
36  *
37  */
38
39 #include "config.h"
40
41 #include <stdarg.h>
42 #include <stdio.h>
43 #include <string.h>
44 #include <assert.h>
45
46 #define COBJMACROS
47 #define NONAMELESSUNION
48 #define NONAMELESSSTRUCT
49
50 #include "windef.h"
51 #include "winbase.h"
52 #include "winerror.h"
53 #include "winreg.h"
54 #include "winuser.h"
55 #include "objbase.h"
56 #include "ole2.h"
57 #include "ole2ver.h"
58 #include "ctxtcall.h"
59
60 #include "compobj_private.h"
61
62 #include "wine/unicode.h"
63 #include "wine/debug.h"
64
65 WINE_DEFAULT_DEBUG_CHANNEL(ole);
66
67 #define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))
68
69 /****************************************************************************
70  * This section defines variables internal to the COM module.
71  */
72
73 static HRESULT COM_GetRegisteredClassObject(const struct apartment *apt, REFCLSID rclsid,
74                                             DWORD dwClsContext, LPUNKNOWN*  ppUnk);
75 static void COM_RevokeAllClasses(const struct apartment *apt);
76 static HRESULT get_inproc_class_object(APARTMENT *apt, HKEY hkeydll, REFCLSID rclsid, REFIID riid, BOOL hostifnecessary, void **ppv);
77
78 static APARTMENT *MTA; /* protected by csApartment */
79 static APARTMENT *MainApartment; /* the first STA apartment */
80 static struct list apts = LIST_INIT( apts ); /* protected by csApartment */
81
82 static CRITICAL_SECTION csApartment;
83 static CRITICAL_SECTION_DEBUG critsect_debug =
84 {
85     0, 0, &csApartment,
86     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
87       0, 0, { (DWORD_PTR)(__FILE__ ": csApartment") }
88 };
89 static CRITICAL_SECTION csApartment = { &critsect_debug, -1, 0, 0, 0, 0 };
90
91 struct registered_psclsid
92 {
93     struct list entry;
94     IID iid;
95     CLSID clsid;
96 };
97
98 /*
99  * This lock count counts the number of times CoInitialize is called. It is
100  * decreased every time CoUninitialize is called. When it hits 0, the COM
101  * libraries are freed
102  */
103 static LONG s_COMLockCount = 0;
104 /* Reference count used by CoAddRefServerProcess/CoReleaseServerProcess */
105 static LONG s_COMServerProcessReferences = 0;
106
107 /*
108  * This linked list contains the list of registered class objects. These
109  * are mostly used to register the factories for out-of-proc servers of OLE
110  * objects.
111  *
112  * TODO: Make this data structure aware of inter-process communication. This
113  *       means that parts of this will be exported to rpcss.
114  */
115 typedef struct tagRegisteredClass
116 {
117   struct list entry;
118   CLSID     classIdentifier;
119   OXID      apartment_id;
120   LPUNKNOWN classObject;
121   DWORD     runContext;
122   DWORD     connectFlags;
123   DWORD     dwCookie;
124   LPSTREAM  pMarshaledData; /* FIXME: only really need to store OXID and IPID */
125   void     *RpcRegistration;
126 } RegisteredClass;
127
128 static struct list RegisteredClassList = LIST_INIT(RegisteredClassList);
129
130 static CRITICAL_SECTION csRegisteredClassList;
131 static CRITICAL_SECTION_DEBUG class_cs_debug =
132 {
133     0, 0, &csRegisteredClassList,
134     { &class_cs_debug.ProcessLocksList, &class_cs_debug.ProcessLocksList },
135       0, 0, { (DWORD_PTR)(__FILE__ ": csRegisteredClassList") }
136 };
137 static CRITICAL_SECTION csRegisteredClassList = { &class_cs_debug, -1, 0, 0, 0, 0 };
138
139 /*****************************************************************************
140  * This section contains OpenDllList definitions
141  *
142  * The OpenDllList contains only handles of dll loaded by CoGetClassObject or
143  * other functions that do LoadLibrary _without_ giving back a HMODULE.
144  * Without this list these handles would never be freed.
145  *
146  * FIXME: a DLL that says OK when asked for unloading is unloaded in the
147  * next unload-call but not before 600 sec.
148  */
149
150 typedef HRESULT (CALLBACK *DllGetClassObjectFunc)(REFCLSID clsid, REFIID iid, LPVOID *ppv);
151 typedef HRESULT (WINAPI *DllCanUnloadNowFunc)(void);
152
153 typedef struct tagOpenDll
154 {
155   LONG refs;
156   LPWSTR library_name;
157   HANDLE library;
158   DllGetClassObjectFunc DllGetClassObject;
159   DllCanUnloadNowFunc DllCanUnloadNow;
160   struct list entry;
161 } OpenDll;
162
163 static struct list openDllList = LIST_INIT(openDllList);
164
165 static CRITICAL_SECTION csOpenDllList;
166 static CRITICAL_SECTION_DEBUG dll_cs_debug =
167 {
168     0, 0, &csOpenDllList,
169     { &dll_cs_debug.ProcessLocksList, &dll_cs_debug.ProcessLocksList },
170       0, 0, { (DWORD_PTR)(__FILE__ ": csOpenDllList") }
171 };
172 static CRITICAL_SECTION csOpenDllList = { &dll_cs_debug, -1, 0, 0, 0, 0 };
173
174 struct apartment_loaded_dll
175 {
176     struct list entry;
177     OpenDll *dll;
178     DWORD unload_time;
179     BOOL multi_threaded;
180 };
181
182 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',' ',
183                                        '0','x','#','#','#','#','#','#','#','#',' ',0};
184 static LRESULT CALLBACK apartment_wndproc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
185 static HRESULT apartment_getclassobject(struct apartment *apt, LPCWSTR dllpath,
186                                         BOOL apartment_threaded,
187                                         REFCLSID rclsid, REFIID riid, void **ppv);
188 static void apartment_freeunusedlibraries(struct apartment *apt, DWORD delay);
189
190 static HRESULT COMPOBJ_DllList_Add(LPCWSTR library_name, OpenDll **ret);
191 static OpenDll *COMPOBJ_DllList_Get(LPCWSTR library_name);
192 static void COMPOBJ_DllList_ReleaseRef(OpenDll *entry, BOOL free_entry);
193
194 static DWORD COM_RegReadPath(HKEY hkeyroot, const WCHAR *keyname, const WCHAR *valuename, WCHAR * dst, DWORD dstlen);
195
196 static void COMPOBJ_InitProcess( void )
197 {
198     WNDCLASSW wclass;
199
200     /* Dispatching to the correct thread in an apartment is done through
201      * window messages rather than RPC transports. When an interface is
202      * marshalled into another apartment in the same process, a window of the
203      * following class is created. The *caller* of CoMarshalInterface (i.e., the
204      * application) is responsible for pumping the message loop in that thread.
205      * The WM_USER messages which point to the RPCs are then dispatched to
206      * apartment_wndproc by the user's code from the apartment in which the
207      * interface was unmarshalled.
208      */
209     memset(&wclass, 0, sizeof(wclass));
210     wclass.lpfnWndProc = apartment_wndproc;
211     wclass.hInstance = hProxyDll;
212     wclass.lpszClassName = wszAptWinClass;
213     RegisterClassW(&wclass);
214 }
215
216 static void COMPOBJ_UninitProcess( void )
217 {
218     UnregisterClassW(wszAptWinClass, hProxyDll);
219 }
220
221 static void COM_TlsDestroy(void)
222 {
223     struct oletls *info = NtCurrentTeb()->ReservedForOle;
224     if (info)
225     {
226         if (info->apt) apartment_release(info->apt);
227         if (info->errorinfo) IErrorInfo_Release(info->errorinfo);
228         if (info->state) IUnknown_Release(info->state);
229         if (info->spy) IUnknown_Release(info->spy);
230         HeapFree(GetProcessHeap(), 0, info);
231         NtCurrentTeb()->ReservedForOle = NULL;
232     }
233 }
234
235 /******************************************************************************
236  * Manage apartments.
237  */
238
239 /* allocates memory and fills in the necessary fields for a new apartment
240  * object. must be called inside apartment cs */
241 static APARTMENT *apartment_construct(DWORD model)
242 {
243     APARTMENT *apt;
244
245     TRACE("creating new apartment, model=%d\n", model);
246
247     apt = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*apt));
248     apt->tid = GetCurrentThreadId();
249
250     list_init(&apt->proxies);
251     list_init(&apt->stubmgrs);
252     list_init(&apt->psclsids);
253     list_init(&apt->loaded_dlls);
254     apt->ipidc = 0;
255     apt->refs = 1;
256     apt->remunk_exported = FALSE;
257     apt->oidc = 1;
258     InitializeCriticalSection(&apt->cs);
259     DEBUG_SET_CRITSEC_NAME(&apt->cs, "apartment");
260
261     apt->multi_threaded = !(model & COINIT_APARTMENTTHREADED);
262
263     if (apt->multi_threaded)
264     {
265         /* FIXME: should be randomly generated by in an RPC call to rpcss */
266         apt->oxid = ((OXID)GetCurrentProcessId() << 32) | 0xcafe;
267     }
268     else
269     {
270         /* FIXME: should be randomly generated by in an RPC call to rpcss */
271         apt->oxid = ((OXID)GetCurrentProcessId() << 32) | GetCurrentThreadId();
272     }
273
274     TRACE("Created apartment on OXID %s\n", wine_dbgstr_longlong(apt->oxid));
275
276     list_add_head(&apts, &apt->entry);
277
278     return apt;
279 }
280
281 /* gets and existing apartment if one exists or otherwise creates an apartment
282  * structure which stores OLE apartment-local information and stores a pointer
283  * to it in the thread-local storage */
284 static APARTMENT *apartment_get_or_create(DWORD model)
285 {
286     APARTMENT *apt = COM_CurrentApt();
287
288     if (!apt)
289     {
290         if (model & COINIT_APARTMENTTHREADED)
291         {
292             EnterCriticalSection(&csApartment);
293
294             apt = apartment_construct(model);
295             if (!MainApartment)
296             {
297                 MainApartment = apt;
298                 apt->main = TRUE;
299                 TRACE("Created main-threaded apartment with OXID %s\n", wine_dbgstr_longlong(apt->oxid));
300             }
301
302             LeaveCriticalSection(&csApartment);
303
304             if (apt->main)
305                 apartment_createwindowifneeded(apt);
306         }
307         else
308         {
309             EnterCriticalSection(&csApartment);
310
311             /* The multi-threaded apartment (MTA) contains zero or more threads interacting
312              * with free threaded (ie thread safe) COM objects. There is only ever one MTA
313              * in a process */
314             if (MTA)
315             {
316                 TRACE("entering the multithreaded apartment %s\n", wine_dbgstr_longlong(MTA->oxid));
317                 apartment_addref(MTA);
318             }
319             else
320                 MTA = apartment_construct(model);
321
322             apt = MTA;
323
324             LeaveCriticalSection(&csApartment);
325         }
326         COM_CurrentInfo()->apt = apt;
327     }
328
329     return apt;
330 }
331
332 static inline BOOL apartment_is_model(const APARTMENT *apt, DWORD model)
333 {
334     return (apt->multi_threaded == !(model & COINIT_APARTMENTTHREADED));
335 }
336
337 DWORD apartment_addref(struct apartment *apt)
338 {
339     DWORD refs = InterlockedIncrement(&apt->refs);
340     TRACE("%s: before = %d\n", wine_dbgstr_longlong(apt->oxid), refs - 1);
341     return refs;
342 }
343
344 DWORD apartment_release(struct apartment *apt)
345 {
346     DWORD ret;
347
348     EnterCriticalSection(&csApartment);
349
350     ret = InterlockedDecrement(&apt->refs);
351     TRACE("%s: after = %d\n", wine_dbgstr_longlong(apt->oxid), ret);
352     /* destruction stuff that needs to happen under csApartment CS */
353     if (ret == 0)
354     {
355         if (apt == MTA) MTA = NULL;
356         else if (apt == MainApartment) MainApartment = NULL;
357         list_remove(&apt->entry);
358     }
359
360     LeaveCriticalSection(&csApartment);
361
362     if (ret == 0)
363     {
364         struct list *cursor, *cursor2;
365
366         TRACE("destroying apartment %p, oxid %s\n", apt, wine_dbgstr_longlong(apt->oxid));
367
368         /* Release the references to the registered class objects */
369         COM_RevokeAllClasses(apt);
370
371         /* no locking is needed for this apartment, because no other thread
372          * can access it at this point */
373
374         apartment_disconnectproxies(apt);
375
376         if (apt->win) DestroyWindow(apt->win);
377         if (apt->host_apt_tid) PostThreadMessageW(apt->host_apt_tid, WM_QUIT, 0, 0);
378
379         LIST_FOR_EACH_SAFE(cursor, cursor2, &apt->stubmgrs)
380         {
381             struct stub_manager *stubmgr = LIST_ENTRY(cursor, struct stub_manager, entry);
382             /* release the implicit reference given by the fact that the
383              * stub has external references (it must do since it is in the
384              * stub manager list in the apartment and all non-apartment users
385              * must have a ref on the apartment and so it cannot be destroyed).
386              */
387             stub_manager_int_release(stubmgr);
388         }
389
390         LIST_FOR_EACH_SAFE(cursor, cursor2, &apt->psclsids)
391         {
392             struct registered_psclsid *registered_psclsid =
393                 LIST_ENTRY(cursor, struct registered_psclsid, entry);
394
395             list_remove(&registered_psclsid->entry);
396             HeapFree(GetProcessHeap(), 0, registered_psclsid);
397         }
398
399         /* if this assert fires, then another thread took a reference to a
400          * stub manager without taking a reference to the containing
401          * apartment, which it must do. */
402         assert(list_empty(&apt->stubmgrs));
403
404         if (apt->filter) IUnknown_Release(apt->filter);
405
406         /* free as many unused libraries as possible... */
407         apartment_freeunusedlibraries(apt, 0);
408
409         /* ... and free the memory for the apartment loaded dll entry and
410          * release the dll list reference without freeing the library for the
411          * rest */
412         while ((cursor = list_head(&apt->loaded_dlls)))
413         {
414             struct apartment_loaded_dll *apartment_loaded_dll = LIST_ENTRY(cursor, struct apartment_loaded_dll, entry);
415             COMPOBJ_DllList_ReleaseRef(apartment_loaded_dll->dll, FALSE);
416             list_remove(cursor);
417             HeapFree(GetProcessHeap(), 0, apartment_loaded_dll);
418         }
419
420         DEBUG_CLEAR_CRITSEC_NAME(&apt->cs);
421         DeleteCriticalSection(&apt->cs);
422
423         HeapFree(GetProcessHeap(), 0, apt);
424     }
425
426     return ret;
427 }
428
429 /* The given OXID must be local to this process: 
430  *
431  * The ref parameter is here mostly to ensure people remember that
432  * they get one, you should normally take a ref for thread safety.
433  */
434 APARTMENT *apartment_findfromoxid(OXID oxid, BOOL ref)
435 {
436     APARTMENT *result = NULL;
437     struct list *cursor;
438
439     EnterCriticalSection(&csApartment);
440     LIST_FOR_EACH( cursor, &apts )
441     {
442         struct apartment *apt = LIST_ENTRY( cursor, struct apartment, entry );
443         if (apt->oxid == oxid)
444         {
445             result = apt;
446             if (ref) apartment_addref(result);
447             break;
448         }
449     }
450     LeaveCriticalSection(&csApartment);
451
452     return result;
453 }
454
455 /* gets the apartment which has a given creator thread ID. The caller must
456  * release the reference from the apartment as soon as the apartment pointer
457  * is no longer required. */
458 APARTMENT *apartment_findfromtid(DWORD tid)
459 {
460     APARTMENT *result = NULL;
461     struct list *cursor;
462
463     EnterCriticalSection(&csApartment);
464     LIST_FOR_EACH( cursor, &apts )
465     {
466         struct apartment *apt = LIST_ENTRY( cursor, struct apartment, entry );
467         if (apt->tid == tid)
468         {
469             result = apt;
470             apartment_addref(result);
471             break;
472         }
473     }
474     LeaveCriticalSection(&csApartment);
475
476     return result;
477 }
478
479 /* gets the main apartment if it exists. The caller must
480  * release the reference from the apartment as soon as the apartment pointer
481  * is no longer required. */
482 static APARTMENT *apartment_findmain(void)
483 {
484     APARTMENT *result;
485
486     EnterCriticalSection(&csApartment);
487
488     result = MainApartment;
489     if (result) apartment_addref(result);
490
491     LeaveCriticalSection(&csApartment);
492
493     return result;
494 }
495
496 struct host_object_params
497 {
498     HKEY hkeydll;
499     CLSID clsid; /* clsid of object to marshal */
500     IID iid; /* interface to marshal */
501     HANDLE event; /* event signalling when ready for multi-threaded case */
502     HRESULT hr; /* result for multi-threaded case */
503     IStream *stream; /* stream that the object will be marshaled into */
504     BOOL apartment_threaded; /* is the component purely apartment-threaded? */
505 };
506
507 static HRESULT apartment_hostobject(struct apartment *apt,
508                                     const struct host_object_params *params)
509 {
510     IUnknown *object;
511     HRESULT hr;
512     static const LARGE_INTEGER llZero;
513     WCHAR dllpath[MAX_PATH+1];
514
515     TRACE("clsid %s, iid %s\n", debugstr_guid(&params->clsid), debugstr_guid(&params->iid));
516
517     if (COM_RegReadPath(params->hkeydll, NULL, NULL, dllpath, ARRAYSIZE(dllpath)) != ERROR_SUCCESS)
518     {
519         /* failure: CLSID is not found in registry */
520         WARN("class %s not registered inproc\n", debugstr_guid(&params->clsid));
521         return REGDB_E_CLASSNOTREG;
522     }
523
524     hr = apartment_getclassobject(apt, dllpath, params->apartment_threaded,
525                                   &params->clsid, &params->iid, (void **)&object);
526     if (FAILED(hr))
527         return hr;
528
529     hr = CoMarshalInterface(params->stream, &params->iid, object, MSHCTX_INPROC, NULL, MSHLFLAGS_NORMAL);
530     if (FAILED(hr))
531         IUnknown_Release(object);
532     IStream_Seek(params->stream, llZero, STREAM_SEEK_SET, NULL);
533
534     return hr;
535 }
536
537 static LRESULT CALLBACK apartment_wndproc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
538 {
539     switch (msg)
540     {
541     case DM_EXECUTERPC:
542         RPC_ExecuteCall((struct dispatch_params *)lParam);
543         return 0;
544     case DM_HOSTOBJECT:
545         return apartment_hostobject(COM_CurrentApt(), (const struct host_object_params *)lParam);
546     default:
547         return DefWindowProcW(hWnd, msg, wParam, lParam);
548     }
549 }
550
551 struct host_thread_params
552 {
553     COINIT threading_model;
554     HANDLE ready_event;
555     HWND apartment_hwnd;
556 };
557
558 /* thread for hosting an object to allow an object to appear to be created in
559  * an apartment with an incompatible threading model */
560 static DWORD CALLBACK apartment_hostobject_thread(LPVOID p)
561 {
562     struct host_thread_params *params = p;
563     MSG msg;
564     HRESULT hr;
565     struct apartment *apt;
566
567     TRACE("\n");
568
569     hr = CoInitializeEx(NULL, params->threading_model);
570     if (FAILED(hr)) return hr;
571
572     apt = COM_CurrentApt();
573     if (params->threading_model == COINIT_APARTMENTTHREADED)
574     {
575         apartment_createwindowifneeded(apt);
576         params->apartment_hwnd = apartment_getwindow(apt);
577     }
578     else
579         params->apartment_hwnd = NULL;
580
581     /* force the message queue to be created before signaling parent thread */
582     PeekMessageW(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
583
584     SetEvent(params->ready_event);
585     params = NULL; /* can't touch params after here as it may be invalid */
586
587     while (GetMessageW(&msg, NULL, 0, 0))
588     {
589         if (!msg.hwnd && (msg.message == DM_HOSTOBJECT))
590         {
591             struct host_object_params *obj_params = (struct host_object_params *)msg.lParam;
592             obj_params->hr = apartment_hostobject(apt, obj_params);
593             SetEvent(obj_params->event);
594         }
595         else
596         {
597             TranslateMessage(&msg);
598             DispatchMessageW(&msg);
599         }
600     }
601
602     TRACE("exiting\n");
603
604     CoUninitialize();
605
606     return S_OK;
607 }
608
609 /* finds or creates a host apartment, creates the object inside it and returns
610  * a proxy to it so that the object can be used in the apartment of the
611  * caller of this function */
612 static HRESULT apartment_hostobject_in_hostapt(
613     struct apartment *apt, BOOL multi_threaded, BOOL main_apartment,
614     HKEY hkeydll, REFCLSID rclsid, REFIID riid, void **ppv)
615 {
616     struct host_object_params params;
617     HWND apartment_hwnd = NULL;
618     DWORD apartment_tid = 0;
619     HRESULT hr;
620
621     if (!multi_threaded && main_apartment)
622     {
623         APARTMENT *host_apt = apartment_findmain();
624         if (host_apt)
625         {
626             apartment_hwnd = apartment_getwindow(host_apt);
627             apartment_release(host_apt);
628         }
629     }
630
631     if (!apartment_hwnd)
632     {
633         EnterCriticalSection(&apt->cs);
634
635         if (!apt->host_apt_tid)
636         {
637             struct host_thread_params thread_params;
638             HANDLE handles[2];
639             DWORD wait_value;
640
641             thread_params.threading_model = multi_threaded ? COINIT_MULTITHREADED : COINIT_APARTMENTTHREADED;
642             handles[0] = thread_params.ready_event = CreateEventW(NULL, FALSE, FALSE, NULL);
643             thread_params.apartment_hwnd = NULL;
644             handles[1] = CreateThread(NULL, 0, apartment_hostobject_thread, &thread_params, 0, &apt->host_apt_tid);
645             if (!handles[1])
646             {
647                 CloseHandle(handles[0]);
648                 LeaveCriticalSection(&apt->cs);
649                 return E_OUTOFMEMORY;
650             }
651             wait_value = WaitForMultipleObjects(2, handles, FALSE, INFINITE);
652             CloseHandle(handles[0]);
653             CloseHandle(handles[1]);
654             if (wait_value == WAIT_OBJECT_0)
655                 apt->host_apt_hwnd = thread_params.apartment_hwnd;
656             else
657             {
658                 LeaveCriticalSection(&apt->cs);
659                 return E_OUTOFMEMORY;
660             }
661         }
662
663         if (multi_threaded || !main_apartment)
664         {
665             apartment_hwnd = apt->host_apt_hwnd;
666             apartment_tid = apt->host_apt_tid;
667         }
668
669         LeaveCriticalSection(&apt->cs);
670     }
671
672     /* another thread may have become the main apartment in the time it took
673      * us to create the thread for the host apartment */
674     if (!apartment_hwnd && !multi_threaded && main_apartment)
675     {
676         APARTMENT *host_apt = apartment_findmain();
677         if (host_apt)
678         {
679             apartment_hwnd = apartment_getwindow(host_apt);
680             apartment_release(host_apt);
681         }
682     }
683
684     params.hkeydll = hkeydll;
685     params.clsid = *rclsid;
686     params.iid = *riid;
687     hr = CreateStreamOnHGlobal(NULL, TRUE, &params.stream);
688     if (FAILED(hr))
689         return hr;
690     params.apartment_threaded = !multi_threaded;
691     if (multi_threaded)
692     {
693         params.hr = S_OK;
694         params.event = CreateEventW(NULL, FALSE, FALSE, NULL);
695         if (!PostThreadMessageW(apartment_tid, DM_HOSTOBJECT, 0, (LPARAM)&params))
696             hr = E_OUTOFMEMORY;
697         else
698         {
699             WaitForSingleObject(params.event, INFINITE);
700             hr = params.hr;
701         }
702         CloseHandle(params.event);
703     }
704     else
705     {
706         if (!apartment_hwnd)
707         {
708             ERR("host apartment didn't create window\n");
709             hr = E_OUTOFMEMORY;
710         }
711         else
712             hr = SendMessageW(apartment_hwnd, DM_HOSTOBJECT, 0, (LPARAM)&params);
713     }
714     if (SUCCEEDED(hr))
715         hr = CoUnmarshalInterface(params.stream, riid, ppv);
716     IStream_Release(params.stream);
717     return hr;
718 }
719
720 /* create a window for the apartment or return the current one if one has
721  * already been created */
722 HRESULT apartment_createwindowifneeded(struct apartment *apt)
723 {
724     if (apt->multi_threaded)
725         return S_OK;
726
727     if (!apt->win)
728     {
729         HWND hwnd = CreateWindowW(wszAptWinClass, NULL, 0,
730                                   0, 0, 0, 0,
731                                   HWND_MESSAGE, 0, hProxyDll, NULL);
732         if (!hwnd)
733         {
734             ERR("CreateWindow failed with error %d\n", GetLastError());
735             return HRESULT_FROM_WIN32(GetLastError());
736         }
737         if (InterlockedCompareExchangePointer((PVOID *)&apt->win, hwnd, NULL))
738             /* someone beat us to it */
739             DestroyWindow(hwnd);
740     }
741
742     return S_OK;
743 }
744
745 /* retrieves the window for the main- or apartment-threaded apartment */
746 HWND apartment_getwindow(const struct apartment *apt)
747 {
748     assert(!apt->multi_threaded);
749     return apt->win;
750 }
751
752 void apartment_joinmta(void)
753 {
754     apartment_addref(MTA);
755     COM_CurrentInfo()->apt = MTA;
756 }
757
758 /* gets the specified class object by loading the appropriate DLL, if
759  * necessary and calls the DllGetClassObject function for the DLL */
760 static HRESULT apartment_getclassobject(struct apartment *apt, LPCWSTR dllpath,
761                                         BOOL apartment_threaded,
762                                         REFCLSID rclsid, REFIID riid, void **ppv)
763 {
764     static const WCHAR wszOle32[] = {'o','l','e','3','2','.','d','l','l',0};
765     HRESULT hr = S_OK;
766     BOOL found = FALSE;
767     struct apartment_loaded_dll *apartment_loaded_dll;
768
769     if (!strcmpiW(dllpath, wszOle32))
770     {
771         /* we don't need to control the lifetime of this dll, so use the local
772          * implementation of DllGetClassObject directly */
773         TRACE("calling ole32!DllGetClassObject\n");
774         hr = DllGetClassObject(rclsid, riid, ppv);
775
776         if (hr != S_OK)
777             ERR("DllGetClassObject returned error 0x%08x\n", hr);
778
779         return hr;
780     }
781
782     EnterCriticalSection(&apt->cs);
783
784     LIST_FOR_EACH_ENTRY(apartment_loaded_dll, &apt->loaded_dlls, struct apartment_loaded_dll, entry)
785         if (!strcmpiW(dllpath, apartment_loaded_dll->dll->library_name))
786         {
787             TRACE("found %s already loaded\n", debugstr_w(dllpath));
788             found = TRUE;
789             break;
790         }
791
792     if (!found)
793     {
794         apartment_loaded_dll = HeapAlloc(GetProcessHeap(), 0, sizeof(*apartment_loaded_dll));
795         if (!apartment_loaded_dll)
796             hr = E_OUTOFMEMORY;
797         if (SUCCEEDED(hr))
798         {
799             apartment_loaded_dll->unload_time = 0;
800             apartment_loaded_dll->multi_threaded = FALSE;
801             hr = COMPOBJ_DllList_Add( dllpath, &apartment_loaded_dll->dll );
802             if (FAILED(hr))
803                 HeapFree(GetProcessHeap(), 0, apartment_loaded_dll);
804         }
805         if (SUCCEEDED(hr))
806         {
807             TRACE("added new loaded dll %s\n", debugstr_w(dllpath));
808             list_add_tail(&apt->loaded_dlls, &apartment_loaded_dll->entry);
809         }
810     }
811
812     LeaveCriticalSection(&apt->cs);
813
814     if (SUCCEEDED(hr))
815     {
816         /* one component being multi-threaded overrides any number of
817          * apartment-threaded components */
818         if (!apartment_threaded)
819             apartment_loaded_dll->multi_threaded = TRUE;
820
821         TRACE("calling DllGetClassObject %p\n", apartment_loaded_dll->dll->DllGetClassObject);
822         /* OK: get the ClassObject */
823         hr = apartment_loaded_dll->dll->DllGetClassObject(rclsid, riid, ppv);
824
825         if (hr != S_OK)
826             ERR("DllGetClassObject returned error 0x%08x\n", hr);
827     }
828
829     return hr;
830 }
831
832 /* frees unused libraries loaded by apartment_getclassobject by calling the
833  * DLL's DllCanUnloadNow entry point */
834 static void apartment_freeunusedlibraries(struct apartment *apt, DWORD delay)
835 {
836     struct apartment_loaded_dll *entry, *next;
837     EnterCriticalSection(&apt->cs);
838     LIST_FOR_EACH_ENTRY_SAFE(entry, next, &apt->loaded_dlls, struct apartment_loaded_dll, entry)
839     {
840         if (entry->dll->DllCanUnloadNow && (entry->dll->DllCanUnloadNow() == S_OK))
841         {
842             DWORD real_delay = delay;
843
844             if (real_delay == INFINITE)
845             {
846                 /* DLLs that return multi-threaded objects aren't unloaded
847                  * straight away to cope for programs that have races between
848                  * last object destruction and threads in the DLLs that haven't
849                  * finished, despite DllCanUnloadNow returning S_OK */
850                 if (entry->multi_threaded)
851                     real_delay = 10 * 60 * 1000; /* 10 minutes */
852                 else
853                     real_delay = 0;
854             }
855
856             if (!real_delay || (entry->unload_time && (entry->unload_time < GetTickCount())))
857             {
858                 list_remove(&entry->entry);
859                 COMPOBJ_DllList_ReleaseRef(entry->dll, TRUE);
860                 HeapFree(GetProcessHeap(), 0, entry);
861             }
862             else
863                 entry->unload_time = GetTickCount() + real_delay;
864         }
865         else if (entry->unload_time)
866             entry->unload_time = 0;
867     }
868     LeaveCriticalSection(&apt->cs);
869 }
870
871 /*****************************************************************************
872  * This section contains OpenDllList implementation
873  */
874
875 /* caller must ensure that library_name is not already in the open dll list */
876 static HRESULT COMPOBJ_DllList_Add(LPCWSTR library_name, OpenDll **ret)
877 {
878     OpenDll *entry;
879     int len;
880     HRESULT hr = S_OK;
881     HANDLE hLibrary;
882     DllCanUnloadNowFunc DllCanUnloadNow;
883     DllGetClassObjectFunc DllGetClassObject;
884
885     TRACE("\n");
886
887     *ret = COMPOBJ_DllList_Get(library_name);
888     if (*ret) return S_OK;
889
890     /* do this outside the csOpenDllList to avoid creating a lock dependency on
891      * the loader lock */
892     hLibrary = LoadLibraryExW(library_name, 0, LOAD_WITH_ALTERED_SEARCH_PATH);
893     if (!hLibrary)
894     {
895         ERR("couldn't load in-process dll %s\n", debugstr_w(library_name));
896         /* failure: DLL could not be loaded */
897         return E_ACCESSDENIED; /* FIXME: or should this be CO_E_DLLNOTFOUND? */
898     }
899
900     DllCanUnloadNow = (void *)GetProcAddress(hLibrary, "DllCanUnloadNow");
901     /* Note: failing to find DllCanUnloadNow is not a failure */
902     DllGetClassObject = (void *)GetProcAddress(hLibrary, "DllGetClassObject");
903     if (!DllGetClassObject)
904     {
905         /* failure: the dll did not export DllGetClassObject */
906         ERR("couldn't find function DllGetClassObject in %s\n", debugstr_w(library_name));
907         FreeLibrary(hLibrary);
908         return CO_E_DLLNOTFOUND;
909     }
910
911     EnterCriticalSection( &csOpenDllList );
912
913     *ret = COMPOBJ_DllList_Get(library_name);
914     if (*ret)
915     {
916         /* another caller to this function already added the dll while we
917          * weren't in the critical section */
918         FreeLibrary(hLibrary);
919     }
920     else
921     {
922         len = strlenW(library_name);
923         entry = HeapAlloc(GetProcessHeap(),0, sizeof(OpenDll));
924         if (entry)
925             entry->library_name = HeapAlloc(GetProcessHeap(), 0, (len + 1)*sizeof(WCHAR));
926         if (entry && entry->library_name)
927         {
928             memcpy(entry->library_name, library_name, (len + 1)*sizeof(WCHAR));
929             entry->library = hLibrary;
930             entry->refs = 1;
931             entry->DllCanUnloadNow = DllCanUnloadNow;
932             entry->DllGetClassObject = DllGetClassObject;
933             list_add_tail(&openDllList, &entry->entry);
934         }
935         else
936         {
937             HeapFree(GetProcessHeap(), 0, entry);
938             hr = E_OUTOFMEMORY;
939             FreeLibrary(hLibrary);
940         }
941         *ret = entry;
942     }
943
944     LeaveCriticalSection( &csOpenDllList );
945
946     return hr;
947 }
948
949 static OpenDll *COMPOBJ_DllList_Get(LPCWSTR library_name)
950 {
951     OpenDll *ptr;
952     OpenDll *ret = NULL;
953     EnterCriticalSection(&csOpenDllList);
954     LIST_FOR_EACH_ENTRY(ptr, &openDllList, OpenDll, entry)
955     {
956         if (!strcmpiW(library_name, ptr->library_name) &&
957             (InterlockedIncrement(&ptr->refs) != 1) /* entry is being destroy if == 1 */)
958         {
959             ret = ptr;
960             break;
961         }
962     }
963     LeaveCriticalSection(&csOpenDllList);
964     return ret;
965 }
966
967 /* pass FALSE for free_entry to release a reference without destroying the
968  * entry if it reaches zero or TRUE otherwise */
969 static void COMPOBJ_DllList_ReleaseRef(OpenDll *entry, BOOL free_entry)
970 {
971     if (!InterlockedDecrement(&entry->refs) && free_entry)
972     {
973         EnterCriticalSection(&csOpenDllList);
974         list_remove(&entry->entry);
975         LeaveCriticalSection(&csOpenDllList);
976
977         TRACE("freeing %p\n", entry->library);
978         FreeLibrary(entry->library);
979
980         HeapFree(GetProcessHeap(), 0, entry->library_name);
981         HeapFree(GetProcessHeap(), 0, entry);
982     }
983 }
984
985 /* frees memory associated with active dll list */
986 static void COMPOBJ_DllList_Free(void)
987 {
988     OpenDll *entry, *cursor2;
989     EnterCriticalSection(&csOpenDllList);
990     LIST_FOR_EACH_ENTRY_SAFE(entry, cursor2, &openDllList, OpenDll, entry)
991     {
992         list_remove(&entry->entry);
993
994         HeapFree(GetProcessHeap(), 0, entry->library_name);
995         HeapFree(GetProcessHeap(), 0, entry);
996     }
997     LeaveCriticalSection(&csOpenDllList);
998 }
999
1000 /******************************************************************************
1001  *           CoBuildVersion [OLE32.@]
1002  *
1003  * Gets the build version of the DLL.
1004  *
1005  * PARAMS
1006  *
1007  * RETURNS
1008  *      Current build version, hiword is majornumber, loword is minornumber
1009  */
1010 DWORD WINAPI CoBuildVersion(void)
1011 {
1012     TRACE("Returning version %d, build %d.\n", rmm, rup);
1013     return (rmm<<16)+rup;
1014 }
1015
1016 /******************************************************************************
1017  *              CoRegisterInitializeSpy [OLE32.@]
1018  *
1019  * Add a Spy that watches CoInitializeEx calls
1020  *
1021  * PARAMS
1022  *  spy [I] Pointer to IUnknown interface that will be QueryInterface'd.
1023  *  cookie [II] cookie receiver
1024  *
1025  * RETURNS
1026  *  Success: S_OK if not already initialized, S_FALSE otherwise.
1027  *  Failure: HRESULT code.
1028  *
1029  * SEE ALSO
1030  *   CoInitializeEx
1031  */
1032 HRESULT WINAPI CoRegisterInitializeSpy(IInitializeSpy *spy, ULARGE_INTEGER *cookie)
1033 {
1034     struct oletls *info = COM_CurrentInfo();
1035     HRESULT hr;
1036
1037     TRACE("(%p, %p)\n", spy, cookie);
1038
1039     if (!spy || !cookie || !info)
1040     {
1041         if (!info)
1042             WARN("Could not allocate tls\n");
1043         return E_INVALIDARG;
1044     }
1045
1046     if (info->spy)
1047     {
1048         FIXME("Already registered?\n");
1049         return E_UNEXPECTED;
1050     }
1051
1052     hr = IUnknown_QueryInterface(spy, &IID_IInitializeSpy, (void **) &info->spy);
1053     if (SUCCEEDED(hr))
1054     {
1055         cookie->QuadPart = (DWORD_PTR)spy;
1056         return S_OK;
1057     }
1058     return hr;
1059 }
1060
1061 /******************************************************************************
1062  *              CoRevokeInitializeSpy [OLE32.@]
1063  *
1064  * Remove a spy that previously watched CoInitializeEx calls
1065  *
1066  * PARAMS
1067  *  cookie [I] The cookie obtained from a previous CoRegisterInitializeSpy call
1068  *
1069  * RETURNS
1070  *  Success: S_OK if a spy is removed
1071  *  Failure: E_INVALIDARG
1072  *
1073  * SEE ALSO
1074  *   CoInitializeEx
1075  */
1076 HRESULT WINAPI CoRevokeInitializeSpy(ULARGE_INTEGER cookie)
1077 {
1078     struct oletls *info = COM_CurrentInfo();
1079     TRACE("(%s)\n", wine_dbgstr_longlong(cookie.QuadPart));
1080
1081     if (!info || !info->spy || cookie.QuadPart != (DWORD_PTR)info->spy)
1082         return E_INVALIDARG;
1083
1084     IUnknown_Release(info->spy);
1085     info->spy = NULL;
1086     return S_OK;
1087 }
1088
1089
1090 /******************************************************************************
1091  *              CoInitialize    [OLE32.@]
1092  *
1093  * Initializes the COM libraries by calling CoInitializeEx with
1094  * COINIT_APARTMENTTHREADED, ie it enters a STA thread.
1095  *
1096  * PARAMS
1097  *  lpReserved [I] Pointer to IMalloc interface (obsolete, should be NULL).
1098  *
1099  * RETURNS
1100  *  Success: S_OK if not already initialized, S_FALSE otherwise.
1101  *  Failure: HRESULT code.
1102  *
1103  * SEE ALSO
1104  *   CoInitializeEx
1105  */
1106 HRESULT WINAPI CoInitialize(LPVOID lpReserved)
1107 {
1108   /*
1109    * Just delegate to the newer method.
1110    */
1111   return CoInitializeEx(lpReserved, COINIT_APARTMENTTHREADED);
1112 }
1113
1114 /******************************************************************************
1115  *              CoInitializeEx  [OLE32.@]
1116  *
1117  * Initializes the COM libraries.
1118  *
1119  * PARAMS
1120  *  lpReserved [I] Pointer to IMalloc interface (obsolete, should be NULL).
1121  *  dwCoInit   [I] One or more flags from the COINIT enumeration. See notes.
1122  *
1123  * RETURNS
1124  *  S_OK               if successful,
1125  *  S_FALSE            if this function was called already.
1126  *  RPC_E_CHANGED_MODE if a previous call to CoInitializeEx specified another
1127  *                     threading model.
1128  *
1129  * NOTES
1130  *
1131  * The behavior used to set the IMalloc used for memory management is
1132  * obsolete.
1133  * The dwCoInit parameter must specify one of the following apartment
1134  * threading models:
1135  *| COINIT_APARTMENTTHREADED - A single-threaded apartment (STA).
1136  *| COINIT_MULTITHREADED - A multi-threaded apartment (MTA).
1137  * The parameter may also specify zero or more of the following flags:
1138  *| COINIT_DISABLE_OLE1DDE - Don't use DDE for OLE1 support.
1139  *| COINIT_SPEED_OVER_MEMORY - Trade memory for speed.
1140  *
1141  * SEE ALSO
1142  *   CoUninitialize
1143  */
1144 HRESULT WINAPI CoInitializeEx(LPVOID lpReserved, DWORD dwCoInit)
1145 {
1146   struct oletls *info = COM_CurrentInfo();
1147   HRESULT hr = S_OK;
1148   APARTMENT *apt;
1149
1150   TRACE("(%p, %x)\n", lpReserved, (int)dwCoInit);
1151
1152   if (lpReserved!=NULL)
1153   {
1154     ERR("(%p, %x) - Bad parameter passed-in %p, must be an old Windows Application\n", lpReserved, (int)dwCoInit, lpReserved);
1155   }
1156
1157   /*
1158    * Check the lock count. If this is the first time going through the initialize
1159    * process, we have to initialize the libraries.
1160    *
1161    * And crank-up that lock count.
1162    */
1163   if (InterlockedExchangeAdd(&s_COMLockCount,1)==0)
1164   {
1165     /*
1166      * Initialize the various COM libraries and data structures.
1167      */
1168     TRACE("() - Initializing the COM libraries\n");
1169
1170     /* we may need to defer this until after apartment initialisation */
1171     RunningObjectTableImpl_Initialize();
1172   }
1173
1174   if (info->spy)
1175       IInitializeSpy_PreInitialize(info->spy, dwCoInit, info->inits);
1176
1177   if (!(apt = info->apt))
1178   {
1179     apt = apartment_get_or_create(dwCoInit);
1180     if (!apt) return E_OUTOFMEMORY;
1181   }
1182   else if (!apartment_is_model(apt, dwCoInit))
1183   {
1184     /* Changing the threading model after it's been set is illegal. If this warning is triggered by Wine
1185        code then we are probably using the wrong threading model to implement that API. */
1186     ERR("Attempt to change threading model of this apartment from %s to %s\n",
1187         apt->multi_threaded ? "multi-threaded" : "apartment threaded",
1188         dwCoInit & COINIT_APARTMENTTHREADED ? "apartment threaded" : "multi-threaded");
1189     return RPC_E_CHANGED_MODE;
1190   }
1191   else
1192     hr = S_FALSE;
1193
1194   info->inits++;
1195
1196   if (info->spy)
1197       IInitializeSpy_PostInitialize(info->spy, hr, dwCoInit, info->inits);
1198
1199   return hr;
1200 }
1201
1202 /***********************************************************************
1203  *           CoUninitialize   [OLE32.@]
1204  *
1205  * This method will decrement the refcount on the current apartment, freeing
1206  * the resources associated with it if it is the last thread in the apartment.
1207  * If the last apartment is freed, the function will additionally release
1208  * any COM resources associated with the process.
1209  *
1210  * PARAMS
1211  *
1212  * RETURNS
1213  *  Nothing.
1214  *
1215  * SEE ALSO
1216  *   CoInitializeEx
1217  */
1218 void WINAPI CoUninitialize(void)
1219 {
1220   struct oletls * info = COM_CurrentInfo();
1221   LONG lCOMRefCnt;
1222
1223   TRACE("()\n");
1224
1225   /* will only happen on OOM */
1226   if (!info) return;
1227
1228   if (info->spy)
1229       IInitializeSpy_PreUninitialize(info->spy, info->inits);
1230
1231   /* sanity check */
1232   if (!info->inits)
1233   {
1234     ERR("Mismatched CoUninitialize\n");
1235
1236     if (info->spy)
1237         IInitializeSpy_PostUninitialize(info->spy, info->inits);
1238     return;
1239   }
1240
1241   if (!--info->inits)
1242   {
1243     apartment_release(info->apt);
1244     info->apt = NULL;
1245   }
1246
1247   /*
1248    * Decrease the reference count.
1249    * If we are back to 0 locks on the COM library, make sure we free
1250    * all the associated data structures.
1251    */
1252   lCOMRefCnt = InterlockedExchangeAdd(&s_COMLockCount,-1);
1253   if (lCOMRefCnt==1)
1254   {
1255     TRACE("() - Releasing the COM libraries\n");
1256
1257     RunningObjectTableImpl_UnInitialize();
1258   }
1259   else if (lCOMRefCnt<1) {
1260     ERR( "CoUninitialize() - not CoInitialized.\n" );
1261     InterlockedExchangeAdd(&s_COMLockCount,1); /* restore the lock count. */
1262   }
1263   if (info->spy)
1264       IInitializeSpy_PostUninitialize(info->spy, info->inits);
1265 }
1266
1267 /******************************************************************************
1268  *              CoDisconnectObject      [OLE32.@]
1269  *
1270  * Disconnects all connections to this object from remote processes. Dispatches
1271  * pending RPCs while blocking new RPCs from occurring, and then calls
1272  * IMarshal::DisconnectObject on the given object.
1273  *
1274  * Typically called when the object server is forced to shut down, for instance by
1275  * the user.
1276  *
1277  * PARAMS
1278  *  lpUnk    [I] The object whose stub should be disconnected.
1279  *  reserved [I] Reserved. Should be set to 0.
1280  *
1281  * RETURNS
1282  *  Success: S_OK.
1283  *  Failure: HRESULT code.
1284  *
1285  * SEE ALSO
1286  *  CoMarshalInterface, CoReleaseMarshalData, CoLockObjectExternal
1287  */
1288 HRESULT WINAPI CoDisconnectObject( LPUNKNOWN lpUnk, DWORD reserved )
1289 {
1290     HRESULT hr;
1291     IMarshal *marshal;
1292     APARTMENT *apt;
1293
1294     TRACE("(%p, 0x%08x)\n", lpUnk, reserved);
1295
1296     hr = IUnknown_QueryInterface(lpUnk, &IID_IMarshal, (void **)&marshal);
1297     if (hr == S_OK)
1298     {
1299         hr = IMarshal_DisconnectObject(marshal, reserved);
1300         IMarshal_Release(marshal);
1301         return hr;
1302     }
1303
1304     apt = COM_CurrentApt();
1305     if (!apt)
1306         return CO_E_NOTINITIALIZED;
1307
1308     apartment_disconnectobject(apt, lpUnk);
1309
1310     /* Note: native is pretty broken here because it just silently
1311      * fails, without returning an appropriate error code if the object was
1312      * not found, making apps think that the object was disconnected, when
1313      * it actually wasn't */
1314
1315     return S_OK;
1316 }
1317
1318 /******************************************************************************
1319  *              CoCreateGuid [OLE32.@]
1320  *
1321  * Simply forwards to UuidCreate in RPCRT4.
1322  *
1323  * PARAMS
1324  *  pguid [O] Points to the GUID to initialize.
1325  *
1326  * RETURNS
1327  *  Success: S_OK.
1328  *  Failure: HRESULT code.
1329  *
1330  * SEE ALSO
1331  *   UuidCreate
1332  */
1333 HRESULT WINAPI CoCreateGuid(GUID *pguid)
1334 {
1335     DWORD status = UuidCreate(pguid);
1336     if (status == RPC_S_OK || status == RPC_S_UUID_LOCAL_ONLY) return S_OK;
1337     return HRESULT_FROM_WIN32( status );
1338 }
1339
1340 /******************************************************************************
1341  *              CLSIDFromString [OLE32.@]
1342  *              IIDFromString   [OLE32.@]
1343  *
1344  * Converts a unique identifier from its string representation into
1345  * the GUID struct.
1346  *
1347  * PARAMS
1348  *  idstr [I] The string representation of the GUID.
1349  *  id    [O] GUID converted from the string.
1350  *
1351  * RETURNS
1352  *   S_OK on success
1353  *   CO_E_CLASSSTRING if idstr is not a valid CLSID
1354  *
1355  * SEE ALSO
1356  *  StringFromCLSID
1357  */
1358 static HRESULT __CLSIDFromString(LPCWSTR s, CLSID *id)
1359 {
1360   int   i;
1361   BYTE table[256];
1362
1363   if (!s) {
1364     memset( id, 0, sizeof (CLSID) );
1365     return S_OK;
1366   }
1367
1368   /* validate the CLSID string */
1369   if (strlenW(s) != 38)
1370     return CO_E_CLASSSTRING;
1371
1372   if ((s[0]!='{') || (s[9]!='-') || (s[14]!='-') || (s[19]!='-') || (s[24]!='-') || (s[37]!='}'))
1373     return CO_E_CLASSSTRING;
1374
1375   for (i=1; i<37; i++) {
1376     if ((i == 9)||(i == 14)||(i == 19)||(i == 24)) continue;
1377     if (!(((s[i] >= '0') && (s[i] <= '9'))  ||
1378           ((s[i] >= 'a') && (s[i] <= 'f'))  ||
1379           ((s[i] >= 'A') && (s[i] <= 'F'))))
1380        return CO_E_CLASSSTRING;
1381   }
1382
1383   TRACE("%s -> %p\n", debugstr_w(s), id);
1384
1385   /* quick lookup table */
1386   memset(table, 0, 256);
1387
1388   for (i = 0; i < 10; i++) {
1389     table['0' + i] = i;
1390   }
1391   for (i = 0; i < 6; i++) {
1392     table['A' + i] = i+10;
1393     table['a' + i] = i+10;
1394   }
1395
1396   /* in form {XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX} */
1397
1398   id->Data1 = (table[s[1]] << 28 | table[s[2]] << 24 | table[s[3]] << 20 | table[s[4]] << 16 |
1399                table[s[5]] << 12 | table[s[6]] << 8  | table[s[7]] << 4  | table[s[8]]);
1400   id->Data2 = table[s[10]] << 12 | table[s[11]] << 8 | table[s[12]] << 4 | table[s[13]];
1401   id->Data3 = table[s[15]] << 12 | table[s[16]] << 8 | table[s[17]] << 4 | table[s[18]];
1402
1403   /* these are just sequential bytes */
1404   id->Data4[0] = table[s[20]] << 4 | table[s[21]];
1405   id->Data4[1] = table[s[22]] << 4 | table[s[23]];
1406   id->Data4[2] = table[s[25]] << 4 | table[s[26]];
1407   id->Data4[3] = table[s[27]] << 4 | table[s[28]];
1408   id->Data4[4] = table[s[29]] << 4 | table[s[30]];
1409   id->Data4[5] = table[s[31]] << 4 | table[s[32]];
1410   id->Data4[6] = table[s[33]] << 4 | table[s[34]];
1411   id->Data4[7] = table[s[35]] << 4 | table[s[36]];
1412
1413   return S_OK;
1414 }
1415
1416 /*****************************************************************************/
1417
1418 HRESULT WINAPI CLSIDFromString(LPOLESTR idstr, CLSID *id )
1419 {
1420     HRESULT ret;
1421
1422     if (!id)
1423         return E_INVALIDARG;
1424
1425     ret = __CLSIDFromString(idstr, id);
1426     if(ret != S_OK) { /* It appears a ProgID is also valid */
1427         ret = CLSIDFromProgID(idstr, id);
1428     }
1429     return ret;
1430 }
1431
1432
1433 /******************************************************************************
1434  *              StringFromCLSID [OLE32.@]
1435  *              StringFromIID   [OLE32.@]
1436  *
1437  * Converts a GUID into the respective string representation.
1438  * The target string is allocated using the OLE IMalloc.
1439  *
1440  * PARAMS
1441  *  id    [I] the GUID to be converted.
1442  *  idstr [O] A pointer to a to-be-allocated pointer pointing to the resulting string.
1443  *
1444  * RETURNS
1445  *   S_OK
1446  *   E_FAIL
1447  *
1448  * SEE ALSO
1449  *  StringFromGUID2, CLSIDFromString
1450  */
1451 HRESULT WINAPI StringFromCLSID(REFCLSID id, LPOLESTR *idstr)
1452 {
1453     HRESULT ret;
1454     LPMALLOC mllc;
1455
1456     if ((ret = CoGetMalloc(0,&mllc))) return ret;
1457     if (!(*idstr = IMalloc_Alloc( mllc, CHARS_IN_GUID * sizeof(WCHAR) ))) return E_OUTOFMEMORY;
1458     StringFromGUID2( id, *idstr, CHARS_IN_GUID );
1459     return S_OK;
1460 }
1461
1462 /******************************************************************************
1463  *              StringFromGUID2 [OLE32.@]
1464  *
1465  * Modified version of StringFromCLSID that allows you to specify max
1466  * buffer size.
1467  *
1468  * PARAMS
1469  *  id   [I] GUID to convert to string.
1470  *  str  [O] Buffer where the result will be stored.
1471  *  cmax [I] Size of the buffer in characters.
1472  *
1473  * RETURNS
1474  *      Success: The length of the resulting string in characters.
1475  *  Failure: 0.
1476  */
1477 INT WINAPI StringFromGUID2(REFGUID id, LPOLESTR str, INT cmax)
1478 {
1479     static const WCHAR formatW[] = { '{','%','0','8','X','-','%','0','4','X','-',
1480                                      '%','0','4','X','-','%','0','2','X','%','0','2','X','-',
1481                                      '%','0','2','X','%','0','2','X','%','0','2','X','%','0','2','X',
1482                                      '%','0','2','X','%','0','2','X','}',0 };
1483     if (cmax < CHARS_IN_GUID) return 0;
1484     sprintfW( str, formatW, id->Data1, id->Data2, id->Data3,
1485               id->Data4[0], id->Data4[1], id->Data4[2], id->Data4[3],
1486               id->Data4[4], id->Data4[5], id->Data4[6], id->Data4[7] );
1487     return CHARS_IN_GUID;
1488 }
1489
1490 /* open HKCR\\CLSID\\{string form of clsid}\\{keyname} key */
1491 HRESULT COM_OpenKeyForCLSID(REFCLSID clsid, LPCWSTR keyname, REGSAM access, HKEY *subkey)
1492 {
1493     static const WCHAR wszCLSIDSlash[] = {'C','L','S','I','D','\\',0};
1494     WCHAR path[CHARS_IN_GUID + ARRAYSIZE(wszCLSIDSlash) - 1];
1495     LONG res;
1496     HKEY key;
1497
1498     strcpyW(path, wszCLSIDSlash);
1499     StringFromGUID2(clsid, path + strlenW(wszCLSIDSlash), CHARS_IN_GUID);
1500     res = RegOpenKeyExW(HKEY_CLASSES_ROOT, path, 0, keyname ? KEY_READ : access, &key);
1501     if (res == ERROR_FILE_NOT_FOUND)
1502         return REGDB_E_CLASSNOTREG;
1503     else if (res != ERROR_SUCCESS)
1504         return REGDB_E_READREGDB;
1505
1506     if (!keyname)
1507     {
1508         *subkey = key;
1509         return S_OK;
1510     }
1511
1512     res = RegOpenKeyExW(key, keyname, 0, access, subkey);
1513     RegCloseKey(key);
1514     if (res == ERROR_FILE_NOT_FOUND)
1515         return REGDB_E_KEYMISSING;
1516     else if (res != ERROR_SUCCESS)
1517         return REGDB_E_READREGDB;
1518
1519     return S_OK;
1520 }
1521
1522 /* open HKCR\\AppId\\{string form of appid clsid} key */
1523 HRESULT COM_OpenKeyForAppIdFromCLSID(REFCLSID clsid, REGSAM access, HKEY *subkey)
1524 {
1525     static const WCHAR szAppId[] = { 'A','p','p','I','d',0 };
1526     static const WCHAR szAppIdKey[] = { 'A','p','p','I','d','\\',0 };
1527     DWORD res;
1528     WCHAR buf[CHARS_IN_GUID];
1529     WCHAR keyname[ARRAYSIZE(szAppIdKey) + CHARS_IN_GUID];
1530     DWORD size;
1531     HKEY hkey;
1532     DWORD type;
1533     HRESULT hr;
1534
1535     /* read the AppID value under the class's key */
1536     hr = COM_OpenKeyForCLSID(clsid, NULL, KEY_READ, &hkey);
1537     if (FAILED(hr))
1538         return hr;
1539
1540     size = sizeof(buf);
1541     res = RegQueryValueExW(hkey, szAppId, NULL, &type, (LPBYTE)buf, &size);
1542     RegCloseKey(hkey);
1543     if (res == ERROR_FILE_NOT_FOUND)
1544         return REGDB_E_KEYMISSING;
1545     else if (res != ERROR_SUCCESS || type!=REG_SZ)
1546         return REGDB_E_READREGDB;
1547
1548     strcpyW(keyname, szAppIdKey);
1549     strcatW(keyname, buf);
1550     res = RegOpenKeyExW(HKEY_CLASSES_ROOT, keyname, 0, access, subkey);
1551     if (res == ERROR_FILE_NOT_FOUND)
1552         return REGDB_E_KEYMISSING;
1553     else if (res != ERROR_SUCCESS)
1554         return REGDB_E_READREGDB;
1555
1556     return S_OK;
1557 }
1558
1559 /******************************************************************************
1560  *               ProgIDFromCLSID [OLE32.@]
1561  *
1562  * Converts a class id into the respective program ID.
1563  *
1564  * PARAMS
1565  *  clsid        [I] Class ID, as found in registry.
1566  *  ppszProgID [O] Associated ProgID.
1567  *
1568  * RETURNS
1569  *   S_OK
1570  *   E_OUTOFMEMORY
1571  *   REGDB_E_CLASSNOTREG if the given clsid has no associated ProgID
1572  */
1573 HRESULT WINAPI ProgIDFromCLSID(REFCLSID clsid, LPOLESTR *ppszProgID)
1574 {
1575     static const WCHAR wszProgID[] = {'P','r','o','g','I','D',0};
1576     HKEY     hkey;
1577     HRESULT  ret;
1578     LONG progidlen = 0;
1579
1580     if (!ppszProgID)
1581     {
1582         ERR("ppszProgId isn't optional\n");
1583         return E_INVALIDARG;
1584     }
1585
1586     *ppszProgID = NULL;
1587     ret = COM_OpenKeyForCLSID(clsid, wszProgID, KEY_READ, &hkey);
1588     if (FAILED(ret))
1589         return ret;
1590
1591     if (RegQueryValueW(hkey, NULL, NULL, &progidlen))
1592       ret = REGDB_E_CLASSNOTREG;
1593
1594     if (ret == S_OK)
1595     {
1596       *ppszProgID = CoTaskMemAlloc(progidlen * sizeof(WCHAR));
1597       if (*ppszProgID)
1598       {
1599         if (RegQueryValueW(hkey, NULL, *ppszProgID, &progidlen))
1600           ret = REGDB_E_CLASSNOTREG;
1601       }
1602       else
1603         ret = E_OUTOFMEMORY;
1604     }
1605
1606     RegCloseKey(hkey);
1607     return ret;
1608 }
1609
1610 /******************************************************************************
1611  *              CLSIDFromProgID [OLE32.@]
1612  *
1613  * Converts a program id into the respective GUID.
1614  *
1615  * PARAMS
1616  *  progid [I] Unicode program ID, as found in registry.
1617  *  clsid  [O] Associated CLSID.
1618  *
1619  * RETURNS
1620  *      Success: S_OK
1621  *  Failure: CO_E_CLASSSTRING - the given ProgID cannot be found.
1622  */
1623 HRESULT WINAPI CLSIDFromProgID(LPCOLESTR progid, LPCLSID clsid)
1624 {
1625     static const WCHAR clsidW[] = { '\\','C','L','S','I','D',0 };
1626     WCHAR buf2[CHARS_IN_GUID];
1627     LONG buf2len = sizeof(buf2);
1628     HKEY xhkey;
1629     WCHAR *buf;
1630
1631     if (!progid || !clsid)
1632     {
1633         ERR("neither progid (%p) nor clsid (%p) are optional\n", progid, clsid);
1634         return E_INVALIDARG;
1635     }
1636
1637     /* initialise clsid in case of failure */
1638     memset(clsid, 0, sizeof(*clsid));
1639
1640     buf = HeapAlloc( GetProcessHeap(),0,(strlenW(progid)+8) * sizeof(WCHAR) );
1641     strcpyW( buf, progid );
1642     strcatW( buf, clsidW );
1643     if (RegOpenKeyW(HKEY_CLASSES_ROOT,buf,&xhkey))
1644     {
1645         HeapFree(GetProcessHeap(),0,buf);
1646         WARN("couldn't open key for ProgID %s\n", debugstr_w(progid));
1647         return CO_E_CLASSSTRING;
1648     }
1649     HeapFree(GetProcessHeap(),0,buf);
1650
1651     if (RegQueryValueW(xhkey,NULL,buf2,&buf2len))
1652     {
1653         RegCloseKey(xhkey);
1654         WARN("couldn't query clsid value for ProgID %s\n", debugstr_w(progid));
1655         return CO_E_CLASSSTRING;
1656     }
1657     RegCloseKey(xhkey);
1658     return __CLSIDFromString(buf2,clsid);
1659 }
1660
1661
1662 /*****************************************************************************
1663  *             CoGetPSClsid [OLE32.@]
1664  *
1665  * Retrieves the CLSID of the proxy/stub factory that implements
1666  * IPSFactoryBuffer for the specified interface.
1667  *
1668  * PARAMS
1669  *  riid   [I] Interface whose proxy/stub CLSID is to be returned.
1670  *  pclsid [O] Where to store returned proxy/stub CLSID.
1671  * 
1672  * RETURNS
1673  *   S_OK
1674  *   E_OUTOFMEMORY
1675  *   REGDB_E_IIDNOTREG if no PSFactoryBuffer is associated with the IID, or it could not be parsed
1676  *
1677  * NOTES
1678  *
1679  * The standard marshaller activates the object with the CLSID
1680  * returned and uses the CreateProxy and CreateStub methods on its
1681  * IPSFactoryBuffer interface to construct the proxies and stubs for a
1682  * given object.
1683  *
1684  * CoGetPSClsid determines this CLSID by searching the
1685  * HKEY_CLASSES_ROOT\Interface\{string form of riid}\ProxyStubClsid32
1686  * in the registry and any interface id registered by
1687  * CoRegisterPSClsid within the current process.
1688  *
1689  * BUGS
1690  *
1691  * Native returns S_OK for interfaces with a key in HKCR\Interface, but
1692  * without a ProxyStubClsid32 key and leaves garbage in pclsid. This should be
1693  * considered a bug in native unless an application depends on this (unlikely).
1694  *
1695  * SEE ALSO
1696  *  CoRegisterPSClsid.
1697  */
1698 HRESULT WINAPI CoGetPSClsid(REFIID riid, CLSID *pclsid)
1699 {
1700     static const WCHAR wszInterface[] = {'I','n','t','e','r','f','a','c','e','\\',0};
1701     static const WCHAR wszPSC[] = {'\\','P','r','o','x','y','S','t','u','b','C','l','s','i','d','3','2',0};
1702     WCHAR path[ARRAYSIZE(wszInterface) - 1 + CHARS_IN_GUID - 1 + ARRAYSIZE(wszPSC)];
1703     WCHAR value[CHARS_IN_GUID];
1704     LONG len;
1705     HKEY hkey;
1706     APARTMENT *apt = COM_CurrentApt();
1707     struct registered_psclsid *registered_psclsid;
1708
1709     TRACE("() riid=%s, pclsid=%p\n", debugstr_guid(riid), pclsid);
1710
1711     if (!apt)
1712     {
1713         ERR("apartment not initialised\n");
1714         return CO_E_NOTINITIALIZED;
1715     }
1716
1717     if (!pclsid)
1718     {
1719         ERR("pclsid isn't optional\n");
1720         return E_INVALIDARG;
1721     }
1722
1723     EnterCriticalSection(&apt->cs);
1724
1725     LIST_FOR_EACH_ENTRY(registered_psclsid, &apt->psclsids, struct registered_psclsid, entry)
1726         if (IsEqualIID(&registered_psclsid->iid, riid))
1727         {
1728             *pclsid = registered_psclsid->clsid;
1729             LeaveCriticalSection(&apt->cs);
1730             return S_OK;
1731         }
1732
1733     LeaveCriticalSection(&apt->cs);
1734
1735     /* Interface\\{string form of riid}\\ProxyStubClsid32 */
1736     strcpyW(path, wszInterface);
1737     StringFromGUID2(riid, path + ARRAYSIZE(wszInterface) - 1, CHARS_IN_GUID);
1738     strcpyW(path + ARRAYSIZE(wszInterface) - 1 + CHARS_IN_GUID - 1, wszPSC);
1739
1740     /* Open the key.. */
1741     if (RegOpenKeyExW(HKEY_CLASSES_ROOT, path, 0, KEY_READ, &hkey))
1742     {
1743         WARN("No PSFactoryBuffer object is registered for IID %s\n", debugstr_guid(riid));
1744         return REGDB_E_IIDNOTREG;
1745     }
1746
1747     /* ... Once we have the key, query the registry to get the
1748        value of CLSID as a string, and convert it into a
1749        proper CLSID structure to be passed back to the app */
1750     len = sizeof(value);
1751     if (ERROR_SUCCESS != RegQueryValueW(hkey, NULL, value, &len))
1752     {
1753         RegCloseKey(hkey);
1754         return REGDB_E_IIDNOTREG;
1755     }
1756     RegCloseKey(hkey);
1757
1758     /* We have the CLSID we want back from the registry as a string, so
1759        let's convert it into a CLSID structure */
1760     if (CLSIDFromString(value, pclsid) != NOERROR)
1761         return REGDB_E_IIDNOTREG;
1762
1763     TRACE ("() Returning CLSID=%s\n", debugstr_guid(pclsid));
1764     return S_OK;
1765 }
1766
1767 /*****************************************************************************
1768  *             CoRegisterPSClsid [OLE32.@]
1769  *
1770  * Register a proxy/stub CLSID for the given interface in the current process
1771  * only.
1772  *
1773  * PARAMS
1774  *  riid   [I] Interface whose proxy/stub CLSID is to be registered.
1775  *  rclsid [I] CLSID of the proxy/stub.
1776  * 
1777  * RETURNS
1778  *   Success: S_OK
1779  *   Failure: E_OUTOFMEMORY
1780  *
1781  * NOTES
1782  *
1783  * This function does not add anything to the registry and the effects are
1784  * limited to the lifetime of the current process.
1785  *
1786  * SEE ALSO
1787  *  CoGetPSClsid.
1788  */
1789 HRESULT WINAPI CoRegisterPSClsid(REFIID riid, REFCLSID rclsid)
1790 {
1791     APARTMENT *apt = COM_CurrentApt();
1792     struct registered_psclsid *registered_psclsid;
1793
1794     TRACE("(%s, %s)\n", debugstr_guid(riid), debugstr_guid(rclsid));
1795
1796     if (!apt)
1797     {
1798         ERR("apartment not initialised\n");
1799         return CO_E_NOTINITIALIZED;
1800     }
1801
1802     EnterCriticalSection(&apt->cs);
1803
1804     LIST_FOR_EACH_ENTRY(registered_psclsid, &apt->psclsids, struct registered_psclsid, entry)
1805         if (IsEqualIID(&registered_psclsid->iid, riid))
1806         {
1807             registered_psclsid->clsid = *rclsid;
1808             LeaveCriticalSection(&apt->cs);
1809             return S_OK;
1810         }
1811
1812     registered_psclsid = HeapAlloc(GetProcessHeap(), 0, sizeof(struct registered_psclsid));
1813     if (!registered_psclsid)
1814     {
1815         LeaveCriticalSection(&apt->cs);
1816         return E_OUTOFMEMORY;
1817     }
1818
1819     registered_psclsid->iid = *riid;
1820     registered_psclsid->clsid = *rclsid;
1821     list_add_head(&apt->psclsids, &registered_psclsid->entry);
1822
1823     LeaveCriticalSection(&apt->cs);
1824
1825     return S_OK;
1826 }
1827
1828
1829 /***
1830  * COM_GetRegisteredClassObject
1831  *
1832  * This internal method is used to scan the registered class list to
1833  * find a class object.
1834  *
1835  * Params:
1836  *   rclsid        Class ID of the class to find.
1837  *   dwClsContext  Class context to match.
1838  *   ppv           [out] returns a pointer to the class object. Complying
1839  *                 to normal COM usage, this method will increase the
1840  *                 reference count on this object.
1841  */
1842 static HRESULT COM_GetRegisteredClassObject(const struct apartment *apt, REFCLSID rclsid,
1843                                             DWORD dwClsContext, LPUNKNOWN* ppUnk)
1844 {
1845   HRESULT hr = S_FALSE;
1846   RegisteredClass *curClass;
1847
1848   EnterCriticalSection( &csRegisteredClassList );
1849
1850   LIST_FOR_EACH_ENTRY(curClass, &RegisteredClassList, RegisteredClass, entry)
1851   {
1852     /*
1853      * Check if we have a match on the class ID and context.
1854      */
1855     if ((apt->oxid == curClass->apartment_id) &&
1856         (dwClsContext & curClass->runContext) &&
1857         IsEqualGUID(&(curClass->classIdentifier), rclsid))
1858     {
1859       /*
1860        * We have a match, return the pointer to the class object.
1861        */
1862       *ppUnk = curClass->classObject;
1863
1864       IUnknown_AddRef(curClass->classObject);
1865
1866       hr = S_OK;
1867       break;
1868     }
1869   }
1870
1871   LeaveCriticalSection( &csRegisteredClassList );
1872
1873   return hr;
1874 }
1875
1876 /******************************************************************************
1877  *              CoRegisterClassObject   [OLE32.@]
1878  *
1879  * Registers the class object for a given class ID. Servers housed in EXE
1880  * files use this method instead of exporting DllGetClassObject to allow
1881  * other code to connect to their objects.
1882  *
1883  * PARAMS
1884  *  rclsid       [I] CLSID of the object to register.
1885  *  pUnk         [I] IUnknown of the object.
1886  *  dwClsContext [I] CLSCTX flags indicating the context in which to run the executable.
1887  *  flags        [I] REGCLS flags indicating how connections are made.
1888  *  lpdwRegister [I] A unique cookie that can be passed to CoRevokeClassObject.
1889  *
1890  * RETURNS
1891  *   S_OK on success,
1892  *   E_INVALIDARG if lpdwRegister or pUnk are NULL,
1893  *   CO_E_OBJISREG if the object is already registered. We should not return this.
1894  *
1895  * SEE ALSO
1896  *   CoRevokeClassObject, CoGetClassObject
1897  *
1898  * NOTES
1899  *  In-process objects are only registered for the current apartment.
1900  *  CoGetClassObject() and CoCreateInstance() will not return objects registered
1901  *  in other apartments.
1902  *
1903  * BUGS
1904  *  MSDN claims that multiple interface registrations are legal, but we
1905  *  can't do that with our current implementation.
1906  */
1907 HRESULT WINAPI CoRegisterClassObject(
1908     REFCLSID rclsid,
1909     LPUNKNOWN pUnk,
1910     DWORD dwClsContext,
1911     DWORD flags,
1912     LPDWORD lpdwRegister)
1913 {
1914   RegisteredClass* newClass;
1915   LPUNKNOWN        foundObject;
1916   HRESULT          hr;
1917   APARTMENT *apt;
1918
1919   TRACE("(%s,%p,0x%08x,0x%08x,%p)\n",
1920         debugstr_guid(rclsid),pUnk,dwClsContext,flags,lpdwRegister);
1921
1922   if ( (lpdwRegister==0) || (pUnk==0) )
1923     return E_INVALIDARG;
1924
1925   apt = COM_CurrentApt();
1926   if (!apt)
1927   {
1928       ERR("COM was not initialized\n");
1929       return CO_E_NOTINITIALIZED;
1930   }
1931
1932   *lpdwRegister = 0;
1933
1934   /* REGCLS_MULTIPLEUSE implies registering as inproc server. This is what
1935    * differentiates the flag from REGCLS_MULTI_SEPARATE. */
1936   if (flags & REGCLS_MULTIPLEUSE)
1937     dwClsContext |= CLSCTX_INPROC_SERVER;
1938
1939   /*
1940    * First, check if the class is already registered.
1941    * If it is, this should cause an error.
1942    */
1943   hr = COM_GetRegisteredClassObject(apt, rclsid, dwClsContext, &foundObject);
1944   if (hr == S_OK) {
1945     if (flags & REGCLS_MULTIPLEUSE) {
1946       if (dwClsContext & CLSCTX_LOCAL_SERVER)
1947         hr = CoLockObjectExternal(foundObject, TRUE, FALSE);
1948       IUnknown_Release(foundObject);
1949       return hr;
1950     }
1951     IUnknown_Release(foundObject);
1952     ERR("object already registered for class %s\n", debugstr_guid(rclsid));
1953     return CO_E_OBJISREG;
1954   }
1955
1956   newClass = HeapAlloc(GetProcessHeap(), 0, sizeof(RegisteredClass));
1957   if ( newClass == NULL )
1958     return E_OUTOFMEMORY;
1959
1960   newClass->classIdentifier = *rclsid;
1961   newClass->apartment_id    = apt->oxid;
1962   newClass->runContext      = dwClsContext;
1963   newClass->connectFlags    = flags;
1964   newClass->pMarshaledData  = NULL;
1965   newClass->RpcRegistration = NULL;
1966
1967   /*
1968    * Use the address of the chain node as the cookie since we are sure it's
1969    * unique. FIXME: not on 64-bit platforms.
1970    */
1971   newClass->dwCookie        = (DWORD)newClass;
1972
1973   /*
1974    * Since we're making a copy of the object pointer, we have to increase its
1975    * reference count.
1976    */
1977   newClass->classObject     = pUnk;
1978   IUnknown_AddRef(newClass->classObject);
1979
1980   EnterCriticalSection( &csRegisteredClassList );
1981   list_add_tail(&RegisteredClassList, &newClass->entry);
1982   LeaveCriticalSection( &csRegisteredClassList );
1983
1984   *lpdwRegister = newClass->dwCookie;
1985
1986   if (dwClsContext & CLSCTX_LOCAL_SERVER) {
1987       hr = CreateStreamOnHGlobal(0, TRUE, &newClass->pMarshaledData);
1988       if (hr) {
1989           FIXME("Failed to create stream on hglobal, %x\n", hr);
1990           return hr;
1991       }
1992       hr = CoMarshalInterface(newClass->pMarshaledData, &IID_IClassFactory,
1993                               newClass->classObject, MSHCTX_LOCAL, NULL,
1994                               MSHLFLAGS_TABLESTRONG);
1995       if (hr) {
1996           FIXME("CoMarshalInterface failed, %x!\n",hr);
1997           return hr;
1998       }
1999
2000       hr = RPC_StartLocalServer(&newClass->classIdentifier,
2001                                 newClass->pMarshaledData,
2002                                 flags & (REGCLS_MULTIPLEUSE|REGCLS_MULTI_SEPARATE),
2003                                 &newClass->RpcRegistration);
2004   }
2005   return S_OK;
2006 }
2007
2008 static void COM_RevokeRegisteredClassObject(RegisteredClass *curClass)
2009 {
2010     list_remove(&curClass->entry);
2011
2012     if (curClass->runContext & CLSCTX_LOCAL_SERVER)
2013         RPC_StopLocalServer(curClass->RpcRegistration);
2014
2015     /*
2016      * Release the reference to the class object.
2017      */
2018     IUnknown_Release(curClass->classObject);
2019
2020     if (curClass->pMarshaledData)
2021     {
2022         LARGE_INTEGER zero;
2023         memset(&zero, 0, sizeof(zero));
2024         IStream_Seek(curClass->pMarshaledData, zero, STREAM_SEEK_SET, NULL);
2025         CoReleaseMarshalData(curClass->pMarshaledData);
2026         IStream_Release(curClass->pMarshaledData);
2027     }
2028
2029     HeapFree(GetProcessHeap(), 0, curClass);
2030 }
2031
2032 static void COM_RevokeAllClasses(const struct apartment *apt)
2033 {
2034   RegisteredClass *curClass, *cursor;
2035
2036   EnterCriticalSection( &csRegisteredClassList );
2037
2038   LIST_FOR_EACH_ENTRY_SAFE(curClass, cursor, &RegisteredClassList, RegisteredClass, entry)
2039   {
2040     if (curClass->apartment_id == apt->oxid)
2041       COM_RevokeRegisteredClassObject(curClass);
2042   }
2043
2044   LeaveCriticalSection( &csRegisteredClassList );
2045 }
2046
2047 /***********************************************************************
2048  *           CoRevokeClassObject [OLE32.@]
2049  *
2050  * Removes a class object from the class registry.
2051  *
2052  * PARAMS
2053  *  dwRegister [I] Cookie returned from CoRegisterClassObject().
2054  *
2055  * RETURNS
2056  *  Success: S_OK.
2057  *  Failure: HRESULT code.
2058  *
2059  * NOTES
2060  *  Must be called from the same apartment that called CoRegisterClassObject(),
2061  *  otherwise it will fail with RPC_E_WRONG_THREAD.
2062  *
2063  * SEE ALSO
2064  *  CoRegisterClassObject
2065  */
2066 HRESULT WINAPI CoRevokeClassObject(
2067         DWORD dwRegister)
2068 {
2069   HRESULT hr = E_INVALIDARG;
2070   RegisteredClass *curClass;
2071   APARTMENT *apt;
2072
2073   TRACE("(%08x)\n",dwRegister);
2074
2075   apt = COM_CurrentApt();
2076   if (!apt)
2077   {
2078     ERR("COM was not initialized\n");
2079     return CO_E_NOTINITIALIZED;
2080   }
2081
2082   EnterCriticalSection( &csRegisteredClassList );
2083
2084   LIST_FOR_EACH_ENTRY(curClass, &RegisteredClassList, RegisteredClass, entry)
2085   {
2086     /*
2087      * Check if we have a match on the cookie.
2088      */
2089     if (curClass->dwCookie == dwRegister)
2090     {
2091       if (curClass->apartment_id == apt->oxid)
2092       {
2093           COM_RevokeRegisteredClassObject(curClass);
2094           hr = S_OK;
2095       }
2096       else
2097       {
2098           ERR("called from wrong apartment, should be called from %s\n",
2099               wine_dbgstr_longlong(curClass->apartment_id));
2100           hr = RPC_E_WRONG_THREAD;
2101       }
2102       break;
2103     }
2104   }
2105
2106   LeaveCriticalSection( &csRegisteredClassList );
2107
2108   return hr;
2109 }
2110
2111 /***********************************************************************
2112  *      COM_RegReadPath [internal]
2113  *
2114  *      Reads a registry value and expands it when necessary
2115  */
2116 static DWORD COM_RegReadPath(HKEY hkeyroot, const WCHAR *keyname, const WCHAR *valuename, WCHAR * dst, DWORD dstlen)
2117 {
2118         DWORD ret;
2119         HKEY key;
2120         DWORD keytype;
2121         WCHAR src[MAX_PATH];
2122         DWORD dwLength = dstlen * sizeof(WCHAR);
2123
2124         if((ret = RegOpenKeyExW(hkeyroot, keyname, 0, KEY_READ, &key)) == ERROR_SUCCESS) {
2125           if( (ret = RegQueryValueExW(key, NULL, NULL, &keytype, (LPBYTE)src, &dwLength)) == ERROR_SUCCESS ) {
2126             if (keytype == REG_EXPAND_SZ) {
2127               if (dstlen <= ExpandEnvironmentStringsW(src, dst, dstlen)) ret = ERROR_MORE_DATA;
2128             } else {
2129               lstrcpynW(dst, src, dstlen);
2130             }
2131           }
2132           RegCloseKey (key);
2133         }
2134         return ret;
2135 }
2136
2137 static void get_threading_model(HKEY key, LPWSTR value, DWORD len)
2138 {
2139     static const WCHAR wszThreadingModel[] = {'T','h','r','e','a','d','i','n','g','M','o','d','e','l',0};
2140     DWORD keytype;
2141     DWORD ret;
2142     DWORD dwLength = len * sizeof(WCHAR);
2143
2144     ret = RegQueryValueExW(key, wszThreadingModel, NULL, &keytype, (LPBYTE)value, &dwLength);
2145     if ((ret != ERROR_SUCCESS) || (keytype != REG_SZ))
2146         value[0] = '\0';
2147 }
2148
2149 static HRESULT get_inproc_class_object(APARTMENT *apt, HKEY hkeydll,
2150                                        REFCLSID rclsid, REFIID riid,
2151                                        BOOL hostifnecessary, void **ppv)
2152 {
2153     WCHAR dllpath[MAX_PATH+1];
2154     BOOL apartment_threaded;
2155
2156     if (hostifnecessary)
2157     {
2158         static const WCHAR wszApartment[] = {'A','p','a','r','t','m','e','n','t',0};
2159         static const WCHAR wszFree[] = {'F','r','e','e',0};
2160         static const WCHAR wszBoth[] = {'B','o','t','h',0};
2161         WCHAR threading_model[10 /* strlenW(L"apartment")+1 */];
2162
2163         get_threading_model(hkeydll, threading_model, ARRAYSIZE(threading_model));
2164         /* "Apartment" */
2165         if (!strcmpiW(threading_model, wszApartment))
2166         {
2167             apartment_threaded = TRUE;
2168             if (apt->multi_threaded)
2169                 return apartment_hostobject_in_hostapt(apt, FALSE, FALSE, hkeydll, rclsid, riid, ppv);
2170         }
2171         /* "Free" */
2172         else if (!strcmpiW(threading_model, wszFree))
2173         {
2174             apartment_threaded = FALSE;
2175             if (!apt->multi_threaded)
2176                 return apartment_hostobject_in_hostapt(apt, TRUE, FALSE, hkeydll, rclsid, riid, ppv);
2177         }
2178         /* everything except "Apartment", "Free" and "Both" */
2179         else if (strcmpiW(threading_model, wszBoth))
2180         {
2181             apartment_threaded = TRUE;
2182             /* everything else is main-threaded */
2183             if (threading_model[0])
2184                 FIXME("unrecognised threading model %s for object %s, should be main-threaded?\n",
2185                     debugstr_w(threading_model), debugstr_guid(rclsid));
2186
2187             if (apt->multi_threaded || !apt->main)
2188                 return apartment_hostobject_in_hostapt(apt, FALSE, TRUE, hkeydll, rclsid, riid, ppv);
2189         }
2190         else
2191             apartment_threaded = FALSE;
2192     }
2193     else
2194         apartment_threaded = !apt->multi_threaded;
2195
2196     if (COM_RegReadPath(hkeydll, NULL, NULL, dllpath, ARRAYSIZE(dllpath)) != ERROR_SUCCESS)
2197     {
2198         /* failure: CLSID is not found in registry */
2199         WARN("class %s not registered inproc\n", debugstr_guid(rclsid));
2200         return REGDB_E_CLASSNOTREG;
2201     }
2202
2203     return apartment_getclassobject(apt, dllpath, apartment_threaded,
2204                                     rclsid, riid, ppv);
2205 }
2206
2207 /***********************************************************************
2208  *           CoGetClassObject [OLE32.@]
2209  *
2210  * Creates an object of the specified class.
2211  *
2212  * PARAMS
2213  *  rclsid       [I] Class ID to create an instance of.
2214  *  dwClsContext [I] Flags to restrict the location of the created instance.
2215  *  pServerInfo  [I] Optional. Details for connecting to a remote server.
2216  *  iid          [I] The ID of the interface of the instance to return.
2217  *  ppv          [O] On returns, contains a pointer to the specified interface of the object.
2218  *
2219  * RETURNS
2220  *  Success: S_OK
2221  *  Failure: HRESULT code.
2222  *
2223  * NOTES
2224  *  The dwClsContext parameter can be one or more of the following:
2225  *| CLSCTX_INPROC_SERVER - Use an in-process server, such as from a DLL.
2226  *| CLSCTX_INPROC_HANDLER - Use an in-process object which handles certain functions for an object running in another process.
2227  *| CLSCTX_LOCAL_SERVER - Connect to an object running in another process.
2228  *| CLSCTX_REMOTE_SERVER - Connect to an object running on another machine.
2229  *
2230  * SEE ALSO
2231  *  CoCreateInstance()
2232  */
2233 HRESULT WINAPI CoGetClassObject(
2234     REFCLSID rclsid, DWORD dwClsContext, COSERVERINFO *pServerInfo,
2235     REFIID iid, LPVOID *ppv)
2236 {
2237     LPUNKNOWN   regClassObject;
2238     HRESULT     hres = E_UNEXPECTED;
2239     APARTMENT  *apt;
2240
2241     TRACE("\n\tCLSID:\t%s,\n\tIID:\t%s\n", debugstr_guid(rclsid), debugstr_guid(iid));
2242
2243     if (!ppv)
2244         return E_INVALIDARG;
2245
2246     *ppv = NULL;
2247
2248     apt = COM_CurrentApt();
2249     if (!apt)
2250     {
2251         ERR("apartment not initialised\n");
2252         return CO_E_NOTINITIALIZED;
2253     }
2254
2255     if (pServerInfo) {
2256         FIXME("\tpServerInfo: name=%s\n",debugstr_w(pServerInfo->pwszName));
2257         FIXME("\t\tpAuthInfo=%p\n",pServerInfo->pAuthInfo);
2258     }
2259
2260     /*
2261      * First, try and see if we can't match the class ID with one of the
2262      * registered classes.
2263      */
2264     if (S_OK == COM_GetRegisteredClassObject(apt, rclsid, dwClsContext,
2265                                              &regClassObject))
2266     {
2267       /* Get the required interface from the retrieved pointer. */
2268       hres = IUnknown_QueryInterface(regClassObject, iid, ppv);
2269
2270       /*
2271        * Since QI got another reference on the pointer, we want to release the
2272        * one we already have. If QI was unsuccessful, this will release the object. This
2273        * is good since we are not returning it in the "out" parameter.
2274        */
2275       IUnknown_Release(regClassObject);
2276
2277       return hres;
2278     }
2279
2280     /* First try in-process server */
2281     if (CLSCTX_INPROC_SERVER & dwClsContext)
2282     {
2283         static const WCHAR wszInprocServer32[] = {'I','n','p','r','o','c','S','e','r','v','e','r','3','2',0};
2284         HKEY hkey;
2285
2286         if (IsEqualCLSID(rclsid, &CLSID_InProcFreeMarshaler))
2287             return FTMarshalCF_Create(iid, ppv);
2288
2289         hres = COM_OpenKeyForCLSID(rclsid, wszInprocServer32, KEY_READ, &hkey);
2290         if (FAILED(hres))
2291         {
2292             if (hres == REGDB_E_CLASSNOTREG)
2293                 ERR("class %s not registered\n", debugstr_guid(rclsid));
2294             else if (hres == REGDB_E_KEYMISSING)
2295             {
2296                 WARN("class %s not registered as in-proc server\n", debugstr_guid(rclsid));
2297                 hres = REGDB_E_CLASSNOTREG;
2298             }
2299         }
2300
2301         if (SUCCEEDED(hres))
2302         {
2303             hres = get_inproc_class_object(apt, hkey, rclsid, iid,
2304                 !(dwClsContext & WINE_CLSCTX_DONT_HOST), ppv);
2305             RegCloseKey(hkey);
2306         }
2307
2308         /* return if we got a class, otherwise fall through to one of the
2309          * other types */
2310         if (SUCCEEDED(hres))
2311             return hres;
2312     }
2313
2314     /* Next try in-process handler */
2315     if (CLSCTX_INPROC_HANDLER & dwClsContext)
2316     {
2317         static const WCHAR wszInprocHandler32[] = {'I','n','p','r','o','c','H','a','n','d','l','e','r','3','2',0};
2318         HKEY hkey;
2319
2320         hres = COM_OpenKeyForCLSID(rclsid, wszInprocHandler32, KEY_READ, &hkey);
2321         if (FAILED(hres))
2322         {
2323             if (hres == REGDB_E_CLASSNOTREG)
2324                 ERR("class %s not registered\n", debugstr_guid(rclsid));
2325             else if (hres == REGDB_E_KEYMISSING)
2326             {
2327                 WARN("class %s not registered in-proc handler\n", debugstr_guid(rclsid));
2328                 hres = REGDB_E_CLASSNOTREG;
2329             }
2330         }
2331
2332         if (SUCCEEDED(hres))
2333         {
2334             hres = get_inproc_class_object(apt, hkey, rclsid, iid,
2335                 !(dwClsContext & WINE_CLSCTX_DONT_HOST), ppv);
2336             RegCloseKey(hkey);
2337         }
2338
2339         /* return if we got a class, otherwise fall through to one of the
2340          * other types */
2341         if (SUCCEEDED(hres))
2342             return hres;
2343     }
2344
2345     /* Next try out of process */
2346     if (CLSCTX_LOCAL_SERVER & dwClsContext)
2347     {
2348         hres = RPC_GetLocalClassObject(rclsid,iid,ppv);
2349         if (SUCCEEDED(hres))
2350             return hres;
2351     }
2352
2353     /* Finally try remote: this requires networked DCOM (a lot of work) */
2354     if (CLSCTX_REMOTE_SERVER & dwClsContext)
2355     {
2356         FIXME ("CLSCTX_REMOTE_SERVER not supported\n");
2357         hres = E_NOINTERFACE;
2358     }
2359
2360     if (FAILED(hres))
2361         ERR("no class object %s could be created for context 0x%x\n",
2362             debugstr_guid(rclsid), dwClsContext);
2363     return hres;
2364 }
2365
2366 /***********************************************************************
2367  *        CoResumeClassObjects (OLE32.@)
2368  *
2369  * Resumes all class objects registered with REGCLS_SUSPENDED.
2370  *
2371  * RETURNS
2372  *  Success: S_OK.
2373  *  Failure: HRESULT code.
2374  */
2375 HRESULT WINAPI CoResumeClassObjects(void)
2376 {
2377        FIXME("stub\n");
2378         return S_OK;
2379 }
2380
2381 /***********************************************************************
2382  *           CoCreateInstance [OLE32.@]
2383  *
2384  * Creates an instance of the specified class.
2385  *
2386  * PARAMS
2387  *  rclsid       [I] Class ID to create an instance of.
2388  *  pUnkOuter    [I] Optional outer unknown to allow aggregation with another object.
2389  *  dwClsContext [I] Flags to restrict the location of the created instance.
2390  *  iid          [I] The ID of the interface of the instance to return.
2391  *  ppv          [O] On returns, contains a pointer to the specified interface of the instance.
2392  *
2393  * RETURNS
2394  *  Success: S_OK
2395  *  Failure: HRESULT code.
2396  *
2397  * NOTES
2398  *  The dwClsContext parameter can be one or more of the following:
2399  *| CLSCTX_INPROC_SERVER - Use an in-process server, such as from a DLL.
2400  *| CLSCTX_INPROC_HANDLER - Use an in-process object which handles certain functions for an object running in another process.
2401  *| CLSCTX_LOCAL_SERVER - Connect to an object running in another process.
2402  *| CLSCTX_REMOTE_SERVER - Connect to an object running on another machine.
2403  *
2404  * Aggregation is the concept of deferring the IUnknown of an object to another
2405  * object. This allows a separate object to behave as though it was part of
2406  * the object and to allow this the pUnkOuter parameter can be set. Note that
2407  * not all objects support having an outer of unknown.
2408  *
2409  * SEE ALSO
2410  *  CoGetClassObject()
2411  */
2412 HRESULT WINAPI CoCreateInstance(
2413         REFCLSID rclsid,
2414         LPUNKNOWN pUnkOuter,
2415         DWORD dwClsContext,
2416         REFIID iid,
2417         LPVOID *ppv)
2418 {
2419   HRESULT hres;
2420   LPCLASSFACTORY lpclf = 0;
2421
2422   TRACE("(rclsid=%s, pUnkOuter=%p, dwClsContext=%08x, riid=%s, ppv=%p)\n", debugstr_guid(rclsid),
2423         pUnkOuter, dwClsContext, debugstr_guid(iid), ppv);
2424
2425   /*
2426    * Sanity check
2427    */
2428   if (ppv==0)
2429     return E_POINTER;
2430
2431   /*
2432    * Initialize the "out" parameter
2433    */
2434   *ppv = 0;
2435
2436   if (!COM_CurrentApt())
2437   {
2438       ERR("apartment not initialised\n");
2439       return CO_E_NOTINITIALIZED;
2440   }
2441
2442   /*
2443    * The Standard Global Interface Table (GIT) object is a process-wide singleton.
2444    * Rather than create a class factory, we can just check for it here
2445    */
2446   if (IsEqualIID(rclsid, &CLSID_StdGlobalInterfaceTable)) {
2447     if (StdGlobalInterfaceTableInstance == NULL)
2448       StdGlobalInterfaceTableInstance = StdGlobalInterfaceTable_Construct();
2449     hres = IGlobalInterfaceTable_QueryInterface( (IGlobalInterfaceTable*) StdGlobalInterfaceTableInstance, iid, ppv);
2450     if (hres) return hres;
2451
2452     TRACE("Retrieved GIT (%p)\n", *ppv);
2453     return S_OK;
2454   }
2455
2456   /*
2457    * Get a class factory to construct the object we want.
2458    */
2459   hres = CoGetClassObject(rclsid,
2460                           dwClsContext,
2461                           NULL,
2462                           &IID_IClassFactory,
2463                           (LPVOID)&lpclf);
2464
2465   if (FAILED(hres))
2466     return hres;
2467
2468   /*
2469    * Create the object and don't forget to release the factory
2470    */
2471         hres = IClassFactory_CreateInstance(lpclf, pUnkOuter, iid, ppv);
2472         IClassFactory_Release(lpclf);
2473         if(FAILED(hres))
2474         {
2475           if (hres == CLASS_E_NOAGGREGATION && pUnkOuter)
2476               FIXME("Class %s does not support aggregation\n", debugstr_guid(rclsid));
2477           else
2478               FIXME("no instance created for interface %s of class %s, hres is 0x%08x\n", debugstr_guid(iid), debugstr_guid(rclsid),hres);
2479         }
2480
2481         return hres;
2482 }
2483
2484 /***********************************************************************
2485  *           CoCreateInstanceEx [OLE32.@]
2486  */
2487 HRESULT WINAPI CoCreateInstanceEx(
2488   REFCLSID      rclsid,
2489   LPUNKNOWN     pUnkOuter,
2490   DWORD         dwClsContext,
2491   COSERVERINFO* pServerInfo,
2492   ULONG         cmq,
2493   MULTI_QI*     pResults)
2494 {
2495   IUnknown* pUnk = NULL;
2496   HRESULT   hr;
2497   ULONG     index;
2498   ULONG     successCount = 0;
2499
2500   /*
2501    * Sanity check
2502    */
2503   if ( (cmq==0) || (pResults==NULL))
2504     return E_INVALIDARG;
2505
2506   if (pServerInfo!=NULL)
2507     FIXME("() non-NULL pServerInfo not supported!\n");
2508
2509   /*
2510    * Initialize all the "out" parameters.
2511    */
2512   for (index = 0; index < cmq; index++)
2513   {
2514     pResults[index].pItf = NULL;
2515     pResults[index].hr   = E_NOINTERFACE;
2516   }
2517
2518   /*
2519    * Get the object and get its IUnknown pointer.
2520    */
2521   hr = CoCreateInstance(rclsid,
2522                         pUnkOuter,
2523                         dwClsContext,
2524                         &IID_IUnknown,
2525                         (VOID**)&pUnk);
2526
2527   if (hr)
2528     return hr;
2529
2530   /*
2531    * Then, query for all the interfaces requested.
2532    */
2533   for (index = 0; index < cmq; index++)
2534   {
2535     pResults[index].hr = IUnknown_QueryInterface(pUnk,
2536                                                  pResults[index].pIID,
2537                                                  (VOID**)&(pResults[index].pItf));
2538
2539     if (pResults[index].hr == S_OK)
2540       successCount++;
2541   }
2542
2543   /*
2544    * Release our temporary unknown pointer.
2545    */
2546   IUnknown_Release(pUnk);
2547
2548   if (successCount == 0)
2549     return E_NOINTERFACE;
2550
2551   if (successCount!=cmq)
2552     return CO_S_NOTALLINTERFACES;
2553
2554   return S_OK;
2555 }
2556
2557 /***********************************************************************
2558  *           CoLoadLibrary (OLE32.@)
2559  *
2560  * Loads a library.
2561  *
2562  * PARAMS
2563  *  lpszLibName [I] Path to library.
2564  *  bAutoFree   [I] Whether the library should automatically be freed.
2565  *
2566  * RETURNS
2567  *  Success: Handle to loaded library.
2568  *  Failure: NULL.
2569  *
2570  * SEE ALSO
2571  *  CoFreeLibrary, CoFreeAllLibraries, CoFreeUnusedLibraries
2572  */
2573 HINSTANCE WINAPI CoLoadLibrary(LPOLESTR lpszLibName, BOOL bAutoFree)
2574 {
2575     TRACE("(%s, %d)\n", debugstr_w(lpszLibName), bAutoFree);
2576
2577     return LoadLibraryExW(lpszLibName, 0, LOAD_WITH_ALTERED_SEARCH_PATH);
2578 }
2579
2580 /***********************************************************************
2581  *           CoFreeLibrary [OLE32.@]
2582  *
2583  * Unloads a library from memory.
2584  *
2585  * PARAMS
2586  *  hLibrary [I] Handle to library to unload.
2587  *
2588  * RETURNS
2589  *  Nothing
2590  *
2591  * SEE ALSO
2592  *  CoLoadLibrary, CoFreeAllLibraries, CoFreeUnusedLibraries
2593  */
2594 void WINAPI CoFreeLibrary(HINSTANCE hLibrary)
2595 {
2596     FreeLibrary(hLibrary);
2597 }
2598
2599
2600 /***********************************************************************
2601  *           CoFreeAllLibraries [OLE32.@]
2602  *
2603  * Function for backwards compatibility only. Does nothing.
2604  *
2605  * RETURNS
2606  *  Nothing.
2607  *
2608  * SEE ALSO
2609  *  CoLoadLibrary, CoFreeLibrary, CoFreeUnusedLibraries
2610  */
2611 void WINAPI CoFreeAllLibraries(void)
2612 {
2613     /* NOP */
2614 }
2615
2616 /***********************************************************************
2617  *           CoFreeUnusedLibrariesEx [OLE32.@]
2618  *
2619  * Frees any previously unused libraries whose delay has expired and marks
2620  * currently unused libraries for unloading. Unused are identified as those that
2621  * return S_OK from their DllCanUnloadNow function.
2622  *
2623  * PARAMS
2624  *  dwUnloadDelay [I] Unload delay in milliseconds.
2625  *  dwReserved    [I] Reserved. Set to 0.
2626  *
2627  * RETURNS
2628  *  Nothing.
2629  *
2630  * SEE ALSO
2631  *  CoLoadLibrary, CoFreeAllLibraries, CoFreeLibrary
2632  */
2633 void WINAPI CoFreeUnusedLibrariesEx(DWORD dwUnloadDelay, DWORD dwReserved)
2634 {
2635     struct apartment *apt = COM_CurrentApt();
2636     if (!apt)
2637     {
2638         ERR("apartment not initialised\n");
2639         return;
2640     }
2641
2642     apartment_freeunusedlibraries(apt, dwUnloadDelay);
2643 }
2644
2645 /***********************************************************************
2646  *           CoFreeUnusedLibraries [OLE32.@]
2647  *
2648  * Frees any unused libraries. Unused are identified as those that return
2649  * S_OK from their DllCanUnloadNow function.
2650  *
2651  * RETURNS
2652  *  Nothing.
2653  *
2654  * SEE ALSO
2655  *  CoLoadLibrary, CoFreeAllLibraries, CoFreeLibrary
2656  */
2657 void WINAPI CoFreeUnusedLibraries(void)
2658 {
2659     CoFreeUnusedLibrariesEx(INFINITE, 0);
2660 }
2661
2662 /***********************************************************************
2663  *           CoFileTimeNow [OLE32.@]
2664  *
2665  * Retrieves the current time in FILETIME format.
2666  *
2667  * PARAMS
2668  *  lpFileTime [O] The current time.
2669  *
2670  * RETURNS
2671  *      S_OK.
2672  */
2673 HRESULT WINAPI CoFileTimeNow( FILETIME *lpFileTime )
2674 {
2675     GetSystemTimeAsFileTime( lpFileTime );
2676     return S_OK;
2677 }
2678
2679 /******************************************************************************
2680  *              CoLockObjectExternal    [OLE32.@]
2681  *
2682  * Increments or decrements the external reference count of a stub object.
2683  *
2684  * PARAMS
2685  *  pUnk                [I] Stub object.
2686  *  fLock               [I] If TRUE then increments the external ref-count,
2687  *                          otherwise decrements.
2688  *  fLastUnlockReleases [I] If TRUE then the last unlock has the effect of
2689  *                          calling CoDisconnectObject.
2690  *
2691  * RETURNS
2692  *  Success: S_OK.
2693  *  Failure: HRESULT code.
2694  *
2695  * NOTES
2696  *  If fLock is TRUE and an object is passed in that doesn't have a stub
2697  *  manager then a new stub manager is created for the object.
2698  */
2699 HRESULT WINAPI CoLockObjectExternal(
2700     LPUNKNOWN pUnk,
2701     BOOL fLock,
2702     BOOL fLastUnlockReleases)
2703 {
2704     struct stub_manager *stubmgr;
2705     struct apartment *apt;
2706
2707     TRACE("pUnk=%p, fLock=%s, fLastUnlockReleases=%s\n",
2708           pUnk, fLock ? "TRUE" : "FALSE", fLastUnlockReleases ? "TRUE" : "FALSE");
2709
2710     apt = COM_CurrentApt();
2711     if (!apt) return CO_E_NOTINITIALIZED;
2712
2713     stubmgr = get_stub_manager_from_object(apt, pUnk);
2714     
2715     if (stubmgr)
2716     {
2717         if (fLock)
2718             stub_manager_ext_addref(stubmgr, 1, FALSE);
2719         else
2720             stub_manager_ext_release(stubmgr, 1, FALSE, fLastUnlockReleases);
2721         
2722         stub_manager_int_release(stubmgr);
2723
2724         return S_OK;
2725     }
2726     else if (fLock)
2727     {
2728         stubmgr = new_stub_manager(apt, pUnk);
2729
2730         if (stubmgr)
2731         {
2732             stub_manager_ext_addref(stubmgr, 1, FALSE);
2733             stub_manager_int_release(stubmgr);
2734         }
2735
2736         return S_OK;
2737     }
2738     else
2739     {
2740         WARN("stub object not found %p\n", pUnk);
2741         /* Note: native is pretty broken here because it just silently
2742          * fails, without returning an appropriate error code, making apps
2743          * think that the object was disconnected, when it actually wasn't */
2744         return S_OK;
2745     }
2746 }
2747
2748 /***********************************************************************
2749  *           CoInitializeWOW (OLE32.@)
2750  *
2751  * WOW equivalent of CoInitialize?
2752  *
2753  * PARAMS
2754  *  x [I] Unknown.
2755  *  y [I] Unknown.
2756  *
2757  * RETURNS
2758  *  Unknown.
2759  */
2760 HRESULT WINAPI CoInitializeWOW(DWORD x,DWORD y)
2761 {
2762     FIXME("(0x%08x,0x%08x),stub!\n",x,y);
2763     return 0;
2764 }
2765
2766 /***********************************************************************
2767  *           CoGetState [OLE32.@]
2768  *
2769  * Retrieves the thread state object previously stored by CoSetState().
2770  *
2771  * PARAMS
2772  *  ppv [I] Address where pointer to object will be stored.
2773  *
2774  * RETURNS
2775  *  Success: S_OK.
2776  *  Failure: E_OUTOFMEMORY.
2777  *
2778  * NOTES
2779  *  Crashes on all invalid ppv addresses, including NULL.
2780  *  If the function returns a non-NULL object then the caller must release its
2781  *  reference on the object when the object is no longer required.
2782  *
2783  * SEE ALSO
2784  *  CoSetState().
2785  */
2786 HRESULT WINAPI CoGetState(IUnknown ** ppv)
2787 {
2788     struct oletls *info = COM_CurrentInfo();
2789     if (!info) return E_OUTOFMEMORY;
2790
2791     *ppv = NULL;
2792
2793     if (info->state)
2794     {
2795         IUnknown_AddRef(info->state);
2796         *ppv = info->state;
2797         TRACE("apt->state=%p\n", info->state);
2798     }
2799
2800     return S_OK;
2801 }
2802
2803 /***********************************************************************
2804  *           CoSetState [OLE32.@]
2805  *
2806  * Sets the thread state object.
2807  *
2808  * PARAMS
2809  *  pv [I] Pointer to state object to be stored.
2810  *
2811  * NOTES
2812  *  The system keeps a reference on the object while the object stored.
2813  *
2814  * RETURNS
2815  *  Success: S_OK.
2816  *  Failure: E_OUTOFMEMORY.
2817  */
2818 HRESULT WINAPI CoSetState(IUnknown * pv)
2819 {
2820     struct oletls *info = COM_CurrentInfo();
2821     if (!info) return E_OUTOFMEMORY;
2822
2823     if (pv) IUnknown_AddRef(pv);
2824
2825     if (info->state)
2826     {
2827         TRACE("-- release %p now\n", info->state);
2828         IUnknown_Release(info->state);
2829     }
2830
2831     info->state = pv;
2832
2833     return S_OK;
2834 }
2835
2836
2837 /******************************************************************************
2838  *              CoTreatAsClass        [OLE32.@]
2839  *
2840  * Sets the TreatAs value of a class.
2841  *
2842  * PARAMS
2843  *  clsidOld [I] Class to set TreatAs value on.
2844  *  clsidNew [I] The class the clsidOld should be treated as.
2845  *
2846  * RETURNS
2847  *  Success: S_OK.
2848  *  Failure: HRESULT code.
2849  *
2850  * SEE ALSO
2851  *  CoGetTreatAsClass
2852  */
2853 HRESULT WINAPI CoTreatAsClass(REFCLSID clsidOld, REFCLSID clsidNew)
2854 {
2855     static const WCHAR wszAutoTreatAs[] = {'A','u','t','o','T','r','e','a','t','A','s',0};
2856     static const WCHAR wszTreatAs[] = {'T','r','e','a','t','A','s',0};
2857     HKEY hkey = NULL;
2858     WCHAR szClsidNew[CHARS_IN_GUID];
2859     HRESULT res = S_OK;
2860     WCHAR auto_treat_as[CHARS_IN_GUID];
2861     LONG auto_treat_as_size = sizeof(auto_treat_as);
2862     CLSID id;
2863
2864     res = COM_OpenKeyForCLSID(clsidOld, NULL, KEY_READ | KEY_WRITE, &hkey);
2865     if (FAILED(res))
2866         goto done;
2867     if (!memcmp( clsidOld, clsidNew, sizeof(*clsidOld) ))
2868     {
2869        if (!RegQueryValueW(hkey, wszAutoTreatAs, auto_treat_as, &auto_treat_as_size) &&
2870            CLSIDFromString(auto_treat_as, &id) == S_OK)
2871        {
2872            if (RegSetValueW(hkey, wszTreatAs, REG_SZ, auto_treat_as, sizeof(auto_treat_as)))
2873            {
2874                res = REGDB_E_WRITEREGDB;
2875                goto done;
2876            }
2877        }
2878        else
2879        {
2880            RegDeleteKeyW(hkey, wszTreatAs);
2881            goto done;
2882        }
2883     }
2884     else if (!StringFromGUID2(clsidNew, szClsidNew, ARRAYSIZE(szClsidNew)) &&
2885              !RegSetValueW(hkey, wszTreatAs, REG_SZ, szClsidNew, sizeof(szClsidNew)))
2886     {
2887         res = REGDB_E_WRITEREGDB;
2888         goto done;
2889     }
2890
2891 done:
2892     if (hkey) RegCloseKey(hkey);
2893     return res;
2894 }
2895
2896 /******************************************************************************
2897  *              CoGetTreatAsClass        [OLE32.@]
2898  *
2899  * Gets the TreatAs value of a class.
2900  *
2901  * PARAMS
2902  *  clsidOld [I] Class to get the TreatAs value of.
2903  *  clsidNew [I] The class the clsidOld should be treated as.
2904  *
2905  * RETURNS
2906  *  Success: S_OK.
2907  *  Failure: HRESULT code.
2908  *
2909  * SEE ALSO
2910  *  CoSetTreatAsClass
2911  */
2912 HRESULT WINAPI CoGetTreatAsClass(REFCLSID clsidOld, LPCLSID clsidNew)
2913 {
2914     static const WCHAR wszTreatAs[] = {'T','r','e','a','t','A','s',0};
2915     HKEY hkey = NULL;
2916     WCHAR szClsidNew[CHARS_IN_GUID];
2917     HRESULT res = S_OK;
2918     LONG len = sizeof(szClsidNew);
2919
2920     FIXME("(%s,%p)\n", debugstr_guid(clsidOld), clsidNew);
2921     *clsidNew = *clsidOld; /* copy over old value */
2922
2923     res = COM_OpenKeyForCLSID(clsidOld, wszTreatAs, KEY_READ, &hkey);
2924     if (FAILED(res))
2925     {
2926         res = S_FALSE;
2927         goto done;
2928     }
2929     if (RegQueryValueW(hkey, NULL, szClsidNew, &len))
2930     {
2931         res = S_FALSE;
2932         goto done;
2933     }
2934     res = CLSIDFromString(szClsidNew,clsidNew);
2935     if (FAILED(res))
2936         ERR("Failed CLSIDFromStringA(%s), hres 0x%08x\n", debugstr_w(szClsidNew), res);
2937 done:
2938     if (hkey) RegCloseKey(hkey);
2939     return res;
2940 }
2941
2942 /******************************************************************************
2943  *              CoGetCurrentProcess     [OLE32.@]
2944  *
2945  * Gets the current process ID.
2946  *
2947  * RETURNS
2948  *  The current process ID.
2949  *
2950  * NOTES
2951  *   Is DWORD really the correct return type for this function?
2952  */
2953 DWORD WINAPI CoGetCurrentProcess(void)
2954 {
2955         return GetCurrentProcessId();
2956 }
2957
2958 /******************************************************************************
2959  *              CoRegisterMessageFilter [OLE32.@]
2960  *
2961  * Registers a message filter.
2962  *
2963  * PARAMS
2964  *  lpMessageFilter [I] Pointer to interface.
2965  *  lplpMessageFilter [O] Indirect pointer to prior instance if non-NULL.
2966  *
2967  * RETURNS
2968  *  Success: S_OK.
2969  *  Failure: HRESULT code.
2970  *
2971  * NOTES
2972  *  Both lpMessageFilter and lplpMessageFilter are optional. Passing in a NULL
2973  *  lpMessageFilter removes the message filter.
2974  *
2975  *  If lplpMessageFilter is not NULL the previous message filter will be
2976  *  returned in the memory pointer to this parameter and the caller is
2977  *  responsible for releasing the object.
2978  *
2979  *  The current thread be in an apartment otherwise the function will crash.
2980  */
2981 HRESULT WINAPI CoRegisterMessageFilter(
2982     LPMESSAGEFILTER lpMessageFilter,
2983     LPMESSAGEFILTER *lplpMessageFilter)
2984 {
2985     struct apartment *apt;
2986     IMessageFilter *lpOldMessageFilter;
2987
2988     TRACE("(%p, %p)\n", lpMessageFilter, lplpMessageFilter);
2989
2990     apt = COM_CurrentApt();
2991
2992     /* can't set a message filter in a multi-threaded apartment */
2993     if (!apt || apt->multi_threaded)
2994     {
2995         WARN("can't set message filter in MTA or uninitialized apt\n");
2996         return CO_E_NOT_SUPPORTED;
2997     }
2998
2999     if (lpMessageFilter)
3000         IMessageFilter_AddRef(lpMessageFilter);
3001
3002     EnterCriticalSection(&apt->cs);
3003
3004     lpOldMessageFilter = apt->filter;
3005     apt->filter = lpMessageFilter;
3006
3007     LeaveCriticalSection(&apt->cs);
3008
3009     if (lplpMessageFilter)
3010         *lplpMessageFilter = lpOldMessageFilter;
3011     else if (lpOldMessageFilter)
3012         IMessageFilter_Release(lpOldMessageFilter);
3013
3014     return S_OK;
3015 }
3016
3017 /***********************************************************************
3018  *           CoIsOle1Class [OLE32.@]
3019  *
3020  * Determines whether the specified class an OLE v1 class.
3021  *
3022  * PARAMS
3023  *  clsid [I] Class to test.
3024  *
3025  * RETURNS
3026  *  TRUE if the class is an OLE v1 class, or FALSE otherwise.
3027  */
3028 BOOL WINAPI CoIsOle1Class(REFCLSID clsid)
3029 {
3030   FIXME("%s\n", debugstr_guid(clsid));
3031   return FALSE;
3032 }
3033
3034 /***********************************************************************
3035  *           IsEqualGUID [OLE32.@]
3036  *
3037  * Compares two Unique Identifiers.
3038  *
3039  * PARAMS
3040  *  rguid1 [I] The first GUID to compare.
3041  *  rguid2 [I] The other GUID to compare.
3042  *
3043  * RETURNS
3044  *      TRUE if equal
3045  */
3046 #undef IsEqualGUID
3047 BOOL WINAPI IsEqualGUID(
3048      REFGUID rguid1,
3049      REFGUID rguid2)
3050 {
3051     return !memcmp(rguid1,rguid2,sizeof(GUID));
3052 }
3053
3054 /***********************************************************************
3055  *           CoInitializeSecurity [OLE32.@]
3056  */
3057 HRESULT WINAPI CoInitializeSecurity(PSECURITY_DESCRIPTOR pSecDesc, LONG cAuthSvc,
3058                                     SOLE_AUTHENTICATION_SERVICE* asAuthSvc,
3059                                     void* pReserved1, DWORD dwAuthnLevel,
3060                                     DWORD dwImpLevel, void* pReserved2,
3061                                     DWORD dwCapabilities, void* pReserved3)
3062 {
3063   FIXME("(%p,%d,%p,%p,%d,%d,%p,%d,%p) - stub!\n", pSecDesc, cAuthSvc,
3064         asAuthSvc, pReserved1, dwAuthnLevel, dwImpLevel, pReserved2,
3065         dwCapabilities, pReserved3);
3066   return S_OK;
3067 }
3068
3069 /***********************************************************************
3070  *           CoSuspendClassObjects [OLE32.@]
3071  *
3072  * Suspends all registered class objects to prevent further requests coming in
3073  * for those objects.
3074  *
3075  * RETURNS
3076  *  Success: S_OK.
3077  *  Failure: HRESULT code.
3078  */
3079 HRESULT WINAPI CoSuspendClassObjects(void)
3080 {
3081     FIXME("\n");
3082     return S_OK;
3083 }
3084
3085 /***********************************************************************
3086  *           CoAddRefServerProcess [OLE32.@]
3087  *
3088  * Helper function for incrementing the reference count of a local-server
3089  * process.
3090  *
3091  * RETURNS
3092  *  New reference count.
3093  *
3094  * SEE ALSO
3095  *  CoReleaseServerProcess().
3096  */
3097 ULONG WINAPI CoAddRefServerProcess(void)
3098 {
3099     ULONG refs;
3100
3101     TRACE("\n");
3102
3103     EnterCriticalSection(&csRegisteredClassList);
3104     refs = ++s_COMServerProcessReferences;
3105     LeaveCriticalSection(&csRegisteredClassList);
3106
3107     TRACE("refs before: %d\n", refs - 1);
3108
3109     return refs;
3110 }
3111
3112 /***********************************************************************
3113  *           CoReleaseServerProcess [OLE32.@]
3114  *
3115  * Helper function for decrementing the reference count of a local-server
3116  * process.
3117  *
3118  * RETURNS
3119  *  New reference count.
3120  *
3121  * NOTES
3122  *  When reference count reaches 0, this function suspends all registered
3123  *  classes so no new connections are accepted.
3124  *
3125  * SEE ALSO
3126  *  CoAddRefServerProcess(), CoSuspendClassObjects().
3127  */
3128 ULONG WINAPI CoReleaseServerProcess(void)
3129 {
3130     ULONG refs;
3131
3132     TRACE("\n");
3133
3134     EnterCriticalSection(&csRegisteredClassList);
3135
3136     refs = --s_COMServerProcessReferences;
3137     /* FIXME: if (!refs) COM_SuspendClassObjects(); */
3138
3139     LeaveCriticalSection(&csRegisteredClassList);
3140
3141     TRACE("refs after: %d\n", refs);
3142
3143     return refs;
3144 }
3145
3146 /***********************************************************************
3147  *           CoIsHandlerConnected [OLE32.@]
3148  *
3149  * Determines whether a proxy is connected to a remote stub.
3150  *
3151  * PARAMS
3152  *  pUnk [I] Pointer to object that may or may not be connected.
3153  *
3154  * RETURNS
3155  *  TRUE if pUnk is not a proxy or if pUnk is connected to a remote stub, or
3156  *  FALSE otherwise.
3157  */
3158 BOOL WINAPI CoIsHandlerConnected(IUnknown *pUnk)
3159 {
3160     FIXME("%p\n", pUnk);
3161
3162     return TRUE;
3163 }
3164
3165 /***********************************************************************
3166  *           CoAllowSetForegroundWindow [OLE32.@]
3167  *
3168  */
3169 HRESULT WINAPI CoAllowSetForegroundWindow(IUnknown *pUnk, void *pvReserved)
3170 {
3171     FIXME("(%p, %p): stub\n", pUnk, pvReserved);
3172     return S_OK;
3173 }
3174  
3175 /***********************************************************************
3176  *           CoQueryProxyBlanket [OLE32.@]
3177  *
3178  * Retrieves the security settings being used by a proxy.
3179  *
3180  * PARAMS
3181  *  pProxy        [I] Pointer to the proxy object.
3182  *  pAuthnSvc     [O] The type of authentication service.
3183  *  pAuthzSvc     [O] The type of authorization service.
3184  *  ppServerPrincName [O] Optional. The server prinicple name.
3185  *  pAuthnLevel   [O] The authentication level.
3186  *  pImpLevel     [O] The impersonation level.
3187  *  ppAuthInfo    [O] Information specific to the authorization/authentication service.
3188  *  pCapabilities [O] Flags affecting the security behaviour.
3189  *
3190  * RETURNS
3191  *  Success: S_OK.
3192  *  Failure: HRESULT code.
3193  *
3194  * SEE ALSO
3195  *  CoCopyProxy, CoSetProxyBlanket.
3196  */
3197 HRESULT WINAPI CoQueryProxyBlanket(IUnknown *pProxy, DWORD *pAuthnSvc,
3198     DWORD *pAuthzSvc, OLECHAR **ppServerPrincName, DWORD *pAuthnLevel,
3199     DWORD *pImpLevel, void **ppAuthInfo, DWORD *pCapabilities)
3200 {
3201     IClientSecurity *pCliSec;
3202     HRESULT hr;
3203
3204     TRACE("%p\n", pProxy);
3205
3206     hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
3207     if (SUCCEEDED(hr))
3208     {
3209         hr = IClientSecurity_QueryBlanket(pCliSec, pProxy, pAuthnSvc,
3210                                           pAuthzSvc, ppServerPrincName,
3211                                           pAuthnLevel, pImpLevel, ppAuthInfo,
3212                                           pCapabilities);
3213         IClientSecurity_Release(pCliSec);
3214     }
3215
3216     if (FAILED(hr)) ERR("-- failed with 0x%08x\n", hr);
3217     return hr;
3218 }
3219
3220 /***********************************************************************
3221  *           CoSetProxyBlanket [OLE32.@]
3222  *
3223  * Sets the security settings for a proxy.
3224  *
3225  * PARAMS
3226  *  pProxy       [I] Pointer to the proxy object.
3227  *  AuthnSvc     [I] The type of authentication service.
3228  *  AuthzSvc     [I] The type of authorization service.
3229  *  pServerPrincName [I] The server prinicple name.
3230  *  AuthnLevel   [I] The authentication level.
3231  *  ImpLevel     [I] The impersonation level.
3232  *  pAuthInfo    [I] Information specific to the authorization/authentication service.
3233  *  Capabilities [I] Flags affecting the security behaviour.
3234  *
3235  * RETURNS
3236  *  Success: S_OK.
3237  *  Failure: HRESULT code.
3238  *
3239  * SEE ALSO
3240  *  CoQueryProxyBlanket, CoCopyProxy.
3241  */
3242 HRESULT WINAPI CoSetProxyBlanket(IUnknown *pProxy, DWORD AuthnSvc,
3243     DWORD AuthzSvc, OLECHAR *pServerPrincName, DWORD AuthnLevel,
3244     DWORD ImpLevel, void *pAuthInfo, DWORD Capabilities)
3245 {
3246     IClientSecurity *pCliSec;
3247     HRESULT hr;
3248
3249     TRACE("%p\n", pProxy);
3250
3251     hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
3252     if (SUCCEEDED(hr))
3253     {
3254         hr = IClientSecurity_SetBlanket(pCliSec, pProxy, AuthnSvc,
3255                                         AuthzSvc, pServerPrincName,
3256                                         AuthnLevel, ImpLevel, pAuthInfo,
3257                                         Capabilities);
3258         IClientSecurity_Release(pCliSec);
3259     }
3260
3261     if (FAILED(hr)) ERR("-- failed with 0x%08x\n", hr);
3262     return hr;
3263 }
3264
3265 /***********************************************************************
3266  *           CoCopyProxy [OLE32.@]
3267  *
3268  * Copies a proxy.
3269  *
3270  * PARAMS
3271  *  pProxy [I] Pointer to the proxy object.
3272  *  ppCopy [O] Copy of the proxy.
3273  *
3274  * RETURNS
3275  *  Success: S_OK.
3276  *  Failure: HRESULT code.
3277  *
3278  * SEE ALSO
3279  *  CoQueryProxyBlanket, CoSetProxyBlanket.
3280  */
3281 HRESULT WINAPI CoCopyProxy(IUnknown *pProxy, IUnknown **ppCopy)
3282 {
3283     IClientSecurity *pCliSec;
3284     HRESULT hr;
3285
3286     TRACE("%p\n", pProxy);
3287
3288     hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
3289     if (SUCCEEDED(hr))
3290     {
3291         hr = IClientSecurity_CopyProxy(pCliSec, pProxy, ppCopy);
3292         IClientSecurity_Release(pCliSec);
3293     }
3294
3295     if (FAILED(hr)) ERR("-- failed with 0x%08x\n", hr);
3296     return hr;
3297 }
3298
3299
3300 /***********************************************************************
3301  *           CoGetCallContext [OLE32.@]
3302  *
3303  * Gets the context of the currently executing server call in the current
3304  * thread.
3305  *
3306  * PARAMS
3307  *  riid [I] Context interface to return.
3308  *  ppv  [O] Pointer to memory that will receive the context on return.
3309  *
3310  * RETURNS
3311  *  Success: S_OK.
3312  *  Failure: HRESULT code.
3313  */
3314 HRESULT WINAPI CoGetCallContext(REFIID riid, void **ppv)
3315 {
3316     struct oletls *info = COM_CurrentInfo();
3317
3318     TRACE("(%s, %p)\n", debugstr_guid(riid), ppv);
3319
3320     if (!info)
3321         return E_OUTOFMEMORY;
3322
3323     if (!info->call_state)
3324         return RPC_E_CALL_COMPLETE;
3325
3326     return IUnknown_QueryInterface(info->call_state, riid, ppv);
3327 }
3328
3329 /***********************************************************************
3330  *           CoSwitchCallContext [OLE32.@]
3331  *
3332  * Switches the context of the currently executing server call in the current
3333  * thread.
3334  *
3335  * PARAMS
3336  *  pObject     [I] Pointer to new context object
3337  *  ppOldObject [O] Pointer to memory that will receive old context object pointer
3338  *
3339  * RETURNS
3340  *  Success: S_OK.
3341  *  Failure: HRESULT code.
3342  */
3343 HRESULT WINAPI CoSwitchCallContext(IUnknown *pObject, IUnknown **ppOldObject)
3344 {
3345     struct oletls *info = COM_CurrentInfo();
3346
3347     TRACE("(%p, %p)\n", pObject, ppOldObject);
3348
3349     if (!info)
3350         return E_OUTOFMEMORY;
3351
3352     *ppOldObject = info->call_state;
3353     info->call_state = pObject; /* CoSwitchCallContext does not addref nor release objects */
3354
3355     return S_OK;
3356 }
3357
3358 /***********************************************************************
3359  *           CoQueryClientBlanket [OLE32.@]
3360  *
3361  * Retrieves the authentication information about the client of the currently
3362  * executing server call in the current thread.
3363  *
3364  * PARAMS
3365  *  pAuthnSvc     [O] Optional. The type of authentication service.
3366  *  pAuthzSvc     [O] Optional. The type of authorization service.
3367  *  pServerPrincName [O] Optional. The server prinicple name.
3368  *  pAuthnLevel   [O] Optional. The authentication level.
3369  *  pImpLevel     [O] Optional. The impersonation level.
3370  *  pPrivs        [O] Optional. Information about the privileges of the client.
3371  *  pCapabilities [IO] Optional. Flags affecting the security behaviour.
3372  *
3373  * RETURNS
3374  *  Success: S_OK.
3375  *  Failure: HRESULT code.
3376  *
3377  * SEE ALSO
3378  *  CoImpersonateClient, CoRevertToSelf, CoGetCallContext.
3379  */
3380 HRESULT WINAPI CoQueryClientBlanket(
3381     DWORD *pAuthnSvc,
3382     DWORD *pAuthzSvc,
3383     OLECHAR **pServerPrincName,
3384     DWORD *pAuthnLevel,
3385     DWORD *pImpLevel,
3386     RPC_AUTHZ_HANDLE *pPrivs,
3387     DWORD *pCapabilities)
3388 {
3389     IServerSecurity *pSrvSec;
3390     HRESULT hr;
3391
3392     TRACE("(%p, %p, %p, %p, %p, %p, %p)\n",
3393         pAuthnSvc, pAuthzSvc, pServerPrincName, pAuthnLevel, pImpLevel,
3394         pPrivs, pCapabilities);
3395
3396     hr = CoGetCallContext(&IID_IServerSecurity, (void **)&pSrvSec);
3397     if (SUCCEEDED(hr))
3398     {
3399         hr = IServerSecurity_QueryBlanket(
3400             pSrvSec, pAuthnSvc, pAuthzSvc, pServerPrincName, pAuthnLevel,
3401             pImpLevel, pPrivs, pCapabilities);
3402         IServerSecurity_Release(pSrvSec);
3403     }
3404
3405     return hr;
3406 }
3407
3408 /***********************************************************************
3409  *           CoImpersonateClient [OLE32.@]
3410  *
3411  * Impersonates the client of the currently executing server call in the
3412  * current thread.
3413  *
3414  * PARAMS
3415  *  None.
3416  *
3417  * RETURNS
3418  *  Success: S_OK.
3419  *  Failure: HRESULT code.
3420  *
3421  * NOTES
3422  *  If this function fails then the current thread will not be impersonating
3423  *  the client and all actions will take place on behalf of the server.
3424  *  Therefore, it is important to check the return value from this function.
3425  *
3426  * SEE ALSO
3427  *  CoRevertToSelf, CoQueryClientBlanket, CoGetCallContext.
3428  */
3429 HRESULT WINAPI CoImpersonateClient(void)
3430 {
3431     IServerSecurity *pSrvSec;
3432     HRESULT hr;
3433
3434     TRACE("\n");
3435
3436     hr = CoGetCallContext(&IID_IServerSecurity, (void **)&pSrvSec);
3437     if (SUCCEEDED(hr))
3438     {
3439         hr = IServerSecurity_ImpersonateClient(pSrvSec);
3440         IServerSecurity_Release(pSrvSec);
3441     }
3442
3443     return hr;
3444 }
3445
3446 /***********************************************************************
3447  *           CoRevertToSelf [OLE32.@]
3448  *
3449  * Ends the impersonation of the client of the currently executing server
3450  * call in the current thread.
3451  *
3452  * PARAMS
3453  *  None.
3454  *
3455  * RETURNS
3456  *  Success: S_OK.
3457  *  Failure: HRESULT code.
3458  *
3459  * SEE ALSO
3460  *  CoImpersonateClient, CoQueryClientBlanket, CoGetCallContext.
3461  */
3462 HRESULT WINAPI CoRevertToSelf(void)
3463 {
3464     IServerSecurity *pSrvSec;
3465     HRESULT hr;
3466
3467     TRACE("\n");
3468
3469     hr = CoGetCallContext(&IID_IServerSecurity, (void **)&pSrvSec);
3470     if (SUCCEEDED(hr))
3471     {
3472         hr = IServerSecurity_RevertToSelf(pSrvSec);
3473         IServerSecurity_Release(pSrvSec);
3474     }
3475
3476     return hr;
3477 }
3478
3479 static BOOL COM_PeekMessage(struct apartment *apt, MSG *msg)
3480 {
3481     /* first try to retrieve messages for incoming COM calls to the apartment window */
3482     return PeekMessageW(msg, apt->win, WM_USER, WM_APP - 1, PM_REMOVE|PM_NOYIELD) ||
3483            /* next retrieve other messages necessary for the app to remain responsive */
3484            PeekMessageW(msg, NULL, 0, 0, PM_QS_PAINT|PM_QS_POSTMESSAGE|PM_REMOVE|PM_NOYIELD);
3485 }
3486
3487 /***********************************************************************
3488  *           CoWaitForMultipleHandles [OLE32.@]
3489  *
3490  * Waits for one or more handles to become signaled.
3491  *
3492  * PARAMS
3493  *  dwFlags   [I] Flags. See notes.
3494  *  dwTimeout [I] Timeout in milliseconds.
3495  *  cHandles  [I] Number of handles pointed to by pHandles.
3496  *  pHandles  [I] Handles to wait for.
3497  *  lpdwindex [O] Index of handle that was signaled.
3498  *
3499  * RETURNS
3500  *  Success: S_OK.
3501  *  Failure: RPC_S_CALLPENDING on timeout.
3502  *
3503  * NOTES
3504  *
3505  * The dwFlags parameter can be zero or more of the following:
3506  *| COWAIT_WAITALL - Wait for all of the handles to become signaled.
3507  *| COWAIT_ALERTABLE - Allows a queued APC to run during the wait.
3508  *
3509  * SEE ALSO
3510  *  MsgWaitForMultipleObjects, WaitForMultipleObjects.
3511  */
3512 HRESULT WINAPI CoWaitForMultipleHandles(DWORD dwFlags, DWORD dwTimeout,
3513     ULONG cHandles, LPHANDLE pHandles, LPDWORD lpdwindex)
3514 {
3515     HRESULT hr = S_OK;
3516     DWORD start_time = GetTickCount();
3517     APARTMENT *apt = COM_CurrentApt();
3518     BOOL message_loop = apt && !apt->multi_threaded;
3519
3520     TRACE("(0x%08x, 0x%08x, %d, %p, %p)\n", dwFlags, dwTimeout, cHandles,
3521         pHandles, lpdwindex);
3522
3523     while (TRUE)
3524     {
3525         DWORD now = GetTickCount();
3526         DWORD res;
3527
3528         if (now - start_time > dwTimeout)
3529         {
3530             hr = RPC_S_CALLPENDING;
3531             break;
3532         }
3533
3534         if (message_loop)
3535         {
3536             DWORD wait_flags = ((dwFlags & COWAIT_WAITALL) ? MWMO_WAITALL : 0) |
3537                     ((dwFlags & COWAIT_ALERTABLE ) ? MWMO_ALERTABLE : 0);
3538
3539             TRACE("waiting for rpc completion or window message\n");
3540
3541             res = MsgWaitForMultipleObjectsEx(cHandles, pHandles,
3542                 (dwTimeout == INFINITE) ? INFINITE : start_time + dwTimeout - now,
3543                 QS_ALLINPUT, wait_flags);
3544
3545             if (res == WAIT_OBJECT_0 + cHandles)  /* messages available */
3546             {
3547                 MSG msg;
3548
3549                 /* call message filter */
3550
3551                 if (COM_CurrentApt()->filter)
3552                 {
3553                     PENDINGTYPE pendingtype =
3554                         COM_CurrentInfo()->pending_call_count_server ?
3555                             PENDINGTYPE_NESTED : PENDINGTYPE_TOPLEVEL;
3556                     DWORD be_handled = IMessageFilter_MessagePending(
3557                         COM_CurrentApt()->filter, 0 /* FIXME */,
3558                         now - start_time, pendingtype);
3559                     TRACE("IMessageFilter_MessagePending returned %d\n", be_handled);
3560                     switch (be_handled)
3561                     {
3562                     case PENDINGMSG_CANCELCALL:
3563                         WARN("call canceled\n");
3564                         hr = RPC_E_CALL_CANCELED;
3565                         break;
3566                     case PENDINGMSG_WAITNOPROCESS:
3567                     case PENDINGMSG_WAITDEFPROCESS:
3568                     default:
3569                         /* FIXME: MSDN is very vague about the difference
3570                          * between WAITNOPROCESS and WAITDEFPROCESS - there
3571                          * appears to be none, so it is possibly a left-over
3572                          * from the 16-bit world. */
3573                         break;
3574                     }
3575                 }
3576
3577                 /* note: using "if" here instead of "while" might seem less
3578                  * efficient, but only if we are optimising for quick delivery
3579                  * of pending messages, rather than quick completion of the
3580                  * COM call */
3581                 if (COM_PeekMessage(apt, &msg))
3582                 {
3583                     TRACE("received message whilst waiting for RPC: 0x%04x\n", msg.message);
3584                     TranslateMessage(&msg);
3585                     DispatchMessageW(&msg);
3586                     if (msg.message == WM_QUIT)
3587                     {
3588                         TRACE("resending WM_QUIT to outer message loop\n");
3589                         PostQuitMessage(msg.wParam);
3590                         /* no longer need to process messages */
3591                         message_loop = FALSE;
3592                     }
3593                 }
3594                 continue;
3595             }
3596         }
3597         else
3598         {
3599             TRACE("waiting for rpc completion\n");
3600
3601             res = WaitForMultipleObjectsEx(cHandles, pHandles,
3602                 (dwFlags & COWAIT_WAITALL) ? TRUE : FALSE,
3603                 (dwTimeout == INFINITE) ? INFINITE : start_time + dwTimeout - now,
3604                 (dwFlags & COWAIT_ALERTABLE) ? TRUE : FALSE);
3605         }
3606
3607         if (res < WAIT_OBJECT_0 + cHandles)
3608         {
3609             /* handle signaled, store index */
3610             *lpdwindex = (res - WAIT_OBJECT_0);
3611             break;
3612         }
3613         else if (res == WAIT_TIMEOUT)
3614         {
3615             hr = RPC_S_CALLPENDING;
3616             break;
3617         }
3618         else
3619         {
3620             ERR("Unexpected wait termination: %d, %d\n", res, GetLastError());
3621             hr = E_UNEXPECTED;
3622             break;
3623         }
3624     }
3625     TRACE("-- 0x%08x\n", hr);
3626     return hr;
3627 }
3628
3629
3630 /***********************************************************************
3631  *           CoGetObject [OLE32.@]
3632  *
3633  * Gets the object named by converting the name to a moniker and binding to it.
3634  *
3635  * PARAMS
3636  *  pszName      [I] String representing the object.
3637  *  pBindOptions [I] Parameters affecting the binding to the named object.
3638  *  riid         [I] Interface to bind to on the objecct.
3639  *  ppv          [O] On output, the interface riid of the object represented
3640  *                   by pszName.
3641  *
3642  * RETURNS
3643  *  Success: S_OK.
3644  *  Failure: HRESULT code.
3645  *
3646  * SEE ALSO
3647  *  MkParseDisplayName.
3648  */
3649 HRESULT WINAPI CoGetObject(LPCWSTR pszName, BIND_OPTS *pBindOptions,
3650     REFIID riid, void **ppv)
3651 {
3652     IBindCtx *pbc;
3653     HRESULT hr;
3654
3655     *ppv = NULL;
3656
3657     hr = CreateBindCtx(0, &pbc);
3658     if (SUCCEEDED(hr))
3659     {
3660         if (pBindOptions)
3661             hr = IBindCtx_SetBindOptions(pbc, pBindOptions);
3662
3663         if (SUCCEEDED(hr))
3664         {
3665             ULONG chEaten;
3666             IMoniker *pmk;
3667
3668             hr = MkParseDisplayName(pbc, pszName, &chEaten, &pmk);
3669             if (SUCCEEDED(hr))
3670             {
3671                 hr = IMoniker_BindToObject(pmk, pbc, NULL, riid, ppv);
3672                 IMoniker_Release(pmk);
3673             }
3674         }
3675
3676         IBindCtx_Release(pbc);
3677     }
3678     return hr;
3679 }
3680
3681 /***********************************************************************
3682  *           CoRegisterChannelHook [OLE32.@]
3683  *
3684  * Registers a process-wide hook that is called during ORPC calls.
3685  *
3686  * PARAMS
3687  *  guidExtension [I] GUID of the channel hook to register.
3688  *  pChannelHook  [I] Channel hook object to register.
3689  *
3690  * RETURNS
3691  *  Success: S_OK.
3692  *  Failure: HRESULT code.
3693  */
3694 HRESULT WINAPI CoRegisterChannelHook(REFGUID guidExtension, IChannelHook *pChannelHook)
3695 {
3696     TRACE("(%s, %p)\n", debugstr_guid(guidExtension), pChannelHook);
3697
3698     return RPC_RegisterChannelHook(guidExtension, pChannelHook);
3699 }
3700
3701 typedef struct Context
3702 {
3703     const IComThreadingInfoVtbl *lpVtbl;
3704     const IContextCallbackVtbl  *lpCallbackVtbl;
3705     LONG refs;
3706     APTTYPE apttype;
3707 } Context;
3708
3709 static inline Context *impl_from_IComThreadingInfo( IComThreadingInfo *iface )
3710 {
3711         return (Context *)((char*)iface - FIELD_OFFSET(Context, lpVtbl));
3712 }
3713
3714 static inline Context *impl_from_IContextCallback( IContextCallback *iface )
3715 {
3716         return (Context *)((char*)iface - FIELD_OFFSET(Context, lpCallbackVtbl));
3717 }
3718
3719 static HRESULT Context_QueryInterface(Context *iface, REFIID riid, LPVOID *ppv)
3720 {
3721     *ppv = NULL;
3722
3723     if (IsEqualIID(riid, &IID_IComThreadingInfo) ||
3724         IsEqualIID(riid, &IID_IUnknown))
3725     {
3726         *ppv = &iface->lpVtbl;
3727     } else if (IsEqualIID(riid, &IID_IContextCallback))
3728     {
3729         *ppv = &iface->lpCallbackVtbl;
3730     }
3731
3732     if (*ppv)
3733     {
3734         IUnknown_AddRef((IUnknown*)*ppv);
3735         return S_OK;
3736     }
3737
3738     FIXME("interface not implemented %s\n", debugstr_guid(riid));
3739     return E_NOINTERFACE;
3740 }
3741
3742 static ULONG Context_AddRef(Context *This)
3743 {
3744     return InterlockedIncrement(&This->refs);
3745 }
3746
3747 static ULONG Context_Release(Context *This)
3748 {
3749     ULONG refs = InterlockedDecrement(&This->refs);
3750     if (!refs)
3751         HeapFree(GetProcessHeap(), 0, This);
3752     return refs;
3753 }
3754
3755 static HRESULT WINAPI Context_CTI_QueryInterface(IComThreadingInfo *iface, REFIID riid, LPVOID *ppv)
3756 {
3757     Context *This = impl_from_IComThreadingInfo(iface);
3758     return Context_QueryInterface(This, riid, ppv);
3759 }
3760
3761 static ULONG WINAPI Context_CTI_AddRef(IComThreadingInfo *iface)
3762 {
3763     Context *This = impl_from_IComThreadingInfo(iface);
3764     return Context_AddRef(This);
3765 }
3766
3767 static ULONG WINAPI Context_CTI_Release(IComThreadingInfo *iface)
3768 {
3769     Context *This = impl_from_IComThreadingInfo(iface);
3770     return Context_Release(This);
3771 }
3772
3773 static HRESULT WINAPI Context_CTI_GetCurrentApartmentType(IComThreadingInfo *iface, APTTYPE *apttype)
3774 {
3775     Context *This = impl_from_IComThreadingInfo(iface);
3776
3777     TRACE("(%p)\n", apttype);
3778
3779     *apttype = This->apttype;
3780     return S_OK;
3781 }
3782
3783 static HRESULT WINAPI Context_CTI_GetCurrentThreadType(IComThreadingInfo *iface, THDTYPE *thdtype)
3784 {
3785     Context *This = impl_from_IComThreadingInfo(iface);
3786
3787     TRACE("(%p)\n", thdtype);
3788
3789     switch (This->apttype)
3790     {
3791     case APTTYPE_STA:
3792     case APTTYPE_MAINSTA:
3793         *thdtype = THDTYPE_PROCESSMESSAGES;
3794         break;
3795     default:
3796         *thdtype = THDTYPE_BLOCKMESSAGES;
3797         break;
3798     }
3799     return S_OK;
3800 }
3801
3802 static HRESULT WINAPI Context_CTI_GetCurrentLogicalThreadId(IComThreadingInfo *iface, GUID *logical_thread_id)
3803 {
3804     FIXME("(%p): stub\n", logical_thread_id);
3805     return E_NOTIMPL;
3806 }
3807
3808 static HRESULT WINAPI Context_CTI_SetCurrentLogicalThreadId(IComThreadingInfo *iface, REFGUID logical_thread_id)
3809 {
3810     FIXME("(%s): stub\n", debugstr_guid(logical_thread_id));
3811     return E_NOTIMPL;
3812 }
3813
3814 static const IComThreadingInfoVtbl Context_Threading_Vtbl =
3815 {
3816     Context_CTI_QueryInterface,
3817     Context_CTI_AddRef,
3818     Context_CTI_Release,
3819     Context_CTI_GetCurrentApartmentType,
3820     Context_CTI_GetCurrentThreadType,
3821     Context_CTI_GetCurrentLogicalThreadId,
3822     Context_CTI_SetCurrentLogicalThreadId
3823 };
3824
3825 static HRESULT WINAPI Context_CC_QueryInterface(IContextCallback *iface, REFIID riid, LPVOID *ppv)
3826 {
3827     Context *This = impl_from_IContextCallback(iface);
3828     return Context_QueryInterface(This, riid, ppv);
3829 }
3830
3831 static ULONG WINAPI Context_CC_AddRef(IContextCallback *iface)
3832 {
3833     Context *This = impl_from_IContextCallback(iface);
3834     return Context_AddRef(This);
3835 }
3836
3837 static ULONG WINAPI Context_CC_Release(IContextCallback *iface)
3838 {
3839     Context *This = impl_from_IContextCallback(iface);
3840     return Context_Release(This);
3841 }
3842
3843 static HRESULT WINAPI Context_CC_ContextCallback(IContextCallback *iface, PFNCONTEXTCALL pCallback,
3844                             ComCallData *param, REFIID riid, int method, IUnknown *punk)
3845 {
3846     Context *This = impl_from_IContextCallback(iface);
3847
3848     FIXME("(%p/%p)->(%p, %p, %s, %d, %p)\n", This, iface, pCallback, param, debugstr_guid(riid), method, punk);
3849     return E_NOTIMPL;
3850 }
3851
3852 static const IContextCallbackVtbl Context_Callback_Vtbl =
3853 {
3854     Context_CC_QueryInterface,
3855     Context_CC_AddRef,
3856     Context_CC_Release,
3857     Context_CC_ContextCallback
3858 };
3859
3860
3861 /***********************************************************************
3862  *           CoGetObjectContext [OLE32.@]
3863  *
3864  * Retrieves an object associated with the current context (i.e. apartment).
3865  *
3866  * PARAMS
3867  *  riid [I] ID of the interface of the object to retrieve.
3868  *  ppv  [O] Address where object will be stored on return.
3869  *
3870  * RETURNS
3871  *  Success: S_OK.
3872  *  Failure: HRESULT code.
3873  */
3874 HRESULT WINAPI CoGetObjectContext(REFIID riid, void **ppv)
3875 {
3876     APARTMENT *apt = COM_CurrentApt();
3877     Context *context;
3878     HRESULT hr;
3879
3880     TRACE("(%s, %p)\n", debugstr_guid(riid), ppv);
3881
3882     *ppv = NULL;
3883     if (!apt)
3884     {
3885         ERR("apartment not initialised\n");
3886         return CO_E_NOTINITIALIZED;
3887     }
3888
3889     context = HeapAlloc(GetProcessHeap(), 0, sizeof(*context));
3890     if (!context)
3891         return E_OUTOFMEMORY;
3892
3893     context->lpVtbl = &Context_Threading_Vtbl;
3894     context->lpCallbackVtbl = &Context_Callback_Vtbl;
3895     context->refs = 1;
3896     if (apt->multi_threaded)
3897         context->apttype = APTTYPE_MTA;
3898     else if (apt->main)
3899         context->apttype = APTTYPE_MAINSTA;
3900     else
3901         context->apttype = APTTYPE_STA;
3902
3903     hr = IUnknown_QueryInterface((IUnknown *)&context->lpVtbl, riid, ppv);
3904     IUnknown_Release((IUnknown *)&context->lpVtbl);
3905
3906     return hr;
3907 }
3908
3909
3910 /***********************************************************************
3911  *           CoGetContextToken [OLE32.@]
3912  */
3913 HRESULT WINAPI CoGetContextToken( ULONG_PTR *token )
3914 {
3915     struct oletls *info = COM_CurrentInfo();
3916     static int calls;
3917     if(!(calls++)) FIXME( "stub\n" );
3918     if (!info)
3919         return E_OUTOFMEMORY;
3920     if (token) *token = info->context_token;
3921     return E_NOTIMPL;
3922 }
3923
3924
3925 /***********************************************************************
3926  *              DllMain (OLE32.@)
3927  */
3928 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID fImpLoad)
3929 {
3930     TRACE("%p 0x%x %p\n", hinstDLL, fdwReason, fImpLoad);
3931
3932     switch(fdwReason) {
3933     case DLL_PROCESS_ATTACH:
3934         hProxyDll = hinstDLL;
3935         COMPOBJ_InitProcess();
3936         if (TRACE_ON(ole)) CoRegisterMallocSpy((LPVOID)-1);
3937         break;
3938
3939     case DLL_PROCESS_DETACH:
3940         if (TRACE_ON(ole)) CoRevokeMallocSpy();
3941         OLEDD_UnInitialize();
3942         COMPOBJ_UninitProcess();
3943         RPC_UnregisterAllChannelHooks();
3944         COMPOBJ_DllList_Free();
3945         break;
3946
3947     case DLL_THREAD_DETACH:
3948         COM_TlsDestroy();
3949         break;
3950     }
3951     return TRUE;
3952 }
3953
3954 /* NOTE: DllRegisterServer and DllUnregisterServer are in regsvr.c */