Updated.
[wine] / dlls / ole32 / compobj.c
1 /*
2  *      COMPOBJ library
3  *
4  *      Copyright 1995  Martin von Loewis
5  *      Copyright 1998  Justin Bradford
6  *      Copyright 1999  Francis Beaudet
7  *  Copyright 1999  Sylvain St-Germain
8  */
9
10 #include "config.h"
11
12 #include <stdlib.h>
13 #include <stdio.h>
14 #include <string.h>
15 #include <assert.h>
16 #include "windef.h"
17 #include "wtypes.h"
18 #include "wingdi.h"
19 #include "wine/winbase16.h"
20 #include "winerror.h"
21 #include "wownt32.h"
22 #include "ole2ver.h"
23 #include "debugtools.h"
24 #include "heap.h"
25 #include "winreg.h"
26 #include "rpc.h"
27
28 #include "wine/obj_base.h"
29 #include "wine/obj_misc.h"
30 #include "wine/obj_storage.h"
31 #include "wine/obj_clientserver.h"
32
33 #include "ole.h"
34 #include "ifs.h"
35 #include "compobj_private.h"
36
37 DEFAULT_DEBUG_CHANNEL(ole);
38
39 /****************************************************************************
40  *  COM External Lock structures and methods declaration
41  *
42  *  This api provides a linked list to managed external references to 
43  *  COM objects.  
44  *
45  *  The public interface consists of three calls: 
46  *      COM_ExternalLockAddRef
47  *      COM_ExternalLockRelease
48  *      COM_ExternalLockFreeList
49  */
50
51 #define EL_END_OF_LIST 0
52 #define EL_NOT_FOUND   0
53
54 /*
55  * Declaration of the static structure that manage the 
56  * external lock to COM  objects.
57  */
58 typedef struct COM_ExternalLock     COM_ExternalLock;
59 typedef struct COM_ExternalLockList COM_ExternalLockList;
60
61 struct COM_ExternalLock
62 {
63   IUnknown         *pUnk;     /* IUnknown referenced */
64   ULONG            uRefCount; /* external lock counter to IUnknown object*/
65   COM_ExternalLock *next;     /* Pointer to next element in list */
66 };
67
68 struct COM_ExternalLockList
69 {
70   COM_ExternalLock *head;     /* head of list */
71 };
72
73 /*
74  * Declaration and initialization of the static structure that manages
75  * the external lock to COM objects.
76  */
77 static COM_ExternalLockList elList = { EL_END_OF_LIST };
78
79 /*
80  * Public Interface to the external lock list   
81  */
82 static void COM_ExternalLockFreeList();
83 static void COM_ExternalLockAddRef(IUnknown *pUnk);
84 static void COM_ExternalLockRelease(IUnknown *pUnk, BOOL bRelAll);
85 void COM_ExternalLockDump(); /* testing purposes, not static to avoid warning */
86
87 /*
88  * Private methods used to managed the linked list   
89  */
90 static BOOL COM_ExternalLockInsert(
91   IUnknown *pUnk);
92
93 static void COM_ExternalLockDelete(
94   COM_ExternalLock *element);
95
96 static COM_ExternalLock* COM_ExternalLockFind(
97   IUnknown *pUnk);
98
99 static COM_ExternalLock* COM_ExternalLockLocate(
100   COM_ExternalLock *element,
101   IUnknown         *pUnk);
102
103 /****************************************************************************
104  * This section defines variables internal to the COM module.
105  *
106  * TODO: Most of these things will have to be made thread-safe.
107  */
108 HINSTANCE16     COMPOBJ_hInstance = 0;
109 HINSTANCE       COMPOBJ_hInstance32 = 0;
110 static int      COMPOBJ_Attach = 0;
111
112 LPMALLOC16 currentMalloc16=NULL;
113 LPMALLOC currentMalloc32=NULL;
114
115 HTASK16 hETask = 0;
116 WORD Table_ETask[62];
117
118 /*
119  * This lock count counts the number of times CoInitialize is called. It is
120  * decreased every time CoUninitialize is called. When it hits 0, the COM
121  * libraries are freed
122  */
123 static ULONG s_COMLockCount = 0;
124
125 /*
126  * This linked list contains the list of registered class objects. These
127  * are mostly used to register the factories for out-of-proc servers of OLE
128  * objects.
129  *
130  * TODO: Make this data structure aware of inter-process communication. This
131  *       means that parts of this will be exported to the Wine Server.
132  */
133 typedef struct tagRegisteredClass
134 {
135   CLSID     classIdentifier;
136   LPUNKNOWN classObject;
137   DWORD     runContext;
138   DWORD     connectFlags;
139   DWORD     dwCookie;
140   struct tagRegisteredClass* nextClass;
141 } RegisteredClass;
142
143 static RegisteredClass* firstRegisteredClass = NULL;
144
145 /* this open DLL table belongs in a per process table, but my guess is that
146  * it shouldn't live in the kernel, so I'll put them out here in DLL
147  * space assuming that there is one OLE32 per process.
148  */
149 typedef struct tagOpenDll {
150   HINSTANCE hLibrary;       
151   struct tagOpenDll *next;
152 } OpenDll;
153
154 static OpenDll *openDllList = NULL; /* linked list of open dlls */
155
156 /*****************************************************************************
157  * This section contains prototypes to internal methods for this
158  * module
159  */
160 static HRESULT COM_GetRegisteredClassObject(REFCLSID    rclsid,
161                                             DWORD       dwClsContext,
162                                             LPUNKNOWN*  ppUnk);
163
164 static void COM_RevokeAllClasses();
165
166
167 /******************************************************************************
168  *           CoBuildVersion [COMPOBJ.1]
169  *
170  * RETURNS
171  *      Current build version, hiword is majornumber, loword is minornumber
172  */
173 DWORD WINAPI CoBuildVersion(void)
174 {
175     TRACE("Returning version %d, build %d.\n", rmm, rup);
176     return (rmm<<16)+rup;
177 }
178
179 /******************************************************************************
180  *              CoInitialize16  [COMPOBJ.2]
181  * Set the win16 IMalloc used for memory management
182  */
183 HRESULT WINAPI CoInitialize16(
184         LPVOID lpReserved       /* [in] pointer to win16 malloc interface */
185 ) {
186     currentMalloc16 = (LPMALLOC16)lpReserved;
187     return S_OK;
188 }
189
190 /******************************************************************************
191  *              CoInitialize    [OLE32.26]
192  *
193  * Initializes the COM libraries.
194  *
195  * See CoInitializeEx
196  */
197 HRESULT WINAPI CoInitialize(
198         LPVOID lpReserved       /* [in] pointer to win32 malloc interface
199                                    (obsolete, should be NULL) */
200
201 {
202   /*
203    * Just delegate to the newer method.
204    */
205   return CoInitializeEx(lpReserved, COINIT_APARTMENTTHREADED);
206 }
207
208 /******************************************************************************
209  *              CoInitializeEx  [OLE32.163]
210  *
211  * Initializes the COM libraries. The behavior used to set the win32 IMalloc
212  * used for memory management is obsolete.
213  *
214  * RETURNS
215  *  S_OK               if successful,
216  *  S_FALSE            if this function was called already.
217  *  RPC_E_CHANGED_MODE if a previous call to CoInitialize specified another
218  *                      threading model.
219  *
220  * BUGS
221  * Only the single threaded model is supported. As a result RPC_E_CHANGED_MODE 
222  * is never returned.
223  *
224  * See the windows documentation for more details.
225  */
226 HRESULT WINAPI CoInitializeEx(
227         LPVOID lpReserved,      /* [in] pointer to win32 malloc interface
228                                    (obsolete, should be NULL) */
229         DWORD dwCoInit          /* [in] A value from COINIT specifies the threading model */
230
231 {
232   HRESULT hr;
233
234   TRACE("(%p, %x)\n", lpReserved, (int)dwCoInit);
235
236   if (lpReserved!=NULL)
237   {
238     ERR("(%p, %x) - Bad parameter passed-in %p, must be an old Windows Application\n", lpReserved, (int)dwCoInit, lpReserved);
239   }
240
241   /*
242    * Check for unsupported features.
243    */
244   if (dwCoInit!=COINIT_APARTMENTTHREADED) 
245   {
246     FIXME(":(%p,%x): unsupported flag %x\n", lpReserved, (int)dwCoInit, (int)dwCoInit);
247     /* Hope for the best and continue anyway */
248   }
249
250   /*
251    * Check the lock count. If this is the first time going through the initialize
252    * process, we have to initialize the libraries.
253    */
254   if (s_COMLockCount==0)
255   {
256     /*
257      * Initialize the various COM libraries and data structures.
258      */
259     TRACE("() - Initializing the COM libraries\n");
260
261     RunningObjectTableImpl_Initialize();
262
263     hr = S_OK;
264   }
265   else
266     hr = S_FALSE;
267
268   /*
269    * Crank-up that lock count.
270    */
271   s_COMLockCount++;
272
273   return hr;
274 }
275
276 /***********************************************************************
277  *           CoUninitialize16   [COMPOBJ.3]
278  * Don't know what it does. 
279  * 3-Nov-98 -- this was originally misspelled, I changed it to what I
280  *   believe is the correct spelling
281  */
282 void WINAPI CoUninitialize16(void)
283 {
284   TRACE("()\n");
285   CoFreeAllLibraries();
286 }
287
288 /***********************************************************************
289  *           CoUninitialize   [OLE32.47]
290  *
291  * This method will release the COM libraries.
292  *
293  * See the windows documentation for more details.
294  */
295 void WINAPI CoUninitialize(void)
296 {
297   TRACE("()\n");
298   
299   /*
300    * Decrease the reference count.
301    */
302   s_COMLockCount--;
303   
304   /*
305    * If we are back to 0 locks on the COM library, make sure we free
306    * all the associated data structures.
307    */
308   if (s_COMLockCount==0)
309   {
310     /*
311      * Release the various COM libraries and data structures.
312      */
313     TRACE("() - Releasing the COM libraries\n");
314
315     RunningObjectTableImpl_UnInitialize();
316     /*
317      * Release the references to the registered class objects.
318      */
319     COM_RevokeAllClasses();
320
321     /*
322      * This will free the loaded COM Dlls.
323      */
324     CoFreeAllLibraries();
325
326     /*
327      * This will free list of external references to COM objects.
328      */
329     COM_ExternalLockFreeList();
330 }
331 }
332
333 /***********************************************************************
334  *           CoGetMalloc16    [COMPOBJ.4]
335  * RETURNS
336  *      The current win16 IMalloc
337  */
338 HRESULT WINAPI CoGetMalloc16(
339         DWORD dwMemContext,     /* [in] unknown */
340         LPMALLOC16 * lpMalloc   /* [out] current win16 malloc interface */
341 ) {
342     if(!currentMalloc16)
343         currentMalloc16 = IMalloc16_Constructor();
344     *lpMalloc = currentMalloc16;
345     return S_OK;
346 }
347
348 /******************************************************************************
349  *              CoGetMalloc     [OLE32.20]
350  *
351  * RETURNS
352  *      The current win32 IMalloc
353  */
354 HRESULT WINAPI CoGetMalloc(
355         DWORD dwMemContext,     /* [in] unknown */
356         LPMALLOC *lpMalloc      /* [out] current win32 malloc interface */
357 ) {
358     if(!currentMalloc32)
359         currentMalloc32 = IMalloc_Constructor();
360     *lpMalloc = currentMalloc32;
361     return S_OK;
362 }
363
364 /***********************************************************************
365  *           CoCreateStandardMalloc16 [COMPOBJ.71]
366  */
367 HRESULT WINAPI CoCreateStandardMalloc16(DWORD dwMemContext,
368                                           LPMALLOC16 *lpMalloc)
369 {
370     /* FIXME: docu says we shouldn't return the same allocator as in
371      * CoGetMalloc16 */
372     *lpMalloc = IMalloc16_Constructor();
373     return S_OK;
374 }
375
376 /******************************************************************************
377  *              CoDisconnectObject      [COMPOBJ.15]
378  */
379 HRESULT WINAPI CoDisconnectObject( LPUNKNOWN lpUnk, DWORD reserved )
380 {
381     TRACE("(%p, %lx)\n",lpUnk,reserved);
382     return S_OK;
383 }
384
385 /***********************************************************************
386  *           IsEqualGUID16 [COMPOBJ.18]
387  *
388  * Compares two Unique Identifiers.
389  *
390  * RETURNS
391  *      TRUE if equal
392  */
393 BOOL16 WINAPI IsEqualGUID16(
394         GUID* g1,       /* [in] unique id 1 */
395         GUID* g2        /* [in] unique id 2 */
396 ) {
397     return !memcmp( g1, g2, sizeof(GUID) );
398 }
399
400 /******************************************************************************
401  *              CLSIDFromString16       [COMPOBJ.20]
402  * Converts a unique identifier from its string representation into 
403  * the GUID struct.
404  *
405  * Class id: DWORD-WORD-WORD-BYTES[2]-BYTES[6] 
406  *
407  * RETURNS
408  *      the converted GUID
409  */
410 HRESULT WINAPI CLSIDFromString16(
411         LPCOLESTR16 idstr,      /* [in] string representation of guid */
412         CLSID *id               /* [out] GUID converted from string */
413 ) {
414   BYTE *s = (BYTE *) idstr;
415   BYTE *p;
416   int   i;
417   BYTE table[256];
418
419   if (!s)
420           s = "{00000000-0000-0000-0000-000000000000}";
421   else {  /* validate the CLSID string */
422
423       if (strlen(s) != 38)
424           return CO_E_CLASSSTRING;
425
426       if ((s[0]!='{') || (s[9]!='-') || (s[14]!='-') || (s[19]!='-') || (s[24]!='-') || (s[37]!='}'))
427           return CO_E_CLASSSTRING;
428
429       for (i=1; i<37; i++)
430       {
431           if ((i == 9)||(i == 14)||(i == 19)||(i == 24)) continue;
432           if (!(((s[i] >= '0') && (s[i] <= '9'))  ||
433                 ((s[i] >= 'a') && (s[i] <= 'f'))  ||
434                 ((s[i] >= 'A') && (s[i] <= 'F')))
435              )
436               return CO_E_CLASSSTRING;
437       }
438   }
439
440   TRACE("%s -> %p\n", s, id);
441
442   /* quick lookup table */
443   memset(table, 0, 256);
444
445   for (i = 0; i < 10; i++) {
446     table['0' + i] = i;
447   }
448   for (i = 0; i < 6; i++) {
449     table['A' + i] = i+10;
450     table['a' + i] = i+10;
451   }
452
453   /* in form {XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX} */
454
455   p = (BYTE *) id;
456
457   s++;  /* skip leading brace  */
458   for (i = 0; i < 4; i++) {
459     p[3 - i] = table[*s]<<4 | table[*(s+1)];
460     s += 2;
461   }
462   p += 4;
463   s++;  /* skip - */
464
465   for (i = 0; i < 2; i++) {
466     p[1-i] = table[*s]<<4 | table[*(s+1)];
467     s += 2;
468   }
469   p += 2;
470   s++;  /* skip - */
471
472   for (i = 0; i < 2; i++) {
473     p[1-i] = table[*s]<<4 | table[*(s+1)];
474     s += 2;
475   }
476   p += 2;
477   s++;  /* skip - */
478
479   /* these are just sequential bytes */
480   for (i = 0; i < 2; i++) {
481     *p++ = table[*s]<<4 | table[*(s+1)];
482     s += 2;
483   }
484   s++;  /* skip - */
485
486   for (i = 0; i < 6; i++) {
487     *p++ = table[*s]<<4 | table[*(s+1)];
488     s += 2;
489   }
490
491   return S_OK;
492 }
493
494 /******************************************************************************
495  *              CoCreateGuid[OLE32.6]
496  *
497  */
498 HRESULT WINAPI CoCreateGuid(
499         GUID *pguid /* [out] points to the GUID to initialize */
500 ) {
501     return UuidCreate(pguid);
502 }
503
504 /******************************************************************************
505  *              CLSIDFromString [OLE32.3]
506  * Converts a unique identifier from its string representation into 
507  * the GUID struct.
508  *
509  * UNDOCUMENTED
510  *      If idstr is not a valid CLSID string then it gets treated as a ProgID
511  *
512  * RETURNS
513  *      the converted GUID
514  */
515 HRESULT WINAPI CLSIDFromString(
516         LPCOLESTR idstr,        /* [in] string representation of GUID */
517         CLSID *id               /* [out] GUID represented by above string */
518 ) {
519     LPOLESTR16      xid = HEAP_strdupWtoA(GetProcessHeap(),0,idstr);
520     HRESULT       ret = CLSIDFromString16(xid,id);
521
522     HeapFree(GetProcessHeap(),0,xid);
523     if(ret != S_OK) { /* It appears a ProgID is also valid */
524         ret = CLSIDFromProgID(idstr, id);
525     }
526     return ret;
527 }
528
529 /******************************************************************************
530  *              WINE_StringFromCLSID    [Internal]
531  * Converts a GUID into the respective string representation.
532  *
533  * NOTES
534  *
535  * RETURNS
536  *      the string representation and HRESULT
537  */
538 static HRESULT WINE_StringFromCLSID(
539         const CLSID *id,        /* [in] GUID to be converted */
540         LPSTR idstr             /* [out] pointer to buffer to contain converted guid */
541 ) {
542   static const char *hex = "0123456789ABCDEF";
543   char *s;
544   int   i;
545
546   if (!id)
547         { ERR("called with id=Null\n");
548           *idstr = 0x00;
549           return E_FAIL;
550         }
551         
552   sprintf(idstr, "{%08lX-%04X-%04X-%02X%02X-",
553           id->Data1, id->Data2, id->Data3,
554           id->Data4[0], id->Data4[1]);
555   s = &idstr[25];
556
557   /* 6 hex bytes */
558   for (i = 2; i < 8; i++) {
559     *s++ = hex[id->Data4[i]>>4];
560     *s++ = hex[id->Data4[i] & 0xf];
561   }
562
563   *s++ = '}';
564   *s++ = '\0';
565
566   TRACE("%p->%s\n", id, idstr);
567
568   return S_OK;
569 }
570
571 /******************************************************************************
572  *              StringFromCLSID16       [COMPOBJ.19]
573  * Converts a GUID into the respective string representation.
574  * The target string is allocated using the OLE IMalloc.
575  * RETURNS
576  *      the string representation and HRESULT
577  */
578 HRESULT WINAPI StringFromCLSID16(
579         REFCLSID id,            /* [in] the GUID to be converted */
580         LPOLESTR16 *idstr       /* [out] a pointer to a to-be-allocated segmented pointer pointing to the resulting string */
581
582 ) {
583     extern BOOL WINAPI K32WOWCallback16Ex( DWORD vpfn16, DWORD dwFlags,
584                                            DWORD cbArgs, LPVOID pArgs, LPDWORD pdwRetCode );
585     LPMALLOC16  mllc;
586     HRESULT     ret;
587     DWORD       args[2];
588
589     ret = CoGetMalloc16(0,&mllc);
590     if (ret) return ret;
591
592     args[0] = (DWORD)mllc;
593     args[1] = 40;
594
595     /* No need for a Callback entry, we have WOWCallback16Ex which does
596      * everything we need.
597      */
598     if (!K32WOWCallback16Ex(
599         (DWORD)((ICOM_VTABLE(IMalloc16)*)MapSL(
600             (SEGPTR)ICOM_VTBL(((LPMALLOC16)MapSL((SEGPTR)mllc))))
601         )->Alloc,
602         WCB16_CDECL,
603         2*sizeof(DWORD),
604         (LPVOID)args,
605         (LPDWORD)idstr
606     )) {
607         WARN("CallTo16 IMalloc16 failed\n");
608         return E_FAIL;
609     }
610     return WINE_StringFromCLSID(id,MapSL((SEGPTR)*idstr));
611 }
612
613 /******************************************************************************
614  *              StringFromCLSID [OLE32.151]
615  * Converts a GUID into the respective string representation.
616  * The target string is allocated using the OLE IMalloc.
617  * RETURNS
618  *      the string representation and HRESULT
619  */
620 HRESULT WINAPI StringFromCLSID(
621         REFCLSID id,            /* [in] the GUID to be converted */
622         LPOLESTR *idstr /* [out] a pointer to a to-be-allocated pointer pointing to the resulting string */
623 ) {
624         char            buf[80];
625         HRESULT       ret;
626         LPMALLOC        mllc;
627
628         if ((ret=CoGetMalloc(0,&mllc)))
629                 return ret;
630
631         ret=WINE_StringFromCLSID(id,buf);
632         if (!ret) {
633             DWORD len = MultiByteToWideChar( CP_ACP, 0, buf, -1, NULL, 0 );
634             *idstr = IMalloc_Alloc( mllc, len * sizeof(WCHAR) );
635             MultiByteToWideChar( CP_ACP, 0, buf, -1, *idstr, len );
636         }
637         return ret;
638 }
639
640 /******************************************************************************
641  *              StringFromGUID2 [COMPOBJ.76] [OLE32.152]
642  *
643  * Converts a global unique identifier into a string of an API-
644  * specified fixed format. (The usual {.....} stuff.)
645  *
646  * RETURNS
647  *      The (UNICODE) string representation of the GUID in 'str'
648  *      The length of the resulting string, 0 if there was any problem.
649  */
650 INT WINAPI
651 StringFromGUID2(REFGUID id, LPOLESTR str, INT cmax)
652 {
653   char          xguid[80];
654
655   if (WINE_StringFromCLSID(id,xguid))
656         return 0;
657   return MultiByteToWideChar( CP_ACP, 0, xguid, -1, str, cmax );
658 }
659
660 /******************************************************************************
661  * ProgIDFromCLSID [OLE32.133]
662  * Converts a class id into the respective Program ID. (By using a registry lookup)
663  * RETURNS S_OK on success
664  * riid associated with the progid
665  */
666
667 HRESULT WINAPI ProgIDFromCLSID(
668   REFCLSID clsid, /* [in] class id as found in registry */
669   LPOLESTR *lplpszProgID/* [out] associated Prog ID */
670 )
671 {
672   char     strCLSID[50], *buf, *buf2;
673   DWORD    buf2len;
674   HKEY     xhkey;
675   LPMALLOC mllc;
676   HRESULT  ret = S_OK;
677
678   WINE_StringFromCLSID(clsid, strCLSID);
679
680   buf = HeapAlloc(GetProcessHeap(), 0, strlen(strCLSID)+14);
681   sprintf(buf,"CLSID\\%s\\ProgID", strCLSID);
682   if (RegOpenKeyA(HKEY_CLASSES_ROOT, buf, &xhkey))
683     ret = REGDB_E_CLASSNOTREG;
684
685   HeapFree(GetProcessHeap(), 0, buf);
686
687   if (ret == S_OK)
688   {
689     buf2 = HeapAlloc(GetProcessHeap(), 0, 255);
690     buf2len = 255;
691     if (RegQueryValueA(xhkey, NULL, buf2, &buf2len))
692       ret = REGDB_E_CLASSNOTREG;
693
694     if (ret == S_OK)
695     {
696       if (CoGetMalloc(0,&mllc))
697         ret = E_OUTOFMEMORY;
698       else
699       {
700           DWORD len = MultiByteToWideChar( CP_ACP, 0, buf2, -1, NULL, 0 );
701           *lplpszProgID = IMalloc_Alloc(mllc, len * sizeof(WCHAR) );
702           MultiByteToWideChar( CP_ACP, 0, buf2, -1, *lplpszProgID, len );
703       }
704     }
705     HeapFree(GetProcessHeap(), 0, buf2);
706   }
707
708   RegCloseKey(xhkey);
709   return ret;
710 }
711
712 /******************************************************************************
713  *              CLSIDFromProgID16       [COMPOBJ.61]
714  * Converts a program id into the respective GUID. (By using a registry lookup)
715  * RETURNS
716  *      riid associated with the progid
717  */
718 HRESULT WINAPI CLSIDFromProgID16(
719         LPCOLESTR16 progid,     /* [in] program id as found in registry */
720         LPCLSID riid            /* [out] associated CLSID */
721 ) {
722         char    *buf,buf2[80];
723         DWORD   buf2len;
724         HRESULT err;
725         HKEY    xhkey;
726
727         buf = HeapAlloc(GetProcessHeap(),0,strlen(progid)+8);
728         sprintf(buf,"%s\\CLSID",progid);
729         if ((err=RegOpenKeyA(HKEY_CLASSES_ROOT,buf,&xhkey))) {
730                 HeapFree(GetProcessHeap(),0,buf);
731                 return CO_E_CLASSSTRING;
732         }
733         HeapFree(GetProcessHeap(),0,buf);
734         buf2len = sizeof(buf2);
735         if ((err=RegQueryValueA(xhkey,NULL,buf2,&buf2len))) {
736                 RegCloseKey(xhkey);
737                 return CO_E_CLASSSTRING;
738         }
739         RegCloseKey(xhkey);
740         return CLSIDFromString16(buf2,riid);
741 }
742
743 /******************************************************************************
744  *              CLSIDFromProgID [OLE32.2]
745  * Converts a program id into the respective GUID. (By using a registry lookup)
746  * RETURNS
747  *      riid associated with the progid
748  */
749 HRESULT WINAPI CLSIDFromProgID(
750         LPCOLESTR progid,       /* [in] program id as found in registry */
751         LPCLSID riid            /* [out] associated CLSID */
752 ) {
753         LPOLESTR16 pid = HEAP_strdupWtoA(GetProcessHeap(),0,progid);
754         HRESULT       ret = CLSIDFromProgID16(pid,riid);
755
756         HeapFree(GetProcessHeap(),0,pid);
757         return ret;
758 }
759
760
761
762 /*****************************************************************************
763  *             CoGetPSClsid [OLE32.22]
764  *
765  * This function returns the CLSID of the DLL that implements the proxy and stub
766  * for the specified interface. 
767  *
768  * It determines this by searching the 
769  * HKEY_CLASSES_ROOT\Interface\{string form of riid}\ProxyStubClsid32 in the registry
770  * and any interface id registered by CoRegisterPSClsid within the current process.
771  * 
772  * FIXME: We only search the registry, not ids registered with CoRegisterPSClsid.
773  */
774 HRESULT WINAPI CoGetPSClsid(
775           REFIID riid,     /* [in]  Interface whose proxy/stub CLSID is to be returned */
776           CLSID *pclsid )    /* [out] Where to store returned proxy/stub CLSID */
777 {
778     char *buf, buf2[40];
779     DWORD buf2len;
780     HKEY xhkey;
781
782     TRACE("() riid=%s, pclsid=%p\n", debugstr_guid(riid), pclsid);
783
784     /* Get the input iid as a string */
785     WINE_StringFromCLSID(riid, buf2);
786     /* Allocate memory for the registry key we will construct.
787        (length of iid string plus constant length of static text */
788     buf = HeapAlloc(GetProcessHeap(), 0, strlen(buf2)+27);
789     if (buf == NULL)
790     {
791        return (E_OUTOFMEMORY);
792     }
793
794     /* Construct the registry key we want */
795     sprintf(buf,"Interface\\%s\\ProxyStubClsid32", buf2);
796
797     /* Open the key.. */
798     if (RegOpenKeyA(HKEY_CLASSES_ROOT, buf, &xhkey))
799     {
800        HeapFree(GetProcessHeap(),0,buf);
801        return (E_INVALIDARG);
802     }
803     HeapFree(GetProcessHeap(),0,buf);
804
805     /* ... Once we have the key, query the registry to get the
806        value of CLSID as a string, and convert it into a 
807        proper CLSID structure to be passed back to the app */
808     buf2len = sizeof(buf2);
809     if ( (RegQueryValueA(xhkey,NULL,buf2,&buf2len)) )
810     {
811        RegCloseKey(xhkey);
812        return E_INVALIDARG;
813     }
814     RegCloseKey(xhkey);
815
816     /* We have the CLSid we want back from the registry as a string, so
817        lets convert it into a CLSID structure */
818     if ( (CLSIDFromString16(buf2,pclsid)) != NOERROR)
819     {
820        return E_INVALIDARG;
821     }
822
823     TRACE ("() Returning CLSID=%s\n", debugstr_guid(pclsid));
824     return (S_OK);
825 }
826
827
828
829 /***********************************************************************
830  *              WriteClassStm
831  *
832  * This function write a CLSID on stream
833  */
834 HRESULT WINAPI WriteClassStm(IStream *pStm,REFCLSID rclsid)
835 {
836     TRACE("(%p,%p)\n",pStm,rclsid);
837
838     if (rclsid==NULL)
839         return E_INVALIDARG;
840
841     return IStream_Write(pStm,rclsid,sizeof(CLSID),NULL);
842 }
843
844 /***********************************************************************
845  *              ReadClassStm
846  *
847  * This function read a CLSID from a stream
848  */
849 HRESULT WINAPI ReadClassStm(IStream *pStm,REFCLSID rclsid)
850 {
851     ULONG nbByte;
852     HRESULT res;
853     
854     TRACE("(%p,%p)\n",pStm,rclsid);
855
856     if (rclsid==NULL)
857         return E_INVALIDARG;
858     
859     res = IStream_Read(pStm,(void*)rclsid,sizeof(CLSID),&nbByte);
860
861     if (FAILED(res))
862         return res;
863     
864     if (nbByte != sizeof(CLSID))
865         return S_FALSE;
866     else
867         return S_OK;
868 }
869
870 /* FIXME: this function is not declared in the WINELIB headers. But where should it go ? */
871 /***********************************************************************
872  *           LookupETask (COMPOBJ.94)
873  */
874 HRESULT WINAPI LookupETask16(HTASK16 *hTask,LPVOID p) {
875         FIXME("(%p,%p),stub!\n",hTask,p);
876         if ((*hTask = GetCurrentTask()) == hETask) {
877                 memcpy(p, Table_ETask, sizeof(Table_ETask));
878         }
879         return 0;
880 }
881
882 /* FIXME: this function is not declared in the WINELIB headers. But where should it go ? */
883 /***********************************************************************
884  *           SetETask (COMPOBJ.95)
885  */
886 HRESULT WINAPI SetETask16(HTASK16 hTask, LPVOID p) {
887         FIXME("(%04x,%p),stub!\n",hTask,p);
888         hETask = hTask;
889         return 0;
890 }
891
892 /* FIXME: this function is not declared in the WINELIB headers. But where should it go ? */
893 /***********************************************************************
894  *           CallObjectInWOW (COMPOBJ.201)
895  */
896 HRESULT WINAPI CallObjectInWOW(LPVOID p1,LPVOID p2) {
897         FIXME("(%p,%p),stub!\n",p1,p2);
898         return 0;
899 }
900
901 /******************************************************************************
902  *              CoRegisterClassObject16 [COMPOBJ.5]
903  *
904  * Don't know where it registers it ...
905  */
906 HRESULT WINAPI CoRegisterClassObject16(
907         REFCLSID rclsid,
908         LPUNKNOWN pUnk,
909         DWORD dwClsContext, /* [in] CLSCTX flags indicating the context in which to run the executable */
910         DWORD flags,        /* [in] REGCLS flags indicating how connections are made */
911         LPDWORD lpdwRegister
912 ) {
913         char    buf[80];
914
915         WINE_StringFromCLSID(rclsid,buf);
916
917         FIXME("(%s,%p,0x%08lx,0x%08lx,%p),stub\n",
918                 buf,pUnk,dwClsContext,flags,lpdwRegister
919         );
920         return 0;
921 }
922
923
924 /******************************************************************************
925  *      CoRevokeClassObject16 [COMPOBJ.6]
926  *
927  */
928 HRESULT WINAPI CoRevokeClassObject16(DWORD dwRegister) /* [in] token on class obj */
929 {
930     FIXME("(0x%08lx),stub!\n", dwRegister);
931     return 0;
932 }
933
934
935 /***
936  * COM_GetRegisteredClassObject
937  *
938  * This internal method is used to scan the registered class list to 
939  * find a class object.
940  *
941  * Params: 
942  *   rclsid        Class ID of the class to find.
943  *   dwClsContext  Class context to match.
944  *   ppv           [out] returns a pointer to the class object. Complying
945  *                 to normal COM usage, this method will increase the
946  *                 reference count on this object.
947  */
948 static HRESULT COM_GetRegisteredClassObject(
949         REFCLSID    rclsid,
950         DWORD       dwClsContext,
951         LPUNKNOWN*  ppUnk)
952 {
953   RegisteredClass* curClass;
954
955   /*
956    * Sanity check
957    */
958   assert(ppUnk!=0);
959
960   /*
961    * Iterate through the whole list and try to match the class ID.
962    */
963   curClass = firstRegisteredClass;
964
965   while (curClass != 0)
966   {
967     /*
968      * Check if we have a match on the class ID.
969      */
970     if (IsEqualGUID(&(curClass->classIdentifier), rclsid))
971     {
972       /*
973        * Since we don't do out-of process or DCOM just right away, let's ignore the
974        * class context.
975        */
976
977       /*
978        * We have a match, return the pointer to the class object.
979        */
980       *ppUnk = curClass->classObject;
981
982       IUnknown_AddRef(curClass->classObject);
983
984       return S_OK;
985     }
986
987     /*
988      * Step to the next class in the list.
989      */
990     curClass = curClass->nextClass;
991   }
992
993   /*
994    * If we get to here, we haven't found our class.
995    */
996   return S_FALSE;
997 }
998
999 /******************************************************************************
1000  *              CoRegisterClassObject   [OLE32.36]
1001  *
1002  * This method will register the class object for a given class ID.
1003  *
1004  * See the Windows documentation for more details.
1005  */
1006 HRESULT WINAPI CoRegisterClassObject(
1007         REFCLSID rclsid,
1008         LPUNKNOWN pUnk,
1009         DWORD dwClsContext, /* [in] CLSCTX flags indicating the context in which to run the executable */
1010         DWORD flags,        /* [in] REGCLS flags indicating how connections are made */
1011         LPDWORD lpdwRegister
1012
1013 {
1014   RegisteredClass* newClass;
1015   LPUNKNOWN        foundObject;
1016   HRESULT          hr;
1017     char buf[80];
1018
1019     WINE_StringFromCLSID(rclsid,buf);
1020
1021   TRACE("(%s,%p,0x%08lx,0x%08lx,%p)\n",
1022         buf,pUnk,dwClsContext,flags,lpdwRegister);
1023
1024   /*
1025    * Perform a sanity check on the parameters
1026    */
1027   if ( (lpdwRegister==0) || (pUnk==0) )
1028   {
1029     return E_INVALIDARG;
1030 }
1031
1032   /*
1033    * Initialize the cookie (out parameter)
1034    */
1035   *lpdwRegister = 0;
1036
1037   /*
1038    * First, check if the class is already registered.
1039    * If it is, this should cause an error.
1040    */
1041   hr = COM_GetRegisteredClassObject(rclsid, dwClsContext, &foundObject);
1042
1043   if (hr == S_OK)
1044   {
1045     /*
1046      * The COM_GetRegisteredClassObject increased the reference count on the
1047      * object so it has to be released.
1048      */
1049     IUnknown_Release(foundObject);
1050
1051     return CO_E_OBJISREG;
1052   }
1053     
1054   /*
1055    * If it is not registered, we must create a new entry for this class and
1056    * append it to the registered class list.
1057    * We use the address of the chain node as the cookie since we are sure it's
1058    * unique.
1059    */
1060   newClass = HeapAlloc(GetProcessHeap(), 0, sizeof(RegisteredClass));
1061
1062   /*
1063    * Initialize the node.
1064    */
1065   newClass->classIdentifier = *rclsid;
1066   newClass->runContext      = dwClsContext;
1067   newClass->connectFlags    = flags;
1068   newClass->dwCookie        = (DWORD)newClass;
1069   newClass->nextClass       = firstRegisteredClass;
1070
1071   /*
1072    * Since we're making a copy of the object pointer, we have to increase its
1073    * reference count.
1074    */
1075   newClass->classObject     = pUnk;
1076   IUnknown_AddRef(newClass->classObject);
1077
1078   firstRegisteredClass = newClass;
1079
1080   /*
1081    * Assign the out parameter (cookie)
1082    */
1083   *lpdwRegister = newClass->dwCookie;
1084     
1085   /*
1086    * We're successful Yippee!
1087    */
1088   return S_OK;
1089 }
1090
1091 /***********************************************************************
1092  *           CoRevokeClassObject [OLE32.40]
1093  *
1094  * This method will remove a class object from the class registry
1095  *
1096  * See the Windows documentation for more details.
1097  */
1098 HRESULT WINAPI CoRevokeClassObject(
1099         DWORD dwRegister) 
1100 {
1101   RegisteredClass** prevClassLink;
1102   RegisteredClass*  curClass;
1103
1104   TRACE("(%08lx)\n",dwRegister);
1105
1106   /*
1107    * Iterate through the whole list and try to match the cookie.
1108    */
1109   curClass      = firstRegisteredClass;
1110   prevClassLink = &firstRegisteredClass;
1111
1112   while (curClass != 0)
1113   {
1114     /*
1115      * Check if we have a match on the cookie.
1116      */
1117     if (curClass->dwCookie == dwRegister)
1118     {
1119       /*
1120        * Remove the class from the chain.
1121        */
1122       *prevClassLink = curClass->nextClass;
1123
1124       /*
1125        * Release the reference to the class object.
1126        */
1127       IUnknown_Release(curClass->classObject);
1128
1129       /*
1130        * Free the memory used by the chain node.
1131  */
1132       HeapFree(GetProcessHeap(), 0, curClass);
1133
1134     return S_OK;
1135 }
1136
1137     /*
1138      * Step to the next class in the list.
1139      */
1140     prevClassLink = &(curClass->nextClass);
1141     curClass      = curClass->nextClass;
1142   }
1143
1144   /*
1145    * If we get to here, we haven't found our class.
1146    */
1147   return E_INVALIDARG;
1148 }
1149
1150 /***********************************************************************
1151  *           CoGetClassObject [COMPOBJ.7]
1152  */
1153 HRESULT WINAPI CoGetClassObject(REFCLSID rclsid, DWORD dwClsContext,
1154                         LPVOID pvReserved, REFIID iid, LPVOID *ppv)
1155 {
1156     LPUNKNOWN   regClassObject;
1157     HRESULT     hres = E_UNEXPECTED;
1158     char        xclsid[80];
1159     WCHAR dllName[MAX_PATH+1];
1160     DWORD dllNameLen = sizeof(dllName);
1161     HINSTANCE hLibrary;
1162     typedef HRESULT CALLBACK (*DllGetClassObjectFunc)(REFCLSID clsid, 
1163                              REFIID iid, LPVOID *ppv);
1164     DllGetClassObjectFunc DllGetClassObject;
1165
1166     WINE_StringFromCLSID((LPCLSID)rclsid,xclsid);
1167
1168     TRACE("\n\tCLSID:\t%s,\n\tIID:\t%s\n",
1169         debugstr_guid(rclsid),
1170         debugstr_guid(iid)
1171     );
1172
1173     /*
1174      * First, try and see if we can't match the class ID with one of the 
1175      * registered classes.
1176      */
1177     if (S_OK == COM_GetRegisteredClassObject(rclsid, dwClsContext, &regClassObject))
1178     {
1179       /*
1180        * Get the required interface from the retrieved pointer.
1181        */
1182       hres = IUnknown_QueryInterface(regClassObject, iid, ppv);
1183
1184       /*
1185        * Since QI got another reference on the pointer, we want to release the
1186        * one we already have. If QI was unsuccessful, this will release the object. This
1187        * is good since we are not returning it in the "out" parameter.
1188        */
1189       IUnknown_Release(regClassObject);
1190
1191       return hres;
1192     }
1193
1194     /* out of process and remote servers not supported yet */
1195     if (((CLSCTX_LOCAL_SERVER|CLSCTX_REMOTE_SERVER) & dwClsContext)
1196         && !((CLSCTX_INPROC_SERVER|CLSCTX_INPROC_HANDLER) & dwClsContext)){
1197         FIXME("CLSCTX_LOCAL_SERVER and CLSCTX_REMOTE_SERVER not supported!\n");
1198         return E_ACCESSDENIED;
1199     }
1200
1201     if ((CLSCTX_INPROC_SERVER|CLSCTX_INPROC_HANDLER) & dwClsContext) {
1202         HKEY key;
1203         char buf[200];
1204
1205         sprintf(buf,"CLSID\\%s\\InprocServer32",xclsid);
1206         hres = RegOpenKeyExA(HKEY_CLASSES_ROOT, buf, 0, KEY_READ, &key);
1207
1208         if (hres != ERROR_SUCCESS) {
1209             return REGDB_E_CLASSNOTREG;
1210         }
1211
1212         memset(dllName,0,sizeof(dllName));
1213         hres= RegQueryValueExW(key,NULL,NULL,NULL,(LPBYTE)dllName,&dllNameLen);
1214         if (hres)
1215                 return REGDB_E_CLASSNOTREG; /* FIXME: check retval */
1216         RegCloseKey(key);
1217         TRACE("found InprocServer32 dll %s\n", debugstr_w(dllName));
1218
1219         /* open dll, call DllGetClassObject */
1220         hLibrary = CoLoadLibrary(dllName, TRUE);
1221         if (hLibrary == 0) {
1222             FIXME("couldn't load InprocServer32 dll %s\n", debugstr_w(dllName));
1223             return E_ACCESSDENIED; /* or should this be CO_E_DLLNOTFOUND? */
1224         }
1225         DllGetClassObject = (DllGetClassObjectFunc)GetProcAddress(hLibrary, "DllGetClassObject");
1226         if (!DllGetClassObject) {
1227             /* not sure if this should be called here CoFreeLibrary(hLibrary);*/
1228             FIXME("couldn't find function DllGetClassObject in %s\n", debugstr_w(dllName));
1229             return E_ACCESSDENIED;
1230         }
1231
1232         /*
1233          * Ask the DLL for its class object. (there was a note here about class
1234          * factories but this is good.
1235          */
1236         return DllGetClassObject(rclsid, iid, ppv);
1237     }
1238     return hres;
1239 }
1240
1241 /***********************************************************************
1242  *        CoResumeClassObjects
1243  *
1244  * Resumes classobjects registered with REGCLS suspended
1245  */
1246 HRESULT WINAPI CoResumeClassObjects(void)
1247 {
1248         FIXME("\n");
1249         return S_OK;
1250 }
1251
1252 /***********************************************************************
1253  *        GetClassFile
1254  *
1255  * This function supplies the CLSID associated with the given filename.
1256  */
1257 HRESULT WINAPI GetClassFile(LPOLESTR filePathName,CLSID *pclsid)
1258 {
1259     IStorage *pstg=0;
1260     HRESULT res;
1261     int nbElm=0,length=0,i=0;
1262     LONG sizeProgId=20;
1263     LPOLESTR *pathDec=0,absFile=0,progId=0;
1264     WCHAR extention[100]={0};
1265
1266     TRACE("()\n");
1267
1268     /* if the file contain a storage object the return the CLSID writen by IStorage_SetClass method*/
1269     if((StgIsStorageFile(filePathName))==S_OK){
1270
1271         res=StgOpenStorage(filePathName,NULL,STGM_READ | STGM_SHARE_DENY_WRITE,NULL,0,&pstg);
1272
1273         if (SUCCEEDED(res))
1274             res=ReadClassStg(pstg,pclsid);
1275
1276         IStorage_Release(pstg);
1277
1278         return res;
1279     }
1280     /* if the file is not a storage object then attemps to match various bits in the file against a
1281        pattern in the registry. this case is not frequently used ! so I present only the psodocode for
1282        this case
1283        
1284      for(i=0;i<nFileTypes;i++)
1285
1286         for(i=0;j<nPatternsForType;j++){
1287
1288             PATTERN pat;
1289             HANDLE  hFile;
1290
1291             pat=ReadPatternFromRegistry(i,j);
1292             hFile=CreateFileW(filePathName,,,,,,hFile);
1293             SetFilePosition(hFile,pat.offset);
1294             ReadFile(hFile,buf,pat.size,NULL,NULL);
1295             if (memcmp(buf&pat.mask,pat.pattern.pat.size)==0){
1296
1297                 *pclsid=ReadCLSIDFromRegistry(i);
1298                 return S_OK;
1299             }
1300         }
1301      */
1302
1303     /* if the obove strategies fail then search for the extension key in the registry */
1304
1305     /* get the last element (absolute file) in the path name */
1306     nbElm=FileMonikerImpl_DecomposePath(filePathName,&pathDec);
1307     absFile=pathDec[nbElm-1];
1308
1309     /* failed if the path represente a directory and not an absolute file name*/
1310     if (lstrcmpW(absFile,(LPOLESTR)"\\"))
1311         return MK_E_INVALIDEXTENSION;
1312
1313     /* get the extension of the file */
1314     length=lstrlenW(absFile);
1315     for(i=length-1; ( (i>=0) && (extention[i]=absFile[i]) );i--);
1316         
1317     /* get the progId associated to the extension */
1318     progId=CoTaskMemAlloc(sizeProgId);
1319
1320     res=RegQueryValueW(HKEY_CLASSES_ROOT,extention,progId,&sizeProgId);
1321
1322     if (res==ERROR_MORE_DATA){
1323
1324         progId = CoTaskMemRealloc(progId,sizeProgId);
1325         res=RegQueryValueW(HKEY_CLASSES_ROOT,extention,progId,&sizeProgId);
1326     }
1327     if (res==ERROR_SUCCESS)
1328         /* return the clsid associated to the progId */
1329         res= CLSIDFromProgID(progId,pclsid);
1330
1331     for(i=0; pathDec[i]!=NULL;i++)
1332         CoTaskMemFree(pathDec[i]);
1333     CoTaskMemFree(pathDec);
1334
1335     CoTaskMemFree(progId);
1336
1337     if (res==ERROR_SUCCESS)
1338         return res;
1339
1340     return MK_E_INVALIDEXTENSION;
1341 }
1342 /******************************************************************************
1343  *              CoRegisterMessageFilter16       [COMPOBJ.27]
1344  */
1345 HRESULT WINAPI CoRegisterMessageFilter16(
1346         LPMESSAGEFILTER lpMessageFilter,
1347         LPMESSAGEFILTER *lplpMessageFilter
1348 ) {
1349         FIXME("(%p,%p),stub!\n",lpMessageFilter,lplpMessageFilter);
1350         return 0;
1351 }
1352
1353 /***********************************************************************
1354  *           CoCreateInstance [COMPOBJ.13, OLE32.7]
1355  */
1356 HRESULT WINAPI CoCreateInstance(
1357         REFCLSID rclsid,
1358         LPUNKNOWN pUnkOuter,
1359         DWORD dwClsContext,
1360         REFIID iid,
1361         LPVOID *ppv) 
1362 {
1363         HRESULT hres;
1364         LPCLASSFACTORY lpclf = 0;
1365
1366   /*
1367    * Sanity check
1368    */
1369   if (ppv==0)
1370     return E_POINTER;
1371
1372   /*
1373    * Initialize the "out" parameter
1374    */
1375   *ppv = 0;
1376   
1377   /*
1378    * Get a class factory to construct the object we want.
1379    */
1380   hres = CoGetClassObject(rclsid,
1381                           dwClsContext,
1382                           NULL,
1383                           &IID_IClassFactory,
1384                           (LPVOID)&lpclf);
1385
1386   if (FAILED(hres))
1387     return hres;
1388
1389   /*
1390    * Create the object and don't forget to release the factory
1391    */
1392         hres = IClassFactory_CreateInstance(lpclf, pUnkOuter, iid, ppv);
1393         IClassFactory_Release(lpclf);
1394
1395         return hres;
1396 }
1397
1398 /***********************************************************************
1399  *           CoCreateInstanceEx [OLE32.165]
1400  */
1401 HRESULT WINAPI CoCreateInstanceEx(
1402   REFCLSID      rclsid, 
1403   LPUNKNOWN     pUnkOuter,
1404   DWORD         dwClsContext, 
1405   COSERVERINFO* pServerInfo,
1406   ULONG         cmq,
1407   MULTI_QI*     pResults)
1408 {
1409   IUnknown* pUnk = NULL;
1410   HRESULT   hr;
1411   ULONG     index;
1412   int       successCount = 0;
1413
1414   /*
1415    * Sanity check
1416    */
1417   if ( (cmq==0) || (pResults==NULL))
1418     return E_INVALIDARG;
1419
1420   if (pServerInfo!=NULL)
1421     FIXME("() non-NULL pServerInfo not supported!\n");
1422
1423   /*
1424    * Initialize all the "out" parameters.
1425    */
1426   for (index = 0; index < cmq; index++)
1427   {
1428     pResults[index].pItf = NULL;
1429     pResults[index].hr   = E_NOINTERFACE;
1430   }
1431
1432   /*
1433    * Get the object and get its IUnknown pointer.
1434    */
1435   hr = CoCreateInstance(rclsid, 
1436                         pUnkOuter,
1437                         dwClsContext,
1438                         &IID_IUnknown,
1439                         (VOID**)&pUnk);
1440
1441   if (hr)
1442     return hr;
1443
1444   /*
1445    * Then, query for all the interfaces requested.
1446    */
1447   for (index = 0; index < cmq; index++)
1448   {
1449     pResults[index].hr = IUnknown_QueryInterface(pUnk,
1450                                                  pResults[index].pIID,
1451                                                  (VOID**)&(pResults[index].pItf));
1452
1453     if (pResults[index].hr == S_OK)
1454       successCount++;
1455   }
1456
1457   /*
1458    * Release our temporary unknown pointer.
1459    */
1460   IUnknown_Release(pUnk);
1461
1462   if (successCount == 0)
1463     return E_NOINTERFACE;
1464
1465   if (successCount!=cmq)
1466     return CO_S_NOTALLINTERFACES;
1467
1468   return S_OK;
1469 }
1470
1471 /***********************************************************************
1472  *           CoFreeLibrary [COMPOBJ.13]
1473  */
1474 void WINAPI CoFreeLibrary(HINSTANCE hLibrary)
1475 {
1476     OpenDll *ptr, *prev;
1477     OpenDll *tmp;
1478
1479     /* lookup library in linked list */
1480     prev = NULL;
1481     for (ptr = openDllList; ptr != NULL; ptr=ptr->next) {
1482         if (ptr->hLibrary == hLibrary) {
1483             break;
1484         }
1485         prev = ptr;
1486     }
1487
1488     if (ptr == NULL) {
1489         /* shouldn't happen if user passed in a valid hLibrary */
1490         return;
1491     }
1492     /* assert: ptr points to the library entry to free */
1493
1494     /* free library and remove node from list */
1495     FreeLibrary(hLibrary);
1496     if (ptr == openDllList) {
1497         tmp = openDllList->next;
1498         HeapFree(GetProcessHeap(), 0, openDllList);
1499         openDllList = tmp;
1500     } else {
1501         tmp = ptr->next;
1502         HeapFree(GetProcessHeap(), 0, ptr);
1503         prev->next = tmp;
1504     }
1505
1506 }
1507
1508
1509 /***********************************************************************
1510  *           CoFreeAllLibraries [COMPOBJ.12]
1511  */
1512 void WINAPI CoFreeAllLibraries(void)
1513 {
1514     OpenDll *ptr, *tmp;
1515
1516     for (ptr = openDllList; ptr != NULL; ) {
1517         tmp=ptr->next;
1518         CoFreeLibrary(ptr->hLibrary);
1519         ptr = tmp;
1520     }
1521 }
1522
1523
1524
1525 /***********************************************************************
1526  *           CoFreeUnusedLibraries [COMPOBJ.17]
1527  */
1528 void WINAPI CoFreeUnusedLibraries(void)
1529 {
1530     OpenDll *ptr, *tmp;
1531     typedef HRESULT(*DllCanUnloadNowFunc)(void);
1532     DllCanUnloadNowFunc DllCanUnloadNow;
1533
1534     for (ptr = openDllList; ptr != NULL; ) {
1535         DllCanUnloadNow = (DllCanUnloadNowFunc)
1536             GetProcAddress(ptr->hLibrary, "DllCanUnloadNow");
1537         
1538         if ( (DllCanUnloadNow != NULL) &&
1539              (DllCanUnloadNow() == S_OK) ) {
1540             tmp=ptr->next;
1541             CoFreeLibrary(ptr->hLibrary);
1542             ptr = tmp;
1543         } else {
1544             ptr=ptr->next;
1545         }
1546     }
1547 }
1548
1549 /***********************************************************************
1550  *           CoFileTimeNow [COMPOBJ.82, OLE32.10]
1551  * RETURNS
1552  *      the current system time in lpFileTime
1553  */
1554 HRESULT WINAPI CoFileTimeNow( FILETIME *lpFileTime ) /* [out] the current time */
1555 {
1556     GetSystemTimeAsFileTime( lpFileTime );
1557     return S_OK;
1558 }
1559
1560 /***********************************************************************
1561  *           CoTaskMemAlloc (OLE32.43)
1562  * RETURNS
1563  *      pointer to newly allocated block
1564  */
1565 LPVOID WINAPI CoTaskMemAlloc(
1566         ULONG size      /* [in] size of memoryblock to be allocated */
1567 ) {
1568     LPMALLOC    lpmalloc;
1569     HRESULT     ret = CoGetMalloc(0,&lpmalloc);
1570
1571     if (FAILED(ret)) 
1572         return NULL;
1573
1574     return IMalloc_Alloc(lpmalloc,size);
1575 }
1576 /***********************************************************************
1577  *           CoTaskMemFree (OLE32.44)
1578  */
1579 VOID WINAPI CoTaskMemFree(
1580         LPVOID ptr      /* [in] pointer to be freed */
1581 ) {
1582     LPMALLOC    lpmalloc;
1583     HRESULT     ret = CoGetMalloc(0,&lpmalloc);
1584
1585     if (FAILED(ret)) 
1586       return;
1587
1588     IMalloc_Free(lpmalloc, ptr);
1589 }
1590
1591 /***********************************************************************
1592  *           CoTaskMemRealloc (OLE32.45)
1593  * RETURNS
1594  *      pointer to newly allocated block
1595  */
1596 LPVOID WINAPI CoTaskMemRealloc(
1597   LPVOID pvOld,
1598   ULONG  size)  /* [in] size of memoryblock to be allocated */
1599 {
1600   LPMALLOC lpmalloc;
1601   HRESULT  ret = CoGetMalloc(0,&lpmalloc);
1602   
1603   if (FAILED(ret)) 
1604     return NULL;
1605
1606   return IMalloc_Realloc(lpmalloc, pvOld, size);
1607 }
1608
1609 /***********************************************************************
1610  *           CoLoadLibrary (OLE32.30)
1611  */
1612 HINSTANCE WINAPI CoLoadLibrary(LPOLESTR lpszLibName, BOOL bAutoFree)
1613 {
1614     HINSTANCE hLibrary;
1615     OpenDll *ptr;
1616     OpenDll *tmp;
1617   
1618     TRACE("(%s, %d)\n", debugstr_w(lpszLibName), bAutoFree);
1619
1620     hLibrary = LoadLibraryExW(lpszLibName, 0, LOAD_WITH_ALTERED_SEARCH_PATH);
1621
1622     if (!bAutoFree)
1623         return hLibrary;
1624
1625     if (openDllList == NULL) {
1626         /* empty list -- add first node */
1627         openDllList = (OpenDll*)HeapAlloc(GetProcessHeap(),0, sizeof(OpenDll));
1628         openDllList->hLibrary=hLibrary;
1629         openDllList->next = NULL;
1630     } else {
1631         /* search for this dll */
1632         int found = FALSE;
1633         for (ptr = openDllList; ptr->next != NULL; ptr=ptr->next) {
1634             if (ptr->hLibrary == hLibrary) {
1635                 found = TRUE;
1636                 break;
1637             }
1638         }
1639         if (!found) {
1640             /* dll not found, add it */
1641             tmp = openDllList;
1642             openDllList = (OpenDll*)HeapAlloc(GetProcessHeap(),0, sizeof(OpenDll));
1643             openDllList->hLibrary = hLibrary;
1644             openDllList->next = tmp;
1645         }
1646     }
1647      
1648     return hLibrary;
1649 }
1650
1651 /***********************************************************************
1652  *           CoInitializeWOW (OLE32.27)
1653  */
1654 HRESULT WINAPI CoInitializeWOW(DWORD x,DWORD y) {
1655     FIXME("(0x%08lx,0x%08lx),stub!\n",x,y);
1656     return 0;
1657 }
1658
1659 /******************************************************************************
1660  *              CoLockObjectExternal16  [COMPOBJ.63]
1661  */
1662 HRESULT WINAPI CoLockObjectExternal16(
1663     LPUNKNOWN pUnk,             /* [in] object to be locked */
1664     BOOL16 fLock,               /* [in] do lock */
1665     BOOL16 fLastUnlockReleases  /* [in] ? */
1666 ) {
1667     FIXME("(%p,%d,%d),stub!\n",pUnk,fLock,fLastUnlockReleases);
1668     return S_OK;
1669 }
1670
1671 /******************************************************************************
1672  *              CoLockObjectExternal    [OLE32.31]
1673  */
1674 HRESULT WINAPI CoLockObjectExternal(
1675     LPUNKNOWN pUnk,             /* [in] object to be locked */
1676     BOOL fLock,         /* [in] do lock */
1677     BOOL fLastUnlockReleases) /* [in] unlock all */
1678 {
1679
1680   if (fLock) 
1681   {
1682     /* 
1683      * Increment the external lock coutner, COM_ExternalLockAddRef also
1684      * increment the object's internal lock counter.
1685      */
1686     COM_ExternalLockAddRef( pUnk); 
1687   }
1688   else
1689   {
1690     /* 
1691      * Decrement the external lock coutner, COM_ExternalLockRelease also
1692      * decrement the object's internal lock counter.
1693      */
1694     COM_ExternalLockRelease( pUnk, fLastUnlockReleases);
1695   }
1696
1697     return S_OK;
1698 }
1699
1700 /***********************************************************************
1701  *           CoGetState16 [COMPOBJ.115]
1702  */
1703 HRESULT WINAPI CoGetState16(LPDWORD state)
1704 {
1705     FIXME("(%p),stub!\n", state);
1706     *state = 0;
1707     return S_OK;
1708 }
1709 /***********************************************************************
1710  *           CoSetState [COM32.42]
1711  */
1712 HRESULT WINAPI CoSetState(LPDWORD state)
1713 {
1714     FIXME("(%p),stub!\n", state);
1715     if (state) *state = 0;
1716     return S_OK;
1717 }
1718 /***********************************************************************
1719  *          CoCreateFreeThreadedMarshaler [OLE32.5]
1720  */
1721 HRESULT WINAPI CoCreateFreeThreadedMarshaler (LPUNKNOWN punkOuter, LPUNKNOWN* ppunkMarshal)
1722 {
1723    FIXME ("(%p %p): stub\n", punkOuter, ppunkMarshal);
1724     
1725    return S_OK;
1726 }
1727
1728
1729 /***********************************************************************
1730  *           DllGetClassObject [OLE32.63]
1731  */
1732 HRESULT WINAPI OLE32_DllGetClassObject(REFCLSID rclsid, REFIID iid,LPVOID *ppv)
1733 {       
1734         FIXME("\n\tCLSID:\t%s,\n\tIID:\t%s\n",debugstr_guid(rclsid),debugstr_guid(iid));
1735         *ppv = NULL;
1736         return CLASS_E_CLASSNOTAVAILABLE;
1737 }
1738
1739
1740 /***
1741  * COM_RevokeAllClasses
1742  *
1743  * This method is called when the COM libraries are uninitialized to 
1744  * release all the references to the class objects registered with
1745  * the library
1746  */
1747 static void COM_RevokeAllClasses()
1748 {
1749   while (firstRegisteredClass!=0)
1750   {
1751     CoRevokeClassObject(firstRegisteredClass->dwCookie);
1752   }
1753 }
1754
1755 /****************************************************************************
1756  *  COM External Lock methods implementation
1757  */
1758
1759 /****************************************************************************
1760  * Public - Method that increments the count for a IUnknown* in the linked 
1761  * list.  The item is inserted if not already in the list.
1762  */
1763 static void COM_ExternalLockAddRef(
1764   IUnknown *pUnk)
1765 {
1766   COM_ExternalLock *externalLock = COM_ExternalLockFind(pUnk);
1767
1768   /*
1769    * Add an external lock to the object. If it was already externally
1770    * locked, just increase the reference count. If it was not.
1771    * add the item to the list.
1772    */
1773   if ( externalLock == EL_NOT_FOUND )
1774     COM_ExternalLockInsert(pUnk);
1775   else
1776     externalLock->uRefCount++;
1777
1778   /*
1779    * Add an internal lock to the object
1780    */
1781   IUnknown_AddRef(pUnk); 
1782 }
1783
1784 /****************************************************************************
1785  * Public - Method that decrements the count for a IUnknown* in the linked 
1786  * list.  The item is removed from the list if its count end up at zero or if
1787  * bRelAll is TRUE.
1788  */
1789 static void COM_ExternalLockRelease(
1790   IUnknown *pUnk,
1791   BOOL   bRelAll)
1792 {
1793   COM_ExternalLock *externalLock = COM_ExternalLockFind(pUnk);
1794
1795   if ( externalLock != EL_NOT_FOUND )
1796   {
1797     do
1798     {
1799       externalLock->uRefCount--;  /* release external locks      */
1800       IUnknown_Release(pUnk);     /* release local locks as well */
1801
1802       if ( bRelAll == FALSE ) 
1803         break;  /* perform single release */
1804
1805     } while ( externalLock->uRefCount > 0 );  
1806
1807     if ( externalLock->uRefCount == 0 )  /* get rid of the list entry */
1808       COM_ExternalLockDelete(externalLock);
1809   }
1810 }
1811 /****************************************************************************
1812  * Public - Method that frees the content of the list.
1813  */
1814 static void COM_ExternalLockFreeList()
1815 {
1816   COM_ExternalLock *head;
1817
1818   head = elList.head;                 /* grab it by the head             */
1819   while ( head != EL_END_OF_LIST )
1820   {
1821     COM_ExternalLockDelete(head);     /* get rid of the head stuff       */
1822
1823     head = elList.head;               /* get the new head...             */ 
1824   }
1825 }
1826
1827 /****************************************************************************
1828  * Public - Method that dump the content of the list.
1829  */
1830 void COM_ExternalLockDump()
1831 {
1832   COM_ExternalLock *current = elList.head;
1833
1834   DPRINTF("\nExternal lock list contains:\n");
1835
1836   while ( current != EL_END_OF_LIST )
1837   {
1838       DPRINTF( "\t%p with %lu references count.\n", current->pUnk, current->uRefCount);
1839  
1840     /* Skip to the next item */ 
1841     current = current->next;
1842   } 
1843
1844 }
1845
1846 /****************************************************************************
1847  * Internal - Find a IUnknown* in the linked list
1848  */
1849 static COM_ExternalLock* COM_ExternalLockFind(
1850   IUnknown *pUnk)
1851 {
1852   return COM_ExternalLockLocate(elList.head, pUnk);
1853 }
1854
1855 /****************************************************************************
1856  * Internal - Recursivity agent for IUnknownExternalLockList_Find
1857  */
1858 static COM_ExternalLock* COM_ExternalLockLocate(
1859   COM_ExternalLock *element,
1860   IUnknown         *pUnk)
1861 {
1862   if ( element == EL_END_OF_LIST )  
1863     return EL_NOT_FOUND;
1864
1865   else if ( element->pUnk == pUnk )    /* We found it */
1866     return element;
1867
1868   else                                 /* Not the right guy, keep on looking */ 
1869     return COM_ExternalLockLocate( element->next, pUnk);
1870 }
1871
1872 /****************************************************************************
1873  * Internal - Insert a new IUnknown* to the linked list
1874  */
1875 static BOOL COM_ExternalLockInsert(
1876   IUnknown *pUnk)
1877 {
1878   COM_ExternalLock *newLock      = NULL;
1879   COM_ExternalLock *previousHead = NULL;
1880
1881   /*
1882    * Allocate space for the new storage object
1883    */
1884   newLock = HeapAlloc(GetProcessHeap(), 0, sizeof(COM_ExternalLock));
1885
1886   if (newLock!=NULL)
1887   {
1888     if ( elList.head == EL_END_OF_LIST ) 
1889     {
1890       elList.head = newLock;    /* The list is empty */
1891     }
1892     else 
1893     {
1894       /* 
1895        * insert does it at the head
1896        */
1897       previousHead  = elList.head;
1898       elList.head = newLock;
1899     }
1900
1901     /*
1902      * Set new list item data member 
1903      */
1904     newLock->pUnk      = pUnk;
1905     newLock->uRefCount = 1;
1906     newLock->next      = previousHead;
1907     
1908     return TRUE;
1909   }
1910   else
1911     return FALSE;
1912 }
1913
1914 /****************************************************************************
1915  * Internal - Method that removes an item from the linked list.
1916  */
1917 static void COM_ExternalLockDelete(
1918   COM_ExternalLock *itemList)
1919 {
1920   COM_ExternalLock *current = elList.head;
1921
1922   if ( current == itemList )
1923   {
1924     /* 
1925      * this section handles the deletion of the first node 
1926      */
1927     elList.head = itemList->next;
1928     HeapFree( GetProcessHeap(), 0, itemList);  
1929   }
1930   else
1931   {
1932     do 
1933     {
1934       if ( current->next == itemList )   /* We found the item to free  */
1935       {
1936         current->next = itemList->next;  /* readjust the list pointers */
1937   
1938         HeapFree( GetProcessHeap(), 0, itemList);  
1939         break; 
1940       }
1941  
1942       /* Skip to the next item */ 
1943       current = current->next;
1944   
1945     } while ( current != EL_END_OF_LIST );
1946   }
1947 }
1948
1949 /***********************************************************************
1950  *      COMPOBJ_DllEntryPoint                   [COMPOBJ.entry]
1951  *
1952  *    Initialization code for the COMPOBJ DLL
1953  *
1954  * RETURNS:
1955  */
1956 BOOL WINAPI COMPOBJ_DllEntryPoint(DWORD Reason, HINSTANCE16 hInst, WORD ds, WORD HeapSize, DWORD res1, WORD res2)
1957 {
1958         TRACE("(%08lx, %04x, %04x, %04x, %08lx, %04x)\n", Reason, hInst, ds, HeapSize,
1959  res1, res2);
1960         switch(Reason)
1961         {
1962         case DLL_PROCESS_ATTACH:
1963                 if (!COMPOBJ_Attach++) COMPOBJ_hInstance = hInst;
1964                 break;
1965
1966         case DLL_PROCESS_DETACH:
1967                 if(!--COMPOBJ_Attach)
1968                         COMPOBJ_hInstance = 0;
1969                 break;
1970         }
1971         return TRUE;
1972 }
1973
1974 /******************************************************************************
1975  *              OleGetAutoConvert        [OLE32.104]
1976  */
1977 HRESULT WINAPI OleGetAutoConvert(REFCLSID clsidOld, LPCLSID pClsidNew)
1978 {
1979     HKEY hkey = 0;
1980     char buf[200];
1981     WCHAR wbuf[200];
1982     DWORD len;
1983     HRESULT res = S_OK;
1984
1985     sprintf(buf,"CLSID\\");WINE_StringFromCLSID(clsidOld,&buf[6]);
1986     if (RegOpenKeyA(HKEY_CLASSES_ROOT,buf,&hkey))
1987     {
1988         res = REGDB_E_CLASSNOTREG;
1989         goto done;
1990     }
1991     len = 200;
1992     /* we can just query for the default value of AutoConvertTo key like that,
1993        without opening the AutoConvertTo key and querying for NULL (default) */
1994     if (RegQueryValueA(hkey,"AutoConvertTo",buf,&len))
1995     {
1996         res = REGDB_E_KEYMISSING;
1997         goto done;
1998     }
1999     MultiByteToWideChar( CP_ACP, 0, buf, -1, wbuf, sizeof(wbuf)/sizeof(WCHAR) );
2000     CLSIDFromString(wbuf,pClsidNew);
2001 done:
2002   if (hkey) RegCloseKey(hkey);
2003
2004   return res;
2005 }
2006
2007 /******************************************************************************
2008  *              OleSetAutoConvert        [OLE32.126]
2009  */
2010 HRESULT WINAPI OleSetAutoConvert(REFCLSID clsidOld, REFCLSID clsidNew)
2011 {
2012     HKEY hkey = 0, hkeyConvert = 0;
2013     char buf[200], szClsidNew[200];
2014     HRESULT res = S_OK;
2015
2016     TRACE("(%p,%p);\n", clsidOld, clsidNew);
2017     sprintf(buf,"CLSID\\");WINE_StringFromCLSID(clsidOld,&buf[6]);
2018     WINE_StringFromCLSID(clsidNew, szClsidNew);
2019     if (RegOpenKeyA(HKEY_CLASSES_ROOT,buf,&hkey))
2020     {
2021         res = REGDB_E_CLASSNOTREG;
2022         goto done;
2023     }
2024     if (RegCreateKeyA(hkey, "AutoConvertTo", &hkeyConvert))
2025     {
2026         res = REGDB_E_WRITEREGDB;
2027         goto done;
2028     }
2029     if (RegSetValueExA(hkeyConvert, NULL, 0,
2030                             REG_SZ, (LPBYTE)szClsidNew, strlen(szClsidNew)+1))
2031     {
2032         res = REGDB_E_WRITEREGDB;
2033         goto done;
2034     }
2035
2036 done:
2037     if (hkeyConvert) RegCloseKey(hkeyConvert);
2038     if (hkey) RegCloseKey(hkey);
2039
2040     return res;
2041 }
2042
2043 /***********************************************************************
2044  *           IsEqualGUID [OLE32.76]
2045  *
2046  * Compares two Unique Identifiers.
2047  *
2048  * RETURNS
2049  *      TRUE if equal
2050  */
2051 #undef IsEqualGUID
2052 BOOL WINAPI IsEqualGUID(
2053      REFGUID rguid1, /* [in] unique id 1 */
2054      REFGUID rguid2  /* [in] unique id 2 */
2055      )
2056 {
2057     return !memcmp(rguid1,rguid2,sizeof(GUID));
2058 }