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