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