d3dx8: Implement the C++ stuff of the D3DXVECTOR3 structure.
[wine/multimedia.git] / dlls / ole32 / compobj.c
blob154ebc53c4222fee96323ed25f9e27a7f88e9820
1 /*
2 * COMPOBJ library
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)
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.
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.
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
26 * Note
27 * 1. COINIT_MULTITHREADED is 0; it is the lack of COINIT_APARTMENTTHREADED
28 * Therefore do not test against COINIT_MULTITHREADED
30 * TODO list: (items bunched together depend on each other)
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
37 * - Make all ole interface marshaling use NDR to be wire compatible with
38 * native DCOM
42 #include "config.h"
44 #include <stdarg.h>
45 #include <stdio.h>
46 #include <string.h>
47 #include <assert.h>
49 #define COBJMACROS
50 #define NONAMELESSUNION
51 #define NONAMELESSSTRUCT
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"
62 #include "compobj_private.h"
64 #include "wine/unicode.h"
65 #include "wine/debug.h"
67 WINE_DEFAULT_DEBUG_CHANNEL(ole);
69 HINSTANCE OLE32_hInstance = 0; /* FIXME: make static ... */
71 #define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))
73 /****************************************************************************
74 * This section defines variables internal to the COM module.
76 * TODO: Most of these things will have to be made thread-safe.
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);
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 */
88 static CRITICAL_SECTION csApartment;
89 static CRITICAL_SECTION_DEBUG critsect_debug =
91 0, 0, &csApartment,
92 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
93 0, 0, { (DWORD_PTR)(__FILE__ ": csApartment") }
95 static CRITICAL_SECTION csApartment = { &critsect_debug, -1, 0, 0, 0, 0 };
97 struct registered_psclsid
99 struct list entry;
100 IID iid;
101 CLSID clsid;
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
109 static LONG s_COMLockCount = 0;
110 /* Reference count used by CoAddRefServerProcess/CoReleaseServerProcess */
111 static LONG s_COMServerProcessReferences = 0;
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.
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.
121 typedef struct tagRegisteredClass
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;
134 static struct list RegisteredClassList = LIST_INIT(RegisteredClassList);
136 static CRITICAL_SECTION csRegisteredClassList;
137 static CRITICAL_SECTION_DEBUG class_cs_debug =
139 0, 0, &csRegisteredClassList,
140 { &class_cs_debug.ProcessLocksList, &class_cs_debug.ProcessLocksList },
141 0, 0, { (DWORD_PTR)(__FILE__ ": csRegisteredClassList") }
143 static CRITICAL_SECTION csRegisteredClassList = { &class_cs_debug, -1, 0, 0, 0, 0 };
145 /*****************************************************************************
146 * This section contains OpenDllList definitions
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.
152 * FIXME: a DLL that says OK when asked for unloading is unloaded in the
153 * next unload-call but not before 600 sec.
156 typedef HRESULT (CALLBACK *DllGetClassObjectFunc)(REFCLSID clsid, REFIID iid, LPVOID *ppv);
157 typedef HRESULT (WINAPI *DllCanUnloadNowFunc)(void);
159 typedef struct tagOpenDll
161 LONG refs;
162 LPWSTR library_name;
163 HANDLE library;
164 DllGetClassObjectFunc DllGetClassObject;
165 DllCanUnloadNowFunc DllCanUnloadNow;
166 struct list entry;
167 } OpenDll;
169 static struct list openDllList = LIST_INIT(openDllList);
171 static CRITICAL_SECTION csOpenDllList;
172 static CRITICAL_SECTION_DEBUG dll_cs_debug =
174 0, 0, &csOpenDllList,
175 { &dll_cs_debug.ProcessLocksList, &dll_cs_debug.ProcessLocksList },
176 0, 0, { (DWORD_PTR)(__FILE__ ": csOpenDllList") }
178 static CRITICAL_SECTION csOpenDllList = { &dll_cs_debug, -1, 0, 0, 0, 0 };
180 struct apartment_loaded_dll
182 struct list entry;
183 OpenDll *dll;
184 DWORD unload_time;
185 BOOL multi_threaded;
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);
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);
200 static DWORD COM_RegReadPath(HKEY hkeyroot, const WCHAR *keyname, const WCHAR *valuename, WCHAR * dst, DWORD dstlen);
202 static void COMPOBJ_InitProcess( void )
204 WNDCLASSW wclass;
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.
215 memset(&wclass, 0, sizeof(wclass));
216 wclass.lpfnWndProc = apartment_wndproc;
217 wclass.hInstance = OLE32_hInstance;
218 wclass.lpszClassName = wszAptWinClass;
219 RegisterClassW(&wclass);
222 static void COMPOBJ_UninitProcess( void )
224 UnregisterClassW(wszAptWinClass, OLE32_hInstance);
227 static void COM_TlsDestroy(void)
229 struct oletls *info = NtCurrentTeb()->ReservedForOle;
230 if (info)
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;
240 /******************************************************************************
241 * Manage apartments.
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)
248 APARTMENT *apt;
250 TRACE("creating new apartment, model=%d\n", model);
252 apt = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*apt));
253 apt->tid = GetCurrentThreadId();
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");
266 apt->multi_threaded = !(model & COINIT_APARTMENTTHREADED);
268 if (apt->multi_threaded)
270 /* FIXME: should be randomly generated by in an RPC call to rpcss */
271 apt->oxid = ((OXID)GetCurrentProcessId() << 32) | 0xcafe;
273 else
275 /* FIXME: should be randomly generated by in an RPC call to rpcss */
276 apt->oxid = ((OXID)GetCurrentProcessId() << 32) | GetCurrentThreadId();
279 TRACE("Created apartment on OXID %s\n", wine_dbgstr_longlong(apt->oxid));
281 list_add_head(&apts, &apt->entry);
283 return apt;
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)
291 APARTMENT *apt = COM_CurrentApt();
293 if (!apt)
295 if (model & COINIT_APARTMENTTHREADED)
297 EnterCriticalSection(&csApartment);
299 apt = apartment_construct(model);
300 if (!MainApartment)
302 MainApartment = apt;
303 apt->main = TRUE;
304 TRACE("Created main-threaded apartment with OXID %s\n", wine_dbgstr_longlong(apt->oxid));
307 LeaveCriticalSection(&csApartment);
309 else
311 EnterCriticalSection(&csApartment);
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)
318 TRACE("entering the multithreaded apartment %s\n", wine_dbgstr_longlong(MTA->oxid));
319 apartment_addref(MTA);
321 else
322 MTA = apartment_construct(model);
324 apt = MTA;
326 LeaveCriticalSection(&csApartment);
328 COM_CurrentInfo()->apt = apt;
331 return apt;
334 static inline BOOL apartment_is_model(const APARTMENT *apt, DWORD model)
336 return (apt->multi_threaded == !(model & COINIT_APARTMENTTHREADED));
339 DWORD apartment_addref(struct apartment *apt)
341 DWORD refs = InterlockedIncrement(&apt->refs);
342 TRACE("%s: before = %d\n", wine_dbgstr_longlong(apt->oxid), refs - 1);
343 return refs;
346 DWORD apartment_release(struct apartment *apt)
348 DWORD ret;
350 EnterCriticalSection(&csApartment);
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)
357 if (apt == MTA) MTA = NULL;
358 else if (apt == MainApartment) MainApartment = NULL;
359 list_remove(&apt->entry);
362 LeaveCriticalSection(&csApartment);
364 if (ret == 0)
366 struct list *cursor, *cursor2;
368 TRACE("destroying apartment %p, oxid %s\n", apt, wine_dbgstr_longlong(apt->oxid));
370 /* Release the references to the registered class objects */
371 COM_RevokeAllClasses(apt);
373 /* no locking is needed for this apartment, because no other thread
374 * can access it at this point */
376 apartment_disconnectproxies(apt);
378 if (apt->win) DestroyWindow(apt->win);
379 if (apt->host_apt_tid) PostThreadMessageW(apt->host_apt_tid, WM_QUIT, 0, 0);
381 LIST_FOR_EACH_SAFE(cursor, cursor2, &apt->stubmgrs)
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).
389 stub_manager_int_release(stubmgr);
392 LIST_FOR_EACH_SAFE(cursor, cursor2, &apt->psclsids)
394 struct registered_psclsid *registered_psclsid =
395 LIST_ENTRY(cursor, struct registered_psclsid, entry);
397 list_remove(&registered_psclsid->entry);
398 HeapFree(GetProcessHeap(), 0, registered_psclsid);
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));
406 if (apt->filter) IUnknown_Release(apt->filter);
408 /* free as many unused libraries as possible... */
409 apartment_freeunusedlibraries(apt, 0);
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)))
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);
422 DEBUG_CLEAR_CRITSEC_NAME(&apt->cs);
423 DeleteCriticalSection(&apt->cs);
425 HeapFree(GetProcessHeap(), 0, apt);
428 return ret;
431 /* The given OXID must be local to this process:
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.
436 APARTMENT *apartment_findfromoxid(OXID oxid, BOOL ref)
438 APARTMENT *result = NULL;
439 struct list *cursor;
441 EnterCriticalSection(&csApartment);
442 LIST_FOR_EACH( cursor, &apts )
444 struct apartment *apt = LIST_ENTRY( cursor, struct apartment, entry );
445 if (apt->oxid == oxid)
447 result = apt;
448 if (ref) apartment_addref(result);
449 break;
452 LeaveCriticalSection(&csApartment);
454 return result;
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)
462 APARTMENT *result = NULL;
463 struct list *cursor;
465 EnterCriticalSection(&csApartment);
466 LIST_FOR_EACH( cursor, &apts )
468 struct apartment *apt = LIST_ENTRY( cursor, struct apartment, entry );
469 if (apt->tid == tid)
471 result = apt;
472 apartment_addref(result);
473 break;
476 LeaveCriticalSection(&csApartment);
478 return result;
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)
486 APARTMENT *result;
488 EnterCriticalSection(&csApartment);
490 result = MainApartment;
491 if (result) apartment_addref(result);
493 LeaveCriticalSection(&csApartment);
495 return result;
498 struct host_object_params
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? */
509 static HRESULT apartment_hostobject(struct apartment *apt,
510 const struct host_object_params *params)
512 IUnknown *object;
513 HRESULT hr;
514 static const LARGE_INTEGER llZero;
515 WCHAR dllpath[MAX_PATH+1];
517 TRACE("clsid %s, iid %s\n", debugstr_guid(&params->clsid), debugstr_guid(&params->iid));
519 if (COM_RegReadPath(params->hkeydll, NULL, NULL, dllpath, ARRAYSIZE(dllpath)) != ERROR_SUCCESS)
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;
526 hr = apartment_getclassobject(apt, dllpath, params->apartment_threaded,
527 &params->clsid, &params->iid, (void **)&object);
528 if (FAILED(hr))
529 return hr;
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);
536 return hr;
539 static LRESULT CALLBACK apartment_wndproc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
541 switch (msg)
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);
553 struct host_thread_params
555 COINIT threading_model;
556 HANDLE ready_event;
557 HWND apartment_hwnd;
560 static DWORD CALLBACK apartment_hostobject_thread(LPVOID p)
562 struct host_thread_params *params = p;
563 MSG msg;
564 HRESULT hr;
565 struct apartment *apt;
567 TRACE("\n");
569 hr = CoInitializeEx(NULL, params->threading_model);
570 if (FAILED(hr)) return hr;
572 apt = COM_CurrentApt();
573 if (params->threading_model == COINIT_APARTMENTTHREADED)
575 apartment_createwindowifneeded(apt);
576 params->apartment_hwnd = apartment_getwindow(apt);
578 else
579 params->apartment_hwnd = NULL;
581 /* force the message queue to be created before signaling parent thread */
582 PeekMessageW(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
584 SetEvent(params->ready_event);
585 params = NULL; /* can't touch params after here as it may be invalid */
587 while (GetMessageW(&msg, NULL, 0, 0))
589 if (!msg.hwnd && (msg.message == DM_HOSTOBJECT))
591 struct host_object_params *params = (struct host_object_params *)msg.lParam;
592 params->hr = apartment_hostobject(apt, params);
593 SetEvent(params->event);
595 else
597 TranslateMessage(&msg);
598 DispatchMessageW(&msg);
602 TRACE("exiting\n");
604 CoUninitialize();
606 return S_OK;
609 static HRESULT apartment_hostobject_in_hostapt(struct apartment *apt, BOOL multi_threaded, BOOL main_apartment, HKEY hkeydll, REFCLSID rclsid, REFIID riid, void **ppv)
611 struct host_object_params params;
612 HWND apartment_hwnd = NULL;
613 DWORD apartment_tid = 0;
614 HRESULT hr;
616 if (!multi_threaded && main_apartment)
618 APARTMENT *host_apt = apartment_findmain();
619 if (host_apt)
621 apartment_hwnd = apartment_getwindow(host_apt);
622 apartment_release(host_apt);
626 if (!apartment_hwnd)
628 EnterCriticalSection(&apt->cs);
630 if (!apt->host_apt_tid)
632 struct host_thread_params thread_params;
633 HANDLE handles[2];
634 DWORD wait_value;
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])
642 CloseHandle(handles[0]);
643 LeaveCriticalSection(&apt->cs);
644 return E_OUTOFMEMORY;
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
653 LeaveCriticalSection(&apt->cs);
654 return E_OUTOFMEMORY;
658 if (multi_threaded || !main_apartment)
660 apartment_hwnd = apt->host_apt_hwnd;
661 apartment_tid = apt->host_apt_tid;
664 LeaveCriticalSection(&apt->cs);
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)
671 APARTMENT *host_apt = apartment_findmain();
672 if (host_apt)
674 apartment_hwnd = apartment_getwindow(host_apt);
675 apartment_release(host_apt);
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)
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
694 WaitForSingleObject(params.event, INFINITE);
695 hr = params.hr;
697 CloseHandle(params.event);
699 else
701 if (!apartment_hwnd)
703 ERR("host apartment didn't create window\n");
704 hr = E_OUTOFMEMORY;
706 else
707 hr = SendMessageW(apartment_hwnd, DM_HOSTOBJECT, 0, (LPARAM)&params);
709 if (SUCCEEDED(hr))
710 hr = CoUnmarshalInterface(params.stream, riid, ppv);
711 IStream_Release(params.stream);
712 return hr;
715 HRESULT apartment_createwindowifneeded(struct apartment *apt)
717 if (apt->multi_threaded)
718 return S_OK;
720 if (!apt->win)
722 HWND hwnd = CreateWindowW(wszAptWinClass, NULL, 0,
723 0, 0, 0, 0,
724 0, 0, OLE32_hInstance, NULL);
725 if (!hwnd)
727 ERR("CreateWindow failed with error %d\n", GetLastError());
728 return HRESULT_FROM_WIN32(GetLastError());
730 if (InterlockedCompareExchangePointer((PVOID *)&apt->win, hwnd, NULL))
731 /* someone beat us to it */
732 DestroyWindow(hwnd);
735 return S_OK;
738 HWND apartment_getwindow(const struct apartment *apt)
740 assert(!apt->multi_threaded);
741 return apt->win;
744 void apartment_joinmta(void)
746 apartment_addref(MTA);
747 COM_CurrentInfo()->apt = MTA;
750 static HRESULT apartment_getclassobject(struct apartment *apt, LPCWSTR dllpath,
751 BOOL apartment_threaded,
752 REFCLSID rclsid, REFIID riid, void **ppv)
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;
759 if (!strcmpiW(dllpath, wszOle32))
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);
766 if (hr != S_OK)
767 ERR("DllGetClassObject returned error 0x%08x\n", hr);
769 return hr;
772 EnterCriticalSection(&apt->cs);
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))
777 TRACE("found %s already loaded\n", debugstr_w(dllpath));
778 found = TRUE;
779 break;
782 if (!found)
784 apartment_loaded_dll = HeapAlloc(GetProcessHeap(), 0, sizeof(*apartment_loaded_dll));
785 if (!apartment_loaded_dll)
786 hr = E_OUTOFMEMORY;
787 if (SUCCEEDED(hr))
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);
795 if (SUCCEEDED(hr))
797 TRACE("added new loaded dll %s\n", debugstr_w(dllpath));
798 list_add_tail(&apt->loaded_dlls, &apartment_loaded_dll->entry);
802 LeaveCriticalSection(&apt->cs);
804 if (SUCCEEDED(hr))
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;
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);
815 if (hr != S_OK)
816 ERR("DllGetClassObject returned error 0x%08x\n", hr);
819 return hr;
822 static void apartment_freeunusedlibraries(struct apartment *apt, DWORD delay)
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)
828 if (entry->dll->DllCanUnloadNow && (entry->dll->DllCanUnloadNow() == S_OK))
830 DWORD real_delay = delay;
832 if (real_delay == INFINITE)
834 if (entry->multi_threaded)
835 real_delay = 10 * 60 * 1000; /* 10 minutes */
836 else
837 real_delay = 0;
840 if (!real_delay || (entry->unload_time && (entry->unload_time < GetTickCount())))
842 list_remove(&entry->entry);
843 COMPOBJ_DllList_ReleaseRef(entry->dll, TRUE);
844 HeapFree(GetProcessHeap(), 0, entry);
846 else
847 entry->unload_time = GetTickCount() + real_delay;
849 else if (entry->unload_time)
850 entry->unload_time = 0;
852 LeaveCriticalSection(&apt->cs);
855 /*****************************************************************************
856 * This section contains OpenDllList implementation
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)
862 OpenDll *entry;
863 int len;
864 HRESULT hr = S_OK;
865 HANDLE hLibrary;
866 DllCanUnloadNowFunc DllCanUnloadNow;
867 DllGetClassObjectFunc DllGetClassObject;
869 TRACE("\n");
871 *ret = COMPOBJ_DllList_Get(library_name);
872 if (*ret) return S_OK;
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)
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? */
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)
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;
895 EnterCriticalSection( &csOpenDllList );
897 *ret = COMPOBJ_DllList_Get(library_name);
898 if (*ret)
900 /* another caller to this function already added the dll while we
901 * weren't in the critical section */
902 FreeLibrary(hLibrary);
904 else
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)
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);
919 else
921 hr = E_OUTOFMEMORY;
922 FreeLibrary(hLibrary);
924 *ret = entry;
927 LeaveCriticalSection( &csOpenDllList );
929 return hr;
932 static OpenDll *COMPOBJ_DllList_Get(LPCWSTR library_name)
934 OpenDll *ptr;
935 OpenDll *ret = NULL;
936 EnterCriticalSection(&csOpenDllList);
937 LIST_FOR_EACH_ENTRY(ptr, &openDllList, OpenDll, entry)
939 if (!strcmpiW(library_name, ptr->library_name) &&
940 (InterlockedIncrement(&ptr->refs) != 1) /* entry is being destroy if == 1 */)
942 ret = ptr;
943 break;
946 LeaveCriticalSection(&csOpenDllList);
947 return ret;
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)
954 if (!InterlockedDecrement(&entry->refs) && free_entry)
956 EnterCriticalSection(&csOpenDllList);
957 list_remove(&entry->entry);
958 LeaveCriticalSection(&csOpenDllList);
960 TRACE("freeing %p\n", entry->library);
961 FreeLibrary(entry->library);
963 HeapFree(GetProcessHeap(), 0, entry->library_name);
964 HeapFree(GetProcessHeap(), 0, entry);
968 /* frees memory associated with active dll list */
969 static void COMPOBJ_DllList_Free(void)
971 OpenDll *entry, *cursor2;
972 EnterCriticalSection(&csOpenDllList);
973 LIST_FOR_EACH_ENTRY_SAFE(entry, cursor2, &openDllList, OpenDll, entry)
975 list_remove(&entry->entry);
977 HeapFree(GetProcessHeap(), 0, entry->library_name);
978 HeapFree(GetProcessHeap(), 0, entry);
980 LeaveCriticalSection(&csOpenDllList);
983 /******************************************************************************
984 * CoBuildVersion [OLE32.@]
985 * CoBuildVersion [COMPOBJ.1]
987 * Gets the build version of the DLL.
989 * PARAMS
991 * RETURNS
992 * Current build version, hiword is majornumber, loword is minornumber
994 DWORD WINAPI CoBuildVersion(void)
996 TRACE("Returning version %d, build %d.\n", rmm, rup);
997 return (rmm<<16)+rup;
1000 /******************************************************************************
1001 * CoInitialize [OLE32.@]
1003 * Initializes the COM libraries by calling CoInitializeEx with
1004 * COINIT_APARTMENTTHREADED, ie it enters a STA thread.
1006 * PARAMS
1007 * lpReserved [I] Pointer to IMalloc interface (obsolete, should be NULL).
1009 * RETURNS
1010 * Success: S_OK if not already initialized, S_FALSE otherwise.
1011 * Failure: HRESULT code.
1013 * SEE ALSO
1014 * CoInitializeEx
1016 HRESULT WINAPI CoInitialize(LPVOID lpReserved)
1019 * Just delegate to the newer method.
1021 return CoInitializeEx(lpReserved, COINIT_APARTMENTTHREADED);
1024 /******************************************************************************
1025 * CoInitializeEx [OLE32.@]
1027 * Initializes the COM libraries.
1029 * PARAMS
1030 * lpReserved [I] Pointer to IMalloc interface (obsolete, should be NULL).
1031 * dwCoInit [I] One or more flags from the COINIT enumeration. See notes.
1033 * RETURNS
1034 * S_OK if successful,
1035 * S_FALSE if this function was called already.
1036 * RPC_E_CHANGED_MODE if a previous call to CoInitializeEx specified another
1037 * threading model.
1039 * NOTES
1041 * The behavior used to set the IMalloc used for memory management is
1042 * obsolete.
1043 * The dwCoInit parameter must specify one of the following apartment
1044 * threading models:
1045 *| COINIT_APARTMENTTHREADED - A single-threaded apartment (STA).
1046 *| COINIT_MULTITHREADED - A multi-threaded apartment (MTA).
1047 * The parameter may also specify zero or more of the following flags:
1048 *| COINIT_DISABLE_OLE1DDE - Don't use DDE for OLE1 support.
1049 *| COINIT_SPEED_OVER_MEMORY - Trade memory for speed.
1051 * SEE ALSO
1052 * CoUninitialize
1054 HRESULT WINAPI CoInitializeEx(LPVOID lpReserved, DWORD dwCoInit)
1056 HRESULT hr = S_OK;
1057 APARTMENT *apt;
1059 TRACE("(%p, %x)\n", lpReserved, (int)dwCoInit);
1061 if (lpReserved!=NULL)
1063 ERR("(%p, %x) - Bad parameter passed-in %p, must be an old Windows Application\n", lpReserved, (int)dwCoInit, lpReserved);
1067 * Check the lock count. If this is the first time going through the initialize
1068 * process, we have to initialize the libraries.
1070 * And crank-up that lock count.
1072 if (InterlockedExchangeAdd(&s_COMLockCount,1)==0)
1075 * Initialize the various COM libraries and data structures.
1077 TRACE("() - Initializing the COM libraries\n");
1079 /* we may need to defer this until after apartment initialisation */
1080 RunningObjectTableImpl_Initialize();
1083 if (!(apt = COM_CurrentInfo()->apt))
1085 apt = apartment_get_or_create(dwCoInit);
1086 if (!apt) return E_OUTOFMEMORY;
1088 else if (!apartment_is_model(apt, dwCoInit))
1090 /* Changing the threading model after it's been set is illegal. If this warning is triggered by Wine
1091 code then we are probably using the wrong threading model to implement that API. */
1092 ERR("Attempt to change threading model of this apartment from %s to %s\n",
1093 apt->multi_threaded ? "multi-threaded" : "apartment threaded",
1094 dwCoInit & COINIT_APARTMENTTHREADED ? "apartment threaded" : "multi-threaded");
1095 return RPC_E_CHANGED_MODE;
1097 else
1098 hr = S_FALSE;
1100 COM_CurrentInfo()->inits++;
1102 return hr;
1105 /***********************************************************************
1106 * CoUninitialize [OLE32.@]
1108 * This method will decrement the refcount on the current apartment, freeing
1109 * the resources associated with it if it is the last thread in the apartment.
1110 * If the last apartment is freed, the function will additionally release
1111 * any COM resources associated with the process.
1113 * PARAMS
1115 * RETURNS
1116 * Nothing.
1118 * SEE ALSO
1119 * CoInitializeEx
1121 void WINAPI CoUninitialize(void)
1123 struct oletls * info = COM_CurrentInfo();
1124 LONG lCOMRefCnt;
1126 TRACE("()\n");
1128 /* will only happen on OOM */
1129 if (!info) return;
1131 /* sanity check */
1132 if (!info->inits)
1134 ERR("Mismatched CoUninitialize\n");
1135 return;
1138 if (!--info->inits)
1140 apartment_release(info->apt);
1141 info->apt = NULL;
1145 * Decrease the reference count.
1146 * If we are back to 0 locks on the COM library, make sure we free
1147 * all the associated data structures.
1149 lCOMRefCnt = InterlockedExchangeAdd(&s_COMLockCount,-1);
1150 if (lCOMRefCnt==1)
1152 TRACE("() - Releasing the COM libraries\n");
1154 RunningObjectTableImpl_UnInitialize();
1156 else if (lCOMRefCnt<1) {
1157 ERR( "CoUninitialize() - not CoInitialized.\n" );
1158 InterlockedExchangeAdd(&s_COMLockCount,1); /* restore the lock count. */
1162 /******************************************************************************
1163 * CoDisconnectObject [OLE32.@]
1165 * Disconnects all connections to this object from remote processes. Dispatches
1166 * pending RPCs while blocking new RPCs from occurring, and then calls
1167 * IMarshal::DisconnectObject on the given object.
1169 * Typically called when the object server is forced to shut down, for instance by
1170 * the user.
1172 * PARAMS
1173 * lpUnk [I] The object whose stub should be disconnected.
1174 * reserved [I] Reserved. Should be set to 0.
1176 * RETURNS
1177 * Success: S_OK.
1178 * Failure: HRESULT code.
1180 * SEE ALSO
1181 * CoMarshalInterface, CoReleaseMarshalData, CoLockObjectExternal
1183 HRESULT WINAPI CoDisconnectObject( LPUNKNOWN lpUnk, DWORD reserved )
1185 HRESULT hr;
1186 IMarshal *marshal;
1187 APARTMENT *apt;
1189 TRACE("(%p, 0x%08x)\n", lpUnk, reserved);
1191 hr = IUnknown_QueryInterface(lpUnk, &IID_IMarshal, (void **)&marshal);
1192 if (hr == S_OK)
1194 hr = IMarshal_DisconnectObject(marshal, reserved);
1195 IMarshal_Release(marshal);
1196 return hr;
1199 apt = COM_CurrentApt();
1200 if (!apt)
1201 return CO_E_NOTINITIALIZED;
1203 apartment_disconnectobject(apt, lpUnk);
1205 /* Note: native is pretty broken here because it just silently
1206 * fails, without returning an appropriate error code if the object was
1207 * not found, making apps think that the object was disconnected, when
1208 * it actually wasn't */
1210 return S_OK;
1213 /******************************************************************************
1214 * CoCreateGuid [OLE32.@]
1215 * CoCreateGuid [COMPOBJ.73]
1217 * Simply forwards to UuidCreate in RPCRT4.
1219 * PARAMS
1220 * pguid [O] Points to the GUID to initialize.
1222 * RETURNS
1223 * Success: S_OK.
1224 * Failure: HRESULT code.
1226 * SEE ALSO
1227 * UuidCreate
1229 HRESULT WINAPI CoCreateGuid(GUID *pguid)
1231 return UuidCreate(pguid);
1234 /******************************************************************************
1235 * CLSIDFromString [OLE32.@]
1236 * IIDFromString [OLE32.@]
1238 * Converts a unique identifier from its string representation into
1239 * the GUID struct.
1241 * PARAMS
1242 * idstr [I] The string representation of the GUID.
1243 * id [O] GUID converted from the string.
1245 * RETURNS
1246 * S_OK on success
1247 * CO_E_CLASSSTRING if idstr is not a valid CLSID
1249 * SEE ALSO
1250 * StringFromCLSID
1252 static HRESULT WINAPI __CLSIDFromString(LPCWSTR s, CLSID *id)
1254 int i;
1255 BYTE table[256];
1257 if (!s) {
1258 memset( id, 0, sizeof (CLSID) );
1259 return S_OK;
1262 /* validate the CLSID string */
1263 if (strlenW(s) != 38)
1264 return CO_E_CLASSSTRING;
1266 if ((s[0]!='{') || (s[9]!='-') || (s[14]!='-') || (s[19]!='-') || (s[24]!='-') || (s[37]!='}'))
1267 return CO_E_CLASSSTRING;
1269 for (i=1; i<37; i++) {
1270 if ((i == 9)||(i == 14)||(i == 19)||(i == 24)) continue;
1271 if (!(((s[i] >= '0') && (s[i] <= '9')) ||
1272 ((s[i] >= 'a') && (s[i] <= 'f')) ||
1273 ((s[i] >= 'A') && (s[i] <= 'F'))))
1274 return CO_E_CLASSSTRING;
1277 TRACE("%s -> %p\n", debugstr_w(s), id);
1279 /* quick lookup table */
1280 memset(table, 0, 256);
1282 for (i = 0; i < 10; i++) {
1283 table['0' + i] = i;
1285 for (i = 0; i < 6; i++) {
1286 table['A' + i] = i+10;
1287 table['a' + i] = i+10;
1290 /* in form {XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX} */
1292 id->Data1 = (table[s[1]] << 28 | table[s[2]] << 24 | table[s[3]] << 20 | table[s[4]] << 16 |
1293 table[s[5]] << 12 | table[s[6]] << 8 | table[s[7]] << 4 | table[s[8]]);
1294 id->Data2 = table[s[10]] << 12 | table[s[11]] << 8 | table[s[12]] << 4 | table[s[13]];
1295 id->Data3 = table[s[15]] << 12 | table[s[16]] << 8 | table[s[17]] << 4 | table[s[18]];
1297 /* these are just sequential bytes */
1298 id->Data4[0] = table[s[20]] << 4 | table[s[21]];
1299 id->Data4[1] = table[s[22]] << 4 | table[s[23]];
1300 id->Data4[2] = table[s[25]] << 4 | table[s[26]];
1301 id->Data4[3] = table[s[27]] << 4 | table[s[28]];
1302 id->Data4[4] = table[s[29]] << 4 | table[s[30]];
1303 id->Data4[5] = table[s[31]] << 4 | table[s[32]];
1304 id->Data4[6] = table[s[33]] << 4 | table[s[34]];
1305 id->Data4[7] = table[s[35]] << 4 | table[s[36]];
1307 return S_OK;
1310 /*****************************************************************************/
1312 HRESULT WINAPI CLSIDFromString(LPOLESTR idstr, CLSID *id )
1314 HRESULT ret;
1316 if (!id)
1317 return E_INVALIDARG;
1319 ret = __CLSIDFromString(idstr, id);
1320 if(ret != S_OK) { /* It appears a ProgID is also valid */
1321 ret = CLSIDFromProgID(idstr, id);
1323 return ret;
1326 /* Converts a GUID into the respective string representation. */
1327 HRESULT WINE_StringFromCLSID(
1328 const CLSID *id, /* [in] GUID to be converted */
1329 LPSTR idstr /* [out] pointer to buffer to contain converted guid */
1331 static const char hex[] = "0123456789ABCDEF";
1332 char *s;
1333 int i;
1335 if (!id)
1336 { ERR("called with id=Null\n");
1337 *idstr = 0x00;
1338 return E_FAIL;
1341 sprintf(idstr, "{%08X-%04X-%04X-%02X%02X-",
1342 id->Data1, id->Data2, id->Data3,
1343 id->Data4[0], id->Data4[1]);
1344 s = &idstr[25];
1346 /* 6 hex bytes */
1347 for (i = 2; i < 8; i++) {
1348 *s++ = hex[id->Data4[i]>>4];
1349 *s++ = hex[id->Data4[i] & 0xf];
1352 *s++ = '}';
1353 *s++ = '\0';
1355 TRACE("%p->%s\n", id, idstr);
1357 return S_OK;
1361 /******************************************************************************
1362 * StringFromCLSID [OLE32.@]
1363 * StringFromIID [OLE32.@]
1365 * Converts a GUID into the respective string representation.
1366 * The target string is allocated using the OLE IMalloc.
1368 * PARAMS
1369 * id [I] the GUID to be converted.
1370 * idstr [O] A pointer to a to-be-allocated pointer pointing to the resulting string.
1372 * RETURNS
1373 * S_OK
1374 * E_FAIL
1376 * SEE ALSO
1377 * StringFromGUID2, CLSIDFromString
1379 HRESULT WINAPI StringFromCLSID(REFCLSID id, LPOLESTR *idstr)
1381 char buf[80];
1382 HRESULT ret;
1383 LPMALLOC mllc;
1385 if ((ret = CoGetMalloc(0,&mllc)))
1386 return ret;
1388 ret=WINE_StringFromCLSID(id,buf);
1389 if (!ret) {
1390 DWORD len = MultiByteToWideChar( CP_ACP, 0, buf, -1, NULL, 0 );
1391 *idstr = IMalloc_Alloc( mllc, len * sizeof(WCHAR) );
1392 MultiByteToWideChar( CP_ACP, 0, buf, -1, *idstr, len );
1394 return ret;
1397 /******************************************************************************
1398 * StringFromGUID2 [OLE32.@]
1399 * StringFromGUID2 [COMPOBJ.76]
1401 * Modified version of StringFromCLSID that allows you to specify max
1402 * buffer size.
1404 * PARAMS
1405 * id [I] GUID to convert to string.
1406 * str [O] Buffer where the result will be stored.
1407 * cmax [I] Size of the buffer in characters.
1409 * RETURNS
1410 * Success: The length of the resulting string in characters.
1411 * Failure: 0.
1413 INT WINAPI StringFromGUID2(REFGUID id, LPOLESTR str, INT cmax)
1415 char xguid[80];
1417 if (WINE_StringFromCLSID(id,xguid))
1418 return 0;
1419 return MultiByteToWideChar( CP_ACP, 0, xguid, -1, str, cmax );
1422 /* open HKCR\\CLSID\\{string form of clsid}\\{keyname} key */
1423 HRESULT COM_OpenKeyForCLSID(REFCLSID clsid, LPCWSTR keyname, REGSAM access, HKEY *subkey)
1425 static const WCHAR wszCLSIDSlash[] = {'C','L','S','I','D','\\',0};
1426 WCHAR path[CHARS_IN_GUID + ARRAYSIZE(wszCLSIDSlash) - 1];
1427 LONG res;
1428 HKEY key;
1430 strcpyW(path, wszCLSIDSlash);
1431 StringFromGUID2(clsid, path + strlenW(wszCLSIDSlash), CHARS_IN_GUID);
1432 res = RegOpenKeyExW(HKEY_CLASSES_ROOT, path, 0, keyname ? KEY_READ : access, &key);
1433 if (res == ERROR_FILE_NOT_FOUND)
1434 return REGDB_E_CLASSNOTREG;
1435 else if (res != ERROR_SUCCESS)
1436 return REGDB_E_READREGDB;
1438 if (!keyname)
1440 *subkey = key;
1441 return S_OK;
1444 res = RegOpenKeyExW(key, keyname, 0, access, subkey);
1445 RegCloseKey(key);
1446 if (res == ERROR_FILE_NOT_FOUND)
1447 return REGDB_E_KEYMISSING;
1448 else if (res != ERROR_SUCCESS)
1449 return REGDB_E_READREGDB;
1451 return S_OK;
1454 /* open HKCR\\AppId\\{string form of appid clsid} key */
1455 HRESULT COM_OpenKeyForAppIdFromCLSID(REFCLSID clsid, REGSAM access, HKEY *subkey)
1457 static const WCHAR szAppId[] = { 'A','p','p','I','d',0 };
1458 static const WCHAR szAppIdKey[] = { 'A','p','p','I','d','\\',0 };
1459 DWORD res;
1460 WCHAR buf[CHARS_IN_GUID];
1461 WCHAR keyname[ARRAYSIZE(szAppIdKey) + CHARS_IN_GUID];
1462 DWORD size;
1463 HKEY hkey;
1464 DWORD type;
1465 HRESULT hr;
1467 /* read the AppID value under the class's key */
1468 hr = COM_OpenKeyForCLSID(clsid, NULL, KEY_READ, &hkey);
1469 if (FAILED(hr))
1470 return hr;
1472 size = sizeof(buf);
1473 res = RegQueryValueExW(hkey, szAppId, NULL, &type, (LPBYTE)buf, &size);
1474 RegCloseKey(hkey);
1475 if (res == ERROR_FILE_NOT_FOUND)
1476 return REGDB_E_KEYMISSING;
1477 else if (res != ERROR_SUCCESS || type!=REG_SZ)
1478 return REGDB_E_READREGDB;
1480 strcpyW(keyname, szAppIdKey);
1481 strcatW(keyname, buf);
1482 res = RegOpenKeyExW(HKEY_CLASSES_ROOT, keyname, 0, access, subkey);
1483 if (res == ERROR_FILE_NOT_FOUND)
1484 return REGDB_E_KEYMISSING;
1485 else if (res != ERROR_SUCCESS)
1486 return REGDB_E_READREGDB;
1488 return S_OK;
1491 /******************************************************************************
1492 * ProgIDFromCLSID [OLE32.@]
1494 * Converts a class id into the respective program ID.
1496 * PARAMS
1497 * clsid [I] Class ID, as found in registry.
1498 * ppszProgID [O] Associated ProgID.
1500 * RETURNS
1501 * S_OK
1502 * E_OUTOFMEMORY
1503 * REGDB_E_CLASSNOTREG if the given clsid has no associated ProgID
1505 HRESULT WINAPI ProgIDFromCLSID(REFCLSID clsid, LPOLESTR *ppszProgID)
1507 static const WCHAR wszProgID[] = {'P','r','o','g','I','D',0};
1508 HKEY hkey;
1509 HRESULT ret;
1510 LONG progidlen = 0;
1512 if (!ppszProgID)
1514 ERR("ppszProgId isn't optional\n");
1515 return E_INVALIDARG;
1518 *ppszProgID = NULL;
1519 ret = COM_OpenKeyForCLSID(clsid, wszProgID, KEY_READ, &hkey);
1520 if (FAILED(ret))
1521 return ret;
1523 if (RegQueryValueW(hkey, NULL, NULL, &progidlen))
1524 ret = REGDB_E_CLASSNOTREG;
1526 if (ret == S_OK)
1528 *ppszProgID = CoTaskMemAlloc(progidlen * sizeof(WCHAR));
1529 if (*ppszProgID)
1531 if (RegQueryValueW(hkey, NULL, *ppszProgID, &progidlen))
1532 ret = REGDB_E_CLASSNOTREG;
1534 else
1535 ret = E_OUTOFMEMORY;
1538 RegCloseKey(hkey);
1539 return ret;
1542 /******************************************************************************
1543 * CLSIDFromProgID [OLE32.@]
1545 * Converts a program id into the respective GUID.
1547 * PARAMS
1548 * progid [I] Unicode program ID, as found in registry.
1549 * clsid [O] Associated CLSID.
1551 * RETURNS
1552 * Success: S_OK
1553 * Failure: CO_E_CLASSSTRING - the given ProgID cannot be found.
1555 HRESULT WINAPI CLSIDFromProgID(LPCOLESTR progid, LPCLSID clsid)
1557 static const WCHAR clsidW[] = { '\\','C','L','S','I','D',0 };
1558 WCHAR buf2[CHARS_IN_GUID];
1559 LONG buf2len = sizeof(buf2);
1560 HKEY xhkey;
1561 WCHAR *buf;
1563 if (!progid || !clsid)
1565 ERR("neither progid (%p) nor clsid (%p) are optional\n", progid, clsid);
1566 return E_INVALIDARG;
1569 /* initialise clsid in case of failure */
1570 memset(clsid, 0, sizeof(*clsid));
1572 buf = HeapAlloc( GetProcessHeap(),0,(strlenW(progid)+8) * sizeof(WCHAR) );
1573 strcpyW( buf, progid );
1574 strcatW( buf, clsidW );
1575 if (RegOpenKeyW(HKEY_CLASSES_ROOT,buf,&xhkey))
1577 HeapFree(GetProcessHeap(),0,buf);
1578 WARN("couldn't open key for ProgID %s\n", debugstr_w(progid));
1579 return CO_E_CLASSSTRING;
1581 HeapFree(GetProcessHeap(),0,buf);
1583 if (RegQueryValueW(xhkey,NULL,buf2,&buf2len))
1585 RegCloseKey(xhkey);
1586 WARN("couldn't query clsid value for ProgID %s\n", debugstr_w(progid));
1587 return CO_E_CLASSSTRING;
1589 RegCloseKey(xhkey);
1590 return CLSIDFromString(buf2,clsid);
1594 /*****************************************************************************
1595 * CoGetPSClsid [OLE32.@]
1597 * Retrieves the CLSID of the proxy/stub factory that implements
1598 * IPSFactoryBuffer for the specified interface.
1600 * PARAMS
1601 * riid [I] Interface whose proxy/stub CLSID is to be returned.
1602 * pclsid [O] Where to store returned proxy/stub CLSID.
1604 * RETURNS
1605 * S_OK
1606 * E_OUTOFMEMORY
1607 * REGDB_E_IIDNOTREG if no PSFactoryBuffer is associated with the IID, or it could not be parsed
1609 * NOTES
1611 * The standard marshaller activates the object with the CLSID
1612 * returned and uses the CreateProxy and CreateStub methods on its
1613 * IPSFactoryBuffer interface to construct the proxies and stubs for a
1614 * given object.
1616 * CoGetPSClsid determines this CLSID by searching the
1617 * HKEY_CLASSES_ROOT\Interface\{string form of riid}\ProxyStubClsid32
1618 * in the registry and any interface id registered by
1619 * CoRegisterPSClsid within the current process.
1621 * BUGS
1623 * Native returns S_OK for interfaces with a key in HKCR\Interface, but
1624 * without a ProxyStubClsid32 key and leaves garbage in pclsid. This should be
1625 * considered a bug in native unless an application depends on this (unlikely).
1627 * SEE ALSO
1628 * CoRegisterPSClsid.
1630 HRESULT WINAPI CoGetPSClsid(REFIID riid, CLSID *pclsid)
1632 static const WCHAR wszInterface[] = {'I','n','t','e','r','f','a','c','e','\\',0};
1633 static const WCHAR wszPSC[] = {'\\','P','r','o','x','y','S','t','u','b','C','l','s','i','d','3','2',0};
1634 WCHAR path[ARRAYSIZE(wszInterface) - 1 + CHARS_IN_GUID - 1 + ARRAYSIZE(wszPSC)];
1635 WCHAR value[CHARS_IN_GUID];
1636 LONG len;
1637 HKEY hkey;
1638 APARTMENT *apt = COM_CurrentApt();
1639 struct registered_psclsid *registered_psclsid;
1641 TRACE("() riid=%s, pclsid=%p\n", debugstr_guid(riid), pclsid);
1643 if (!apt)
1645 ERR("apartment not initialised\n");
1646 return CO_E_NOTINITIALIZED;
1649 if (!pclsid)
1651 ERR("pclsid isn't optional\n");
1652 return E_INVALIDARG;
1655 EnterCriticalSection(&apt->cs);
1657 LIST_FOR_EACH_ENTRY(registered_psclsid, &apt->psclsids, struct registered_psclsid, entry)
1658 if (IsEqualIID(&registered_psclsid->iid, riid))
1660 *pclsid = registered_psclsid->clsid;
1661 LeaveCriticalSection(&apt->cs);
1662 return S_OK;
1665 LeaveCriticalSection(&apt->cs);
1667 /* Interface\\{string form of riid}\\ProxyStubClsid32 */
1668 strcpyW(path, wszInterface);
1669 StringFromGUID2(riid, path + ARRAYSIZE(wszInterface) - 1, CHARS_IN_GUID);
1670 strcpyW(path + ARRAYSIZE(wszInterface) - 1 + CHARS_IN_GUID - 1, wszPSC);
1672 /* Open the key.. */
1673 if (RegOpenKeyExW(HKEY_CLASSES_ROOT, path, 0, KEY_READ, &hkey))
1675 WARN("No PSFactoryBuffer object is registered for IID %s\n", debugstr_guid(riid));
1676 return REGDB_E_IIDNOTREG;
1679 /* ... Once we have the key, query the registry to get the
1680 value of CLSID as a string, and convert it into a
1681 proper CLSID structure to be passed back to the app */
1682 len = sizeof(value);
1683 if (ERROR_SUCCESS != RegQueryValueW(hkey, NULL, value, &len))
1685 RegCloseKey(hkey);
1686 return REGDB_E_IIDNOTREG;
1688 RegCloseKey(hkey);
1690 /* We have the CLSid we want back from the registry as a string, so
1691 lets convert it into a CLSID structure */
1692 if (CLSIDFromString(value, pclsid) != NOERROR)
1693 return REGDB_E_IIDNOTREG;
1695 TRACE ("() Returning CLSID=%s\n", debugstr_guid(pclsid));
1696 return S_OK;
1699 /*****************************************************************************
1700 * CoRegisterPSClsid [OLE32.@]
1702 * Register a proxy/stub CLSID for the given interface in the current process
1703 * only.
1705 * PARAMS
1706 * riid [I] Interface whose proxy/stub CLSID is to be registered.
1707 * rclsid [I] CLSID of the proxy/stub.
1709 * RETURNS
1710 * Success: S_OK
1711 * Failure: E_OUTOFMEMORY
1713 * NOTES
1715 * This function does not add anything to the registry and the effects are
1716 * limited to the lifetime of the current process.
1718 * SEE ALSO
1719 * CoGetPSClsid.
1721 HRESULT WINAPI CoRegisterPSClsid(REFIID riid, REFCLSID rclsid)
1723 APARTMENT *apt = COM_CurrentApt();
1724 struct registered_psclsid *registered_psclsid;
1726 TRACE("(%s, %s)\n", debugstr_guid(riid), debugstr_guid(rclsid));
1728 if (!apt)
1730 ERR("apartment not initialised\n");
1731 return CO_E_NOTINITIALIZED;
1734 EnterCriticalSection(&apt->cs);
1736 LIST_FOR_EACH_ENTRY(registered_psclsid, &apt->psclsids, struct registered_psclsid, entry)
1737 if (IsEqualIID(&registered_psclsid->iid, riid))
1739 registered_psclsid->clsid = *rclsid;
1740 LeaveCriticalSection(&apt->cs);
1741 return S_OK;
1744 registered_psclsid = HeapAlloc(GetProcessHeap(), 0, sizeof(struct registered_psclsid));
1745 if (!registered_psclsid)
1747 LeaveCriticalSection(&apt->cs);
1748 return E_OUTOFMEMORY;
1751 registered_psclsid->iid = *riid;
1752 registered_psclsid->clsid = *rclsid;
1753 list_add_head(&apt->psclsids, &registered_psclsid->entry);
1755 LeaveCriticalSection(&apt->cs);
1757 return S_OK;
1761 /***
1762 * COM_GetRegisteredClassObject
1764 * This internal method is used to scan the registered class list to
1765 * find a class object.
1767 * Params:
1768 * rclsid Class ID of the class to find.
1769 * dwClsContext Class context to match.
1770 * ppv [out] returns a pointer to the class object. Complying
1771 * to normal COM usage, this method will increase the
1772 * reference count on this object.
1774 static HRESULT COM_GetRegisteredClassObject(const struct apartment *apt, REFCLSID rclsid,
1775 DWORD dwClsContext, LPUNKNOWN* ppUnk)
1777 HRESULT hr = S_FALSE;
1778 RegisteredClass *curClass;
1781 * Sanity check
1783 assert(ppUnk!=0);
1785 EnterCriticalSection( &csRegisteredClassList );
1787 LIST_FOR_EACH_ENTRY(curClass, &RegisteredClassList, RegisteredClass, entry)
1790 * Check if we have a match on the class ID and context.
1792 if ((apt->oxid == curClass->apartment_id) &&
1793 (dwClsContext & curClass->runContext) &&
1794 IsEqualGUID(&(curClass->classIdentifier), rclsid))
1797 * We have a match, return the pointer to the class object.
1799 *ppUnk = curClass->classObject;
1801 IUnknown_AddRef(curClass->classObject);
1803 hr = S_OK;
1804 break;
1808 LeaveCriticalSection( &csRegisteredClassList );
1810 return hr;
1813 /******************************************************************************
1814 * CoRegisterClassObject [OLE32.@]
1816 * Registers the class object for a given class ID. Servers housed in EXE
1817 * files use this method instead of exporting DllGetClassObject to allow
1818 * other code to connect to their objects.
1820 * PARAMS
1821 * rclsid [I] CLSID of the object to register.
1822 * pUnk [I] IUnknown of the object.
1823 * dwClsContext [I] CLSCTX flags indicating the context in which to run the executable.
1824 * flags [I] REGCLS flags indicating how connections are made.
1825 * lpdwRegister [I] A unique cookie that can be passed to CoRevokeClassObject.
1827 * RETURNS
1828 * S_OK on success,
1829 * E_INVALIDARG if lpdwRegister or pUnk are NULL,
1830 * CO_E_OBJISREG if the object is already registered. We should not return this.
1832 * SEE ALSO
1833 * CoRevokeClassObject, CoGetClassObject
1835 * NOTES
1836 * In-process objects are only registered for the current apartment.
1837 * CoGetClassObject() and CoCreateInstance() will not return objects registered
1838 * in other apartments.
1840 * BUGS
1841 * MSDN claims that multiple interface registrations are legal, but we
1842 * can't do that with our current implementation.
1844 HRESULT WINAPI CoRegisterClassObject(
1845 REFCLSID rclsid,
1846 LPUNKNOWN pUnk,
1847 DWORD dwClsContext,
1848 DWORD flags,
1849 LPDWORD lpdwRegister)
1851 RegisteredClass* newClass;
1852 LPUNKNOWN foundObject;
1853 HRESULT hr;
1854 APARTMENT *apt;
1856 TRACE("(%s,%p,0x%08x,0x%08x,%p)\n",
1857 debugstr_guid(rclsid),pUnk,dwClsContext,flags,lpdwRegister);
1859 if ( (lpdwRegister==0) || (pUnk==0) )
1860 return E_INVALIDARG;
1862 apt = COM_CurrentApt();
1863 if (!apt)
1865 ERR("COM was not initialized\n");
1866 return CO_E_NOTINITIALIZED;
1869 *lpdwRegister = 0;
1871 /* REGCLS_MULTIPLEUSE implies registering as inproc server. This is what
1872 * differentiates the flag from REGCLS_MULTI_SEPARATE. */
1873 if (flags & REGCLS_MULTIPLEUSE)
1874 dwClsContext |= CLSCTX_INPROC_SERVER;
1877 * First, check if the class is already registered.
1878 * If it is, this should cause an error.
1880 hr = COM_GetRegisteredClassObject(apt, rclsid, dwClsContext, &foundObject);
1881 if (hr == S_OK) {
1882 if (flags & REGCLS_MULTIPLEUSE) {
1883 if (dwClsContext & CLSCTX_LOCAL_SERVER)
1884 hr = CoLockObjectExternal(foundObject, TRUE, FALSE);
1885 IUnknown_Release(foundObject);
1886 return hr;
1888 IUnknown_Release(foundObject);
1889 ERR("object already registered for class %s\n", debugstr_guid(rclsid));
1890 return CO_E_OBJISREG;
1893 newClass = HeapAlloc(GetProcessHeap(), 0, sizeof(RegisteredClass));
1894 if ( newClass == NULL )
1895 return E_OUTOFMEMORY;
1897 newClass->classIdentifier = *rclsid;
1898 newClass->apartment_id = apt->oxid;
1899 newClass->runContext = dwClsContext;
1900 newClass->connectFlags = flags;
1901 newClass->pMarshaledData = NULL;
1902 newClass->RpcRegistration = NULL;
1905 * Use the address of the chain node as the cookie since we are sure it's
1906 * unique. FIXME: not on 64-bit platforms.
1908 newClass->dwCookie = (DWORD)newClass;
1911 * Since we're making a copy of the object pointer, we have to increase its
1912 * reference count.
1914 newClass->classObject = pUnk;
1915 IUnknown_AddRef(newClass->classObject);
1917 EnterCriticalSection( &csRegisteredClassList );
1918 list_add_tail(&RegisteredClassList, &newClass->entry);
1919 LeaveCriticalSection( &csRegisteredClassList );
1921 *lpdwRegister = newClass->dwCookie;
1923 if (dwClsContext & CLSCTX_LOCAL_SERVER) {
1924 hr = CreateStreamOnHGlobal(0, TRUE, &newClass->pMarshaledData);
1925 if (hr) {
1926 FIXME("Failed to create stream on hglobal, %x\n", hr);
1927 return hr;
1929 hr = CoMarshalInterface(newClass->pMarshaledData, &IID_IClassFactory,
1930 newClass->classObject, MSHCTX_LOCAL, NULL,
1931 MSHLFLAGS_TABLESTRONG);
1932 if (hr) {
1933 FIXME("CoMarshalInterface failed, %x!\n",hr);
1934 return hr;
1937 hr = RPC_StartLocalServer(&newClass->classIdentifier,
1938 newClass->pMarshaledData,
1939 flags & (REGCLS_MULTIPLEUSE|REGCLS_MULTI_SEPARATE),
1940 &newClass->RpcRegistration);
1942 return S_OK;
1945 static void COM_RevokeRegisteredClassObject(RegisteredClass *curClass)
1947 list_remove(&curClass->entry);
1949 if (curClass->runContext & CLSCTX_LOCAL_SERVER)
1950 RPC_StopLocalServer(curClass->RpcRegistration);
1953 * Release the reference to the class object.
1955 IUnknown_Release(curClass->classObject);
1957 if (curClass->pMarshaledData)
1959 LARGE_INTEGER zero;
1960 memset(&zero, 0, sizeof(zero));
1961 IStream_Seek(curClass->pMarshaledData, zero, STREAM_SEEK_SET, NULL);
1962 CoReleaseMarshalData(curClass->pMarshaledData);
1965 HeapFree(GetProcessHeap(), 0, curClass);
1968 static void COM_RevokeAllClasses(const struct apartment *apt)
1970 RegisteredClass *curClass, *cursor;
1972 EnterCriticalSection( &csRegisteredClassList );
1974 LIST_FOR_EACH_ENTRY_SAFE(curClass, cursor, &RegisteredClassList, RegisteredClass, entry)
1976 if (curClass->apartment_id == apt->oxid)
1977 COM_RevokeRegisteredClassObject(curClass);
1980 LeaveCriticalSection( &csRegisteredClassList );
1983 /***********************************************************************
1984 * CoRevokeClassObject [OLE32.@]
1986 * Removes a class object from the class registry.
1988 * PARAMS
1989 * dwRegister [I] Cookie returned from CoRegisterClassObject().
1991 * RETURNS
1992 * Success: S_OK.
1993 * Failure: HRESULT code.
1995 * NOTES
1996 * Must be called from the same apartment that called CoRegisterClassObject(),
1997 * otherwise it will fail with RPC_E_WRONG_THREAD.
1999 * SEE ALSO
2000 * CoRegisterClassObject
2002 HRESULT WINAPI CoRevokeClassObject(
2003 DWORD dwRegister)
2005 HRESULT hr = E_INVALIDARG;
2006 RegisteredClass *curClass;
2007 APARTMENT *apt;
2009 TRACE("(%08x)\n",dwRegister);
2011 apt = COM_CurrentApt();
2012 if (!apt)
2014 ERR("COM was not initialized\n");
2015 return CO_E_NOTINITIALIZED;
2018 EnterCriticalSection( &csRegisteredClassList );
2020 LIST_FOR_EACH_ENTRY(curClass, &RegisteredClassList, RegisteredClass, entry)
2023 * Check if we have a match on the cookie.
2025 if (curClass->dwCookie == dwRegister)
2027 if (curClass->apartment_id == apt->oxid)
2029 COM_RevokeRegisteredClassObject(curClass);
2030 hr = S_OK;
2032 else
2034 ERR("called from wrong apartment, should be called from %s\n",
2035 wine_dbgstr_longlong(curClass->apartment_id));
2036 hr = RPC_E_WRONG_THREAD;
2038 break;
2042 LeaveCriticalSection( &csRegisteredClassList );
2044 return hr;
2047 /***********************************************************************
2048 * COM_RegReadPath [internal]
2050 * Reads a registry value and expands it when necessary
2052 static DWORD COM_RegReadPath(HKEY hkeyroot, const WCHAR *keyname, const WCHAR *valuename, WCHAR * dst, DWORD dstlen)
2054 DWORD ret;
2055 HKEY key;
2056 DWORD keytype;
2057 WCHAR src[MAX_PATH];
2058 DWORD dwLength = dstlen * sizeof(WCHAR);
2060 if((ret = RegOpenKeyExW(hkeyroot, keyname, 0, KEY_READ, &key)) == ERROR_SUCCESS) {
2061 if( (ret = RegQueryValueExW(key, NULL, NULL, &keytype, (LPBYTE)src, &dwLength)) == ERROR_SUCCESS ) {
2062 if (keytype == REG_EXPAND_SZ) {
2063 if (dstlen <= ExpandEnvironmentStringsW(src, dst, dstlen)) ret = ERROR_MORE_DATA;
2064 } else {
2065 lstrcpynW(dst, src, dstlen);
2068 RegCloseKey (key);
2070 return ret;
2073 static void get_threading_model(HKEY key, LPWSTR value, DWORD len)
2075 static const WCHAR wszThreadingModel[] = {'T','h','r','e','a','d','i','n','g','M','o','d','e','l',0};
2076 DWORD keytype;
2077 DWORD ret;
2078 DWORD dwLength = len * sizeof(WCHAR);
2080 ret = RegQueryValueExW(key, wszThreadingModel, NULL, &keytype, (LPBYTE)value, &dwLength);
2081 if ((ret != ERROR_SUCCESS) || (keytype != REG_SZ))
2082 value[0] = '\0';
2085 static HRESULT get_inproc_class_object(APARTMENT *apt, HKEY hkeydll,
2086 REFCLSID rclsid, REFIID riid, void **ppv)
2088 static const WCHAR wszApartment[] = {'A','p','a','r','t','m','e','n','t',0};
2089 static const WCHAR wszFree[] = {'F','r','e','e',0};
2090 static const WCHAR wszBoth[] = {'B','o','t','h',0};
2091 WCHAR dllpath[MAX_PATH+1];
2092 WCHAR threading_model[10 /* strlenW(L"apartment")+1 */];
2094 get_threading_model(hkeydll, threading_model, ARRAYSIZE(threading_model));
2095 /* "Apartment" */
2096 if (!strcmpiW(threading_model, wszApartment))
2098 if (apt->multi_threaded)
2099 return apartment_hostobject_in_hostapt(apt, FALSE, FALSE, hkeydll, rclsid, riid, ppv);
2101 /* "Free" */
2102 else if (!strcmpiW(threading_model, wszFree))
2104 if (!apt->multi_threaded)
2105 return apartment_hostobject_in_hostapt(apt, TRUE, FALSE, hkeydll, rclsid, riid, ppv);
2107 /* everything except "Apartment", "Free" and "Both" */
2108 else if (strcmpiW(threading_model, wszBoth))
2110 /* everything else is main-threaded */
2111 if (threading_model[0])
2112 FIXME("unrecognised threading model %s for object %s, should be main-threaded?\n",
2113 debugstr_w(threading_model), debugstr_guid(rclsid));
2115 if (apt->multi_threaded || !apt->main)
2116 return apartment_hostobject_in_hostapt(apt, FALSE, TRUE, hkeydll, rclsid, riid, ppv);
2119 if (COM_RegReadPath(hkeydll, NULL, NULL, dllpath, ARRAYSIZE(dllpath)) != ERROR_SUCCESS)
2121 /* failure: CLSID is not found in registry */
2122 WARN("class %s not registered inproc\n", debugstr_guid(rclsid));
2123 return REGDB_E_CLASSNOTREG;
2126 return apartment_getclassobject(apt, dllpath,
2127 !strcmpiW(threading_model, wszApartment),
2128 rclsid, riid, ppv);
2131 /***********************************************************************
2132 * CoGetClassObject [OLE32.@]
2134 * Creates an object of the specified class.
2136 * PARAMS
2137 * rclsid [I] Class ID to create an instance of.
2138 * dwClsContext [I] Flags to restrict the location of the created instance.
2139 * pServerInfo [I] Optional. Details for connecting to a remote server.
2140 * iid [I] The ID of the interface of the instance to return.
2141 * ppv [O] On returns, contains a pointer to the specified interface of the object.
2143 * RETURNS
2144 * Success: S_OK
2145 * Failure: HRESULT code.
2147 * NOTES
2148 * The dwClsContext parameter can be one or more of the following:
2149 *| CLSCTX_INPROC_SERVER - Use an in-process server, such as from a DLL.
2150 *| CLSCTX_INPROC_HANDLER - Use an in-process object which handles certain functions for an object running in another process.
2151 *| CLSCTX_LOCAL_SERVER - Connect to an object running in another process.
2152 *| CLSCTX_REMOTE_SERVER - Connect to an object running on another machine.
2154 * SEE ALSO
2155 * CoCreateInstance()
2157 HRESULT WINAPI CoGetClassObject(
2158 REFCLSID rclsid, DWORD dwClsContext, COSERVERINFO *pServerInfo,
2159 REFIID iid, LPVOID *ppv)
2161 LPUNKNOWN regClassObject;
2162 HRESULT hres = E_UNEXPECTED;
2163 APARTMENT *apt;
2165 TRACE("\n\tCLSID:\t%s,\n\tIID:\t%s\n", debugstr_guid(rclsid), debugstr_guid(iid));
2167 if (!ppv)
2168 return E_INVALIDARG;
2170 *ppv = NULL;
2172 apt = COM_CurrentApt();
2173 if (!apt)
2175 ERR("apartment not initialised\n");
2176 return CO_E_NOTINITIALIZED;
2179 if (pServerInfo) {
2180 FIXME("\tpServerInfo: name=%s\n",debugstr_w(pServerInfo->pwszName));
2181 FIXME("\t\tpAuthInfo=%p\n",pServerInfo->pAuthInfo);
2185 * First, try and see if we can't match the class ID with one of the
2186 * registered classes.
2188 if (S_OK == COM_GetRegisteredClassObject(apt, rclsid, dwClsContext,
2189 &regClassObject))
2191 /* Get the required interface from the retrieved pointer. */
2192 hres = IUnknown_QueryInterface(regClassObject, iid, ppv);
2195 * Since QI got another reference on the pointer, we want to release the
2196 * one we already have. If QI was unsuccessful, this will release the object. This
2197 * is good since we are not returning it in the "out" parameter.
2199 IUnknown_Release(regClassObject);
2201 return hres;
2204 /* First try in-process server */
2205 if (CLSCTX_INPROC_SERVER & dwClsContext)
2207 static const WCHAR wszInprocServer32[] = {'I','n','p','r','o','c','S','e','r','v','e','r','3','2',0};
2208 HKEY hkey;
2210 if (IsEqualCLSID(rclsid, &CLSID_InProcFreeMarshaler))
2211 return FTMarshalCF_Create(iid, ppv);
2213 hres = COM_OpenKeyForCLSID(rclsid, wszInprocServer32, KEY_READ, &hkey);
2214 if (FAILED(hres))
2216 if (hres == REGDB_E_CLASSNOTREG)
2217 ERR("class %s not registered\n", debugstr_guid(rclsid));
2218 else if (hres == REGDB_E_KEYMISSING)
2220 WARN("class %s not registered as in-proc server\n", debugstr_guid(rclsid));
2221 hres = REGDB_E_CLASSNOTREG;
2225 if (SUCCEEDED(hres))
2227 hres = get_inproc_class_object(apt, hkey, rclsid, iid, ppv);
2228 RegCloseKey(hkey);
2231 /* return if we got a class, otherwise fall through to one of the
2232 * other types */
2233 if (SUCCEEDED(hres))
2234 return hres;
2237 /* Next try in-process handler */
2238 if (CLSCTX_INPROC_HANDLER & dwClsContext)
2240 static const WCHAR wszInprocHandler32[] = {'I','n','p','r','o','c','H','a','n','d','l','e','r','3','2',0};
2241 HKEY hkey;
2243 hres = COM_OpenKeyForCLSID(rclsid, wszInprocHandler32, KEY_READ, &hkey);
2244 if (FAILED(hres))
2246 if (hres == REGDB_E_CLASSNOTREG)
2247 ERR("class %s not registered\n", debugstr_guid(rclsid));
2248 else if (hres == REGDB_E_KEYMISSING)
2250 WARN("class %s not registered in-proc handler\n", debugstr_guid(rclsid));
2251 hres = REGDB_E_CLASSNOTREG;
2255 if (SUCCEEDED(hres))
2257 hres = get_inproc_class_object(apt, hkey, rclsid, iid, ppv);
2258 RegCloseKey(hkey);
2261 /* return if we got a class, otherwise fall through to one of the
2262 * other types */
2263 if (SUCCEEDED(hres))
2264 return hres;
2267 /* Next try out of process */
2268 if (CLSCTX_LOCAL_SERVER & dwClsContext)
2270 hres = RPC_GetLocalClassObject(rclsid,iid,ppv);
2271 if (SUCCEEDED(hres))
2272 return hres;
2275 /* Finally try remote: this requires networked DCOM (a lot of work) */
2276 if (CLSCTX_REMOTE_SERVER & dwClsContext)
2278 FIXME ("CLSCTX_REMOTE_SERVER not supported\n");
2279 hres = E_NOINTERFACE;
2282 if (FAILED(hres))
2283 ERR("no class object %s could be created for context 0x%x\n",
2284 debugstr_guid(rclsid), dwClsContext);
2285 return hres;
2288 /***********************************************************************
2289 * CoResumeClassObjects (OLE32.@)
2291 * Resumes all class objects registered with REGCLS_SUSPENDED.
2293 * RETURNS
2294 * Success: S_OK.
2295 * Failure: HRESULT code.
2297 HRESULT WINAPI CoResumeClassObjects(void)
2299 FIXME("stub\n");
2300 return S_OK;
2303 /***********************************************************************
2304 * CoCreateInstance [OLE32.@]
2306 * Creates an instance of the specified class.
2308 * PARAMS
2309 * rclsid [I] Class ID to create an instance of.
2310 * pUnkOuter [I] Optional outer unknown to allow aggregation with another object.
2311 * dwClsContext [I] Flags to restrict the location of the created instance.
2312 * iid [I] The ID of the interface of the instance to return.
2313 * ppv [O] On returns, contains a pointer to the specified interface of the instance.
2315 * RETURNS
2316 * Success: S_OK
2317 * Failure: HRESULT code.
2319 * NOTES
2320 * The dwClsContext parameter can be one or more of the following:
2321 *| CLSCTX_INPROC_SERVER - Use an in-process server, such as from a DLL.
2322 *| CLSCTX_INPROC_HANDLER - Use an in-process object which handles certain functions for an object running in another process.
2323 *| CLSCTX_LOCAL_SERVER - Connect to an object running in another process.
2324 *| CLSCTX_REMOTE_SERVER - Connect to an object running on another machine.
2326 * Aggregation is the concept of deferring the IUnknown of an object to another
2327 * object. This allows a separate object to behave as though it was part of
2328 * the object and to allow this the pUnkOuter parameter can be set. Note that
2329 * not all objects support having an outer of unknown.
2331 * SEE ALSO
2332 * CoGetClassObject()
2334 HRESULT WINAPI CoCreateInstance(
2335 REFCLSID rclsid,
2336 LPUNKNOWN pUnkOuter,
2337 DWORD dwClsContext,
2338 REFIID iid,
2339 LPVOID *ppv)
2341 HRESULT hres;
2342 LPCLASSFACTORY lpclf = 0;
2344 TRACE("(rclsid=%s, pUnkOuter=%p, dwClsContext=%08x, riid=%s, ppv=%p)\n", debugstr_guid(rclsid),
2345 pUnkOuter, dwClsContext, debugstr_guid(iid), ppv);
2348 * Sanity check
2350 if (ppv==0)
2351 return E_POINTER;
2354 * Initialize the "out" parameter
2356 *ppv = 0;
2358 if (!COM_CurrentApt())
2360 ERR("apartment not initialised\n");
2361 return CO_E_NOTINITIALIZED;
2365 * The Standard Global Interface Table (GIT) object is a process-wide singleton.
2366 * Rather than create a class factory, we can just check for it here
2368 if (IsEqualIID(rclsid, &CLSID_StdGlobalInterfaceTable)) {
2369 if (StdGlobalInterfaceTableInstance == NULL)
2370 StdGlobalInterfaceTableInstance = StdGlobalInterfaceTable_Construct();
2371 hres = IGlobalInterfaceTable_QueryInterface( (IGlobalInterfaceTable*) StdGlobalInterfaceTableInstance, iid, ppv);
2372 if (hres) return hres;
2374 TRACE("Retrieved GIT (%p)\n", *ppv);
2375 return S_OK;
2379 * Get a class factory to construct the object we want.
2381 hres = CoGetClassObject(rclsid,
2382 dwClsContext,
2383 NULL,
2384 &IID_IClassFactory,
2385 (LPVOID)&lpclf);
2387 if (FAILED(hres))
2388 return hres;
2391 * Create the object and don't forget to release the factory
2393 hres = IClassFactory_CreateInstance(lpclf, pUnkOuter, iid, ppv);
2394 IClassFactory_Release(lpclf);
2395 if(FAILED(hres))
2396 FIXME("no instance created for interface %s of class %s, hres is 0x%08x\n",
2397 debugstr_guid(iid), debugstr_guid(rclsid),hres);
2399 return hres;
2402 /***********************************************************************
2403 * CoCreateInstanceEx [OLE32.@]
2405 HRESULT WINAPI CoCreateInstanceEx(
2406 REFCLSID rclsid,
2407 LPUNKNOWN pUnkOuter,
2408 DWORD dwClsContext,
2409 COSERVERINFO* pServerInfo,
2410 ULONG cmq,
2411 MULTI_QI* pResults)
2413 IUnknown* pUnk = NULL;
2414 HRESULT hr;
2415 ULONG index;
2416 ULONG successCount = 0;
2419 * Sanity check
2421 if ( (cmq==0) || (pResults==NULL))
2422 return E_INVALIDARG;
2424 if (pServerInfo!=NULL)
2425 FIXME("() non-NULL pServerInfo not supported!\n");
2428 * Initialize all the "out" parameters.
2430 for (index = 0; index < cmq; index++)
2432 pResults[index].pItf = NULL;
2433 pResults[index].hr = E_NOINTERFACE;
2437 * Get the object and get its IUnknown pointer.
2439 hr = CoCreateInstance(rclsid,
2440 pUnkOuter,
2441 dwClsContext,
2442 &IID_IUnknown,
2443 (VOID**)&pUnk);
2445 if (hr)
2446 return hr;
2449 * Then, query for all the interfaces requested.
2451 for (index = 0; index < cmq; index++)
2453 pResults[index].hr = IUnknown_QueryInterface(pUnk,
2454 pResults[index].pIID,
2455 (VOID**)&(pResults[index].pItf));
2457 if (pResults[index].hr == S_OK)
2458 successCount++;
2462 * Release our temporary unknown pointer.
2464 IUnknown_Release(pUnk);
2466 if (successCount == 0)
2467 return E_NOINTERFACE;
2469 if (successCount!=cmq)
2470 return CO_S_NOTALLINTERFACES;
2472 return S_OK;
2475 /***********************************************************************
2476 * CoLoadLibrary (OLE32.@)
2478 * Loads a library.
2480 * PARAMS
2481 * lpszLibName [I] Path to library.
2482 * bAutoFree [I] Whether the library should automatically be freed.
2484 * RETURNS
2485 * Success: Handle to loaded library.
2486 * Failure: NULL.
2488 * SEE ALSO
2489 * CoFreeLibrary, CoFreeAllLibraries, CoFreeUnusedLibraries
2491 HINSTANCE WINAPI CoLoadLibrary(LPOLESTR lpszLibName, BOOL bAutoFree)
2493 TRACE("(%s, %d)\n", debugstr_w(lpszLibName), bAutoFree);
2495 return LoadLibraryExW(lpszLibName, 0, LOAD_WITH_ALTERED_SEARCH_PATH);
2498 /***********************************************************************
2499 * CoFreeLibrary [OLE32.@]
2501 * Unloads a library from memory.
2503 * PARAMS
2504 * hLibrary [I] Handle to library to unload.
2506 * RETURNS
2507 * Nothing
2509 * SEE ALSO
2510 * CoLoadLibrary, CoFreeAllLibraries, CoFreeUnusedLibraries
2512 void WINAPI CoFreeLibrary(HINSTANCE hLibrary)
2514 FreeLibrary(hLibrary);
2518 /***********************************************************************
2519 * CoFreeAllLibraries [OLE32.@]
2521 * Function for backwards compatibility only. Does nothing.
2523 * RETURNS
2524 * Nothing.
2526 * SEE ALSO
2527 * CoLoadLibrary, CoFreeLibrary, CoFreeUnusedLibraries
2529 void WINAPI CoFreeAllLibraries(void)
2531 /* NOP */
2534 /***********************************************************************
2535 * CoFreeUnusedLibrariesEx [OLE32.@]
2537 * Frees any previously unused libraries whose delay has expired and marks
2538 * currently unused libraries for unloading. Unused are identified as those that
2539 * return S_OK from their DllCanUnloadNow function.
2541 * PARAMS
2542 * dwUnloadDelay [I] Unload delay in milliseconds.
2543 * dwReserved [I] Reserved. Set to 0.
2545 * RETURNS
2546 * Nothing.
2548 * SEE ALSO
2549 * CoLoadLibrary, CoFreeAllLibraries, CoFreeLibrary
2551 void WINAPI CoFreeUnusedLibrariesEx(DWORD dwUnloadDelay, DWORD dwReserved)
2553 struct apartment *apt = COM_CurrentApt();
2554 if (!apt)
2556 ERR("apartment not initialised\n");
2557 return;
2560 apartment_freeunusedlibraries(apt, dwUnloadDelay);
2563 /***********************************************************************
2564 * CoFreeUnusedLibraries [OLE32.@]
2565 * CoFreeUnusedLibraries [COMPOBJ.17]
2567 * Frees any unused libraries. Unused are identified as those that return
2568 * S_OK from their DllCanUnloadNow function.
2570 * RETURNS
2571 * Nothing.
2573 * SEE ALSO
2574 * CoLoadLibrary, CoFreeAllLibraries, CoFreeLibrary
2576 void WINAPI CoFreeUnusedLibraries(void)
2578 CoFreeUnusedLibrariesEx(INFINITE, 0);
2581 /***********************************************************************
2582 * CoFileTimeNow [OLE32.@]
2583 * CoFileTimeNow [COMPOBJ.82]
2585 * Retrieves the current time in FILETIME format.
2587 * PARAMS
2588 * lpFileTime [O] The current time.
2590 * RETURNS
2591 * S_OK.
2593 HRESULT WINAPI CoFileTimeNow( FILETIME *lpFileTime )
2595 GetSystemTimeAsFileTime( lpFileTime );
2596 return S_OK;
2599 /******************************************************************************
2600 * CoLockObjectExternal [OLE32.@]
2602 * Increments or decrements the external reference count of a stub object.
2604 * PARAMS
2605 * pUnk [I] Stub object.
2606 * fLock [I] If TRUE then increments the external ref-count,
2607 * otherwise decrements.
2608 * fLastUnlockReleases [I] If TRUE then the last unlock has the effect of
2609 * calling CoDisconnectObject.
2611 * RETURNS
2612 * Success: S_OK.
2613 * Failure: HRESULT code.
2615 * NOTES
2616 * If fLock is TRUE and an object is passed in that doesn't have a stub
2617 * manager then a new stub manager is created for the object.
2619 HRESULT WINAPI CoLockObjectExternal(
2620 LPUNKNOWN pUnk,
2621 BOOL fLock,
2622 BOOL fLastUnlockReleases)
2624 struct stub_manager *stubmgr;
2625 struct apartment *apt;
2627 TRACE("pUnk=%p, fLock=%s, fLastUnlockReleases=%s\n",
2628 pUnk, fLock ? "TRUE" : "FALSE", fLastUnlockReleases ? "TRUE" : "FALSE");
2630 apt = COM_CurrentApt();
2631 if (!apt) return CO_E_NOTINITIALIZED;
2633 stubmgr = get_stub_manager_from_object(apt, pUnk);
2635 if (stubmgr)
2637 if (fLock)
2638 stub_manager_ext_addref(stubmgr, 1);
2639 else
2640 stub_manager_ext_release(stubmgr, 1, fLastUnlockReleases);
2642 stub_manager_int_release(stubmgr);
2644 return S_OK;
2646 else if (fLock)
2648 stubmgr = new_stub_manager(apt, pUnk);
2650 if (stubmgr)
2652 stub_manager_ext_addref(stubmgr, 1);
2653 stub_manager_int_release(stubmgr);
2656 return S_OK;
2658 else
2660 WARN("stub object not found %p\n", pUnk);
2661 /* Note: native is pretty broken here because it just silently
2662 * fails, without returning an appropriate error code, making apps
2663 * think that the object was disconnected, when it actually wasn't */
2664 return S_OK;
2668 /***********************************************************************
2669 * CoInitializeWOW (OLE32.@)
2671 * WOW equivalent of CoInitialize?
2673 * PARAMS
2674 * x [I] Unknown.
2675 * y [I] Unknown.
2677 * RETURNS
2678 * Unknown.
2680 HRESULT WINAPI CoInitializeWOW(DWORD x,DWORD y)
2682 FIXME("(0x%08x,0x%08x),stub!\n",x,y);
2683 return 0;
2686 /***********************************************************************
2687 * CoGetState [OLE32.@]
2689 * Retrieves the thread state object previously stored by CoSetState().
2691 * PARAMS
2692 * ppv [I] Address where pointer to object will be stored.
2694 * RETURNS
2695 * Success: S_OK.
2696 * Failure: E_OUTOFMEMORY.
2698 * NOTES
2699 * Crashes on all invalid ppv addresses, including NULL.
2700 * If the function returns a non-NULL object then the caller must release its
2701 * reference on the object when the object is no longer required.
2703 * SEE ALSO
2704 * CoSetState().
2706 HRESULT WINAPI CoGetState(IUnknown ** ppv)
2708 struct oletls *info = COM_CurrentInfo();
2709 if (!info) return E_OUTOFMEMORY;
2711 *ppv = NULL;
2713 if (info->state)
2715 IUnknown_AddRef(info->state);
2716 *ppv = info->state;
2717 TRACE("apt->state=%p\n", info->state);
2720 return S_OK;
2723 /***********************************************************************
2724 * CoSetState [OLE32.@]
2726 * Sets the thread state object.
2728 * PARAMS
2729 * pv [I] Pointer to state object to be stored.
2731 * NOTES
2732 * The system keeps a reference on the object while the object stored.
2734 * RETURNS
2735 * Success: S_OK.
2736 * Failure: E_OUTOFMEMORY.
2738 HRESULT WINAPI CoSetState(IUnknown * pv)
2740 struct oletls *info = COM_CurrentInfo();
2741 if (!info) return E_OUTOFMEMORY;
2743 if (pv) IUnknown_AddRef(pv);
2745 if (info->state)
2747 TRACE("-- release %p now\n", info->state);
2748 IUnknown_Release(info->state);
2751 info->state = pv;
2753 return S_OK;
2757 /******************************************************************************
2758 * CoTreatAsClass [OLE32.@]
2760 * Sets the TreatAs value of a class.
2762 * PARAMS
2763 * clsidOld [I] Class to set TreatAs value on.
2764 * clsidNew [I] The class the clsidOld should be treated as.
2766 * RETURNS
2767 * Success: S_OK.
2768 * Failure: HRESULT code.
2770 * SEE ALSO
2771 * CoGetTreatAsClass
2773 HRESULT WINAPI CoTreatAsClass(REFCLSID clsidOld, REFCLSID clsidNew)
2775 static const WCHAR wszAutoTreatAs[] = {'A','u','t','o','T','r','e','a','t','A','s',0};
2776 static const WCHAR wszTreatAs[] = {'T','r','e','a','t','A','s',0};
2777 HKEY hkey = NULL;
2778 WCHAR szClsidNew[CHARS_IN_GUID];
2779 HRESULT res = S_OK;
2780 WCHAR auto_treat_as[CHARS_IN_GUID];
2781 LONG auto_treat_as_size = sizeof(auto_treat_as);
2782 CLSID id;
2784 res = COM_OpenKeyForCLSID(clsidOld, NULL, KEY_READ | KEY_WRITE, &hkey);
2785 if (FAILED(res))
2786 goto done;
2787 if (!memcmp( clsidOld, clsidNew, sizeof(*clsidOld) ))
2789 if (!RegQueryValueW(hkey, wszAutoTreatAs, auto_treat_as, &auto_treat_as_size) &&
2790 !CLSIDFromString(auto_treat_as, &id))
2792 if (RegSetValueW(hkey, wszTreatAs, REG_SZ, auto_treat_as, sizeof(auto_treat_as)))
2794 res = REGDB_E_WRITEREGDB;
2795 goto done;
2798 else
2800 RegDeleteKeyW(hkey, wszTreatAs);
2801 goto done;
2804 else if (!StringFromGUID2(clsidNew, szClsidNew, ARRAYSIZE(szClsidNew)) &&
2805 !RegSetValueW(hkey, wszTreatAs, REG_SZ, szClsidNew, sizeof(szClsidNew)))
2807 res = REGDB_E_WRITEREGDB;
2808 goto done;
2811 done:
2812 if (hkey) RegCloseKey(hkey);
2813 return res;
2816 /******************************************************************************
2817 * CoGetTreatAsClass [OLE32.@]
2819 * Gets the TreatAs value of a class.
2821 * PARAMS
2822 * clsidOld [I] Class to get the TreatAs value of.
2823 * clsidNew [I] The class the clsidOld should be treated as.
2825 * RETURNS
2826 * Success: S_OK.
2827 * Failure: HRESULT code.
2829 * SEE ALSO
2830 * CoSetTreatAsClass
2832 HRESULT WINAPI CoGetTreatAsClass(REFCLSID clsidOld, LPCLSID clsidNew)
2834 static const WCHAR wszTreatAs[] = {'T','r','e','a','t','A','s',0};
2835 HKEY hkey = NULL;
2836 WCHAR szClsidNew[CHARS_IN_GUID];
2837 HRESULT res = S_OK;
2838 LONG len = sizeof(szClsidNew);
2840 FIXME("(%s,%p)\n", debugstr_guid(clsidOld), clsidNew);
2841 memcpy(clsidNew,clsidOld,sizeof(CLSID)); /* copy over old value */
2843 res = COM_OpenKeyForCLSID(clsidOld, wszTreatAs, KEY_READ, &hkey);
2844 if (FAILED(res))
2845 goto done;
2846 if (RegQueryValueW(hkey, NULL, szClsidNew, &len))
2848 res = S_FALSE;
2849 goto done;
2851 res = CLSIDFromString(szClsidNew,clsidNew);
2852 if (FAILED(res))
2853 ERR("Failed CLSIDFromStringA(%s), hres 0x%08x\n", debugstr_w(szClsidNew), res);
2854 done:
2855 if (hkey) RegCloseKey(hkey);
2856 return res;
2859 /******************************************************************************
2860 * CoGetCurrentProcess [OLE32.@]
2861 * CoGetCurrentProcess [COMPOBJ.34]
2863 * Gets the current process ID.
2865 * RETURNS
2866 * The current process ID.
2868 * NOTES
2869 * Is DWORD really the correct return type for this function?
2871 DWORD WINAPI CoGetCurrentProcess(void)
2873 return GetCurrentProcessId();
2876 /******************************************************************************
2877 * CoRegisterMessageFilter [OLE32.@]
2879 * Registers a message filter.
2881 * PARAMS
2882 * lpMessageFilter [I] Pointer to interface.
2883 * lplpMessageFilter [O] Indirect pointer to prior instance if non-NULL.
2885 * RETURNS
2886 * Success: S_OK.
2887 * Failure: HRESULT code.
2889 * NOTES
2890 * Both lpMessageFilter and lplpMessageFilter are optional. Passing in a NULL
2891 * lpMessageFilter removes the message filter.
2893 * If lplpMessageFilter is not NULL the previous message filter will be
2894 * returned in the memory pointer to this parameter and the caller is
2895 * responsible for releasing the object.
2897 * The current thread be in an apartment otherwise the function will crash.
2899 HRESULT WINAPI CoRegisterMessageFilter(
2900 LPMESSAGEFILTER lpMessageFilter,
2901 LPMESSAGEFILTER *lplpMessageFilter)
2903 struct apartment *apt;
2904 IMessageFilter *lpOldMessageFilter;
2906 TRACE("(%p, %p)\n", lpMessageFilter, lplpMessageFilter);
2908 apt = COM_CurrentApt();
2910 /* can't set a message filter in a multi-threaded apartment */
2911 if (!apt || apt->multi_threaded)
2913 WARN("can't set message filter in MTA or uninitialized apt\n");
2914 return CO_E_NOT_SUPPORTED;
2917 if (lpMessageFilter)
2918 IMessageFilter_AddRef(lpMessageFilter);
2920 EnterCriticalSection(&apt->cs);
2922 lpOldMessageFilter = apt->filter;
2923 apt->filter = lpMessageFilter;
2925 LeaveCriticalSection(&apt->cs);
2927 if (lplpMessageFilter)
2928 *lplpMessageFilter = lpOldMessageFilter;
2929 else if (lpOldMessageFilter)
2930 IMessageFilter_Release(lpOldMessageFilter);
2932 return S_OK;
2935 /***********************************************************************
2936 * CoIsOle1Class [OLE32.@]
2938 * Determines whether the specified class an OLE v1 class.
2940 * PARAMS
2941 * clsid [I] Class to test.
2943 * RETURNS
2944 * TRUE if the class is an OLE v1 class, or FALSE otherwise.
2946 BOOL WINAPI CoIsOle1Class(REFCLSID clsid)
2948 FIXME("%s\n", debugstr_guid(clsid));
2949 return FALSE;
2952 /***********************************************************************
2953 * IsEqualGUID [OLE32.@]
2955 * Compares two Unique Identifiers.
2957 * PARAMS
2958 * rguid1 [I] The first GUID to compare.
2959 * rguid2 [I] The other GUID to compare.
2961 * RETURNS
2962 * TRUE if equal
2964 #undef IsEqualGUID
2965 BOOL WINAPI IsEqualGUID(
2966 REFGUID rguid1,
2967 REFGUID rguid2)
2969 return !memcmp(rguid1,rguid2,sizeof(GUID));
2972 /***********************************************************************
2973 * CoInitializeSecurity [OLE32.@]
2975 HRESULT WINAPI CoInitializeSecurity(PSECURITY_DESCRIPTOR pSecDesc, LONG cAuthSvc,
2976 SOLE_AUTHENTICATION_SERVICE* asAuthSvc,
2977 void* pReserved1, DWORD dwAuthnLevel,
2978 DWORD dwImpLevel, void* pReserved2,
2979 DWORD dwCapabilities, void* pReserved3)
2981 FIXME("(%p,%d,%p,%p,%d,%d,%p,%d,%p) - stub!\n", pSecDesc, cAuthSvc,
2982 asAuthSvc, pReserved1, dwAuthnLevel, dwImpLevel, pReserved2,
2983 dwCapabilities, pReserved3);
2984 return S_OK;
2987 /***********************************************************************
2988 * CoSuspendClassObjects [OLE32.@]
2990 * Suspends all registered class objects to prevent further requests coming in
2991 * for those objects.
2993 * RETURNS
2994 * Success: S_OK.
2995 * Failure: HRESULT code.
2997 HRESULT WINAPI CoSuspendClassObjects(void)
2999 FIXME("\n");
3000 return S_OK;
3003 /***********************************************************************
3004 * CoAddRefServerProcess [OLE32.@]
3006 * Helper function for incrementing the reference count of a local-server
3007 * process.
3009 * RETURNS
3010 * New reference count.
3012 * SEE ALSO
3013 * CoReleaseServerProcess().
3015 ULONG WINAPI CoAddRefServerProcess(void)
3017 ULONG refs;
3019 TRACE("\n");
3021 EnterCriticalSection(&csRegisteredClassList);
3022 refs = ++s_COMServerProcessReferences;
3023 LeaveCriticalSection(&csRegisteredClassList);
3025 TRACE("refs before: %d\n", refs - 1);
3027 return refs;
3030 /***********************************************************************
3031 * CoReleaseServerProcess [OLE32.@]
3033 * Helper function for decrementing the reference count of a local-server
3034 * process.
3036 * RETURNS
3037 * New reference count.
3039 * NOTES
3040 * When reference count reaches 0, this function suspends all registered
3041 * classes so no new connections are accepted.
3043 * SEE ALSO
3044 * CoAddRefServerProcess(), CoSuspendClassObjects().
3046 ULONG WINAPI CoReleaseServerProcess(void)
3048 ULONG refs;
3050 TRACE("\n");
3052 EnterCriticalSection(&csRegisteredClassList);
3054 refs = --s_COMServerProcessReferences;
3055 /* FIXME: if (!refs) COM_SuspendClassObjects(); */
3057 LeaveCriticalSection(&csRegisteredClassList);
3059 TRACE("refs after: %d\n", refs);
3061 return refs;
3064 /***********************************************************************
3065 * CoIsHandlerConnected [OLE32.@]
3067 * Determines whether a proxy is connected to a remote stub.
3069 * PARAMS
3070 * pUnk [I] Pointer to object that may or may not be connected.
3072 * RETURNS
3073 * TRUE if pUnk is not a proxy or if pUnk is connected to a remote stub, or
3074 * FALSE otherwise.
3076 BOOL WINAPI CoIsHandlerConnected(IUnknown *pUnk)
3078 FIXME("%p\n", pUnk);
3080 return TRUE;
3083 /***********************************************************************
3084 * CoAllowSetForegroundWindow [OLE32.@]
3087 HRESULT WINAPI CoAllowSetForegroundWindow(IUnknown *pUnk, void *pvReserved)
3089 FIXME("(%p, %p): stub\n", pUnk, pvReserved);
3090 return S_OK;
3093 /***********************************************************************
3094 * CoQueryProxyBlanket [OLE32.@]
3096 * Retrieves the security settings being used by a proxy.
3098 * PARAMS
3099 * pProxy [I] Pointer to the proxy object.
3100 * pAuthnSvc [O] The type of authentication service.
3101 * pAuthzSvc [O] The type of authorization service.
3102 * ppServerPrincName [O] Optional. The server prinicple name.
3103 * pAuthnLevel [O] The authentication level.
3104 * pImpLevel [O] The impersonation level.
3105 * ppAuthInfo [O] Information specific to the authorization/authentication service.
3106 * pCapabilities [O] Flags affecting the security behaviour.
3108 * RETURNS
3109 * Success: S_OK.
3110 * Failure: HRESULT code.
3112 * SEE ALSO
3113 * CoCopyProxy, CoSetProxyBlanket.
3115 HRESULT WINAPI CoQueryProxyBlanket(IUnknown *pProxy, DWORD *pAuthnSvc,
3116 DWORD *pAuthzSvc, OLECHAR **ppServerPrincName, DWORD *pAuthnLevel,
3117 DWORD *pImpLevel, void **ppAuthInfo, DWORD *pCapabilities)
3119 IClientSecurity *pCliSec;
3120 HRESULT hr;
3122 TRACE("%p\n", pProxy);
3124 hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
3125 if (SUCCEEDED(hr))
3127 hr = IClientSecurity_QueryBlanket(pCliSec, pProxy, pAuthnSvc,
3128 pAuthzSvc, ppServerPrincName,
3129 pAuthnLevel, pImpLevel, ppAuthInfo,
3130 pCapabilities);
3131 IClientSecurity_Release(pCliSec);
3134 if (FAILED(hr)) ERR("-- failed with 0x%08x\n", hr);
3135 return hr;
3138 /***********************************************************************
3139 * CoSetProxyBlanket [OLE32.@]
3141 * Sets the security settings for a proxy.
3143 * PARAMS
3144 * pProxy [I] Pointer to the proxy object.
3145 * AuthnSvc [I] The type of authentication service.
3146 * AuthzSvc [I] The type of authorization service.
3147 * pServerPrincName [I] The server prinicple name.
3148 * AuthnLevel [I] The authentication level.
3149 * ImpLevel [I] The impersonation level.
3150 * pAuthInfo [I] Information specific to the authorization/authentication service.
3151 * Capabilities [I] Flags affecting the security behaviour.
3153 * RETURNS
3154 * Success: S_OK.
3155 * Failure: HRESULT code.
3157 * SEE ALSO
3158 * CoQueryProxyBlanket, CoCopyProxy.
3160 HRESULT WINAPI CoSetProxyBlanket(IUnknown *pProxy, DWORD AuthnSvc,
3161 DWORD AuthzSvc, OLECHAR *pServerPrincName, DWORD AuthnLevel,
3162 DWORD ImpLevel, void *pAuthInfo, DWORD Capabilities)
3164 IClientSecurity *pCliSec;
3165 HRESULT hr;
3167 TRACE("%p\n", pProxy);
3169 hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
3170 if (SUCCEEDED(hr))
3172 hr = IClientSecurity_SetBlanket(pCliSec, pProxy, AuthnSvc,
3173 AuthzSvc, pServerPrincName,
3174 AuthnLevel, ImpLevel, pAuthInfo,
3175 Capabilities);
3176 IClientSecurity_Release(pCliSec);
3179 if (FAILED(hr)) ERR("-- failed with 0x%08x\n", hr);
3180 return hr;
3183 /***********************************************************************
3184 * CoCopyProxy [OLE32.@]
3186 * Copies a proxy.
3188 * PARAMS
3189 * pProxy [I] Pointer to the proxy object.
3190 * ppCopy [O] Copy of the proxy.
3192 * RETURNS
3193 * Success: S_OK.
3194 * Failure: HRESULT code.
3196 * SEE ALSO
3197 * CoQueryProxyBlanket, CoSetProxyBlanket.
3199 HRESULT WINAPI CoCopyProxy(IUnknown *pProxy, IUnknown **ppCopy)
3201 IClientSecurity *pCliSec;
3202 HRESULT hr;
3204 TRACE("%p\n", pProxy);
3206 hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
3207 if (SUCCEEDED(hr))
3209 hr = IClientSecurity_CopyProxy(pCliSec, pProxy, ppCopy);
3210 IClientSecurity_Release(pCliSec);
3213 if (FAILED(hr)) ERR("-- failed with 0x%08x\n", hr);
3214 return hr;
3218 /***********************************************************************
3219 * CoGetCallContext [OLE32.@]
3221 * Gets the context of the currently executing server call in the current
3222 * thread.
3224 * PARAMS
3225 * riid [I] Context interface to return.
3226 * ppv [O] Pointer to memory that will receive the context on return.
3228 * RETURNS
3229 * Success: S_OK.
3230 * Failure: HRESULT code.
3232 HRESULT WINAPI CoGetCallContext(REFIID riid, void **ppv)
3234 FIXME("(%s, %p): stub\n", debugstr_guid(riid), ppv);
3236 *ppv = NULL;
3237 return E_NOINTERFACE;
3240 /***********************************************************************
3241 * CoQueryClientBlanket [OLE32.@]
3243 * Retrieves the authentication information about the client of the currently
3244 * executing server call in the current thread.
3246 * PARAMS
3247 * pAuthnSvc [O] Optional. The type of authentication service.
3248 * pAuthzSvc [O] Optional. The type of authorization service.
3249 * pServerPrincName [O] Optional. The server prinicple name.
3250 * pAuthnLevel [O] Optional. The authentication level.
3251 * pImpLevel [O] Optional. The impersonation level.
3252 * pPrivs [O] Optional. Information about the privileges of the client.
3253 * pCapabilities [IO] Optional. Flags affecting the security behaviour.
3255 * RETURNS
3256 * Success: S_OK.
3257 * Failure: HRESULT code.
3259 * SEE ALSO
3260 * CoImpersonateClient, CoRevertToSelf, CoGetCallContext.
3262 HRESULT WINAPI CoQueryClientBlanket(
3263 DWORD *pAuthnSvc,
3264 DWORD *pAuthzSvc,
3265 OLECHAR **pServerPrincName,
3266 DWORD *pAuthnLevel,
3267 DWORD *pImpLevel,
3268 RPC_AUTHZ_HANDLE *pPrivs,
3269 DWORD *pCapabilities)
3271 IServerSecurity *pSrvSec;
3272 HRESULT hr;
3274 TRACE("(%p, %p, %p, %p, %p, %p, %p)\n",
3275 pAuthnSvc, pAuthzSvc, pServerPrincName, pAuthnLevel, pImpLevel,
3276 pPrivs, pCapabilities);
3278 hr = CoGetCallContext(&IID_IServerSecurity, (void **)&pSrvSec);
3279 if (SUCCEEDED(hr))
3281 hr = IServerSecurity_QueryBlanket(
3282 pSrvSec, pAuthnSvc, pAuthzSvc, pServerPrincName, pAuthnLevel,
3283 pImpLevel, pPrivs, pCapabilities);
3284 IServerSecurity_Release(pSrvSec);
3287 return hr;
3290 /***********************************************************************
3291 * CoImpersonateClient [OLE32.@]
3293 * Impersonates the client of the currently executing server call in the
3294 * current thread.
3296 * PARAMS
3297 * None.
3299 * RETURNS
3300 * Success: S_OK.
3301 * Failure: HRESULT code.
3303 * NOTES
3304 * If this function fails then the current thread will not be impersonating
3305 * the client and all actions will take place on behalf of the server.
3306 * Therefore, it is important to check the return value from this function.
3308 * SEE ALSO
3309 * CoRevertToSelf, CoQueryClientBlanket, CoGetCallContext.
3311 HRESULT WINAPI CoImpersonateClient(void)
3313 IServerSecurity *pSrvSec;
3314 HRESULT hr;
3316 TRACE("\n");
3318 hr = CoGetCallContext(&IID_IServerSecurity, (void **)&pSrvSec);
3319 if (SUCCEEDED(hr))
3321 hr = IServerSecurity_ImpersonateClient(pSrvSec);
3322 IServerSecurity_Release(pSrvSec);
3325 return hr;
3328 /***********************************************************************
3329 * CoRevertToSelf [OLE32.@]
3331 * Ends the impersonation of the client of the currently executing server
3332 * call in the current thread.
3334 * PARAMS
3335 * None.
3337 * RETURNS
3338 * Success: S_OK.
3339 * Failure: HRESULT code.
3341 * SEE ALSO
3342 * CoImpersonateClient, CoQueryClientBlanket, CoGetCallContext.
3344 HRESULT WINAPI CoRevertToSelf(void)
3346 IServerSecurity *pSrvSec;
3347 HRESULT hr;
3349 TRACE("\n");
3351 hr = CoGetCallContext(&IID_IServerSecurity, (void **)&pSrvSec);
3352 if (SUCCEEDED(hr))
3354 hr = IServerSecurity_RevertToSelf(pSrvSec);
3355 IServerSecurity_Release(pSrvSec);
3358 return hr;
3361 static BOOL COM_PeekMessage(struct apartment *apt, MSG *msg)
3363 /* first try to retrieve messages for incoming COM calls to the apartment window */
3364 return PeekMessageW(msg, apt->win, WM_USER, WM_APP - 1, PM_REMOVE|PM_NOYIELD) ||
3365 /* next retrieve other messages necessary for the app to remain responsive */
3366 PeekMessageW(msg, NULL, 0, 0, PM_QS_PAINT|PM_QS_POSTMESSAGE|PM_REMOVE|PM_NOYIELD);
3369 /***********************************************************************
3370 * CoWaitForMultipleHandles [OLE32.@]
3372 * Waits for one or more handles to become signaled.
3374 * PARAMS
3375 * dwFlags [I] Flags. See notes.
3376 * dwTimeout [I] Timeout in milliseconds.
3377 * cHandles [I] Number of handles pointed to by pHandles.
3378 * pHandles [I] Handles to wait for.
3379 * lpdwindex [O] Index of handle that was signaled.
3381 * RETURNS
3382 * Success: S_OK.
3383 * Failure: RPC_S_CALLPENDING on timeout.
3385 * NOTES
3387 * The dwFlags parameter can be zero or more of the following:
3388 *| COWAIT_WAITALL - Wait for all of the handles to become signaled.
3389 *| COWAIT_ALERTABLE - Allows a queued APC to run during the wait.
3391 * SEE ALSO
3392 * MsgWaitForMultipleObjects, WaitForMultipleObjects.
3394 HRESULT WINAPI CoWaitForMultipleHandles(DWORD dwFlags, DWORD dwTimeout,
3395 ULONG cHandles, LPHANDLE pHandles, LPDWORD lpdwindex)
3397 HRESULT hr = S_OK;
3398 DWORD start_time = GetTickCount();
3399 APARTMENT *apt = COM_CurrentApt();
3400 BOOL message_loop = apt && !apt->multi_threaded;
3402 TRACE("(0x%08x, 0x%08x, %d, %p, %p)\n", dwFlags, dwTimeout, cHandles,
3403 pHandles, lpdwindex);
3405 while (TRUE)
3407 DWORD now = GetTickCount();
3408 DWORD res;
3410 if ((dwTimeout != INFINITE) && (start_time + dwTimeout >= now))
3412 hr = RPC_S_CALLPENDING;
3413 break;
3416 if (message_loop)
3418 DWORD wait_flags = (dwFlags & COWAIT_WAITALL) ? MWMO_WAITALL : 0 |
3419 (dwFlags & COWAIT_ALERTABLE ) ? MWMO_ALERTABLE : 0;
3421 TRACE("waiting for rpc completion or window message\n");
3423 res = MsgWaitForMultipleObjectsEx(cHandles, pHandles,
3424 (dwTimeout == INFINITE) ? INFINITE : start_time + dwTimeout - now,
3425 QS_ALLINPUT, wait_flags);
3427 if (res == WAIT_OBJECT_0 + cHandles) /* messages available */
3429 MSG msg;
3431 /* call message filter */
3433 if (COM_CurrentApt()->filter)
3435 PENDINGTYPE pendingtype =
3436 COM_CurrentInfo()->pending_call_count_server ?
3437 PENDINGTYPE_NESTED : PENDINGTYPE_TOPLEVEL;
3438 DWORD be_handled = IMessageFilter_MessagePending(
3439 COM_CurrentApt()->filter, 0 /* FIXME */,
3440 now - start_time, pendingtype);
3441 TRACE("IMessageFilter_MessagePending returned %d\n", be_handled);
3442 switch (be_handled)
3444 case PENDINGMSG_CANCELCALL:
3445 WARN("call canceled\n");
3446 hr = RPC_E_CALL_CANCELED;
3447 break;
3448 case PENDINGMSG_WAITNOPROCESS:
3449 case PENDINGMSG_WAITDEFPROCESS:
3450 default:
3451 /* FIXME: MSDN is very vague about the difference
3452 * between WAITNOPROCESS and WAITDEFPROCESS - there
3453 * appears to be none, so it is possibly a left-over
3454 * from the 16-bit world. */
3455 break;
3459 /* note: using "if" here instead of "while" might seem less
3460 * efficient, but only if we are optimising for quick delivery
3461 * of pending messages, rather than quick completion of the
3462 * COM call */
3463 if (COM_PeekMessage(apt, &msg))
3465 TRACE("received message whilst waiting for RPC: 0x%04x\n", msg.message);
3466 TranslateMessage(&msg);
3467 DispatchMessageW(&msg);
3468 if (msg.message == WM_QUIT)
3470 TRACE("resending WM_QUIT to outer message loop\n");
3471 PostQuitMessage(msg.wParam);
3472 /* no longer need to process messages */
3473 message_loop = FALSE;
3476 continue;
3479 else
3481 TRACE("waiting for rpc completion\n");
3483 res = WaitForMultipleObjectsEx(cHandles, pHandles,
3484 (dwFlags & COWAIT_WAITALL) ? TRUE : FALSE,
3485 (dwTimeout == INFINITE) ? INFINITE : start_time + dwTimeout - now,
3486 (dwFlags & COWAIT_ALERTABLE) ? TRUE : FALSE);
3489 if ((res >= WAIT_OBJECT_0) && (res < WAIT_OBJECT_0 + cHandles))
3491 /* handle signaled, store index */
3492 *lpdwindex = (res - WAIT_OBJECT_0);
3493 break;
3495 else if (res == WAIT_TIMEOUT)
3497 hr = RPC_S_CALLPENDING;
3498 break;
3500 else
3502 ERR("Unexpected wait termination: %d, %d\n", res, GetLastError());
3503 hr = E_UNEXPECTED;
3504 break;
3507 TRACE("-- 0x%08x\n", hr);
3508 return hr;
3512 /***********************************************************************
3513 * CoGetObject [OLE32.@]
3515 * Gets the object named by coverting the name to a moniker and binding to it.
3517 * PARAMS
3518 * pszName [I] String representing the object.
3519 * pBindOptions [I] Parameters affecting the binding to the named object.
3520 * riid [I] Interface to bind to on the objecct.
3521 * ppv [O] On output, the interface riid of the object represented
3522 * by pszName.
3524 * RETURNS
3525 * Success: S_OK.
3526 * Failure: HRESULT code.
3528 * SEE ALSO
3529 * MkParseDisplayName.
3531 HRESULT WINAPI CoGetObject(LPCWSTR pszName, BIND_OPTS *pBindOptions,
3532 REFIID riid, void **ppv)
3534 IBindCtx *pbc;
3535 HRESULT hr;
3537 *ppv = NULL;
3539 hr = CreateBindCtx(0, &pbc);
3540 if (SUCCEEDED(hr))
3542 if (pBindOptions)
3543 hr = IBindCtx_SetBindOptions(pbc, pBindOptions);
3545 if (SUCCEEDED(hr))
3547 ULONG chEaten;
3548 IMoniker *pmk;
3550 hr = MkParseDisplayName(pbc, pszName, &chEaten, &pmk);
3551 if (SUCCEEDED(hr))
3553 hr = IMoniker_BindToObject(pmk, pbc, NULL, riid, ppv);
3554 IMoniker_Release(pmk);
3558 IBindCtx_Release(pbc);
3560 return hr;
3563 /***********************************************************************
3564 * CoRegisterChannelHook [OLE32.@]
3566 * Registers a process-wide hook that is called during ORPC calls.
3568 * PARAMS
3569 * guidExtension [I] GUID of the channel hook to register.
3570 * pChannelHook [I] Channel hook object to register.
3572 * RETURNS
3573 * Success: S_OK.
3574 * Failure: HRESULT code.
3576 HRESULT WINAPI CoRegisterChannelHook(REFGUID guidExtension, IChannelHook *pChannelHook)
3578 TRACE("(%s, %p)\n", debugstr_guid(guidExtension), pChannelHook);
3580 return RPC_RegisterChannelHook(guidExtension, pChannelHook);
3583 typedef struct Context
3585 const IComThreadingInfoVtbl *lpVtbl;
3586 LONG refs;
3587 APTTYPE apttype;
3588 } Context;
3590 static HRESULT WINAPI Context_QueryInterface(IComThreadingInfo *iface, REFIID riid, LPVOID *ppv)
3592 *ppv = NULL;
3594 if (IsEqualIID(riid, &IID_IComThreadingInfo) ||
3595 IsEqualIID(riid, &IID_IUnknown))
3597 *ppv = iface;
3598 IUnknown_AddRef(iface);
3599 return S_OK;
3602 FIXME("interface not implemented %s\n", debugstr_guid(riid));
3603 return E_NOINTERFACE;
3606 static ULONG WINAPI Context_AddRef(IComThreadingInfo *iface)
3608 Context *This = (Context *)iface;
3609 return InterlockedIncrement(&This->refs);
3612 static ULONG WINAPI Context_Release(IComThreadingInfo *iface)
3614 Context *This = (Context *)iface;
3615 ULONG refs = InterlockedDecrement(&This->refs);
3616 if (!refs)
3617 HeapFree(GetProcessHeap(), 0, This);
3618 return refs;
3621 static HRESULT WINAPI Context_GetCurrentApartmentType(IComThreadingInfo *iface, APTTYPE *apttype)
3623 Context *This = (Context *)iface;
3625 TRACE("(%p)\n", apttype);
3627 *apttype = This->apttype;
3628 return S_OK;
3631 static HRESULT WINAPI Context_GetCurrentThreadType(IComThreadingInfo *iface, THDTYPE *thdtype)
3633 Context *This = (Context *)iface;
3635 TRACE("(%p)\n", thdtype);
3637 switch (This->apttype)
3639 case APTTYPE_STA:
3640 case APTTYPE_MAINSTA:
3641 *thdtype = THDTYPE_PROCESSMESSAGES;
3642 break;
3643 default:
3644 *thdtype = THDTYPE_BLOCKMESSAGES;
3645 break;
3647 return S_OK;
3650 static HRESULT WINAPI Context_GetCurrentLogicalThreadId(IComThreadingInfo *iface, GUID *logical_thread_id)
3652 FIXME("(%p): stub\n", logical_thread_id);
3653 return E_NOTIMPL;
3656 static HRESULT WINAPI Context_SetCurrentLogicalThreadId(IComThreadingInfo *iface, REFGUID logical_thread_id)
3658 FIXME("(%s): stub\n", debugstr_guid(logical_thread_id));
3659 return E_NOTIMPL;
3662 static const IComThreadingInfoVtbl Context_Threading_Vtbl =
3664 Context_QueryInterface,
3665 Context_AddRef,
3666 Context_Release,
3667 Context_GetCurrentApartmentType,
3668 Context_GetCurrentThreadType,
3669 Context_GetCurrentLogicalThreadId,
3670 Context_SetCurrentLogicalThreadId
3673 /***********************************************************************
3674 * CoGetObjectContext [OLE32.@]
3676 * Retrieves an object associated with the current context (i.e. apartment).
3678 * PARAMS
3679 * riid [I] ID of the interface of the object to retrieve.
3680 * ppv [O] Address where object will be stored on return.
3682 * RETURNS
3683 * Success: S_OK.
3684 * Failure: HRESULT code.
3686 HRESULT WINAPI CoGetObjectContext(REFIID riid, void **ppv)
3688 APARTMENT *apt = COM_CurrentApt();
3689 Context *context;
3690 HRESULT hr;
3692 TRACE("(%s, %p)\n", debugstr_guid(riid), ppv);
3694 *ppv = NULL;
3695 if (!apt)
3697 ERR("apartment not initialised\n");
3698 return CO_E_NOTINITIALIZED;
3701 context = HeapAlloc(GetProcessHeap(), 0, sizeof(*context));
3702 if (!context)
3703 return E_OUTOFMEMORY;
3705 context->lpVtbl = &Context_Threading_Vtbl;
3706 context->refs = 1;
3707 if (apt->multi_threaded)
3708 context->apttype = APTTYPE_MTA;
3709 else if (apt->main)
3710 context->apttype = APTTYPE_MAINSTA;
3711 else
3712 context->apttype = APTTYPE_STA;
3714 hr = IUnknown_QueryInterface((IUnknown *)&context->lpVtbl, riid, ppv);
3715 IUnknown_Release((IUnknown *)&context->lpVtbl);
3717 return hr;
3720 /***********************************************************************
3721 * DllMain (OLE32.@)
3723 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID fImpLoad)
3725 TRACE("%p 0x%x %p\n", hinstDLL, fdwReason, fImpLoad);
3727 switch(fdwReason) {
3728 case DLL_PROCESS_ATTACH:
3729 OLE32_hInstance = hinstDLL;
3730 COMPOBJ_InitProcess();
3731 if (TRACE_ON(ole)) CoRegisterMallocSpy((LPVOID)-1);
3732 break;
3734 case DLL_PROCESS_DETACH:
3735 if (TRACE_ON(ole)) CoRevokeMallocSpy();
3736 OLEDD_UnInitialize();
3737 COMPOBJ_UninitProcess();
3738 RPC_UnregisterAllChannelHooks();
3739 COMPOBJ_DllList_Free();
3740 OLE32_hInstance = 0;
3741 break;
3743 case DLL_THREAD_DETACH:
3744 COM_TlsDestroy();
3745 break;
3747 return TRUE;
3750 /* NOTE: DllRegisterServer and DllUnregisterServer are in regsvr.c */