Added support for DirectDraw overlays using the XVideo extension.
[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 "wine/winestring.h"
22 #include "wownt32.h"
23 #include "ole2ver.h"
24 #include "debugtools.h"
25 #include "heap.h"
26 #include "ldt.h"
27 #include "winreg.h"
28 #include "rpc.h"
29
30 #include "wine/obj_base.h"
31 #include "wine/obj_misc.h"
32 #include "wine/obj_storage.h"
33 #include "wine/obj_clientserver.h"
34
35 #include "ifs.h"
36 #include "compobj.h"
37
38 DEFAULT_DEBUG_CHANNEL(ole);
39
40 /****************************************************************************
41  *  COM External Lock structures and methods declaration
42  *
43  *  This api provides a linked list to managed external references to 
44  *  COM objects.  
45  *
46  *  The public interface consists of three calls: 
47  *      COM_ExternalLockAddRef
48  *      COM_ExternalLockRelease
49  *      COM_ExternalLockFreeList
50  */
51
52 #define EL_END_OF_LIST 0
53 #define EL_NOT_FOUND   0
54
55 /*
56  * Declaration of the static structure that manage the 
57  * external lock to COM  objects.
58  */
59 typedef struct COM_ExternalLock     COM_ExternalLock;
60 typedef struct COM_ExternalLockList COM_ExternalLockList;
61
62 struct COM_ExternalLock
63 {
64   IUnknown         *pUnk;     /* IUnknown referenced */
65   ULONG            uRefCount; /* external lock counter to IUnknown object*/
66   COM_ExternalLock *next;     /* Pointer to next element in list */
67 };
68
69 struct COM_ExternalLockList
70 {
71   COM_ExternalLock *head;     /* head of list */
72 };
73
74 /*
75  * Declaration and initialization of the static structure that manages
76  * the external lock to COM objects.
77  */
78 static COM_ExternalLockList elList = { EL_END_OF_LIST };
79
80 /*
81  * Public Interface to the external lock list   
82  */
83 static void COM_ExternalLockFreeList();
84 static void COM_ExternalLockAddRef(IUnknown *pUnk);
85 static void COM_ExternalLockRelease(IUnknown *pUnk, BOOL bRelAll);
86 void COM_ExternalLockDump(); /* testing purposes, not static to avoid warning */
87
88 /*
89  * Private methods used to managed the linked list   
90  */
91 static BOOL COM_ExternalLockInsert(
92   IUnknown *pUnk);
93
94 static void COM_ExternalLockDelete(
95   COM_ExternalLock *element);
96
97 static COM_ExternalLock* COM_ExternalLockFind(
98   IUnknown *pUnk);
99
100 static COM_ExternalLock* COM_ExternalLockLocate(
101   COM_ExternalLock *element,
102   IUnknown         *pUnk);
103
104 /****************************************************************************
105  * This section defines variables internal to the COM module.
106  *
107  * TODO: Most of these things will have to be made thread-safe.
108  */
109 HINSTANCE16     COMPOBJ_hInstance = 0;
110 HINSTANCE       COMPOBJ_hInstance32 = 0;
111 static int      COMPOBJ_Attach = 0;
112
113 LPMALLOC16 currentMalloc16=NULL;
114 LPMALLOC currentMalloc32=NULL;
115
116 HTASK16 hETask = 0;
117 WORD Table_ETask[62];
118
119 /*
120  * This lock count counts the number of times CoInitialize is called. It is
121  * decreased every time CoUninitialize is called. When it hits 0, the COM
122  * libraries are freed
123  */
124 static ULONG s_COMLockCount = 0;
125
126 /*
127  * This linked list contains the list of registered class objects. These
128  * are mostly used to register the factories for out-of-proc servers of OLE
129  * objects.
130  *
131  * TODO: Make this data structure aware of inter-process communication. This
132  *       means that parts of this will be exported to the Wine Server.
133  */
134 typedef struct tagRegisteredClass
135 {
136   CLSID     classIdentifier;
137   LPUNKNOWN classObject;
138   DWORD     runContext;
139   DWORD     connectFlags;
140   DWORD     dwCookie;
141   struct tagRegisteredClass* nextClass;
142 } RegisteredClass;
143
144 static RegisteredClass* firstRegisteredClass = NULL;
145
146 /* this open DLL table belongs in a per process table, but my guess is that
147  * it shouldn't live in the kernel, so I'll put them out here in DLL
148  * space assuming that there is one OLE32 per process.
149  */
150 typedef struct tagOpenDll {
151   HINSTANCE hLibrary;       
152   struct tagOpenDll *next;
153 } OpenDll;
154
155 static OpenDll *openDllList = NULL; /* linked list of open dlls */
156
157 /*****************************************************************************
158  * This section contains prototypes to internal methods for this
159  * module
160  */
161 static HRESULT COM_GetRegisteredClassObject(REFCLSID    rclsid,
162                                             DWORD       dwClsContext,
163                                             LPUNKNOWN*  ppUnk);
164
165 static void COM_RevokeAllClasses();
166
167
168 /******************************************************************************
169  *           CoBuildVersion [COMPOBJ.1]
170  *
171  * RETURNS
172  *      Current build version, hiword is majornumber, loword is minornumber
173  */
174 DWORD WINAPI CoBuildVersion(void)
175 {
176     TRACE("Returning version %d, build %d.\n", rmm, rup);
177     return (rmm<<16)+rup;
178 }
179
180 /******************************************************************************
181  *              CoInitialize16  [COMPOBJ.2]
182  * Set the win16 IMalloc used for memory management
183  */
184 HRESULT WINAPI CoInitialize16(
185         LPVOID lpReserved       /* [in] pointer to win16 malloc interface */
186 ) {
187     currentMalloc16 = (LPMALLOC16)lpReserved;
188     return S_OK;
189 }
190
191 /******************************************************************************
192  *              CoInitialize    [OLE32.26]
193  *
194  * Initializes the COM libraries.
195  *
196  * See CoInitializeEx
197  */
198 HRESULT WINAPI CoInitialize(
199         LPVOID lpReserved       /* [in] pointer to win32 malloc interface
200                                    (obsolete, should be NULL) */
201
202 {
203   /*
204    * Just delegate to the newer method.
205    */
206   return CoInitializeEx(lpReserved, COINIT_APARTMENTTHREADED);
207 }
208
209 /******************************************************************************
210  *              CoInitializeEx  [OLE32.163]
211  *
212  * Initializes the COM libraries. The behavior used to set the win32 IMalloc
213  * used for memory management is obsolete.
214  *
215  * RETURNS
216  *  S_OK               if successful,
217  *  S_FALSE            if this function was called already.
218  *  RPC_E_CHANGED_MODE if a previous call to CoInitialize specified another
219  *                      threading model.
220  *
221  * BUGS
222  * Only the single threaded model is supported. As a result RPC_E_CHANGED_MODE 
223  * is never returned.
224  *
225  * See the windows documentation for more details.
226  */
227 HRESULT WINAPI CoInitializeEx(
228         LPVOID lpReserved,      /* [in] pointer to win32 malloc interface
229                                    (obsolete, should be NULL) */
230         DWORD dwCoInit          /* [in] A value from COINIT specifies the threading model */
231
232 {
233   HRESULT hr;
234
235   TRACE("(%p, %x)\n", lpReserved, (int)dwCoInit);
236
237   if (lpReserved!=NULL)
238   {
239     ERR("(%p, %x) - Bad parameter passed-in %p, must be an old Windows Application\n", lpReserved, (int)dwCoInit, lpReserved);
240   }
241
242   /*
243    * Check for unsupported features.
244    */
245   if (dwCoInit!=COINIT_APARTMENTTHREADED) 
246   {
247     FIXME(":(%p,%x): unsupported flag %x\n", lpReserved, (int)dwCoInit, (int)dwCoInit);
248     /* Hope for the best and continue anyway */
249   }
250
251   /*
252    * Check the lock count. If this is the first time going through the initialize
253    * process, we have to initialize the libraries.
254    */
255   if (s_COMLockCount==0)
256   {
257     /*
258      * Initialize the various COM libraries and data structures.
259      */
260     TRACE("() - Initializing the COM libraries\n");
261
262     RunningObjectTableImpl_Initialize();
263
264     hr = S_OK;
265   }
266   else
267     hr = S_FALSE;
268
269   /*
270    * Crank-up that lock count.
271    */
272   s_COMLockCount++;
273
274   return hr;
275 }
276
277 /***********************************************************************
278  *           CoUninitialize16   [COMPOBJ.3]
279  * Don't know what it does. 
280  * 3-Nov-98 -- this was originally misspelled, I changed it to what I
281  *   believe is the correct spelling
282  */
283 void WINAPI CoUninitialize16(void)
284 {
285   TRACE("()\n");
286   CoFreeAllLibraries();
287 }
288
289 /***********************************************************************
290  *           CoUninitialize   [OLE32.47]
291  *
292  * This method will release the COM libraries.
293  *
294  * See the windows documentation for more details.
295  */
296 void WINAPI CoUninitialize(void)
297 {
298   TRACE("()\n");
299   
300   /*
301    * Decrease the reference count.
302    */
303   s_COMLockCount--;
304   
305   /*
306    * If we are back to 0 locks on the COM library, make sure we free
307    * all the associated data structures.
308    */
309   if (s_COMLockCount==0)
310   {
311     /*
312      * Release the various COM libraries and data structures.
313      */
314     TRACE("() - Releasing the COM libraries\n");
315
316     RunningObjectTableImpl_UnInitialize();
317     /*
318      * Release the references to the registered class objects.
319      */
320     COM_RevokeAllClasses();
321
322     /*
323      * This will free the loaded COM Dlls.
324      */
325     CoFreeAllLibraries();
326
327     /*
328      * This will free list of external references to COM objects.
329      */
330     COM_ExternalLockFreeList();
331 }
332 }
333
334 /***********************************************************************
335  *           CoGetMalloc16    [COMPOBJ.4]
336  * RETURNS
337  *      The current win16 IMalloc
338  */
339 HRESULT WINAPI CoGetMalloc16(
340         DWORD dwMemContext,     /* [in] unknown */
341         LPMALLOC16 * lpMalloc   /* [out] current win16 malloc interface */
342 ) {
343     if(!currentMalloc16)
344         currentMalloc16 = IMalloc16_Constructor();
345     *lpMalloc = currentMalloc16;
346     return S_OK;
347 }
348
349 /******************************************************************************
350  *              CoGetMalloc     [OLE32.20]
351  *
352  * RETURNS
353  *      The current win32 IMalloc
354  */
355 HRESULT WINAPI CoGetMalloc(
356         DWORD dwMemContext,     /* [in] unknown */
357         LPMALLOC *lpMalloc      /* [out] current win32 malloc interface */
358 ) {
359     if(!currentMalloc32)
360         currentMalloc32 = IMalloc_Constructor();
361     *lpMalloc = currentMalloc32;
362     return S_OK;
363 }
364
365 /***********************************************************************
366  *           CoCreateStandardMalloc16 [COMPOBJ.71]
367  */
368 HRESULT WINAPI CoCreateStandardMalloc16(DWORD dwMemContext,
369                                           LPMALLOC16 *lpMalloc)
370 {
371     /* FIXME: docu says we shouldn't return the same allocator as in
372      * CoGetMalloc16 */
373     *lpMalloc = IMalloc16_Constructor();
374     return S_OK;
375 }
376
377 /******************************************************************************
378  *              CoDisconnectObject      [COMPOBJ.15]
379  */
380 HRESULT WINAPI CoDisconnectObject( LPUNKNOWN lpUnk, DWORD reserved )
381 {
382     TRACE("%p %lx\n",lpUnk,reserved);
383     return S_OK;
384 }
385
386 /***********************************************************************
387  *           IsEqualGUID16 [COMPOBJ.18]
388  *
389  * Compares two Unique Identifiers.
390  *
391  * RETURNS
392  *      TRUE if equal
393  */
394 BOOL16 WINAPI IsEqualGUID16(
395         GUID* g1,       /* [in] unique id 1 */
396         GUID* g2        /* [in] unique id 2 */
397 ) {
398     return !memcmp( g1, g2, sizeof(GUID) );
399 }
400
401 /******************************************************************************
402  *              CLSIDFromString16       [COMPOBJ.20]
403  * Converts a unique identifier from its string representation into 
404  * the GUID struct.
405  *
406  * Class id: DWORD-WORD-WORD-BYTES[2]-BYTES[6] 
407  *
408  * RETURNS
409  *      the converted GUID
410  */
411 HRESULT WINAPI CLSIDFromString16(
412         LPCOLESTR16 idstr,      /* [in] string representation of guid */
413         CLSID *id               /* [out] GUID converted from string */
414 ) {
415   BYTE *s = (BYTE *) idstr;
416   BYTE *p;
417   int   i;
418   BYTE table[256];
419
420   if (!s)
421           s = "{00000000-0000-0000-0000-000000000000}";
422   else {  /* validate the CLSID string */
423
424       if (strlen(s) != 38)
425           return CO_E_CLASSSTRING;
426
427       if ((s[0]!='{') || (s[9]!='-') || (s[14]!='-') || (s[19]!='-') || (s[24]!='-') || (s[37]!='}'))
428           return CO_E_CLASSSTRING;
429
430       for (i=1; i<37; i++)
431       {
432           if ((i == 9)||(i == 14)||(i == 19)||(i == 24)) continue;
433           if (!(((s[i] >= '0') && (s[i] <= '9'))  ||
434                 ((s[i] >= 'a') && (s[i] <= 'f'))  ||
435                 ((s[i] >= 'A') && (s[i] <= 'F')))
436              )
437               return CO_E_CLASSSTRING;
438       }
439   }
440
441   TRACE("%s -> %p\n", s, id);
442
443   /* quick lookup table */
444   memset(table, 0, 256);
445
446   for (i = 0; i < 10; i++) {
447     table['0' + i] = i;
448   }
449   for (i = 0; i < 6; i++) {
450     table['A' + i] = i+10;
451     table['a' + i] = i+10;
452   }
453
454   /* in form {XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX} */
455
456   p = (BYTE *) id;
457
458   s++;  /* skip leading brace  */
459   for (i = 0; i < 4; i++) {
460     p[3 - i] = table[*s]<<4 | table[*(s+1)];
461     s += 2;
462   }
463   p += 4;
464   s++;  /* skip - */
465
466   for (i = 0; i < 2; i++) {
467     p[1-i] = table[*s]<<4 | table[*(s+1)];
468     s += 2;
469   }
470   p += 2;
471   s++;  /* skip - */
472
473   for (i = 0; i < 2; i++) {
474     p[1-i] = table[*s]<<4 | table[*(s+1)];
475     s += 2;
476   }
477   p += 2;
478   s++;  /* skip - */
479
480   /* these are just sequential bytes */
481   for (i = 0; i < 2; i++) {
482     *p++ = table[*s]<<4 | table[*(s+1)];
483     s += 2;
484   }
485   s++;  /* skip - */
486
487   for (i = 0; i < 6; i++) {
488     *p++ = table[*s]<<4 | table[*(s+1)];
489     s += 2;
490   }
491
492   return S_OK;
493 }
494
495 /******************************************************************************
496  *              CoCreateGuid[OLE32.6]
497  *
498  */
499 HRESULT WINAPI CoCreateGuid(
500         GUID *pguid /* [out] points to the GUID to initialize */
501 ) {
502     return UuidCreate(pguid);
503 }
504
505 /******************************************************************************
506  *              CLSIDFromString [OLE32.3]
507  * Converts a unique identifier from its string representation into 
508  * the GUID struct.
509  *
510  * UNDOCUMENTED
511  *      If idstr is not a valid CLSID string then it gets treated as a ProgID
512  *
513  * RETURNS
514  *      the converted GUID
515  */
516 HRESULT WINAPI CLSIDFromString(
517         LPCOLESTR idstr,        /* [in] string representation of GUID */
518         CLSID *id               /* [out] GUID represented by above string */
519 ) {
520     LPOLESTR16      xid = HEAP_strdupWtoA(GetProcessHeap(),0,idstr);
521     HRESULT       ret = CLSIDFromString16(xid,id);
522
523     HeapFree(GetProcessHeap(),0,xid);
524     if(ret != S_OK) { /* It appears a ProgID is also valid */
525         ret = CLSIDFromProgID(idstr, id);
526     }
527     return ret;
528 }
529
530 /******************************************************************************
531  *              WINE_StringFromCLSID    [Internal]
532  * Converts a GUID into the respective string representation.
533  *
534  * NOTES
535  *
536  * RETURNS
537  *      the string representation and HRESULT
538  */
539 static HRESULT WINE_StringFromCLSID(
540         const CLSID *id,        /* [in] GUID to be converted */
541         LPSTR idstr             /* [out] pointer to buffer to contain converted guid */
542 ) {
543   static const char *hex = "0123456789ABCDEF";
544   char *s;
545   int   i;
546
547   if (!id)
548         { ERR("called with id=Null\n");
549           *idstr = 0x00;
550           return E_FAIL;
551         }
552         
553   sprintf(idstr, "{%08lX-%04X-%04X-%02X%02X-",
554           id->Data1, id->Data2, id->Data3,
555           id->Data4[0], id->Data4[1]);
556   s = &idstr[25];
557
558   /* 6 hex bytes */
559   for (i = 2; i < 8; i++) {
560     *s++ = hex[id->Data4[i]>>4];
561     *s++ = hex[id->Data4[i] & 0xf];
562   }
563
564   *s++ = '}';
565   *s++ = '\0';
566
567   TRACE("%p->%s\n", id, idstr);
568
569   return S_OK;
570 }
571
572 /******************************************************************************
573  *              StringFromCLSID16       [COMPOBJ.19]
574  * Converts a GUID into the respective string representation.
575  * The target string is allocated using the OLE IMalloc.
576  * RETURNS
577  *      the string representation and HRESULT
578  */
579 HRESULT WINAPI StringFromCLSID16(
580         REFCLSID id,            /* [in] the GUID to be converted */
581         LPOLESTR16 *idstr       /* [out] a pointer to a to-be-allocated segmented pointer pointing to the resulting string */
582
583 ) {
584     LPMALLOC16  mllc;
585     HRESULT     ret;
586     DWORD       args[2];
587
588     ret = CoGetMalloc16(0,&mllc);
589     if (ret) return ret;
590
591     args[0] = (DWORD)mllc;
592     args[1] = 40;
593
594     /* No need for a Callback entry, we have WOWCallback16Ex which does
595      * everything we need.
596      */
597     if (!WOWCallback16Ex(
598         (DWORD)((ICOM_VTABLE(IMalloc16)*)PTR_SEG_TO_LIN(
599                 ICOM_VTBL(((LPMALLOC16)PTR_SEG_TO_LIN(mllc))))
600         )->fnAlloc,
601         WCB16_CDECL,
602         2*sizeof(DWORD),
603         (LPVOID)args,
604         (LPDWORD)idstr
605     )) {
606         WARN("CallTo16 IMalloc16 failed\n");
607         return E_FAIL;
608     }
609     return WINE_StringFromCLSID(id,PTR_SEG_TO_LIN(*idstr));
610 }
611
612 /******************************************************************************
613  *              StringFromCLSID [OLE32.151]
614  * Converts a GUID into the respective string representation.
615  * The target string is allocated using the OLE IMalloc.
616  * RETURNS
617  *      the string representation and HRESULT
618  */
619 HRESULT WINAPI StringFromCLSID(
620         REFCLSID id,            /* [in] the GUID to be converted */
621         LPOLESTR *idstr /* [out] a pointer to a to-be-allocated pointer pointing to the resulting string */
622 ) {
623         char            buf[80];
624         HRESULT       ret;
625         LPMALLOC        mllc;
626
627         if ((ret=CoGetMalloc(0,&mllc)))
628                 return ret;
629
630         ret=WINE_StringFromCLSID(id,buf);
631         if (!ret) {
632                 *idstr = IMalloc_Alloc(mllc,strlen(buf)*2+2);
633                 lstrcpyAtoW(*idstr,buf);
634         }
635         return ret;
636 }
637
638 /******************************************************************************
639  *              StringFromGUID2 [COMPOBJ.76] [OLE32.152]
640  *
641  * Converts a global unique identifier into a string of an API-
642  * specified fixed format. (The usual {.....} stuff.)
643  *
644  * RETURNS
645  *      The (UNICODE) string representation of the GUID in 'str'
646  *      The length of the resulting string, 0 if there was any problem.
647  */
648 INT WINAPI
649 StringFromGUID2(REFGUID id, LPOLESTR str, INT cmax)
650 {
651   char          xguid[80];
652
653   if (WINE_StringFromCLSID(id,xguid))
654         return 0;
655   if (strlen(xguid)>=cmax)
656         return 0;
657   lstrcpyAtoW(str,xguid);
658   return strlen(xguid) + 1;
659 }
660
661 /******************************************************************************
662  * ProgIDFromCLSID [OLE32.133]
663  * Converts a class id into the respective Program ID. (By using a registry lookup)
664  * RETURNS S_OK on success
665  * riid associated with the progid
666  */
667
668 HRESULT WINAPI ProgIDFromCLSID(
669   REFCLSID clsid, /* [in] class id as found in registry */
670   LPOLESTR *lplpszProgID/* [out] associated Prog ID */
671 )
672 {
673   char     strCLSID[50], *buf, *buf2;
674   DWORD    buf2len;
675   HKEY     xhkey;
676   LPMALLOC mllc;
677   HRESULT  ret = S_OK;
678
679   WINE_StringFromCLSID(clsid, strCLSID);
680
681   buf = HeapAlloc(GetProcessHeap(), 0, strlen(strCLSID)+14);
682   sprintf(buf,"CLSID\\%s\\ProgID", strCLSID);
683   if (RegOpenKeyA(HKEY_CLASSES_ROOT, buf, &xhkey))
684     ret = REGDB_E_CLASSNOTREG;
685
686   HeapFree(GetProcessHeap(), 0, buf);
687
688   if (ret == S_OK)
689   {
690     buf2 = HeapAlloc(GetProcessHeap(), 0, 255);
691     buf2len = 255;
692     if (RegQueryValueA(xhkey, NULL, buf2, &buf2len))
693       ret = REGDB_E_CLASSNOTREG;
694
695     if (ret == S_OK)
696     {
697       if (CoGetMalloc(0,&mllc))
698         ret = E_OUTOFMEMORY;
699       else
700       {
701         *lplpszProgID = IMalloc_Alloc(mllc, (buf2len+1)*2);
702         lstrcpyAtoW(*lplpszProgID, buf2);
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 /* 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 CLSIDkey,key;
1203         WCHAR valname[]={       'I','n','p','r','o','c',
1204                                 'S','e','r','v','e','r','3','2',0};
1205
1206         /* lookup CLSID in registry key HKCR/CLSID */
1207         hres = RegOpenKeyExA(HKEY_CLASSES_ROOT, "CLSID", 0, 
1208                                KEY_READ, &CLSIDkey);
1209
1210         if (hres != ERROR_SUCCESS)
1211                 return REGDB_E_READREGDB;
1212         hres = RegOpenKeyExA(CLSIDkey,xclsid,0,KEY_QUERY_VALUE,&key);
1213         if (hres != ERROR_SUCCESS) {
1214             RegCloseKey(CLSIDkey);
1215             return REGDB_E_CLASSNOTREG;
1216         }
1217         memset(dllName,0,sizeof(dllName));
1218         hres = RegQueryValueW(key, valname, dllName, &dllNameLen);
1219         if (hres) {
1220                 ERR("RegQueryValue of %s failed with hres %lx\n",debugstr_w(dllName),hres);
1221                 return REGDB_E_CLASSNOTREG; /* FIXME: check retval */
1222         }
1223         RegCloseKey(key);
1224         RegCloseKey(CLSIDkey);
1225         if (hres != ERROR_SUCCESS)
1226                 return REGDB_E_READREGDB;
1227         TRACE("found InprocServer32 dll %s\n", debugstr_w(dllName));
1228
1229         /* open dll, call DllGetClassObject */
1230         hLibrary = CoLoadLibrary(dllName, TRUE);
1231         if (hLibrary == 0) {
1232             FIXME("couldn't load InprocServer32 dll %s\n", debugstr_w(dllName));
1233             return E_ACCESSDENIED; /* or should this be CO_E_DLLNOTFOUND? */
1234         }
1235         DllGetClassObject = (DllGetClassObjectFunc)GetProcAddress(hLibrary, "DllGetClassObject");
1236         if (!DllGetClassObject) {
1237             /* not sure if this should be called here CoFreeLibrary(hLibrary);*/
1238             FIXME("couldn't find function DllGetClassObject in %s\n", debugstr_w(dllName));
1239             return E_ACCESSDENIED;
1240         }
1241
1242         /*
1243          * Ask the DLL for its class object. (there was a note here about class
1244          * factories but this is good.
1245          */
1246         return DllGetClassObject(rclsid, iid, ppv);
1247     }
1248     return hres;
1249 }
1250
1251 /***********************************************************************
1252  *        CoResumeClassObjects
1253  *
1254  * Resumes classobjects registered with REGCLS suspended
1255  */
1256 HRESULT WINAPI CoResumeClassObjects(void)
1257 {
1258         FIXME("\n");
1259         return S_OK;
1260 }
1261
1262 /***********************************************************************
1263  *        GetClassFile
1264  *
1265  * This function supplies the CLSID associated with the given filename.
1266  */
1267 HRESULT WINAPI GetClassFile(LPOLESTR filePathName,CLSID *pclsid)
1268 {
1269     IStorage *pstg=0;
1270     HRESULT res;
1271     int nbElm=0,length=0,i=0;
1272     LONG sizeProgId=20;
1273     LPOLESTR *pathDec=0,absFile=0,progId=0;
1274     WCHAR extention[100]={0};
1275
1276     TRACE("()\n");
1277
1278     /* if the file contain a storage object the return the CLSID writen by IStorage_SetClass method*/
1279     if((StgIsStorageFile(filePathName))==S_OK){
1280
1281         res=StgOpenStorage(filePathName,NULL,STGM_READ | STGM_SHARE_DENY_WRITE,NULL,0,&pstg);
1282
1283         if (SUCCEEDED(res))
1284             res=ReadClassStg(pstg,pclsid);
1285
1286         IStorage_Release(pstg);
1287
1288         return res;
1289     }
1290     /* if the file is not a storage object then attemps to match various bits in the file against a
1291        pattern in the registry. this case is not frequently used ! so I present only the psodocode for
1292        this case
1293        
1294      for(i=0;i<nFileTypes;i++)
1295
1296         for(i=0;j<nPatternsForType;j++){
1297
1298             PATTERN pat;
1299             HANDLE  hFile;
1300
1301             pat=ReadPatternFromRegistry(i,j);
1302             hFile=CreateFileW(filePathName,,,,,,hFile);
1303             SetFilePosition(hFile,pat.offset);
1304             ReadFile(hFile,buf,pat.size,NULL,NULL);
1305             if (memcmp(buf&pat.mask,pat.pattern.pat.size)==0){
1306
1307                 *pclsid=ReadCLSIDFromRegistry(i);
1308                 return S_OK;
1309             }
1310         }
1311      */
1312
1313     /* if the obove strategies fail then search for the extension key in the registry */
1314
1315     /* get the last element (absolute file) in the path name */
1316     nbElm=FileMonikerImpl_DecomposePath(filePathName,&pathDec);
1317     absFile=pathDec[nbElm-1];
1318
1319     /* failed if the path represente a directory and not an absolute file name*/
1320     if (lstrcmpW(absFile,(LPOLESTR)"\\"))
1321         return MK_E_INVALIDEXTENSION;
1322
1323     /* get the extension of the file */
1324     length=lstrlenW(absFile);
1325     for(i=length-1; ( (i>=0) && (extention[i]=absFile[i]) );i--);
1326         
1327     /* get the progId associated to the extension */
1328     progId=CoTaskMemAlloc(sizeProgId);
1329
1330     res=RegQueryValueW(HKEY_CLASSES_ROOT,extention,progId,&sizeProgId);
1331
1332     if (res==ERROR_MORE_DATA){
1333
1334         progId = CoTaskMemRealloc(progId,sizeProgId);
1335         res=RegQueryValueW(HKEY_CLASSES_ROOT,extention,progId,&sizeProgId);
1336     }
1337     if (res==ERROR_SUCCESS)
1338         /* return the clsid associated to the progId */
1339         res= CLSIDFromProgID(progId,pclsid);
1340
1341     for(i=0; pathDec[i]!=NULL;i++)
1342         CoTaskMemFree(pathDec[i]);
1343     CoTaskMemFree(pathDec);
1344
1345     CoTaskMemFree(progId);
1346
1347     if (res==ERROR_SUCCESS)
1348         return res;
1349
1350     return MK_E_INVALIDEXTENSION;
1351 }
1352 /******************************************************************************
1353  *              CoRegisterMessageFilter16       [COMPOBJ.27]
1354  */
1355 HRESULT WINAPI CoRegisterMessageFilter16(
1356         LPMESSAGEFILTER lpMessageFilter,
1357         LPMESSAGEFILTER *lplpMessageFilter
1358 ) {
1359         FIXME("(%p,%p),stub!\n",lpMessageFilter,lplpMessageFilter);
1360         return 0;
1361 }
1362
1363 /***********************************************************************
1364  *           CoCreateInstance [COMPOBJ.13, OLE32.7]
1365  */
1366 HRESULT WINAPI CoCreateInstance(
1367         REFCLSID rclsid,
1368         LPUNKNOWN pUnkOuter,
1369         DWORD dwClsContext,
1370         REFIID iid,
1371         LPVOID *ppv) 
1372 {
1373         HRESULT hres;
1374         LPCLASSFACTORY lpclf = 0;
1375
1376   /*
1377    * Sanity check
1378    */
1379   if (ppv==0)
1380     return E_POINTER;
1381
1382   /*
1383    * Initialize the "out" parameter
1384    */
1385   *ppv = 0;
1386   
1387   /*
1388    * Get a class factory to construct the object we want.
1389    */
1390   hres = CoGetClassObject(rclsid,
1391                           dwClsContext,
1392                           NULL,
1393                           &IID_IClassFactory,
1394                           (LPVOID)&lpclf);
1395
1396   if (FAILED(hres))
1397     return hres;
1398
1399   /*
1400    * Create the object and don't forget to release the factory
1401    */
1402         hres = IClassFactory_CreateInstance(lpclf, pUnkOuter, iid, ppv);
1403         IClassFactory_Release(lpclf);
1404
1405         return hres;
1406 }
1407
1408 /***********************************************************************
1409  *           CoCreateInstanceEx [OLE32.165]
1410  */
1411 HRESULT WINAPI CoCreateInstanceEx(
1412   REFCLSID      rclsid, 
1413   LPUNKNOWN     pUnkOuter,
1414   DWORD         dwClsContext, 
1415   COSERVERINFO* pServerInfo,
1416   ULONG         cmq,
1417   MULTI_QI*     pResults)
1418 {
1419   IUnknown* pUnk = NULL;
1420   HRESULT   hr;
1421   ULONG     index;
1422   int       successCount = 0;
1423
1424   /*
1425    * Sanity check
1426    */
1427   if ( (cmq==0) || (pResults==NULL))
1428     return E_INVALIDARG;
1429
1430   if (pServerInfo!=NULL)
1431     FIXME("() non-NULL pServerInfo not supported!\n");
1432
1433   /*
1434    * Initialize all the "out" parameters.
1435    */
1436   for (index = 0; index < cmq; index++)
1437   {
1438     pResults[index].pItf = NULL;
1439     pResults[index].hr   = E_NOINTERFACE;
1440   }
1441
1442   /*
1443    * Get the object and get its IUnknown pointer.
1444    */
1445   hr = CoCreateInstance(rclsid, 
1446                         pUnkOuter,
1447                         dwClsContext,
1448                         &IID_IUnknown,
1449                         (VOID**)&pUnk);
1450
1451   if (hr)
1452     return hr;
1453
1454   /*
1455    * Then, query for all the interfaces requested.
1456    */
1457   for (index = 0; index < cmq; index++)
1458   {
1459     pResults[index].hr = IUnknown_QueryInterface(pUnk,
1460                                                  pResults[index].pIID,
1461                                                  (VOID**)&(pResults[index].pItf));
1462
1463     if (pResults[index].hr == S_OK)
1464       successCount++;
1465   }
1466
1467   /*
1468    * Release our temporary unknown pointer.
1469    */
1470   IUnknown_Release(pUnk);
1471
1472   if (successCount == 0)
1473     return E_NOINTERFACE;
1474
1475   if (successCount!=cmq)
1476     return CO_S_NOTALLINTERFACES;
1477
1478   return S_OK;
1479 }
1480
1481 /***********************************************************************
1482  *           CoFreeLibrary [COMPOBJ.13]
1483  */
1484 void WINAPI CoFreeLibrary(HINSTANCE hLibrary)
1485 {
1486     OpenDll *ptr, *prev;
1487     OpenDll *tmp;
1488
1489     /* lookup library in linked list */
1490     prev = NULL;
1491     for (ptr = openDllList; ptr != NULL; ptr=ptr->next) {
1492         if (ptr->hLibrary == hLibrary) {
1493             break;
1494         }
1495         prev = ptr;
1496     }
1497
1498     if (ptr == NULL) {
1499         /* shouldn't happen if user passed in a valid hLibrary */
1500         return;
1501     }
1502     /* assert: ptr points to the library entry to free */
1503
1504     /* free library and remove node from list */
1505     FreeLibrary(hLibrary);
1506     if (ptr == openDllList) {
1507         tmp = openDllList->next;
1508         HeapFree(GetProcessHeap(), 0, openDllList);
1509         openDllList = tmp;
1510     } else {
1511         tmp = ptr->next;
1512         HeapFree(GetProcessHeap(), 0, ptr);
1513         prev->next = tmp;
1514     }
1515
1516 }
1517
1518
1519 /***********************************************************************
1520  *           CoFreeAllLibraries [COMPOBJ.12]
1521  */
1522 void WINAPI CoFreeAllLibraries(void)
1523 {
1524     OpenDll *ptr, *tmp;
1525
1526     for (ptr = openDllList; ptr != NULL; ) {
1527         tmp=ptr->next;
1528         CoFreeLibrary(ptr->hLibrary);
1529         ptr = tmp;
1530     }
1531 }
1532
1533
1534
1535 /***********************************************************************
1536  *           CoFreeUnusedLibraries [COMPOBJ.17]
1537  */
1538 void WINAPI CoFreeUnusedLibraries(void)
1539 {
1540     OpenDll *ptr, *tmp;
1541     typedef HRESULT(*DllCanUnloadNowFunc)(void);
1542     DllCanUnloadNowFunc DllCanUnloadNow;
1543
1544     for (ptr = openDllList; ptr != NULL; ) {
1545         DllCanUnloadNow = (DllCanUnloadNowFunc)
1546             GetProcAddress(ptr->hLibrary, "DllCanUnloadNow");
1547         
1548         if ( (DllCanUnloadNow != NULL) &&
1549              (DllCanUnloadNow() == S_OK) ) {
1550             tmp=ptr->next;
1551             CoFreeLibrary(ptr->hLibrary);
1552             ptr = tmp;
1553         } else {
1554             ptr=ptr->next;
1555         }
1556     }
1557 }
1558
1559 /***********************************************************************
1560  *           CoFileTimeNow [COMPOBJ.82, OLE32.10]
1561  * RETURNS
1562  *      the current system time in lpFileTime
1563  */
1564 HRESULT WINAPI CoFileTimeNow( FILETIME *lpFileTime ) /* [out] the current time */
1565 {
1566     GetSystemTimeAsFileTime( lpFileTime );
1567     return S_OK;
1568 }
1569
1570 /***********************************************************************
1571  *           CoTaskMemAlloc (OLE32.43)
1572  * RETURNS
1573  *      pointer to newly allocated block
1574  */
1575 LPVOID WINAPI CoTaskMemAlloc(
1576         ULONG size      /* [in] size of memoryblock to be allocated */
1577 ) {
1578     LPMALLOC    lpmalloc;
1579     HRESULT     ret = CoGetMalloc(0,&lpmalloc);
1580
1581     if (FAILED(ret)) 
1582         return NULL;
1583
1584     return IMalloc_Alloc(lpmalloc,size);
1585 }
1586 /***********************************************************************
1587  *           CoTaskMemFree (OLE32.44)
1588  */
1589 VOID WINAPI CoTaskMemFree(
1590         LPVOID ptr      /* [in] pointer to be freed */
1591 ) {
1592     LPMALLOC    lpmalloc;
1593     HRESULT     ret = CoGetMalloc(0,&lpmalloc);
1594
1595     if (FAILED(ret)) 
1596       return;
1597
1598     IMalloc_Free(lpmalloc, ptr);
1599 }
1600
1601 /***********************************************************************
1602  *           CoTaskMemRealloc (OLE32.45)
1603  * RETURNS
1604  *      pointer to newly allocated block
1605  */
1606 LPVOID WINAPI CoTaskMemRealloc(
1607   LPVOID pvOld,
1608   ULONG  size)  /* [in] size of memoryblock to be allocated */
1609 {
1610   LPMALLOC lpmalloc;
1611   HRESULT  ret = CoGetMalloc(0,&lpmalloc);
1612   
1613   if (FAILED(ret)) 
1614     return NULL;
1615
1616   return IMalloc_Realloc(lpmalloc, pvOld, size);
1617 }
1618
1619 /***********************************************************************
1620  *           CoLoadLibrary (OLE32.30)
1621  */
1622 HINSTANCE WINAPI CoLoadLibrary(LPOLESTR lpszLibName, BOOL bAutoFree)
1623 {
1624     HINSTANCE hLibrary;
1625     OpenDll *ptr;
1626     OpenDll *tmp;
1627   
1628     TRACE("CoLoadLibrary(%p, %d\n", debugstr_w(lpszLibName), bAutoFree);
1629
1630     hLibrary = LoadLibraryExW(lpszLibName, 0, LOAD_WITH_ALTERED_SEARCH_PATH);
1631
1632     if (!bAutoFree)
1633         return hLibrary;
1634
1635     if (openDllList == NULL) {
1636         /* empty list -- add first node */
1637         openDllList = (OpenDll*)HeapAlloc(GetProcessHeap(),0, sizeof(OpenDll));
1638         openDllList->hLibrary=hLibrary;
1639         openDllList->next = NULL;
1640     } else {
1641         /* search for this dll */
1642         int found = FALSE;
1643         for (ptr = openDllList; ptr->next != NULL; ptr=ptr->next) {
1644             if (ptr->hLibrary == hLibrary) {
1645                 found = TRUE;
1646                 break;
1647             }
1648         }
1649         if (!found) {
1650             /* dll not found, add it */
1651             tmp = openDllList;
1652             openDllList = (OpenDll*)HeapAlloc(GetProcessHeap(),0, sizeof(OpenDll));
1653             openDllList->hLibrary = hLibrary;
1654             openDllList->next = tmp;
1655         }
1656     }
1657      
1658     return hLibrary;
1659 }
1660
1661 /***********************************************************************
1662  *           CoInitializeWOW (OLE32.27)
1663  */
1664 HRESULT WINAPI CoInitializeWOW(DWORD x,DWORD y) {
1665     FIXME("(0x%08lx,0x%08lx),stub!\n",x,y);
1666     return 0;
1667 }
1668
1669 /******************************************************************************
1670  *              CoLockObjectExternal16  [COMPOBJ.63]
1671  */
1672 HRESULT WINAPI CoLockObjectExternal16(
1673     LPUNKNOWN pUnk,             /* [in] object to be locked */
1674     BOOL16 fLock,               /* [in] do lock */
1675     BOOL16 fLastUnlockReleases  /* [in] ? */
1676 ) {
1677     FIXME("(%p,%d,%d),stub!\n",pUnk,fLock,fLastUnlockReleases);
1678     return S_OK;
1679 }
1680
1681 /******************************************************************************
1682  *              CoLockObjectExternal    [OLE32.31]
1683  */
1684 HRESULT WINAPI CoLockObjectExternal(
1685     LPUNKNOWN pUnk,             /* [in] object to be locked */
1686     BOOL fLock,         /* [in] do lock */
1687     BOOL fLastUnlockReleases) /* [in] unlock all */
1688 {
1689
1690   if (fLock) 
1691   {
1692     /* 
1693      * Increment the external lock coutner, COM_ExternalLockAddRef also
1694      * increment the object's internal lock counter.
1695      */
1696     COM_ExternalLockAddRef( pUnk); 
1697   }
1698   else
1699   {
1700     /* 
1701      * Decrement the external lock coutner, COM_ExternalLockRelease also
1702      * decrement the object's internal lock counter.
1703      */
1704     COM_ExternalLockRelease( pUnk, fLastUnlockReleases);
1705   }
1706
1707     return S_OK;
1708 }
1709
1710 /***********************************************************************
1711  *           CoGetState16 [COMPOBJ.115]
1712  */
1713 HRESULT WINAPI CoGetState16(LPDWORD state)
1714 {
1715     FIXME("(%p),stub!\n", state);
1716     *state = 0;
1717     return S_OK;
1718 }
1719 /***********************************************************************
1720  *           CoSetState [COM32.42]
1721  */
1722 HRESULT WINAPI CoSetState(LPDWORD state)
1723 {
1724     FIXME("(%p),stub!\n", state);
1725     if (state) *state = 0;
1726     return S_OK;
1727 }
1728 /***********************************************************************
1729  *          CoCreateFreeThreadedMarshaler [OLE32.5]
1730  */
1731 HRESULT WINAPI CoCreateFreeThreadedMarshaler (LPUNKNOWN punkOuter, LPUNKNOWN* ppunkMarshal)
1732 {
1733    FIXME ("(%p %p): stub\n", punkOuter, ppunkMarshal);
1734     
1735    return S_OK;
1736 }
1737
1738
1739 /***********************************************************************
1740  *           DllGetClassObject [OLE32.63]
1741  */
1742 HRESULT WINAPI OLE32_DllGetClassObject(REFCLSID rclsid, REFIID iid,LPVOID *ppv)
1743 {       
1744         FIXME("\n\tCLSID:\t%s,\n\tIID:\t%s\n",debugstr_guid(rclsid),debugstr_guid(iid));
1745         *ppv = NULL;
1746         return CLASS_E_CLASSNOTAVAILABLE;
1747 }
1748
1749
1750 /***
1751  * COM_RevokeAllClasses
1752  *
1753  * This method is called when the COM libraries are uninitialized to 
1754  * release all the references to the class objects registered with
1755  * the library
1756  */
1757 static void COM_RevokeAllClasses()
1758 {
1759   while (firstRegisteredClass!=0)
1760   {
1761     CoRevokeClassObject(firstRegisteredClass->dwCookie);
1762   }
1763 }
1764
1765 /****************************************************************************
1766  *  COM External Lock methods implementation
1767  */
1768
1769 /****************************************************************************
1770  * Public - Method that increments the count for a IUnknown* in the linked 
1771  * list.  The item is inserted if not already in the list.
1772  */
1773 static void COM_ExternalLockAddRef(
1774   IUnknown *pUnk)
1775 {
1776   COM_ExternalLock *externalLock = COM_ExternalLockFind(pUnk);
1777
1778   /*
1779    * Add an external lock to the object. If it was already externally
1780    * locked, just increase the reference count. If it was not.
1781    * add the item to the list.
1782    */
1783   if ( externalLock == EL_NOT_FOUND )
1784     COM_ExternalLockInsert(pUnk);
1785   else
1786     externalLock->uRefCount++;
1787
1788   /*
1789    * Add an internal lock to the object
1790    */
1791   IUnknown_AddRef(pUnk); 
1792 }
1793
1794 /****************************************************************************
1795  * Public - Method that decrements the count for a IUnknown* in the linked 
1796  * list.  The item is removed from the list if its count end up at zero or if
1797  * bRelAll is TRUE.
1798  */
1799 static void COM_ExternalLockRelease(
1800   IUnknown *pUnk,
1801   BOOL   bRelAll)
1802 {
1803   COM_ExternalLock *externalLock = COM_ExternalLockFind(pUnk);
1804
1805   if ( externalLock != EL_NOT_FOUND )
1806   {
1807     do
1808     {
1809       externalLock->uRefCount--;  /* release external locks      */
1810       IUnknown_Release(pUnk);     /* release local locks as well */
1811
1812       if ( bRelAll == FALSE ) 
1813         break;  /* perform single release */
1814
1815     } while ( externalLock->uRefCount > 0 );  
1816
1817     if ( externalLock->uRefCount == 0 )  /* get rid of the list entry */
1818       COM_ExternalLockDelete(externalLock);
1819   }
1820 }
1821 /****************************************************************************
1822  * Public - Method that frees the content of the list.
1823  */
1824 static void COM_ExternalLockFreeList()
1825 {
1826   COM_ExternalLock *head;
1827
1828   head = elList.head;                 /* grab it by the head             */
1829   while ( head != EL_END_OF_LIST )
1830   {
1831     COM_ExternalLockDelete(head);     /* get rid of the head stuff       */
1832
1833     head = elList.head;               /* get the new head...             */ 
1834   }
1835 }
1836
1837 /****************************************************************************
1838  * Public - Method that dump the content of the list.
1839  */
1840 void COM_ExternalLockDump()
1841 {
1842   COM_ExternalLock *current = elList.head;
1843
1844   DPRINTF("\nExternal lock list contains:\n");
1845
1846   while ( current != EL_END_OF_LIST )
1847   {
1848       DPRINTF( "\t%p with %lu references count.\n", current->pUnk, current->uRefCount);
1849  
1850     /* Skip to the next item */ 
1851     current = current->next;
1852   } 
1853
1854 }
1855
1856 /****************************************************************************
1857  * Internal - Find a IUnknown* in the linked list
1858  */
1859 static COM_ExternalLock* COM_ExternalLockFind(
1860   IUnknown *pUnk)
1861 {
1862   return COM_ExternalLockLocate(elList.head, pUnk);
1863 }
1864
1865 /****************************************************************************
1866  * Internal - Recursivity agent for IUnknownExternalLockList_Find
1867  */
1868 static COM_ExternalLock* COM_ExternalLockLocate(
1869   COM_ExternalLock *element,
1870   IUnknown         *pUnk)
1871 {
1872   if ( element == EL_END_OF_LIST )  
1873     return EL_NOT_FOUND;
1874
1875   else if ( element->pUnk == pUnk )    /* We found it */
1876     return element;
1877
1878   else                                 /* Not the right guy, keep on looking */ 
1879     return COM_ExternalLockLocate( element->next, pUnk);
1880 }
1881
1882 /****************************************************************************
1883  * Internal - Insert a new IUnknown* to the linked list
1884  */
1885 static BOOL COM_ExternalLockInsert(
1886   IUnknown *pUnk)
1887 {
1888   COM_ExternalLock *newLock      = NULL;
1889   COM_ExternalLock *previousHead = NULL;
1890
1891   /*
1892    * Allocate space for the new storage object
1893    */
1894   newLock = HeapAlloc(GetProcessHeap(), 0, sizeof(COM_ExternalLock));
1895
1896   if (newLock!=NULL)
1897   {
1898     if ( elList.head == EL_END_OF_LIST ) 
1899     {
1900       elList.head = newLock;    /* The list is empty */
1901     }
1902     else 
1903     {
1904       /* 
1905        * insert does it at the head
1906        */
1907       previousHead  = elList.head;
1908       elList.head = newLock;
1909     }
1910
1911     /*
1912      * Set new list item data member 
1913      */
1914     newLock->pUnk      = pUnk;
1915     newLock->uRefCount = 1;
1916     newLock->next      = previousHead;
1917     
1918     return TRUE;
1919   }
1920   else
1921     return FALSE;
1922 }
1923
1924 /****************************************************************************
1925  * Internal - Method that removes an item from the linked list.
1926  */
1927 static void COM_ExternalLockDelete(
1928   COM_ExternalLock *itemList)
1929 {
1930   COM_ExternalLock *current = elList.head;
1931
1932   if ( current == itemList )
1933   {
1934     /* 
1935      * this section handles the deletion of the first node 
1936      */
1937     elList.head = itemList->next;
1938     HeapFree( GetProcessHeap(), 0, itemList);  
1939   }
1940   else
1941   {
1942     do 
1943     {
1944       if ( current->next == itemList )   /* We found the item to free  */
1945       {
1946         current->next = itemList->next;  /* readjust the list pointers */
1947   
1948         HeapFree( GetProcessHeap(), 0, itemList);  
1949         break; 
1950       }
1951  
1952       /* Skip to the next item */ 
1953       current = current->next;
1954   
1955     } while ( current != EL_END_OF_LIST );
1956   }
1957 }
1958
1959 /***********************************************************************
1960  *      COMPOBJ_DllEntryPoint                   [COMPOBJ.entry]
1961  *
1962  *    Initialization code for the COMPOBJ DLL
1963  *
1964  * RETURNS:
1965  */
1966 BOOL WINAPI COMPOBJ_DllEntryPoint(DWORD Reason, HINSTANCE16 hInst, WORD ds, WORD HeapSize, DWORD res1, WORD res2)
1967 {
1968         TRACE("(%08lx, %04x, %04x, %04x, %08lx, %04x)\n", Reason, hInst, ds, HeapSize,
1969  res1, res2);
1970         switch(Reason)
1971         {
1972         case DLL_PROCESS_ATTACH:
1973                 COMPOBJ_Attach++;
1974                 if(COMPOBJ_hInstance)
1975                 {
1976                         ERR("compobj.dll instantiated twice!\n");
1977                         /*
1978                          * We should return FALSE here, but that will break
1979                          * most apps that use CreateProcess because we do
1980                          * not yet support seperate address-spaces.
1981                          */
1982                         return TRUE;
1983                 }
1984
1985                 COMPOBJ_hInstance = hInst;
1986                 break;
1987
1988         case DLL_PROCESS_DETACH:
1989                 if(!--COMPOBJ_Attach)
1990                         COMPOBJ_hInstance = 0;
1991                 break;
1992         }
1993         return TRUE;
1994 }
1995
1996 /******************************************************************************
1997  *              OleGetAutoConvert        [OLE32.104]
1998  */
1999 HRESULT WINAPI OleGetAutoConvert(REFCLSID clsidOld, LPCLSID pClsidNew)
2000 {
2001   HKEY  hkey;
2002   char  buf[200];
2003   WCHAR wbuf[200];
2004   DWORD len;
2005
2006   sprintf(buf,"CLSID\\");WINE_StringFromCLSID(clsidOld,&buf[6]);
2007   if (RegOpenKeyA(HKEY_CLASSES_ROOT,buf,&hkey))
2008       return REGDB_E_CLASSNOTREG;
2009   len = 200;
2010   if (RegQueryValueA(hkey,"AutoConvertTo",buf,&len))
2011       return REGDB_E_KEYMISSING;
2012   RegCloseKey(hkey);
2013   lstrcpyAtoW(wbuf,buf);
2014   CLSIDFromString(wbuf,pClsidNew);
2015   return S_OK;
2016 }
2017
2018 /***********************************************************************
2019  *           IsEqualGUID [OLE32.76]
2020  *
2021  * Compares two Unique Identifiers.
2022  *
2023  * RETURNS
2024  *      TRUE if equal
2025  */
2026 #undef IsEqualGUID
2027 BOOL WINAPI IsEqualGUID(
2028      REFGUID rguid1, /* [in] unique id 1 */
2029      REFGUID rguid2  /* [in] unique id 2 */
2030      )
2031 {
2032     return !memcmp(rguid1,rguid2,sizeof(GUID));
2033 }