Remove the win32 debug channel, misc cleanup of debugging code.
[wine/dcerpc.git] / dlls / ole32 / compobj.c
blob2e6e6db7ff5bc8b59c2760025e493434f99ff564
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
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 #include "config.h"
27 #include <stdlib.h>
28 #include <stdarg.h>
29 #include <stdio.h>
30 #include <string.h>
31 #include <assert.h>
33 #define NONAMELESSUNION
34 #define NONAMELESSSTRUCT
35 #include "windef.h"
36 #include "winbase.h"
37 #include "winuser.h"
38 #include "objbase.h"
39 #include "ole2.h"
40 #include "ole2ver.h"
41 #include "rpc.h"
42 #include "winerror.h"
43 #include "winreg.h"
44 #include "wownt32.h"
45 #include "wine/unicode.h"
46 #include "objbase.h"
47 #include "ole32_main.h"
48 #include "compobj_private.h"
50 #include "wine/debug.h"
52 WINE_DEFAULT_DEBUG_CHANNEL(ole);
54 typedef LPCSTR LPCOLESTR16;
56 /****************************************************************************
57 * This section defines variables internal to the COM module.
59 * TODO: Most of these things will have to be made thread-safe.
61 HINSTANCE COMPOBJ_hInstance32 = 0;
63 static HRESULT COM_GetRegisteredClassObject(REFCLSID rclsid, DWORD dwClsContext, LPUNKNOWN* ppUnk);
64 static void COM_RevokeAllClasses();
65 static void COM_ExternalLockFreeList();
67 const CLSID CLSID_StdGlobalInterfaceTable = { 0x00000323, 0, 0, {0xc0, 0, 0, 0, 0, 0, 0, 0x46} };
69 APARTMENT MTA, *apts;
71 static CRITICAL_SECTION csApartment;
72 static CRITICAL_SECTION_DEBUG critsect_debug =
74 0, 0, &csApartment,
75 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
76 0, 0, { 0, (DWORD)(__FILE__ ": csApartment") }
78 static CRITICAL_SECTION csApartment = { &critsect_debug, -1, 0, 0, 0, 0 };
81 * This lock count counts the number of times CoInitialize is called. It is
82 * decreased every time CoUninitialize is called. When it hits 0, the COM
83 * libraries are freed
85 static LONG s_COMLockCount = 0;
88 * This linked list contains the list of registered class objects. These
89 * are mostly used to register the factories for out-of-proc servers of OLE
90 * objects.
92 * TODO: Make this data structure aware of inter-process communication. This
93 * means that parts of this will be exported to the Wine Server.
95 typedef struct tagRegisteredClass
97 CLSID classIdentifier;
98 LPUNKNOWN classObject;
99 DWORD runContext;
100 DWORD connectFlags;
101 DWORD dwCookie;
102 HANDLE hThread; /* only for localserver */
103 struct tagRegisteredClass* nextClass;
104 } RegisteredClass;
106 static RegisteredClass* firstRegisteredClass = NULL;
108 static CRITICAL_SECTION csRegisteredClassList;
109 static CRITICAL_SECTION_DEBUG class_cs_debug =
111 0, 0, &csRegisteredClassList,
112 { &class_cs_debug.ProcessLocksList, &class_cs_debug.ProcessLocksList },
113 0, 0, { 0, (DWORD)(__FILE__ ": csRegisteredClassList") }
115 static CRITICAL_SECTION csRegisteredClassList = { &class_cs_debug, -1, 0, 0, 0, 0 };
117 /*****************************************************************************
118 * This section contains OpenDllList definitions
120 * The OpenDllList contains only handles of dll loaded by CoGetClassObject or
121 * other functions what do LoadLibrary _without_ giving back a HMODULE.
122 * Without this list these handles would be freed never.
124 * FIXME: a DLL what says OK whenn asked for unloading is unloaded in the
125 * next unload-call but not before 600 sec.
128 typedef struct tagOpenDll {
129 HINSTANCE hLibrary;
130 struct tagOpenDll *next;
131 } OpenDll;
133 static OpenDll *openDllList = NULL; /* linked list of open dlls */
135 static CRITICAL_SECTION csOpenDllList;
136 static CRITICAL_SECTION_DEBUG dll_cs_debug =
138 0, 0, &csOpenDllList,
139 { &dll_cs_debug.ProcessLocksList, &dll_cs_debug.ProcessLocksList },
140 0, 0, { 0, (DWORD)(__FILE__ ": csOpenDllList") }
142 static CRITICAL_SECTION csOpenDllList = { &dll_cs_debug, -1, 0, 0, 0, 0 };
144 static const char aptWinClass[] = "WINE_OLE32_APT_CLASS";
145 static LRESULT CALLBACK COM_AptWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
147 static void COMPOBJ_DLLList_Add(HANDLE hLibrary);
148 static void COMPOBJ_DllList_FreeUnused(int Timeout);
151 /******************************************************************************
152 * Initialize/Unitialize threading stuff.
154 void COMPOBJ_InitProcess( void )
156 WNDCLASSA wclass;
158 memset(&wclass, 0, sizeof(wclass));
159 wclass.lpfnWndProc = &COM_AptWndProc;
160 wclass.hInstance = OLE32_hInstance;
161 wclass.lpszClassName = aptWinClass;
162 RegisterClassA(&wclass);
165 void COMPOBJ_UninitProcess( void )
167 UnregisterClassA(aptWinClass, OLE32_hInstance);
170 /******************************************************************************
171 * Manage apartments.
173 static void COM_InitMTA(void)
175 /* FIXME: how does windoze create OXIDs?
176 * this method will only work for local RPC */
177 MTA.oxid = ((OXID)GetCurrentProcessId() << 32);
178 InitializeCriticalSection(&MTA.cs);
181 static void COM_UninitMTA(void)
183 DeleteCriticalSection(&MTA.cs);
184 MTA.oxid = 0;
187 /* creates an apartment structure which stores OLE thread-local
188 * information. Call with COINIT_UNINITIALIZED to create an apartment
189 * that will be initialized with a model later. Note: do not call
190 * with COINIT_UNINITIALIZED if the apartment has already been initialized
191 * with a different COINIT value */
192 APARTMENT* COM_CreateApartment(DWORD model)
194 APARTMENT *apt;
195 BOOL create = (NtCurrentTeb()->ReservedForOle == NULL);
197 if (create)
199 apt = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(APARTMENT));
200 apt->tid = GetCurrentThreadId();
201 DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
202 GetCurrentProcess(), &apt->thread,
203 THREAD_ALL_ACCESS, FALSE, 0);
205 else
206 apt = NtCurrentTeb()->ReservedForOle;
207 apt->model = model;
208 if (model & COINIT_APARTMENTTHREADED) {
209 /* FIXME: how does windoze create OXIDs? */
210 apt->oxid = MTA.oxid | GetCurrentThreadId();
211 apt->win = CreateWindowA(aptWinClass, NULL, 0,
212 0, 0, 0, 0,
213 0, 0, OLE32_hInstance, NULL);
214 InitializeCriticalSection(&apt->cs);
216 else if (!(model & COINIT_UNINITIALIZED)) {
217 apt->parent = &MTA;
218 apt->oxid = MTA.oxid;
220 EnterCriticalSection(&csApartment);
221 if (create)
223 if (apts) apts->prev = apt;
224 apt->next = apts;
225 apts = apt;
227 LeaveCriticalSection(&csApartment);
228 NtCurrentTeb()->ReservedForOle = apt;
229 return apt;
232 static void COM_DestroyApartment(APARTMENT *apt)
234 EnterCriticalSection(&csApartment);
235 if (apt->prev) apt->prev->next = apt->next;
236 if (apt->next) apt->next->prev = apt->prev;
237 if (apts == apt) apts = apt->next;
238 apt->prev = NULL; apt->next = NULL;
239 LeaveCriticalSection(&csApartment);
240 if (apt->model & COINIT_APARTMENTTHREADED) {
241 if (apt->win) DestroyWindow(apt->win);
242 DeleteCriticalSection(&apt->cs);
244 CloseHandle(apt->thread);
245 HeapFree(GetProcessHeap(), 0, apt);
248 HWND COM_GetApartmentWin(OXID oxid)
250 APARTMENT *apt;
251 HWND win = 0;
253 EnterCriticalSection(&csApartment);
254 apt = apts;
255 while (apt && apt->oxid != oxid) apt = apt->next;
256 if (apt) win = apt->win;
257 LeaveCriticalSection(&csApartment);
258 return win;
261 static LRESULT CALLBACK COM_AptWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
263 return DefWindowProcA(hWnd, msg, wParam, lParam);
266 /*****************************************************************************
267 * This section contains OpenDllList implemantation
270 static void COMPOBJ_DLLList_Add(HANDLE hLibrary)
272 OpenDll *ptr;
273 OpenDll *tmp;
275 TRACE("\n");
277 EnterCriticalSection( &csOpenDllList );
279 if (openDllList == NULL) {
280 /* empty list -- add first node */
281 openDllList = (OpenDll*)HeapAlloc(GetProcessHeap(),0, sizeof(OpenDll));
282 openDllList->hLibrary=hLibrary;
283 openDllList->next = NULL;
284 } else {
285 /* search for this dll */
286 int found = FALSE;
287 for (ptr = openDllList; ptr->next != NULL; ptr=ptr->next) {
288 if (ptr->hLibrary == hLibrary) {
289 found = TRUE;
290 break;
293 if (!found) {
294 /* dll not found, add it */
295 tmp = openDllList;
296 openDllList = (OpenDll*)HeapAlloc(GetProcessHeap(),0, sizeof(OpenDll));
297 openDllList->hLibrary = hLibrary;
298 openDllList->next = tmp;
302 LeaveCriticalSection( &csOpenDllList );
305 static void COMPOBJ_DllList_FreeUnused(int Timeout)
307 OpenDll *curr, *next, *prev = NULL;
308 typedef HRESULT(*DllCanUnloadNowFunc)(void);
309 DllCanUnloadNowFunc DllCanUnloadNow;
311 TRACE("\n");
313 EnterCriticalSection( &csOpenDllList );
315 for (curr = openDllList; curr != NULL; ) {
316 DllCanUnloadNow = (DllCanUnloadNowFunc) GetProcAddress(curr->hLibrary, "DllCanUnloadNow");
318 if ( (DllCanUnloadNow != NULL) && (DllCanUnloadNow() == S_OK) ) {
319 next = curr->next;
321 TRACE("freeing %p\n", curr->hLibrary);
322 FreeLibrary(curr->hLibrary);
324 HeapFree(GetProcessHeap(), 0, curr);
325 if (curr == openDllList) {
326 openDllList = next;
327 } else {
328 prev->next = next;
331 curr = next;
332 } else {
333 prev = curr;
334 curr = curr->next;
338 LeaveCriticalSection( &csOpenDllList );
341 /******************************************************************************
342 * CoBuildVersion [COMPOBJ.1]
343 * CoBuildVersion [OLE32.@]
345 * RETURNS
346 * Current build version, hiword is majornumber, loword is minornumber
348 DWORD WINAPI CoBuildVersion(void)
350 TRACE("Returning version %d, build %d.\n", rmm, rup);
351 return (rmm<<16)+rup;
354 /******************************************************************************
355 * CoInitialize [OLE32.@]
357 * Initializes the COM libraries.
359 * See CoInitializeEx
361 HRESULT WINAPI CoInitialize(
362 LPVOID lpReserved /* [in] pointer to win32 malloc interface
363 (obsolete, should be NULL) */
367 * Just delegate to the newer method.
369 return CoInitializeEx(lpReserved, COINIT_APARTMENTTHREADED);
372 /******************************************************************************
373 * CoInitializeEx [OLE32.@]
375 * Initializes the COM libraries. The behavior used to set the win32 IMalloc
376 * used for memory management is obsolete.
378 * RETURNS
379 * S_OK if successful,
380 * S_FALSE if this function was called already.
381 * RPC_E_CHANGED_MODE if a previous call to CoInitialize specified another
382 * threading model.
384 HRESULT WINAPI CoInitializeEx(
385 LPVOID lpReserved, /* [in] pointer to win32 malloc interface
386 (obsolete, should be NULL) */
387 DWORD dwCoInit /* [in] A value from COINIT specifies the threading model */
390 HRESULT hr = S_OK;
391 APARTMENT *apt;
393 TRACE("(%p, %x)\n", lpReserved, (int)dwCoInit);
395 if (lpReserved!=NULL)
397 ERR("(%p, %x) - Bad parameter passed-in %p, must be an old Windows Application\n", lpReserved, (int)dwCoInit, lpReserved);
400 apt = NtCurrentTeb()->ReservedForOle;
401 if (apt && !(apt->model == COINIT_UNINITIALIZED))
403 if (dwCoInit != apt->model)
405 WARN("Apartment threading model already initialized with another model\n");
406 return RPC_E_CHANGED_MODE;
408 hr = S_FALSE;
410 else
411 hr = S_OK;
414 * Check the lock count. If this is the first time going through the initialize
415 * process, we have to initialize the libraries.
417 * And crank-up that lock count.
419 if (InterlockedExchangeAdd(&s_COMLockCount,1)==0)
422 * Initialize the various COM libraries and data structures.
424 TRACE("() - Initializing the COM libraries\n");
426 COM_InitMTA();
428 RunningObjectTableImpl_Initialize();
431 if (!apt || apt->model == COINIT_UNINITIALIZED) apt = COM_CreateApartment(dwCoInit);
433 InterlockedIncrement(&apt->inits);
434 if (hr == S_OK) NtCurrentTeb()->ReservedForOle = apt;
436 return hr;
439 /***********************************************************************
440 * CoUninitialize [OLE32.@]
442 * This method will release the COM libraries.
444 * See the windows documentation for more details.
446 void WINAPI CoUninitialize(void)
448 LONG lCOMRefCnt;
449 APARTMENT *apt;
451 TRACE("()\n");
453 apt = NtCurrentTeb()->ReservedForOle;
454 if (!apt) return;
455 if (InterlockedDecrement(&apt->inits)==0) {
456 NtCurrentTeb()->ReservedForOle = NULL;
457 COM_DestroyApartment(apt);
458 apt = NULL;
462 * Decrease the reference count.
463 * If we are back to 0 locks on the COM library, make sure we free
464 * all the associated data structures.
466 lCOMRefCnt = InterlockedExchangeAdd(&s_COMLockCount,-1);
467 if (lCOMRefCnt==1)
470 * Release the various COM libraries and data structures.
472 TRACE("() - Releasing the COM libraries\n");
474 RunningObjectTableImpl_UnInitialize();
476 * Release the references to the registered class objects.
478 COM_RevokeAllClasses();
481 * This will free the loaded COM Dlls.
483 CoFreeAllLibraries();
486 * This will free list of external references to COM objects.
488 COM_ExternalLockFreeList();
490 COM_UninitMTA();
492 else if (lCOMRefCnt<1) {
493 ERR( "CoUninitialize() - not CoInitialized.\n" );
494 InterlockedExchangeAdd(&s_COMLockCount,1); /* restore the lock count. */
498 /******************************************************************************
499 * CoDisconnectObject [COMPOBJ.15]
500 * CoDisconnectObject [OLE32.@]
502 HRESULT WINAPI CoDisconnectObject( LPUNKNOWN lpUnk, DWORD reserved )
504 TRACE("(%p, %lx)\n",lpUnk,reserved);
505 return S_OK;
508 /******************************************************************************
509 * CoCreateGuid[OLE32.@]
512 HRESULT WINAPI CoCreateGuid(
513 GUID *pguid /* [out] points to the GUID to initialize */
515 return UuidCreate(pguid);
518 /******************************************************************************
519 * CLSIDFromString [OLE32.@]
520 * IIDFromString [OLE32.@]
521 * Converts a unique identifier from its string representation into
522 * the GUID struct.
524 * UNDOCUMENTED
525 * If idstr is not a valid CLSID string then it gets treated as a ProgID
527 * RETURNS
528 * the converted GUID
530 HRESULT WINAPI __CLSIDFromStringA(
531 LPCSTR idstr, /* [in] string representation of guid */
532 CLSID *id) /* [out] GUID converted from string */
534 const BYTE *s = (BYTE *) idstr;
535 int i;
536 BYTE table[256];
538 if (!s)
539 s = "{00000000-0000-0000-0000-000000000000}";
540 else { /* validate the CLSID string */
542 if (strlen(s) != 38)
543 return CO_E_CLASSSTRING;
545 if ((s[0]!='{') || (s[9]!='-') || (s[14]!='-') || (s[19]!='-') || (s[24]!='-') || (s[37]!='}'))
546 return CO_E_CLASSSTRING;
548 for (i=1; i<37; i++) {
549 if ((i == 9)||(i == 14)||(i == 19)||(i == 24)) continue;
550 if (!(((s[i] >= '0') && (s[i] <= '9')) ||
551 ((s[i] >= 'a') && (s[i] <= 'f')) ||
552 ((s[i] >= 'A') && (s[i] <= 'F'))))
553 return CO_E_CLASSSTRING;
557 TRACE("%s -> %p\n", s, id);
559 /* quick lookup table */
560 memset(table, 0, 256);
562 for (i = 0; i < 10; i++) {
563 table['0' + i] = i;
565 for (i = 0; i < 6; i++) {
566 table['A' + i] = i+10;
567 table['a' + i] = i+10;
570 /* in form {XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX} */
572 id->Data1 = (table[s[1]] << 28 | table[s[2]] << 24 | table[s[3]] << 20 | table[s[4]] << 16 |
573 table[s[5]] << 12 | table[s[6]] << 8 | table[s[7]] << 4 | table[s[8]]);
574 id->Data2 = table[s[10]] << 12 | table[s[11]] << 8 | table[s[12]] << 4 | table[s[13]];
575 id->Data3 = table[s[15]] << 12 | table[s[16]] << 8 | table[s[17]] << 4 | table[s[18]];
577 /* these are just sequential bytes */
578 id->Data4[0] = table[s[20]] << 4 | table[s[21]];
579 id->Data4[1] = table[s[22]] << 4 | table[s[23]];
580 id->Data4[2] = table[s[25]] << 4 | table[s[26]];
581 id->Data4[3] = table[s[27]] << 4 | table[s[28]];
582 id->Data4[4] = table[s[29]] << 4 | table[s[30]];
583 id->Data4[5] = table[s[31]] << 4 | table[s[32]];
584 id->Data4[6] = table[s[33]] << 4 | table[s[34]];
585 id->Data4[7] = table[s[35]] << 4 | table[s[36]];
587 return S_OK;
590 /*****************************************************************************/
592 HRESULT WINAPI CLSIDFromString(
593 LPOLESTR idstr, /* [in] string representation of GUID */
594 CLSID *id ) /* [out] GUID represented by above string */
596 char xid[40];
597 HRESULT ret;
599 if (!WideCharToMultiByte( CP_ACP, 0, idstr, -1, xid, sizeof(xid), NULL, NULL ))
600 return CO_E_CLASSSTRING;
603 ret = __CLSIDFromStringA(xid,id);
604 if(ret != S_OK) { /* It appears a ProgID is also valid */
605 ret = CLSIDFromProgID(idstr, id);
607 return ret;
610 /******************************************************************************
611 * WINE_StringFromCLSID [Internal]
612 * Converts a GUID into the respective string representation.
614 * NOTES
616 * RETURNS
617 * the string representation and HRESULT
619 HRESULT WINE_StringFromCLSID(
620 const CLSID *id, /* [in] GUID to be converted */
621 LPSTR idstr /* [out] pointer to buffer to contain converted guid */
623 static const char *hex = "0123456789ABCDEF";
624 char *s;
625 int i;
627 if (!id)
628 { ERR("called with id=Null\n");
629 *idstr = 0x00;
630 return E_FAIL;
633 sprintf(idstr, "{%08lX-%04X-%04X-%02X%02X-",
634 id->Data1, id->Data2, id->Data3,
635 id->Data4[0], id->Data4[1]);
636 s = &idstr[25];
638 /* 6 hex bytes */
639 for (i = 2; i < 8; i++) {
640 *s++ = hex[id->Data4[i]>>4];
641 *s++ = hex[id->Data4[i] & 0xf];
644 *s++ = '}';
645 *s++ = '\0';
647 TRACE("%p->%s\n", id, idstr);
649 return S_OK;
653 /******************************************************************************
654 * StringFromCLSID [OLE32.@]
655 * StringFromIID [OLE32.@]
656 * Converts a GUID into the respective string representation.
657 * The target string is allocated using the OLE IMalloc.
658 * RETURNS
659 * the string representation and HRESULT
661 HRESULT WINAPI StringFromCLSID(
662 REFCLSID id, /* [in] the GUID to be converted */
663 LPOLESTR *idstr /* [out] a pointer to a to-be-allocated pointer pointing to the resulting string */
665 char buf[80];
666 HRESULT ret;
667 LPMALLOC mllc;
669 if ((ret=CoGetMalloc(0,&mllc)))
670 return ret;
672 ret=WINE_StringFromCLSID(id,buf);
673 if (!ret) {
674 DWORD len = MultiByteToWideChar( CP_ACP, 0, buf, -1, NULL, 0 );
675 *idstr = IMalloc_Alloc( mllc, len * sizeof(WCHAR) );
676 MultiByteToWideChar( CP_ACP, 0, buf, -1, *idstr, len );
678 return ret;
681 /******************************************************************************
682 * StringFromGUID2 [COMPOBJ.76]
683 * StringFromGUID2 [OLE32.@]
685 * Converts a global unique identifier into a string of an API-
686 * specified fixed format. (The usual {.....} stuff.)
688 * RETURNS
689 * The (UNICODE) string representation of the GUID in 'str'
690 * The length of the resulting string, 0 if there was any problem.
692 INT WINAPI
693 StringFromGUID2(REFGUID id, LPOLESTR str, INT cmax)
695 char xguid[80];
697 if (WINE_StringFromCLSID(id,xguid))
698 return 0;
699 return MultiByteToWideChar( CP_ACP, 0, xguid, -1, str, cmax );
702 /******************************************************************************
703 * ProgIDFromCLSID [OLE32.@]
704 * Converts a class id into the respective Program ID. (By using a registry lookup)
705 * RETURNS S_OK on success
706 * riid associated with the progid
709 HRESULT WINAPI ProgIDFromCLSID(
710 REFCLSID clsid, /* [in] class id as found in registry */
711 LPOLESTR *lplpszProgID/* [out] associated Prog ID */
714 char strCLSID[50], *buf, *buf2;
715 DWORD buf2len;
716 HKEY xhkey;
717 LPMALLOC mllc;
718 HRESULT ret = S_OK;
720 WINE_StringFromCLSID(clsid, strCLSID);
722 buf = HeapAlloc(GetProcessHeap(), 0, strlen(strCLSID)+14);
723 sprintf(buf,"CLSID\\%s\\ProgID", strCLSID);
724 if (RegOpenKeyA(HKEY_CLASSES_ROOT, buf, &xhkey))
725 ret = REGDB_E_CLASSNOTREG;
727 HeapFree(GetProcessHeap(), 0, buf);
729 if (ret == S_OK)
731 buf2 = HeapAlloc(GetProcessHeap(), 0, 255);
732 buf2len = 255;
733 if (RegQueryValueA(xhkey, NULL, buf2, &buf2len))
734 ret = REGDB_E_CLASSNOTREG;
736 if (ret == S_OK)
738 if (CoGetMalloc(0,&mllc))
739 ret = E_OUTOFMEMORY;
740 else
742 DWORD len = MultiByteToWideChar( CP_ACP, 0, buf2, -1, NULL, 0 );
743 *lplpszProgID = IMalloc_Alloc(mllc, len * sizeof(WCHAR) );
744 MultiByteToWideChar( CP_ACP, 0, buf2, -1, *lplpszProgID, len );
747 HeapFree(GetProcessHeap(), 0, buf2);
750 RegCloseKey(xhkey);
751 return ret;
754 /******************************************************************************
755 * CLSIDFromProgID [COMPOBJ.61]
756 * Converts a program id into the respective GUID. (By using a registry lookup)
757 * RETURNS
758 * riid associated with the progid
760 HRESULT WINAPI CLSIDFromProgID16(
761 LPCOLESTR16 progid, /* [in] program id as found in registry */
762 LPCLSID riid /* [out] associated CLSID */
764 char *buf,buf2[80];
765 DWORD buf2len;
766 HRESULT err;
767 HKEY xhkey;
769 buf = HeapAlloc(GetProcessHeap(),0,strlen(progid)+8);
770 sprintf(buf,"%s\\CLSID",progid);
771 if ((err=RegOpenKeyA(HKEY_CLASSES_ROOT,buf,&xhkey))) {
772 HeapFree(GetProcessHeap(),0,buf);
773 return CO_E_CLASSSTRING;
775 HeapFree(GetProcessHeap(),0,buf);
776 buf2len = sizeof(buf2);
777 if ((err=RegQueryValueA(xhkey,NULL,buf2,&buf2len))) {
778 RegCloseKey(xhkey);
779 return CO_E_CLASSSTRING;
781 RegCloseKey(xhkey);
782 return __CLSIDFromStringA(buf2,riid);
785 /******************************************************************************
786 * CLSIDFromProgID [OLE32.@]
787 * Converts a program id into the respective GUID. (By using a registry lookup)
788 * RETURNS
789 * riid associated with the progid
791 HRESULT WINAPI CLSIDFromProgID(
792 LPCOLESTR progid, /* [in] program id as found in registry */
793 LPCLSID riid ) /* [out] associated CLSID */
795 static const WCHAR clsidW[] = { '\\','C','L','S','I','D',0 };
796 char buf2[80];
797 DWORD buf2len = sizeof(buf2);
798 HKEY xhkey;
800 WCHAR *buf = HeapAlloc( GetProcessHeap(),0,(strlenW(progid)+8) * sizeof(WCHAR) );
801 strcpyW( buf, progid );
802 strcatW( buf, clsidW );
803 if (RegOpenKeyW(HKEY_CLASSES_ROOT,buf,&xhkey))
805 HeapFree(GetProcessHeap(),0,buf);
806 return CO_E_CLASSSTRING;
808 HeapFree(GetProcessHeap(),0,buf);
810 if (RegQueryValueA(xhkey,NULL,buf2,&buf2len))
812 RegCloseKey(xhkey);
813 return CO_E_CLASSSTRING;
815 RegCloseKey(xhkey);
816 return __CLSIDFromStringA(buf2,riid);
821 /*****************************************************************************
822 * CoGetPSClsid [OLE32.@]
824 * This function returns the CLSID of the DLL that implements the proxy and stub
825 * for the specified interface.
827 * It determines this by searching the
828 * HKEY_CLASSES_ROOT\Interface\{string form of riid}\ProxyStubClsid32 in the registry
829 * and any interface id registered by CoRegisterPSClsid within the current process.
831 * FIXME: We only search the registry, not ids registered with CoRegisterPSClsid.
833 HRESULT WINAPI CoGetPSClsid(
834 REFIID riid, /* [in] Interface whose proxy/stub CLSID is to be returned */
835 CLSID *pclsid ) /* [out] Where to store returned proxy/stub CLSID */
837 char *buf, buf2[40];
838 DWORD buf2len;
839 HKEY xhkey;
841 TRACE("() riid=%s, pclsid=%p\n", debugstr_guid(riid), pclsid);
843 /* Get the input iid as a string */
844 WINE_StringFromCLSID(riid, buf2);
845 /* Allocate memory for the registry key we will construct.
846 (length of iid string plus constant length of static text */
847 buf = HeapAlloc(GetProcessHeap(), 0, strlen(buf2)+27);
848 if (buf == NULL)
850 return (E_OUTOFMEMORY);
853 /* Construct the registry key we want */
854 sprintf(buf,"Interface\\%s\\ProxyStubClsid32", buf2);
856 /* Open the key.. */
857 if (RegOpenKeyA(HKEY_CLASSES_ROOT, buf, &xhkey))
859 HeapFree(GetProcessHeap(),0,buf);
860 return (E_INVALIDARG);
862 HeapFree(GetProcessHeap(),0,buf);
864 /* ... Once we have the key, query the registry to get the
865 value of CLSID as a string, and convert it into a
866 proper CLSID structure to be passed back to the app */
867 buf2len = sizeof(buf2);
868 if ( (RegQueryValueA(xhkey,NULL,buf2,&buf2len)) )
870 RegCloseKey(xhkey);
871 return E_INVALIDARG;
873 RegCloseKey(xhkey);
875 /* We have the CLSid we want back from the registry as a string, so
876 lets convert it into a CLSID structure */
877 if ( (__CLSIDFromStringA(buf2,pclsid)) != NOERROR) {
878 return E_INVALIDARG;
881 TRACE ("() Returning CLSID=%s\n", debugstr_guid(pclsid));
882 return (S_OK);
887 /***********************************************************************
888 * WriteClassStm (OLE32.@)
890 * This function write a CLSID on stream
892 HRESULT WINAPI WriteClassStm(IStream *pStm,REFCLSID rclsid)
894 TRACE("(%p,%p)\n",pStm,rclsid);
896 if (rclsid==NULL)
897 return E_INVALIDARG;
899 return IStream_Write(pStm,rclsid,sizeof(CLSID),NULL);
902 /***********************************************************************
903 * ReadClassStm (OLE32.@)
905 * This function read a CLSID from a stream
907 HRESULT WINAPI ReadClassStm(IStream *pStm,CLSID *pclsid)
909 ULONG nbByte;
910 HRESULT res;
912 TRACE("(%p,%p)\n",pStm,pclsid);
914 if (pclsid==NULL)
915 return E_INVALIDARG;
917 res = IStream_Read(pStm,(void*)pclsid,sizeof(CLSID),&nbByte);
919 if (FAILED(res))
920 return res;
922 if (nbByte != sizeof(CLSID))
923 return S_FALSE;
924 else
925 return S_OK;
929 /***
930 * COM_GetRegisteredClassObject
932 * This internal method is used to scan the registered class list to
933 * find a class object.
935 * Params:
936 * rclsid Class ID of the class to find.
937 * dwClsContext Class context to match.
938 * ppv [out] returns a pointer to the class object. Complying
939 * to normal COM usage, this method will increase the
940 * reference count on this object.
942 static HRESULT COM_GetRegisteredClassObject(
943 REFCLSID rclsid,
944 DWORD dwClsContext,
945 LPUNKNOWN* ppUnk)
947 HRESULT hr = S_FALSE;
948 RegisteredClass* curClass;
950 EnterCriticalSection( &csRegisteredClassList );
953 * Sanity check
955 assert(ppUnk!=0);
958 * Iterate through the whole list and try to match the class ID.
960 curClass = firstRegisteredClass;
962 while (curClass != 0)
965 * Check if we have a match on the class ID.
967 if (IsEqualGUID(&(curClass->classIdentifier), rclsid))
970 * Since we don't do out-of process or DCOM just right away, let's ignore the
971 * class context.
975 * We have a match, return the pointer to the class object.
977 *ppUnk = curClass->classObject;
979 IUnknown_AddRef(curClass->classObject);
981 hr = S_OK;
982 goto end;
986 * Step to the next class in the list.
988 curClass = curClass->nextClass;
991 end:
992 LeaveCriticalSection( &csRegisteredClassList );
994 * If we get to here, we haven't found our class.
996 return hr;
999 static DWORD WINAPI
1000 _LocalServerThread(LPVOID param) {
1001 HANDLE hPipe;
1002 char pipefn[200];
1003 RegisteredClass *newClass = (RegisteredClass*)param;
1004 HRESULT hres;
1005 IStream *pStm;
1006 STATSTG ststg;
1007 unsigned char *buffer;
1008 int buflen;
1009 IClassFactory *classfac;
1010 LARGE_INTEGER seekto;
1011 ULARGE_INTEGER newpos;
1012 ULONG res;
1014 TRACE("Starting threader for %s.\n",debugstr_guid(&newClass->classIdentifier));
1015 strcpy(pipefn,PIPEPREF);
1016 WINE_StringFromCLSID(&newClass->classIdentifier,pipefn+strlen(PIPEPREF));
1018 hres = IUnknown_QueryInterface(newClass->classObject,&IID_IClassFactory,(LPVOID*)&classfac);
1019 if (hres) return hres;
1021 hres = CreateStreamOnHGlobal(0,TRUE,&pStm);
1022 if (hres) {
1023 FIXME("Failed to create stream on hglobal.\n");
1024 return hres;
1026 hres = CoMarshalInterface(pStm,&IID_IClassFactory,(LPVOID)classfac,0,NULL,0);
1027 if (hres) {
1028 FIXME("CoMarshalInterface failed, %lx!\n",hres);
1029 return hres;
1031 hres = IStream_Stat(pStm,&ststg,0);
1032 if (hres) return hres;
1034 buflen = ststg.cbSize.u.LowPart;
1035 buffer = HeapAlloc(GetProcessHeap(),0,buflen);
1036 seekto.u.LowPart = 0;
1037 seekto.u.HighPart = 0;
1038 hres = IStream_Seek(pStm,seekto,SEEK_SET,&newpos);
1039 if (hres) {
1040 FIXME("IStream_Seek failed, %lx\n",hres);
1041 return hres;
1043 hres = IStream_Read(pStm,buffer,buflen,&res);
1044 if (hres) {
1045 FIXME("Stream Read failed, %lx\n",hres);
1046 return hres;
1048 IStream_Release(pStm);
1050 while (1) {
1051 hPipe = CreateNamedPipeA(
1052 pipefn,
1053 PIPE_ACCESS_DUPLEX,
1054 PIPE_TYPE_BYTE|PIPE_WAIT,
1055 PIPE_UNLIMITED_INSTANCES,
1056 4096,
1057 4096,
1058 NMPWAIT_USE_DEFAULT_WAIT,
1059 NULL
1061 if (hPipe == INVALID_HANDLE_VALUE) {
1062 FIXME("pipe creation failed for %s, le is %lx\n",pipefn,GetLastError());
1063 return 1;
1065 if (!ConnectNamedPipe(hPipe,NULL)) {
1066 ERR("Failure during ConnectNamedPipe %lx, ABORT!\n",GetLastError());
1067 CloseHandle(hPipe);
1068 continue;
1070 WriteFile(hPipe,buffer,buflen,&res,NULL);
1071 CloseHandle(hPipe);
1073 return 0;
1076 /******************************************************************************
1077 * CoRegisterClassObject [OLE32.@]
1079 * This method will register the class object for a given class ID.
1081 * See the Windows documentation for more details.
1083 HRESULT WINAPI CoRegisterClassObject(
1084 REFCLSID rclsid,
1085 LPUNKNOWN pUnk,
1086 DWORD dwClsContext, /* [in] CLSCTX flags indicating the context in which to run the executable */
1087 DWORD flags, /* [in] REGCLS flags indicating how connections are made */
1088 LPDWORD lpdwRegister
1091 RegisteredClass* newClass;
1092 LPUNKNOWN foundObject;
1093 HRESULT hr;
1095 TRACE("(%s,%p,0x%08lx,0x%08lx,%p)\n",
1096 debugstr_guid(rclsid),pUnk,dwClsContext,flags,lpdwRegister);
1098 if ( (lpdwRegister==0) || (pUnk==0) )
1099 return E_INVALIDARG;
1101 *lpdwRegister = 0;
1104 * First, check if the class is already registered.
1105 * If it is, this should cause an error.
1107 hr = COM_GetRegisteredClassObject(rclsid, dwClsContext, &foundObject);
1108 if (hr == S_OK) {
1109 IUnknown_Release(foundObject);
1110 return CO_E_OBJISREG;
1113 newClass = HeapAlloc(GetProcessHeap(), 0, sizeof(RegisteredClass));
1114 if ( newClass == NULL )
1115 return E_OUTOFMEMORY;
1117 EnterCriticalSection( &csRegisteredClassList );
1119 newClass->classIdentifier = *rclsid;
1120 newClass->runContext = dwClsContext;
1121 newClass->connectFlags = flags;
1123 * Use the address of the chain node as the cookie since we are sure it's
1124 * unique.
1126 newClass->dwCookie = (DWORD)newClass;
1127 newClass->nextClass = firstRegisteredClass;
1130 * Since we're making a copy of the object pointer, we have to increase its
1131 * reference count.
1133 newClass->classObject = pUnk;
1134 IUnknown_AddRef(newClass->classObject);
1136 firstRegisteredClass = newClass;
1137 LeaveCriticalSection( &csRegisteredClassList );
1139 *lpdwRegister = newClass->dwCookie;
1141 if (dwClsContext & CLSCTX_LOCAL_SERVER) {
1142 DWORD tid;
1144 STUBMGR_Start();
1145 newClass->hThread=CreateThread(NULL,0,_LocalServerThread,newClass,0,&tid);
1147 return S_OK;
1150 /***********************************************************************
1151 * CoRevokeClassObject [OLE32.@]
1153 * This method will remove a class object from the class registry
1155 * See the Windows documentation for more details.
1157 HRESULT WINAPI CoRevokeClassObject(
1158 DWORD dwRegister)
1160 HRESULT hr = E_INVALIDARG;
1161 RegisteredClass** prevClassLink;
1162 RegisteredClass* curClass;
1164 TRACE("(%08lx)\n",dwRegister);
1166 EnterCriticalSection( &csRegisteredClassList );
1169 * Iterate through the whole list and try to match the cookie.
1171 curClass = firstRegisteredClass;
1172 prevClassLink = &firstRegisteredClass;
1174 while (curClass != 0)
1177 * Check if we have a match on the cookie.
1179 if (curClass->dwCookie == dwRegister)
1182 * Remove the class from the chain.
1184 *prevClassLink = curClass->nextClass;
1187 * Release the reference to the class object.
1189 IUnknown_Release(curClass->classObject);
1192 * Free the memory used by the chain node.
1194 HeapFree(GetProcessHeap(), 0, curClass);
1196 hr = S_OK;
1197 goto end;
1201 * Step to the next class in the list.
1203 prevClassLink = &(curClass->nextClass);
1204 curClass = curClass->nextClass;
1207 end:
1208 LeaveCriticalSection( &csRegisteredClassList );
1210 * If we get to here, we haven't found our class.
1212 return hr;
1215 /***********************************************************************
1216 * compobj_RegReadPath [internal]
1218 * Reads a registry value and expands it when necessary
1220 HRESULT compobj_RegReadPath(char * keyname, char * valuename, char * dst, int dstlen)
1222 HRESULT hres;
1223 HKEY key;
1224 DWORD keytype;
1225 char src[MAX_PATH];
1226 DWORD dwLength = dstlen;
1228 if((hres = RegOpenKeyExA(HKEY_CLASSES_ROOT, keyname, 0, KEY_READ, &key)) == ERROR_SUCCESS) {
1229 if( (hres = RegQueryValueExA(key, NULL, NULL, &keytype, (LPBYTE)src, &dwLength)) == ERROR_SUCCESS ) {
1230 if (keytype == REG_EXPAND_SZ) {
1231 if (dstlen <= ExpandEnvironmentStringsA(src, dst, dstlen)) hres = ERROR_MORE_DATA;
1232 } else {
1233 strncpy(dst, src, dstlen);
1236 RegCloseKey (key);
1238 return hres;
1241 /***********************************************************************
1242 * CoGetClassObject [COMPOBJ.7]
1243 * CoGetClassObject [OLE32.@]
1245 * FIXME. If request allows of several options and there is a failure
1246 * with one (other than not being registered) do we try the
1247 * others or return failure? (E.g. inprocess is registered but
1248 * the DLL is not found but the server version works)
1250 HRESULT WINAPI CoGetClassObject(
1251 REFCLSID rclsid, DWORD dwClsContext, COSERVERINFO *pServerInfo,
1252 REFIID iid, LPVOID *ppv
1254 LPUNKNOWN regClassObject;
1255 HRESULT hres = E_UNEXPECTED;
1256 char xclsid[80];
1257 HINSTANCE hLibrary;
1258 typedef HRESULT (CALLBACK *DllGetClassObjectFunc)(REFCLSID clsid, REFIID iid, LPVOID *ppv);
1259 DllGetClassObjectFunc DllGetClassObject;
1261 WINE_StringFromCLSID((LPCLSID)rclsid,xclsid);
1263 TRACE("\n\tCLSID:\t%s,\n\tIID:\t%s\n", debugstr_guid(rclsid), debugstr_guid(iid));
1265 if (pServerInfo) {
1266 FIXME("\tpServerInfo: name=%s\n",debugstr_w(pServerInfo->pwszName));
1267 FIXME("\t\tpAuthInfo=%p\n",pServerInfo->pAuthInfo);
1271 * First, try and see if we can't match the class ID with one of the
1272 * registered classes.
1274 if (S_OK == COM_GetRegisteredClassObject(rclsid, dwClsContext, &regClassObject))
1277 * Get the required interface from the retrieved pointer.
1279 hres = IUnknown_QueryInterface(regClassObject, iid, ppv);
1282 * Since QI got another reference on the pointer, we want to release the
1283 * one we already have. If QI was unsuccessful, this will release the object. This
1284 * is good since we are not returning it in the "out" parameter.
1286 IUnknown_Release(regClassObject);
1288 return hres;
1291 /* first try: in-process */
1292 if ((CLSCTX_INPROC_SERVER | CLSCTX_INPROC_HANDLER) & dwClsContext) {
1293 char keyname[MAX_PATH];
1294 char dllpath[MAX_PATH+1];
1296 sprintf(keyname,"CLSID\\%s\\InprocServer32",xclsid);
1298 if ( compobj_RegReadPath(keyname, NULL, dllpath, sizeof(dllpath)) != ERROR_SUCCESS) {
1299 /* failure: CLSID is not found in registry */
1300 WARN("class %s not registred\n", xclsid);
1301 hres = REGDB_E_CLASSNOTREG;
1302 } else {
1303 if ((hLibrary = LoadLibraryExA(dllpath, 0, LOAD_WITH_ALTERED_SEARCH_PATH)) == 0) {
1304 /* failure: DLL could not be loaded */
1305 ERR("couldn't load InprocServer32 dll %s\n", dllpath);
1306 hres = E_ACCESSDENIED; /* FIXME: or should this be CO_E_DLLNOTFOUND? */
1307 } else if (!(DllGetClassObject = (DllGetClassObjectFunc)GetProcAddress(hLibrary, "DllGetClassObject"))) {
1308 /* failure: the dll did not export DllGetClassObject */
1309 ERR("couldn't find function DllGetClassObject in %s\n", dllpath);
1310 FreeLibrary( hLibrary );
1311 hres = CO_E_DLLNOTFOUND;
1312 } else {
1313 /* OK: get the ClassObject */
1314 COMPOBJ_DLLList_Add( hLibrary );
1315 return DllGetClassObject(rclsid, iid, ppv);
1320 /* Next try out of process */
1321 if (CLSCTX_LOCAL_SERVER & dwClsContext)
1323 return create_marshalled_proxy(rclsid,iid,ppv);
1326 /* Finally try remote */
1327 if (CLSCTX_REMOTE_SERVER & dwClsContext)
1329 FIXME ("CLSCTX_REMOTE_SERVER not supported\n");
1330 hres = E_NOINTERFACE;
1333 return hres;
1335 /***********************************************************************
1336 * CoResumeClassObjects (OLE32.@)
1338 * Resumes classobjects registered with REGCLS suspended
1340 HRESULT WINAPI CoResumeClassObjects(void)
1342 FIXME("\n");
1343 return S_OK;
1346 /***********************************************************************
1347 * GetClassFile (OLE32.@)
1349 * This function supplies the CLSID associated with the given filename.
1351 HRESULT WINAPI GetClassFile(LPCOLESTR filePathName,CLSID *pclsid)
1353 IStorage *pstg=0;
1354 HRESULT res;
1355 int nbElm, length, i;
1356 LONG sizeProgId;
1357 LPOLESTR *pathDec=0,absFile=0,progId=0;
1358 LPWSTR extension;
1359 static const WCHAR bkslashW[] = {'\\',0};
1360 static const WCHAR dotW[] = {'.',0};
1362 TRACE("%s, %p\n", debugstr_w(filePathName), pclsid);
1364 /* if the file contain a storage object the return the CLSID written by IStorage_SetClass method*/
1365 if((StgIsStorageFile(filePathName))==S_OK){
1367 res=StgOpenStorage(filePathName,NULL,STGM_READ | STGM_SHARE_DENY_WRITE,NULL,0,&pstg);
1369 if (SUCCEEDED(res))
1370 res=ReadClassStg(pstg,pclsid);
1372 IStorage_Release(pstg);
1374 return res;
1376 /* if the file is not a storage object then attemps to match various bits in the file against a
1377 pattern in the registry. this case is not frequently used ! so I present only the psodocode for
1378 this case
1380 for(i=0;i<nFileTypes;i++)
1382 for(i=0;j<nPatternsForType;j++){
1384 PATTERN pat;
1385 HANDLE hFile;
1387 pat=ReadPatternFromRegistry(i,j);
1388 hFile=CreateFileW(filePathName,,,,,,hFile);
1389 SetFilePosition(hFile,pat.offset);
1390 ReadFile(hFile,buf,pat.size,NULL,NULL);
1391 if (memcmp(buf&pat.mask,pat.pattern.pat.size)==0){
1393 *pclsid=ReadCLSIDFromRegistry(i);
1394 return S_OK;
1399 /* if the obove strategies fail then search for the extension key in the registry */
1401 /* get the last element (absolute file) in the path name */
1402 nbElm=FileMonikerImpl_DecomposePath(filePathName,&pathDec);
1403 absFile=pathDec[nbElm-1];
1405 /* failed if the path represente a directory and not an absolute file name*/
1406 if (!lstrcmpW(absFile, bkslashW))
1407 return MK_E_INVALIDEXTENSION;
1409 /* get the extension of the file */
1410 extension = NULL;
1411 length=lstrlenW(absFile);
1412 for(i = length-1; (i >= 0) && *(extension = &absFile[i]) != '.'; i--)
1413 /* nothing */;
1415 if (!extension || !lstrcmpW(extension, dotW))
1416 return MK_E_INVALIDEXTENSION;
1418 res=RegQueryValueW(HKEY_CLASSES_ROOT, extension, NULL, &sizeProgId);
1420 /* get the progId associated to the extension */
1421 progId = CoTaskMemAlloc(sizeProgId);
1422 res = RegQueryValueW(HKEY_CLASSES_ROOT, extension, progId, &sizeProgId);
1424 if (res==ERROR_SUCCESS)
1425 /* return the clsid associated to the progId */
1426 res= CLSIDFromProgID(progId,pclsid);
1428 for(i=0; pathDec[i]!=NULL;i++)
1429 CoTaskMemFree(pathDec[i]);
1430 CoTaskMemFree(pathDec);
1432 CoTaskMemFree(progId);
1434 if (res==ERROR_SUCCESS)
1435 return res;
1437 return MK_E_INVALIDEXTENSION;
1439 /***********************************************************************
1440 * CoCreateInstance [COMPOBJ.13]
1441 * CoCreateInstance [OLE32.@]
1443 HRESULT WINAPI CoCreateInstance(
1444 REFCLSID rclsid,
1445 LPUNKNOWN pUnkOuter,
1446 DWORD dwClsContext,
1447 REFIID iid,
1448 LPVOID *ppv)
1450 HRESULT hres;
1451 LPCLASSFACTORY lpclf = 0;
1454 * Sanity check
1456 if (ppv==0)
1457 return E_POINTER;
1460 * Initialize the "out" parameter
1462 *ppv = 0;
1465 * The Standard Global Interface Table (GIT) object is a process-wide singleton.
1466 * Rather than create a class factory, we can just check for it here
1468 if (IsEqualIID(rclsid, &CLSID_StdGlobalInterfaceTable)) {
1469 if (StdGlobalInterfaceTableInstance == NULL)
1470 StdGlobalInterfaceTableInstance = StdGlobalInterfaceTable_Construct();
1471 hres = IGlobalInterfaceTable_QueryInterface( (IGlobalInterfaceTable*) StdGlobalInterfaceTableInstance, iid, ppv);
1472 if (hres) return hres;
1474 TRACE("Retrieved GIT (%p)\n", *ppv);
1475 return S_OK;
1479 * Get a class factory to construct the object we want.
1481 hres = CoGetClassObject(rclsid,
1482 dwClsContext,
1483 NULL,
1484 &IID_IClassFactory,
1485 (LPVOID)&lpclf);
1487 if (FAILED(hres)) {
1488 FIXME("no classfactory created for CLSID %s, hres is 0x%08lx\n",
1489 debugstr_guid(rclsid),hres);
1490 return hres;
1494 * Create the object and don't forget to release the factory
1496 hres = IClassFactory_CreateInstance(lpclf, pUnkOuter, iid, ppv);
1497 IClassFactory_Release(lpclf);
1498 if(FAILED(hres))
1499 FIXME("no instance created for interface %s of class %s, hres is 0x%08lx\n",
1500 debugstr_guid(iid), debugstr_guid(rclsid),hres);
1502 return hres;
1505 /***********************************************************************
1506 * CoCreateInstanceEx [OLE32.@]
1508 HRESULT WINAPI CoCreateInstanceEx(
1509 REFCLSID rclsid,
1510 LPUNKNOWN pUnkOuter,
1511 DWORD dwClsContext,
1512 COSERVERINFO* pServerInfo,
1513 ULONG cmq,
1514 MULTI_QI* pResults)
1516 IUnknown* pUnk = NULL;
1517 HRESULT hr;
1518 ULONG index;
1519 int successCount = 0;
1522 * Sanity check
1524 if ( (cmq==0) || (pResults==NULL))
1525 return E_INVALIDARG;
1527 if (pServerInfo!=NULL)
1528 FIXME("() non-NULL pServerInfo not supported!\n");
1531 * Initialize all the "out" parameters.
1533 for (index = 0; index < cmq; index++)
1535 pResults[index].pItf = NULL;
1536 pResults[index].hr = E_NOINTERFACE;
1540 * Get the object and get its IUnknown pointer.
1542 hr = CoCreateInstance(rclsid,
1543 pUnkOuter,
1544 dwClsContext,
1545 &IID_IUnknown,
1546 (VOID**)&pUnk);
1548 if (hr)
1549 return hr;
1552 * Then, query for all the interfaces requested.
1554 for (index = 0; index < cmq; index++)
1556 pResults[index].hr = IUnknown_QueryInterface(pUnk,
1557 pResults[index].pIID,
1558 (VOID**)&(pResults[index].pItf));
1560 if (pResults[index].hr == S_OK)
1561 successCount++;
1565 * Release our temporary unknown pointer.
1567 IUnknown_Release(pUnk);
1569 if (successCount == 0)
1570 return E_NOINTERFACE;
1572 if (successCount!=cmq)
1573 return CO_S_NOTALLINTERFACES;
1575 return S_OK;
1578 /***********************************************************************
1579 * CoLoadLibrary (OLE32.@)
1581 HINSTANCE WINAPI CoLoadLibrary(LPOLESTR lpszLibName, BOOL bAutoFree)
1583 TRACE("(%s, %d)\n", debugstr_w(lpszLibName), bAutoFree);
1585 return LoadLibraryExW(lpszLibName, 0, LOAD_WITH_ALTERED_SEARCH_PATH);
1588 /***********************************************************************
1589 * CoFreeLibrary [OLE32.@]
1591 * NOTES: don't belive the docu
1593 void WINAPI CoFreeLibrary(HINSTANCE hLibrary)
1595 FreeLibrary(hLibrary);
1599 /***********************************************************************
1600 * CoFreeAllLibraries [OLE32.@]
1602 * NOTES: don't belive the docu
1604 void WINAPI CoFreeAllLibraries(void)
1606 /* NOP */
1610 /***********************************************************************
1611 * CoFreeUnusedLibraries [COMPOBJ.17]
1612 * CoFreeUnusedLibraries [OLE32.@]
1614 * FIXME: Calls to CoFreeUnusedLibraries from any thread always route
1615 * through the main apartment's thread to call DllCanUnloadNow
1617 void WINAPI CoFreeUnusedLibraries(void)
1619 COMPOBJ_DllList_FreeUnused(0);
1622 /***********************************************************************
1623 * CoFileTimeNow [COMPOBJ.82]
1624 * CoFileTimeNow [OLE32.@]
1626 * RETURNS
1627 * the current system time in lpFileTime
1629 HRESULT WINAPI CoFileTimeNow( FILETIME *lpFileTime ) /* [out] the current time */
1631 GetSystemTimeAsFileTime( lpFileTime );
1632 return S_OK;
1635 /***********************************************************************
1636 * CoLoadLibrary (OLE32.@)
1638 static void COM_RevokeAllClasses()
1640 EnterCriticalSection( &csRegisteredClassList );
1642 while (firstRegisteredClass!=0)
1644 CoRevokeClassObject(firstRegisteredClass->dwCookie);
1647 LeaveCriticalSection( &csRegisteredClassList );
1650 /****************************************************************************
1651 * COM External Lock methods implementation
1653 * This api provides a linked list to managed external references to
1654 * COM objects.
1656 * The public interface consists of three calls:
1657 * COM_ExternalLockAddRef
1658 * COM_ExternalLockRelease
1659 * COM_ExternalLockFreeList
1662 #define EL_END_OF_LIST 0
1663 #define EL_NOT_FOUND 0
1666 * Declaration of the static structure that manage the
1667 * external lock to COM objects.
1669 typedef struct COM_ExternalLock COM_ExternalLock;
1670 typedef struct COM_ExternalLockList COM_ExternalLockList;
1672 struct COM_ExternalLock
1674 IUnknown *pUnk; /* IUnknown referenced */
1675 ULONG uRefCount; /* external lock counter to IUnknown object*/
1676 COM_ExternalLock *next; /* Pointer to next element in list */
1679 struct COM_ExternalLockList
1681 COM_ExternalLock *head; /* head of list */
1685 * Declaration and initialization of the static structure that manages
1686 * the external lock to COM objects.
1688 static COM_ExternalLockList elList = { EL_END_OF_LIST };
1691 * Private methods used to managed the linked list
1695 static COM_ExternalLock* COM_ExternalLockLocate(
1696 COM_ExternalLock *element,
1697 IUnknown *pUnk);
1699 /****************************************************************************
1700 * Internal - Insert a new IUnknown* to the linked list
1702 static BOOL COM_ExternalLockInsert(
1703 IUnknown *pUnk)
1705 COM_ExternalLock *newLock = NULL;
1706 COM_ExternalLock *previousHead = NULL;
1709 * Allocate space for the new storage object
1711 newLock = HeapAlloc(GetProcessHeap(), 0, sizeof(COM_ExternalLock));
1713 if (newLock!=NULL) {
1714 if ( elList.head == EL_END_OF_LIST ) {
1715 elList.head = newLock; /* The list is empty */
1716 } else {
1717 /* insert does it at the head */
1718 previousHead = elList.head;
1719 elList.head = newLock;
1722 /* Set new list item data member */
1723 newLock->pUnk = pUnk;
1724 newLock->uRefCount = 1;
1725 newLock->next = previousHead;
1727 return TRUE;
1729 return FALSE;
1732 /****************************************************************************
1733 * Internal - Method that removes an item from the linked list.
1735 static void COM_ExternalLockDelete(
1736 COM_ExternalLock *itemList)
1738 COM_ExternalLock *current = elList.head;
1740 if ( current == itemList ) {
1741 /* this section handles the deletion of the first node */
1742 elList.head = itemList->next;
1743 HeapFree( GetProcessHeap(), 0, itemList);
1744 } else {
1745 do {
1746 if ( current->next == itemList ){ /* We found the item to free */
1747 current->next = itemList->next; /* readjust the list pointers */
1748 HeapFree( GetProcessHeap(), 0, itemList);
1749 break;
1752 /* Skip to the next item */
1753 current = current->next;
1755 } while ( current != EL_END_OF_LIST );
1759 /****************************************************************************
1760 * Internal - Recursivity agent for IUnknownExternalLockList_Find
1762 * NOTES: how long can the list be ?? (recursive!!!)
1764 static COM_ExternalLock* COM_ExternalLockLocate( COM_ExternalLock *element, IUnknown *pUnk)
1766 if ( element == EL_END_OF_LIST )
1767 return EL_NOT_FOUND;
1768 else if ( element->pUnk == pUnk ) /* We found it */
1769 return element;
1770 else /* Not the right guy, keep on looking */
1771 return COM_ExternalLockLocate( element->next, pUnk);
1774 /****************************************************************************
1775 * Public - Method that increments the count for a IUnknown* in the linked
1776 * list. The item is inserted if not already in the list.
1778 static void COM_ExternalLockAddRef(IUnknown *pUnk)
1780 COM_ExternalLock *externalLock = COM_ExternalLockLocate(elList.head, pUnk);
1783 * Add an external lock to the object. If it was already externally
1784 * locked, just increase the reference count. If it was not.
1785 * add the item to the list.
1787 if ( externalLock == EL_NOT_FOUND )
1788 COM_ExternalLockInsert(pUnk);
1789 else
1790 externalLock->uRefCount++;
1793 * Add an internal lock to the object
1795 IUnknown_AddRef(pUnk);
1798 /****************************************************************************
1799 * Public - Method that decrements the count for a IUnknown* in the linked
1800 * list. The item is removed from the list if its count end up at zero or if
1801 * bRelAll is TRUE.
1803 static void COM_ExternalLockRelease(
1804 IUnknown *pUnk,
1805 BOOL bRelAll)
1807 COM_ExternalLock *externalLock = COM_ExternalLockLocate(elList.head, pUnk);
1809 if ( externalLock != EL_NOT_FOUND ) {
1810 do {
1811 externalLock->uRefCount--; /* release external locks */
1812 IUnknown_Release(pUnk); /* release local locks as well */
1814 if ( bRelAll == FALSE ) break; /* perform single release */
1816 } while ( externalLock->uRefCount > 0 );
1818 if ( externalLock->uRefCount == 0 ) /* get rid of the list entry */
1819 COM_ExternalLockDelete(externalLock);
1822 /****************************************************************************
1823 * Public - Method that frees the content of the list.
1825 static void COM_ExternalLockFreeList()
1827 COM_ExternalLock *head;
1829 head = elList.head; /* grab it by the head */
1830 while ( head != EL_END_OF_LIST ) {
1831 COM_ExternalLockDelete(head); /* get rid of the head stuff */
1832 head = elList.head; /* get the new head... */
1836 /****************************************************************************
1837 * Public - Method that dump the content of the list.
1839 void COM_ExternalLockDump()
1841 COM_ExternalLock *current = elList.head;
1843 DPRINTF("\nExternal lock list contains:\n");
1845 while ( current != EL_END_OF_LIST ) {
1846 DPRINTF( "\t%p with %lu references count.\n", current->pUnk, current->uRefCount);
1848 /* Skip to the next item */
1849 current = current->next;
1853 /******************************************************************************
1854 * CoLockObjectExternal [OLE32.@]
1856 HRESULT WINAPI CoLockObjectExternal(
1857 LPUNKNOWN pUnk, /* [in] object to be locked */
1858 BOOL fLock, /* [in] do lock */
1859 BOOL fLastUnlockReleases) /* [in] unlock all */
1862 if (fLock) {
1864 * Increment the external lock coutner, COM_ExternalLockAddRef also
1865 * increment the object's internal lock counter.
1867 COM_ExternalLockAddRef( pUnk);
1868 } else {
1870 * Decrement the external lock coutner, COM_ExternalLockRelease also
1871 * decrement the object's internal lock counter.
1873 COM_ExternalLockRelease( pUnk, fLastUnlockReleases);
1876 return S_OK;
1879 /***********************************************************************
1880 * CoInitializeWOW (OLE32.@)
1882 HRESULT WINAPI CoInitializeWOW(DWORD x,DWORD y) {
1883 FIXME("(0x%08lx,0x%08lx),stub!\n",x,y);
1884 return 0;
1887 static int nStatCounter = 0; /* global */
1888 static HMODULE hOleAut32 = 0; /* global */
1890 /***********************************************************************
1891 * CoGetState [OLE32.@]
1893 * NOTES: might be incomplete
1895 HRESULT WINAPI CoGetState(IUnknown ** ppv)
1897 APARTMENT * apt = COM_CurrentInfo();
1899 FIXME("\n");
1901 if(apt && apt->state) {
1902 IUnknown_AddRef(apt->state);
1903 *ppv = apt->state;
1904 FIXME("-- %p\n", *ppv);
1905 return S_OK;
1907 *ppv = NULL;
1908 return E_FAIL;
1912 /***********************************************************************
1913 * CoSetState [OLE32.@]
1915 * NOTES: FIXME: protect this with a crst
1917 HRESULT WINAPI CoSetState(IUnknown * pv)
1919 APARTMENT * apt = COM_CurrentInfo();
1921 if (!apt) apt = COM_CreateApartment(COINIT_UNINITIALIZED);
1923 FIXME("(%p),stub!\n", pv);
1925 if (pv) {
1926 IUnknown_AddRef(pv);
1927 nStatCounter++;
1928 if (nStatCounter == 1) LoadLibraryA("OLEAUT32.DLL");
1931 if (apt->state) {
1932 TRACE("-- release %p now\n", apt->state);
1933 IUnknown_Release(apt->state);
1934 nStatCounter--;
1935 if (!nStatCounter) FreeLibrary(hOleAut32);
1937 apt->state = pv;
1938 return S_OK;
1942 /******************************************************************************
1943 * OleGetAutoConvert [OLE32.@]
1945 HRESULT WINAPI OleGetAutoConvert(REFCLSID clsidOld, LPCLSID pClsidNew)
1947 HKEY hkey = 0;
1948 char buf[200];
1949 WCHAR wbuf[200];
1950 DWORD len;
1951 HRESULT res = S_OK;
1953 sprintf(buf,"CLSID\\");WINE_StringFromCLSID(clsidOld,&buf[6]);
1954 if (RegOpenKeyA(HKEY_CLASSES_ROOT,buf,&hkey))
1956 res = REGDB_E_CLASSNOTREG;
1957 goto done;
1959 len = 200;
1960 /* we can just query for the default value of AutoConvertTo key like that,
1961 without opening the AutoConvertTo key and querying for NULL (default) */
1962 if (RegQueryValueA(hkey,"AutoConvertTo",buf,&len))
1964 res = REGDB_E_KEYMISSING;
1965 goto done;
1967 MultiByteToWideChar( CP_ACP, 0, buf, -1, wbuf, sizeof(wbuf)/sizeof(WCHAR) );
1968 CLSIDFromString(wbuf,pClsidNew);
1969 done:
1970 if (hkey) RegCloseKey(hkey);
1971 return res;
1974 /******************************************************************************
1975 * OleSetAutoConvert [OLE32.@]
1977 HRESULT WINAPI OleSetAutoConvert(REFCLSID clsidOld, REFCLSID clsidNew)
1979 HKEY hkey = 0;
1980 char buf[200], szClsidNew[200];
1981 HRESULT res = S_OK;
1983 TRACE("(%s,%s)\n", debugstr_guid(clsidOld), debugstr_guid(clsidNew));
1984 sprintf(buf,"CLSID\\");WINE_StringFromCLSID(clsidOld,&buf[6]);
1985 WINE_StringFromCLSID(clsidNew, szClsidNew);
1986 if (RegOpenKeyA(HKEY_CLASSES_ROOT,buf,&hkey))
1988 res = REGDB_E_CLASSNOTREG;
1989 goto done;
1991 if (RegSetValueA(hkey, "AutoConvertTo", REG_SZ, szClsidNew, strlen(szClsidNew)+1))
1993 res = REGDB_E_WRITEREGDB;
1994 goto done;
1997 done:
1998 if (hkey) RegCloseKey(hkey);
1999 return res;
2002 /******************************************************************************
2003 * OleDoAutoConvert [OLE32.@]
2005 HRESULT WINAPI OleDoAutoConvert(IStorage *pStg, LPCLSID pClsidNew)
2007 FIXME("(%p,%p) : stub\n",pStg,pClsidNew);
2008 return E_NOTIMPL;
2011 /******************************************************************************
2012 * CoTreatAsClass [OLE32.@]
2014 HRESULT WINAPI CoTreatAsClass(REFCLSID clsidOld, REFCLSID clsidNew)
2016 HKEY hkey = 0;
2017 char buf[200], szClsidNew[200];
2018 HRESULT res = S_OK;
2020 FIXME("(%s,%s)\n", debugstr_guid(clsidOld), debugstr_guid(clsidNew));
2021 sprintf(buf,"CLSID\\");WINE_StringFromCLSID(clsidOld,&buf[6]);
2022 WINE_StringFromCLSID(clsidNew, szClsidNew);
2023 if (RegOpenKeyA(HKEY_CLASSES_ROOT,buf,&hkey))
2025 res = REGDB_E_CLASSNOTREG;
2026 goto done;
2028 if (RegSetValueA(hkey, "AutoTreatAs", REG_SZ, szClsidNew, strlen(szClsidNew)+1))
2030 res = REGDB_E_WRITEREGDB;
2031 goto done;
2034 done:
2035 if (hkey) RegCloseKey(hkey);
2036 return res;
2039 /******************************************************************************
2040 * CoGetTreatAsClass [OLE32.@]
2042 * Reads the TreatAs value from a class.
2044 HRESULT WINAPI CoGetTreatAsClass(REFCLSID clsidOld, LPCLSID clsidNew)
2046 HKEY hkey = 0;
2047 char buf[200], szClsidNew[200];
2048 HRESULT res = S_OK;
2049 LONG len = sizeof(szClsidNew);
2051 FIXME("(%s,%p)\n", debugstr_guid(clsidOld), clsidNew);
2052 sprintf(buf,"CLSID\\");WINE_StringFromCLSID(clsidOld,&buf[6]);
2053 memcpy(clsidNew,clsidOld,sizeof(CLSID)); /* copy over old value */
2055 if (RegOpenKeyA(HKEY_CLASSES_ROOT,buf,&hkey))
2057 res = REGDB_E_CLASSNOTREG;
2058 goto done;
2060 if (RegQueryValueA(hkey, "TreatAs", szClsidNew, &len))
2062 res = S_FALSE;
2063 goto done;
2065 res = __CLSIDFromStringA(szClsidNew,clsidNew);
2066 if (FAILED(res))
2067 FIXME("Failed CLSIDFromStringA(%s), hres %lx?\n",szClsidNew,res);
2068 done:
2069 if (hkey) RegCloseKey(hkey);
2070 return res;
2074 /***********************************************************************
2075 * IsEqualGUID [OLE32.@]
2077 * Compares two Unique Identifiers.
2079 * RETURNS
2080 * TRUE if equal
2082 #undef IsEqualGUID
2083 BOOL WINAPI IsEqualGUID(
2084 REFGUID rguid1, /* [in] unique id 1 */
2085 REFGUID rguid2 /* [in] unique id 2 */
2088 return !memcmp(rguid1,rguid2,sizeof(GUID));
2091 /***********************************************************************
2092 * CoInitializeSecurity [OLE32.@]
2094 HRESULT WINAPI CoInitializeSecurity(PSECURITY_DESCRIPTOR pSecDesc, LONG cAuthSvc,
2095 SOLE_AUTHENTICATION_SERVICE* asAuthSvc,
2096 void* pReserved1, DWORD dwAuthnLevel,
2097 DWORD dwImpLevel, void* pReserved2,
2098 DWORD dwCapabilities, void* pReserved3)
2100 FIXME("(%p,%ld,%p,%p,%ld,%ld,%p,%ld,%p) - stub!\n", pSecDesc, cAuthSvc,
2101 asAuthSvc, pReserved1, dwAuthnLevel, dwImpLevel, pReserved2,
2102 dwCapabilities, pReserved3);
2103 return S_OK;