wined3d: Rework surface Blt a bit to only lock the part of the destination surface...
[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 (i.e., 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 *obj_params = (struct host_object_params *)msg.lParam;
595             obj_params->hr = apartment_hostobject(apt, obj_params);
596             SetEvent(obj_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                                   HWND_MESSAGE, 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     DWORD status = UuidCreate(pguid);
1235     if (status == RPC_S_OK || status == RPC_S_UUID_LOCAL_ONLY) return S_OK;
1236     return HRESULT_FROM_WIN32( status );
1237 }
1238
1239 /******************************************************************************
1240  *              CLSIDFromString [OLE32.@]
1241  *              IIDFromString   [OLE32.@]
1242  *
1243  * Converts a unique identifier from its string representation into
1244  * the GUID struct.
1245  *
1246  * PARAMS
1247  *  idstr [I] The string representation of the GUID.
1248  *  id    [O] GUID converted from the string.
1249  *
1250  * RETURNS
1251  *   S_OK on success
1252  *   CO_E_CLASSSTRING if idstr is not a valid CLSID
1253  *
1254  * SEE ALSO
1255  *  StringFromCLSID
1256  */
1257 static HRESULT WINAPI __CLSIDFromString(LPCWSTR s, CLSID *id)
1258 {
1259   int   i;
1260   BYTE table[256];
1261
1262   if (!s) {
1263     memset( id, 0, sizeof (CLSID) );
1264     return S_OK;
1265   }
1266
1267   /* validate the CLSID string */
1268   if (strlenW(s) != 38)
1269     return CO_E_CLASSSTRING;
1270
1271   if ((s[0]!='{') || (s[9]!='-') || (s[14]!='-') || (s[19]!='-') || (s[24]!='-') || (s[37]!='}'))
1272     return CO_E_CLASSSTRING;
1273
1274   for (i=1; i<37; i++) {
1275     if ((i == 9)||(i == 14)||(i == 19)||(i == 24)) continue;
1276     if (!(((s[i] >= '0') && (s[i] <= '9'))  ||
1277           ((s[i] >= 'a') && (s[i] <= 'f'))  ||
1278           ((s[i] >= 'A') && (s[i] <= 'F'))))
1279        return CO_E_CLASSSTRING;
1280   }
1281
1282   TRACE("%s -> %p\n", debugstr_w(s), id);
1283
1284   /* quick lookup table */
1285   memset(table, 0, 256);
1286
1287   for (i = 0; i < 10; i++) {
1288     table['0' + i] = i;
1289   }
1290   for (i = 0; i < 6; i++) {
1291     table['A' + i] = i+10;
1292     table['a' + i] = i+10;
1293   }
1294
1295   /* in form {XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX} */
1296
1297   id->Data1 = (table[s[1]] << 28 | table[s[2]] << 24 | table[s[3]] << 20 | table[s[4]] << 16 |
1298                table[s[5]] << 12 | table[s[6]] << 8  | table[s[7]] << 4  | table[s[8]]);
1299   id->Data2 = table[s[10]] << 12 | table[s[11]] << 8 | table[s[12]] << 4 | table[s[13]];
1300   id->Data3 = table[s[15]] << 12 | table[s[16]] << 8 | table[s[17]] << 4 | table[s[18]];
1301
1302   /* these are just sequential bytes */
1303   id->Data4[0] = table[s[20]] << 4 | table[s[21]];
1304   id->Data4[1] = table[s[22]] << 4 | table[s[23]];
1305   id->Data4[2] = table[s[25]] << 4 | table[s[26]];
1306   id->Data4[3] = table[s[27]] << 4 | table[s[28]];
1307   id->Data4[4] = table[s[29]] << 4 | table[s[30]];
1308   id->Data4[5] = table[s[31]] << 4 | table[s[32]];
1309   id->Data4[6] = table[s[33]] << 4 | table[s[34]];
1310   id->Data4[7] = table[s[35]] << 4 | table[s[36]];
1311
1312   return S_OK;
1313 }
1314
1315 /*****************************************************************************/
1316
1317 HRESULT WINAPI CLSIDFromString(LPOLESTR idstr, CLSID *id )
1318 {
1319     HRESULT ret;
1320
1321     if (!id)
1322         return E_INVALIDARG;
1323
1324     ret = __CLSIDFromString(idstr, id);
1325     if(ret != S_OK) { /* It appears a ProgID is also valid */
1326         ret = CLSIDFromProgID(idstr, id);
1327     }
1328     return ret;
1329 }
1330
1331 /* Converts a GUID into the respective string representation. */
1332 HRESULT WINE_StringFromCLSID(
1333         const CLSID *id,        /* [in] GUID to be converted */
1334         LPSTR idstr             /* [out] pointer to buffer to contain converted guid */
1335 ) {
1336   static const char hex[] = "0123456789ABCDEF";
1337   char *s;
1338   int   i;
1339
1340   if (!id)
1341         { ERR("called with id=Null\n");
1342           *idstr = 0x00;
1343           return E_FAIL;
1344         }
1345
1346   sprintf(idstr, "{%08X-%04X-%04X-%02X%02X-",
1347           id->Data1, id->Data2, id->Data3,
1348           id->Data4[0], id->Data4[1]);
1349   s = &idstr[25];
1350
1351   /* 6 hex bytes */
1352   for (i = 2; i < 8; i++) {
1353     *s++ = hex[id->Data4[i]>>4];
1354     *s++ = hex[id->Data4[i] & 0xf];
1355   }
1356
1357   *s++ = '}';
1358   *s++ = '\0';
1359
1360   TRACE("%p->%s\n", id, idstr);
1361
1362   return S_OK;
1363 }
1364
1365
1366 /******************************************************************************
1367  *              StringFromCLSID [OLE32.@]
1368  *              StringFromIID   [OLE32.@]
1369  *
1370  * Converts a GUID into the respective string representation.
1371  * The target string is allocated using the OLE IMalloc.
1372  *
1373  * PARAMS
1374  *  id    [I] the GUID to be converted.
1375  *  idstr [O] A pointer to a to-be-allocated pointer pointing to the resulting string.
1376  *
1377  * RETURNS
1378  *   S_OK
1379  *   E_FAIL
1380  *
1381  * SEE ALSO
1382  *  StringFromGUID2, CLSIDFromString
1383  */
1384 HRESULT WINAPI StringFromCLSID(REFCLSID id, LPOLESTR *idstr)
1385 {
1386         char            buf[80];
1387         HRESULT       ret;
1388         LPMALLOC        mllc;
1389
1390         if ((ret = CoGetMalloc(0,&mllc)))
1391                 return ret;
1392
1393         ret=WINE_StringFromCLSID(id,buf);
1394         if (!ret) {
1395             DWORD len = MultiByteToWideChar( CP_ACP, 0, buf, -1, NULL, 0 );
1396             *idstr = IMalloc_Alloc( mllc, len * sizeof(WCHAR) );
1397             MultiByteToWideChar( CP_ACP, 0, buf, -1, *idstr, len );
1398         }
1399         return ret;
1400 }
1401
1402 /******************************************************************************
1403  *              StringFromGUID2 [OLE32.@]
1404  *              StringFromGUID2 [COMPOBJ.76]
1405  *
1406  * Modified version of StringFromCLSID that allows you to specify max
1407  * buffer size.
1408  *
1409  * PARAMS
1410  *  id   [I] GUID to convert to string.
1411  *  str  [O] Buffer where the result will be stored.
1412  *  cmax [I] Size of the buffer in characters.
1413  *
1414  * RETURNS
1415  *      Success: The length of the resulting string in characters.
1416  *  Failure: 0.
1417  */
1418 INT WINAPI StringFromGUID2(REFGUID id, LPOLESTR str, INT cmax)
1419 {
1420   char          xguid[80];
1421
1422   if (WINE_StringFromCLSID(id,xguid))
1423         return 0;
1424   return MultiByteToWideChar( CP_ACP, 0, xguid, -1, str, cmax );
1425 }
1426
1427 /* open HKCR\\CLSID\\{string form of clsid}\\{keyname} key */
1428 HRESULT COM_OpenKeyForCLSID(REFCLSID clsid, LPCWSTR keyname, REGSAM access, HKEY *subkey)
1429 {
1430     static const WCHAR wszCLSIDSlash[] = {'C','L','S','I','D','\\',0};
1431     WCHAR path[CHARS_IN_GUID + ARRAYSIZE(wszCLSIDSlash) - 1];
1432     LONG res;
1433     HKEY key;
1434
1435     strcpyW(path, wszCLSIDSlash);
1436     StringFromGUID2(clsid, path + strlenW(wszCLSIDSlash), CHARS_IN_GUID);
1437     res = RegOpenKeyExW(HKEY_CLASSES_ROOT, path, 0, keyname ? KEY_READ : access, &key);
1438     if (res == ERROR_FILE_NOT_FOUND)
1439         return REGDB_E_CLASSNOTREG;
1440     else if (res != ERROR_SUCCESS)
1441         return REGDB_E_READREGDB;
1442
1443     if (!keyname)
1444     {
1445         *subkey = key;
1446         return S_OK;
1447     }
1448
1449     res = RegOpenKeyExW(key, keyname, 0, access, subkey);
1450     RegCloseKey(key);
1451     if (res == ERROR_FILE_NOT_FOUND)
1452         return REGDB_E_KEYMISSING;
1453     else if (res != ERROR_SUCCESS)
1454         return REGDB_E_READREGDB;
1455
1456     return S_OK;
1457 }
1458
1459 /* open HKCR\\AppId\\{string form of appid clsid} key */
1460 HRESULT COM_OpenKeyForAppIdFromCLSID(REFCLSID clsid, REGSAM access, HKEY *subkey)
1461 {
1462     static const WCHAR szAppId[] = { 'A','p','p','I','d',0 };
1463     static const WCHAR szAppIdKey[] = { 'A','p','p','I','d','\\',0 };
1464     DWORD res;
1465     WCHAR buf[CHARS_IN_GUID];
1466     WCHAR keyname[ARRAYSIZE(szAppIdKey) + CHARS_IN_GUID];
1467     DWORD size;
1468     HKEY hkey;
1469     DWORD type;
1470     HRESULT hr;
1471
1472     /* read the AppID value under the class's key */
1473     hr = COM_OpenKeyForCLSID(clsid, NULL, KEY_READ, &hkey);
1474     if (FAILED(hr))
1475         return hr;
1476
1477     size = sizeof(buf);
1478     res = RegQueryValueExW(hkey, szAppId, NULL, &type, (LPBYTE)buf, &size);
1479     RegCloseKey(hkey);
1480     if (res == ERROR_FILE_NOT_FOUND)
1481         return REGDB_E_KEYMISSING;
1482     else if (res != ERROR_SUCCESS || type!=REG_SZ)
1483         return REGDB_E_READREGDB;
1484
1485     strcpyW(keyname, szAppIdKey);
1486     strcatW(keyname, buf);
1487     res = RegOpenKeyExW(HKEY_CLASSES_ROOT, keyname, 0, access, subkey);
1488     if (res == ERROR_FILE_NOT_FOUND)
1489         return REGDB_E_KEYMISSING;
1490     else if (res != ERROR_SUCCESS)
1491         return REGDB_E_READREGDB;
1492
1493     return S_OK;
1494 }
1495
1496 /******************************************************************************
1497  *               ProgIDFromCLSID [OLE32.@]
1498  *
1499  * Converts a class id into the respective program ID.
1500  *
1501  * PARAMS
1502  *  clsid        [I] Class ID, as found in registry.
1503  *  ppszProgID [O] Associated ProgID.
1504  *
1505  * RETURNS
1506  *   S_OK
1507  *   E_OUTOFMEMORY
1508  *   REGDB_E_CLASSNOTREG if the given clsid has no associated ProgID
1509  */
1510 HRESULT WINAPI ProgIDFromCLSID(REFCLSID clsid, LPOLESTR *ppszProgID)
1511 {
1512     static const WCHAR wszProgID[] = {'P','r','o','g','I','D',0};
1513     HKEY     hkey;
1514     HRESULT  ret;
1515     LONG progidlen = 0;
1516
1517     if (!ppszProgID)
1518     {
1519         ERR("ppszProgId isn't optional\n");
1520         return E_INVALIDARG;
1521     }
1522
1523     *ppszProgID = NULL;
1524     ret = COM_OpenKeyForCLSID(clsid, wszProgID, KEY_READ, &hkey);
1525     if (FAILED(ret))
1526         return ret;
1527
1528     if (RegQueryValueW(hkey, NULL, NULL, &progidlen))
1529       ret = REGDB_E_CLASSNOTREG;
1530
1531     if (ret == S_OK)
1532     {
1533       *ppszProgID = CoTaskMemAlloc(progidlen * sizeof(WCHAR));
1534       if (*ppszProgID)
1535       {
1536         if (RegQueryValueW(hkey, NULL, *ppszProgID, &progidlen))
1537           ret = REGDB_E_CLASSNOTREG;
1538       }
1539       else
1540         ret = E_OUTOFMEMORY;
1541     }
1542
1543     RegCloseKey(hkey);
1544     return ret;
1545 }
1546
1547 /******************************************************************************
1548  *              CLSIDFromProgID [OLE32.@]
1549  *
1550  * Converts a program id into the respective GUID.
1551  *
1552  * PARAMS
1553  *  progid [I] Unicode program ID, as found in registry.
1554  *  clsid  [O] Associated CLSID.
1555  *
1556  * RETURNS
1557  *      Success: S_OK
1558  *  Failure: CO_E_CLASSSTRING - the given ProgID cannot be found.
1559  */
1560 HRESULT WINAPI CLSIDFromProgID(LPCOLESTR progid, LPCLSID clsid)
1561 {
1562     static const WCHAR clsidW[] = { '\\','C','L','S','I','D',0 };
1563     WCHAR buf2[CHARS_IN_GUID];
1564     LONG buf2len = sizeof(buf2);
1565     HKEY xhkey;
1566     WCHAR *buf;
1567
1568     if (!progid || !clsid)
1569     {
1570         ERR("neither progid (%p) nor clsid (%p) are optional\n", progid, clsid);
1571         return E_INVALIDARG;
1572     }
1573
1574     /* initialise clsid in case of failure */
1575     memset(clsid, 0, sizeof(*clsid));
1576
1577     buf = HeapAlloc( GetProcessHeap(),0,(strlenW(progid)+8) * sizeof(WCHAR) );
1578     strcpyW( buf, progid );
1579     strcatW( buf, clsidW );
1580     if (RegOpenKeyW(HKEY_CLASSES_ROOT,buf,&xhkey))
1581     {
1582         HeapFree(GetProcessHeap(),0,buf);
1583         WARN("couldn't open key for ProgID %s\n", debugstr_w(progid));
1584         return CO_E_CLASSSTRING;
1585     }
1586     HeapFree(GetProcessHeap(),0,buf);
1587
1588     if (RegQueryValueW(xhkey,NULL,buf2,&buf2len))
1589     {
1590         RegCloseKey(xhkey);
1591         WARN("couldn't query clsid value for ProgID %s\n", debugstr_w(progid));
1592         return CO_E_CLASSSTRING;
1593     }
1594     RegCloseKey(xhkey);
1595     return CLSIDFromString(buf2,clsid);
1596 }
1597
1598
1599 /*****************************************************************************
1600  *             CoGetPSClsid [OLE32.@]
1601  *
1602  * Retrieves the CLSID of the proxy/stub factory that implements
1603  * IPSFactoryBuffer for the specified interface.
1604  *
1605  * PARAMS
1606  *  riid   [I] Interface whose proxy/stub CLSID is to be returned.
1607  *  pclsid [O] Where to store returned proxy/stub CLSID.
1608  * 
1609  * RETURNS
1610  *   S_OK
1611  *   E_OUTOFMEMORY
1612  *   REGDB_E_IIDNOTREG if no PSFactoryBuffer is associated with the IID, or it could not be parsed
1613  *
1614  * NOTES
1615  *
1616  * The standard marshaller activates the object with the CLSID
1617  * returned and uses the CreateProxy and CreateStub methods on its
1618  * IPSFactoryBuffer interface to construct the proxies and stubs for a
1619  * given object.
1620  *
1621  * CoGetPSClsid determines this CLSID by searching the
1622  * HKEY_CLASSES_ROOT\Interface\{string form of riid}\ProxyStubClsid32
1623  * in the registry and any interface id registered by
1624  * CoRegisterPSClsid within the current process.
1625  *
1626  * BUGS
1627  *
1628  * Native returns S_OK for interfaces with a key in HKCR\Interface, but
1629  * without a ProxyStubClsid32 key and leaves garbage in pclsid. This should be
1630  * considered a bug in native unless an application depends on this (unlikely).
1631  *
1632  * SEE ALSO
1633  *  CoRegisterPSClsid.
1634  */
1635 HRESULT WINAPI CoGetPSClsid(REFIID riid, CLSID *pclsid)
1636 {
1637     static const WCHAR wszInterface[] = {'I','n','t','e','r','f','a','c','e','\\',0};
1638     static const WCHAR wszPSC[] = {'\\','P','r','o','x','y','S','t','u','b','C','l','s','i','d','3','2',0};
1639     WCHAR path[ARRAYSIZE(wszInterface) - 1 + CHARS_IN_GUID - 1 + ARRAYSIZE(wszPSC)];
1640     WCHAR value[CHARS_IN_GUID];
1641     LONG len;
1642     HKEY hkey;
1643     APARTMENT *apt = COM_CurrentApt();
1644     struct registered_psclsid *registered_psclsid;
1645
1646     TRACE("() riid=%s, pclsid=%p\n", debugstr_guid(riid), pclsid);
1647
1648     if (!apt)
1649     {
1650         ERR("apartment not initialised\n");
1651         return CO_E_NOTINITIALIZED;
1652     }
1653
1654     if (!pclsid)
1655     {
1656         ERR("pclsid isn't optional\n");
1657         return E_INVALIDARG;
1658     }
1659
1660     EnterCriticalSection(&apt->cs);
1661
1662     LIST_FOR_EACH_ENTRY(registered_psclsid, &apt->psclsids, struct registered_psclsid, entry)
1663         if (IsEqualIID(&registered_psclsid->iid, riid))
1664         {
1665             *pclsid = registered_psclsid->clsid;
1666             LeaveCriticalSection(&apt->cs);
1667             return S_OK;
1668         }
1669
1670     LeaveCriticalSection(&apt->cs);
1671
1672     /* Interface\\{string form of riid}\\ProxyStubClsid32 */
1673     strcpyW(path, wszInterface);
1674     StringFromGUID2(riid, path + ARRAYSIZE(wszInterface) - 1, CHARS_IN_GUID);
1675     strcpyW(path + ARRAYSIZE(wszInterface) - 1 + CHARS_IN_GUID - 1, wszPSC);
1676
1677     /* Open the key.. */
1678     if (RegOpenKeyExW(HKEY_CLASSES_ROOT, path, 0, KEY_READ, &hkey))
1679     {
1680         WARN("No PSFactoryBuffer object is registered for IID %s\n", debugstr_guid(riid));
1681         return REGDB_E_IIDNOTREG;
1682     }
1683
1684     /* ... Once we have the key, query the registry to get the
1685        value of CLSID as a string, and convert it into a
1686        proper CLSID structure to be passed back to the app */
1687     len = sizeof(value);
1688     if (ERROR_SUCCESS != RegQueryValueW(hkey, NULL, value, &len))
1689     {
1690         RegCloseKey(hkey);
1691         return REGDB_E_IIDNOTREG;
1692     }
1693     RegCloseKey(hkey);
1694
1695     /* We have the CLSID we want back from the registry as a string, so
1696        let's convert it into a CLSID structure */
1697     if (CLSIDFromString(value, pclsid) != NOERROR)
1698         return REGDB_E_IIDNOTREG;
1699
1700     TRACE ("() Returning CLSID=%s\n", debugstr_guid(pclsid));
1701     return S_OK;
1702 }
1703
1704 /*****************************************************************************
1705  *             CoRegisterPSClsid [OLE32.@]
1706  *
1707  * Register a proxy/stub CLSID for the given interface in the current process
1708  * only.
1709  *
1710  * PARAMS
1711  *  riid   [I] Interface whose proxy/stub CLSID is to be registered.
1712  *  rclsid [I] CLSID of the proxy/stub.
1713  * 
1714  * RETURNS
1715  *   Success: S_OK
1716  *   Failure: E_OUTOFMEMORY
1717  *
1718  * NOTES
1719  *
1720  * This function does not add anything to the registry and the effects are
1721  * limited to the lifetime of the current process.
1722  *
1723  * SEE ALSO
1724  *  CoGetPSClsid.
1725  */
1726 HRESULT WINAPI CoRegisterPSClsid(REFIID riid, REFCLSID rclsid)
1727 {
1728     APARTMENT *apt = COM_CurrentApt();
1729     struct registered_psclsid *registered_psclsid;
1730
1731     TRACE("(%s, %s)\n", debugstr_guid(riid), debugstr_guid(rclsid));
1732
1733     if (!apt)
1734     {
1735         ERR("apartment not initialised\n");
1736         return CO_E_NOTINITIALIZED;
1737     }
1738
1739     EnterCriticalSection(&apt->cs);
1740
1741     LIST_FOR_EACH_ENTRY(registered_psclsid, &apt->psclsids, struct registered_psclsid, entry)
1742         if (IsEqualIID(&registered_psclsid->iid, riid))
1743         {
1744             registered_psclsid->clsid = *rclsid;
1745             LeaveCriticalSection(&apt->cs);
1746             return S_OK;
1747         }
1748
1749     registered_psclsid = HeapAlloc(GetProcessHeap(), 0, sizeof(struct registered_psclsid));
1750     if (!registered_psclsid)
1751     {
1752         LeaveCriticalSection(&apt->cs);
1753         return E_OUTOFMEMORY;
1754     }
1755
1756     registered_psclsid->iid = *riid;
1757     registered_psclsid->clsid = *rclsid;
1758     list_add_head(&apt->psclsids, &registered_psclsid->entry);
1759
1760     LeaveCriticalSection(&apt->cs);
1761
1762     return S_OK;
1763 }
1764
1765
1766 /***
1767  * COM_GetRegisteredClassObject
1768  *
1769  * This internal method is used to scan the registered class list to
1770  * find a class object.
1771  *
1772  * Params:
1773  *   rclsid        Class ID of the class to find.
1774  *   dwClsContext  Class context to match.
1775  *   ppv           [out] returns a pointer to the class object. Complying
1776  *                 to normal COM usage, this method will increase the
1777  *                 reference count on this object.
1778  */
1779 static HRESULT COM_GetRegisteredClassObject(const struct apartment *apt, REFCLSID rclsid,
1780                                             DWORD dwClsContext, LPUNKNOWN* ppUnk)
1781 {
1782   HRESULT hr = S_FALSE;
1783   RegisteredClass *curClass;
1784
1785   EnterCriticalSection( &csRegisteredClassList );
1786
1787   LIST_FOR_EACH_ENTRY(curClass, &RegisteredClassList, RegisteredClass, entry)
1788   {
1789     /*
1790      * Check if we have a match on the class ID and context.
1791      */
1792     if ((apt->oxid == curClass->apartment_id) &&
1793         (dwClsContext & curClass->runContext) &&
1794         IsEqualGUID(&(curClass->classIdentifier), rclsid))
1795     {
1796       /*
1797        * We have a match, return the pointer to the class object.
1798        */
1799       *ppUnk = curClass->classObject;
1800
1801       IUnknown_AddRef(curClass->classObject);
1802
1803       hr = S_OK;
1804       break;
1805     }
1806   }
1807
1808   LeaveCriticalSection( &csRegisteredClassList );
1809
1810   return hr;
1811 }
1812
1813 /******************************************************************************
1814  *              CoRegisterClassObject   [OLE32.@]
1815  *
1816  * Registers the class object for a given class ID. Servers housed in EXE
1817  * files use this method instead of exporting DllGetClassObject to allow
1818  * other code to connect to their objects.
1819  *
1820  * PARAMS
1821  *  rclsid       [I] CLSID of the object to register.
1822  *  pUnk         [I] IUnknown of the object.
1823  *  dwClsContext [I] CLSCTX flags indicating the context in which to run the executable.
1824  *  flags        [I] REGCLS flags indicating how connections are made.
1825  *  lpdwRegister [I] A unique cookie that can be passed to CoRevokeClassObject.
1826  *
1827  * RETURNS
1828  *   S_OK on success,
1829  *   E_INVALIDARG if lpdwRegister or pUnk are NULL,
1830  *   CO_E_OBJISREG if the object is already registered. We should not return this.
1831  *
1832  * SEE ALSO
1833  *   CoRevokeClassObject, CoGetClassObject
1834  *
1835  * NOTES
1836  *  In-process objects are only registered for the current apartment.
1837  *  CoGetClassObject() and CoCreateInstance() will not return objects registered
1838  *  in other apartments.
1839  *
1840  * BUGS
1841  *  MSDN claims that multiple interface registrations are legal, but we
1842  *  can't do that with our current implementation.
1843  */
1844 HRESULT WINAPI CoRegisterClassObject(
1845     REFCLSID rclsid,
1846     LPUNKNOWN pUnk,
1847     DWORD dwClsContext,
1848     DWORD flags,
1849     LPDWORD lpdwRegister)
1850 {
1851   RegisteredClass* newClass;
1852   LPUNKNOWN        foundObject;
1853   HRESULT          hr;
1854   APARTMENT *apt;
1855
1856   TRACE("(%s,%p,0x%08x,0x%08x,%p)\n",
1857         debugstr_guid(rclsid),pUnk,dwClsContext,flags,lpdwRegister);
1858
1859   if ( (lpdwRegister==0) || (pUnk==0) )
1860     return E_INVALIDARG;
1861
1862   apt = COM_CurrentApt();
1863   if (!apt)
1864   {
1865       ERR("COM was not initialized\n");
1866       return CO_E_NOTINITIALIZED;
1867   }
1868
1869   *lpdwRegister = 0;
1870
1871   /* REGCLS_MULTIPLEUSE implies registering as inproc server. This is what
1872    * differentiates the flag from REGCLS_MULTI_SEPARATE. */
1873   if (flags & REGCLS_MULTIPLEUSE)
1874     dwClsContext |= CLSCTX_INPROC_SERVER;
1875
1876   /*
1877    * First, check if the class is already registered.
1878    * If it is, this should cause an error.
1879    */
1880   hr = COM_GetRegisteredClassObject(apt, rclsid, dwClsContext, &foundObject);
1881   if (hr == S_OK) {
1882     if (flags & REGCLS_MULTIPLEUSE) {
1883       if (dwClsContext & CLSCTX_LOCAL_SERVER)
1884         hr = CoLockObjectExternal(foundObject, TRUE, FALSE);
1885       IUnknown_Release(foundObject);
1886       return hr;
1887     }
1888     IUnknown_Release(foundObject);
1889     ERR("object already registered for class %s\n", debugstr_guid(rclsid));
1890     return CO_E_OBJISREG;
1891   }
1892
1893   newClass = HeapAlloc(GetProcessHeap(), 0, sizeof(RegisteredClass));
1894   if ( newClass == NULL )
1895     return E_OUTOFMEMORY;
1896
1897   newClass->classIdentifier = *rclsid;
1898   newClass->apartment_id    = apt->oxid;
1899   newClass->runContext      = dwClsContext;
1900   newClass->connectFlags    = flags;
1901   newClass->pMarshaledData  = NULL;
1902   newClass->RpcRegistration = NULL;
1903
1904   /*
1905    * Use the address of the chain node as the cookie since we are sure it's
1906    * unique. FIXME: not on 64-bit platforms.
1907    */
1908   newClass->dwCookie        = (DWORD)newClass;
1909
1910   /*
1911    * Since we're making a copy of the object pointer, we have to increase its
1912    * reference count.
1913    */
1914   newClass->classObject     = pUnk;
1915   IUnknown_AddRef(newClass->classObject);
1916
1917   EnterCriticalSection( &csRegisteredClassList );
1918   list_add_tail(&RegisteredClassList, &newClass->entry);
1919   LeaveCriticalSection( &csRegisteredClassList );
1920
1921   *lpdwRegister = newClass->dwCookie;
1922
1923   if (dwClsContext & CLSCTX_LOCAL_SERVER) {
1924       hr = CreateStreamOnHGlobal(0, TRUE, &newClass->pMarshaledData);
1925       if (hr) {
1926           FIXME("Failed to create stream on hglobal, %x\n", hr);
1927           return hr;
1928       }
1929       hr = CoMarshalInterface(newClass->pMarshaledData, &IID_IClassFactory,
1930                               newClass->classObject, MSHCTX_LOCAL, NULL,
1931                               MSHLFLAGS_TABLESTRONG);
1932       if (hr) {
1933           FIXME("CoMarshalInterface failed, %x!\n",hr);
1934           return hr;
1935       }
1936
1937       hr = RPC_StartLocalServer(&newClass->classIdentifier,
1938                                 newClass->pMarshaledData,
1939                                 flags & (REGCLS_MULTIPLEUSE|REGCLS_MULTI_SEPARATE),
1940                                 &newClass->RpcRegistration);
1941   }
1942   return S_OK;
1943 }
1944
1945 static void COM_RevokeRegisteredClassObject(RegisteredClass *curClass)
1946 {
1947     list_remove(&curClass->entry);
1948
1949     if (curClass->runContext & CLSCTX_LOCAL_SERVER)
1950         RPC_StopLocalServer(curClass->RpcRegistration);
1951
1952     /*
1953      * Release the reference to the class object.
1954      */
1955     IUnknown_Release(curClass->classObject);
1956
1957     if (curClass->pMarshaledData)
1958     {
1959         LARGE_INTEGER zero;
1960         memset(&zero, 0, sizeof(zero));
1961         IStream_Seek(curClass->pMarshaledData, zero, STREAM_SEEK_SET, NULL);
1962         CoReleaseMarshalData(curClass->pMarshaledData);
1963         IStream_Release(curClass->pMarshaledData);
1964     }
1965
1966     HeapFree(GetProcessHeap(), 0, curClass);
1967 }
1968
1969 static void COM_RevokeAllClasses(const struct apartment *apt)
1970 {
1971   RegisteredClass *curClass, *cursor;
1972
1973   EnterCriticalSection( &csRegisteredClassList );
1974
1975   LIST_FOR_EACH_ENTRY_SAFE(curClass, cursor, &RegisteredClassList, RegisteredClass, entry)
1976   {
1977     if (curClass->apartment_id == apt->oxid)
1978       COM_RevokeRegisteredClassObject(curClass);
1979   }
1980
1981   LeaveCriticalSection( &csRegisteredClassList );
1982 }
1983
1984 /***********************************************************************
1985  *           CoRevokeClassObject [OLE32.@]
1986  *
1987  * Removes a class object from the class registry.
1988  *
1989  * PARAMS
1990  *  dwRegister [I] Cookie returned from CoRegisterClassObject().
1991  *
1992  * RETURNS
1993  *  Success: S_OK.
1994  *  Failure: HRESULT code.
1995  *
1996  * NOTES
1997  *  Must be called from the same apartment that called CoRegisterClassObject(),
1998  *  otherwise it will fail with RPC_E_WRONG_THREAD.
1999  *
2000  * SEE ALSO
2001  *  CoRegisterClassObject
2002  */
2003 HRESULT WINAPI CoRevokeClassObject(
2004         DWORD dwRegister)
2005 {
2006   HRESULT hr = E_INVALIDARG;
2007   RegisteredClass *curClass;
2008   APARTMENT *apt;
2009
2010   TRACE("(%08x)\n",dwRegister);
2011
2012   apt = COM_CurrentApt();
2013   if (!apt)
2014   {
2015     ERR("COM was not initialized\n");
2016     return CO_E_NOTINITIALIZED;
2017   }
2018
2019   EnterCriticalSection( &csRegisteredClassList );
2020
2021   LIST_FOR_EACH_ENTRY(curClass, &RegisteredClassList, RegisteredClass, entry)
2022   {
2023     /*
2024      * Check if we have a match on the cookie.
2025      */
2026     if (curClass->dwCookie == dwRegister)
2027     {
2028       if (curClass->apartment_id == apt->oxid)
2029       {
2030           COM_RevokeRegisteredClassObject(curClass);
2031           hr = S_OK;
2032       }
2033       else
2034       {
2035           ERR("called from wrong apartment, should be called from %s\n",
2036               wine_dbgstr_longlong(curClass->apartment_id));
2037           hr = RPC_E_WRONG_THREAD;
2038       }
2039       break;
2040     }
2041   }
2042
2043   LeaveCriticalSection( &csRegisteredClassList );
2044
2045   return hr;
2046 }
2047
2048 /***********************************************************************
2049  *      COM_RegReadPath [internal]
2050  *
2051  *      Reads a registry value and expands it when necessary
2052  */
2053 static DWORD COM_RegReadPath(HKEY hkeyroot, const WCHAR *keyname, const WCHAR *valuename, WCHAR * dst, DWORD dstlen)
2054 {
2055         DWORD ret;
2056         HKEY key;
2057         DWORD keytype;
2058         WCHAR src[MAX_PATH];
2059         DWORD dwLength = dstlen * sizeof(WCHAR);
2060
2061         if((ret = RegOpenKeyExW(hkeyroot, keyname, 0, KEY_READ, &key)) == ERROR_SUCCESS) {
2062           if( (ret = RegQueryValueExW(key, NULL, NULL, &keytype, (LPBYTE)src, &dwLength)) == ERROR_SUCCESS ) {
2063             if (keytype == REG_EXPAND_SZ) {
2064               if (dstlen <= ExpandEnvironmentStringsW(src, dst, dstlen)) ret = ERROR_MORE_DATA;
2065             } else {
2066               lstrcpynW(dst, src, dstlen);
2067             }
2068           }
2069           RegCloseKey (key);
2070         }
2071         return ret;
2072 }
2073
2074 static void get_threading_model(HKEY key, LPWSTR value, DWORD len)
2075 {
2076     static const WCHAR wszThreadingModel[] = {'T','h','r','e','a','d','i','n','g','M','o','d','e','l',0};
2077     DWORD keytype;
2078     DWORD ret;
2079     DWORD dwLength = len * sizeof(WCHAR);
2080
2081     ret = RegQueryValueExW(key, wszThreadingModel, NULL, &keytype, (LPBYTE)value, &dwLength);
2082     if ((ret != ERROR_SUCCESS) || (keytype != REG_SZ))
2083         value[0] = '\0';
2084 }
2085
2086 static HRESULT get_inproc_class_object(APARTMENT *apt, HKEY hkeydll,
2087                                        REFCLSID rclsid, REFIID riid,
2088                                        BOOL hostifnecessary, void **ppv)
2089 {
2090     WCHAR dllpath[MAX_PATH+1];
2091     BOOL apartment_threaded;
2092
2093     if (hostifnecessary)
2094     {
2095         static const WCHAR wszApartment[] = {'A','p','a','r','t','m','e','n','t',0};
2096         static const WCHAR wszFree[] = {'F','r','e','e',0};
2097         static const WCHAR wszBoth[] = {'B','o','t','h',0};
2098         WCHAR threading_model[10 /* strlenW(L"apartment")+1 */];
2099
2100         get_threading_model(hkeydll, threading_model, ARRAYSIZE(threading_model));
2101         /* "Apartment" */
2102         if (!strcmpiW(threading_model, wszApartment))
2103         {
2104             apartment_threaded = TRUE;
2105             if (apt->multi_threaded)
2106                 return apartment_hostobject_in_hostapt(apt, FALSE, FALSE, hkeydll, rclsid, riid, ppv);
2107         }
2108         /* "Free" */
2109         else if (!strcmpiW(threading_model, wszFree))
2110         {
2111             apartment_threaded = FALSE;
2112             if (!apt->multi_threaded)
2113                 return apartment_hostobject_in_hostapt(apt, TRUE, FALSE, hkeydll, rclsid, riid, ppv);
2114         }
2115         /* everything except "Apartment", "Free" and "Both" */
2116         else if (strcmpiW(threading_model, wszBoth))
2117         {
2118             apartment_threaded = TRUE;
2119             /* everything else is main-threaded */
2120             if (threading_model[0])
2121                 FIXME("unrecognised threading model %s for object %s, should be main-threaded?\n",
2122                     debugstr_w(threading_model), debugstr_guid(rclsid));
2123
2124             if (apt->multi_threaded || !apt->main)
2125                 return apartment_hostobject_in_hostapt(apt, FALSE, TRUE, hkeydll, rclsid, riid, ppv);
2126         }
2127         else
2128             apartment_threaded = FALSE;
2129     }
2130     else
2131         apartment_threaded = !apt->multi_threaded;
2132
2133     if (COM_RegReadPath(hkeydll, NULL, NULL, dllpath, ARRAYSIZE(dllpath)) != ERROR_SUCCESS)
2134     {
2135         /* failure: CLSID is not found in registry */
2136         WARN("class %s not registered inproc\n", debugstr_guid(rclsid));
2137         return REGDB_E_CLASSNOTREG;
2138     }
2139
2140     return apartment_getclassobject(apt, dllpath, apartment_threaded,
2141                                     rclsid, riid, ppv);
2142 }
2143
2144 /***********************************************************************
2145  *           CoGetClassObject [OLE32.@]
2146  *
2147  * Creates an object of the specified class.
2148  *
2149  * PARAMS
2150  *  rclsid       [I] Class ID to create an instance of.
2151  *  dwClsContext [I] Flags to restrict the location of the created instance.
2152  *  pServerInfo  [I] Optional. Details for connecting to a remote server.
2153  *  iid          [I] The ID of the interface of the instance to return.
2154  *  ppv          [O] On returns, contains a pointer to the specified interface of the object.
2155  *
2156  * RETURNS
2157  *  Success: S_OK
2158  *  Failure: HRESULT code.
2159  *
2160  * NOTES
2161  *  The dwClsContext parameter can be one or more of the following:
2162  *| CLSCTX_INPROC_SERVER - Use an in-process server, such as from a DLL.
2163  *| CLSCTX_INPROC_HANDLER - Use an in-process object which handles certain functions for an object running in another process.
2164  *| CLSCTX_LOCAL_SERVER - Connect to an object running in another process.
2165  *| CLSCTX_REMOTE_SERVER - Connect to an object running on another machine.
2166  *
2167  * SEE ALSO
2168  *  CoCreateInstance()
2169  */
2170 HRESULT WINAPI CoGetClassObject(
2171     REFCLSID rclsid, DWORD dwClsContext, COSERVERINFO *pServerInfo,
2172     REFIID iid, LPVOID *ppv)
2173 {
2174     LPUNKNOWN   regClassObject;
2175     HRESULT     hres = E_UNEXPECTED;
2176     APARTMENT  *apt;
2177
2178     TRACE("\n\tCLSID:\t%s,\n\tIID:\t%s\n", debugstr_guid(rclsid), debugstr_guid(iid));
2179
2180     if (!ppv)
2181         return E_INVALIDARG;
2182
2183     *ppv = NULL;
2184
2185     apt = COM_CurrentApt();
2186     if (!apt)
2187     {
2188         ERR("apartment not initialised\n");
2189         return CO_E_NOTINITIALIZED;
2190     }
2191
2192     if (pServerInfo) {
2193         FIXME("\tpServerInfo: name=%s\n",debugstr_w(pServerInfo->pwszName));
2194         FIXME("\t\tpAuthInfo=%p\n",pServerInfo->pAuthInfo);
2195     }
2196
2197     /*
2198      * First, try and see if we can't match the class ID with one of the
2199      * registered classes.
2200      */
2201     if (S_OK == COM_GetRegisteredClassObject(apt, rclsid, dwClsContext,
2202                                              &regClassObject))
2203     {
2204       /* Get the required interface from the retrieved pointer. */
2205       hres = IUnknown_QueryInterface(regClassObject, iid, ppv);
2206
2207       /*
2208        * Since QI got another reference on the pointer, we want to release the
2209        * one we already have. If QI was unsuccessful, this will release the object. This
2210        * is good since we are not returning it in the "out" parameter.
2211        */
2212       IUnknown_Release(regClassObject);
2213
2214       return hres;
2215     }
2216
2217     /* First try in-process server */
2218     if (CLSCTX_INPROC_SERVER & dwClsContext)
2219     {
2220         static const WCHAR wszInprocServer32[] = {'I','n','p','r','o','c','S','e','r','v','e','r','3','2',0};
2221         HKEY hkey;
2222
2223         if (IsEqualCLSID(rclsid, &CLSID_InProcFreeMarshaler))
2224             return FTMarshalCF_Create(iid, ppv);
2225
2226         hres = COM_OpenKeyForCLSID(rclsid, wszInprocServer32, KEY_READ, &hkey);
2227         if (FAILED(hres))
2228         {
2229             if (hres == REGDB_E_CLASSNOTREG)
2230                 ERR("class %s not registered\n", debugstr_guid(rclsid));
2231             else if (hres == REGDB_E_KEYMISSING)
2232             {
2233                 WARN("class %s not registered as in-proc server\n", debugstr_guid(rclsid));
2234                 hres = REGDB_E_CLASSNOTREG;
2235             }
2236         }
2237
2238         if (SUCCEEDED(hres))
2239         {
2240             hres = get_inproc_class_object(apt, hkey, rclsid, iid,
2241                 !(dwClsContext & WINE_CLSCTX_DONT_HOST), ppv);
2242             RegCloseKey(hkey);
2243         }
2244
2245         /* return if we got a class, otherwise fall through to one of the
2246          * other types */
2247         if (SUCCEEDED(hres))
2248             return hres;
2249     }
2250
2251     /* Next try in-process handler */
2252     if (CLSCTX_INPROC_HANDLER & dwClsContext)
2253     {
2254         static const WCHAR wszInprocHandler32[] = {'I','n','p','r','o','c','H','a','n','d','l','e','r','3','2',0};
2255         HKEY hkey;
2256
2257         hres = COM_OpenKeyForCLSID(rclsid, wszInprocHandler32, KEY_READ, &hkey);
2258         if (FAILED(hres))
2259         {
2260             if (hres == REGDB_E_CLASSNOTREG)
2261                 ERR("class %s not registered\n", debugstr_guid(rclsid));
2262             else if (hres == REGDB_E_KEYMISSING)
2263             {
2264                 WARN("class %s not registered in-proc handler\n", debugstr_guid(rclsid));
2265                 hres = REGDB_E_CLASSNOTREG;
2266             }
2267         }
2268
2269         if (SUCCEEDED(hres))
2270         {
2271             hres = get_inproc_class_object(apt, hkey, rclsid, iid,
2272                 !(dwClsContext & WINE_CLSCTX_DONT_HOST), ppv);
2273             RegCloseKey(hkey);
2274         }
2275
2276         /* return if we got a class, otherwise fall through to one of the
2277          * other types */
2278         if (SUCCEEDED(hres))
2279             return hres;
2280     }
2281
2282     /* Next try out of process */
2283     if (CLSCTX_LOCAL_SERVER & dwClsContext)
2284     {
2285         hres = RPC_GetLocalClassObject(rclsid,iid,ppv);
2286         if (SUCCEEDED(hres))
2287             return hres;
2288     }
2289
2290     /* Finally try remote: this requires networked DCOM (a lot of work) */
2291     if (CLSCTX_REMOTE_SERVER & dwClsContext)
2292     {
2293         FIXME ("CLSCTX_REMOTE_SERVER not supported\n");
2294         hres = E_NOINTERFACE;
2295     }
2296
2297     if (FAILED(hres))
2298         ERR("no class object %s could be created for context 0x%x\n",
2299             debugstr_guid(rclsid), dwClsContext);
2300     return hres;
2301 }
2302
2303 /***********************************************************************
2304  *        CoResumeClassObjects (OLE32.@)
2305  *
2306  * Resumes all class objects registered with REGCLS_SUSPENDED.
2307  *
2308  * RETURNS
2309  *  Success: S_OK.
2310  *  Failure: HRESULT code.
2311  */
2312 HRESULT WINAPI CoResumeClassObjects(void)
2313 {
2314        FIXME("stub\n");
2315         return S_OK;
2316 }
2317
2318 /***********************************************************************
2319  *           CoCreateInstance [OLE32.@]
2320  *
2321  * Creates an instance of the specified class.
2322  *
2323  * PARAMS
2324  *  rclsid       [I] Class ID to create an instance of.
2325  *  pUnkOuter    [I] Optional outer unknown to allow aggregation with another object.
2326  *  dwClsContext [I] Flags to restrict the location of the created instance.
2327  *  iid          [I] The ID of the interface of the instance to return.
2328  *  ppv          [O] On returns, contains a pointer to the specified interface of the instance.
2329  *
2330  * RETURNS
2331  *  Success: S_OK
2332  *  Failure: HRESULT code.
2333  *
2334  * NOTES
2335  *  The dwClsContext parameter can be one or more of the following:
2336  *| CLSCTX_INPROC_SERVER - Use an in-process server, such as from a DLL.
2337  *| CLSCTX_INPROC_HANDLER - Use an in-process object which handles certain functions for an object running in another process.
2338  *| CLSCTX_LOCAL_SERVER - Connect to an object running in another process.
2339  *| CLSCTX_REMOTE_SERVER - Connect to an object running on another machine.
2340  *
2341  * Aggregation is the concept of deferring the IUnknown of an object to another
2342  * object. This allows a separate object to behave as though it was part of
2343  * the object and to allow this the pUnkOuter parameter can be set. Note that
2344  * not all objects support having an outer of unknown.
2345  *
2346  * SEE ALSO
2347  *  CoGetClassObject()
2348  */
2349 HRESULT WINAPI CoCreateInstance(
2350         REFCLSID rclsid,
2351         LPUNKNOWN pUnkOuter,
2352         DWORD dwClsContext,
2353         REFIID iid,
2354         LPVOID *ppv)
2355 {
2356   HRESULT hres;
2357   LPCLASSFACTORY lpclf = 0;
2358
2359   TRACE("(rclsid=%s, pUnkOuter=%p, dwClsContext=%08x, riid=%s, ppv=%p)\n", debugstr_guid(rclsid),
2360         pUnkOuter, dwClsContext, debugstr_guid(iid), ppv);
2361
2362   /*
2363    * Sanity check
2364    */
2365   if (ppv==0)
2366     return E_POINTER;
2367
2368   /*
2369    * Initialize the "out" parameter
2370    */
2371   *ppv = 0;
2372
2373   if (!COM_CurrentApt())
2374   {
2375       ERR("apartment not initialised\n");
2376       return CO_E_NOTINITIALIZED;
2377   }
2378
2379   /*
2380    * The Standard Global Interface Table (GIT) object is a process-wide singleton.
2381    * Rather than create a class factory, we can just check for it here
2382    */
2383   if (IsEqualIID(rclsid, &CLSID_StdGlobalInterfaceTable)) {
2384     if (StdGlobalInterfaceTableInstance == NULL)
2385       StdGlobalInterfaceTableInstance = StdGlobalInterfaceTable_Construct();
2386     hres = IGlobalInterfaceTable_QueryInterface( (IGlobalInterfaceTable*) StdGlobalInterfaceTableInstance, iid, ppv);
2387     if (hres) return hres;
2388
2389     TRACE("Retrieved GIT (%p)\n", *ppv);
2390     return S_OK;
2391   }
2392
2393   /*
2394    * Get a class factory to construct the object we want.
2395    */
2396   hres = CoGetClassObject(rclsid,
2397                           dwClsContext,
2398                           NULL,
2399                           &IID_IClassFactory,
2400                           (LPVOID)&lpclf);
2401
2402   if (FAILED(hres))
2403     return hres;
2404
2405   /*
2406    * Create the object and don't forget to release the factory
2407    */
2408         hres = IClassFactory_CreateInstance(lpclf, pUnkOuter, iid, ppv);
2409         IClassFactory_Release(lpclf);
2410         if(FAILED(hres))
2411         {
2412           if (hres == CLASS_E_NOAGGREGATION && pUnkOuter)
2413               FIXME("Class %s does not support aggregation\n", debugstr_guid(rclsid));
2414           else
2415               FIXME("no instance created for interface %s of class %s, hres is 0x%08x\n", debugstr_guid(iid), debugstr_guid(rclsid),hres);
2416         }
2417
2418         return hres;
2419 }
2420
2421 /***********************************************************************
2422  *           CoCreateInstanceEx [OLE32.@]
2423  */
2424 HRESULT WINAPI CoCreateInstanceEx(
2425   REFCLSID      rclsid,
2426   LPUNKNOWN     pUnkOuter,
2427   DWORD         dwClsContext,
2428   COSERVERINFO* pServerInfo,
2429   ULONG         cmq,
2430   MULTI_QI*     pResults)
2431 {
2432   IUnknown* pUnk = NULL;
2433   HRESULT   hr;
2434   ULONG     index;
2435   ULONG     successCount = 0;
2436
2437   /*
2438    * Sanity check
2439    */
2440   if ( (cmq==0) || (pResults==NULL))
2441     return E_INVALIDARG;
2442
2443   if (pServerInfo!=NULL)
2444     FIXME("() non-NULL pServerInfo not supported!\n");
2445
2446   /*
2447    * Initialize all the "out" parameters.
2448    */
2449   for (index = 0; index < cmq; index++)
2450   {
2451     pResults[index].pItf = NULL;
2452     pResults[index].hr   = E_NOINTERFACE;
2453   }
2454
2455   /*
2456    * Get the object and get its IUnknown pointer.
2457    */
2458   hr = CoCreateInstance(rclsid,
2459                         pUnkOuter,
2460                         dwClsContext,
2461                         &IID_IUnknown,
2462                         (VOID**)&pUnk);
2463
2464   if (hr)
2465     return hr;
2466
2467   /*
2468    * Then, query for all the interfaces requested.
2469    */
2470   for (index = 0; index < cmq; index++)
2471   {
2472     pResults[index].hr = IUnknown_QueryInterface(pUnk,
2473                                                  pResults[index].pIID,
2474                                                  (VOID**)&(pResults[index].pItf));
2475
2476     if (pResults[index].hr == S_OK)
2477       successCount++;
2478   }
2479
2480   /*
2481    * Release our temporary unknown pointer.
2482    */
2483   IUnknown_Release(pUnk);
2484
2485   if (successCount == 0)
2486     return E_NOINTERFACE;
2487
2488   if (successCount!=cmq)
2489     return CO_S_NOTALLINTERFACES;
2490
2491   return S_OK;
2492 }
2493
2494 /***********************************************************************
2495  *           CoLoadLibrary (OLE32.@)
2496  *
2497  * Loads a library.
2498  *
2499  * PARAMS
2500  *  lpszLibName [I] Path to library.
2501  *  bAutoFree   [I] Whether the library should automatically be freed.
2502  *
2503  * RETURNS
2504  *  Success: Handle to loaded library.
2505  *  Failure: NULL.
2506  *
2507  * SEE ALSO
2508  *  CoFreeLibrary, CoFreeAllLibraries, CoFreeUnusedLibraries
2509  */
2510 HINSTANCE WINAPI CoLoadLibrary(LPOLESTR lpszLibName, BOOL bAutoFree)
2511 {
2512     TRACE("(%s, %d)\n", debugstr_w(lpszLibName), bAutoFree);
2513
2514     return LoadLibraryExW(lpszLibName, 0, LOAD_WITH_ALTERED_SEARCH_PATH);
2515 }
2516
2517 /***********************************************************************
2518  *           CoFreeLibrary [OLE32.@]
2519  *
2520  * Unloads a library from memory.
2521  *
2522  * PARAMS
2523  *  hLibrary [I] Handle to library to unload.
2524  *
2525  * RETURNS
2526  *  Nothing
2527  *
2528  * SEE ALSO
2529  *  CoLoadLibrary, CoFreeAllLibraries, CoFreeUnusedLibraries
2530  */
2531 void WINAPI CoFreeLibrary(HINSTANCE hLibrary)
2532 {
2533     FreeLibrary(hLibrary);
2534 }
2535
2536
2537 /***********************************************************************
2538  *           CoFreeAllLibraries [OLE32.@]
2539  *
2540  * Function for backwards compatibility only. Does nothing.
2541  *
2542  * RETURNS
2543  *  Nothing.
2544  *
2545  * SEE ALSO
2546  *  CoLoadLibrary, CoFreeLibrary, CoFreeUnusedLibraries
2547  */
2548 void WINAPI CoFreeAllLibraries(void)
2549 {
2550     /* NOP */
2551 }
2552
2553 /***********************************************************************
2554  *           CoFreeUnusedLibrariesEx [OLE32.@]
2555  *
2556  * Frees any previously unused libraries whose delay has expired and marks
2557  * currently unused libraries for unloading. Unused are identified as those that
2558  * return S_OK from their DllCanUnloadNow function.
2559  *
2560  * PARAMS
2561  *  dwUnloadDelay [I] Unload delay in milliseconds.
2562  *  dwReserved    [I] Reserved. Set to 0.
2563  *
2564  * RETURNS
2565  *  Nothing.
2566  *
2567  * SEE ALSO
2568  *  CoLoadLibrary, CoFreeAllLibraries, CoFreeLibrary
2569  */
2570 void WINAPI CoFreeUnusedLibrariesEx(DWORD dwUnloadDelay, DWORD dwReserved)
2571 {
2572     struct apartment *apt = COM_CurrentApt();
2573     if (!apt)
2574     {
2575         ERR("apartment not initialised\n");
2576         return;
2577     }
2578
2579     apartment_freeunusedlibraries(apt, dwUnloadDelay);
2580 }
2581
2582 /***********************************************************************
2583  *           CoFreeUnusedLibraries [OLE32.@]
2584  *           CoFreeUnusedLibraries [COMPOBJ.17]
2585  *
2586  * Frees any unused libraries. Unused are identified as those that return
2587  * S_OK from their DllCanUnloadNow function.
2588  *
2589  * RETURNS
2590  *  Nothing.
2591  *
2592  * SEE ALSO
2593  *  CoLoadLibrary, CoFreeAllLibraries, CoFreeLibrary
2594  */
2595 void WINAPI CoFreeUnusedLibraries(void)
2596 {
2597     CoFreeUnusedLibrariesEx(INFINITE, 0);
2598 }
2599
2600 /***********************************************************************
2601  *           CoFileTimeNow [OLE32.@]
2602  *           CoFileTimeNow [COMPOBJ.82]
2603  *
2604  * Retrieves the current time in FILETIME format.
2605  *
2606  * PARAMS
2607  *  lpFileTime [O] The current time.
2608  *
2609  * RETURNS
2610  *      S_OK.
2611  */
2612 HRESULT WINAPI CoFileTimeNow( FILETIME *lpFileTime )
2613 {
2614     GetSystemTimeAsFileTime( lpFileTime );
2615     return S_OK;
2616 }
2617
2618 /******************************************************************************
2619  *              CoLockObjectExternal    [OLE32.@]
2620  *
2621  * Increments or decrements the external reference count of a stub object.
2622  *
2623  * PARAMS
2624  *  pUnk                [I] Stub object.
2625  *  fLock               [I] If TRUE then increments the external ref-count,
2626  *                          otherwise decrements.
2627  *  fLastUnlockReleases [I] If TRUE then the last unlock has the effect of
2628  *                          calling CoDisconnectObject.
2629  *
2630  * RETURNS
2631  *  Success: S_OK.
2632  *  Failure: HRESULT code.
2633  *
2634  * NOTES
2635  *  If fLock is TRUE and an object is passed in that doesn't have a stub
2636  *  manager then a new stub manager is created for the object.
2637  */
2638 HRESULT WINAPI CoLockObjectExternal(
2639     LPUNKNOWN pUnk,
2640     BOOL fLock,
2641     BOOL fLastUnlockReleases)
2642 {
2643     struct stub_manager *stubmgr;
2644     struct apartment *apt;
2645
2646     TRACE("pUnk=%p, fLock=%s, fLastUnlockReleases=%s\n",
2647           pUnk, fLock ? "TRUE" : "FALSE", fLastUnlockReleases ? "TRUE" : "FALSE");
2648
2649     apt = COM_CurrentApt();
2650     if (!apt) return CO_E_NOTINITIALIZED;
2651
2652     stubmgr = get_stub_manager_from_object(apt, pUnk);
2653     
2654     if (stubmgr)
2655     {
2656         if (fLock)
2657             stub_manager_ext_addref(stubmgr, 1, FALSE);
2658         else
2659             stub_manager_ext_release(stubmgr, 1, FALSE, fLastUnlockReleases);
2660         
2661         stub_manager_int_release(stubmgr);
2662
2663         return S_OK;
2664     }
2665     else if (fLock)
2666     {
2667         stubmgr = new_stub_manager(apt, pUnk);
2668
2669         if (stubmgr)
2670         {
2671             stub_manager_ext_addref(stubmgr, 1, FALSE);
2672             stub_manager_int_release(stubmgr);
2673         }
2674
2675         return S_OK;
2676     }
2677     else
2678     {
2679         WARN("stub object not found %p\n", pUnk);
2680         /* Note: native is pretty broken here because it just silently
2681          * fails, without returning an appropriate error code, making apps
2682          * think that the object was disconnected, when it actually wasn't */
2683         return S_OK;
2684     }
2685 }
2686
2687 /***********************************************************************
2688  *           CoInitializeWOW (OLE32.@)
2689  *
2690  * WOW equivalent of CoInitialize?
2691  *
2692  * PARAMS
2693  *  x [I] Unknown.
2694  *  y [I] Unknown.
2695  *
2696  * RETURNS
2697  *  Unknown.
2698  */
2699 HRESULT WINAPI CoInitializeWOW(DWORD x,DWORD y)
2700 {
2701     FIXME("(0x%08x,0x%08x),stub!\n",x,y);
2702     return 0;
2703 }
2704
2705 /***********************************************************************
2706  *           CoGetState [OLE32.@]
2707  *
2708  * Retrieves the thread state object previously stored by CoSetState().
2709  *
2710  * PARAMS
2711  *  ppv [I] Address where pointer to object will be stored.
2712  *
2713  * RETURNS
2714  *  Success: S_OK.
2715  *  Failure: E_OUTOFMEMORY.
2716  *
2717  * NOTES
2718  *  Crashes on all invalid ppv addresses, including NULL.
2719  *  If the function returns a non-NULL object then the caller must release its
2720  *  reference on the object when the object is no longer required.
2721  *
2722  * SEE ALSO
2723  *  CoSetState().
2724  */
2725 HRESULT WINAPI CoGetState(IUnknown ** ppv)
2726 {
2727     struct oletls *info = COM_CurrentInfo();
2728     if (!info) return E_OUTOFMEMORY;
2729
2730     *ppv = NULL;
2731
2732     if (info->state)
2733     {
2734         IUnknown_AddRef(info->state);
2735         *ppv = info->state;
2736         TRACE("apt->state=%p\n", info->state);
2737     }
2738
2739     return S_OK;
2740 }
2741
2742 /***********************************************************************
2743  *           CoSetState [OLE32.@]
2744  *
2745  * Sets the thread state object.
2746  *
2747  * PARAMS
2748  *  pv [I] Pointer to state object to be stored.
2749  *
2750  * NOTES
2751  *  The system keeps a reference on the object while the object stored.
2752  *
2753  * RETURNS
2754  *  Success: S_OK.
2755  *  Failure: E_OUTOFMEMORY.
2756  */
2757 HRESULT WINAPI CoSetState(IUnknown * pv)
2758 {
2759     struct oletls *info = COM_CurrentInfo();
2760     if (!info) return E_OUTOFMEMORY;
2761
2762     if (pv) IUnknown_AddRef(pv);
2763
2764     if (info->state)
2765     {
2766         TRACE("-- release %p now\n", info->state);
2767         IUnknown_Release(info->state);
2768     }
2769
2770     info->state = pv;
2771
2772     return S_OK;
2773 }
2774
2775
2776 /******************************************************************************
2777  *              CoTreatAsClass        [OLE32.@]
2778  *
2779  * Sets the TreatAs value of a class.
2780  *
2781  * PARAMS
2782  *  clsidOld [I] Class to set TreatAs value on.
2783  *  clsidNew [I] The class the clsidOld should be treated as.
2784  *
2785  * RETURNS
2786  *  Success: S_OK.
2787  *  Failure: HRESULT code.
2788  *
2789  * SEE ALSO
2790  *  CoGetTreatAsClass
2791  */
2792 HRESULT WINAPI CoTreatAsClass(REFCLSID clsidOld, REFCLSID clsidNew)
2793 {
2794     static const WCHAR wszAutoTreatAs[] = {'A','u','t','o','T','r','e','a','t','A','s',0};
2795     static const WCHAR wszTreatAs[] = {'T','r','e','a','t','A','s',0};
2796     HKEY hkey = NULL;
2797     WCHAR szClsidNew[CHARS_IN_GUID];
2798     HRESULT res = S_OK;
2799     WCHAR auto_treat_as[CHARS_IN_GUID];
2800     LONG auto_treat_as_size = sizeof(auto_treat_as);
2801     CLSID id;
2802
2803     res = COM_OpenKeyForCLSID(clsidOld, NULL, KEY_READ | KEY_WRITE, &hkey);
2804     if (FAILED(res))
2805         goto done;
2806     if (!memcmp( clsidOld, clsidNew, sizeof(*clsidOld) ))
2807     {
2808        if (!RegQueryValueW(hkey, wszAutoTreatAs, auto_treat_as, &auto_treat_as_size) &&
2809            !CLSIDFromString(auto_treat_as, &id))
2810        {
2811            if (RegSetValueW(hkey, wszTreatAs, REG_SZ, auto_treat_as, sizeof(auto_treat_as)))
2812            {
2813                res = REGDB_E_WRITEREGDB;
2814                goto done;
2815            }
2816        }
2817        else
2818        {
2819            RegDeleteKeyW(hkey, wszTreatAs);
2820            goto done;
2821        }
2822     }
2823     else if (!StringFromGUID2(clsidNew, szClsidNew, ARRAYSIZE(szClsidNew)) &&
2824              !RegSetValueW(hkey, wszTreatAs, REG_SZ, szClsidNew, sizeof(szClsidNew)))
2825     {
2826         res = REGDB_E_WRITEREGDB;
2827         goto done;
2828     }
2829
2830 done:
2831     if (hkey) RegCloseKey(hkey);
2832     return res;
2833 }
2834
2835 /******************************************************************************
2836  *              CoGetTreatAsClass        [OLE32.@]
2837  *
2838  * Gets the TreatAs value of a class.
2839  *
2840  * PARAMS
2841  *  clsidOld [I] Class to get the TreatAs value of.
2842  *  clsidNew [I] The class the clsidOld should be treated as.
2843  *
2844  * RETURNS
2845  *  Success: S_OK.
2846  *  Failure: HRESULT code.
2847  *
2848  * SEE ALSO
2849  *  CoSetTreatAsClass
2850  */
2851 HRESULT WINAPI CoGetTreatAsClass(REFCLSID clsidOld, LPCLSID clsidNew)
2852 {
2853     static const WCHAR wszTreatAs[] = {'T','r','e','a','t','A','s',0};
2854     HKEY hkey = NULL;
2855     WCHAR szClsidNew[CHARS_IN_GUID];
2856     HRESULT res = S_OK;
2857     LONG len = sizeof(szClsidNew);
2858
2859     FIXME("(%s,%p)\n", debugstr_guid(clsidOld), clsidNew);
2860     *clsidNew = *clsidOld; /* copy over old value */
2861
2862     res = COM_OpenKeyForCLSID(clsidOld, wszTreatAs, KEY_READ, &hkey);
2863     if (FAILED(res))
2864         goto done;
2865     if (RegQueryValueW(hkey, NULL, szClsidNew, &len))
2866     {
2867         res = S_FALSE;
2868         goto done;
2869     }
2870     res = CLSIDFromString(szClsidNew,clsidNew);
2871     if (FAILED(res))
2872         ERR("Failed CLSIDFromStringA(%s), hres 0x%08x\n", debugstr_w(szClsidNew), res);
2873 done:
2874     if (hkey) RegCloseKey(hkey);
2875     return res;
2876 }
2877
2878 /******************************************************************************
2879  *              CoGetCurrentProcess     [OLE32.@]
2880  *              CoGetCurrentProcess     [COMPOBJ.34]
2881  *
2882  * Gets the current process ID.
2883  *
2884  * RETURNS
2885  *  The current process ID.
2886  *
2887  * NOTES
2888  *   Is DWORD really the correct return type for this function?
2889  */
2890 DWORD WINAPI CoGetCurrentProcess(void)
2891 {
2892         return GetCurrentProcessId();
2893 }
2894
2895 /******************************************************************************
2896  *              CoRegisterMessageFilter [OLE32.@]
2897  *
2898  * Registers a message filter.
2899  *
2900  * PARAMS
2901  *  lpMessageFilter [I] Pointer to interface.
2902  *  lplpMessageFilter [O] Indirect pointer to prior instance if non-NULL.
2903  *
2904  * RETURNS
2905  *  Success: S_OK.
2906  *  Failure: HRESULT code.
2907  *
2908  * NOTES
2909  *  Both lpMessageFilter and lplpMessageFilter are optional. Passing in a NULL
2910  *  lpMessageFilter removes the message filter.
2911  *
2912  *  If lplpMessageFilter is not NULL the previous message filter will be
2913  *  returned in the memory pointer to this parameter and the caller is
2914  *  responsible for releasing the object.
2915  *
2916  *  The current thread be in an apartment otherwise the function will crash.
2917  */
2918 HRESULT WINAPI CoRegisterMessageFilter(
2919     LPMESSAGEFILTER lpMessageFilter,
2920     LPMESSAGEFILTER *lplpMessageFilter)
2921 {
2922     struct apartment *apt;
2923     IMessageFilter *lpOldMessageFilter;
2924
2925     TRACE("(%p, %p)\n", lpMessageFilter, lplpMessageFilter);
2926
2927     apt = COM_CurrentApt();
2928
2929     /* can't set a message filter in a multi-threaded apartment */
2930     if (!apt || apt->multi_threaded)
2931     {
2932         WARN("can't set message filter in MTA or uninitialized apt\n");
2933         return CO_E_NOT_SUPPORTED;
2934     }
2935
2936     if (lpMessageFilter)
2937         IMessageFilter_AddRef(lpMessageFilter);
2938
2939     EnterCriticalSection(&apt->cs);
2940
2941     lpOldMessageFilter = apt->filter;
2942     apt->filter = lpMessageFilter;
2943
2944     LeaveCriticalSection(&apt->cs);
2945
2946     if (lplpMessageFilter)
2947         *lplpMessageFilter = lpOldMessageFilter;
2948     else if (lpOldMessageFilter)
2949         IMessageFilter_Release(lpOldMessageFilter);
2950
2951     return S_OK;
2952 }
2953
2954 /***********************************************************************
2955  *           CoIsOle1Class [OLE32.@]
2956  *
2957  * Determines whether the specified class an OLE v1 class.
2958  *
2959  * PARAMS
2960  *  clsid [I] Class to test.
2961  *
2962  * RETURNS
2963  *  TRUE if the class is an OLE v1 class, or FALSE otherwise.
2964  */
2965 BOOL WINAPI CoIsOle1Class(REFCLSID clsid)
2966 {
2967   FIXME("%s\n", debugstr_guid(clsid));
2968   return FALSE;
2969 }
2970
2971 /***********************************************************************
2972  *           IsEqualGUID [OLE32.@]
2973  *
2974  * Compares two Unique Identifiers.
2975  *
2976  * PARAMS
2977  *  rguid1 [I] The first GUID to compare.
2978  *  rguid2 [I] The other GUID to compare.
2979  *
2980  * RETURNS
2981  *      TRUE if equal
2982  */
2983 #undef IsEqualGUID
2984 BOOL WINAPI IsEqualGUID(
2985      REFGUID rguid1,
2986      REFGUID rguid2)
2987 {
2988     return !memcmp(rguid1,rguid2,sizeof(GUID));
2989 }
2990
2991 /***********************************************************************
2992  *           CoInitializeSecurity [OLE32.@]
2993  */
2994 HRESULT WINAPI CoInitializeSecurity(PSECURITY_DESCRIPTOR pSecDesc, LONG cAuthSvc,
2995                                     SOLE_AUTHENTICATION_SERVICE* asAuthSvc,
2996                                     void* pReserved1, DWORD dwAuthnLevel,
2997                                     DWORD dwImpLevel, void* pReserved2,
2998                                     DWORD dwCapabilities, void* pReserved3)
2999 {
3000   FIXME("(%p,%d,%p,%p,%d,%d,%p,%d,%p) - stub!\n", pSecDesc, cAuthSvc,
3001         asAuthSvc, pReserved1, dwAuthnLevel, dwImpLevel, pReserved2,
3002         dwCapabilities, pReserved3);
3003   return S_OK;
3004 }
3005
3006 /***********************************************************************
3007  *           CoSuspendClassObjects [OLE32.@]
3008  *
3009  * Suspends all registered class objects to prevent further requests coming in
3010  * for those objects.
3011  *
3012  * RETURNS
3013  *  Success: S_OK.
3014  *  Failure: HRESULT code.
3015  */
3016 HRESULT WINAPI CoSuspendClassObjects(void)
3017 {
3018     FIXME("\n");
3019     return S_OK;
3020 }
3021
3022 /***********************************************************************
3023  *           CoAddRefServerProcess [OLE32.@]
3024  *
3025  * Helper function for incrementing the reference count of a local-server
3026  * process.
3027  *
3028  * RETURNS
3029  *  New reference count.
3030  *
3031  * SEE ALSO
3032  *  CoReleaseServerProcess().
3033  */
3034 ULONG WINAPI CoAddRefServerProcess(void)
3035 {
3036     ULONG refs;
3037
3038     TRACE("\n");
3039
3040     EnterCriticalSection(&csRegisteredClassList);
3041     refs = ++s_COMServerProcessReferences;
3042     LeaveCriticalSection(&csRegisteredClassList);
3043
3044     TRACE("refs before: %d\n", refs - 1);
3045
3046     return refs;
3047 }
3048
3049 /***********************************************************************
3050  *           CoReleaseServerProcess [OLE32.@]
3051  *
3052  * Helper function for decrementing the reference count of a local-server
3053  * process.
3054  *
3055  * RETURNS
3056  *  New reference count.
3057  *
3058  * NOTES
3059  *  When reference count reaches 0, this function suspends all registered
3060  *  classes so no new connections are accepted.
3061  *
3062  * SEE ALSO
3063  *  CoAddRefServerProcess(), CoSuspendClassObjects().
3064  */
3065 ULONG WINAPI CoReleaseServerProcess(void)
3066 {
3067     ULONG refs;
3068
3069     TRACE("\n");
3070
3071     EnterCriticalSection(&csRegisteredClassList);
3072
3073     refs = --s_COMServerProcessReferences;
3074     /* FIXME: if (!refs) COM_SuspendClassObjects(); */
3075
3076     LeaveCriticalSection(&csRegisteredClassList);
3077
3078     TRACE("refs after: %d\n", refs);
3079
3080     return refs;
3081 }
3082
3083 /***********************************************************************
3084  *           CoIsHandlerConnected [OLE32.@]
3085  *
3086  * Determines whether a proxy is connected to a remote stub.
3087  *
3088  * PARAMS
3089  *  pUnk [I] Pointer to object that may or may not be connected.
3090  *
3091  * RETURNS
3092  *  TRUE if pUnk is not a proxy or if pUnk is connected to a remote stub, or
3093  *  FALSE otherwise.
3094  */
3095 BOOL WINAPI CoIsHandlerConnected(IUnknown *pUnk)
3096 {
3097     FIXME("%p\n", pUnk);
3098
3099     return TRUE;
3100 }
3101
3102 /***********************************************************************
3103  *           CoAllowSetForegroundWindow [OLE32.@]
3104  *
3105  */
3106 HRESULT WINAPI CoAllowSetForegroundWindow(IUnknown *pUnk, void *pvReserved)
3107 {
3108     FIXME("(%p, %p): stub\n", pUnk, pvReserved);
3109     return S_OK;
3110 }
3111  
3112 /***********************************************************************
3113  *           CoQueryProxyBlanket [OLE32.@]
3114  *
3115  * Retrieves the security settings being used by a proxy.
3116  *
3117  * PARAMS
3118  *  pProxy        [I] Pointer to the proxy object.
3119  *  pAuthnSvc     [O] The type of authentication service.
3120  *  pAuthzSvc     [O] The type of authorization service.
3121  *  ppServerPrincName [O] Optional. The server prinicple name.
3122  *  pAuthnLevel   [O] The authentication level.
3123  *  pImpLevel     [O] The impersonation level.
3124  *  ppAuthInfo    [O] Information specific to the authorization/authentication service.
3125  *  pCapabilities [O] Flags affecting the security behaviour.
3126  *
3127  * RETURNS
3128  *  Success: S_OK.
3129  *  Failure: HRESULT code.
3130  *
3131  * SEE ALSO
3132  *  CoCopyProxy, CoSetProxyBlanket.
3133  */
3134 HRESULT WINAPI CoQueryProxyBlanket(IUnknown *pProxy, DWORD *pAuthnSvc,
3135     DWORD *pAuthzSvc, OLECHAR **ppServerPrincName, DWORD *pAuthnLevel,
3136     DWORD *pImpLevel, void **ppAuthInfo, DWORD *pCapabilities)
3137 {
3138     IClientSecurity *pCliSec;
3139     HRESULT hr;
3140
3141     TRACE("%p\n", pProxy);
3142
3143     hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
3144     if (SUCCEEDED(hr))
3145     {
3146         hr = IClientSecurity_QueryBlanket(pCliSec, pProxy, pAuthnSvc,
3147                                           pAuthzSvc, ppServerPrincName,
3148                                           pAuthnLevel, pImpLevel, ppAuthInfo,
3149                                           pCapabilities);
3150         IClientSecurity_Release(pCliSec);
3151     }
3152
3153     if (FAILED(hr)) ERR("-- failed with 0x%08x\n", hr);
3154     return hr;
3155 }
3156
3157 /***********************************************************************
3158  *           CoSetProxyBlanket [OLE32.@]
3159  *
3160  * Sets the security settings for a proxy.
3161  *
3162  * PARAMS
3163  *  pProxy       [I] Pointer to the proxy object.
3164  *  AuthnSvc     [I] The type of authentication service.
3165  *  AuthzSvc     [I] The type of authorization service.
3166  *  pServerPrincName [I] The server prinicple name.
3167  *  AuthnLevel   [I] The authentication level.
3168  *  ImpLevel     [I] The impersonation level.
3169  *  pAuthInfo    [I] Information specific to the authorization/authentication service.
3170  *  Capabilities [I] Flags affecting the security behaviour.
3171  *
3172  * RETURNS
3173  *  Success: S_OK.
3174  *  Failure: HRESULT code.
3175  *
3176  * SEE ALSO
3177  *  CoQueryProxyBlanket, CoCopyProxy.
3178  */
3179 HRESULT WINAPI CoSetProxyBlanket(IUnknown *pProxy, DWORD AuthnSvc,
3180     DWORD AuthzSvc, OLECHAR *pServerPrincName, DWORD AuthnLevel,
3181     DWORD ImpLevel, void *pAuthInfo, DWORD Capabilities)
3182 {
3183     IClientSecurity *pCliSec;
3184     HRESULT hr;
3185
3186     TRACE("%p\n", pProxy);
3187
3188     hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
3189     if (SUCCEEDED(hr))
3190     {
3191         hr = IClientSecurity_SetBlanket(pCliSec, pProxy, AuthnSvc,
3192                                         AuthzSvc, pServerPrincName,
3193                                         AuthnLevel, ImpLevel, pAuthInfo,
3194                                         Capabilities);
3195         IClientSecurity_Release(pCliSec);
3196     }
3197
3198     if (FAILED(hr)) ERR("-- failed with 0x%08x\n", hr);
3199     return hr;
3200 }
3201
3202 /***********************************************************************
3203  *           CoCopyProxy [OLE32.@]
3204  *
3205  * Copies a proxy.
3206  *
3207  * PARAMS
3208  *  pProxy [I] Pointer to the proxy object.
3209  *  ppCopy [O] Copy of the proxy.
3210  *
3211  * RETURNS
3212  *  Success: S_OK.
3213  *  Failure: HRESULT code.
3214  *
3215  * SEE ALSO
3216  *  CoQueryProxyBlanket, CoSetProxyBlanket.
3217  */
3218 HRESULT WINAPI CoCopyProxy(IUnknown *pProxy, IUnknown **ppCopy)
3219 {
3220     IClientSecurity *pCliSec;
3221     HRESULT hr;
3222
3223     TRACE("%p\n", pProxy);
3224
3225     hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
3226     if (SUCCEEDED(hr))
3227     {
3228         hr = IClientSecurity_CopyProxy(pCliSec, pProxy, ppCopy);
3229         IClientSecurity_Release(pCliSec);
3230     }
3231
3232     if (FAILED(hr)) ERR("-- failed with 0x%08x\n", hr);
3233     return hr;
3234 }
3235
3236
3237 /***********************************************************************
3238  *           CoGetCallContext [OLE32.@]
3239  *
3240  * Gets the context of the currently executing server call in the current
3241  * thread.
3242  *
3243  * PARAMS
3244  *  riid [I] Context interface to return.
3245  *  ppv  [O] Pointer to memory that will receive the context on return.
3246  *
3247  * RETURNS
3248  *  Success: S_OK.
3249  *  Failure: HRESULT code.
3250  */
3251 HRESULT WINAPI CoGetCallContext(REFIID riid, void **ppv)
3252 {
3253     FIXME("(%s, %p): stub\n", debugstr_guid(riid), ppv);
3254
3255     *ppv = NULL;
3256     return E_NOINTERFACE;
3257 }
3258
3259 /***********************************************************************
3260  *           CoQueryClientBlanket [OLE32.@]
3261  *
3262  * Retrieves the authentication information about the client of the currently
3263  * executing server call in the current thread.
3264  *
3265  * PARAMS
3266  *  pAuthnSvc     [O] Optional. The type of authentication service.
3267  *  pAuthzSvc     [O] Optional. The type of authorization service.
3268  *  pServerPrincName [O] Optional. The server prinicple name.
3269  *  pAuthnLevel   [O] Optional. The authentication level.
3270  *  pImpLevel     [O] Optional. The impersonation level.
3271  *  pPrivs        [O] Optional. Information about the privileges of the client.
3272  *  pCapabilities [IO] Optional. Flags affecting the security behaviour.
3273  *
3274  * RETURNS
3275  *  Success: S_OK.
3276  *  Failure: HRESULT code.
3277  *
3278  * SEE ALSO
3279  *  CoImpersonateClient, CoRevertToSelf, CoGetCallContext.
3280  */
3281 HRESULT WINAPI CoQueryClientBlanket(
3282     DWORD *pAuthnSvc,
3283     DWORD *pAuthzSvc,
3284     OLECHAR **pServerPrincName,
3285     DWORD *pAuthnLevel,
3286     DWORD *pImpLevel,
3287     RPC_AUTHZ_HANDLE *pPrivs,
3288     DWORD *pCapabilities)
3289 {
3290     IServerSecurity *pSrvSec;
3291     HRESULT hr;
3292
3293     TRACE("(%p, %p, %p, %p, %p, %p, %p)\n",
3294         pAuthnSvc, pAuthzSvc, pServerPrincName, pAuthnLevel, pImpLevel,
3295         pPrivs, pCapabilities);
3296
3297     hr = CoGetCallContext(&IID_IServerSecurity, (void **)&pSrvSec);
3298     if (SUCCEEDED(hr))
3299     {
3300         hr = IServerSecurity_QueryBlanket(
3301             pSrvSec, pAuthnSvc, pAuthzSvc, pServerPrincName, pAuthnLevel,
3302             pImpLevel, pPrivs, pCapabilities);
3303         IServerSecurity_Release(pSrvSec);
3304     }
3305
3306     return hr;
3307 }
3308
3309 /***********************************************************************
3310  *           CoImpersonateClient [OLE32.@]
3311  *
3312  * Impersonates the client of the currently executing server call in the
3313  * current thread.
3314  *
3315  * PARAMS
3316  *  None.
3317  *
3318  * RETURNS
3319  *  Success: S_OK.
3320  *  Failure: HRESULT code.
3321  *
3322  * NOTES
3323  *  If this function fails then the current thread will not be impersonating
3324  *  the client and all actions will take place on behalf of the server.
3325  *  Therefore, it is important to check the return value from this function.
3326  *
3327  * SEE ALSO
3328  *  CoRevertToSelf, CoQueryClientBlanket, CoGetCallContext.
3329  */
3330 HRESULT WINAPI CoImpersonateClient(void)
3331 {
3332     IServerSecurity *pSrvSec;
3333     HRESULT hr;
3334
3335     TRACE("\n");
3336
3337     hr = CoGetCallContext(&IID_IServerSecurity, (void **)&pSrvSec);
3338     if (SUCCEEDED(hr))
3339     {
3340         hr = IServerSecurity_ImpersonateClient(pSrvSec);
3341         IServerSecurity_Release(pSrvSec);
3342     }
3343
3344     return hr;
3345 }
3346
3347 /***********************************************************************
3348  *           CoRevertToSelf [OLE32.@]
3349  *
3350  * Ends the impersonation of the client of the currently executing server
3351  * call in the current thread.
3352  *
3353  * PARAMS
3354  *  None.
3355  *
3356  * RETURNS
3357  *  Success: S_OK.
3358  *  Failure: HRESULT code.
3359  *
3360  * SEE ALSO
3361  *  CoImpersonateClient, CoQueryClientBlanket, CoGetCallContext.
3362  */
3363 HRESULT WINAPI CoRevertToSelf(void)
3364 {
3365     IServerSecurity *pSrvSec;
3366     HRESULT hr;
3367
3368     TRACE("\n");
3369
3370     hr = CoGetCallContext(&IID_IServerSecurity, (void **)&pSrvSec);
3371     if (SUCCEEDED(hr))
3372     {
3373         hr = IServerSecurity_RevertToSelf(pSrvSec);
3374         IServerSecurity_Release(pSrvSec);
3375     }
3376
3377     return hr;
3378 }
3379
3380 static BOOL COM_PeekMessage(struct apartment *apt, MSG *msg)
3381 {
3382     /* first try to retrieve messages for incoming COM calls to the apartment window */
3383     return PeekMessageW(msg, apt->win, WM_USER, WM_APP - 1, PM_REMOVE|PM_NOYIELD) ||
3384            /* next retrieve other messages necessary for the app to remain responsive */
3385            PeekMessageW(msg, NULL, 0, 0, PM_QS_PAINT|PM_QS_POSTMESSAGE|PM_REMOVE|PM_NOYIELD);
3386 }
3387
3388 /***********************************************************************
3389  *           CoWaitForMultipleHandles [OLE32.@]
3390  *
3391  * Waits for one or more handles to become signaled.
3392  *
3393  * PARAMS
3394  *  dwFlags   [I] Flags. See notes.
3395  *  dwTimeout [I] Timeout in milliseconds.
3396  *  cHandles  [I] Number of handles pointed to by pHandles.
3397  *  pHandles  [I] Handles to wait for.
3398  *  lpdwindex [O] Index of handle that was signaled.
3399  *
3400  * RETURNS
3401  *  Success: S_OK.
3402  *  Failure: RPC_S_CALLPENDING on timeout.
3403  *
3404  * NOTES
3405  *
3406  * The dwFlags parameter can be zero or more of the following:
3407  *| COWAIT_WAITALL - Wait for all of the handles to become signaled.
3408  *| COWAIT_ALERTABLE - Allows a queued APC to run during the wait.
3409  *
3410  * SEE ALSO
3411  *  MsgWaitForMultipleObjects, WaitForMultipleObjects.
3412  */
3413 HRESULT WINAPI CoWaitForMultipleHandles(DWORD dwFlags, DWORD dwTimeout,
3414     ULONG cHandles, LPHANDLE pHandles, LPDWORD lpdwindex)
3415 {
3416     HRESULT hr = S_OK;
3417     DWORD start_time = GetTickCount();
3418     APARTMENT *apt = COM_CurrentApt();
3419     BOOL message_loop = apt && !apt->multi_threaded;
3420
3421     TRACE("(0x%08x, 0x%08x, %d, %p, %p)\n", dwFlags, dwTimeout, cHandles,
3422         pHandles, lpdwindex);
3423
3424     while (TRUE)
3425     {
3426         DWORD now = GetTickCount();
3427         DWORD res;
3428
3429         if (now - start_time > dwTimeout)
3430         {
3431             hr = RPC_S_CALLPENDING;
3432             break;
3433         }
3434
3435         if (message_loop)
3436         {
3437             DWORD wait_flags = ((dwFlags & COWAIT_WAITALL) ? MWMO_WAITALL : 0) |
3438                     ((dwFlags & COWAIT_ALERTABLE ) ? MWMO_ALERTABLE : 0);
3439
3440             TRACE("waiting for rpc completion or window message\n");
3441
3442             res = MsgWaitForMultipleObjectsEx(cHandles, pHandles,
3443                 (dwTimeout == INFINITE) ? INFINITE : start_time + dwTimeout - now,
3444                 QS_ALLINPUT, wait_flags);
3445
3446             if (res == WAIT_OBJECT_0 + cHandles)  /* messages available */
3447             {
3448                 MSG msg;
3449
3450                 /* call message filter */
3451
3452                 if (COM_CurrentApt()->filter)
3453                 {
3454                     PENDINGTYPE pendingtype =
3455                         COM_CurrentInfo()->pending_call_count_server ?
3456                             PENDINGTYPE_NESTED : PENDINGTYPE_TOPLEVEL;
3457                     DWORD be_handled = IMessageFilter_MessagePending(
3458                         COM_CurrentApt()->filter, 0 /* FIXME */,
3459                         now - start_time, pendingtype);
3460                     TRACE("IMessageFilter_MessagePending returned %d\n", be_handled);
3461                     switch (be_handled)
3462                     {
3463                     case PENDINGMSG_CANCELCALL:
3464                         WARN("call canceled\n");
3465                         hr = RPC_E_CALL_CANCELED;
3466                         break;
3467                     case PENDINGMSG_WAITNOPROCESS:
3468                     case PENDINGMSG_WAITDEFPROCESS:
3469                     default:
3470                         /* FIXME: MSDN is very vague about the difference
3471                          * between WAITNOPROCESS and WAITDEFPROCESS - there
3472                          * appears to be none, so it is possibly a left-over
3473                          * from the 16-bit world. */
3474                         break;
3475                     }
3476                 }
3477
3478                 /* note: using "if" here instead of "while" might seem less
3479                  * efficient, but only if we are optimising for quick delivery
3480                  * of pending messages, rather than quick completion of the
3481                  * COM call */
3482                 if (COM_PeekMessage(apt, &msg))
3483                 {
3484                     TRACE("received message whilst waiting for RPC: 0x%04x\n", msg.message);
3485                     TranslateMessage(&msg);
3486                     DispatchMessageW(&msg);
3487                     if (msg.message == WM_QUIT)
3488                     {
3489                         TRACE("resending WM_QUIT to outer message loop\n");
3490                         PostQuitMessage(msg.wParam);
3491                         /* no longer need to process messages */
3492                         message_loop = FALSE;
3493                     }
3494                 }
3495                 continue;
3496             }
3497         }
3498         else
3499         {
3500             TRACE("waiting for rpc completion\n");
3501
3502             res = WaitForMultipleObjectsEx(cHandles, pHandles,
3503                 (dwFlags & COWAIT_WAITALL) ? TRUE : FALSE,
3504                 (dwTimeout == INFINITE) ? INFINITE : start_time + dwTimeout - now,
3505                 (dwFlags & COWAIT_ALERTABLE) ? TRUE : FALSE);
3506         }
3507
3508         if (res < WAIT_OBJECT_0 + cHandles)
3509         {
3510             /* handle signaled, store index */
3511             *lpdwindex = (res - WAIT_OBJECT_0);
3512             break;
3513         }
3514         else if (res == WAIT_TIMEOUT)
3515         {
3516             hr = RPC_S_CALLPENDING;
3517             break;
3518         }
3519         else
3520         {
3521             ERR("Unexpected wait termination: %d, %d\n", res, GetLastError());
3522             hr = E_UNEXPECTED;
3523             break;
3524         }
3525     }
3526     TRACE("-- 0x%08x\n", hr);
3527     return hr;
3528 }
3529
3530
3531 /***********************************************************************
3532  *           CoGetObject [OLE32.@]
3533  *
3534  * Gets the object named by converting the name to a moniker and binding to it.
3535  *
3536  * PARAMS
3537  *  pszName      [I] String representing the object.
3538  *  pBindOptions [I] Parameters affecting the binding to the named object.
3539  *  riid         [I] Interface to bind to on the objecct.
3540  *  ppv          [O] On output, the interface riid of the object represented
3541  *                   by pszName.
3542  *
3543  * RETURNS
3544  *  Success: S_OK.
3545  *  Failure: HRESULT code.
3546  *
3547  * SEE ALSO
3548  *  MkParseDisplayName.
3549  */
3550 HRESULT WINAPI CoGetObject(LPCWSTR pszName, BIND_OPTS *pBindOptions,
3551     REFIID riid, void **ppv)
3552 {
3553     IBindCtx *pbc;
3554     HRESULT hr;
3555
3556     *ppv = NULL;
3557
3558     hr = CreateBindCtx(0, &pbc);
3559     if (SUCCEEDED(hr))
3560     {
3561         if (pBindOptions)
3562             hr = IBindCtx_SetBindOptions(pbc, pBindOptions);
3563
3564         if (SUCCEEDED(hr))
3565         {
3566             ULONG chEaten;
3567             IMoniker *pmk;
3568
3569             hr = MkParseDisplayName(pbc, pszName, &chEaten, &pmk);
3570             if (SUCCEEDED(hr))
3571             {
3572                 hr = IMoniker_BindToObject(pmk, pbc, NULL, riid, ppv);
3573                 IMoniker_Release(pmk);
3574             }
3575         }
3576
3577         IBindCtx_Release(pbc);
3578     }
3579     return hr;
3580 }
3581
3582 /***********************************************************************
3583  *           CoRegisterChannelHook [OLE32.@]
3584  *
3585  * Registers a process-wide hook that is called during ORPC calls.
3586  *
3587  * PARAMS
3588  *  guidExtension [I] GUID of the channel hook to register.
3589  *  pChannelHook  [I] Channel hook object to register.
3590  *
3591  * RETURNS
3592  *  Success: S_OK.
3593  *  Failure: HRESULT code.
3594  */
3595 HRESULT WINAPI CoRegisterChannelHook(REFGUID guidExtension, IChannelHook *pChannelHook)
3596 {
3597     TRACE("(%s, %p)\n", debugstr_guid(guidExtension), pChannelHook);
3598
3599     return RPC_RegisterChannelHook(guidExtension, pChannelHook);
3600 }
3601
3602 typedef struct Context
3603 {
3604     const IComThreadingInfoVtbl *lpVtbl;
3605     LONG refs;
3606     APTTYPE apttype;
3607 } Context;
3608
3609 static HRESULT WINAPI Context_QueryInterface(IComThreadingInfo *iface, REFIID riid, LPVOID *ppv)
3610 {
3611     *ppv = NULL;
3612
3613     if (IsEqualIID(riid, &IID_IComThreadingInfo) ||
3614         IsEqualIID(riid, &IID_IUnknown))
3615     {
3616         *ppv = iface;
3617         IUnknown_AddRef(iface);
3618         return S_OK;
3619     }
3620
3621     FIXME("interface not implemented %s\n", debugstr_guid(riid));
3622     return E_NOINTERFACE;
3623 }
3624
3625 static ULONG WINAPI Context_AddRef(IComThreadingInfo *iface)
3626 {
3627     Context *This = (Context *)iface;
3628     return InterlockedIncrement(&This->refs);
3629 }
3630
3631 static ULONG WINAPI Context_Release(IComThreadingInfo *iface)
3632 {
3633     Context *This = (Context *)iface;
3634     ULONG refs = InterlockedDecrement(&This->refs);
3635     if (!refs)
3636         HeapFree(GetProcessHeap(), 0, This);
3637     return refs;
3638 }
3639
3640 static HRESULT WINAPI Context_GetCurrentApartmentType(IComThreadingInfo *iface, APTTYPE *apttype)
3641 {
3642     Context *This = (Context *)iface;
3643
3644     TRACE("(%p)\n", apttype);
3645
3646     *apttype = This->apttype;
3647     return S_OK;
3648 }
3649
3650 static HRESULT WINAPI Context_GetCurrentThreadType(IComThreadingInfo *iface, THDTYPE *thdtype)
3651 {
3652     Context *This = (Context *)iface;
3653
3654     TRACE("(%p)\n", thdtype);
3655
3656     switch (This->apttype)
3657     {
3658     case APTTYPE_STA:
3659     case APTTYPE_MAINSTA:
3660         *thdtype = THDTYPE_PROCESSMESSAGES;
3661         break;
3662     default:
3663         *thdtype = THDTYPE_BLOCKMESSAGES;
3664         break;
3665     }
3666     return S_OK;
3667 }
3668
3669 static HRESULT WINAPI Context_GetCurrentLogicalThreadId(IComThreadingInfo *iface, GUID *logical_thread_id)
3670 {
3671     FIXME("(%p): stub\n", logical_thread_id);
3672     return E_NOTIMPL;
3673 }
3674
3675 static HRESULT WINAPI Context_SetCurrentLogicalThreadId(IComThreadingInfo *iface, REFGUID logical_thread_id)
3676 {
3677     FIXME("(%s): stub\n", debugstr_guid(logical_thread_id));
3678     return E_NOTIMPL;
3679 }
3680
3681 static const IComThreadingInfoVtbl Context_Threading_Vtbl =
3682 {
3683     Context_QueryInterface,
3684     Context_AddRef,
3685     Context_Release,
3686     Context_GetCurrentApartmentType,
3687     Context_GetCurrentThreadType,
3688     Context_GetCurrentLogicalThreadId,
3689     Context_SetCurrentLogicalThreadId
3690 };
3691
3692 /***********************************************************************
3693  *           CoGetObjectContext [OLE32.@]
3694  *
3695  * Retrieves an object associated with the current context (i.e. apartment).
3696  *
3697  * PARAMS
3698  *  riid [I] ID of the interface of the object to retrieve.
3699  *  ppv  [O] Address where object will be stored on return.
3700  *
3701  * RETURNS
3702  *  Success: S_OK.
3703  *  Failure: HRESULT code.
3704  */
3705 HRESULT WINAPI CoGetObjectContext(REFIID riid, void **ppv)
3706 {
3707     APARTMENT *apt = COM_CurrentApt();
3708     Context *context;
3709     HRESULT hr;
3710
3711     TRACE("(%s, %p)\n", debugstr_guid(riid), ppv);
3712
3713     *ppv = NULL;
3714     if (!apt)
3715     {
3716         ERR("apartment not initialised\n");
3717         return CO_E_NOTINITIALIZED;
3718     }
3719
3720     context = HeapAlloc(GetProcessHeap(), 0, sizeof(*context));
3721     if (!context)
3722         return E_OUTOFMEMORY;
3723
3724     context->lpVtbl = &Context_Threading_Vtbl;
3725     context->refs = 1;
3726     if (apt->multi_threaded)
3727         context->apttype = APTTYPE_MTA;
3728     else if (apt->main)
3729         context->apttype = APTTYPE_MAINSTA;
3730     else
3731         context->apttype = APTTYPE_STA;
3732
3733     hr = IUnknown_QueryInterface((IUnknown *)&context->lpVtbl, riid, ppv);
3734     IUnknown_Release((IUnknown *)&context->lpVtbl);
3735
3736     return hr;
3737 }
3738
3739
3740 /***********************************************************************
3741  *           CoGetContextToken [OLE32.@]
3742  */
3743 HRESULT WINAPI CoGetContextToken( ULONG_PTR *token )
3744 {
3745     static int calls;
3746     if(!(calls++)) FIXME( "stub\n" );
3747     if (token) *token = 0;
3748     return E_NOTIMPL;
3749 }
3750
3751
3752 /***********************************************************************
3753  *              DllMain (OLE32.@)
3754  */
3755 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID fImpLoad)
3756 {
3757     TRACE("%p 0x%x %p\n", hinstDLL, fdwReason, fImpLoad);
3758
3759     switch(fdwReason) {
3760     case DLL_PROCESS_ATTACH:
3761         OLE32_hInstance = hinstDLL;
3762         COMPOBJ_InitProcess();
3763         if (TRACE_ON(ole)) CoRegisterMallocSpy((LPVOID)-1);
3764         break;
3765
3766     case DLL_PROCESS_DETACH:
3767         if (TRACE_ON(ole)) CoRevokeMallocSpy();
3768         OLEDD_UnInitialize();
3769         COMPOBJ_UninitProcess();
3770         RPC_UnregisterAllChannelHooks();
3771         COMPOBJ_DllList_Free();
3772         OLE32_hInstance = 0;
3773         break;
3774
3775     case DLL_THREAD_DETACH:
3776         COM_TlsDestroy();
3777         break;
3778     }
3779     return TRUE;
3780 }
3781
3782 /* NOTE: DllRegisterServer and DllUnregisterServer are in regsvr.c */