ole32: Fix a couple of comments.
[wine] / dlls / ole32 / moniker.c
1 /*
2  *      Monikers
3  *
4  *      Copyright 1998  Marcus Meissner
5  *      Copyright 1999  Noomen Hamza
6  *      Copyright 2005  Robert Shearman (for CodeWeavers)
7  *      Copyright 2007  Robert Shearman
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22  */
23
24 #include "config.h"
25 #include "wine/port.h"
26
27 #include <stdarg.h>
28 #include <string.h>
29
30 #define COBJMACROS
31
32 #include "winerror.h"
33 #include "windef.h"
34 #include "winbase.h"
35 #include "winuser.h"
36 #include "wtypes.h"
37 #include "ole2.h"
38
39 #include "wine/list.h"
40 #include "wine/debug.h"
41 #include "wine/unicode.h"
42 #include "wine/exception.h"
43
44 #include "compobj_private.h"
45 #include "moniker.h"
46 #include "irot.h"
47
48 WINE_DEFAULT_DEBUG_CHANNEL(ole);
49
50 /* see MSDN docs for IROTData::GetComparisonData, which states what this
51  * constant is
52  */
53 #define MAX_COMPARISON_DATA 2048
54
55 static LONG WINAPI rpc_filter(EXCEPTION_POINTERS *eptr)
56 {
57     return I_RpcExceptionFilter(eptr->ExceptionRecord->ExceptionCode);
58 }
59
60 /* define the structure of the running object table elements */
61 struct rot_entry
62 {
63     struct list        entry;
64     InterfaceData* object; /* marshaled running object*/
65     MonikerComparisonData* moniker_data; /* moniker comparison data that identifies this object */
66     DWORD              cookie; /* cookie identifying this object */
67     FILETIME           last_modified;
68     IrotContextHandle  ctxt_handle;
69 };
70
71 /* define the RunningObjectTableImpl structure */
72 typedef struct RunningObjectTableImpl
73 {
74     const IRunningObjectTableVtbl *lpVtbl;
75     LONG ref;
76
77     struct list rot; /* list of ROT entries */
78     CRITICAL_SECTION lock;
79 } RunningObjectTableImpl;
80
81 static RunningObjectTableImpl* runningObjectTableInstance = NULL;
82 static IrotHandle irot_handle;
83
84 /* define the EnumMonikerImpl structure */
85 typedef struct EnumMonikerImpl
86 {
87     const IEnumMonikerVtbl *lpVtbl;
88     LONG ref;
89
90     InterfaceList *moniker_list;
91     ULONG pos;
92 } EnumMonikerImpl;
93
94
95 /* IEnumMoniker Local functions*/
96 static HRESULT EnumMonikerImpl_CreateEnumROTMoniker(InterfaceList *moniker_list,
97     ULONG pos, IEnumMoniker **ppenumMoniker);
98
99 static IrotHandle get_irot_handle(void)
100 {
101     if (!irot_handle)
102     {
103         RPC_STATUS status;
104         RPC_WSTR binding;
105         IrotHandle new_handle;
106         unsigned short ncacn_np[] = IROT_PROTSEQ;
107         unsigned short endpoint[] = IROT_ENDPOINT;
108         status = RpcStringBindingComposeW(NULL, ncacn_np, NULL, endpoint, NULL, &binding);
109         if (status == RPC_S_OK)
110         {
111             status = RpcBindingFromStringBindingW(binding, &new_handle);
112             RpcStringFreeW(&binding);
113         }
114         if (status != RPC_S_OK)
115             return NULL;
116         if (InterlockedCompareExchangePointer(&irot_handle, new_handle, NULL))
117             /* another thread beat us to it */
118             RpcBindingFree(&new_handle);
119     }
120     return irot_handle;
121 }
122
123 static BOOL start_rpcss(void)
124 {
125     PROCESS_INFORMATION pi;
126     STARTUPINFOW si;
127     static WCHAR cmd[6];
128     static const WCHAR rpcss[] = {'r','p','c','s','s',0};
129     BOOL rslt;
130
131     TRACE("\n");
132
133     ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));
134     ZeroMemory(&si, sizeof(STARTUPINFOA));
135     si.cb = sizeof(STARTUPINFOA);
136
137     memcpy(cmd, rpcss, sizeof(rpcss));
138
139     rslt = CreateProcessW(
140                           NULL,           /* executable */
141                           cmd,            /* command line */
142                           NULL,           /* process security attributes */
143                           NULL,           /* primary thread security attributes */
144                           FALSE,          /* inherit handles */
145                           0,              /* creation flags */
146                           NULL,           /* use parent's environment */
147                           NULL,           /* use parent's current directory */
148                           &si,            /* STARTUPINFO pointer */
149                           &pi             /* PROCESS_INFORMATION */
150                           );
151
152     if (rslt)
153     {
154         CloseHandle(pi.hProcess);
155         CloseHandle(pi.hThread);
156         Sleep(100);
157     }
158
159     return rslt;
160 }
161
162 static HRESULT create_stream_on_mip_ro(const InterfaceData *mip, IStream **stream)
163 {
164     HGLOBAL hglobal = GlobalAlloc(0, mip->ulCntData);
165     void *pv = GlobalLock(hglobal);
166     memcpy(pv, mip->abData, mip->ulCntData);
167     GlobalUnlock(hglobal);
168     return CreateStreamOnHGlobal(hglobal, TRUE, stream);
169 }
170
171 static inline void rot_entry_delete(struct rot_entry *rot_entry)
172 {
173     if (rot_entry->cookie)
174     {
175         InterfaceData *object = NULL;
176         InterfaceData *moniker = NULL;
177         __TRY
178         {
179             IrotRevoke(get_irot_handle(), rot_entry->cookie,
180                        &rot_entry->ctxt_handle, &object, &moniker);
181         }
182         __EXCEPT(rpc_filter)
183         {
184         }
185         __ENDTRY
186         MIDL_user_free(object);
187         if (moniker)
188         {
189             IStream *stream;
190             HRESULT hr;
191             hr = create_stream_on_mip_ro(moniker, &stream);
192             if (hr == S_OK)
193             {
194                 CoReleaseMarshalData(stream);
195                 IUnknown_Release(stream);
196             }
197         }
198         MIDL_user_free(moniker);
199     }
200     if (rot_entry->object)
201     {
202         IStream *stream;
203         HRESULT hr;
204         hr = create_stream_on_mip_ro(rot_entry->object, &stream);
205         if (hr == S_OK)
206         {
207             CoReleaseMarshalData(stream);
208             IUnknown_Release(stream);
209         }
210     }
211     HeapFree(GetProcessHeap(), 0, rot_entry->object);
212     HeapFree(GetProcessHeap(), 0, rot_entry->moniker_data);
213     HeapFree(GetProcessHeap(), 0, rot_entry);
214 }
215
216 /* moniker_data must be freed with HeapFree when no longer in use */
217 static HRESULT get_moniker_comparison_data(IMoniker *pMoniker, MonikerComparisonData **moniker_data)
218 {
219     HRESULT hr;
220     IROTData *pROTData = NULL;
221     hr = IMoniker_QueryInterface(pMoniker, &IID_IROTData, (void *)&pROTData);
222     if (SUCCEEDED(hr))
223     {
224         ULONG size = MAX_COMPARISON_DATA;
225         *moniker_data = HeapAlloc(GetProcessHeap(), 0, FIELD_OFFSET(MonikerComparisonData, abData[size]));
226         if (!*moniker_data)
227         {
228             IROTData_Release(pROTData);
229             return E_OUTOFMEMORY;
230         }
231         hr = IROTData_GetComparisonData(pROTData, (*moniker_data)->abData, size, &size);
232         IROTData_Release(pROTData);
233         if (hr != S_OK)
234         {
235             ERR("Failed to copy comparison data into buffer, hr = 0x%08x\n", hr);
236             HeapFree(GetProcessHeap(), 0, *moniker_data);
237             return hr;
238         }
239         (*moniker_data)->ulCntData = size;
240     }
241     else
242     {
243         IBindCtx *pbc;
244         LPOLESTR pszDisplayName;
245         CLSID clsid;
246         int len;
247
248         TRACE("generating comparison data from display name\n");
249
250         hr = CreateBindCtx(0, &pbc);
251         if (FAILED(hr))
252             return hr;
253         hr = IMoniker_GetDisplayName(pMoniker, pbc, NULL, &pszDisplayName);
254         IBindCtx_Release(pbc);
255         if (FAILED(hr))
256             return hr;
257         hr = IMoniker_GetClassID(pMoniker, &clsid);
258         if (FAILED(hr))
259         {
260             CoTaskMemFree(pszDisplayName);
261             return hr;
262         }
263
264         len = strlenW(pszDisplayName);
265         *moniker_data = HeapAlloc(GetProcessHeap(), 0,
266             FIELD_OFFSET(MonikerComparisonData, abData[sizeof(CLSID) + (len+1)*sizeof(WCHAR)]));
267         if (!*moniker_data)
268         {
269             CoTaskMemFree(pszDisplayName);
270             return E_OUTOFMEMORY;
271         }
272         (*moniker_data)->ulCntData = sizeof(CLSID) + (len+1)*sizeof(WCHAR);
273
274         memcpy(&(*moniker_data)->abData[0], &clsid, sizeof(clsid));
275         memcpy(&(*moniker_data)->abData[sizeof(clsid)], pszDisplayName, (len+1)*sizeof(WCHAR));
276         CoTaskMemFree(pszDisplayName);
277     }
278     return S_OK;
279 }
280
281 static HRESULT reduce_moniker(IMoniker *pmk, IBindCtx *pbc, IMoniker **pmkReduced)
282 {
283     IBindCtx *pbcNew = NULL;
284     HRESULT hr;
285     if (!pbc)
286     {
287         hr = CreateBindCtx(0, &pbcNew);
288         if (FAILED(hr))
289             return hr;
290         pbc = pbcNew;
291     }
292     hr = IMoniker_Reduce(pmk, pbc, MKRREDUCE_ALL, NULL, pmkReduced);
293     if (FAILED(hr))
294         ERR("reducing moniker failed with error 0x%08x\n", hr);
295     if (pbcNew) IBindCtx_Release(pbcNew);
296     return hr;
297 }
298
299 /***********************************************************************
300  *        RunningObjectTable_QueryInterface
301  */
302 static HRESULT WINAPI
303 RunningObjectTableImpl_QueryInterface(IRunningObjectTable* iface,
304                                       REFIID riid,void** ppvObject)
305 {
306     RunningObjectTableImpl *This = (RunningObjectTableImpl *)iface;
307
308     TRACE("(%p,%p,%p)\n",This,riid,ppvObject);
309
310     /* validate arguments */
311
312     if (ppvObject==0)
313         return E_INVALIDARG;
314
315     *ppvObject = 0;
316
317     if (IsEqualIID(&IID_IUnknown, riid) ||
318         IsEqualIID(&IID_IRunningObjectTable, riid))
319         *ppvObject = This;
320
321     if ((*ppvObject)==0)
322         return E_NOINTERFACE;
323
324     IRunningObjectTable_AddRef(iface);
325
326     return S_OK;
327 }
328
329 /***********************************************************************
330  *        RunningObjectTable_AddRef
331  */
332 static ULONG WINAPI
333 RunningObjectTableImpl_AddRef(IRunningObjectTable* iface)
334 {
335     RunningObjectTableImpl *This = (RunningObjectTableImpl *)iface;
336
337     TRACE("(%p)\n",This);
338
339     return InterlockedIncrement(&This->ref);
340 }
341
342 /***********************************************************************
343  *        RunningObjectTable_Destroy
344  */
345 static HRESULT
346 RunningObjectTableImpl_Destroy(void)
347 {
348     struct list *cursor, *cursor2;
349     IrotHandle old_handle;
350
351     TRACE("()\n");
352
353     if (runningObjectTableInstance==NULL)
354         return E_INVALIDARG;
355
356     /* free the ROT table memory */
357     LIST_FOR_EACH_SAFE(cursor, cursor2, &runningObjectTableInstance->rot)
358     {
359         struct rot_entry *rot_entry = LIST_ENTRY(cursor, struct rot_entry, entry);
360         list_remove(&rot_entry->entry);
361         rot_entry_delete(rot_entry);
362     }
363
364     DEBUG_CLEAR_CRITSEC_NAME(&runningObjectTableInstance->lock);
365     DeleteCriticalSection(&runningObjectTableInstance->lock);
366
367     /* free the ROT structure memory */
368     HeapFree(GetProcessHeap(),0,runningObjectTableInstance);
369     runningObjectTableInstance = NULL;
370
371     old_handle = irot_handle;
372     irot_handle = NULL;
373     if (old_handle)
374         RpcBindingFree(&old_handle);
375
376     return S_OK;
377 }
378
379 /***********************************************************************
380  *        RunningObjectTable_Release
381  */
382 static ULONG WINAPI
383 RunningObjectTableImpl_Release(IRunningObjectTable* iface)
384 {
385     RunningObjectTableImpl *This = (RunningObjectTableImpl *)iface;
386     ULONG ref;
387
388     TRACE("(%p)\n",This);
389
390     ref = InterlockedDecrement(&This->ref);
391
392     /* uninitialize ROT structure if there's no more references to it */
393     if (ref == 0)
394     {
395         struct list *cursor, *cursor2;
396         LIST_FOR_EACH_SAFE(cursor, cursor2, &This->rot)
397         {
398             struct rot_entry *rot_entry = LIST_ENTRY(cursor, struct rot_entry, entry);
399             list_remove(&rot_entry->entry);
400             rot_entry_delete(rot_entry);
401         }
402         /*  RunningObjectTable data structure will be not destroyed here ! the destruction will be done only
403          *  when RunningObjectTableImpl_UnInitialize function is called
404          */
405     }
406
407     return ref;
408 }
409
410 /***********************************************************************
411  *        RunningObjectTable_Register
412  *
413  * PARAMS
414  * grfFlags       [in] Registration options 
415  * punkObject     [in] the object being registered
416  * pmkObjectName  [in] the moniker of the object being registered
417  * pdwRegister    [out] the value identifying the registration
418  */
419 static HRESULT WINAPI
420 RunningObjectTableImpl_Register(IRunningObjectTable* iface, DWORD grfFlags,
421                IUnknown *punkObject, IMoniker *pmkObjectName, DWORD *pdwRegister)
422 {
423     RunningObjectTableImpl *This = (RunningObjectTableImpl *)iface;
424     struct rot_entry *rot_entry;
425     HRESULT hr = S_OK;
426     IStream *pStream = NULL;
427     DWORD mshlflags;
428     IBindCtx *pbc;
429     InterfaceData *moniker = NULL;
430
431     TRACE("(%p,%d,%p,%p,%p)\n",This,grfFlags,punkObject,pmkObjectName,pdwRegister);
432
433     if (grfFlags & ~(ROTFLAGS_REGISTRATIONKEEPSALIVE|ROTFLAGS_ALLOWANYCLIENT))
434     {
435         ERR("Invalid grfFlags: 0x%08x\n", grfFlags & ~(ROTFLAGS_REGISTRATIONKEEPSALIVE|ROTFLAGS_ALLOWANYCLIENT));
436         return E_INVALIDARG;
437     }
438
439     if (punkObject==NULL || pmkObjectName==NULL || pdwRegister==NULL)
440         return E_INVALIDARG;
441
442     rot_entry = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*rot_entry));
443     if (!rot_entry)
444         return E_OUTOFMEMORY;
445
446     /* marshal object */
447     hr = CreateStreamOnHGlobal(NULL, TRUE, &pStream);
448     if (hr != S_OK)
449     {
450         rot_entry_delete(rot_entry);
451         return hr;
452     }
453     mshlflags = (grfFlags & ROTFLAGS_REGISTRATIONKEEPSALIVE) ? MSHLFLAGS_TABLESTRONG : MSHLFLAGS_TABLEWEAK;
454     hr = CoMarshalInterface(pStream, &IID_IUnknown, punkObject, MSHCTX_LOCAL | MSHCTX_NOSHAREDMEM, NULL, mshlflags);
455     /* FIXME: a cleaner way would be to create an IStream class that writes
456      * directly to an MInterfacePointer */
457     if (hr == S_OK)
458     {
459         HGLOBAL hglobal;
460         hr = GetHGlobalFromStream(pStream, &hglobal);
461         if (hr == S_OK)
462         {
463             SIZE_T size = GlobalSize(hglobal);
464             const void *pv = GlobalLock(hglobal);
465             rot_entry->object = HeapAlloc(GetProcessHeap(), 0, FIELD_OFFSET(MInterfacePointer, abData[size]));
466             rot_entry->object->ulCntData = size;
467             memcpy(rot_entry->object->abData, pv, size);
468             GlobalUnlock(hglobal);
469         }
470     }
471     IStream_Release(pStream);
472     if (hr != S_OK)
473     {
474         rot_entry_delete(rot_entry);
475         return hr;
476     }
477
478     hr = CreateBindCtx(0, &pbc);
479     if (FAILED(hr))
480     {
481         rot_entry_delete(rot_entry);
482         return hr;
483     }
484
485     hr = reduce_moniker(pmkObjectName, pbc, &pmkObjectName);
486     if (FAILED(hr))
487     {
488         rot_entry_delete(rot_entry);
489         IBindCtx_Release(pbc);
490         return hr;
491     }
492
493     hr = IMoniker_GetTimeOfLastChange(pmkObjectName, pbc, NULL,
494                                       &rot_entry->last_modified);
495     IBindCtx_Release(pbc);
496     if (FAILED(hr))
497     {
498         CoFileTimeNow(&rot_entry->last_modified);
499         hr = S_OK;
500     }
501
502     hr = get_moniker_comparison_data(pmkObjectName,
503                                      &rot_entry->moniker_data);
504     if (hr != S_OK)
505     {
506         rot_entry_delete(rot_entry);
507         IMoniker_Release(pmkObjectName);
508         return hr;
509     }
510
511     hr = CreateStreamOnHGlobal(NULL, TRUE, &pStream);
512     if (hr != S_OK)
513     {
514         rot_entry_delete(rot_entry);
515         IMoniker_Release(pmkObjectName);
516         return hr;
517     }
518     /* marshal moniker */
519     hr = CoMarshalInterface(pStream, &IID_IMoniker, (IUnknown *)pmkObjectName,
520                             MSHCTX_LOCAL | MSHCTX_NOSHAREDMEM, NULL, MSHLFLAGS_TABLESTRONG);
521     /* FIXME: a cleaner way would be to create an IStream class that writes
522      * directly to an MInterfacePointer */
523     if (hr == S_OK)
524     {
525         HGLOBAL hglobal;
526         hr = GetHGlobalFromStream(pStream, &hglobal);
527         if (hr == S_OK)
528         {
529             SIZE_T size = GlobalSize(hglobal);
530             const void *pv = GlobalLock(hglobal);
531             moniker = HeapAlloc(GetProcessHeap(), 0, FIELD_OFFSET(InterfaceData, abData[size]));
532             moniker->ulCntData = size;
533             memcpy(moniker->abData, pv, size);
534             GlobalUnlock(hglobal);
535         }
536     }
537     IStream_Release(pStream);
538     IMoniker_Release(pmkObjectName);
539     if (hr != S_OK)
540     {
541         HeapFree(GetProcessHeap(), 0, moniker);
542         rot_entry_delete(rot_entry);
543         return hr;
544     }
545
546
547     while (TRUE)
548     {
549         __TRY
550         {
551             hr = IrotRegister(get_irot_handle(), rot_entry->moniker_data,
552                               rot_entry->object, moniker,
553                               &rot_entry->last_modified, grfFlags,
554                               &rot_entry->cookie, &rot_entry->ctxt_handle);
555         }
556         __EXCEPT(rpc_filter)
557         {
558             hr = HRESULT_FROM_WIN32(GetExceptionCode());
559         }
560         __ENDTRY
561         if (hr == HRESULT_FROM_WIN32(RPC_S_SERVER_UNAVAILABLE))
562         {
563             if (start_rpcss())
564                 continue;
565         }
566         break;
567     }
568     HeapFree(GetProcessHeap(), 0, moniker);
569     if (FAILED(hr))
570     {
571         rot_entry_delete(rot_entry);
572         return hr;
573     }
574
575     /* gives a registration identifier to the registered object*/
576     *pdwRegister = rot_entry->cookie;
577
578     EnterCriticalSection(&This->lock);
579     list_add_tail(&This->rot, &rot_entry->entry);
580     LeaveCriticalSection(&This->lock);
581
582     return hr;
583 }
584
585 /***********************************************************************
586  *        RunningObjectTable_Revoke
587  *
588  * PARAMS
589  *  dwRegister [in] Value identifying registration to be revoked
590  */
591 static HRESULT WINAPI
592 RunningObjectTableImpl_Revoke( IRunningObjectTable* iface, DWORD dwRegister) 
593 {
594     RunningObjectTableImpl *This = (RunningObjectTableImpl *)iface;
595     struct rot_entry *rot_entry;
596
597     TRACE("(%p,%d)\n",This,dwRegister);
598
599     EnterCriticalSection(&This->lock);
600     LIST_FOR_EACH_ENTRY(rot_entry, &This->rot, struct rot_entry, entry)
601     {
602         if (rot_entry->cookie == dwRegister)
603         {
604             list_remove(&rot_entry->entry);
605             LeaveCriticalSection(&This->lock);
606
607             rot_entry_delete(rot_entry);
608             return S_OK;
609         }
610     }
611     LeaveCriticalSection(&This->lock);
612
613     return E_INVALIDARG;
614 }
615
616 /***********************************************************************
617  *        RunningObjectTable_IsRunning
618  *
619  * PARAMS
620  *  pmkObjectName [in]  moniker of the object whose status is desired 
621  */
622 static HRESULT WINAPI
623 RunningObjectTableImpl_IsRunning( IRunningObjectTable* iface, IMoniker *pmkObjectName)
624 {
625     RunningObjectTableImpl *This = (RunningObjectTableImpl *)iface;
626     MonikerComparisonData *moniker_data;
627     HRESULT hr;
628     const struct rot_entry *rot_entry;
629
630     TRACE("(%p,%p)\n",This,pmkObjectName);
631
632     hr = reduce_moniker(pmkObjectName, NULL, &pmkObjectName);
633     if (FAILED(hr))
634         return hr;
635     hr = get_moniker_comparison_data(pmkObjectName, &moniker_data);
636     IMoniker_Release(pmkObjectName);
637     if (hr != S_OK)
638         return hr;
639
640     hr = S_FALSE;
641     EnterCriticalSection(&This->lock);
642     LIST_FOR_EACH_ENTRY(rot_entry, &This->rot, const struct rot_entry, entry)
643     {
644         if ((rot_entry->moniker_data->ulCntData == moniker_data->ulCntData) &&
645             !memcmp(moniker_data->abData, rot_entry->moniker_data->abData, moniker_data->ulCntData))
646         {
647             hr = S_OK;
648             break;
649         }
650     }
651     LeaveCriticalSection(&This->lock);
652
653     if (hr == S_FALSE)
654     {
655         while (TRUE)
656         {
657             __TRY
658             {
659                 hr = IrotIsRunning(get_irot_handle(), moniker_data);
660             }
661             __EXCEPT(rpc_filter)
662             {
663                 hr = HRESULT_FROM_WIN32(GetExceptionCode());
664             }
665             __ENDTRY
666             if (hr == HRESULT_FROM_WIN32(RPC_S_SERVER_UNAVAILABLE))
667             {
668                 if (start_rpcss())
669                     continue;
670             }
671             break;
672         }
673     }
674
675     HeapFree(GetProcessHeap(), 0, moniker_data);
676
677     return hr;
678 }
679
680 /***********************************************************************
681  *        RunningObjectTable_GetObject
682  *
683  * PARAMS
684  * pmkObjectName [in] Pointer to the moniker on the object 
685  * ppunkObject   [out] variable that receives the IUnknown interface pointer
686  */
687 static HRESULT WINAPI
688 RunningObjectTableImpl_GetObject( IRunningObjectTable* iface,
689                      IMoniker *pmkObjectName, IUnknown **ppunkObject)
690 {
691     RunningObjectTableImpl *This = (RunningObjectTableImpl *)iface;
692     MonikerComparisonData *moniker_data;
693     InterfaceData *object = NULL;
694     IrotCookie cookie;
695     HRESULT hr;
696     struct rot_entry *rot_entry;
697
698     TRACE("(%p,%p,%p)\n",This,pmkObjectName,ppunkObject);
699
700     if (ppunkObject == NULL)
701         return E_POINTER;
702
703     *ppunkObject = NULL;
704
705     hr = reduce_moniker(pmkObjectName, NULL, &pmkObjectName);
706     if (FAILED(hr))
707         return hr;
708     hr = get_moniker_comparison_data(pmkObjectName, &moniker_data);
709     IMoniker_Release(pmkObjectName);
710     if (hr != S_OK)
711         return hr;
712
713     EnterCriticalSection(&This->lock);
714     LIST_FOR_EACH_ENTRY(rot_entry, &This->rot, struct rot_entry, entry)
715     {
716         if ((rot_entry->moniker_data->ulCntData == moniker_data->ulCntData) &&
717             !memcmp(moniker_data->abData, rot_entry->moniker_data->abData, moniker_data->ulCntData))
718         {
719             IStream *pStream;
720             hr = create_stream_on_mip_ro(rot_entry->object, &pStream);
721             if (hr == S_OK)
722             {
723                 hr = CoUnmarshalInterface(pStream, &IID_IUnknown, (void **)ppunkObject);
724                 IStream_Release(pStream);
725             }
726
727             LeaveCriticalSection(&This->lock);
728             HeapFree(GetProcessHeap(), 0, moniker_data);
729
730             return hr;
731         }
732     }
733     LeaveCriticalSection(&This->lock);
734
735     TRACE("moniker unavailable locally, calling SCM\n");
736
737     while (TRUE)
738     {
739         __TRY
740         {
741             hr = IrotGetObject(get_irot_handle(), moniker_data, &object, &cookie);
742         }
743         __EXCEPT(rpc_filter)
744         {
745             hr = HRESULT_FROM_WIN32(GetExceptionCode());
746         }
747         __ENDTRY
748         if (hr == HRESULT_FROM_WIN32(RPC_S_SERVER_UNAVAILABLE))
749         {
750             if (start_rpcss())
751                 continue;
752         }
753         break;
754     }
755
756     if (SUCCEEDED(hr))
757     {
758         IStream *pStream;
759         hr = create_stream_on_mip_ro(object, &pStream);
760         if (hr == S_OK)
761         {
762             hr = CoUnmarshalInterface(pStream, &IID_IUnknown, (void **)ppunkObject);
763             IStream_Release(pStream);
764         }
765     }
766     else
767         WARN("Moniker unavailable, IrotGetObject returned 0x%08x\n", hr);
768
769     HeapFree(GetProcessHeap(), 0, moniker_data);
770
771     return hr;
772 }
773
774 /***********************************************************************
775  *        RunningObjectTable_NoteChangeTime
776  *
777  * PARAMS
778  *  dwRegister [in] Value identifying registration being updated
779  *  pfiletime  [in] Pointer to structure containing object's last change time
780  */
781 static HRESULT WINAPI
782 RunningObjectTableImpl_NoteChangeTime(IRunningObjectTable* iface,
783                                       DWORD dwRegister, FILETIME *pfiletime)
784 {
785     RunningObjectTableImpl *This = (RunningObjectTableImpl *)iface;
786     struct rot_entry *rot_entry;
787     HRESULT hr = E_INVALIDARG;
788
789     TRACE("(%p,%d,%p)\n",This,dwRegister,pfiletime);
790
791     EnterCriticalSection(&This->lock);
792     LIST_FOR_EACH_ENTRY(rot_entry, &This->rot, struct rot_entry, entry)
793     {
794         if (rot_entry->cookie == dwRegister)
795         {
796             rot_entry->last_modified = *pfiletime;
797             LeaveCriticalSection(&This->lock);
798
799             while (TRUE)
800             {
801                 __TRY
802                 {
803                     hr = IrotNoteChangeTime(get_irot_handle(), dwRegister, pfiletime);
804                 }
805                 __EXCEPT(rpc_filter)
806                 {
807                     hr = HRESULT_FROM_WIN32(GetExceptionCode());
808                 }
809                 __ENDTRY
810                 if (hr == HRESULT_FROM_WIN32(RPC_S_SERVER_UNAVAILABLE))
811                 {
812                     if (start_rpcss())
813                         continue;
814                 }
815                 break;
816             }
817
818             goto done;
819         }
820     }
821     LeaveCriticalSection(&This->lock);
822
823 done:
824     TRACE("-- 0x08%x\n", hr);
825     return hr;
826 }
827
828 /***********************************************************************
829  *        RunningObjectTable_GetTimeOfLastChange
830  *
831  * PARAMS
832  *  pmkObjectName  [in]  moniker of the object whose status is desired 
833  *  pfiletime      [out] structure that receives object's last change time
834  */
835 static HRESULT WINAPI
836 RunningObjectTableImpl_GetTimeOfLastChange(IRunningObjectTable* iface,
837                             IMoniker *pmkObjectName, FILETIME *pfiletime)
838 {
839     HRESULT hr = MK_E_UNAVAILABLE;
840     RunningObjectTableImpl *This = (RunningObjectTableImpl *)iface;
841     MonikerComparisonData *moniker_data;
842     const struct rot_entry *rot_entry;
843
844     TRACE("(%p,%p,%p)\n",This,pmkObjectName,pfiletime);
845
846     if (pmkObjectName==NULL || pfiletime==NULL)
847         return E_INVALIDARG;
848
849     hr = reduce_moniker(pmkObjectName, NULL, &pmkObjectName);
850     if (FAILED(hr))
851         return hr;
852     hr = get_moniker_comparison_data(pmkObjectName, &moniker_data);
853     IMoniker_Release(pmkObjectName);
854     if (hr != S_OK)
855         return hr;
856
857     hr = MK_E_UNAVAILABLE;
858
859     EnterCriticalSection(&This->lock);
860     LIST_FOR_EACH_ENTRY(rot_entry, &This->rot, const struct rot_entry, entry)
861     {
862         if ((rot_entry->moniker_data->ulCntData == moniker_data->ulCntData) &&
863             !memcmp(moniker_data->abData, rot_entry->moniker_data->abData, moniker_data->ulCntData))
864         {
865             *pfiletime = rot_entry->last_modified;
866             hr = S_OK;
867             break;
868         }
869     }
870     LeaveCriticalSection(&This->lock);
871
872     if (hr != S_OK)
873     {
874         while (TRUE)
875         {
876             __TRY
877             {
878                 hr = IrotGetTimeOfLastChange(get_irot_handle(), moniker_data, pfiletime);
879             }
880             __EXCEPT(rpc_filter)
881             {
882                 hr = HRESULT_FROM_WIN32(GetExceptionCode());
883             }
884             __ENDTRY
885             if (hr == HRESULT_FROM_WIN32(RPC_S_SERVER_UNAVAILABLE))
886             {
887                 if (start_rpcss())
888                     continue;
889             }
890             break;
891         }
892     }
893
894     HeapFree(GetProcessHeap(), 0, moniker_data);
895
896     TRACE("-- 0x%08x\n", hr);
897     return hr;
898 }
899
900 /***********************************************************************
901  *        RunningObjectTable_EnumRunning
902  *
903  * PARAMS
904  *  ppenumMoniker  [out]  receives the IEnumMoniker interface pointer 
905  */
906 static HRESULT WINAPI
907 RunningObjectTableImpl_EnumRunning(IRunningObjectTable* iface,
908                                    IEnumMoniker **ppenumMoniker)
909 {
910     RunningObjectTableImpl *This = (RunningObjectTableImpl *)iface;
911     InterfaceList *interface_list = NULL;
912     HRESULT hr;
913
914     TRACE("(%p, %p)\n", This, ppenumMoniker);
915
916     *ppenumMoniker = NULL;
917
918     while (TRUE)
919     {
920         __TRY
921         {
922             hr = IrotEnumRunning(get_irot_handle(), &interface_list);
923         }
924         __EXCEPT(rpc_filter)
925         {
926             hr = HRESULT_FROM_WIN32(GetExceptionCode());
927         }
928         __ENDTRY
929         if (hr == HRESULT_FROM_WIN32(RPC_S_SERVER_UNAVAILABLE))
930         {
931             if (start_rpcss())
932                 continue;
933         }
934         break;
935     }
936
937     if (SUCCEEDED(hr))
938         hr = EnumMonikerImpl_CreateEnumROTMoniker(interface_list,
939                                                   0, ppenumMoniker);
940
941     return hr;
942 }
943
944 /* Virtual function table for the IRunningObjectTable class. */
945 static const IRunningObjectTableVtbl VT_RunningObjectTableImpl =
946 {
947     RunningObjectTableImpl_QueryInterface,
948     RunningObjectTableImpl_AddRef,
949     RunningObjectTableImpl_Release,
950     RunningObjectTableImpl_Register,
951     RunningObjectTableImpl_Revoke,
952     RunningObjectTableImpl_IsRunning,
953     RunningObjectTableImpl_GetObject,
954     RunningObjectTableImpl_NoteChangeTime,
955     RunningObjectTableImpl_GetTimeOfLastChange,
956     RunningObjectTableImpl_EnumRunning
957 };
958
959 /***********************************************************************
960  *        RunningObjectTable_Initialize
961  */
962 HRESULT WINAPI RunningObjectTableImpl_Initialize(void)
963 {
964     TRACE("\n");
965
966     /* create the unique instance of the RunningObjectTableImpl structure */
967     runningObjectTableInstance = HeapAlloc(GetProcessHeap(), 0, sizeof(RunningObjectTableImpl));
968
969     if (!runningObjectTableInstance)
970         return E_OUTOFMEMORY;
971
972     /* initialize the virtual table function */
973     runningObjectTableInstance->lpVtbl = &VT_RunningObjectTableImpl;
974
975     /* the initial reference is set to "1" so that it isn't destroyed after its
976      * first use until the process is destroyed, as the running object table is
977      * a process-wide cache of a global table */
978     runningObjectTableInstance->ref = 1;
979
980     list_init(&runningObjectTableInstance->rot);
981     InitializeCriticalSection(&runningObjectTableInstance->lock);
982     DEBUG_SET_CRITSEC_NAME(&runningObjectTableInstance->lock, "RunningObjectTableImpl.lock");
983
984     return S_OK;
985 }
986
987 /***********************************************************************
988  *        RunningObjectTable_UnInitialize
989  */
990 HRESULT WINAPI RunningObjectTableImpl_UnInitialize(void)
991 {
992     TRACE("\n");
993
994     if (runningObjectTableInstance==NULL)
995         return E_POINTER;
996
997     RunningObjectTableImpl_Release((IRunningObjectTable*)runningObjectTableInstance);
998
999     RunningObjectTableImpl_Destroy();
1000
1001     return S_OK;
1002 }
1003
1004 /***********************************************************************
1005  *           GetRunningObjectTable (OLE32.@)
1006  *
1007  * Retrieves the global running object table.
1008  *
1009  * PARAMS
1010  *  reserved [I] Reserved. Set to 0.
1011  *  pprot    [O] Address that receives the pointer to the running object table.
1012  *
1013  * RETURNS
1014  *  Success: S_OK.
1015  *  Failure: Any HRESULT code.
1016  */
1017 HRESULT WINAPI
1018 GetRunningObjectTable(DWORD reserved, LPRUNNINGOBJECTTABLE *pprot)
1019 {
1020     IID riid=IID_IRunningObjectTable;
1021     HRESULT res;
1022
1023     TRACE("()\n");
1024
1025     if (reserved!=0)
1026         return E_UNEXPECTED;
1027
1028     if(runningObjectTableInstance==NULL)
1029         return CO_E_NOTINITIALIZED;
1030
1031     res = IRunningObjectTable_QueryInterface((IRunningObjectTable*)runningObjectTableInstance,&riid,(void**)pprot);
1032
1033     return res;
1034 }
1035
1036 static HRESULT get_moniker_for_progid_display_name(LPBC pbc,
1037                                                    LPCOLESTR szDisplayName,
1038                                                    LPDWORD pchEaten,
1039                                                    LPMONIKER *ppmk)
1040 {
1041     CLSID clsid;
1042     HRESULT hr;
1043     LPWSTR progid;
1044     LPCWSTR start = szDisplayName;
1045     LPCWSTR end;
1046     int len;
1047     IMoniker *class_moniker;
1048
1049     if (*start == '@')
1050         start++;
1051
1052     /* find end delimiter */
1053     for (end = start; *end; end++)
1054         if (*end == ':')
1055             break;
1056
1057     len = end - start;
1058
1059     /* must start with '@' or have a ':' somewhere and mustn't be one character
1060      * long (since that looks like an absolute path) */
1061     if (((start == szDisplayName) && (*end == '\0')) || (len <= 1))
1062         return MK_E_SYNTAX;
1063
1064     progid = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
1065     if (progid)
1066     {
1067         memcpy(progid, start, len * sizeof(WCHAR));
1068         progid[len] = '\0';
1069     }
1070     hr = CLSIDFromProgID(progid, &clsid);
1071     HeapFree(GetProcessHeap(), 0, progid);
1072     if (FAILED(hr))
1073         return MK_E_SYNTAX;
1074
1075     hr = CreateClassMoniker(&clsid, &class_moniker);
1076     if (SUCCEEDED(hr))
1077     {
1078         IParseDisplayName *pdn;
1079         hr = IMoniker_BindToObject(class_moniker, pbc, NULL,
1080                                    &IID_IParseDisplayName, (void **)&pdn);
1081         /* fallback to using IClassFactory to get IParseDisplayName -
1082          * adsldp.dll depends on this */
1083         if (FAILED(hr))
1084         {
1085             IClassFactory *pcf;
1086             hr = IMoniker_BindToObject(class_moniker, pbc, NULL,
1087                                        &IID_IClassFactory, (void **)&pcf);
1088             if (SUCCEEDED(hr))
1089             {
1090                 hr = IClassFactory_CreateInstance(pcf, NULL,
1091                                                   &IID_IParseDisplayName,
1092                                                   (void **)&pdn);
1093                 IClassFactory_Release(pcf);
1094             }
1095         }
1096         IMoniker_Release(class_moniker);
1097         if (SUCCEEDED(hr))
1098         {
1099             hr = IParseDisplayName_ParseDisplayName(pdn, pbc,
1100                                                     (LPOLESTR)szDisplayName,
1101                                                     pchEaten, ppmk);
1102             IParseDisplayName_Release(pdn);
1103         }
1104     }
1105     return hr;
1106 }
1107
1108 /******************************************************************************
1109  *              MkParseDisplayName        [OLE32.@]
1110  */
1111 HRESULT WINAPI MkParseDisplayName(LPBC pbc, LPCOLESTR szDisplayName,
1112                                 LPDWORD pchEaten, LPMONIKER *ppmk)
1113 {
1114     HRESULT hr = MK_E_SYNTAX;
1115     static const WCHAR wszClsidColon[] = {'c','l','s','i','d',':'};
1116     IMoniker *moniker;
1117     DWORD chEaten;
1118
1119     TRACE("(%p, %s, %p, %p)\n", pbc, debugstr_w(szDisplayName), pchEaten, ppmk);
1120
1121     if (!(IsValidInterface((LPUNKNOWN) pbc)))
1122         return E_INVALIDARG;
1123
1124     *pchEaten = 0;
1125     *ppmk = NULL;
1126
1127     if (!strncmpiW(szDisplayName, wszClsidColon, sizeof(wszClsidColon)/sizeof(wszClsidColon[0])))
1128     {
1129         hr = ClassMoniker_CreateFromDisplayName(pbc, szDisplayName, &chEaten, &moniker);
1130         if (FAILED(hr) && (hr != MK_E_SYNTAX))
1131             return hr;
1132     }
1133     else
1134     {
1135         hr = get_moniker_for_progid_display_name(pbc, szDisplayName, &chEaten, &moniker);
1136         if (FAILED(hr) && (hr != MK_E_SYNTAX))
1137             return hr;
1138     }
1139
1140     if (FAILED(hr))
1141     {
1142         hr = FileMoniker_CreateFromDisplayName(pbc, szDisplayName, &chEaten, &moniker);
1143         if (FAILED(hr) && (hr != MK_E_SYNTAX))
1144             return hr;
1145     }
1146
1147     if (SUCCEEDED(hr))
1148     {
1149         while (TRUE)
1150         {
1151             IMoniker *next_moniker;
1152             *pchEaten += chEaten;
1153             szDisplayName += chEaten;
1154             if (!*szDisplayName)
1155             {
1156                 *ppmk = moniker;
1157                 return S_OK;
1158             }
1159             chEaten = 0;
1160             hr = IMoniker_ParseDisplayName(moniker, pbc, NULL,
1161                                            (LPOLESTR)szDisplayName, &chEaten,
1162                                            &next_moniker);
1163             IMoniker_Release(moniker);
1164             if (FAILED(hr))
1165             {
1166                 *pchEaten = 0;
1167                 break;
1168             }
1169             moniker = next_moniker;
1170         }
1171     }
1172
1173     return hr;
1174 }
1175
1176 /***********************************************************************
1177  *        GetClassFile (OLE32.@)
1178  *
1179  * Retrieves the class ID associated with the given filename.
1180  *
1181  * PARAMS
1182  *  filePathName [I] Filename to retrieve the class ID for.
1183  *  pclsid       [O] Address that receives the class ID for the file.
1184  *
1185  * RETURNS
1186  *  Success: S_OK.
1187  *  Failure: Any HRESULT code.
1188  */
1189 HRESULT WINAPI GetClassFile(LPCOLESTR filePathName,CLSID *pclsid)
1190 {
1191     IStorage *pstg=0;
1192     HRESULT res;
1193     int nbElm, length, i;
1194     LONG sizeProgId;
1195     LPOLESTR *pathDec=0,absFile=0,progId=0;
1196     LPWSTR extension;
1197     static const WCHAR bkslashW[] = {'\\',0};
1198     static const WCHAR dotW[] = {'.',0};
1199
1200     TRACE("%s, %p\n", debugstr_w(filePathName), pclsid);
1201
1202     /* if the file contain a storage object the return the CLSID written by IStorage_SetClass method*/
1203     if((StgIsStorageFile(filePathName))==S_OK){
1204
1205         res=StgOpenStorage(filePathName,NULL,STGM_READ | STGM_SHARE_DENY_WRITE,NULL,0,&pstg);
1206
1207         if (SUCCEEDED(res))
1208             res=ReadClassStg(pstg,pclsid);
1209
1210         IStorage_Release(pstg);
1211
1212         return res;
1213     }
1214     /* If the file is not a storage object then attempt to match various bits in the file against a
1215        pattern in the registry. This case is not frequently used, so I present only the pseudocode for
1216        this case.
1217
1218      for(i=0;i<nFileTypes;i++)
1219
1220         for(i=0;j<nPatternsForType;j++){
1221
1222             PATTERN pat;
1223             HANDLE  hFile;
1224
1225             pat=ReadPatternFromRegistry(i,j);
1226             hFile=CreateFileW(filePathName,,,,,,hFile);
1227             SetFilePosition(hFile,pat.offset);
1228             ReadFile(hFile,buf,pat.size,&r,NULL);
1229             if (memcmp(buf&pat.mask,pat.pattern.pat.size)==0){
1230
1231                 *pclsid=ReadCLSIDFromRegistry(i);
1232                 return S_OK;
1233             }
1234         }
1235      */
1236
1237     /* if the above strategies fail then search for the extension key in the registry */
1238
1239     /* get the last element (absolute file) in the path name */
1240     nbElm=FileMonikerImpl_DecomposePath(filePathName,&pathDec);
1241     absFile=pathDec[nbElm-1];
1242
1243     /* failed if the path represents a directory and not an absolute file name*/
1244     if (!lstrcmpW(absFile, bkslashW))
1245         return MK_E_INVALIDEXTENSION;
1246
1247     /* get the extension of the file */
1248     extension = NULL;
1249     length=lstrlenW(absFile);
1250     for(i = length-1; (i >= 0) && *(extension = &absFile[i]) != '.'; i--)
1251         /* nothing */;
1252
1253     if (!extension || !lstrcmpW(extension, dotW))
1254         return MK_E_INVALIDEXTENSION;
1255
1256     res=RegQueryValueW(HKEY_CLASSES_ROOT, extension, NULL, &sizeProgId);
1257
1258     /* get the progId associated to the extension */
1259     progId = CoTaskMemAlloc(sizeProgId);
1260     res = RegQueryValueW(HKEY_CLASSES_ROOT, extension, progId, &sizeProgId);
1261
1262     if (res==ERROR_SUCCESS)
1263         /* return the clsid associated to the progId */
1264         res= CLSIDFromProgID(progId,pclsid);
1265
1266     for(i=0; pathDec[i]!=NULL;i++)
1267         CoTaskMemFree(pathDec[i]);
1268     CoTaskMemFree(pathDec);
1269
1270     CoTaskMemFree(progId);
1271
1272     if (res==ERROR_SUCCESS)
1273         return res;
1274
1275     return MK_E_INVALIDEXTENSION;
1276 }
1277
1278 /***********************************************************************
1279  *        EnumMoniker_QueryInterface
1280  */
1281 static HRESULT WINAPI EnumMonikerImpl_QueryInterface(IEnumMoniker* iface,REFIID riid,void** ppvObject)
1282 {
1283     EnumMonikerImpl *This = (EnumMonikerImpl *)iface;
1284
1285     TRACE("(%p,%p,%p)\n",This,riid,ppvObject);
1286
1287     /* validate arguments */
1288     if (ppvObject == NULL)
1289         return E_INVALIDARG;
1290
1291     *ppvObject = NULL;
1292
1293     if (IsEqualIID(&IID_IUnknown, riid))
1294         *ppvObject = This;
1295     else
1296         if (IsEqualIID(&IID_IEnumMoniker, riid))
1297             *ppvObject = This;
1298
1299     if ((*ppvObject)==NULL)
1300         return E_NOINTERFACE;
1301
1302     IEnumMoniker_AddRef(iface);
1303
1304     return S_OK;
1305 }
1306
1307 /***********************************************************************
1308  *        EnumMoniker_AddRef
1309  */
1310 static ULONG   WINAPI EnumMonikerImpl_AddRef(IEnumMoniker* iface)
1311 {
1312     EnumMonikerImpl *This = (EnumMonikerImpl *)iface;
1313
1314     TRACE("(%p)\n",This);
1315
1316     return InterlockedIncrement(&This->ref);
1317 }
1318
1319 /***********************************************************************
1320  *        EnumMoniker_release
1321  */
1322 static ULONG   WINAPI EnumMonikerImpl_Release(IEnumMoniker* iface)
1323 {
1324     EnumMonikerImpl *This = (EnumMonikerImpl *)iface;
1325     ULONG ref;
1326
1327     TRACE("(%p)\n",This);
1328
1329     ref = InterlockedDecrement(&This->ref);
1330
1331     /* uninitialize rot structure if there's no more reference to it*/
1332     if (ref == 0)
1333     {
1334         ULONG i;
1335
1336         TRACE("(%p) Deleting\n",This);
1337
1338         for (i = 0; i < This->moniker_list->size; i++)
1339             HeapFree(GetProcessHeap(), 0, This->moniker_list->interfaces[i]);
1340         HeapFree(GetProcessHeap(), 0, This->moniker_list);
1341         HeapFree(GetProcessHeap(), 0, This);
1342     }
1343
1344     return ref;
1345 }
1346 /***********************************************************************
1347  *        EnumMoniker_Next
1348  */
1349 static HRESULT   WINAPI EnumMonikerImpl_Next(IEnumMoniker* iface, ULONG celt, IMoniker** rgelt, ULONG * pceltFetched)
1350 {
1351     ULONG i;
1352     EnumMonikerImpl *This = (EnumMonikerImpl *)iface;
1353     HRESULT hr = S_OK;
1354
1355     TRACE("(%p) TabCurrentPos %d Tablastindx %d\n", This, This->pos, This->moniker_list->size);
1356
1357     /* retrieve the requested number of moniker from the current position */
1358     for(i = 0; (This->pos < This->moniker_list->size) && (i < celt); i++)
1359     {
1360         IStream *stream;
1361         hr = create_stream_on_mip_ro(This->moniker_list->interfaces[This->pos++], &stream);
1362         if (hr != S_OK) break;
1363         hr = CoUnmarshalInterface(stream, &IID_IMoniker, (void **)&rgelt[i]);
1364         IStream_Release(stream);
1365         if (hr != S_OK) break;
1366     }
1367
1368     if (pceltFetched != NULL)
1369         *pceltFetched= i;
1370
1371     if (hr != S_OK)
1372         return hr;
1373
1374     if (i == celt)
1375         return S_OK;
1376     else
1377         return S_FALSE;
1378
1379 }
1380
1381 /***********************************************************************
1382  *        EnumMoniker_Skip
1383  */
1384 static HRESULT   WINAPI EnumMonikerImpl_Skip(IEnumMoniker* iface, ULONG celt)
1385 {
1386     EnumMonikerImpl *This = (EnumMonikerImpl *)iface;
1387
1388     TRACE("(%p)\n",This);
1389
1390     if  (This->pos + celt >= This->moniker_list->size)
1391         return S_FALSE;
1392
1393     This->pos += celt;
1394
1395     return S_OK;
1396 }
1397
1398 /***********************************************************************
1399  *        EnumMoniker_Reset
1400  */
1401 static HRESULT   WINAPI EnumMonikerImpl_Reset(IEnumMoniker* iface)
1402 {
1403     EnumMonikerImpl *This = (EnumMonikerImpl *)iface;
1404
1405     This->pos = 0;      /* set back to start of list */
1406
1407     TRACE("(%p)\n",This);
1408
1409     return S_OK;
1410 }
1411
1412 /***********************************************************************
1413  *        EnumMoniker_Clone
1414  */
1415 static HRESULT   WINAPI EnumMonikerImpl_Clone(IEnumMoniker* iface, IEnumMoniker ** ppenum)
1416 {
1417     EnumMonikerImpl *This = (EnumMonikerImpl *)iface;
1418     InterfaceList *moniker_list;
1419     ULONG i;
1420
1421     TRACE("(%p)\n",This);
1422
1423     *ppenum = NULL;
1424
1425     moniker_list = HeapAlloc(GetProcessHeap(), 0, FIELD_OFFSET(InterfaceList, interfaces[This->moniker_list->size]));
1426     if (!moniker_list)
1427         return E_OUTOFMEMORY;
1428
1429     moniker_list->size = This->moniker_list->size;
1430     for (i = 0; i < This->moniker_list->size; i++)
1431     {
1432         SIZE_T size = FIELD_OFFSET(InterfaceData, abData[This->moniker_list->interfaces[i]->ulCntData]);
1433         moniker_list->interfaces[i] = HeapAlloc(GetProcessHeap(), 0, size);
1434         if (!moniker_list->interfaces[i])
1435         {
1436             ULONG end = i;
1437             for (i = 0; i < end; i++)
1438                 HeapFree(GetProcessHeap(), 0, moniker_list->interfaces[i]);
1439             HeapFree(GetProcessHeap(), 0, moniker_list);
1440             return E_OUTOFMEMORY;
1441         }
1442         memcpy(moniker_list->interfaces[i], This->moniker_list->interfaces[i], size);
1443     }
1444
1445     /* copy the enum structure */ 
1446     return EnumMonikerImpl_CreateEnumROTMoniker(moniker_list, This->pos, ppenum);
1447 }
1448
1449 /* Virtual function table for the IEnumMoniker class. */
1450 static const IEnumMonikerVtbl VT_EnumMonikerImpl =
1451 {
1452     EnumMonikerImpl_QueryInterface,
1453     EnumMonikerImpl_AddRef,
1454     EnumMonikerImpl_Release,
1455     EnumMonikerImpl_Next,
1456     EnumMonikerImpl_Skip,
1457     EnumMonikerImpl_Reset,
1458     EnumMonikerImpl_Clone
1459 };
1460
1461 /***********************************************************************
1462  *        EnumMonikerImpl_CreateEnumROTMoniker
1463  *        Used by EnumRunning to create the structure and EnumClone
1464  *        to copy the structure
1465  */
1466 static HRESULT EnumMonikerImpl_CreateEnumROTMoniker(InterfaceList *moniker_list,
1467                                                  ULONG current_pos,
1468                                                  IEnumMoniker **ppenumMoniker)
1469 {
1470     EnumMonikerImpl* This = NULL;
1471
1472     if (!ppenumMoniker)
1473         return E_INVALIDARG;
1474
1475     This = HeapAlloc(GetProcessHeap(), 0, sizeof(EnumMonikerImpl));
1476     if (!This) return E_OUTOFMEMORY;
1477
1478     TRACE("(%p)\n", This);
1479
1480     /* initialize the virtual table function */
1481     This->lpVtbl = &VT_EnumMonikerImpl;
1482
1483     /* the initial reference is set to "1" */
1484     This->ref = 1;                      /* set the ref count to one         */
1485     This->pos = current_pos;            /* Set the list start posn */
1486     This->moniker_list = moniker_list;
1487
1488     *ppenumMoniker =  (IEnumMoniker*)This;
1489
1490     return S_OK;
1491 }
1492
1493
1494 /* Shared implementation of moniker marshaler based on saving and loading of
1495  * monikers */
1496
1497 typedef struct MonikerMarshal
1498 {
1499     const IUnknownVtbl *lpVtbl;
1500     const IMarshalVtbl *lpVtblMarshal;
1501     
1502     LONG ref;
1503     IMoniker *moniker;
1504 } MonikerMarshal;
1505
1506 static inline MonikerMarshal *impl_from_IMarshal( IMarshal *iface )
1507 {
1508     return (MonikerMarshal *)((char*)iface - FIELD_OFFSET(MonikerMarshal, lpVtblMarshal));
1509 }
1510
1511 static HRESULT WINAPI MonikerMarshalInner_QueryInterface(IUnknown *iface, REFIID riid, LPVOID *ppv)
1512 {
1513     MonikerMarshal *This = (MonikerMarshal *)iface;
1514     TRACE("(%s, %p)\n", debugstr_guid(riid), ppv);
1515     *ppv = NULL;
1516     if (IsEqualIID(&IID_IUnknown, riid) || IsEqualIID(&IID_IMarshal, riid))
1517     {
1518         *ppv = &This->lpVtblMarshal;
1519         IUnknown_AddRef((IUnknown *)&This->lpVtblMarshal);
1520         return S_OK;
1521     }
1522     FIXME("No interface for %s\n", debugstr_guid(riid));
1523     return E_NOINTERFACE;
1524 }
1525
1526 static ULONG WINAPI MonikerMarshalInner_AddRef(IUnknown *iface)
1527 {
1528     MonikerMarshal *This = (MonikerMarshal *)iface;
1529     return InterlockedIncrement(&This->ref);
1530 }
1531
1532 static ULONG WINAPI MonikerMarshalInner_Release(IUnknown *iface)
1533 {
1534     MonikerMarshal *This = (MonikerMarshal *)iface;
1535     ULONG ref = InterlockedDecrement(&This->ref);
1536
1537     if (!ref) HeapFree(GetProcessHeap(), 0, This);
1538     return ref;
1539 }
1540
1541 static const IUnknownVtbl VT_MonikerMarshalInner =
1542 {
1543     MonikerMarshalInner_QueryInterface,
1544     MonikerMarshalInner_AddRef,
1545     MonikerMarshalInner_Release
1546 };
1547
1548 static HRESULT WINAPI MonikerMarshal_QueryInterface(IMarshal *iface, REFIID riid, LPVOID *ppv)
1549 {
1550     MonikerMarshal *This = impl_from_IMarshal(iface);
1551     return IMoniker_QueryInterface(This->moniker, riid, ppv);
1552 }
1553
1554 static ULONG WINAPI MonikerMarshal_AddRef(IMarshal *iface)
1555 {
1556     MonikerMarshal *This = impl_from_IMarshal(iface);
1557     return IMoniker_AddRef(This->moniker);
1558 }
1559
1560 static ULONG WINAPI MonikerMarshal_Release(IMarshal *iface)
1561 {
1562     MonikerMarshal *This = impl_from_IMarshal(iface);
1563     return IMoniker_Release(This->moniker);
1564 }
1565
1566 static HRESULT WINAPI MonikerMarshal_GetUnmarshalClass(
1567   LPMARSHAL iface, REFIID riid, void* pv, DWORD dwDestContext,
1568   void* pvDestContext, DWORD mshlflags, CLSID* pCid)
1569 {
1570     MonikerMarshal *This = impl_from_IMarshal(iface);
1571
1572     TRACE("(%s, %p, %x, %p, %x, %p)\n", debugstr_guid(riid), pv,
1573         dwDestContext, pvDestContext, mshlflags, pCid);
1574
1575     return IMoniker_GetClassID(This->moniker, pCid);
1576 }
1577
1578 static HRESULT WINAPI MonikerMarshal_GetMarshalSizeMax(
1579   LPMARSHAL iface, REFIID riid, void* pv, DWORD dwDestContext,
1580   void* pvDestContext, DWORD mshlflags, DWORD* pSize)
1581 {
1582     MonikerMarshal *This = impl_from_IMarshal(iface);
1583     HRESULT hr;
1584     ULARGE_INTEGER size;
1585
1586     TRACE("(%s, %p, %x, %p, %x, %p)\n", debugstr_guid(riid), pv,
1587         dwDestContext, pvDestContext, mshlflags, pSize);
1588
1589     hr = IMoniker_GetSizeMax(This->moniker, &size);
1590     if (hr == S_OK)
1591         *pSize = (DWORD)size.QuadPart;
1592     return hr;
1593 }
1594
1595 static HRESULT WINAPI MonikerMarshal_MarshalInterface(LPMARSHAL iface, IStream *pStm, 
1596     REFIID riid, void* pv, DWORD dwDestContext,
1597     void* pvDestContext, DWORD mshlflags)
1598 {
1599     MonikerMarshal *This = impl_from_IMarshal(iface);
1600
1601     TRACE("(%p, %s, %p, %x, %p, %x)\n", pStm, debugstr_guid(riid), pv,
1602         dwDestContext, pvDestContext, mshlflags);
1603
1604     return IMoniker_Save(This->moniker, pStm, FALSE);
1605 }
1606
1607 static HRESULT WINAPI MonikerMarshal_UnmarshalInterface(LPMARSHAL iface, IStream *pStm, REFIID riid, void **ppv)
1608 {
1609     MonikerMarshal *This = impl_from_IMarshal(iface);
1610     HRESULT hr;
1611
1612     TRACE("(%p, %s, %p)\n", pStm, debugstr_guid(riid), ppv);
1613
1614     hr = IMoniker_Load(This->moniker, pStm);
1615     if (hr == S_OK)
1616         hr = IMoniker_QueryInterface(This->moniker, riid, ppv);
1617     return hr;
1618 }
1619
1620 static HRESULT WINAPI MonikerMarshal_ReleaseMarshalData(LPMARSHAL iface, IStream *pStm)
1621 {
1622     TRACE("()\n");
1623     /* can't release a state-based marshal as nothing on server side to
1624      * release */
1625     return S_OK;
1626 }
1627
1628 static HRESULT WINAPI MonikerMarshal_DisconnectObject(LPMARSHAL iface, DWORD dwReserved)
1629 {
1630     TRACE("()\n");
1631     /* can't disconnect a state-based marshal as nothing on server side to
1632      * disconnect from */
1633     return S_OK;
1634 }
1635
1636 static const IMarshalVtbl VT_MonikerMarshal =
1637 {
1638     MonikerMarshal_QueryInterface,
1639     MonikerMarshal_AddRef,
1640     MonikerMarshal_Release,
1641     MonikerMarshal_GetUnmarshalClass,
1642     MonikerMarshal_GetMarshalSizeMax,
1643     MonikerMarshal_MarshalInterface,
1644     MonikerMarshal_UnmarshalInterface,
1645     MonikerMarshal_ReleaseMarshalData,
1646     MonikerMarshal_DisconnectObject
1647 };
1648
1649 HRESULT MonikerMarshal_Create(IMoniker *inner, IUnknown **outer)
1650 {
1651     MonikerMarshal *This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
1652     if (!This) return E_OUTOFMEMORY;
1653
1654     This->lpVtbl = &VT_MonikerMarshalInner;
1655     This->lpVtblMarshal = &VT_MonikerMarshal;
1656     This->ref = 1;
1657     This->moniker = inner;
1658
1659     *outer = (IUnknown *)&This->lpVtbl;
1660     return S_OK;
1661 }
1662
1663 void * __RPC_USER MIDL_user_allocate(SIZE_T size)
1664 {
1665     return HeapAlloc(GetProcessHeap(), 0, size);
1666 }
1667
1668 void __RPC_USER MIDL_user_free(void *p)
1669 {
1670     HeapFree(GetProcessHeap(), 0, p);
1671 }