crypt32: Use BOOL type where appropriate.
[wine/multimedia.git] / dlls / ole32 / compobj.c
blob3c0c0855ba6adc6cf3715fe1520f84efb6a8f245
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
39 #include "config.h"
41 #include <stdarg.h>
42 #include <stdio.h>
43 #include <string.h>
44 #include <assert.h>
46 #define COBJMACROS
47 #define NONAMELESSUNION
48 #define NONAMELESSSTRUCT
50 #include "ntstatus.h"
51 #define WIN32_NO_STATUS
52 #include "windef.h"
53 #include "winbase.h"
54 #include "winerror.h"
55 #include "winreg.h"
56 #include "winuser.h"
57 #define USE_COM_CONTEXT_DEF
58 #include "objbase.h"
59 #include "ole2.h"
60 #include "ole2ver.h"
61 #include "ctxtcall.h"
62 #include "dde.h"
63 #include "servprov.h"
65 #include "initguid.h"
66 #include "compobj_private.h"
67 #include "moniker.h"
69 #include "wine/unicode.h"
70 #include "wine/debug.h"
72 WINE_DEFAULT_DEBUG_CHANNEL(ole);
74 #define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))
76 /****************************************************************************
77 * This section defines variables internal to the COM module.
80 static APARTMENT *MTA; /* protected by csApartment */
81 static APARTMENT *MainApartment; /* the first STA apartment */
82 static struct list apts = LIST_INIT( apts ); /* protected by csApartment */
84 static CRITICAL_SECTION csApartment;
85 static CRITICAL_SECTION_DEBUG critsect_debug =
87 0, 0, &csApartment,
88 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
89 0, 0, { (DWORD_PTR)(__FILE__ ": csApartment") }
91 static CRITICAL_SECTION csApartment = { &critsect_debug, -1, 0, 0, 0, 0 };
93 enum comclass_threadingmodel
95 ThreadingModel_Apartment = 1,
96 ThreadingModel_Free = 2,
97 ThreadingModel_No = 3,
98 ThreadingModel_Both = 4,
99 ThreadingModel_Neutral = 5
102 enum comclass_miscfields
104 MiscStatus = 1,
105 MiscStatusIcon = 2,
106 MiscStatusContent = 4,
107 MiscStatusThumbnail = 8,
108 MiscStatusDocPrint = 16
111 struct comclassredirect_data
113 ULONG size;
114 BYTE res;
115 BYTE miscmask;
116 BYTE res1[2];
117 DWORD model;
118 GUID clsid;
119 GUID alias;
120 GUID clsid2;
121 GUID tlbid;
122 ULONG name_len;
123 ULONG name_offset;
124 ULONG progid_len;
125 ULONG progid_offset;
126 ULONG clrdata_len;
127 ULONG clrdata_offset;
128 DWORD miscstatus;
129 DWORD miscstatuscontent;
130 DWORD miscstatusthumbnail;
131 DWORD miscstatusicon;
132 DWORD miscstatusdocprint;
135 struct ifacepsredirect_data
137 ULONG size;
138 DWORD mask;
139 GUID iid;
140 ULONG nummethods;
141 GUID tlbid;
142 GUID base;
143 ULONG name_len;
144 ULONG name_offset;
147 struct progidredirect_data
149 ULONG size;
150 DWORD reserved;
151 ULONG clsid_offset;
154 struct class_reg_data
156 union
158 struct
160 struct comclassredirect_data *data;
161 void *section;
162 HANDLE hactctx;
163 } actctx;
164 HKEY hkey;
165 } u;
166 BOOL hkey;
169 struct registered_psclsid
171 struct list entry;
172 IID iid;
173 CLSID clsid;
177 * This is a marshallable object exposing registered local servers.
178 * IServiceProvider is used only because it happens meet requirements
179 * and already has proxy/stub code. If more functionality is needed,
180 * a custom interface may be used instead.
182 struct LocalServer
184 IServiceProvider IServiceProvider_iface;
185 LONG ref;
186 APARTMENT *apt;
187 IStream *marshal_stream;
191 * This lock count counts the number of times CoInitialize is called. It is
192 * decreased every time CoUninitialize is called. When it hits 0, the COM
193 * libraries are freed
195 static LONG s_COMLockCount = 0;
196 /* Reference count used by CoAddRefServerProcess/CoReleaseServerProcess */
197 static LONG s_COMServerProcessReferences = 0;
200 * This linked list contains the list of registered class objects. These
201 * are mostly used to register the factories for out-of-proc servers of OLE
202 * objects.
204 * TODO: Make this data structure aware of inter-process communication. This
205 * means that parts of this will be exported to rpcss.
207 typedef struct tagRegisteredClass
209 struct list entry;
210 CLSID classIdentifier;
211 OXID apartment_id;
212 LPUNKNOWN classObject;
213 DWORD runContext;
214 DWORD connectFlags;
215 DWORD dwCookie;
216 void *RpcRegistration;
217 } RegisteredClass;
219 static struct list RegisteredClassList = LIST_INIT(RegisteredClassList);
221 static CRITICAL_SECTION csRegisteredClassList;
222 static CRITICAL_SECTION_DEBUG class_cs_debug =
224 0, 0, &csRegisteredClassList,
225 { &class_cs_debug.ProcessLocksList, &class_cs_debug.ProcessLocksList },
226 0, 0, { (DWORD_PTR)(__FILE__ ": csRegisteredClassList") }
228 static CRITICAL_SECTION csRegisteredClassList = { &class_cs_debug, -1, 0, 0, 0, 0 };
230 static inline enum comclass_miscfields dvaspect_to_miscfields(DWORD aspect)
232 switch (aspect)
234 case DVASPECT_CONTENT:
235 return MiscStatusContent;
236 case DVASPECT_THUMBNAIL:
237 return MiscStatusThumbnail;
238 case DVASPECT_ICON:
239 return MiscStatusIcon;
240 case DVASPECT_DOCPRINT:
241 return MiscStatusDocPrint;
242 default:
243 return MiscStatus;
247 BOOL actctx_get_miscstatus(const CLSID *clsid, DWORD aspect, DWORD *status)
249 ACTCTX_SECTION_KEYED_DATA data;
251 data.cbSize = sizeof(data);
252 if (FindActCtxSectionGuid(0, NULL, ACTIVATION_CONTEXT_SECTION_COM_SERVER_REDIRECTION,
253 clsid, &data))
255 struct comclassredirect_data *comclass = (struct comclassredirect_data*)data.lpData;
256 enum comclass_miscfields misc = dvaspect_to_miscfields(aspect);
258 if (!(comclass->miscmask & misc))
260 if (!(comclass->miscmask & MiscStatus))
262 *status = 0;
263 return TRUE;
265 misc = MiscStatus;
268 switch (misc)
270 case MiscStatus:
271 *status = comclass->miscstatus;
272 break;
273 case MiscStatusIcon:
274 *status = comclass->miscstatusicon;
275 break;
276 case MiscStatusContent:
277 *status = comclass->miscstatuscontent;
278 break;
279 case MiscStatusThumbnail:
280 *status = comclass->miscstatusthumbnail;
281 break;
282 case MiscStatusDocPrint:
283 *status = comclass->miscstatusdocprint;
284 break;
285 default:
289 return TRUE;
291 else
292 return FALSE;
295 /* wrapper for NtCreateKey that creates the key recursively if necessary */
296 static NTSTATUS create_key( HKEY *retkey, ACCESS_MASK access, OBJECT_ATTRIBUTES *attr )
298 NTSTATUS status = NtCreateKey( (HANDLE *)retkey, access, attr, 0, NULL, 0, NULL );
300 if (status == STATUS_OBJECT_NAME_NOT_FOUND)
302 HANDLE subkey, root = attr->RootDirectory;
303 WCHAR *buffer = attr->ObjectName->Buffer;
304 DWORD attrs, pos = 0, i = 0, len = attr->ObjectName->Length / sizeof(WCHAR);
305 UNICODE_STRING str;
307 while (i < len && buffer[i] != '\\') i++;
308 if (i == len) return status;
310 attrs = attr->Attributes;
311 attr->ObjectName = &str;
313 while (i < len)
315 str.Buffer = buffer + pos;
316 str.Length = (i - pos) * sizeof(WCHAR);
317 status = NtCreateKey( &subkey, access, attr, 0, NULL, 0, NULL );
318 if (attr->RootDirectory != root) NtClose( attr->RootDirectory );
319 if (status) return status;
320 attr->RootDirectory = subkey;
321 while (i < len && buffer[i] == '\\') i++;
322 pos = i;
323 while (i < len && buffer[i] != '\\') i++;
325 str.Buffer = buffer + pos;
326 str.Length = (i - pos) * sizeof(WCHAR);
327 attr->Attributes = attrs;
328 status = NtCreateKey( (PHANDLE)retkey, access, attr, 0, NULL, 0, NULL );
329 if (attr->RootDirectory != root) NtClose( attr->RootDirectory );
331 return status;
334 static const WCHAR classes_rootW[] =
335 {'M','a','c','h','i','n','e','\\','S','o','f','t','w','a','r','e','\\','C','l','a','s','s','e','s',0};
337 static HKEY classes_root_hkey;
339 /* create the special HKEY_CLASSES_ROOT key */
340 static HKEY create_classes_root_hkey(void)
342 HKEY hkey, ret = 0;
343 OBJECT_ATTRIBUTES attr;
344 UNICODE_STRING name;
346 attr.Length = sizeof(attr);
347 attr.RootDirectory = 0;
348 attr.ObjectName = &name;
349 attr.Attributes = 0;
350 attr.SecurityDescriptor = NULL;
351 attr.SecurityQualityOfService = NULL;
352 RtlInitUnicodeString( &name, classes_rootW );
353 if (create_key( &hkey, MAXIMUM_ALLOWED, &attr )) return 0;
354 TRACE( "%s -> %p\n", debugstr_w(attr.ObjectName->Buffer), hkey );
356 if (!(ret = InterlockedCompareExchangePointer( (void **)&classes_root_hkey, hkey, 0 )))
357 ret = hkey;
358 else
359 NtClose( hkey ); /* somebody beat us to it */
360 return ret;
363 /* map the hkey from special root to normal key if necessary */
364 static inline HKEY get_classes_root_hkey( HKEY hkey )
366 HKEY ret = hkey;
368 if (hkey == HKEY_CLASSES_ROOT && !(ret = classes_root_hkey))
369 ret = create_classes_root_hkey();
371 return ret;
374 LSTATUS create_classes_key( HKEY hkey, const WCHAR *name, REGSAM access, HKEY *retkey )
376 OBJECT_ATTRIBUTES attr;
377 UNICODE_STRING nameW;
379 if (!(hkey = get_classes_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
381 attr.Length = sizeof(attr);
382 attr.RootDirectory = hkey;
383 attr.ObjectName = &nameW;
384 attr.Attributes = 0;
385 attr.SecurityDescriptor = NULL;
386 attr.SecurityQualityOfService = NULL;
387 RtlInitUnicodeString( &nameW, name );
389 return RtlNtStatusToDosError( create_key( retkey, access, &attr ) );
392 LSTATUS open_classes_key( HKEY hkey, const WCHAR *name, REGSAM access, HKEY *retkey )
394 OBJECT_ATTRIBUTES attr;
395 UNICODE_STRING nameW;
397 if (!(hkey = get_classes_root_hkey( hkey ))) return ERROR_INVALID_HANDLE;
399 attr.Length = sizeof(attr);
400 attr.RootDirectory = hkey;
401 attr.ObjectName = &nameW;
402 attr.Attributes = 0;
403 attr.SecurityDescriptor = NULL;
404 attr.SecurityQualityOfService = NULL;
405 RtlInitUnicodeString( &nameW, name );
407 return RtlNtStatusToDosError( NtOpenKey( (HANDLE *)retkey, access, &attr ) );
410 /*****************************************************************************
411 * This section contains OpenDllList definitions
413 * The OpenDllList contains only handles of dll loaded by CoGetClassObject or
414 * other functions that do LoadLibrary _without_ giving back a HMODULE.
415 * Without this list these handles would never be freed.
417 * FIXME: a DLL that says OK when asked for unloading is unloaded in the
418 * next unload-call but not before 600 sec.
421 typedef HRESULT (CALLBACK *DllGetClassObjectFunc)(REFCLSID clsid, REFIID iid, LPVOID *ppv);
422 typedef HRESULT (WINAPI *DllCanUnloadNowFunc)(void);
424 typedef struct tagOpenDll
426 LONG refs;
427 LPWSTR library_name;
428 HANDLE library;
429 DllGetClassObjectFunc DllGetClassObject;
430 DllCanUnloadNowFunc DllCanUnloadNow;
431 struct list entry;
432 } OpenDll;
434 static struct list openDllList = LIST_INIT(openDllList);
436 static CRITICAL_SECTION csOpenDllList;
437 static CRITICAL_SECTION_DEBUG dll_cs_debug =
439 0, 0, &csOpenDllList,
440 { &dll_cs_debug.ProcessLocksList, &dll_cs_debug.ProcessLocksList },
441 0, 0, { (DWORD_PTR)(__FILE__ ": csOpenDllList") }
443 static CRITICAL_SECTION csOpenDllList = { &dll_cs_debug, -1, 0, 0, 0, 0 };
445 struct apartment_loaded_dll
447 struct list entry;
448 OpenDll *dll;
449 DWORD unload_time;
450 BOOL multi_threaded;
453 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',' ',
454 '0','x','#','#','#','#','#','#','#','#',' ',0};
456 /*****************************************************************************
457 * This section contains OpenDllList implementation
460 static OpenDll *COMPOBJ_DllList_Get(LPCWSTR library_name)
462 OpenDll *ptr;
463 OpenDll *ret = NULL;
464 EnterCriticalSection(&csOpenDllList);
465 LIST_FOR_EACH_ENTRY(ptr, &openDllList, OpenDll, entry)
467 if (!strcmpiW(library_name, ptr->library_name) &&
468 (InterlockedIncrement(&ptr->refs) != 1) /* entry is being destroy if == 1 */)
470 ret = ptr;
471 break;
474 LeaveCriticalSection(&csOpenDllList);
475 return ret;
478 /* caller must ensure that library_name is not already in the open dll list */
479 static HRESULT COMPOBJ_DllList_Add(LPCWSTR library_name, OpenDll **ret)
481 OpenDll *entry;
482 int len;
483 HRESULT hr = S_OK;
484 HANDLE hLibrary;
485 DllCanUnloadNowFunc DllCanUnloadNow;
486 DllGetClassObjectFunc DllGetClassObject;
488 TRACE("%s\n", debugstr_w(library_name));
490 *ret = COMPOBJ_DllList_Get(library_name);
491 if (*ret) return S_OK;
493 /* do this outside the csOpenDllList to avoid creating a lock dependency on
494 * the loader lock */
495 hLibrary = LoadLibraryExW(library_name, 0, LOAD_WITH_ALTERED_SEARCH_PATH);
496 if (!hLibrary)
498 ERR("couldn't load in-process dll %s\n", debugstr_w(library_name));
499 /* failure: DLL could not be loaded */
500 return E_ACCESSDENIED; /* FIXME: or should this be CO_E_DLLNOTFOUND? */
503 DllCanUnloadNow = (void *)GetProcAddress(hLibrary, "DllCanUnloadNow");
504 /* Note: failing to find DllCanUnloadNow is not a failure */
505 DllGetClassObject = (void *)GetProcAddress(hLibrary, "DllGetClassObject");
506 if (!DllGetClassObject)
508 /* failure: the dll did not export DllGetClassObject */
509 ERR("couldn't find function DllGetClassObject in %s\n", debugstr_w(library_name));
510 FreeLibrary(hLibrary);
511 return CO_E_DLLNOTFOUND;
514 EnterCriticalSection( &csOpenDllList );
516 *ret = COMPOBJ_DllList_Get(library_name);
517 if (*ret)
519 /* another caller to this function already added the dll while we
520 * weren't in the critical section */
521 FreeLibrary(hLibrary);
523 else
525 len = strlenW(library_name);
526 entry = HeapAlloc(GetProcessHeap(),0, sizeof(OpenDll));
527 if (entry)
528 entry->library_name = HeapAlloc(GetProcessHeap(), 0, (len + 1)*sizeof(WCHAR));
529 if (entry && entry->library_name)
531 memcpy(entry->library_name, library_name, (len + 1)*sizeof(WCHAR));
532 entry->library = hLibrary;
533 entry->refs = 1;
534 entry->DllCanUnloadNow = DllCanUnloadNow;
535 entry->DllGetClassObject = DllGetClassObject;
536 list_add_tail(&openDllList, &entry->entry);
537 *ret = entry;
539 else
541 HeapFree(GetProcessHeap(), 0, entry);
542 hr = E_OUTOFMEMORY;
543 FreeLibrary(hLibrary);
547 LeaveCriticalSection( &csOpenDllList );
549 return hr;
552 /* pass FALSE for free_entry to release a reference without destroying the
553 * entry if it reaches zero or TRUE otherwise */
554 static void COMPOBJ_DllList_ReleaseRef(OpenDll *entry, BOOL free_entry)
556 if (!InterlockedDecrement(&entry->refs) && free_entry)
558 EnterCriticalSection(&csOpenDllList);
559 list_remove(&entry->entry);
560 LeaveCriticalSection(&csOpenDllList);
562 TRACE("freeing %p\n", entry->library);
563 FreeLibrary(entry->library);
565 HeapFree(GetProcessHeap(), 0, entry->library_name);
566 HeapFree(GetProcessHeap(), 0, entry);
570 /* frees memory associated with active dll list */
571 static void COMPOBJ_DllList_Free(void)
573 OpenDll *entry, *cursor2;
574 EnterCriticalSection(&csOpenDllList);
575 LIST_FOR_EACH_ENTRY_SAFE(entry, cursor2, &openDllList, OpenDll, entry)
577 list_remove(&entry->entry);
579 HeapFree(GetProcessHeap(), 0, entry->library_name);
580 HeapFree(GetProcessHeap(), 0, entry);
582 LeaveCriticalSection(&csOpenDllList);
583 DeleteCriticalSection(&csOpenDllList);
586 /******************************************************************************
587 * Manage apartments.
590 static DWORD apartment_addref(struct apartment *apt)
592 DWORD refs = InterlockedIncrement(&apt->refs);
593 TRACE("%s: before = %d\n", wine_dbgstr_longlong(apt->oxid), refs - 1);
594 return refs;
597 /* allocates memory and fills in the necessary fields for a new apartment
598 * object. must be called inside apartment cs */
599 static APARTMENT *apartment_construct(DWORD model)
601 APARTMENT *apt;
603 TRACE("creating new apartment, model=%d\n", model);
605 apt = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*apt));
606 apt->tid = GetCurrentThreadId();
608 list_init(&apt->proxies);
609 list_init(&apt->stubmgrs);
610 list_init(&apt->psclsids);
611 list_init(&apt->loaded_dlls);
612 apt->ipidc = 0;
613 apt->refs = 1;
614 apt->remunk_exported = FALSE;
615 apt->oidc = 1;
616 InitializeCriticalSection(&apt->cs);
617 DEBUG_SET_CRITSEC_NAME(&apt->cs, "apartment");
619 apt->multi_threaded = !(model & COINIT_APARTMENTTHREADED);
621 if (apt->multi_threaded)
623 /* FIXME: should be randomly generated by in an RPC call to rpcss */
624 apt->oxid = ((OXID)GetCurrentProcessId() << 32) | 0xcafe;
626 else
628 /* FIXME: should be randomly generated by in an RPC call to rpcss */
629 apt->oxid = ((OXID)GetCurrentProcessId() << 32) | GetCurrentThreadId();
632 TRACE("Created apartment on OXID %s\n", wine_dbgstr_longlong(apt->oxid));
634 list_add_head(&apts, &apt->entry);
636 return apt;
639 /* gets and existing apartment if one exists or otherwise creates an apartment
640 * structure which stores OLE apartment-local information and stores a pointer
641 * to it in the thread-local storage */
642 static APARTMENT *apartment_get_or_create(DWORD model)
644 APARTMENT *apt = COM_CurrentApt();
646 if (!apt)
648 if (model & COINIT_APARTMENTTHREADED)
650 EnterCriticalSection(&csApartment);
652 apt = apartment_construct(model);
653 if (!MainApartment)
655 MainApartment = apt;
656 apt->main = TRUE;
657 TRACE("Created main-threaded apartment with OXID %s\n", wine_dbgstr_longlong(apt->oxid));
660 LeaveCriticalSection(&csApartment);
662 if (apt->main)
663 apartment_createwindowifneeded(apt);
665 else
667 EnterCriticalSection(&csApartment);
669 /* The multi-threaded apartment (MTA) contains zero or more threads interacting
670 * with free threaded (ie thread safe) COM objects. There is only ever one MTA
671 * in a process */
672 if (MTA)
674 TRACE("entering the multithreaded apartment %s\n", wine_dbgstr_longlong(MTA->oxid));
675 apartment_addref(MTA);
677 else
678 MTA = apartment_construct(model);
680 apt = MTA;
682 LeaveCriticalSection(&csApartment);
684 COM_CurrentInfo()->apt = apt;
687 return apt;
690 static inline BOOL apartment_is_model(const APARTMENT *apt, DWORD model)
692 return (apt->multi_threaded == !(model & COINIT_APARTMENTTHREADED));
695 static void COM_RevokeRegisteredClassObject(RegisteredClass *curClass)
697 list_remove(&curClass->entry);
699 if (curClass->runContext & CLSCTX_LOCAL_SERVER)
700 RPC_StopLocalServer(curClass->RpcRegistration);
702 IUnknown_Release(curClass->classObject);
703 HeapFree(GetProcessHeap(), 0, curClass);
706 static void COM_RevokeAllClasses(const struct apartment *apt)
708 RegisteredClass *curClass, *cursor;
710 EnterCriticalSection( &csRegisteredClassList );
712 LIST_FOR_EACH_ENTRY_SAFE(curClass, cursor, &RegisteredClassList, RegisteredClass, entry)
714 if (curClass->apartment_id == apt->oxid)
715 COM_RevokeRegisteredClassObject(curClass);
718 LeaveCriticalSection( &csRegisteredClassList );
721 /******************************************************************************
722 * Implementation of the manual reset event object. (CLSID_ManualResetEvent)
725 typedef struct ManualResetEvent {
726 ISynchronize ISynchronize_iface;
727 ISynchronizeHandle ISynchronizeHandle_iface;
728 LONG ref;
729 HANDLE event;
730 } MREImpl;
732 static inline MREImpl *impl_from_ISynchronize(ISynchronize *iface)
734 return CONTAINING_RECORD(iface, MREImpl, ISynchronize_iface);
737 static HRESULT WINAPI ISynchronize_fnQueryInterface(ISynchronize *iface, REFIID riid, void **ppv)
739 MREImpl *This = impl_from_ISynchronize(iface);
741 TRACE("%p (%s, %p)\n", This, debugstr_guid(riid), ppv);
743 if(IsEqualGUID(riid, &IID_IUnknown) || IsEqualGUID(riid, &IID_ISynchronize)) {
744 *ppv = &This->ISynchronize_iface;
745 }else if(IsEqualGUID(riid, &IID_ISynchronizeHandle)) {
746 *ppv = &This->ISynchronizeHandle_iface;
747 }else {
748 ERR("Unknown interface %s requested.\n", debugstr_guid(riid));
749 *ppv = NULL;
750 return E_NOINTERFACE;
753 IUnknown_AddRef((IUnknown*)*ppv);
754 return S_OK;
757 static ULONG WINAPI ISynchronize_fnAddRef(ISynchronize *iface)
759 MREImpl *This = impl_from_ISynchronize(iface);
760 LONG ref = InterlockedIncrement(&This->ref);
761 TRACE("%p - ref %d\n", This, ref);
763 return ref;
766 static ULONG WINAPI ISynchronize_fnRelease(ISynchronize *iface)
768 MREImpl *This = impl_from_ISynchronize(iface);
769 LONG ref = InterlockedDecrement(&This->ref);
770 TRACE("%p - ref %d\n", This, ref);
772 if(!ref)
774 CloseHandle(This->event);
775 HeapFree(GetProcessHeap(), 0, This);
778 return ref;
781 static HRESULT WINAPI ISynchronize_fnWait(ISynchronize *iface, DWORD dwFlags, DWORD dwMilliseconds)
783 MREImpl *This = impl_from_ISynchronize(iface);
784 UINT index;
785 TRACE("%p (%08x, %08x)\n", This, dwFlags, dwMilliseconds);
786 return CoWaitForMultipleHandles(dwFlags, dwMilliseconds, 1, &This->event, &index);
789 static HRESULT WINAPI ISynchronize_fnSignal(ISynchronize *iface)
791 MREImpl *This = impl_from_ISynchronize(iface);
792 TRACE("%p\n", This);
793 SetEvent(This->event);
794 return S_OK;
797 static HRESULT WINAPI ISynchronize_fnReset(ISynchronize *iface)
799 MREImpl *This = impl_from_ISynchronize(iface);
800 TRACE("%p\n", This);
801 ResetEvent(This->event);
802 return S_OK;
805 static ISynchronizeVtbl vt_ISynchronize = {
806 ISynchronize_fnQueryInterface,
807 ISynchronize_fnAddRef,
808 ISynchronize_fnRelease,
809 ISynchronize_fnWait,
810 ISynchronize_fnSignal,
811 ISynchronize_fnReset
814 static inline MREImpl *impl_from_ISynchronizeHandle(ISynchronizeHandle *iface)
816 return CONTAINING_RECORD(iface, MREImpl, ISynchronizeHandle_iface);
819 static HRESULT WINAPI SynchronizeHandle_QueryInterface(ISynchronizeHandle *iface, REFIID riid, void **ppv)
821 MREImpl *This = impl_from_ISynchronizeHandle(iface);
822 return ISynchronize_QueryInterface(&This->ISynchronize_iface, riid, ppv);
825 static ULONG WINAPI SynchronizeHandle_AddRef(ISynchronizeHandle *iface)
827 MREImpl *This = impl_from_ISynchronizeHandle(iface);
828 return ISynchronize_AddRef(&This->ISynchronize_iface);
831 static ULONG WINAPI SynchronizeHandle_Release(ISynchronizeHandle *iface)
833 MREImpl *This = impl_from_ISynchronizeHandle(iface);
834 return ISynchronize_Release(&This->ISynchronize_iface);
837 static HRESULT WINAPI SynchronizeHandle_GetHandle(ISynchronizeHandle *iface, HANDLE *ph)
839 MREImpl *This = impl_from_ISynchronizeHandle(iface);
841 *ph = This->event;
842 return S_OK;
845 static const ISynchronizeHandleVtbl SynchronizeHandleVtbl = {
846 SynchronizeHandle_QueryInterface,
847 SynchronizeHandle_AddRef,
848 SynchronizeHandle_Release,
849 SynchronizeHandle_GetHandle
852 static HRESULT ManualResetEvent_Construct(IUnknown *punkouter, REFIID iid, void **ppv)
854 MREImpl *This = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(MREImpl));
855 HRESULT hr;
857 if(punkouter)
858 FIXME("Aggregation not implemented.\n");
860 This->ref = 1;
861 This->ISynchronize_iface.lpVtbl = &vt_ISynchronize;
862 This->ISynchronizeHandle_iface.lpVtbl = &SynchronizeHandleVtbl;
863 This->event = CreateEventW(NULL, TRUE, FALSE, NULL);
865 hr = ISynchronize_QueryInterface(&This->ISynchronize_iface, iid, ppv);
866 ISynchronize_Release(&This->ISynchronize_iface);
867 return hr;
870 static inline LocalServer *impl_from_IServiceProvider(IServiceProvider *iface)
872 return CONTAINING_RECORD(iface, LocalServer, IServiceProvider_iface);
875 static HRESULT WINAPI LocalServer_QueryInterface(IServiceProvider *iface, REFIID riid, void **ppv)
877 LocalServer *This = impl_from_IServiceProvider(iface);
879 TRACE("(%p)->(%s %p)\n", This, debugstr_guid(riid), ppv);
881 if(IsEqualGUID(riid, &IID_IUnknown) || IsEqualGUID(riid, &IID_IServiceProvider)) {
882 *ppv = &This->IServiceProvider_iface;
883 }else {
884 *ppv = NULL;
885 return E_NOINTERFACE;
888 IUnknown_AddRef((IUnknown*)*ppv);
889 return S_OK;
892 static ULONG WINAPI LocalServer_AddRef(IServiceProvider *iface)
894 LocalServer *This = impl_from_IServiceProvider(iface);
895 LONG ref = InterlockedIncrement(&This->ref);
897 TRACE("(%p) ref=%d\n", This, ref);
899 return ref;
902 static ULONG WINAPI LocalServer_Release(IServiceProvider *iface)
904 LocalServer *This = impl_from_IServiceProvider(iface);
905 LONG ref = InterlockedDecrement(&This->ref);
907 TRACE("(%p) ref=%d\n", This, ref);
909 if(!ref) {
910 assert(!This->apt);
911 HeapFree(GetProcessHeap(), 0, This);
914 return ref;
917 static HRESULT WINAPI LocalServer_QueryService(IServiceProvider *iface, REFGUID guid, REFIID riid, void **ppv)
919 LocalServer *This = impl_from_IServiceProvider(iface);
920 APARTMENT *apt = COM_CurrentApt();
921 RegisteredClass *iter;
922 HRESULT hres = E_FAIL;
924 TRACE("(%p)->(%s %s %p)\n", This, debugstr_guid(guid), debugstr_guid(riid), ppv);
926 if(!This->apt)
927 return E_UNEXPECTED;
929 EnterCriticalSection(&csRegisteredClassList);
931 LIST_FOR_EACH_ENTRY(iter, &RegisteredClassList, RegisteredClass, entry) {
932 if(iter->apartment_id == apt->oxid
933 && (iter->runContext & CLSCTX_LOCAL_SERVER)
934 && IsEqualGUID(&iter->classIdentifier, guid)) {
935 hres = IUnknown_QueryInterface(iter->classObject, riid, ppv);
936 break;
940 LeaveCriticalSection( &csRegisteredClassList );
942 return hres;
945 static const IServiceProviderVtbl LocalServerVtbl = {
946 LocalServer_QueryInterface,
947 LocalServer_AddRef,
948 LocalServer_Release,
949 LocalServer_QueryService
952 static HRESULT get_local_server_stream(APARTMENT *apt, IStream **ret)
954 HRESULT hres = S_OK;
956 EnterCriticalSection(&apt->cs);
958 if(!apt->local_server) {
959 LocalServer *obj;
961 obj = heap_alloc(sizeof(*obj));
962 if(obj) {
963 obj->IServiceProvider_iface.lpVtbl = &LocalServerVtbl;
964 obj->ref = 1;
965 obj->apt = apt;
967 hres = CreateStreamOnHGlobal(0, TRUE, &obj->marshal_stream);
968 if(SUCCEEDED(hres)) {
969 hres = CoMarshalInterface(obj->marshal_stream, &IID_IServiceProvider, (IUnknown*)&obj->IServiceProvider_iface,
970 MSHCTX_LOCAL, NULL, MSHLFLAGS_TABLESTRONG);
971 if(FAILED(hres))
972 IStream_Release(obj->marshal_stream);
975 if(SUCCEEDED(hres))
976 apt->local_server = obj;
977 else
978 heap_free(obj);
979 }else {
980 hres = E_OUTOFMEMORY;
984 if(SUCCEEDED(hres))
985 hres = IStream_Clone(apt->local_server->marshal_stream, ret);
987 LeaveCriticalSection(&apt->cs);
989 if(FAILED(hres))
990 ERR("Failed: %08x\n", hres);
991 return hres;
994 /***********************************************************************
995 * CoRevokeClassObject [OLE32.@]
997 * Removes a class object from the class registry.
999 * PARAMS
1000 * dwRegister [I] Cookie returned from CoRegisterClassObject().
1002 * RETURNS
1003 * Success: S_OK.
1004 * Failure: HRESULT code.
1006 * NOTES
1007 * Must be called from the same apartment that called CoRegisterClassObject(),
1008 * otherwise it will fail with RPC_E_WRONG_THREAD.
1010 * SEE ALSO
1011 * CoRegisterClassObject
1013 HRESULT WINAPI CoRevokeClassObject(
1014 DWORD dwRegister)
1016 HRESULT hr = E_INVALIDARG;
1017 RegisteredClass *curClass;
1018 APARTMENT *apt;
1020 TRACE("(%08x)\n",dwRegister);
1022 apt = COM_CurrentApt();
1023 if (!apt)
1025 ERR("COM was not initialized\n");
1026 return CO_E_NOTINITIALIZED;
1029 EnterCriticalSection( &csRegisteredClassList );
1031 LIST_FOR_EACH_ENTRY(curClass, &RegisteredClassList, RegisteredClass, entry)
1034 * Check if we have a match on the cookie.
1036 if (curClass->dwCookie == dwRegister)
1038 if (curClass->apartment_id == apt->oxid)
1040 COM_RevokeRegisteredClassObject(curClass);
1041 hr = S_OK;
1043 else
1045 ERR("called from wrong apartment, should be called from %s\n",
1046 wine_dbgstr_longlong(curClass->apartment_id));
1047 hr = RPC_E_WRONG_THREAD;
1049 break;
1053 LeaveCriticalSection( &csRegisteredClassList );
1055 return hr;
1058 /* frees unused libraries loaded by apartment_getclassobject by calling the
1059 * DLL's DllCanUnloadNow entry point */
1060 static void apartment_freeunusedlibraries(struct apartment *apt, DWORD delay)
1062 struct apartment_loaded_dll *entry, *next;
1063 EnterCriticalSection(&apt->cs);
1064 LIST_FOR_EACH_ENTRY_SAFE(entry, next, &apt->loaded_dlls, struct apartment_loaded_dll, entry)
1066 if (entry->dll->DllCanUnloadNow && (entry->dll->DllCanUnloadNow() == S_OK))
1068 DWORD real_delay = delay;
1070 if (real_delay == INFINITE)
1072 /* DLLs that return multi-threaded objects aren't unloaded
1073 * straight away to cope for programs that have races between
1074 * last object destruction and threads in the DLLs that haven't
1075 * finished, despite DllCanUnloadNow returning S_OK */
1076 if (entry->multi_threaded)
1077 real_delay = 10 * 60 * 1000; /* 10 minutes */
1078 else
1079 real_delay = 0;
1082 if (!real_delay || (entry->unload_time && ((int)(GetTickCount() - entry->unload_time) > 0)))
1084 list_remove(&entry->entry);
1085 COMPOBJ_DllList_ReleaseRef(entry->dll, TRUE);
1086 HeapFree(GetProcessHeap(), 0, entry);
1088 else
1090 entry->unload_time = GetTickCount() + real_delay;
1091 if (!entry->unload_time) entry->unload_time = 1;
1094 else if (entry->unload_time)
1095 entry->unload_time = 0;
1097 LeaveCriticalSection(&apt->cs);
1100 DWORD apartment_release(struct apartment *apt)
1102 DWORD ret;
1104 EnterCriticalSection(&csApartment);
1106 ret = InterlockedDecrement(&apt->refs);
1107 TRACE("%s: after = %d\n", wine_dbgstr_longlong(apt->oxid), ret);
1108 /* destruction stuff that needs to happen under csApartment CS */
1109 if (ret == 0)
1111 if (apt == MTA) MTA = NULL;
1112 else if (apt == MainApartment) MainApartment = NULL;
1113 list_remove(&apt->entry);
1116 LeaveCriticalSection(&csApartment);
1118 if (ret == 0)
1120 struct list *cursor, *cursor2;
1122 TRACE("destroying apartment %p, oxid %s\n", apt, wine_dbgstr_longlong(apt->oxid));
1124 if(apt->local_server) {
1125 LocalServer *local_server = apt->local_server;
1126 LARGE_INTEGER zero;
1128 memset(&zero, 0, sizeof(zero));
1129 IStream_Seek(local_server->marshal_stream, zero, STREAM_SEEK_SET, NULL);
1130 CoReleaseMarshalData(local_server->marshal_stream);
1131 IStream_Release(local_server->marshal_stream);
1132 local_server->marshal_stream = NULL;
1134 apt->local_server = NULL;
1135 local_server->apt = NULL;
1136 IServiceProvider_Release(&local_server->IServiceProvider_iface);
1139 /* Release the references to the registered class objects */
1140 COM_RevokeAllClasses(apt);
1142 /* no locking is needed for this apartment, because no other thread
1143 * can access it at this point */
1145 apartment_disconnectproxies(apt);
1147 if (apt->win) DestroyWindow(apt->win);
1148 if (apt->host_apt_tid) PostThreadMessageW(apt->host_apt_tid, WM_QUIT, 0, 0);
1150 LIST_FOR_EACH_SAFE(cursor, cursor2, &apt->stubmgrs)
1152 struct stub_manager *stubmgr = LIST_ENTRY(cursor, struct stub_manager, entry);
1153 /* release the implicit reference given by the fact that the
1154 * stub has external references (it must do since it is in the
1155 * stub manager list in the apartment and all non-apartment users
1156 * must have a ref on the apartment and so it cannot be destroyed).
1158 stub_manager_int_release(stubmgr);
1161 LIST_FOR_EACH_SAFE(cursor, cursor2, &apt->psclsids)
1163 struct registered_psclsid *registered_psclsid =
1164 LIST_ENTRY(cursor, struct registered_psclsid, entry);
1166 list_remove(&registered_psclsid->entry);
1167 HeapFree(GetProcessHeap(), 0, registered_psclsid);
1170 /* if this assert fires, then another thread took a reference to a
1171 * stub manager without taking a reference to the containing
1172 * apartment, which it must do. */
1173 assert(list_empty(&apt->stubmgrs));
1175 if (apt->filter) IMessageFilter_Release(apt->filter);
1177 /* free as many unused libraries as possible... */
1178 apartment_freeunusedlibraries(apt, 0);
1180 /* ... and free the memory for the apartment loaded dll entry and
1181 * release the dll list reference without freeing the library for the
1182 * rest */
1183 while ((cursor = list_head(&apt->loaded_dlls)))
1185 struct apartment_loaded_dll *apartment_loaded_dll = LIST_ENTRY(cursor, struct apartment_loaded_dll, entry);
1186 COMPOBJ_DllList_ReleaseRef(apartment_loaded_dll->dll, FALSE);
1187 list_remove(cursor);
1188 HeapFree(GetProcessHeap(), 0, apartment_loaded_dll);
1191 DEBUG_CLEAR_CRITSEC_NAME(&apt->cs);
1192 DeleteCriticalSection(&apt->cs);
1194 HeapFree(GetProcessHeap(), 0, apt);
1197 return ret;
1200 /* The given OXID must be local to this process:
1202 * The ref parameter is here mostly to ensure people remember that
1203 * they get one, you should normally take a ref for thread safety.
1205 APARTMENT *apartment_findfromoxid(OXID oxid, BOOL ref)
1207 APARTMENT *result = NULL;
1208 struct list *cursor;
1210 EnterCriticalSection(&csApartment);
1211 LIST_FOR_EACH( cursor, &apts )
1213 struct apartment *apt = LIST_ENTRY( cursor, struct apartment, entry );
1214 if (apt->oxid == oxid)
1216 result = apt;
1217 if (ref) apartment_addref(result);
1218 break;
1221 LeaveCriticalSection(&csApartment);
1223 return result;
1226 /* gets the apartment which has a given creator thread ID. The caller must
1227 * release the reference from the apartment as soon as the apartment pointer
1228 * is no longer required. */
1229 APARTMENT *apartment_findfromtid(DWORD tid)
1231 APARTMENT *result = NULL;
1232 struct list *cursor;
1234 EnterCriticalSection(&csApartment);
1235 LIST_FOR_EACH( cursor, &apts )
1237 struct apartment *apt = LIST_ENTRY( cursor, struct apartment, entry );
1238 if (apt->tid == tid)
1240 result = apt;
1241 apartment_addref(result);
1242 break;
1245 LeaveCriticalSection(&csApartment);
1247 return result;
1250 /* gets the main apartment if it exists. The caller must
1251 * release the reference from the apartment as soon as the apartment pointer
1252 * is no longer required. */
1253 static APARTMENT *apartment_findmain(void)
1255 APARTMENT *result;
1257 EnterCriticalSection(&csApartment);
1259 result = MainApartment;
1260 if (result) apartment_addref(result);
1262 LeaveCriticalSection(&csApartment);
1264 return result;
1267 /* gets the multi-threaded apartment if it exists. The caller must
1268 * release the reference from the apartment as soon as the apartment pointer
1269 * is no longer required. */
1270 static APARTMENT *apartment_find_multi_threaded(void)
1272 APARTMENT *result = NULL;
1273 struct list *cursor;
1275 EnterCriticalSection(&csApartment);
1277 LIST_FOR_EACH( cursor, &apts )
1279 struct apartment *apt = LIST_ENTRY( cursor, struct apartment, entry );
1280 if (apt->multi_threaded)
1282 result = apt;
1283 apartment_addref(result);
1284 break;
1288 LeaveCriticalSection(&csApartment);
1289 return result;
1292 /* gets the specified class object by loading the appropriate DLL, if
1293 * necessary and calls the DllGetClassObject function for the DLL */
1294 static HRESULT apartment_getclassobject(struct apartment *apt, LPCWSTR dllpath,
1295 BOOL apartment_threaded,
1296 REFCLSID rclsid, REFIID riid, void **ppv)
1298 static const WCHAR wszOle32[] = {'o','l','e','3','2','.','d','l','l',0};
1299 HRESULT hr = S_OK;
1300 BOOL found = FALSE;
1301 struct apartment_loaded_dll *apartment_loaded_dll;
1303 if (!strcmpiW(dllpath, wszOle32))
1305 /* we don't need to control the lifetime of this dll, so use the local
1306 * implementation of DllGetClassObject directly */
1307 TRACE("calling ole32!DllGetClassObject\n");
1308 hr = DllGetClassObject(rclsid, riid, ppv);
1310 if (hr != S_OK)
1311 ERR("DllGetClassObject returned error 0x%08x\n", hr);
1313 return hr;
1316 EnterCriticalSection(&apt->cs);
1318 LIST_FOR_EACH_ENTRY(apartment_loaded_dll, &apt->loaded_dlls, struct apartment_loaded_dll, entry)
1319 if (!strcmpiW(dllpath, apartment_loaded_dll->dll->library_name))
1321 TRACE("found %s already loaded\n", debugstr_w(dllpath));
1322 found = TRUE;
1323 break;
1326 if (!found)
1328 apartment_loaded_dll = HeapAlloc(GetProcessHeap(), 0, sizeof(*apartment_loaded_dll));
1329 if (!apartment_loaded_dll)
1330 hr = E_OUTOFMEMORY;
1331 if (SUCCEEDED(hr))
1333 apartment_loaded_dll->unload_time = 0;
1334 apartment_loaded_dll->multi_threaded = FALSE;
1335 hr = COMPOBJ_DllList_Add( dllpath, &apartment_loaded_dll->dll );
1336 if (FAILED(hr))
1337 HeapFree(GetProcessHeap(), 0, apartment_loaded_dll);
1339 if (SUCCEEDED(hr))
1341 TRACE("added new loaded dll %s\n", debugstr_w(dllpath));
1342 list_add_tail(&apt->loaded_dlls, &apartment_loaded_dll->entry);
1346 LeaveCriticalSection(&apt->cs);
1348 if (SUCCEEDED(hr))
1350 /* one component being multi-threaded overrides any number of
1351 * apartment-threaded components */
1352 if (!apartment_threaded)
1353 apartment_loaded_dll->multi_threaded = TRUE;
1355 TRACE("calling DllGetClassObject %p\n", apartment_loaded_dll->dll->DllGetClassObject);
1356 /* OK: get the ClassObject */
1357 hr = apartment_loaded_dll->dll->DllGetClassObject(rclsid, riid, ppv);
1359 if (hr != S_OK)
1360 ERR("DllGetClassObject returned error 0x%08x\n", hr);
1363 return hr;
1366 /***********************************************************************
1367 * COM_RegReadPath [internal]
1369 * Reads a registry value and expands it when necessary
1371 static DWORD COM_RegReadPath(const struct class_reg_data *regdata, WCHAR *dst, DWORD dstlen)
1373 DWORD ret;
1375 if (regdata->hkey)
1377 DWORD keytype;
1378 WCHAR src[MAX_PATH];
1379 DWORD dwLength = dstlen * sizeof(WCHAR);
1381 if( (ret = RegQueryValueExW(regdata->u.hkey, NULL, NULL, &keytype, (BYTE*)src, &dwLength)) == ERROR_SUCCESS ) {
1382 if (keytype == REG_EXPAND_SZ) {
1383 if (dstlen <= ExpandEnvironmentStringsW(src, dst, dstlen)) ret = ERROR_MORE_DATA;
1384 } else {
1385 const WCHAR *quote_start;
1386 quote_start = strchrW(src, '\"');
1387 if (quote_start) {
1388 const WCHAR *quote_end = strchrW(quote_start + 1, '\"');
1389 if (quote_end) {
1390 memmove(src, quote_start + 1,
1391 (quote_end - quote_start - 1) * sizeof(WCHAR));
1392 src[quote_end - quote_start - 1] = '\0';
1395 lstrcpynW(dst, src, dstlen);
1398 return ret;
1400 else
1402 ULONG_PTR cookie;
1403 WCHAR *nameW;
1405 *dst = 0;
1406 nameW = (WCHAR*)((BYTE*)regdata->u.actctx.section + regdata->u.actctx.data->name_offset);
1407 ActivateActCtx(regdata->u.actctx.hactctx, &cookie);
1408 ret = SearchPathW(NULL, nameW, NULL, dstlen, dst, NULL);
1409 DeactivateActCtx(0, cookie);
1410 return !*dst;
1414 struct host_object_params
1416 struct class_reg_data regdata;
1417 CLSID clsid; /* clsid of object to marshal */
1418 IID iid; /* interface to marshal */
1419 HANDLE event; /* event signalling when ready for multi-threaded case */
1420 HRESULT hr; /* result for multi-threaded case */
1421 IStream *stream; /* stream that the object will be marshaled into */
1422 BOOL apartment_threaded; /* is the component purely apartment-threaded? */
1425 static HRESULT apartment_hostobject(struct apartment *apt,
1426 const struct host_object_params *params)
1428 IUnknown *object;
1429 HRESULT hr;
1430 static const LARGE_INTEGER llZero;
1431 WCHAR dllpath[MAX_PATH+1];
1433 TRACE("clsid %s, iid %s\n", debugstr_guid(&params->clsid), debugstr_guid(&params->iid));
1435 if (COM_RegReadPath(&params->regdata, dllpath, ARRAYSIZE(dllpath)) != ERROR_SUCCESS)
1437 /* failure: CLSID is not found in registry */
1438 WARN("class %s not registered inproc\n", debugstr_guid(&params->clsid));
1439 return REGDB_E_CLASSNOTREG;
1442 hr = apartment_getclassobject(apt, dllpath, params->apartment_threaded,
1443 &params->clsid, &params->iid, (void **)&object);
1444 if (FAILED(hr))
1445 return hr;
1447 hr = CoMarshalInterface(params->stream, &params->iid, object, MSHCTX_INPROC, NULL, MSHLFLAGS_NORMAL);
1448 if (FAILED(hr))
1449 IUnknown_Release(object);
1450 IStream_Seek(params->stream, llZero, STREAM_SEEK_SET, NULL);
1452 return hr;
1455 static LRESULT CALLBACK apartment_wndproc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
1457 switch (msg)
1459 case DM_EXECUTERPC:
1460 RPC_ExecuteCall((struct dispatch_params *)lParam);
1461 return 0;
1462 case DM_HOSTOBJECT:
1463 return apartment_hostobject(COM_CurrentApt(), (const struct host_object_params *)lParam);
1464 default:
1465 return DefWindowProcW(hWnd, msg, wParam, lParam);
1469 struct host_thread_params
1471 COINIT threading_model;
1472 HANDLE ready_event;
1473 HWND apartment_hwnd;
1476 /* thread for hosting an object to allow an object to appear to be created in
1477 * an apartment with an incompatible threading model */
1478 static DWORD CALLBACK apartment_hostobject_thread(LPVOID p)
1480 struct host_thread_params *params = p;
1481 MSG msg;
1482 HRESULT hr;
1483 struct apartment *apt;
1485 TRACE("\n");
1487 hr = CoInitializeEx(NULL, params->threading_model);
1488 if (FAILED(hr)) return hr;
1490 apt = COM_CurrentApt();
1491 if (params->threading_model == COINIT_APARTMENTTHREADED)
1493 apartment_createwindowifneeded(apt);
1494 params->apartment_hwnd = apartment_getwindow(apt);
1496 else
1497 params->apartment_hwnd = NULL;
1499 /* force the message queue to be created before signaling parent thread */
1500 PeekMessageW(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
1502 SetEvent(params->ready_event);
1503 params = NULL; /* can't touch params after here as it may be invalid */
1505 while (GetMessageW(&msg, NULL, 0, 0))
1507 if (!msg.hwnd && (msg.message == DM_HOSTOBJECT))
1509 struct host_object_params *obj_params = (struct host_object_params *)msg.lParam;
1510 obj_params->hr = apartment_hostobject(apt, obj_params);
1511 SetEvent(obj_params->event);
1513 else
1515 TranslateMessage(&msg);
1516 DispatchMessageW(&msg);
1520 TRACE("exiting\n");
1522 CoUninitialize();
1524 return S_OK;
1527 /* finds or creates a host apartment, creates the object inside it and returns
1528 * a proxy to it so that the object can be used in the apartment of the
1529 * caller of this function */
1530 static HRESULT apartment_hostobject_in_hostapt(
1531 struct apartment *apt, BOOL multi_threaded, BOOL main_apartment,
1532 const struct class_reg_data *regdata, REFCLSID rclsid, REFIID riid, void **ppv)
1534 struct host_object_params params;
1535 HWND apartment_hwnd = NULL;
1536 DWORD apartment_tid = 0;
1537 HRESULT hr;
1539 if (!multi_threaded && main_apartment)
1541 APARTMENT *host_apt = apartment_findmain();
1542 if (host_apt)
1544 apartment_hwnd = apartment_getwindow(host_apt);
1545 apartment_release(host_apt);
1549 if (!apartment_hwnd)
1551 EnterCriticalSection(&apt->cs);
1553 if (!apt->host_apt_tid)
1555 struct host_thread_params thread_params;
1556 HANDLE handles[2];
1557 DWORD wait_value;
1559 thread_params.threading_model = multi_threaded ? COINIT_MULTITHREADED : COINIT_APARTMENTTHREADED;
1560 handles[0] = thread_params.ready_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1561 thread_params.apartment_hwnd = NULL;
1562 handles[1] = CreateThread(NULL, 0, apartment_hostobject_thread, &thread_params, 0, &apt->host_apt_tid);
1563 if (!handles[1])
1565 CloseHandle(handles[0]);
1566 LeaveCriticalSection(&apt->cs);
1567 return E_OUTOFMEMORY;
1569 wait_value = WaitForMultipleObjects(2, handles, FALSE, INFINITE);
1570 CloseHandle(handles[0]);
1571 CloseHandle(handles[1]);
1572 if (wait_value == WAIT_OBJECT_0)
1573 apt->host_apt_hwnd = thread_params.apartment_hwnd;
1574 else
1576 LeaveCriticalSection(&apt->cs);
1577 return E_OUTOFMEMORY;
1581 if (multi_threaded || !main_apartment)
1583 apartment_hwnd = apt->host_apt_hwnd;
1584 apartment_tid = apt->host_apt_tid;
1587 LeaveCriticalSection(&apt->cs);
1590 /* another thread may have become the main apartment in the time it took
1591 * us to create the thread for the host apartment */
1592 if (!apartment_hwnd && !multi_threaded && main_apartment)
1594 APARTMENT *host_apt = apartment_findmain();
1595 if (host_apt)
1597 apartment_hwnd = apartment_getwindow(host_apt);
1598 apartment_release(host_apt);
1602 params.regdata = *regdata;
1603 params.clsid = *rclsid;
1604 params.iid = *riid;
1605 hr = CreateStreamOnHGlobal(NULL, TRUE, &params.stream);
1606 if (FAILED(hr))
1607 return hr;
1608 params.apartment_threaded = !multi_threaded;
1609 if (multi_threaded)
1611 params.hr = S_OK;
1612 params.event = CreateEventW(NULL, FALSE, FALSE, NULL);
1613 if (!PostThreadMessageW(apartment_tid, DM_HOSTOBJECT, 0, (LPARAM)&params))
1614 hr = E_OUTOFMEMORY;
1615 else
1617 WaitForSingleObject(params.event, INFINITE);
1618 hr = params.hr;
1620 CloseHandle(params.event);
1622 else
1624 if (!apartment_hwnd)
1626 ERR("host apartment didn't create window\n");
1627 hr = E_OUTOFMEMORY;
1629 else
1630 hr = SendMessageW(apartment_hwnd, DM_HOSTOBJECT, 0, (LPARAM)&params);
1632 if (SUCCEEDED(hr))
1633 hr = CoUnmarshalInterface(params.stream, riid, ppv);
1634 IStream_Release(params.stream);
1635 return hr;
1638 static BOOL WINAPI register_class( INIT_ONCE *once, void *param, void **context )
1640 WNDCLASSW wclass;
1642 /* Dispatching to the correct thread in an apartment is done through
1643 * window messages rather than RPC transports. When an interface is
1644 * marshalled into another apartment in the same process, a window of the
1645 * following class is created. The *caller* of CoMarshalInterface (i.e., the
1646 * application) is responsible for pumping the message loop in that thread.
1647 * The WM_USER messages which point to the RPCs are then dispatched to
1648 * apartment_wndproc by the user's code from the apartment in which the
1649 * interface was unmarshalled.
1651 memset(&wclass, 0, sizeof(wclass));
1652 wclass.lpfnWndProc = apartment_wndproc;
1653 wclass.hInstance = hProxyDll;
1654 wclass.lpszClassName = wszAptWinClass;
1655 RegisterClassW(&wclass);
1656 return TRUE;
1659 /* create a window for the apartment or return the current one if one has
1660 * already been created */
1661 HRESULT apartment_createwindowifneeded(struct apartment *apt)
1663 static INIT_ONCE class_init_once = INIT_ONCE_STATIC_INIT;
1665 if (apt->multi_threaded)
1666 return S_OK;
1668 if (!apt->win)
1670 HWND hwnd;
1672 InitOnceExecuteOnce( &class_init_once, register_class, NULL, NULL );
1674 hwnd = CreateWindowW(wszAptWinClass, NULL, 0, 0, 0, 0, 0,
1675 HWND_MESSAGE, 0, hProxyDll, NULL);
1676 if (!hwnd)
1678 ERR("CreateWindow failed with error %d\n", GetLastError());
1679 return HRESULT_FROM_WIN32(GetLastError());
1681 if (InterlockedCompareExchangePointer((PVOID *)&apt->win, hwnd, NULL))
1682 /* someone beat us to it */
1683 DestroyWindow(hwnd);
1686 return S_OK;
1689 /* retrieves the window for the main- or apartment-threaded apartment */
1690 HWND apartment_getwindow(const struct apartment *apt)
1692 assert(!apt->multi_threaded);
1693 return apt->win;
1696 void apartment_joinmta(void)
1698 apartment_addref(MTA);
1699 COM_CurrentInfo()->apt = MTA;
1702 static void COM_TlsDestroy(void)
1704 struct oletls *info = NtCurrentTeb()->ReservedForOle;
1705 if (info)
1707 if (info->apt) apartment_release(info->apt);
1708 if (info->errorinfo) IErrorInfo_Release(info->errorinfo);
1709 if (info->state) IUnknown_Release(info->state);
1710 if (info->spy) IInitializeSpy_Release(info->spy);
1711 if (info->context_token) IObjContext_Release(info->context_token);
1712 HeapFree(GetProcessHeap(), 0, info);
1713 NtCurrentTeb()->ReservedForOle = NULL;
1717 /******************************************************************************
1718 * CoBuildVersion [OLE32.@]
1720 * Gets the build version of the DLL.
1722 * PARAMS
1724 * RETURNS
1725 * Current build version, hiword is majornumber, loword is minornumber
1727 DWORD WINAPI CoBuildVersion(void)
1729 TRACE("Returning version %d, build %d.\n", rmm, rup);
1730 return (rmm<<16)+rup;
1733 /******************************************************************************
1734 * CoRegisterInitializeSpy [OLE32.@]
1736 * Add a Spy that watches CoInitializeEx calls
1738 * PARAMS
1739 * spy [I] Pointer to IUnknown interface that will be QueryInterface'd.
1740 * cookie [II] cookie receiver
1742 * RETURNS
1743 * Success: S_OK if not already initialized, S_FALSE otherwise.
1744 * Failure: HRESULT code.
1746 * SEE ALSO
1747 * CoInitializeEx
1749 HRESULT WINAPI CoRegisterInitializeSpy(IInitializeSpy *spy, ULARGE_INTEGER *cookie)
1751 struct oletls *info = COM_CurrentInfo();
1752 HRESULT hr;
1754 TRACE("(%p, %p)\n", spy, cookie);
1756 if (!spy || !cookie || !info)
1758 if (!info)
1759 WARN("Could not allocate tls\n");
1760 return E_INVALIDARG;
1763 if (info->spy)
1765 FIXME("Already registered?\n");
1766 return E_UNEXPECTED;
1769 hr = IInitializeSpy_QueryInterface(spy, &IID_IInitializeSpy, (void **) &info->spy);
1770 if (SUCCEEDED(hr))
1772 cookie->QuadPart = (DWORD_PTR)spy;
1773 return S_OK;
1775 return hr;
1778 /******************************************************************************
1779 * CoRevokeInitializeSpy [OLE32.@]
1781 * Remove a spy that previously watched CoInitializeEx calls
1783 * PARAMS
1784 * cookie [I] The cookie obtained from a previous CoRegisterInitializeSpy call
1786 * RETURNS
1787 * Success: S_OK if a spy is removed
1788 * Failure: E_INVALIDARG
1790 * SEE ALSO
1791 * CoInitializeEx
1793 HRESULT WINAPI CoRevokeInitializeSpy(ULARGE_INTEGER cookie)
1795 struct oletls *info = COM_CurrentInfo();
1796 TRACE("(%s)\n", wine_dbgstr_longlong(cookie.QuadPart));
1798 if (!info || !info->spy || cookie.QuadPart != (DWORD_PTR)info->spy)
1799 return E_INVALIDARG;
1801 IInitializeSpy_Release(info->spy);
1802 info->spy = NULL;
1803 return S_OK;
1807 /******************************************************************************
1808 * CoInitialize [OLE32.@]
1810 * Initializes the COM libraries by calling CoInitializeEx with
1811 * COINIT_APARTMENTTHREADED, ie it enters a STA thread.
1813 * PARAMS
1814 * lpReserved [I] Pointer to IMalloc interface (obsolete, should be NULL).
1816 * RETURNS
1817 * Success: S_OK if not already initialized, S_FALSE otherwise.
1818 * Failure: HRESULT code.
1820 * SEE ALSO
1821 * CoInitializeEx
1823 HRESULT WINAPI CoInitialize(LPVOID lpReserved)
1826 * Just delegate to the newer method.
1828 return CoInitializeEx(lpReserved, COINIT_APARTMENTTHREADED);
1831 /******************************************************************************
1832 * CoInitializeEx [OLE32.@]
1834 * Initializes the COM libraries.
1836 * PARAMS
1837 * lpReserved [I] Pointer to IMalloc interface (obsolete, should be NULL).
1838 * dwCoInit [I] One or more flags from the COINIT enumeration. See notes.
1840 * RETURNS
1841 * S_OK if successful,
1842 * S_FALSE if this function was called already.
1843 * RPC_E_CHANGED_MODE if a previous call to CoInitializeEx specified another
1844 * threading model.
1846 * NOTES
1848 * The behavior used to set the IMalloc used for memory management is
1849 * obsolete.
1850 * The dwCoInit parameter must specify one of the following apartment
1851 * threading models:
1852 *| COINIT_APARTMENTTHREADED - A single-threaded apartment (STA).
1853 *| COINIT_MULTITHREADED - A multi-threaded apartment (MTA).
1854 * The parameter may also specify zero or more of the following flags:
1855 *| COINIT_DISABLE_OLE1DDE - Don't use DDE for OLE1 support.
1856 *| COINIT_SPEED_OVER_MEMORY - Trade memory for speed.
1858 * SEE ALSO
1859 * CoUninitialize
1861 HRESULT WINAPI CoInitializeEx(LPVOID lpReserved, DWORD dwCoInit)
1863 struct oletls *info = COM_CurrentInfo();
1864 HRESULT hr = S_OK;
1865 APARTMENT *apt;
1867 TRACE("(%p, %x)\n", lpReserved, (int)dwCoInit);
1869 if (lpReserved!=NULL)
1871 ERR("(%p, %x) - Bad parameter passed-in %p, must be an old Windows Application\n", lpReserved, (int)dwCoInit, lpReserved);
1875 * Check the lock count. If this is the first time going through the initialize
1876 * process, we have to initialize the libraries.
1878 * And crank-up that lock count.
1880 if (InterlockedExchangeAdd(&s_COMLockCount,1)==0)
1883 * Initialize the various COM libraries and data structures.
1885 TRACE("() - Initializing the COM libraries\n");
1887 /* we may need to defer this until after apartment initialisation */
1888 RunningObjectTableImpl_Initialize();
1891 if (info->spy)
1892 IInitializeSpy_PreInitialize(info->spy, dwCoInit, info->inits);
1894 if (!(apt = info->apt))
1896 apt = apartment_get_or_create(dwCoInit);
1897 if (!apt) return E_OUTOFMEMORY;
1899 else if (!apartment_is_model(apt, dwCoInit))
1901 /* Changing the threading model after it's been set is illegal. If this warning is triggered by Wine
1902 code then we are probably using the wrong threading model to implement that API. */
1903 ERR("Attempt to change threading model of this apartment from %s to %s\n",
1904 apt->multi_threaded ? "multi-threaded" : "apartment threaded",
1905 dwCoInit & COINIT_APARTMENTTHREADED ? "apartment threaded" : "multi-threaded");
1906 return RPC_E_CHANGED_MODE;
1908 else
1909 hr = S_FALSE;
1911 info->inits++;
1913 if (info->spy)
1914 IInitializeSpy_PostInitialize(info->spy, hr, dwCoInit, info->inits);
1916 return hr;
1919 /***********************************************************************
1920 * CoUninitialize [OLE32.@]
1922 * This method will decrement the refcount on the current apartment, freeing
1923 * the resources associated with it if it is the last thread in the apartment.
1924 * If the last apartment is freed, the function will additionally release
1925 * any COM resources associated with the process.
1927 * PARAMS
1929 * RETURNS
1930 * Nothing.
1932 * SEE ALSO
1933 * CoInitializeEx
1935 void WINAPI CoUninitialize(void)
1937 struct oletls * info = COM_CurrentInfo();
1938 LONG lCOMRefCnt;
1940 TRACE("()\n");
1942 /* will only happen on OOM */
1943 if (!info) return;
1945 if (info->spy)
1946 IInitializeSpy_PreUninitialize(info->spy, info->inits);
1948 /* sanity check */
1949 if (!info->inits)
1951 ERR("Mismatched CoUninitialize\n");
1953 if (info->spy)
1954 IInitializeSpy_PostUninitialize(info->spy, info->inits);
1955 return;
1958 if (!--info->inits)
1960 apartment_release(info->apt);
1961 info->apt = NULL;
1965 * Decrease the reference count.
1966 * If we are back to 0 locks on the COM library, make sure we free
1967 * all the associated data structures.
1969 lCOMRefCnt = InterlockedExchangeAdd(&s_COMLockCount,-1);
1970 if (lCOMRefCnt==1)
1972 TRACE("() - Releasing the COM libraries\n");
1974 RunningObjectTableImpl_UnInitialize();
1976 else if (lCOMRefCnt<1) {
1977 ERR( "CoUninitialize() - not CoInitialized.\n" );
1978 InterlockedExchangeAdd(&s_COMLockCount,1); /* restore the lock count. */
1980 if (info->spy)
1981 IInitializeSpy_PostUninitialize(info->spy, info->inits);
1984 /******************************************************************************
1985 * CoDisconnectObject [OLE32.@]
1987 * Disconnects all connections to this object from remote processes. Dispatches
1988 * pending RPCs while blocking new RPCs from occurring, and then calls
1989 * IMarshal::DisconnectObject on the given object.
1991 * Typically called when the object server is forced to shut down, for instance by
1992 * the user.
1994 * PARAMS
1995 * lpUnk [I] The object whose stub should be disconnected.
1996 * reserved [I] Reserved. Should be set to 0.
1998 * RETURNS
1999 * Success: S_OK.
2000 * Failure: HRESULT code.
2002 * SEE ALSO
2003 * CoMarshalInterface, CoReleaseMarshalData, CoLockObjectExternal
2005 HRESULT WINAPI CoDisconnectObject( LPUNKNOWN lpUnk, DWORD reserved )
2007 HRESULT hr;
2008 IMarshal *marshal;
2009 APARTMENT *apt;
2011 TRACE("(%p, 0x%08x)\n", lpUnk, reserved);
2013 if (!lpUnk) return E_INVALIDARG;
2015 hr = IUnknown_QueryInterface(lpUnk, &IID_IMarshal, (void **)&marshal);
2016 if (hr == S_OK)
2018 hr = IMarshal_DisconnectObject(marshal, reserved);
2019 IMarshal_Release(marshal);
2020 return hr;
2023 apt = COM_CurrentApt();
2024 if (!apt)
2025 return CO_E_NOTINITIALIZED;
2027 apartment_disconnectobject(apt, lpUnk);
2029 /* Note: native is pretty broken here because it just silently
2030 * fails, without returning an appropriate error code if the object was
2031 * not found, making apps think that the object was disconnected, when
2032 * it actually wasn't */
2034 return S_OK;
2037 /******************************************************************************
2038 * CoCreateGuid [OLE32.@]
2040 * Simply forwards to UuidCreate in RPCRT4.
2042 * PARAMS
2043 * pguid [O] Points to the GUID to initialize.
2045 * RETURNS
2046 * Success: S_OK.
2047 * Failure: HRESULT code.
2049 * SEE ALSO
2050 * UuidCreate
2052 HRESULT WINAPI CoCreateGuid(GUID *pguid)
2054 DWORD status = UuidCreate(pguid);
2055 if (status == RPC_S_OK || status == RPC_S_UUID_LOCAL_ONLY) return S_OK;
2056 return HRESULT_FROM_WIN32( status );
2059 static inline BOOL is_valid_hex(WCHAR c)
2061 if (!(((c >= '0') && (c <= '9')) ||
2062 ((c >= 'a') && (c <= 'f')) ||
2063 ((c >= 'A') && (c <= 'F'))))
2064 return FALSE;
2065 return TRUE;
2068 /******************************************************************************
2069 * CLSIDFromString [OLE32.@]
2070 * IIDFromString [OLE32.@]
2072 * Converts a unique identifier from its string representation into
2073 * the GUID struct.
2075 * PARAMS
2076 * idstr [I] The string representation of the GUID.
2077 * id [O] GUID converted from the string.
2079 * RETURNS
2080 * S_OK on success
2081 * CO_E_CLASSSTRING if idstr is not a valid CLSID
2083 * SEE ALSO
2084 * StringFromCLSID
2086 static HRESULT __CLSIDFromString(LPCWSTR s, LPCLSID id)
2088 int i;
2089 BYTE table[256];
2091 if (!s || s[0]!='{') {
2092 memset( id, 0, sizeof (CLSID) );
2093 if(!s) return S_OK;
2094 return CO_E_CLASSSTRING;
2097 TRACE("%s -> %p\n", debugstr_w(s), id);
2099 /* quick lookup table */
2100 memset(table, 0, 256);
2102 for (i = 0; i < 10; i++) {
2103 table['0' + i] = i;
2105 for (i = 0; i < 6; i++) {
2106 table['A' + i] = i+10;
2107 table['a' + i] = i+10;
2110 /* in form {XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX} */
2112 id->Data1 = 0;
2113 for (i = 1; i < 9; i++) {
2114 if (!is_valid_hex(s[i])) return CO_E_CLASSSTRING;
2115 id->Data1 = (id->Data1 << 4) | table[s[i]];
2117 if (s[9]!='-') return CO_E_CLASSSTRING;
2119 id->Data2 = 0;
2120 for (i = 10; i < 14; i++) {
2121 if (!is_valid_hex(s[i])) return CO_E_CLASSSTRING;
2122 id->Data2 = (id->Data2 << 4) | table[s[i]];
2124 if (s[14]!='-') return CO_E_CLASSSTRING;
2126 id->Data3 = 0;
2127 for (i = 15; i < 19; i++) {
2128 if (!is_valid_hex(s[i])) return CO_E_CLASSSTRING;
2129 id->Data3 = (id->Data3 << 4) | table[s[i]];
2131 if (s[19]!='-') return CO_E_CLASSSTRING;
2133 for (i = 20; i < 37; i+=2) {
2134 if (i == 24) {
2135 if (s[i]!='-') return CO_E_CLASSSTRING;
2136 i++;
2138 if (!is_valid_hex(s[i]) || !is_valid_hex(s[i+1])) return CO_E_CLASSSTRING;
2139 id->Data4[(i-20)/2] = table[s[i]] << 4 | table[s[i+1]];
2142 if (s[37] == '}' && s[38] == '\0')
2143 return S_OK;
2145 return CO_E_CLASSSTRING;
2148 /*****************************************************************************/
2150 static HRESULT clsid_from_string_reg(LPCOLESTR progid, CLSID *clsid)
2152 static const WCHAR clsidW[] = { '\\','C','L','S','I','D',0 };
2153 WCHAR buf2[CHARS_IN_GUID];
2154 LONG buf2len = sizeof(buf2);
2155 HKEY xhkey;
2156 WCHAR *buf;
2158 memset(clsid, 0, sizeof(*clsid));
2159 buf = HeapAlloc( GetProcessHeap(),0,(strlenW(progid)+8) * sizeof(WCHAR) );
2160 strcpyW( buf, progid );
2161 strcatW( buf, clsidW );
2162 if (open_classes_key(HKEY_CLASSES_ROOT, buf, MAXIMUM_ALLOWED, &xhkey))
2164 HeapFree(GetProcessHeap(),0,buf);
2165 WARN("couldn't open key for ProgID %s\n", debugstr_w(progid));
2166 return CO_E_CLASSSTRING;
2168 HeapFree(GetProcessHeap(),0,buf);
2170 if (RegQueryValueW(xhkey,NULL,buf2,&buf2len))
2172 RegCloseKey(xhkey);
2173 WARN("couldn't query clsid value for ProgID %s\n", debugstr_w(progid));
2174 return CO_E_CLASSSTRING;
2176 RegCloseKey(xhkey);
2177 return __CLSIDFromString(buf2,clsid);
2180 HRESULT WINAPI CLSIDFromString(LPCOLESTR idstr, LPCLSID id )
2182 HRESULT ret;
2184 if (!id)
2185 return E_INVALIDARG;
2187 ret = __CLSIDFromString(idstr, id);
2188 if(ret != S_OK) { /* It appears a ProgID is also valid */
2189 CLSID tmp_id;
2190 ret = clsid_from_string_reg(idstr, &tmp_id);
2191 if(SUCCEEDED(ret))
2192 *id = tmp_id;
2194 return ret;
2198 /******************************************************************************
2199 * StringFromCLSID [OLE32.@]
2200 * StringFromIID [OLE32.@]
2202 * Converts a GUID into the respective string representation.
2203 * The target string is allocated using the OLE IMalloc.
2205 * PARAMS
2206 * id [I] the GUID to be converted.
2207 * idstr [O] A pointer to a to-be-allocated pointer pointing to the resulting string.
2209 * RETURNS
2210 * S_OK
2211 * E_FAIL
2213 * SEE ALSO
2214 * StringFromGUID2, CLSIDFromString
2216 HRESULT WINAPI StringFromCLSID(REFCLSID id, LPOLESTR *idstr)
2218 HRESULT ret;
2219 LPMALLOC mllc;
2221 if ((ret = CoGetMalloc(0,&mllc))) return ret;
2222 if (!(*idstr = IMalloc_Alloc( mllc, CHARS_IN_GUID * sizeof(WCHAR) ))) return E_OUTOFMEMORY;
2223 StringFromGUID2( id, *idstr, CHARS_IN_GUID );
2224 return S_OK;
2227 /******************************************************************************
2228 * StringFromGUID2 [OLE32.@]
2230 * Modified version of StringFromCLSID that allows you to specify max
2231 * buffer size.
2233 * PARAMS
2234 * id [I] GUID to convert to string.
2235 * str [O] Buffer where the result will be stored.
2236 * cmax [I] Size of the buffer in characters.
2238 * RETURNS
2239 * Success: The length of the resulting string in characters.
2240 * Failure: 0.
2242 INT WINAPI StringFromGUID2(REFGUID id, LPOLESTR str, INT cmax)
2244 static const WCHAR formatW[] = { '{','%','0','8','X','-','%','0','4','X','-',
2245 '%','0','4','X','-','%','0','2','X','%','0','2','X','-',
2246 '%','0','2','X','%','0','2','X','%','0','2','X','%','0','2','X',
2247 '%','0','2','X','%','0','2','X','}',0 };
2248 if (!id || cmax < CHARS_IN_GUID) return 0;
2249 sprintfW( str, formatW, id->Data1, id->Data2, id->Data3,
2250 id->Data4[0], id->Data4[1], id->Data4[2], id->Data4[3],
2251 id->Data4[4], id->Data4[5], id->Data4[6], id->Data4[7] );
2252 return CHARS_IN_GUID;
2255 /* open HKCR\\CLSID\\{string form of clsid}\\{keyname} key */
2256 HRESULT COM_OpenKeyForCLSID(REFCLSID clsid, LPCWSTR keyname, REGSAM access, HKEY *subkey)
2258 static const WCHAR wszCLSIDSlash[] = {'C','L','S','I','D','\\',0};
2259 WCHAR path[CHARS_IN_GUID + ARRAYSIZE(wszCLSIDSlash) - 1];
2260 LONG res;
2261 HKEY key;
2263 strcpyW(path, wszCLSIDSlash);
2264 StringFromGUID2(clsid, path + strlenW(wszCLSIDSlash), CHARS_IN_GUID);
2265 res = open_classes_key(HKEY_CLASSES_ROOT, path, keyname ? KEY_READ : access, &key);
2266 if (res == ERROR_FILE_NOT_FOUND)
2267 return REGDB_E_CLASSNOTREG;
2268 else if (res != ERROR_SUCCESS)
2269 return REGDB_E_READREGDB;
2271 if (!keyname)
2273 *subkey = key;
2274 return S_OK;
2277 res = open_classes_key(key, keyname, access, subkey);
2278 RegCloseKey(key);
2279 if (res == ERROR_FILE_NOT_FOUND)
2280 return REGDB_E_KEYMISSING;
2281 else if (res != ERROR_SUCCESS)
2282 return REGDB_E_READREGDB;
2284 return S_OK;
2287 /* open HKCR\\AppId\\{string form of appid clsid} key */
2288 HRESULT COM_OpenKeyForAppIdFromCLSID(REFCLSID clsid, REGSAM access, HKEY *subkey)
2290 static const WCHAR szAppId[] = { 'A','p','p','I','d',0 };
2291 static const WCHAR szAppIdKey[] = { 'A','p','p','I','d','\\',0 };
2292 DWORD res;
2293 WCHAR buf[CHARS_IN_GUID];
2294 WCHAR keyname[ARRAYSIZE(szAppIdKey) + CHARS_IN_GUID];
2295 DWORD size;
2296 HKEY hkey;
2297 DWORD type;
2298 HRESULT hr;
2300 /* read the AppID value under the class's key */
2301 hr = COM_OpenKeyForCLSID(clsid, NULL, KEY_READ, &hkey);
2302 if (FAILED(hr))
2303 return hr;
2305 size = sizeof(buf);
2306 res = RegQueryValueExW(hkey, szAppId, NULL, &type, (LPBYTE)buf, &size);
2307 RegCloseKey(hkey);
2308 if (res == ERROR_FILE_NOT_FOUND)
2309 return REGDB_E_KEYMISSING;
2310 else if (res != ERROR_SUCCESS || type!=REG_SZ)
2311 return REGDB_E_READREGDB;
2313 strcpyW(keyname, szAppIdKey);
2314 strcatW(keyname, buf);
2315 res = open_classes_key(HKEY_CLASSES_ROOT, keyname, access, subkey);
2316 if (res == ERROR_FILE_NOT_FOUND)
2317 return REGDB_E_KEYMISSING;
2318 else if (res != ERROR_SUCCESS)
2319 return REGDB_E_READREGDB;
2321 return S_OK;
2324 /******************************************************************************
2325 * ProgIDFromCLSID [OLE32.@]
2327 * Converts a class id into the respective program ID.
2329 * PARAMS
2330 * clsid [I] Class ID, as found in registry.
2331 * ppszProgID [O] Associated ProgID.
2333 * RETURNS
2334 * S_OK
2335 * E_OUTOFMEMORY
2336 * REGDB_E_CLASSNOTREG if the given clsid has no associated ProgID
2338 HRESULT WINAPI ProgIDFromCLSID(REFCLSID clsid, LPOLESTR *ppszProgID)
2340 static const WCHAR wszProgID[] = {'P','r','o','g','I','D',0};
2341 ACTCTX_SECTION_KEYED_DATA data;
2342 HKEY hkey;
2343 HRESULT ret;
2344 LONG progidlen = 0;
2346 if (!ppszProgID)
2348 ERR("ppszProgId isn't optional\n");
2349 return E_INVALIDARG;
2352 *ppszProgID = NULL;
2354 data.cbSize = sizeof(data);
2355 if (FindActCtxSectionGuid(0, NULL, ACTIVATION_CONTEXT_SECTION_COM_SERVER_REDIRECTION,
2356 clsid, &data))
2358 struct comclassredirect_data *comclass = (struct comclassredirect_data*)data.lpData;
2359 if (comclass->progid_len)
2361 WCHAR *ptrW;
2363 *ppszProgID = CoTaskMemAlloc(comclass->progid_len + sizeof(WCHAR));
2364 if (!*ppszProgID) return E_OUTOFMEMORY;
2366 ptrW = (WCHAR*)((BYTE*)comclass + comclass->progid_offset);
2367 memcpy(*ppszProgID, ptrW, comclass->progid_len + sizeof(WCHAR));
2368 return S_OK;
2370 else
2371 return REGDB_E_CLASSNOTREG;
2374 ret = COM_OpenKeyForCLSID(clsid, wszProgID, KEY_READ, &hkey);
2375 if (FAILED(ret))
2376 return ret;
2378 if (RegQueryValueW(hkey, NULL, NULL, &progidlen))
2379 ret = REGDB_E_CLASSNOTREG;
2381 if (ret == S_OK)
2383 *ppszProgID = CoTaskMemAlloc(progidlen * sizeof(WCHAR));
2384 if (*ppszProgID)
2386 if (RegQueryValueW(hkey, NULL, *ppszProgID, &progidlen)) {
2387 ret = REGDB_E_CLASSNOTREG;
2388 CoTaskMemFree(*ppszProgID);
2389 *ppszProgID = NULL;
2392 else
2393 ret = E_OUTOFMEMORY;
2396 RegCloseKey(hkey);
2397 return ret;
2400 /******************************************************************************
2401 * CLSIDFromProgID [OLE32.@]
2403 * Converts a program id into the respective GUID.
2405 * PARAMS
2406 * progid [I] Unicode program ID, as found in registry.
2407 * clsid [O] Associated CLSID.
2409 * RETURNS
2410 * Success: S_OK
2411 * Failure: CO_E_CLASSSTRING - the given ProgID cannot be found.
2413 HRESULT WINAPI CLSIDFromProgID(LPCOLESTR progid, LPCLSID clsid)
2415 ACTCTX_SECTION_KEYED_DATA data;
2417 if (!progid || !clsid)
2419 ERR("neither progid (%p) nor clsid (%p) are optional\n", progid, clsid);
2420 return E_INVALIDARG;
2423 data.cbSize = sizeof(data);
2424 if (FindActCtxSectionStringW(0, NULL, ACTIVATION_CONTEXT_SECTION_COM_PROGID_REDIRECTION,
2425 progid, &data))
2427 struct progidredirect_data *progiddata = (struct progidredirect_data*)data.lpData;
2428 CLSID *alias = (CLSID*)((BYTE*)data.lpSectionBase + progiddata->clsid_offset);
2429 *clsid = *alias;
2430 return S_OK;
2433 return clsid_from_string_reg(progid, clsid);
2436 /******************************************************************************
2437 * CLSIDFromProgIDEx [OLE32.@]
2439 HRESULT WINAPI CLSIDFromProgIDEx(LPCOLESTR progid, LPCLSID clsid)
2441 FIXME("%s,%p: semi-stub\n", debugstr_w(progid), clsid);
2443 return CLSIDFromProgID(progid, clsid);
2446 /*****************************************************************************
2447 * CoGetPSClsid [OLE32.@]
2449 * Retrieves the CLSID of the proxy/stub factory that implements
2450 * IPSFactoryBuffer for the specified interface.
2452 * PARAMS
2453 * riid [I] Interface whose proxy/stub CLSID is to be returned.
2454 * pclsid [O] Where to store returned proxy/stub CLSID.
2456 * RETURNS
2457 * S_OK
2458 * E_OUTOFMEMORY
2459 * REGDB_E_IIDNOTREG if no PSFactoryBuffer is associated with the IID, or it could not be parsed
2461 * NOTES
2463 * The standard marshaller activates the object with the CLSID
2464 * returned and uses the CreateProxy and CreateStub methods on its
2465 * IPSFactoryBuffer interface to construct the proxies and stubs for a
2466 * given object.
2468 * CoGetPSClsid determines this CLSID by searching the
2469 * HKEY_CLASSES_ROOT\Interface\{string form of riid}\ProxyStubClsid32
2470 * in the registry and any interface id registered by
2471 * CoRegisterPSClsid within the current process.
2473 * BUGS
2475 * Native returns S_OK for interfaces with a key in HKCR\Interface, but
2476 * without a ProxyStubClsid32 key and leaves garbage in pclsid. This should be
2477 * considered a bug in native unless an application depends on this (unlikely).
2479 * SEE ALSO
2480 * CoRegisterPSClsid.
2482 HRESULT WINAPI CoGetPSClsid(REFIID riid, CLSID *pclsid)
2484 static const WCHAR wszInterface[] = {'I','n','t','e','r','f','a','c','e','\\',0};
2485 static const WCHAR wszPSC[] = {'\\','P','r','o','x','y','S','t','u','b','C','l','s','i','d','3','2',0};
2486 WCHAR path[ARRAYSIZE(wszInterface) - 1 + CHARS_IN_GUID - 1 + ARRAYSIZE(wszPSC)];
2487 WCHAR value[CHARS_IN_GUID];
2488 LONG len;
2489 HKEY hkey;
2490 APARTMENT *apt = COM_CurrentApt();
2491 struct registered_psclsid *registered_psclsid;
2492 ACTCTX_SECTION_KEYED_DATA data;
2494 TRACE("() riid=%s, pclsid=%p\n", debugstr_guid(riid), pclsid);
2496 if (!apt)
2498 ERR("apartment not initialised\n");
2499 return CO_E_NOTINITIALIZED;
2502 if (!pclsid)
2504 ERR("pclsid isn't optional\n");
2505 return E_INVALIDARG;
2508 EnterCriticalSection(&apt->cs);
2510 LIST_FOR_EACH_ENTRY(registered_psclsid, &apt->psclsids, struct registered_psclsid, entry)
2511 if (IsEqualIID(&registered_psclsid->iid, riid))
2513 *pclsid = registered_psclsid->clsid;
2514 LeaveCriticalSection(&apt->cs);
2515 return S_OK;
2518 LeaveCriticalSection(&apt->cs);
2520 data.cbSize = sizeof(data);
2521 if (FindActCtxSectionGuid(0, NULL, ACTIVATION_CONTEXT_SECTION_COM_INTERFACE_REDIRECTION,
2522 riid, &data))
2524 struct ifacepsredirect_data *ifaceps = (struct ifacepsredirect_data*)data.lpData;
2525 *pclsid = ifaceps->iid;
2526 return S_OK;
2529 /* Interface\\{string form of riid}\\ProxyStubClsid32 */
2530 strcpyW(path, wszInterface);
2531 StringFromGUID2(riid, path + ARRAYSIZE(wszInterface) - 1, CHARS_IN_GUID);
2532 strcpyW(path + ARRAYSIZE(wszInterface) - 1 + CHARS_IN_GUID - 1, wszPSC);
2534 /* Open the key.. */
2535 if (open_classes_key(HKEY_CLASSES_ROOT, path, KEY_READ, &hkey))
2537 WARN("No PSFactoryBuffer object is registered for IID %s\n", debugstr_guid(riid));
2538 return REGDB_E_IIDNOTREG;
2541 /* ... Once we have the key, query the registry to get the
2542 value of CLSID as a string, and convert it into a
2543 proper CLSID structure to be passed back to the app */
2544 len = sizeof(value);
2545 if (ERROR_SUCCESS != RegQueryValueW(hkey, NULL, value, &len))
2547 RegCloseKey(hkey);
2548 return REGDB_E_IIDNOTREG;
2550 RegCloseKey(hkey);
2552 /* We have the CLSID we want back from the registry as a string, so
2553 let's convert it into a CLSID structure */
2554 if (CLSIDFromString(value, pclsid) != NOERROR)
2555 return REGDB_E_IIDNOTREG;
2557 TRACE ("() Returning CLSID=%s\n", debugstr_guid(pclsid));
2558 return S_OK;
2561 /*****************************************************************************
2562 * CoRegisterPSClsid [OLE32.@]
2564 * Register a proxy/stub CLSID for the given interface in the current process
2565 * only.
2567 * PARAMS
2568 * riid [I] Interface whose proxy/stub CLSID is to be registered.
2569 * rclsid [I] CLSID of the proxy/stub.
2571 * RETURNS
2572 * Success: S_OK
2573 * Failure: E_OUTOFMEMORY
2575 * NOTES
2577 * This function does not add anything to the registry and the effects are
2578 * limited to the lifetime of the current process.
2580 * SEE ALSO
2581 * CoGetPSClsid.
2583 HRESULT WINAPI CoRegisterPSClsid(REFIID riid, REFCLSID rclsid)
2585 APARTMENT *apt = COM_CurrentApt();
2586 struct registered_psclsid *registered_psclsid;
2588 TRACE("(%s, %s)\n", debugstr_guid(riid), debugstr_guid(rclsid));
2590 if (!apt)
2592 ERR("apartment not initialised\n");
2593 return CO_E_NOTINITIALIZED;
2596 EnterCriticalSection(&apt->cs);
2598 LIST_FOR_EACH_ENTRY(registered_psclsid, &apt->psclsids, struct registered_psclsid, entry)
2599 if (IsEqualIID(&registered_psclsid->iid, riid))
2601 registered_psclsid->clsid = *rclsid;
2602 LeaveCriticalSection(&apt->cs);
2603 return S_OK;
2606 registered_psclsid = HeapAlloc(GetProcessHeap(), 0, sizeof(struct registered_psclsid));
2607 if (!registered_psclsid)
2609 LeaveCriticalSection(&apt->cs);
2610 return E_OUTOFMEMORY;
2613 registered_psclsid->iid = *riid;
2614 registered_psclsid->clsid = *rclsid;
2615 list_add_head(&apt->psclsids, &registered_psclsid->entry);
2617 LeaveCriticalSection(&apt->cs);
2619 return S_OK;
2623 /***
2624 * COM_GetRegisteredClassObject
2626 * This internal method is used to scan the registered class list to
2627 * find a class object.
2629 * Params:
2630 * rclsid Class ID of the class to find.
2631 * dwClsContext Class context to match.
2632 * ppv [out] returns a pointer to the class object. Complying
2633 * to normal COM usage, this method will increase the
2634 * reference count on this object.
2636 static HRESULT COM_GetRegisteredClassObject(const struct apartment *apt, REFCLSID rclsid,
2637 DWORD dwClsContext, LPUNKNOWN* ppUnk)
2639 HRESULT hr = S_FALSE;
2640 RegisteredClass *curClass;
2642 EnterCriticalSection( &csRegisteredClassList );
2644 LIST_FOR_EACH_ENTRY(curClass, &RegisteredClassList, RegisteredClass, entry)
2647 * Check if we have a match on the class ID and context.
2649 if ((apt->oxid == curClass->apartment_id) &&
2650 (dwClsContext & curClass->runContext) &&
2651 IsEqualGUID(&(curClass->classIdentifier), rclsid))
2654 * We have a match, return the pointer to the class object.
2656 *ppUnk = curClass->classObject;
2658 IUnknown_AddRef(curClass->classObject);
2660 hr = S_OK;
2661 break;
2665 LeaveCriticalSection( &csRegisteredClassList );
2667 return hr;
2670 /******************************************************************************
2671 * CoRegisterClassObject [OLE32.@]
2673 * Registers the class object for a given class ID. Servers housed in EXE
2674 * files use this method instead of exporting DllGetClassObject to allow
2675 * other code to connect to their objects.
2677 * PARAMS
2678 * rclsid [I] CLSID of the object to register.
2679 * pUnk [I] IUnknown of the object.
2680 * dwClsContext [I] CLSCTX flags indicating the context in which to run the executable.
2681 * flags [I] REGCLS flags indicating how connections are made.
2682 * lpdwRegister [I] A unique cookie that can be passed to CoRevokeClassObject.
2684 * RETURNS
2685 * S_OK on success,
2686 * E_INVALIDARG if lpdwRegister or pUnk are NULL,
2687 * CO_E_OBJISREG if the object is already registered. We should not return this.
2689 * SEE ALSO
2690 * CoRevokeClassObject, CoGetClassObject
2692 * NOTES
2693 * In-process objects are only registered for the current apartment.
2694 * CoGetClassObject() and CoCreateInstance() will not return objects registered
2695 * in other apartments.
2697 * BUGS
2698 * MSDN claims that multiple interface registrations are legal, but we
2699 * can't do that with our current implementation.
2701 HRESULT WINAPI CoRegisterClassObject(
2702 REFCLSID rclsid,
2703 LPUNKNOWN pUnk,
2704 DWORD dwClsContext,
2705 DWORD flags,
2706 LPDWORD lpdwRegister)
2708 static LONG next_cookie;
2709 RegisteredClass* newClass;
2710 LPUNKNOWN foundObject;
2711 HRESULT hr;
2712 APARTMENT *apt;
2714 TRACE("(%s,%p,0x%08x,0x%08x,%p)\n",
2715 debugstr_guid(rclsid),pUnk,dwClsContext,flags,lpdwRegister);
2717 if ( (lpdwRegister==0) || (pUnk==0) )
2718 return E_INVALIDARG;
2720 apt = COM_CurrentApt();
2721 if (!apt)
2723 ERR("COM was not initialized\n");
2724 return CO_E_NOTINITIALIZED;
2727 *lpdwRegister = 0;
2729 /* REGCLS_MULTIPLEUSE implies registering as inproc server. This is what
2730 * differentiates the flag from REGCLS_MULTI_SEPARATE. */
2731 if (flags & REGCLS_MULTIPLEUSE)
2732 dwClsContext |= CLSCTX_INPROC_SERVER;
2735 * First, check if the class is already registered.
2736 * If it is, this should cause an error.
2738 hr = COM_GetRegisteredClassObject(apt, rclsid, dwClsContext, &foundObject);
2739 if (hr == S_OK) {
2740 if (flags & REGCLS_MULTIPLEUSE) {
2741 if (dwClsContext & CLSCTX_LOCAL_SERVER)
2742 hr = CoLockObjectExternal(foundObject, TRUE, FALSE);
2743 IUnknown_Release(foundObject);
2744 return hr;
2746 IUnknown_Release(foundObject);
2747 ERR("object already registered for class %s\n", debugstr_guid(rclsid));
2748 return CO_E_OBJISREG;
2751 newClass = HeapAlloc(GetProcessHeap(), 0, sizeof(RegisteredClass));
2752 if ( newClass == NULL )
2753 return E_OUTOFMEMORY;
2755 newClass->classIdentifier = *rclsid;
2756 newClass->apartment_id = apt->oxid;
2757 newClass->runContext = dwClsContext;
2758 newClass->connectFlags = flags;
2759 newClass->RpcRegistration = NULL;
2761 if (!(newClass->dwCookie = InterlockedIncrement( &next_cookie )))
2762 newClass->dwCookie = InterlockedIncrement( &next_cookie );
2765 * Since we're making a copy of the object pointer, we have to increase its
2766 * reference count.
2768 newClass->classObject = pUnk;
2769 IUnknown_AddRef(newClass->classObject);
2771 EnterCriticalSection( &csRegisteredClassList );
2772 list_add_tail(&RegisteredClassList, &newClass->entry);
2773 LeaveCriticalSection( &csRegisteredClassList );
2775 *lpdwRegister = newClass->dwCookie;
2777 if (dwClsContext & CLSCTX_LOCAL_SERVER) {
2778 IStream *marshal_stream;
2780 hr = get_local_server_stream(apt, &marshal_stream);
2781 if(FAILED(hr))
2782 return hr;
2784 hr = RPC_StartLocalServer(&newClass->classIdentifier,
2785 marshal_stream,
2786 flags & (REGCLS_MULTIPLEUSE|REGCLS_MULTI_SEPARATE),
2787 &newClass->RpcRegistration);
2788 IStream_Release(marshal_stream);
2790 return S_OK;
2793 static enum comclass_threadingmodel get_threading_model(const struct class_reg_data *data)
2795 if (data->hkey)
2797 static const WCHAR wszThreadingModel[] = {'T','h','r','e','a','d','i','n','g','M','o','d','e','l',0};
2798 static const WCHAR wszApartment[] = {'A','p','a','r','t','m','e','n','t',0};
2799 static const WCHAR wszFree[] = {'F','r','e','e',0};
2800 static const WCHAR wszBoth[] = {'B','o','t','h',0};
2801 WCHAR threading_model[10 /* strlenW(L"apartment")+1 */];
2802 DWORD dwLength = sizeof(threading_model);
2803 DWORD keytype;
2804 DWORD ret;
2806 ret = RegQueryValueExW(data->u.hkey, wszThreadingModel, NULL, &keytype, (BYTE*)threading_model, &dwLength);
2807 if ((ret != ERROR_SUCCESS) || (keytype != REG_SZ))
2808 threading_model[0] = '\0';
2810 if (!strcmpiW(threading_model, wszApartment)) return ThreadingModel_Apartment;
2811 if (!strcmpiW(threading_model, wszFree)) return ThreadingModel_Free;
2812 if (!strcmpiW(threading_model, wszBoth)) return ThreadingModel_Both;
2814 /* there's not specific handling for this case */
2815 if (threading_model[0]) return ThreadingModel_Neutral;
2816 return ThreadingModel_No;
2818 else
2819 return data->u.actctx.data->model;
2822 static HRESULT get_inproc_class_object(APARTMENT *apt, const struct class_reg_data *regdata,
2823 REFCLSID rclsid, REFIID riid,
2824 BOOL hostifnecessary, void **ppv)
2826 WCHAR dllpath[MAX_PATH+1];
2827 BOOL apartment_threaded;
2829 if (hostifnecessary)
2831 enum comclass_threadingmodel model = get_threading_model(regdata);
2833 if (model == ThreadingModel_Apartment)
2835 apartment_threaded = TRUE;
2836 if (apt->multi_threaded)
2837 return apartment_hostobject_in_hostapt(apt, FALSE, FALSE, regdata, rclsid, riid, ppv);
2839 else if (model == ThreadingModel_Free)
2841 apartment_threaded = FALSE;
2842 if (!apt->multi_threaded)
2843 return apartment_hostobject_in_hostapt(apt, TRUE, FALSE, regdata, rclsid, riid, ppv);
2845 /* everything except "Apartment", "Free" and "Both" */
2846 else if (model != ThreadingModel_Both)
2848 apartment_threaded = TRUE;
2849 /* everything else is main-threaded */
2850 if (model != ThreadingModel_No)
2851 FIXME("unrecognised threading model %d for object %s, should be main-threaded?\n", model, debugstr_guid(rclsid));
2853 if (apt->multi_threaded || !apt->main)
2854 return apartment_hostobject_in_hostapt(apt, FALSE, TRUE, regdata, rclsid, riid, ppv);
2856 else
2857 apartment_threaded = FALSE;
2859 else
2860 apartment_threaded = !apt->multi_threaded;
2862 if (COM_RegReadPath(regdata, dllpath, ARRAYSIZE(dllpath)) != ERROR_SUCCESS)
2864 /* failure: CLSID is not found in registry */
2865 WARN("class %s not registered inproc\n", debugstr_guid(rclsid));
2866 return REGDB_E_CLASSNOTREG;
2869 return apartment_getclassobject(apt, dllpath, apartment_threaded,
2870 rclsid, riid, ppv);
2873 /***********************************************************************
2874 * CoGetClassObject [OLE32.@]
2876 * Creates an object of the specified class.
2878 * PARAMS
2879 * rclsid [I] Class ID to create an instance of.
2880 * dwClsContext [I] Flags to restrict the location of the created instance.
2881 * pServerInfo [I] Optional. Details for connecting to a remote server.
2882 * iid [I] The ID of the interface of the instance to return.
2883 * ppv [O] On returns, contains a pointer to the specified interface of the object.
2885 * RETURNS
2886 * Success: S_OK
2887 * Failure: HRESULT code.
2889 * NOTES
2890 * The dwClsContext parameter can be one or more of the following:
2891 *| CLSCTX_INPROC_SERVER - Use an in-process server, such as from a DLL.
2892 *| CLSCTX_INPROC_HANDLER - Use an in-process object which handles certain functions for an object running in another process.
2893 *| CLSCTX_LOCAL_SERVER - Connect to an object running in another process.
2894 *| CLSCTX_REMOTE_SERVER - Connect to an object running on another machine.
2896 * SEE ALSO
2897 * CoCreateInstance()
2899 HRESULT WINAPI CoGetClassObject(
2900 REFCLSID rclsid, DWORD dwClsContext, COSERVERINFO *pServerInfo,
2901 REFIID iid, LPVOID *ppv)
2903 struct class_reg_data clsreg;
2904 IUnknown *regClassObject;
2905 HRESULT hres = E_UNEXPECTED;
2906 APARTMENT *apt;
2907 BOOL release_apt = FALSE;
2909 TRACE("CLSID: %s,IID: %s\n", debugstr_guid(rclsid), debugstr_guid(iid));
2911 if (!ppv)
2912 return E_INVALIDARG;
2914 *ppv = NULL;
2916 if (!(apt = COM_CurrentApt()))
2918 if (!(apt = apartment_find_multi_threaded()))
2920 ERR("apartment not initialised\n");
2921 return CO_E_NOTINITIALIZED;
2923 release_apt = TRUE;
2926 if (pServerInfo) {
2927 FIXME("pServerInfo->name=%s pAuthInfo=%p\n",
2928 debugstr_w(pServerInfo->pwszName), pServerInfo->pAuthInfo);
2931 if (CLSCTX_INPROC_SERVER & dwClsContext)
2933 if (IsEqualCLSID(rclsid, &CLSID_InProcFreeMarshaler))
2935 if (release_apt) apartment_release(apt);
2936 return FTMarshalCF_Create(iid, ppv);
2940 if (CLSCTX_INPROC & dwClsContext)
2942 ACTCTX_SECTION_KEYED_DATA data;
2944 data.cbSize = sizeof(data);
2945 /* search activation context first */
2946 if (FindActCtxSectionGuid(FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX, NULL,
2947 ACTIVATION_CONTEXT_SECTION_COM_SERVER_REDIRECTION,
2948 rclsid, &data))
2950 struct comclassredirect_data *comclass = (struct comclassredirect_data*)data.lpData;
2952 clsreg.u.actctx.hactctx = data.hActCtx;
2953 clsreg.u.actctx.data = data.lpData;
2954 clsreg.u.actctx.section = data.lpSectionBase;
2955 clsreg.hkey = FALSE;
2957 hres = get_inproc_class_object(apt, &clsreg, &comclass->clsid, iid, !(dwClsContext & WINE_CLSCTX_DONT_HOST), ppv);
2958 ReleaseActCtx(data.hActCtx);
2959 if (release_apt) apartment_release(apt);
2960 return hres;
2965 * First, try and see if we can't match the class ID with one of the
2966 * registered classes.
2968 if (S_OK == COM_GetRegisteredClassObject(apt, rclsid, dwClsContext,
2969 &regClassObject))
2971 /* Get the required interface from the retrieved pointer. */
2972 hres = IUnknown_QueryInterface(regClassObject, iid, ppv);
2975 * Since QI got another reference on the pointer, we want to release the
2976 * one we already have. If QI was unsuccessful, this will release the object. This
2977 * is good since we are not returning it in the "out" parameter.
2979 IUnknown_Release(regClassObject);
2980 if (release_apt) apartment_release(apt);
2981 return hres;
2984 /* First try in-process server */
2985 if (CLSCTX_INPROC_SERVER & dwClsContext)
2987 static const WCHAR wszInprocServer32[] = {'I','n','p','r','o','c','S','e','r','v','e','r','3','2',0};
2988 HKEY hkey;
2990 hres = COM_OpenKeyForCLSID(rclsid, wszInprocServer32, KEY_READ, &hkey);
2991 if (FAILED(hres))
2993 if (hres == REGDB_E_CLASSNOTREG)
2994 ERR("class %s not registered\n", debugstr_guid(rclsid));
2995 else if (hres == REGDB_E_KEYMISSING)
2997 WARN("class %s not registered as in-proc server\n", debugstr_guid(rclsid));
2998 hres = REGDB_E_CLASSNOTREG;
3002 if (SUCCEEDED(hres))
3004 clsreg.u.hkey = hkey;
3005 clsreg.hkey = TRUE;
3007 hres = get_inproc_class_object(apt, &clsreg, rclsid, iid, !(dwClsContext & WINE_CLSCTX_DONT_HOST), ppv);
3008 RegCloseKey(hkey);
3011 /* return if we got a class, otherwise fall through to one of the
3012 * other types */
3013 if (SUCCEEDED(hres))
3015 if (release_apt) apartment_release(apt);
3016 return hres;
3020 /* Next try in-process handler */
3021 if (CLSCTX_INPROC_HANDLER & dwClsContext)
3023 static const WCHAR wszInprocHandler32[] = {'I','n','p','r','o','c','H','a','n','d','l','e','r','3','2',0};
3024 HKEY hkey;
3026 hres = COM_OpenKeyForCLSID(rclsid, wszInprocHandler32, KEY_READ, &hkey);
3027 if (FAILED(hres))
3029 if (hres == REGDB_E_CLASSNOTREG)
3030 ERR("class %s not registered\n", debugstr_guid(rclsid));
3031 else if (hres == REGDB_E_KEYMISSING)
3033 WARN("class %s not registered in-proc handler\n", debugstr_guid(rclsid));
3034 hres = REGDB_E_CLASSNOTREG;
3038 if (SUCCEEDED(hres))
3040 clsreg.u.hkey = hkey;
3041 clsreg.hkey = TRUE;
3043 hres = get_inproc_class_object(apt, &clsreg, rclsid, iid, !(dwClsContext & WINE_CLSCTX_DONT_HOST), ppv);
3044 RegCloseKey(hkey);
3047 /* return if we got a class, otherwise fall through to one of the
3048 * other types */
3049 if (SUCCEEDED(hres))
3051 if (release_apt) apartment_release(apt);
3052 return hres;
3055 if (release_apt) apartment_release(apt);
3057 /* Next try out of process */
3058 if (CLSCTX_LOCAL_SERVER & dwClsContext)
3060 hres = RPC_GetLocalClassObject(rclsid,iid,ppv);
3061 if (SUCCEEDED(hres))
3062 return hres;
3065 /* Finally try remote: this requires networked DCOM (a lot of work) */
3066 if (CLSCTX_REMOTE_SERVER & dwClsContext)
3068 FIXME ("CLSCTX_REMOTE_SERVER not supported\n");
3069 hres = REGDB_E_CLASSNOTREG;
3072 if (FAILED(hres))
3073 ERR("no class object %s could be created for context 0x%x\n",
3074 debugstr_guid(rclsid), dwClsContext);
3075 return hres;
3078 /***********************************************************************
3079 * CoResumeClassObjects (OLE32.@)
3081 * Resumes all class objects registered with REGCLS_SUSPENDED.
3083 * RETURNS
3084 * Success: S_OK.
3085 * Failure: HRESULT code.
3087 HRESULT WINAPI CoResumeClassObjects(void)
3089 FIXME("stub\n");
3090 return S_OK;
3093 /***********************************************************************
3094 * CoCreateInstance [OLE32.@]
3096 * Creates an instance of the specified class.
3098 * PARAMS
3099 * rclsid [I] Class ID to create an instance of.
3100 * pUnkOuter [I] Optional outer unknown to allow aggregation with another object.
3101 * dwClsContext [I] Flags to restrict the location of the created instance.
3102 * iid [I] The ID of the interface of the instance to return.
3103 * ppv [O] On returns, contains a pointer to the specified interface of the instance.
3105 * RETURNS
3106 * Success: S_OK
3107 * Failure: HRESULT code.
3109 * NOTES
3110 * The dwClsContext parameter can be one or more of the following:
3111 *| CLSCTX_INPROC_SERVER - Use an in-process server, such as from a DLL.
3112 *| CLSCTX_INPROC_HANDLER - Use an in-process object which handles certain functions for an object running in another process.
3113 *| CLSCTX_LOCAL_SERVER - Connect to an object running in another process.
3114 *| CLSCTX_REMOTE_SERVER - Connect to an object running on another machine.
3116 * Aggregation is the concept of deferring the IUnknown of an object to another
3117 * object. This allows a separate object to behave as though it was part of
3118 * the object and to allow this the pUnkOuter parameter can be set. Note that
3119 * not all objects support having an outer of unknown.
3121 * SEE ALSO
3122 * CoGetClassObject()
3124 HRESULT WINAPI CoCreateInstance(
3125 REFCLSID rclsid,
3126 LPUNKNOWN pUnkOuter,
3127 DWORD dwClsContext,
3128 REFIID iid,
3129 LPVOID *ppv)
3131 HRESULT hres;
3132 LPCLASSFACTORY lpclf = 0;
3133 APARTMENT *apt;
3135 TRACE("(rclsid=%s, pUnkOuter=%p, dwClsContext=%08x, riid=%s, ppv=%p)\n", debugstr_guid(rclsid),
3136 pUnkOuter, dwClsContext, debugstr_guid(iid), ppv);
3138 if (ppv==0)
3139 return E_POINTER;
3141 *ppv = 0;
3143 if (!(apt = COM_CurrentApt()))
3145 if (!(apt = apartment_find_multi_threaded()))
3147 ERR("apartment not initialised\n");
3148 return CO_E_NOTINITIALIZED;
3150 apartment_release(apt);
3154 * The Standard Global Interface Table (GIT) object is a process-wide singleton.
3156 if (IsEqualIID(rclsid, &CLSID_StdGlobalInterfaceTable))
3158 IGlobalInterfaceTable *git = get_std_git();
3159 hres = IGlobalInterfaceTable_QueryInterface(git, iid, ppv);
3160 if (hres != S_OK) return hres;
3162 TRACE("Retrieved GIT (%p)\n", *ppv);
3163 return S_OK;
3166 if (IsEqualCLSID(rclsid, &CLSID_ManualResetEvent))
3167 return ManualResetEvent_Construct(pUnkOuter, iid, ppv);
3170 * Get a class factory to construct the object we want.
3172 hres = CoGetClassObject(rclsid,
3173 dwClsContext,
3174 NULL,
3175 &IID_IClassFactory,
3176 (LPVOID)&lpclf);
3178 if (FAILED(hres))
3179 return hres;
3182 * Create the object and don't forget to release the factory
3184 hres = IClassFactory_CreateInstance(lpclf, pUnkOuter, iid, ppv);
3185 IClassFactory_Release(lpclf);
3186 if (FAILED(hres))
3188 if (hres == CLASS_E_NOAGGREGATION && pUnkOuter)
3189 FIXME("Class %s does not support aggregation\n", debugstr_guid(rclsid));
3190 else
3191 FIXME("no instance created for interface %s of class %s, hres is 0x%08x\n",
3192 debugstr_guid(iid),
3193 debugstr_guid(rclsid),hres);
3196 return hres;
3199 /***********************************************************************
3200 * CoCreateInstanceEx [OLE32.@]
3202 HRESULT WINAPI CoCreateInstanceEx(
3203 REFCLSID rclsid,
3204 LPUNKNOWN pUnkOuter,
3205 DWORD dwClsContext,
3206 COSERVERINFO* pServerInfo,
3207 ULONG cmq,
3208 MULTI_QI* pResults)
3210 IUnknown* pUnk = NULL;
3211 HRESULT hr;
3212 ULONG index;
3213 ULONG successCount = 0;
3216 * Sanity check
3218 if ( (cmq==0) || (pResults==NULL))
3219 return E_INVALIDARG;
3221 if (pServerInfo!=NULL)
3222 FIXME("() non-NULL pServerInfo not supported!\n");
3225 * Initialize all the "out" parameters.
3227 for (index = 0; index < cmq; index++)
3229 pResults[index].pItf = NULL;
3230 pResults[index].hr = E_NOINTERFACE;
3234 * Get the object and get its IUnknown pointer.
3236 hr = CoCreateInstance(rclsid,
3237 pUnkOuter,
3238 dwClsContext,
3239 &IID_IUnknown,
3240 (VOID**)&pUnk);
3242 if (hr != S_OK)
3243 return hr;
3246 * Then, query for all the interfaces requested.
3248 for (index = 0; index < cmq; index++)
3250 pResults[index].hr = IUnknown_QueryInterface(pUnk,
3251 pResults[index].pIID,
3252 (VOID**)&(pResults[index].pItf));
3254 if (pResults[index].hr == S_OK)
3255 successCount++;
3259 * Release our temporary unknown pointer.
3261 IUnknown_Release(pUnk);
3263 if (successCount == 0)
3264 return E_NOINTERFACE;
3266 if (successCount!=cmq)
3267 return CO_S_NOTALLINTERFACES;
3269 return S_OK;
3272 /***********************************************************************
3273 * CoLoadLibrary (OLE32.@)
3275 * Loads a library.
3277 * PARAMS
3278 * lpszLibName [I] Path to library.
3279 * bAutoFree [I] Whether the library should automatically be freed.
3281 * RETURNS
3282 * Success: Handle to loaded library.
3283 * Failure: NULL.
3285 * SEE ALSO
3286 * CoFreeLibrary, CoFreeAllLibraries, CoFreeUnusedLibraries
3288 HINSTANCE WINAPI CoLoadLibrary(LPOLESTR lpszLibName, BOOL bAutoFree)
3290 TRACE("(%s, %d)\n", debugstr_w(lpszLibName), bAutoFree);
3292 return LoadLibraryExW(lpszLibName, 0, LOAD_WITH_ALTERED_SEARCH_PATH);
3295 /***********************************************************************
3296 * CoFreeLibrary [OLE32.@]
3298 * Unloads a library from memory.
3300 * PARAMS
3301 * hLibrary [I] Handle to library to unload.
3303 * RETURNS
3304 * Nothing
3306 * SEE ALSO
3307 * CoLoadLibrary, CoFreeAllLibraries, CoFreeUnusedLibraries
3309 void WINAPI CoFreeLibrary(HINSTANCE hLibrary)
3311 FreeLibrary(hLibrary);
3315 /***********************************************************************
3316 * CoFreeAllLibraries [OLE32.@]
3318 * Function for backwards compatibility only. Does nothing.
3320 * RETURNS
3321 * Nothing.
3323 * SEE ALSO
3324 * CoLoadLibrary, CoFreeLibrary, CoFreeUnusedLibraries
3326 void WINAPI CoFreeAllLibraries(void)
3328 /* NOP */
3331 /***********************************************************************
3332 * CoFreeUnusedLibrariesEx [OLE32.@]
3334 * Frees any previously unused libraries whose delay has expired and marks
3335 * currently unused libraries for unloading. Unused are identified as those that
3336 * return S_OK from their DllCanUnloadNow function.
3338 * PARAMS
3339 * dwUnloadDelay [I] Unload delay in milliseconds.
3340 * dwReserved [I] Reserved. Set to 0.
3342 * RETURNS
3343 * Nothing.
3345 * SEE ALSO
3346 * CoLoadLibrary, CoFreeAllLibraries, CoFreeLibrary
3348 void WINAPI CoFreeUnusedLibrariesEx(DWORD dwUnloadDelay, DWORD dwReserved)
3350 struct apartment *apt = COM_CurrentApt();
3351 if (!apt)
3353 ERR("apartment not initialised\n");
3354 return;
3357 apartment_freeunusedlibraries(apt, dwUnloadDelay);
3360 /***********************************************************************
3361 * CoFreeUnusedLibraries [OLE32.@]
3363 * Frees any unused libraries. Unused are identified as those that return
3364 * S_OK from their DllCanUnloadNow function.
3366 * RETURNS
3367 * Nothing.
3369 * SEE ALSO
3370 * CoLoadLibrary, CoFreeAllLibraries, CoFreeLibrary
3372 void WINAPI CoFreeUnusedLibraries(void)
3374 CoFreeUnusedLibrariesEx(INFINITE, 0);
3377 /***********************************************************************
3378 * CoFileTimeNow [OLE32.@]
3380 * Retrieves the current time in FILETIME format.
3382 * PARAMS
3383 * lpFileTime [O] The current time.
3385 * RETURNS
3386 * S_OK.
3388 HRESULT WINAPI CoFileTimeNow( FILETIME *lpFileTime )
3390 GetSystemTimeAsFileTime( lpFileTime );
3391 return S_OK;
3394 /******************************************************************************
3395 * CoLockObjectExternal [OLE32.@]
3397 * Increments or decrements the external reference count of a stub object.
3399 * PARAMS
3400 * pUnk [I] Stub object.
3401 * fLock [I] If TRUE then increments the external ref-count,
3402 * otherwise decrements.
3403 * fLastUnlockReleases [I] If TRUE then the last unlock has the effect of
3404 * calling CoDisconnectObject.
3406 * RETURNS
3407 * Success: S_OK.
3408 * Failure: HRESULT code.
3410 * NOTES
3411 * If fLock is TRUE and an object is passed in that doesn't have a stub
3412 * manager then a new stub manager is created for the object.
3414 HRESULT WINAPI CoLockObjectExternal(
3415 LPUNKNOWN pUnk,
3416 BOOL fLock,
3417 BOOL fLastUnlockReleases)
3419 struct stub_manager *stubmgr;
3420 struct apartment *apt;
3422 TRACE("pUnk=%p, fLock=%s, fLastUnlockReleases=%s\n",
3423 pUnk, fLock ? "TRUE" : "FALSE", fLastUnlockReleases ? "TRUE" : "FALSE");
3425 apt = COM_CurrentApt();
3426 if (!apt) return CO_E_NOTINITIALIZED;
3428 stubmgr = get_stub_manager_from_object(apt, pUnk);
3430 if (stubmgr)
3432 if (fLock)
3433 stub_manager_ext_addref(stubmgr, 1, FALSE);
3434 else
3435 stub_manager_ext_release(stubmgr, 1, FALSE, fLastUnlockReleases);
3437 stub_manager_int_release(stubmgr);
3439 return S_OK;
3441 else if (fLock)
3443 stubmgr = new_stub_manager(apt, pUnk);
3445 if (stubmgr)
3447 stub_manager_ext_addref(stubmgr, 1, FALSE);
3448 stub_manager_int_release(stubmgr);
3451 return S_OK;
3453 else
3455 WARN("stub object not found %p\n", pUnk);
3456 /* Note: native is pretty broken here because it just silently
3457 * fails, without returning an appropriate error code, making apps
3458 * think that the object was disconnected, when it actually wasn't */
3459 return S_OK;
3463 /***********************************************************************
3464 * CoInitializeWOW (OLE32.@)
3466 * WOW equivalent of CoInitialize?
3468 * PARAMS
3469 * x [I] Unknown.
3470 * y [I] Unknown.
3472 * RETURNS
3473 * Unknown.
3475 HRESULT WINAPI CoInitializeWOW(DWORD x,DWORD y)
3477 FIXME("(0x%08x,0x%08x),stub!\n",x,y);
3478 return 0;
3481 /***********************************************************************
3482 * CoGetState [OLE32.@]
3484 * Retrieves the thread state object previously stored by CoSetState().
3486 * PARAMS
3487 * ppv [I] Address where pointer to object will be stored.
3489 * RETURNS
3490 * Success: S_OK.
3491 * Failure: E_OUTOFMEMORY.
3493 * NOTES
3494 * Crashes on all invalid ppv addresses, including NULL.
3495 * If the function returns a non-NULL object then the caller must release its
3496 * reference on the object when the object is no longer required.
3498 * SEE ALSO
3499 * CoSetState().
3501 HRESULT WINAPI CoGetState(IUnknown ** ppv)
3503 struct oletls *info = COM_CurrentInfo();
3504 if (!info) return E_OUTOFMEMORY;
3506 *ppv = NULL;
3508 if (info->state)
3510 IUnknown_AddRef(info->state);
3511 *ppv = info->state;
3512 TRACE("apt->state=%p\n", info->state);
3515 return S_OK;
3518 /***********************************************************************
3519 * CoSetState [OLE32.@]
3521 * Sets the thread state object.
3523 * PARAMS
3524 * pv [I] Pointer to state object to be stored.
3526 * NOTES
3527 * The system keeps a reference on the object while the object stored.
3529 * RETURNS
3530 * Success: S_OK.
3531 * Failure: E_OUTOFMEMORY.
3533 HRESULT WINAPI CoSetState(IUnknown * pv)
3535 struct oletls *info = COM_CurrentInfo();
3536 if (!info) return E_OUTOFMEMORY;
3538 if (pv) IUnknown_AddRef(pv);
3540 if (info->state)
3542 TRACE("-- release %p now\n", info->state);
3543 IUnknown_Release(info->state);
3546 info->state = pv;
3548 return S_OK;
3552 /******************************************************************************
3553 * CoTreatAsClass [OLE32.@]
3555 * Sets the TreatAs value of a class.
3557 * PARAMS
3558 * clsidOld [I] Class to set TreatAs value on.
3559 * clsidNew [I] The class the clsidOld should be treated as.
3561 * RETURNS
3562 * Success: S_OK.
3563 * Failure: HRESULT code.
3565 * SEE ALSO
3566 * CoGetTreatAsClass
3568 HRESULT WINAPI CoTreatAsClass(REFCLSID clsidOld, REFCLSID clsidNew)
3570 static const WCHAR wszAutoTreatAs[] = {'A','u','t','o','T','r','e','a','t','A','s',0};
3571 static const WCHAR wszTreatAs[] = {'T','r','e','a','t','A','s',0};
3572 HKEY hkey = NULL;
3573 WCHAR szClsidNew[CHARS_IN_GUID];
3574 HRESULT res = S_OK;
3575 WCHAR auto_treat_as[CHARS_IN_GUID];
3576 LONG auto_treat_as_size = sizeof(auto_treat_as);
3577 CLSID id;
3579 res = COM_OpenKeyForCLSID(clsidOld, NULL, KEY_READ | KEY_WRITE, &hkey);
3580 if (FAILED(res))
3581 goto done;
3582 if (!memcmp( clsidOld, clsidNew, sizeof(*clsidOld) ))
3584 if (!RegQueryValueW(hkey, wszAutoTreatAs, auto_treat_as, &auto_treat_as_size) &&
3585 CLSIDFromString(auto_treat_as, &id) == S_OK)
3587 if (RegSetValueW(hkey, wszTreatAs, REG_SZ, auto_treat_as, sizeof(auto_treat_as)))
3589 res = REGDB_E_WRITEREGDB;
3590 goto done;
3593 else
3595 RegDeleteKeyW(hkey, wszTreatAs);
3596 goto done;
3599 else if (!StringFromGUID2(clsidNew, szClsidNew, ARRAYSIZE(szClsidNew)) &&
3600 !RegSetValueW(hkey, wszTreatAs, REG_SZ, szClsidNew, sizeof(szClsidNew)))
3602 res = REGDB_E_WRITEREGDB;
3603 goto done;
3606 done:
3607 if (hkey) RegCloseKey(hkey);
3608 return res;
3611 /******************************************************************************
3612 * CoGetTreatAsClass [OLE32.@]
3614 * Gets the TreatAs value of a class.
3616 * PARAMS
3617 * clsidOld [I] Class to get the TreatAs value of.
3618 * clsidNew [I] The class the clsidOld should be treated as.
3620 * RETURNS
3621 * Success: S_OK.
3622 * Failure: HRESULT code.
3624 * SEE ALSO
3625 * CoSetTreatAsClass
3627 HRESULT WINAPI CoGetTreatAsClass(REFCLSID clsidOld, LPCLSID clsidNew)
3629 static const WCHAR wszTreatAs[] = {'T','r','e','a','t','A','s',0};
3630 HKEY hkey = NULL;
3631 WCHAR szClsidNew[CHARS_IN_GUID];
3632 HRESULT res = S_OK;
3633 LONG len = sizeof(szClsidNew);
3635 TRACE("(%s,%p)\n", debugstr_guid(clsidOld), clsidNew);
3636 *clsidNew = *clsidOld; /* copy over old value */
3638 res = COM_OpenKeyForCLSID(clsidOld, wszTreatAs, KEY_READ, &hkey);
3639 if (FAILED(res))
3641 res = S_FALSE;
3642 goto done;
3644 if (RegQueryValueW(hkey, NULL, szClsidNew, &len))
3646 res = S_FALSE;
3647 goto done;
3649 res = CLSIDFromString(szClsidNew,clsidNew);
3650 if (FAILED(res))
3651 ERR("Failed CLSIDFromStringA(%s), hres 0x%08x\n", debugstr_w(szClsidNew), res);
3652 done:
3653 if (hkey) RegCloseKey(hkey);
3654 return res;
3657 /******************************************************************************
3658 * CoGetCurrentProcess [OLE32.@]
3660 * Gets the current process ID.
3662 * RETURNS
3663 * The current process ID.
3665 * NOTES
3666 * Is DWORD really the correct return type for this function?
3668 DWORD WINAPI CoGetCurrentProcess(void)
3670 return GetCurrentProcessId();
3673 /******************************************************************************
3674 * CoRegisterMessageFilter [OLE32.@]
3676 * Registers a message filter.
3678 * PARAMS
3679 * lpMessageFilter [I] Pointer to interface.
3680 * lplpMessageFilter [O] Indirect pointer to prior instance if non-NULL.
3682 * RETURNS
3683 * Success: S_OK.
3684 * Failure: HRESULT code.
3686 * NOTES
3687 * Both lpMessageFilter and lplpMessageFilter are optional. Passing in a NULL
3688 * lpMessageFilter removes the message filter.
3690 * If lplpMessageFilter is not NULL the previous message filter will be
3691 * returned in the memory pointer to this parameter and the caller is
3692 * responsible for releasing the object.
3694 * The current thread be in an apartment otherwise the function will crash.
3696 HRESULT WINAPI CoRegisterMessageFilter(
3697 LPMESSAGEFILTER lpMessageFilter,
3698 LPMESSAGEFILTER *lplpMessageFilter)
3700 struct apartment *apt;
3701 IMessageFilter *lpOldMessageFilter;
3703 TRACE("(%p, %p)\n", lpMessageFilter, lplpMessageFilter);
3705 apt = COM_CurrentApt();
3707 /* can't set a message filter in a multi-threaded apartment */
3708 if (!apt || apt->multi_threaded)
3710 WARN("can't set message filter in MTA or uninitialized apt\n");
3711 return CO_E_NOT_SUPPORTED;
3714 if (lpMessageFilter)
3715 IMessageFilter_AddRef(lpMessageFilter);
3717 EnterCriticalSection(&apt->cs);
3719 lpOldMessageFilter = apt->filter;
3720 apt->filter = lpMessageFilter;
3722 LeaveCriticalSection(&apt->cs);
3724 if (lplpMessageFilter)
3725 *lplpMessageFilter = lpOldMessageFilter;
3726 else if (lpOldMessageFilter)
3727 IMessageFilter_Release(lpOldMessageFilter);
3729 return S_OK;
3732 /***********************************************************************
3733 * CoIsOle1Class [OLE32.@]
3735 * Determines whether the specified class an OLE v1 class.
3737 * PARAMS
3738 * clsid [I] Class to test.
3740 * RETURNS
3741 * TRUE if the class is an OLE v1 class, or FALSE otherwise.
3743 BOOL WINAPI CoIsOle1Class(REFCLSID clsid)
3745 FIXME("%s\n", debugstr_guid(clsid));
3746 return FALSE;
3749 /***********************************************************************
3750 * IsEqualGUID [OLE32.@]
3752 * Compares two Unique Identifiers.
3754 * PARAMS
3755 * rguid1 [I] The first GUID to compare.
3756 * rguid2 [I] The other GUID to compare.
3758 * RETURNS
3759 * TRUE if equal
3761 #undef IsEqualGUID
3762 BOOL WINAPI IsEqualGUID(
3763 REFGUID rguid1,
3764 REFGUID rguid2)
3766 return !memcmp(rguid1,rguid2,sizeof(GUID));
3769 /***********************************************************************
3770 * CoInitializeSecurity [OLE32.@]
3772 HRESULT WINAPI CoInitializeSecurity(PSECURITY_DESCRIPTOR pSecDesc, LONG cAuthSvc,
3773 SOLE_AUTHENTICATION_SERVICE* asAuthSvc,
3774 void* pReserved1, DWORD dwAuthnLevel,
3775 DWORD dwImpLevel, void* pReserved2,
3776 DWORD dwCapabilities, void* pReserved3)
3778 FIXME("(%p,%d,%p,%p,%d,%d,%p,%d,%p) - stub!\n", pSecDesc, cAuthSvc,
3779 asAuthSvc, pReserved1, dwAuthnLevel, dwImpLevel, pReserved2,
3780 dwCapabilities, pReserved3);
3781 return S_OK;
3784 /***********************************************************************
3785 * CoSuspendClassObjects [OLE32.@]
3787 * Suspends all registered class objects to prevent further requests coming in
3788 * for those objects.
3790 * RETURNS
3791 * Success: S_OK.
3792 * Failure: HRESULT code.
3794 HRESULT WINAPI CoSuspendClassObjects(void)
3796 FIXME("\n");
3797 return S_OK;
3800 /***********************************************************************
3801 * CoAddRefServerProcess [OLE32.@]
3803 * Helper function for incrementing the reference count of a local-server
3804 * process.
3806 * RETURNS
3807 * New reference count.
3809 * SEE ALSO
3810 * CoReleaseServerProcess().
3812 ULONG WINAPI CoAddRefServerProcess(void)
3814 ULONG refs;
3816 TRACE("\n");
3818 EnterCriticalSection(&csRegisteredClassList);
3819 refs = ++s_COMServerProcessReferences;
3820 LeaveCriticalSection(&csRegisteredClassList);
3822 TRACE("refs before: %d\n", refs - 1);
3824 return refs;
3827 /***********************************************************************
3828 * CoReleaseServerProcess [OLE32.@]
3830 * Helper function for decrementing the reference count of a local-server
3831 * process.
3833 * RETURNS
3834 * New reference count.
3836 * NOTES
3837 * When reference count reaches 0, this function suspends all registered
3838 * classes so no new connections are accepted.
3840 * SEE ALSO
3841 * CoAddRefServerProcess(), CoSuspendClassObjects().
3843 ULONG WINAPI CoReleaseServerProcess(void)
3845 ULONG refs;
3847 TRACE("\n");
3849 EnterCriticalSection(&csRegisteredClassList);
3851 refs = --s_COMServerProcessReferences;
3852 /* FIXME: if (!refs) COM_SuspendClassObjects(); */
3854 LeaveCriticalSection(&csRegisteredClassList);
3856 TRACE("refs after: %d\n", refs);
3858 return refs;
3861 /***********************************************************************
3862 * CoIsHandlerConnected [OLE32.@]
3864 * Determines whether a proxy is connected to a remote stub.
3866 * PARAMS
3867 * pUnk [I] Pointer to object that may or may not be connected.
3869 * RETURNS
3870 * TRUE if pUnk is not a proxy or if pUnk is connected to a remote stub, or
3871 * FALSE otherwise.
3873 BOOL WINAPI CoIsHandlerConnected(IUnknown *pUnk)
3875 FIXME("%p\n", pUnk);
3877 return TRUE;
3880 /***********************************************************************
3881 * CoAllowSetForegroundWindow [OLE32.@]
3884 HRESULT WINAPI CoAllowSetForegroundWindow(IUnknown *pUnk, void *pvReserved)
3886 FIXME("(%p, %p): stub\n", pUnk, pvReserved);
3887 return S_OK;
3890 /***********************************************************************
3891 * CoQueryProxyBlanket [OLE32.@]
3893 * Retrieves the security settings being used by a proxy.
3895 * PARAMS
3896 * pProxy [I] Pointer to the proxy object.
3897 * pAuthnSvc [O] The type of authentication service.
3898 * pAuthzSvc [O] The type of authorization service.
3899 * ppServerPrincName [O] Optional. The server prinicple name.
3900 * pAuthnLevel [O] The authentication level.
3901 * pImpLevel [O] The impersonation level.
3902 * ppAuthInfo [O] Information specific to the authorization/authentication service.
3903 * pCapabilities [O] Flags affecting the security behaviour.
3905 * RETURNS
3906 * Success: S_OK.
3907 * Failure: HRESULT code.
3909 * SEE ALSO
3910 * CoCopyProxy, CoSetProxyBlanket.
3912 HRESULT WINAPI CoQueryProxyBlanket(IUnknown *pProxy, DWORD *pAuthnSvc,
3913 DWORD *pAuthzSvc, OLECHAR **ppServerPrincName, DWORD *pAuthnLevel,
3914 DWORD *pImpLevel, void **ppAuthInfo, DWORD *pCapabilities)
3916 IClientSecurity *pCliSec;
3917 HRESULT hr;
3919 TRACE("%p\n", pProxy);
3921 hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
3922 if (SUCCEEDED(hr))
3924 hr = IClientSecurity_QueryBlanket(pCliSec, pProxy, pAuthnSvc,
3925 pAuthzSvc, ppServerPrincName,
3926 pAuthnLevel, pImpLevel, ppAuthInfo,
3927 pCapabilities);
3928 IClientSecurity_Release(pCliSec);
3931 if (FAILED(hr)) ERR("-- failed with 0x%08x\n", hr);
3932 return hr;
3935 /***********************************************************************
3936 * CoSetProxyBlanket [OLE32.@]
3938 * Sets the security settings for a proxy.
3940 * PARAMS
3941 * pProxy [I] Pointer to the proxy object.
3942 * AuthnSvc [I] The type of authentication service.
3943 * AuthzSvc [I] The type of authorization service.
3944 * pServerPrincName [I] The server prinicple name.
3945 * AuthnLevel [I] The authentication level.
3946 * ImpLevel [I] The impersonation level.
3947 * pAuthInfo [I] Information specific to the authorization/authentication service.
3948 * Capabilities [I] Flags affecting the security behaviour.
3950 * RETURNS
3951 * Success: S_OK.
3952 * Failure: HRESULT code.
3954 * SEE ALSO
3955 * CoQueryProxyBlanket, CoCopyProxy.
3957 HRESULT WINAPI CoSetProxyBlanket(IUnknown *pProxy, DWORD AuthnSvc,
3958 DWORD AuthzSvc, OLECHAR *pServerPrincName, DWORD AuthnLevel,
3959 DWORD ImpLevel, void *pAuthInfo, DWORD Capabilities)
3961 IClientSecurity *pCliSec;
3962 HRESULT hr;
3964 TRACE("%p\n", pProxy);
3966 hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
3967 if (SUCCEEDED(hr))
3969 hr = IClientSecurity_SetBlanket(pCliSec, pProxy, AuthnSvc,
3970 AuthzSvc, pServerPrincName,
3971 AuthnLevel, ImpLevel, pAuthInfo,
3972 Capabilities);
3973 IClientSecurity_Release(pCliSec);
3976 if (FAILED(hr)) ERR("-- failed with 0x%08x\n", hr);
3977 return hr;
3980 /***********************************************************************
3981 * CoCopyProxy [OLE32.@]
3983 * Copies a proxy.
3985 * PARAMS
3986 * pProxy [I] Pointer to the proxy object.
3987 * ppCopy [O] Copy of the proxy.
3989 * RETURNS
3990 * Success: S_OK.
3991 * Failure: HRESULT code.
3993 * SEE ALSO
3994 * CoQueryProxyBlanket, CoSetProxyBlanket.
3996 HRESULT WINAPI CoCopyProxy(IUnknown *pProxy, IUnknown **ppCopy)
3998 IClientSecurity *pCliSec;
3999 HRESULT hr;
4001 TRACE("%p\n", pProxy);
4003 hr = IUnknown_QueryInterface(pProxy, &IID_IClientSecurity, (void **)&pCliSec);
4004 if (SUCCEEDED(hr))
4006 hr = IClientSecurity_CopyProxy(pCliSec, pProxy, ppCopy);
4007 IClientSecurity_Release(pCliSec);
4010 if (FAILED(hr)) ERR("-- failed with 0x%08x\n", hr);
4011 return hr;
4015 /***********************************************************************
4016 * CoGetCallContext [OLE32.@]
4018 * Gets the context of the currently executing server call in the current
4019 * thread.
4021 * PARAMS
4022 * riid [I] Context interface to return.
4023 * ppv [O] Pointer to memory that will receive the context on return.
4025 * RETURNS
4026 * Success: S_OK.
4027 * Failure: HRESULT code.
4029 HRESULT WINAPI CoGetCallContext(REFIID riid, void **ppv)
4031 struct oletls *info = COM_CurrentInfo();
4033 TRACE("(%s, %p)\n", debugstr_guid(riid), ppv);
4035 if (!info)
4036 return E_OUTOFMEMORY;
4038 if (!info->call_state)
4039 return RPC_E_CALL_COMPLETE;
4041 return IUnknown_QueryInterface(info->call_state, riid, ppv);
4044 /***********************************************************************
4045 * CoSwitchCallContext [OLE32.@]
4047 * Switches the context of the currently executing server call in the current
4048 * thread.
4050 * PARAMS
4051 * pObject [I] Pointer to new context object
4052 * ppOldObject [O] Pointer to memory that will receive old context object pointer
4054 * RETURNS
4055 * Success: S_OK.
4056 * Failure: HRESULT code.
4058 HRESULT WINAPI CoSwitchCallContext(IUnknown *pObject, IUnknown **ppOldObject)
4060 struct oletls *info = COM_CurrentInfo();
4062 TRACE("(%p, %p)\n", pObject, ppOldObject);
4064 if (!info)
4065 return E_OUTOFMEMORY;
4067 *ppOldObject = info->call_state;
4068 info->call_state = pObject; /* CoSwitchCallContext does not addref nor release objects */
4070 return S_OK;
4073 /***********************************************************************
4074 * CoQueryClientBlanket [OLE32.@]
4076 * Retrieves the authentication information about the client of the currently
4077 * executing server call in the current thread.
4079 * PARAMS
4080 * pAuthnSvc [O] Optional. The type of authentication service.
4081 * pAuthzSvc [O] Optional. The type of authorization service.
4082 * pServerPrincName [O] Optional. The server prinicple name.
4083 * pAuthnLevel [O] Optional. The authentication level.
4084 * pImpLevel [O] Optional. The impersonation level.
4085 * pPrivs [O] Optional. Information about the privileges of the client.
4086 * pCapabilities [IO] Optional. Flags affecting the security behaviour.
4088 * RETURNS
4089 * Success: S_OK.
4090 * Failure: HRESULT code.
4092 * SEE ALSO
4093 * CoImpersonateClient, CoRevertToSelf, CoGetCallContext.
4095 HRESULT WINAPI CoQueryClientBlanket(
4096 DWORD *pAuthnSvc,
4097 DWORD *pAuthzSvc,
4098 OLECHAR **pServerPrincName,
4099 DWORD *pAuthnLevel,
4100 DWORD *pImpLevel,
4101 RPC_AUTHZ_HANDLE *pPrivs,
4102 DWORD *pCapabilities)
4104 IServerSecurity *pSrvSec;
4105 HRESULT hr;
4107 TRACE("(%p, %p, %p, %p, %p, %p, %p)\n",
4108 pAuthnSvc, pAuthzSvc, pServerPrincName, pAuthnLevel, pImpLevel,
4109 pPrivs, pCapabilities);
4111 hr = CoGetCallContext(&IID_IServerSecurity, (void **)&pSrvSec);
4112 if (SUCCEEDED(hr))
4114 hr = IServerSecurity_QueryBlanket(
4115 pSrvSec, pAuthnSvc, pAuthzSvc, pServerPrincName, pAuthnLevel,
4116 pImpLevel, pPrivs, pCapabilities);
4117 IServerSecurity_Release(pSrvSec);
4120 return hr;
4123 /***********************************************************************
4124 * CoImpersonateClient [OLE32.@]
4126 * Impersonates the client of the currently executing server call in the
4127 * current thread.
4129 * PARAMS
4130 * None.
4132 * RETURNS
4133 * Success: S_OK.
4134 * Failure: HRESULT code.
4136 * NOTES
4137 * If this function fails then the current thread will not be impersonating
4138 * the client and all actions will take place on behalf of the server.
4139 * Therefore, it is important to check the return value from this function.
4141 * SEE ALSO
4142 * CoRevertToSelf, CoQueryClientBlanket, CoGetCallContext.
4144 HRESULT WINAPI CoImpersonateClient(void)
4146 IServerSecurity *pSrvSec;
4147 HRESULT hr;
4149 TRACE("\n");
4151 hr = CoGetCallContext(&IID_IServerSecurity, (void **)&pSrvSec);
4152 if (SUCCEEDED(hr))
4154 hr = IServerSecurity_ImpersonateClient(pSrvSec);
4155 IServerSecurity_Release(pSrvSec);
4158 return hr;
4161 /***********************************************************************
4162 * CoRevertToSelf [OLE32.@]
4164 * Ends the impersonation of the client of the currently executing server
4165 * call in the current thread.
4167 * PARAMS
4168 * None.
4170 * RETURNS
4171 * Success: S_OK.
4172 * Failure: HRESULT code.
4174 * SEE ALSO
4175 * CoImpersonateClient, CoQueryClientBlanket, CoGetCallContext.
4177 HRESULT WINAPI CoRevertToSelf(void)
4179 IServerSecurity *pSrvSec;
4180 HRESULT hr;
4182 TRACE("\n");
4184 hr = CoGetCallContext(&IID_IServerSecurity, (void **)&pSrvSec);
4185 if (SUCCEEDED(hr))
4187 hr = IServerSecurity_RevertToSelf(pSrvSec);
4188 IServerSecurity_Release(pSrvSec);
4191 return hr;
4194 static BOOL COM_PeekMessage(struct apartment *apt, MSG *msg)
4196 /* first try to retrieve messages for incoming COM calls to the apartment window */
4197 return PeekMessageW(msg, apt->win, 0, 0, PM_REMOVE|PM_NOYIELD) ||
4198 /* next retrieve other messages necessary for the app to remain responsive */
4199 PeekMessageW(msg, NULL, WM_DDE_FIRST, WM_DDE_LAST, PM_REMOVE|PM_NOYIELD) ||
4200 PeekMessageW(msg, NULL, 0, 0, PM_QS_PAINT|PM_QS_SENDMESSAGE|PM_REMOVE|PM_NOYIELD);
4203 /***********************************************************************
4204 * CoWaitForMultipleHandles [OLE32.@]
4206 * Waits for one or more handles to become signaled.
4208 * PARAMS
4209 * dwFlags [I] Flags. See notes.
4210 * dwTimeout [I] Timeout in milliseconds.
4211 * cHandles [I] Number of handles pointed to by pHandles.
4212 * pHandles [I] Handles to wait for.
4213 * lpdwindex [O] Index of handle that was signaled.
4215 * RETURNS
4216 * Success: S_OK.
4217 * Failure: RPC_S_CALLPENDING on timeout.
4219 * NOTES
4221 * The dwFlags parameter can be zero or more of the following:
4222 *| COWAIT_WAITALL - Wait for all of the handles to become signaled.
4223 *| COWAIT_ALERTABLE - Allows a queued APC to run during the wait.
4225 * SEE ALSO
4226 * MsgWaitForMultipleObjects, WaitForMultipleObjects.
4228 HRESULT WINAPI CoWaitForMultipleHandles(DWORD dwFlags, DWORD dwTimeout,
4229 ULONG cHandles, LPHANDLE pHandles, LPDWORD lpdwindex)
4231 HRESULT hr = S_OK;
4232 DWORD start_time = GetTickCount();
4233 APARTMENT *apt = COM_CurrentApt();
4234 BOOL message_loop = apt && !apt->multi_threaded;
4236 TRACE("(0x%08x, 0x%08x, %d, %p, %p)\n", dwFlags, dwTimeout, cHandles,
4237 pHandles, lpdwindex);
4239 while (TRUE)
4241 DWORD now = GetTickCount();
4242 DWORD res;
4244 if (now - start_time > dwTimeout)
4246 hr = RPC_S_CALLPENDING;
4247 break;
4250 if (message_loop)
4252 DWORD wait_flags = ((dwFlags & COWAIT_WAITALL) ? MWMO_WAITALL : 0) |
4253 ((dwFlags & COWAIT_ALERTABLE ) ? MWMO_ALERTABLE : 0);
4255 TRACE("waiting for rpc completion or window message\n");
4257 res = MsgWaitForMultipleObjectsEx(cHandles, pHandles,
4258 (dwTimeout == INFINITE) ? INFINITE : start_time + dwTimeout - now,
4259 QS_SENDMESSAGE | QS_ALLPOSTMESSAGE | QS_PAINT, wait_flags);
4261 if (res == WAIT_OBJECT_0 + cHandles) /* messages available */
4263 MSG msg;
4264 int count = 0;
4266 /* call message filter */
4268 if (COM_CurrentApt()->filter)
4270 PENDINGTYPE pendingtype =
4271 COM_CurrentInfo()->pending_call_count_server ?
4272 PENDINGTYPE_NESTED : PENDINGTYPE_TOPLEVEL;
4273 DWORD be_handled = IMessageFilter_MessagePending(
4274 COM_CurrentApt()->filter, 0 /* FIXME */,
4275 now - start_time, pendingtype);
4276 TRACE("IMessageFilter_MessagePending returned %d\n", be_handled);
4277 switch (be_handled)
4279 case PENDINGMSG_CANCELCALL:
4280 WARN("call canceled\n");
4281 hr = RPC_E_CALL_CANCELED;
4282 break;
4283 case PENDINGMSG_WAITNOPROCESS:
4284 case PENDINGMSG_WAITDEFPROCESS:
4285 default:
4286 /* FIXME: MSDN is very vague about the difference
4287 * between WAITNOPROCESS and WAITDEFPROCESS - there
4288 * appears to be none, so it is possibly a left-over
4289 * from the 16-bit world. */
4290 break;
4294 /* some apps (e.g. Visio 2010) don't handle WM_PAINT properly and loop forever,
4295 * so after processing 100 messages we go back to checking the wait handles */
4296 while (count++ < 100 && COM_PeekMessage(apt, &msg))
4298 TRACE("received message whilst waiting for RPC: 0x%04x\n", msg.message);
4299 TranslateMessage(&msg);
4300 DispatchMessageW(&msg);
4301 if (msg.message == WM_QUIT)
4303 TRACE("resending WM_QUIT to outer message loop\n");
4304 PostQuitMessage(msg.wParam);
4305 /* no longer need to process messages */
4306 message_loop = FALSE;
4307 break;
4310 continue;
4313 else
4315 TRACE("waiting for rpc completion\n");
4317 res = WaitForMultipleObjectsEx(cHandles, pHandles, (dwFlags & COWAIT_WAITALL) != 0,
4318 (dwTimeout == INFINITE) ? INFINITE : start_time + dwTimeout - now,
4319 (dwFlags & COWAIT_ALERTABLE) != 0);
4322 switch (res)
4324 case WAIT_TIMEOUT:
4325 hr = RPC_S_CALLPENDING;
4326 break;
4327 case WAIT_FAILED:
4328 hr = HRESULT_FROM_WIN32( GetLastError() );
4329 break;
4330 default:
4331 *lpdwindex = res;
4332 break;
4334 break;
4336 TRACE("-- 0x%08x\n", hr);
4337 return hr;
4341 /***********************************************************************
4342 * CoGetObject [OLE32.@]
4344 * Gets the object named by converting the name to a moniker and binding to it.
4346 * PARAMS
4347 * pszName [I] String representing the object.
4348 * pBindOptions [I] Parameters affecting the binding to the named object.
4349 * riid [I] Interface to bind to on the objecct.
4350 * ppv [O] On output, the interface riid of the object represented
4351 * by pszName.
4353 * RETURNS
4354 * Success: S_OK.
4355 * Failure: HRESULT code.
4357 * SEE ALSO
4358 * MkParseDisplayName.
4360 HRESULT WINAPI CoGetObject(LPCWSTR pszName, BIND_OPTS *pBindOptions,
4361 REFIID riid, void **ppv)
4363 IBindCtx *pbc;
4364 HRESULT hr;
4366 *ppv = NULL;
4368 hr = CreateBindCtx(0, &pbc);
4369 if (SUCCEEDED(hr))
4371 if (pBindOptions)
4372 hr = IBindCtx_SetBindOptions(pbc, pBindOptions);
4374 if (SUCCEEDED(hr))
4376 ULONG chEaten;
4377 IMoniker *pmk;
4379 hr = MkParseDisplayName(pbc, pszName, &chEaten, &pmk);
4380 if (SUCCEEDED(hr))
4382 hr = IMoniker_BindToObject(pmk, pbc, NULL, riid, ppv);
4383 IMoniker_Release(pmk);
4387 IBindCtx_Release(pbc);
4389 return hr;
4392 /***********************************************************************
4393 * CoRegisterChannelHook [OLE32.@]
4395 * Registers a process-wide hook that is called during ORPC calls.
4397 * PARAMS
4398 * guidExtension [I] GUID of the channel hook to register.
4399 * pChannelHook [I] Channel hook object to register.
4401 * RETURNS
4402 * Success: S_OK.
4403 * Failure: HRESULT code.
4405 HRESULT WINAPI CoRegisterChannelHook(REFGUID guidExtension, IChannelHook *pChannelHook)
4407 TRACE("(%s, %p)\n", debugstr_guid(guidExtension), pChannelHook);
4409 return RPC_RegisterChannelHook(guidExtension, pChannelHook);
4412 typedef struct Context
4414 IComThreadingInfo IComThreadingInfo_iface;
4415 IContextCallback IContextCallback_iface;
4416 IObjContext IObjContext_iface;
4417 LONG refs;
4418 APTTYPE apttype;
4419 } Context;
4421 static inline Context *impl_from_IComThreadingInfo( IComThreadingInfo *iface )
4423 return CONTAINING_RECORD(iface, Context, IComThreadingInfo_iface);
4426 static inline Context *impl_from_IContextCallback( IContextCallback *iface )
4428 return CONTAINING_RECORD(iface, Context, IContextCallback_iface);
4431 static inline Context *impl_from_IObjContext( IObjContext *iface )
4433 return CONTAINING_RECORD(iface, Context, IObjContext_iface);
4436 static HRESULT Context_QueryInterface(Context *iface, REFIID riid, LPVOID *ppv)
4438 *ppv = NULL;
4440 if (IsEqualIID(riid, &IID_IComThreadingInfo) ||
4441 IsEqualIID(riid, &IID_IUnknown))
4443 *ppv = &iface->IComThreadingInfo_iface;
4445 else if (IsEqualIID(riid, &IID_IContextCallback))
4447 *ppv = &iface->IContextCallback_iface;
4449 else if (IsEqualIID(riid, &IID_IObjContext))
4451 *ppv = &iface->IObjContext_iface;
4454 if (*ppv)
4456 IUnknown_AddRef((IUnknown*)*ppv);
4457 return S_OK;
4460 FIXME("interface not implemented %s\n", debugstr_guid(riid));
4461 return E_NOINTERFACE;
4464 static ULONG Context_AddRef(Context *This)
4466 return InterlockedIncrement(&This->refs);
4469 static ULONG Context_Release(Context *This)
4471 ULONG refs = InterlockedDecrement(&This->refs);
4472 if (!refs)
4473 HeapFree(GetProcessHeap(), 0, This);
4474 return refs;
4477 static HRESULT WINAPI Context_CTI_QueryInterface(IComThreadingInfo *iface, REFIID riid, LPVOID *ppv)
4479 Context *This = impl_from_IComThreadingInfo(iface);
4480 return Context_QueryInterface(This, riid, ppv);
4483 static ULONG WINAPI Context_CTI_AddRef(IComThreadingInfo *iface)
4485 Context *This = impl_from_IComThreadingInfo(iface);
4486 return Context_AddRef(This);
4489 static ULONG WINAPI Context_CTI_Release(IComThreadingInfo *iface)
4491 Context *This = impl_from_IComThreadingInfo(iface);
4492 return Context_Release(This);
4495 static HRESULT WINAPI Context_CTI_GetCurrentApartmentType(IComThreadingInfo *iface, APTTYPE *apttype)
4497 Context *This = impl_from_IComThreadingInfo(iface);
4499 TRACE("(%p)\n", apttype);
4501 *apttype = This->apttype;
4502 return S_OK;
4505 static HRESULT WINAPI Context_CTI_GetCurrentThreadType(IComThreadingInfo *iface, THDTYPE *thdtype)
4507 Context *This = impl_from_IComThreadingInfo(iface);
4509 TRACE("(%p)\n", thdtype);
4511 switch (This->apttype)
4513 case APTTYPE_STA:
4514 case APTTYPE_MAINSTA:
4515 *thdtype = THDTYPE_PROCESSMESSAGES;
4516 break;
4517 default:
4518 *thdtype = THDTYPE_BLOCKMESSAGES;
4519 break;
4521 return S_OK;
4524 static HRESULT WINAPI Context_CTI_GetCurrentLogicalThreadId(IComThreadingInfo *iface, GUID *logical_thread_id)
4526 FIXME("(%p): stub\n", logical_thread_id);
4527 return E_NOTIMPL;
4530 static HRESULT WINAPI Context_CTI_SetCurrentLogicalThreadId(IComThreadingInfo *iface, REFGUID logical_thread_id)
4532 FIXME("(%s): stub\n", debugstr_guid(logical_thread_id));
4533 return E_NOTIMPL;
4536 static const IComThreadingInfoVtbl Context_Threading_Vtbl =
4538 Context_CTI_QueryInterface,
4539 Context_CTI_AddRef,
4540 Context_CTI_Release,
4541 Context_CTI_GetCurrentApartmentType,
4542 Context_CTI_GetCurrentThreadType,
4543 Context_CTI_GetCurrentLogicalThreadId,
4544 Context_CTI_SetCurrentLogicalThreadId
4547 static HRESULT WINAPI Context_CC_QueryInterface(IContextCallback *iface, REFIID riid, LPVOID *ppv)
4549 Context *This = impl_from_IContextCallback(iface);
4550 return Context_QueryInterface(This, riid, ppv);
4553 static ULONG WINAPI Context_CC_AddRef(IContextCallback *iface)
4555 Context *This = impl_from_IContextCallback(iface);
4556 return Context_AddRef(This);
4559 static ULONG WINAPI Context_CC_Release(IContextCallback *iface)
4561 Context *This = impl_from_IContextCallback(iface);
4562 return Context_Release(This);
4565 static HRESULT WINAPI Context_CC_ContextCallback(IContextCallback *iface, PFNCONTEXTCALL pCallback,
4566 ComCallData *param, REFIID riid, int method, IUnknown *punk)
4568 Context *This = impl_from_IContextCallback(iface);
4570 FIXME("(%p/%p)->(%p, %p, %s, %d, %p)\n", This, iface, pCallback, param, debugstr_guid(riid), method, punk);
4571 return E_NOTIMPL;
4574 static const IContextCallbackVtbl Context_Callback_Vtbl =
4576 Context_CC_QueryInterface,
4577 Context_CC_AddRef,
4578 Context_CC_Release,
4579 Context_CC_ContextCallback
4582 static HRESULT WINAPI Context_OC_QueryInterface(IObjContext *iface, REFIID riid, LPVOID *ppv)
4584 Context *This = impl_from_IObjContext(iface);
4585 return Context_QueryInterface(This, riid, ppv);
4588 static ULONG WINAPI Context_OC_AddRef(IObjContext *iface)
4590 Context *This = impl_from_IObjContext(iface);
4591 return Context_AddRef(This);
4594 static ULONG WINAPI Context_OC_Release(IObjContext *iface)
4596 Context *This = impl_from_IObjContext(iface);
4597 return Context_Release(This);
4600 static HRESULT WINAPI Context_OC_SetProperty(IObjContext *iface, REFGUID propid, CPFLAGS flags, IUnknown *punk)
4602 Context *This = impl_from_IObjContext(iface);
4604 FIXME("(%p/%p)->(%s, %x, %p)\n", This, iface, debugstr_guid(propid), flags, punk);
4605 return E_NOTIMPL;
4608 static HRESULT WINAPI Context_OC_RemoveProperty(IObjContext *iface, REFGUID propid)
4610 Context *This = impl_from_IObjContext(iface);
4612 FIXME("(%p/%p)->(%s)\n", This, iface, debugstr_guid(propid));
4613 return E_NOTIMPL;
4616 static HRESULT WINAPI Context_OC_GetProperty(IObjContext *iface, REFGUID propid, CPFLAGS *flags, IUnknown **punk)
4618 Context *This = impl_from_IObjContext(iface);
4620 FIXME("(%p/%p)->(%s, %p, %p)\n", This, iface, debugstr_guid(propid), flags, punk);
4621 return E_NOTIMPL;
4624 static HRESULT WINAPI Context_OC_EnumContextProps(IObjContext *iface, IEnumContextProps **props)
4626 Context *This = impl_from_IObjContext(iface);
4628 FIXME("(%p/%p)->(%p)\n", This, iface, props);
4629 return E_NOTIMPL;
4632 static void WINAPI Context_OC_Reserved1(IObjContext *iface)
4634 Context *This = impl_from_IObjContext(iface);
4635 FIXME("(%p/%p)\n", This, iface);
4638 static void WINAPI Context_OC_Reserved2(IObjContext *iface)
4640 Context *This = impl_from_IObjContext(iface);
4641 FIXME("(%p/%p)\n", This, iface);
4644 static void WINAPI Context_OC_Reserved3(IObjContext *iface)
4646 Context *This = impl_from_IObjContext(iface);
4647 FIXME("(%p/%p)\n", This, iface);
4650 static void WINAPI Context_OC_Reserved4(IObjContext *iface)
4652 Context *This = impl_from_IObjContext(iface);
4653 FIXME("(%p/%p)\n", This, iface);
4656 static void WINAPI Context_OC_Reserved5(IObjContext *iface)
4658 Context *This = impl_from_IObjContext(iface);
4659 FIXME("(%p/%p)\n", This, iface);
4662 static void WINAPI Context_OC_Reserved6(IObjContext *iface)
4664 Context *This = impl_from_IObjContext(iface);
4665 FIXME("(%p/%p)\n", This, iface);
4668 static void WINAPI Context_OC_Reserved7(IObjContext *iface)
4670 Context *This = impl_from_IObjContext(iface);
4671 FIXME("(%p/%p)\n", This, iface);
4674 static const IObjContextVtbl Context_Object_Vtbl =
4676 Context_OC_QueryInterface,
4677 Context_OC_AddRef,
4678 Context_OC_Release,
4679 Context_OC_SetProperty,
4680 Context_OC_RemoveProperty,
4681 Context_OC_GetProperty,
4682 Context_OC_EnumContextProps,
4683 Context_OC_Reserved1,
4684 Context_OC_Reserved2,
4685 Context_OC_Reserved3,
4686 Context_OC_Reserved4,
4687 Context_OC_Reserved5,
4688 Context_OC_Reserved6,
4689 Context_OC_Reserved7
4692 /***********************************************************************
4693 * CoGetObjectContext [OLE32.@]
4695 * Retrieves an object associated with the current context (i.e. apartment).
4697 * PARAMS
4698 * riid [I] ID of the interface of the object to retrieve.
4699 * ppv [O] Address where object will be stored on return.
4701 * RETURNS
4702 * Success: S_OK.
4703 * Failure: HRESULT code.
4705 HRESULT WINAPI CoGetObjectContext(REFIID riid, void **ppv)
4707 APARTMENT *apt = COM_CurrentApt();
4708 Context *context;
4709 HRESULT hr;
4711 TRACE("(%s, %p)\n", debugstr_guid(riid), ppv);
4713 *ppv = NULL;
4714 if (!apt)
4716 if (!(apt = apartment_find_multi_threaded()))
4718 ERR("apartment not initialised\n");
4719 return CO_E_NOTINITIALIZED;
4721 apartment_release(apt);
4724 context = HeapAlloc(GetProcessHeap(), 0, sizeof(*context));
4725 if (!context)
4726 return E_OUTOFMEMORY;
4728 context->IComThreadingInfo_iface.lpVtbl = &Context_Threading_Vtbl;
4729 context->IContextCallback_iface.lpVtbl = &Context_Callback_Vtbl;
4730 context->IObjContext_iface.lpVtbl = &Context_Object_Vtbl;
4731 context->refs = 1;
4732 if (apt->multi_threaded)
4733 context->apttype = APTTYPE_MTA;
4734 else if (apt->main)
4735 context->apttype = APTTYPE_MAINSTA;
4736 else
4737 context->apttype = APTTYPE_STA;
4739 hr = IUnknown_QueryInterface((IUnknown *)&context->IComThreadingInfo_iface, riid, ppv);
4740 IUnknown_Release((IUnknown *)&context->IComThreadingInfo_iface);
4742 return hr;
4746 /***********************************************************************
4747 * CoGetContextToken [OLE32.@]
4749 HRESULT WINAPI CoGetContextToken( ULONG_PTR *token )
4751 struct oletls *info = COM_CurrentInfo();
4753 TRACE("(%p)\n", token);
4755 if (!info)
4756 return E_OUTOFMEMORY;
4758 if (!info->apt)
4760 APARTMENT *apt;
4761 if (!(apt = apartment_find_multi_threaded()))
4763 ERR("apartment not initialised\n");
4764 return CO_E_NOTINITIALIZED;
4766 apartment_release(apt);
4769 if (!token)
4770 return E_POINTER;
4772 if (!info->context_token)
4774 HRESULT hr;
4775 IObjContext *ctx;
4777 hr = CoGetObjectContext(&IID_IObjContext, (void **)&ctx);
4778 if (FAILED(hr)) return hr;
4779 info->context_token = ctx;
4782 *token = (ULONG_PTR)info->context_token;
4783 TRACE("apt->context_token=%p\n", info->context_token);
4785 return S_OK;
4788 /***********************************************************************
4789 * CoGetDefaultContext [OLE32.@]
4791 HRESULT WINAPI CoGetDefaultContext(APTTYPE type, REFIID riid, LPVOID *ppv)
4793 FIXME("%d %s %p stub\n", type, debugstr_guid(riid), ppv);
4794 return E_NOINTERFACE;
4797 HRESULT Handler_DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv)
4799 static const WCHAR wszInprocHandler32[] = {'I','n','p','r','o','c','H','a','n','d','l','e','r','3','2',0};
4800 HKEY hkey;
4801 HRESULT hres;
4803 hres = COM_OpenKeyForCLSID(rclsid, wszInprocHandler32, KEY_READ, &hkey);
4804 if (SUCCEEDED(hres))
4806 struct class_reg_data regdata;
4807 WCHAR dllpath[MAX_PATH+1];
4809 regdata.u.hkey = hkey;
4810 regdata.hkey = TRUE;
4812 if (COM_RegReadPath(&regdata, dllpath, ARRAYSIZE(dllpath)) == ERROR_SUCCESS)
4814 static const WCHAR wszOle32[] = {'o','l','e','3','2','.','d','l','l',0};
4815 if (!strcmpiW(dllpath, wszOle32))
4817 RegCloseKey(hkey);
4818 return HandlerCF_Create(rclsid, riid, ppv);
4821 else
4822 WARN("not creating object for inproc handler path %s\n", debugstr_w(dllpath));
4823 RegCloseKey(hkey);
4826 return CLASS_E_CLASSNOTAVAILABLE;
4829 /***********************************************************************
4830 * DllMain (OLE32.@)
4832 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID reserved)
4834 TRACE("%p 0x%x %p\n", hinstDLL, fdwReason, reserved);
4836 switch(fdwReason) {
4837 case DLL_PROCESS_ATTACH:
4838 hProxyDll = hinstDLL;
4839 break;
4841 case DLL_PROCESS_DETACH:
4842 if (reserved) break;
4843 release_std_git();
4844 UnregisterClassW( wszAptWinClass, hProxyDll );
4845 RPC_UnregisterAllChannelHooks();
4846 COMPOBJ_DllList_Free();
4847 DeleteCriticalSection(&csRegisteredClassList);
4848 DeleteCriticalSection(&csApartment);
4849 break;
4851 case DLL_THREAD_DETACH:
4852 COM_TlsDestroy();
4853 break;
4855 return TRUE;
4858 /***********************************************************************
4859 * DllRegisterServer (OLE32.@)
4861 HRESULT WINAPI DllRegisterServer(void)
4863 return OLE32_DllRegisterServer();
4866 /***********************************************************************
4867 * DllUnregisterServer (OLE32.@)
4869 HRESULT WINAPI DllUnregisterServer(void)
4871 return OLE32_DllUnregisterServer();