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