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