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