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