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