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