oleaut32: Fix a stream leak on failure.
[wine] / dlls / oleaut32 / tmarshal.c
1 /*
2  *      TYPELIB Marshaler
3  *
4  *      Copyright 2002,2005     Marcus Meissner
5  *
6  * The olerelay debug channel allows you to see calls marshalled by
7  * the typelib marshaller. It is not a generic COM relaying system.
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 <assert.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <stdarg.h>
31 #include <stdio.h>
32 #include <ctype.h>
33
34 #define COBJMACROS
35 #define NONAMELESSUNION
36 #define NONAMELESSSTRUCT
37
38 #include "winerror.h"
39 #include "windef.h"
40 #include "winbase.h"
41 #include "winnls.h"
42 #include "winreg.h"
43 #include "winuser.h"
44
45 #include "ole2.h"
46 #include "propidl.h" /* for LPSAFEARRAY_User* functions */
47 #include "typelib.h"
48 #include "variant.h"
49 #include "wine/debug.h"
50 #include "wine/exception.h"
51
52 static const WCHAR IDispatchW[] = { 'I','D','i','s','p','a','t','c','h',0};
53
54 WINE_DEFAULT_DEBUG_CHANNEL(ole);
55 WINE_DECLARE_DEBUG_CHANNEL(olerelay);
56
57 static HRESULT TMarshalDispatchChannel_Create(
58     IRpcChannelBuffer *pDelegateChannel, REFIID tmarshal_riid,
59     IRpcChannelBuffer **ppChannel);
60
61 typedef struct _marshal_state {
62     LPBYTE      base;
63     int         size;
64     int         curoff;
65 } marshal_state;
66
67 /* used in the olerelay code to avoid having the L"" stuff added by debugstr_w */
68 static char *relaystr(WCHAR *in) {
69     char *tmp = (char *)debugstr_w(in);
70     tmp += 2;
71     tmp[strlen(tmp)-1] = '\0';
72     return tmp;
73 }
74
75 static HRESULT
76 xbuf_resize(marshal_state *buf, DWORD newsize)
77 {
78     if(buf->size >= newsize)
79         return S_FALSE;
80
81     if(buf->base)
82     {
83         buf->base = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, buf->base, newsize);
84         if(!buf->base)
85             return E_OUTOFMEMORY;
86     }
87     else
88     {
89         buf->base = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, newsize);
90         if(!buf->base)
91             return E_OUTOFMEMORY;
92     }
93     buf->size = newsize;
94     return S_OK;
95 }
96
97 static HRESULT
98 xbuf_add(marshal_state *buf, const BYTE *stuff, DWORD size)
99 {
100     HRESULT hr;
101
102     if(buf->size - buf->curoff < size)
103     {
104         hr = xbuf_resize(buf, buf->size + size + 100);
105         if(FAILED(hr)) return hr;
106     }
107     memcpy(buf->base+buf->curoff,stuff,size);
108     buf->curoff += size;
109     return S_OK;
110 }
111
112 static HRESULT
113 xbuf_get(marshal_state *buf, LPBYTE stuff, DWORD size) {
114     if (buf->size < buf->curoff+size) return E_FAIL;
115     memcpy(stuff,buf->base+buf->curoff,size);
116     buf->curoff += size;
117     return S_OK;
118 }
119
120 static HRESULT
121 xbuf_skip(marshal_state *buf, DWORD size) {
122     if (buf->size < buf->curoff+size) return E_FAIL;
123     buf->curoff += size;
124     return S_OK;
125 }
126
127 static HRESULT
128 _unmarshal_interface(marshal_state *buf, REFIID riid, LPUNKNOWN *pUnk) {
129     IStream             *pStm;
130     ULARGE_INTEGER      newpos;
131     LARGE_INTEGER       seekto;
132     ULONG               res;
133     HRESULT             hres;
134     DWORD               xsize;
135
136     TRACE("...%s...\n",debugstr_guid(riid));
137     
138     *pUnk = NULL;
139     hres = xbuf_get(buf,(LPBYTE)&xsize,sizeof(xsize));
140     if (hres) {
141         ERR("xbuf_get failed\n");
142         return hres;
143     }
144     
145     if (xsize == 0) return S_OK;
146     
147     hres = CreateStreamOnHGlobal(0,TRUE,&pStm);
148     if (hres) {
149         ERR("Stream create failed %x\n",hres);
150         return hres;
151     }
152     
153     hres = IStream_Write(pStm,buf->base+buf->curoff,xsize,&res);
154     if (hres) {
155         ERR("stream write %x\n",hres);
156         IStream_Release(pStm);
157         return hres;
158     }
159     
160     memset(&seekto,0,sizeof(seekto));
161     hres = IStream_Seek(pStm,seekto,SEEK_SET,&newpos);
162     if (hres) {
163         ERR("Failed Seek %x\n",hres);
164         IStream_Release(pStm);
165         return hres;
166     }
167     
168     hres = CoUnmarshalInterface(pStm,riid,(LPVOID*)pUnk);
169     if (hres) {
170         ERR("Unmarshalling interface %s failed with %x\n",debugstr_guid(riid),hres);
171         IStream_Release(pStm);
172         return hres;
173     }
174     
175     IStream_Release(pStm);
176     return xbuf_skip(buf,xsize);
177 }
178
179 static HRESULT
180 _marshal_interface(marshal_state *buf, REFIID riid, LPUNKNOWN pUnk) {
181     LPBYTE              tempbuf = NULL;
182     IStream             *pStm = NULL;
183     STATSTG             ststg;
184     ULARGE_INTEGER      newpos;
185     LARGE_INTEGER       seekto;
186     ULONG               res;
187     DWORD               xsize;
188     HRESULT             hres;
189
190     if (!pUnk) {
191         /* this is valid, if for instance we serialize
192          * a VT_DISPATCH with NULL ptr which apparently
193          * can happen. S_OK to make sure we continue
194          * serializing.
195          */
196         WARN("pUnk is NULL\n");
197         xsize = 0;
198         return xbuf_add(buf,(LPBYTE)&xsize,sizeof(xsize));
199     }
200
201     hres = E_FAIL;
202
203     TRACE("...%s...\n",debugstr_guid(riid));
204     
205     hres = CreateStreamOnHGlobal(0,TRUE,&pStm);
206     if (hres) {
207         ERR("Stream create failed %x\n",hres);
208         goto fail;
209     }
210     
211     hres = CoMarshalInterface(pStm,riid,pUnk,0,NULL,0);
212     if (hres) {
213         ERR("Marshalling interface %s failed with %x\n", debugstr_guid(riid), hres);
214         goto fail;
215     }
216     
217     hres = IStream_Stat(pStm,&ststg,STATFLAG_NONAME);
218     if (hres) {
219         ERR("Stream stat failed\n");
220         goto fail;
221     }
222     
223     tempbuf = HeapAlloc(GetProcessHeap(), 0, ststg.cbSize.u.LowPart);
224     memset(&seekto,0,sizeof(seekto));
225     hres = IStream_Seek(pStm,seekto,SEEK_SET,&newpos);
226     if (hres) {
227         ERR("Failed Seek %x\n",hres);
228         goto fail;
229     }
230     
231     hres = IStream_Read(pStm,tempbuf,ststg.cbSize.u.LowPart,&res);
232     if (hres) {
233         ERR("Failed Read %x\n",hres);
234         goto fail;
235     }
236     
237     xsize = ststg.cbSize.u.LowPart;
238     xbuf_add(buf,(LPBYTE)&xsize,sizeof(xsize));
239     hres = xbuf_add(buf,tempbuf,ststg.cbSize.u.LowPart);
240     
241     HeapFree(GetProcessHeap(),0,tempbuf);
242     IStream_Release(pStm);
243     
244     return hres;
245     
246 fail:
247     xsize = 0;
248     xbuf_add(buf,(LPBYTE)&xsize,sizeof(xsize));
249     if (pStm) IUnknown_Release(pStm);
250     HeapFree(GetProcessHeap(), 0, tempbuf);
251     return hres;
252 }
253
254 /********************* OLE Proxy/Stub Factory ********************************/
255 static HRESULT WINAPI
256 PSFacBuf_QueryInterface(LPPSFACTORYBUFFER iface, REFIID iid, LPVOID *ppv) {
257     if (IsEqualIID(iid,&IID_IPSFactoryBuffer)||IsEqualIID(iid,&IID_IUnknown)) {
258         *ppv = iface;
259         /* No ref counting, static class */
260         return S_OK;
261     }
262     FIXME("(%s) unknown IID?\n",debugstr_guid(iid));
263     return E_NOINTERFACE;
264 }
265
266 static ULONG WINAPI PSFacBuf_AddRef(LPPSFACTORYBUFFER iface) { return 2; }
267 static ULONG WINAPI PSFacBuf_Release(LPPSFACTORYBUFFER iface) { return 1; }
268
269 static HRESULT
270 _get_typeinfo_for_iid(REFIID riid, ITypeInfo**ti) {
271     HRESULT     hres;
272     HKEY        ikey;
273     char        tlguid[200],typelibkey[300],interfacekey[300],ver[100];
274     char        tlfn[260];
275     OLECHAR     tlfnW[260];
276     DWORD       tlguidlen, verlen, type;
277     LONG        tlfnlen;
278     ITypeLib    *tl;
279
280     sprintf( interfacekey, "Interface\\{%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}\\Typelib",
281         riid->Data1, riid->Data2, riid->Data3,
282         riid->Data4[0], riid->Data4[1], riid->Data4[2], riid->Data4[3],
283         riid->Data4[4], riid->Data4[5], riid->Data4[6], riid->Data4[7]
284     );
285
286     if (RegOpenKeyA(HKEY_CLASSES_ROOT,interfacekey,&ikey)) {
287         ERR("No %s key found.\n",interfacekey);
288         return E_FAIL;
289     }
290     tlguidlen = sizeof(tlguid);
291     if (RegQueryValueExA(ikey,NULL,NULL,&type,(LPBYTE)tlguid,&tlguidlen)) {
292         ERR("Getting typelib guid failed.\n");
293         RegCloseKey(ikey);
294         return E_FAIL;
295     }
296     verlen = sizeof(ver);
297     if (RegQueryValueExA(ikey,"Version",NULL,&type,(LPBYTE)ver,&verlen)) {
298         ERR("Could not get version value?\n");
299         RegCloseKey(ikey);
300         return E_FAIL;
301     }
302     RegCloseKey(ikey);
303     sprintf(typelibkey,"Typelib\\%s\\%s\\0\\win%u",tlguid,ver,(sizeof(void*) == 8) ? 64 : 32);
304     tlfnlen = sizeof(tlfn);
305     if (RegQueryValueA(HKEY_CLASSES_ROOT,typelibkey,tlfn,&tlfnlen)) {
306         ERR("Could not get typelib fn?\n");
307         return E_FAIL;
308     }
309     MultiByteToWideChar(CP_ACP, 0, tlfn, -1, tlfnW, sizeof(tlfnW) / sizeof(tlfnW[0]));
310     hres = LoadTypeLib(tlfnW,&tl);
311     if (hres) {
312         ERR("Failed to load typelib for %s, but it should be there.\n",debugstr_guid(riid));
313         return hres;
314     }
315     hres = ITypeLib_GetTypeInfoOfGuid(tl,riid,ti);
316     if (hres) {
317         ERR("typelib does not contain info for %s?\n",debugstr_guid(riid));
318         ITypeLib_Release(tl);
319         return hres;
320     }
321     ITypeLib_Release(tl);
322     return hres;
323 }
324
325 /*
326  * Determine the number of functions including all inherited functions.
327  * Note for non-dual dispinterfaces we simply return the size of IDispatch.
328  */
329 static HRESULT num_of_funcs(ITypeInfo *tinfo, unsigned int *num)
330 {
331     HRESULT hres;
332     TYPEATTR *attr;
333     ITypeInfo *tinfo2;
334
335     *num = 0;
336     hres = ITypeInfo_GetTypeAttr(tinfo, &attr);
337     if (hres) {
338         ERR("GetTypeAttr failed with %x\n",hres);
339         return hres;
340     }
341
342     if(attr->typekind == TKIND_DISPATCH && (attr->wTypeFlags & TYPEFLAG_FDUAL))
343     {
344         HREFTYPE href;
345         hres = ITypeInfo_GetRefTypeOfImplType(tinfo, -1, &href);
346         if(FAILED(hres))
347         {
348             ERR("Unable to get interface href from dual dispinterface\n");
349             goto end;
350         }
351         hres = ITypeInfo_GetRefTypeInfo(tinfo, href, &tinfo2);
352         if(FAILED(hres))
353         {
354             ERR("Unable to get interface from dual dispinterface\n");
355             goto end;
356         }
357         hres = num_of_funcs(tinfo2, num);
358         ITypeInfo_Release(tinfo2);
359     }
360     else
361     {
362         *num = attr->cbSizeVft / 4;
363     }
364
365  end:
366     ITypeInfo_ReleaseTypeAttr(tinfo, attr);
367     return hres;
368 }
369
370 #ifdef __i386__
371
372 #include "pshpack1.h"
373
374 typedef struct _TMAsmProxy {
375     BYTE        popleax;
376     BYTE        pushlval;
377     DWORD       nr;
378     BYTE        pushleax;
379     BYTE        lcall;
380     DWORD       xcall;
381     BYTE        lret;
382     WORD        bytestopop;
383     BYTE        nop;
384 } TMAsmProxy;
385
386 #include "poppack.h"
387
388 #else /* __i386__ */
389 # warning You need to implement stubless proxies for your architecture
390 typedef struct _TMAsmProxy {
391 } TMAsmProxy;
392 #endif
393
394 typedef struct _TMProxyImpl {
395     LPVOID                             *lpvtbl;
396     IRpcProxyBuffer                     IRpcProxyBuffer_iface;
397     LONG                                ref;
398
399     TMAsmProxy                          *asmstubs;
400     ITypeInfo*                          tinfo;
401     IRpcChannelBuffer*                  chanbuf;
402     IID                                 iid;
403     CRITICAL_SECTION    crit;
404     IUnknown                            *outerunknown;
405     IDispatch                           *dispatch;
406     IRpcProxyBuffer                     *dispatch_proxy;
407 } TMProxyImpl;
408
409 static inline TMProxyImpl *impl_from_IRpcProxyBuffer( IRpcProxyBuffer *iface )
410 {
411     return CONTAINING_RECORD(iface, TMProxyImpl, IRpcProxyBuffer_iface);
412 }
413
414 static HRESULT WINAPI
415 TMProxyImpl_QueryInterface(LPRPCPROXYBUFFER iface, REFIID riid, LPVOID *ppv)
416 {
417     TRACE("()\n");
418     if (IsEqualIID(riid,&IID_IUnknown)||IsEqualIID(riid,&IID_IRpcProxyBuffer)) {
419         *ppv = iface;
420         IRpcProxyBuffer_AddRef(iface);
421         return S_OK;
422     }
423     FIXME("no interface for %s\n",debugstr_guid(riid));
424     return E_NOINTERFACE;
425 }
426
427 static ULONG WINAPI
428 TMProxyImpl_AddRef(LPRPCPROXYBUFFER iface)
429 {
430     TMProxyImpl *This = impl_from_IRpcProxyBuffer( iface );
431     ULONG refCount = InterlockedIncrement(&This->ref);
432
433     TRACE("(%p)->(ref before=%u)\n",This, refCount - 1);
434
435     return refCount;
436 }
437
438 static ULONG WINAPI
439 TMProxyImpl_Release(LPRPCPROXYBUFFER iface)
440 {
441     TMProxyImpl *This = impl_from_IRpcProxyBuffer( iface );
442     ULONG refCount = InterlockedDecrement(&This->ref);
443
444     TRACE("(%p)->(ref before=%u)\n",This, refCount + 1);
445
446     if (!refCount)
447     {
448         if (This->dispatch_proxy) IRpcProxyBuffer_Release(This->dispatch_proxy);
449         This->crit.DebugInfo->Spare[0] = 0;
450         DeleteCriticalSection(&This->crit);
451         if (This->chanbuf) IRpcChannelBuffer_Release(This->chanbuf);
452         VirtualFree(This->asmstubs, 0, MEM_RELEASE);
453         HeapFree(GetProcessHeap(), 0, This->lpvtbl);
454         ITypeInfo_Release(This->tinfo);
455         CoTaskMemFree(This);
456     }
457     return refCount;
458 }
459
460 static HRESULT WINAPI
461 TMProxyImpl_Connect(
462     LPRPCPROXYBUFFER iface,IRpcChannelBuffer* pRpcChannelBuffer)
463 {
464     TMProxyImpl *This = impl_from_IRpcProxyBuffer( iface );
465
466     TRACE("(%p)\n", pRpcChannelBuffer);
467
468     EnterCriticalSection(&This->crit);
469
470     IRpcChannelBuffer_AddRef(pRpcChannelBuffer);
471     This->chanbuf = pRpcChannelBuffer;
472
473     LeaveCriticalSection(&This->crit);
474
475     if (This->dispatch_proxy)
476     {
477         IRpcChannelBuffer *pDelegateChannel;
478         HRESULT hr = TMarshalDispatchChannel_Create(pRpcChannelBuffer, &This->iid, &pDelegateChannel);
479         if (FAILED(hr))
480             return hr;
481         hr = IRpcProxyBuffer_Connect(This->dispatch_proxy, pDelegateChannel);
482         IRpcChannelBuffer_Release(pDelegateChannel);
483         return hr;
484     }
485
486     return S_OK;
487 }
488
489 static void WINAPI
490 TMProxyImpl_Disconnect(LPRPCPROXYBUFFER iface)
491 {
492     TMProxyImpl *This = impl_from_IRpcProxyBuffer( iface );
493
494     TRACE("()\n");
495
496     EnterCriticalSection(&This->crit);
497
498     IRpcChannelBuffer_Release(This->chanbuf);
499     This->chanbuf = NULL;
500
501     LeaveCriticalSection(&This->crit);
502
503     if (This->dispatch_proxy)
504         IRpcProxyBuffer_Disconnect(This->dispatch_proxy);
505 }
506
507
508 static const IRpcProxyBufferVtbl tmproxyvtable = {
509     TMProxyImpl_QueryInterface,
510     TMProxyImpl_AddRef,
511     TMProxyImpl_Release,
512     TMProxyImpl_Connect,
513     TMProxyImpl_Disconnect
514 };
515
516 /* how much space do we use on stack in DWORD steps. */
517 static int
518 _argsize(TYPEDESC *tdesc, ITypeInfo *tinfo) {
519     switch (tdesc->vt) {
520     case VT_I8:
521     case VT_UI8:
522         return 8/sizeof(DWORD);
523     case VT_R8:
524         return sizeof(double)/sizeof(DWORD);
525     case VT_CY:
526         return sizeof(CY)/sizeof(DWORD);
527     case VT_DATE:
528         return sizeof(DATE)/sizeof(DWORD);
529     case VT_DECIMAL:
530         return (sizeof(DECIMAL)+3)/sizeof(DWORD);
531     case VT_VARIANT:
532         return (sizeof(VARIANT)+3)/sizeof(DWORD);
533     case VT_USERDEFINED:
534     {
535         ITypeInfo *tinfo2;
536         TYPEATTR *tattr;
537         HRESULT hres;
538         DWORD ret;
539
540         hres = ITypeInfo_GetRefTypeInfo(tinfo,tdesc->u.hreftype,&tinfo2);
541         if (FAILED(hres))
542             return 0; /* should fail critically in serialize_param */
543         ITypeInfo_GetTypeAttr(tinfo2,&tattr);
544         ret = (tattr->cbSizeInstance+3)/sizeof(DWORD);
545         ITypeInfo_ReleaseTypeAttr(tinfo2, tattr);
546         ITypeInfo_Release(tinfo2);
547         return ret;
548     }
549     default:
550         return 1;
551     }
552 }
553
554 /* how much space do we use on the heap (in bytes) */
555 static int
556 _xsize(const TYPEDESC *td, ITypeInfo *tinfo) {
557     switch (td->vt) {
558     case VT_DATE:
559         return sizeof(DATE);
560     case VT_CY:
561         return sizeof(CY);
562     case VT_VARIANT:
563         return sizeof(VARIANT)+3; /* FIXME: why the +3? */
564     case VT_CARRAY: {
565         int i, arrsize = 1;
566         const ARRAYDESC *adesc = td->u.lpadesc;
567
568         for (i=0;i<adesc->cDims;i++)
569             arrsize *= adesc->rgbounds[i].cElements;
570         return arrsize*_xsize(&adesc->tdescElem, tinfo);
571     }
572     case VT_UI8:
573     case VT_I8:
574     case VT_R8:
575         return 8;
576     case VT_UI2:
577     case VT_I2:
578     case VT_BOOL:
579         return 2;
580     case VT_UI1:
581     case VT_I1:
582         return 1;
583     case VT_USERDEFINED:
584     {
585         ITypeInfo *tinfo2;
586         TYPEATTR *tattr;
587         HRESULT hres;
588         DWORD ret;
589
590         hres = ITypeInfo_GetRefTypeInfo(tinfo,td->u.hreftype,&tinfo2);
591         if (FAILED(hres))
592             return 0;
593         ITypeInfo_GetTypeAttr(tinfo2,&tattr);
594         ret = tattr->cbSizeInstance;
595         ITypeInfo_ReleaseTypeAttr(tinfo2, tattr);
596         ITypeInfo_Release(tinfo2);
597         return ret;
598     }
599     default:
600         return 4;
601     }
602 }
603
604 static HRESULT
605 serialize_param(
606     ITypeInfo           *tinfo,
607     BOOL                writeit,
608     BOOL                debugout,
609     BOOL                dealloc,
610     TYPEDESC            *tdesc,
611     DWORD               *arg,
612     marshal_state       *buf)
613 {
614     HRESULT hres = S_OK;
615     VARTYPE vartype;
616
617     TRACE("(tdesc.vt %s)\n",debugstr_vt(tdesc->vt));
618
619     vartype = tdesc->vt;
620     if ((vartype & 0xf000) == VT_ARRAY)
621         vartype = VT_SAFEARRAY;
622
623     switch (vartype) {
624     case VT_DATE:
625     case VT_I8:
626     case VT_UI8:
627     case VT_R8:
628     case VT_CY:
629         hres = S_OK;
630         if (debugout) TRACE_(olerelay)("%x%x\n",arg[0],arg[1]);
631         if (writeit)
632             hres = xbuf_add(buf,(LPBYTE)arg,8);
633         return hres;
634     case VT_ERROR:
635     case VT_INT:
636     case VT_UINT:
637     case VT_I4:
638     case VT_R4:
639     case VT_UI4:
640         hres = S_OK;
641         if (debugout) TRACE_(olerelay)("%x\n",*arg);
642         if (writeit)
643             hres = xbuf_add(buf,(LPBYTE)arg,sizeof(DWORD));
644         return hres;
645     case VT_I2:
646     case VT_UI2:
647     case VT_BOOL:
648         hres = S_OK;
649         if (debugout) TRACE_(olerelay)("%04x\n",*arg & 0xffff);
650         if (writeit)
651             hres = xbuf_add(buf,(LPBYTE)arg,sizeof(DWORD));
652         return hres;
653     case VT_I1:
654     case VT_UI1:
655         hres = S_OK;
656         if (debugout) TRACE_(olerelay)("%02x\n",*arg & 0xff);
657         if (writeit)
658             hres = xbuf_add(buf,(LPBYTE)arg,sizeof(DWORD));
659         return hres;
660     case VT_VARIANT: {
661         if (debugout) TRACE_(olerelay)("Vt(%s%s)(",debugstr_vt(V_VT((VARIANT *)arg)),debugstr_vf(V_VT((VARIANT *)arg)));
662         if (writeit)
663         {
664             ULONG flags = MAKELONG(MSHCTX_DIFFERENTMACHINE, NDR_LOCAL_DATA_REPRESENTATION);
665             ULONG size = VARIANT_UserSize(&flags, buf->curoff, (VARIANT *)arg);
666             xbuf_resize(buf, size);
667             VARIANT_UserMarshal(&flags, buf->base + buf->curoff, (VARIANT *)arg);
668             buf->curoff = size;
669         }
670         if (dealloc)
671         {
672             ULONG flags = MAKELONG(MSHCTX_DIFFERENTMACHINE, NDR_LOCAL_DATA_REPRESENTATION);
673             VARIANT_UserFree(&flags, (VARIANT *)arg);
674         }
675         return S_OK;
676     }
677     case VT_BSTR: {
678         if (debugout) {
679             if (*arg)
680                    TRACE_(olerelay)("%s",relaystr((WCHAR*)*arg));
681             else
682                     TRACE_(olerelay)("<bstr NULL>");
683         }
684         if (writeit)
685         {
686             ULONG flags = MAKELONG(MSHCTX_DIFFERENTMACHINE, NDR_LOCAL_DATA_REPRESENTATION);
687             ULONG size = BSTR_UserSize(&flags, buf->curoff, (BSTR *)arg);
688             xbuf_resize(buf, size);
689             BSTR_UserMarshal(&flags, buf->base + buf->curoff, (BSTR *)arg);
690             buf->curoff = size;
691         }
692         if (dealloc)
693         {
694             ULONG flags = MAKELONG(MSHCTX_DIFFERENTMACHINE, NDR_LOCAL_DATA_REPRESENTATION);
695             BSTR_UserFree(&flags, (BSTR *)arg);
696         }
697         return S_OK;
698     }
699     case VT_PTR: {
700         DWORD cookie;
701         BOOL        derefhere = TRUE;
702
703         if (tdesc->u.lptdesc->vt == VT_USERDEFINED) {
704             ITypeInfo   *tinfo2;
705             TYPEATTR    *tattr;
706
707             hres = ITypeInfo_GetRefTypeInfo(tinfo,tdesc->u.lptdesc->u.hreftype,&tinfo2);
708             if (hres) {
709                 ERR("Could not get typeinfo of hreftype %x for VT_USERDEFINED.\n",tdesc->u.lptdesc->u.hreftype);
710                 return hres;
711             }
712             ITypeInfo_GetTypeAttr(tinfo2,&tattr);
713             switch (tattr->typekind) {
714             case TKIND_ALIAS:
715                 if (tattr->tdescAlias.vt == VT_USERDEFINED)
716                 {
717                     DWORD href = tattr->tdescAlias.u.hreftype;
718                     ITypeInfo_ReleaseTypeAttr(tinfo, tattr);
719                     ITypeInfo_Release(tinfo2);
720                     hres = ITypeInfo_GetRefTypeInfo(tinfo,href,&tinfo2);
721                     if (hres) {
722                         ERR("Could not get typeinfo of hreftype %x for VT_USERDEFINED.\n",tdesc->u.lptdesc->u.hreftype);
723                         return hres;
724                     }
725                     ITypeInfo_GetTypeAttr(tinfo2,&tattr);
726                     derefhere = (tattr->typekind != TKIND_DISPATCH && tattr->typekind != TKIND_INTERFACE);
727                 }
728                 break;
729             case TKIND_ENUM:    /* confirmed */
730             case TKIND_RECORD:  /* FIXME: mostly untested */
731                 break;
732             case TKIND_DISPATCH:        /* will be done in VT_USERDEFINED case */
733             case TKIND_INTERFACE:       /* will be done in VT_USERDEFINED case */
734                 derefhere=FALSE;
735                 break;
736             default:
737                 FIXME("unhandled switch cases tattr->typekind %d\n", tattr->typekind);
738                 derefhere=FALSE;
739                 break;
740             }
741             ITypeInfo_ReleaseTypeAttr(tinfo, tattr);
742             ITypeInfo_Release(tinfo2);
743         }
744
745         if (debugout) TRACE_(olerelay)("*");
746         /* Write always, so the other side knows when it gets a NULL pointer.
747          */
748         cookie = *arg ? 0x42424242 : 0;
749         hres = xbuf_add(buf,(LPBYTE)&cookie,sizeof(cookie));
750         if (hres)
751             return hres;
752         if (!*arg) {
753             if (debugout) TRACE_(olerelay)("NULL");
754             return S_OK;
755         }
756         hres = serialize_param(tinfo,writeit,debugout,dealloc,tdesc->u.lptdesc,(DWORD*)*arg,buf);
757         if (derefhere && dealloc) HeapFree(GetProcessHeap(),0,(LPVOID)*arg);
758         return hres;
759     }
760     case VT_UNKNOWN:
761         if (debugout) TRACE_(olerelay)("unk(0x%x)",*arg);
762         if (writeit)
763             hres = _marshal_interface(buf,&IID_IUnknown,(LPUNKNOWN)*arg);
764         if (dealloc && *(IUnknown **)arg)
765             IUnknown_Release((LPUNKNOWN)*arg);
766         return hres;
767     case VT_DISPATCH:
768         if (debugout) TRACE_(olerelay)("idisp(0x%x)",*arg);
769         if (writeit)
770             hres = _marshal_interface(buf,&IID_IDispatch,(LPUNKNOWN)*arg);
771         if (dealloc && *(IUnknown **)arg)
772             IUnknown_Release((LPUNKNOWN)*arg);
773         return hres;
774     case VT_VOID:
775         if (debugout) TRACE_(olerelay)("<void>");
776         return S_OK;
777     case VT_USERDEFINED: {
778         ITypeInfo       *tinfo2;
779         TYPEATTR        *tattr;
780
781         hres = ITypeInfo_GetRefTypeInfo(tinfo,tdesc->u.hreftype,&tinfo2);
782         if (hres) {
783             ERR("Could not get typeinfo of hreftype %x for VT_USERDEFINED.\n",tdesc->u.hreftype);
784             return hres;
785         }
786         ITypeInfo_GetTypeAttr(tinfo2,&tattr);
787         switch (tattr->typekind) {
788         case TKIND_DISPATCH:
789         case TKIND_INTERFACE:
790             if (writeit)
791                hres=_marshal_interface(buf,&(tattr->guid),(LPUNKNOWN)arg);
792             if (dealloc)
793                 IUnknown_Release((LPUNKNOWN)arg);
794             break;
795         case TKIND_RECORD: {
796             int i;
797             if (debugout) TRACE_(olerelay)("{");
798             for (i=0;i<tattr->cVars;i++) {
799                 VARDESC *vdesc;
800                 ELEMDESC *elem2;
801                 TYPEDESC *tdesc2;
802
803                 hres = ITypeInfo2_GetVarDesc(tinfo2, i, &vdesc);
804                 if (hres) {
805                     ERR("Could not get vardesc of %d\n",i);
806                     return hres;
807                 }
808                 elem2 = &vdesc->elemdescVar;
809                 tdesc2 = &elem2->tdesc;
810                 hres = serialize_param(
811                     tinfo2,
812                     writeit,
813                     debugout,
814                     dealloc,
815                     tdesc2,
816                     (DWORD*)(((LPBYTE)arg)+vdesc->u.oInst),
817                     buf
818                 );
819                 ITypeInfo_ReleaseVarDesc(tinfo2, vdesc);
820                 if (hres!=S_OK)
821                     return hres;
822                 if (debugout && (i<(tattr->cVars-1)))
823                     TRACE_(olerelay)(",");
824             }
825             if (debugout) TRACE_(olerelay)("}");
826             break;
827         }
828         case TKIND_ALIAS:
829             hres = serialize_param(tinfo2,writeit,debugout,dealloc,&tattr->tdescAlias,arg,buf);
830             break;
831         case TKIND_ENUM:
832             hres = S_OK;
833             if (debugout) TRACE_(olerelay)("%x",*arg);
834             if (writeit)
835                 hres = xbuf_add(buf,(LPBYTE)arg,sizeof(DWORD));
836             break;
837         default:
838             FIXME("Unhandled typekind %d\n",tattr->typekind);
839             hres = E_FAIL;
840             break;
841         }
842         ITypeInfo_ReleaseTypeAttr(tinfo2, tattr);
843         ITypeInfo_Release(tinfo2);
844         return hres;
845     }
846     case VT_CARRAY: {
847         ARRAYDESC *adesc = tdesc->u.lpadesc;
848         int i, arrsize = 1;
849
850         if (debugout) TRACE_(olerelay)("carr");
851         for (i=0;i<adesc->cDims;i++) {
852             if (debugout) TRACE_(olerelay)("[%d]",adesc->rgbounds[i].cElements);
853             arrsize *= adesc->rgbounds[i].cElements;
854         }
855         if (debugout) TRACE_(olerelay)("(vt %s)",debugstr_vt(adesc->tdescElem.vt));
856         if (debugout) TRACE_(olerelay)("[");
857         for (i=0;i<arrsize;i++) {
858             hres = serialize_param(tinfo, writeit, debugout, dealloc, &adesc->tdescElem, (DWORD*)((LPBYTE)(*arg)+i*_xsize(&adesc->tdescElem, tinfo)), buf);
859             if (hres)
860                 return hres;
861             if (debugout && (i<arrsize-1)) TRACE_(olerelay)(",");
862         }
863         if (debugout) TRACE_(olerelay)("]");
864         if (dealloc)
865             HeapFree(GetProcessHeap(), 0, *(void **)arg);
866         return S_OK;
867     }
868     case VT_SAFEARRAY: {
869         if (writeit)
870         {
871             ULONG flags = MAKELONG(MSHCTX_DIFFERENTMACHINE, NDR_LOCAL_DATA_REPRESENTATION);
872             ULONG size = LPSAFEARRAY_UserSize(&flags, buf->curoff, (LPSAFEARRAY *)arg);
873             xbuf_resize(buf, size);
874             LPSAFEARRAY_UserMarshal(&flags, buf->base + buf->curoff, (LPSAFEARRAY *)arg);
875             buf->curoff = size;
876         }
877         if (dealloc)
878         {
879             ULONG flags = MAKELONG(MSHCTX_DIFFERENTMACHINE, NDR_LOCAL_DATA_REPRESENTATION);
880             LPSAFEARRAY_UserFree(&flags, (LPSAFEARRAY *)arg);
881         }
882         return S_OK;
883     }
884     default:
885         ERR("Unhandled marshal type %d.\n",tdesc->vt);
886         return S_OK;
887     }
888 }
889
890 static HRESULT
891 deserialize_param(
892     ITypeInfo           *tinfo,
893     BOOL                readit,
894     BOOL                debugout,
895     BOOL                alloc,
896     TYPEDESC            *tdesc,
897     DWORD               *arg,
898     marshal_state       *buf)
899 {
900     HRESULT hres = S_OK;
901     VARTYPE vartype;
902
903     TRACE("vt %s at %p\n",debugstr_vt(tdesc->vt),arg);
904
905     vartype = tdesc->vt;
906     if ((vartype & 0xf000) == VT_ARRAY)
907         vartype = VT_SAFEARRAY;
908
909     while (1) {
910         switch (vartype) {
911         case VT_VARIANT: {
912             if (readit)
913             {
914                 ULONG flags = MAKELONG(MSHCTX_DIFFERENTMACHINE, NDR_LOCAL_DATA_REPRESENTATION);
915                 unsigned char *buffer;
916                 buffer = VARIANT_UserUnmarshal(&flags, buf->base + buf->curoff, (VARIANT *)arg);
917                 buf->curoff = buffer - buf->base;
918             }
919             return S_OK;
920         }
921         case VT_DATE:
922         case VT_I8:
923         case VT_UI8:
924         case VT_R8:
925         case VT_CY:
926             if (readit) {
927                 hres = xbuf_get(buf,(LPBYTE)arg,8);
928                 if (hres) ERR("Failed to read integer 8 byte\n");
929             }
930             if (debugout) TRACE_(olerelay)("%x%x",arg[0],arg[1]);
931             return hres;
932         case VT_ERROR:
933         case VT_I4:
934         case VT_INT:
935         case VT_UINT:
936         case VT_R4:
937         case VT_UI4:
938             if (readit) {
939                 hres = xbuf_get(buf,(LPBYTE)arg,sizeof(DWORD));
940                 if (hres) ERR("Failed to read integer 4 byte\n");
941             }
942             if (debugout) TRACE_(olerelay)("%x",*arg);
943             return hres;
944         case VT_I2:
945         case VT_UI2:
946         case VT_BOOL:
947             if (readit) {
948                 DWORD x;
949                 hres = xbuf_get(buf,(LPBYTE)&x,sizeof(DWORD));
950                 if (hres) ERR("Failed to read integer 4 byte\n");
951                 memcpy(arg,&x,2);
952             }
953             if (debugout) TRACE_(olerelay)("%04x",*arg & 0xffff);
954             return hres;
955         case VT_I1:
956         case VT_UI1:
957             if (readit) {
958                 DWORD x;
959                 hres = xbuf_get(buf,(LPBYTE)&x,sizeof(DWORD));
960                 if (hres) ERR("Failed to read integer 4 byte\n");
961                 memcpy(arg,&x,1);
962             }
963             if (debugout) TRACE_(olerelay)("%02x",*arg & 0xff);
964             return hres;
965         case VT_BSTR: {
966             if (readit)
967             {
968                 ULONG flags = MAKELONG(MSHCTX_DIFFERENTMACHINE, NDR_LOCAL_DATA_REPRESENTATION);
969                 unsigned char *buffer;
970                 buffer = BSTR_UserUnmarshal(&flags, buf->base + buf->curoff, (BSTR *)arg);
971                 buf->curoff = buffer - buf->base;
972                 if (debugout) TRACE_(olerelay)("%s",debugstr_w(*(BSTR *)arg));
973             }
974             return S_OK;
975         }
976         case VT_PTR: {
977             DWORD       cookie;
978             BOOL        derefhere = TRUE;
979
980             if (tdesc->u.lptdesc->vt == VT_USERDEFINED) {
981                 ITypeInfo       *tinfo2;
982                 TYPEATTR        *tattr;
983
984                 hres = ITypeInfo_GetRefTypeInfo(tinfo,tdesc->u.lptdesc->u.hreftype,&tinfo2);
985                 if (hres) {
986                     ERR("Could not get typeinfo of hreftype %x for VT_USERDEFINED.\n",tdesc->u.lptdesc->u.hreftype);
987                     return hres;
988                 }
989                 ITypeInfo_GetTypeAttr(tinfo2,&tattr);
990                 switch (tattr->typekind) {
991                 case TKIND_ALIAS:
992                     if (tattr->tdescAlias.vt == VT_USERDEFINED)
993                     {
994                         DWORD href = tattr->tdescAlias.u.hreftype;
995                         ITypeInfo_ReleaseTypeAttr(tinfo, tattr);
996                         ITypeInfo_Release(tinfo2);
997                         hres = ITypeInfo_GetRefTypeInfo(tinfo,href,&tinfo2);
998                         if (hres) {
999                             ERR("Could not get typeinfo of hreftype %x for VT_USERDEFINED.\n",tdesc->u.lptdesc->u.hreftype);
1000                             return hres;
1001                         }
1002                         ITypeInfo_GetTypeAttr(tinfo2,&tattr);
1003                         derefhere = (tattr->typekind != TKIND_DISPATCH && tattr->typekind != TKIND_INTERFACE);
1004                     }
1005                     break;
1006                 case TKIND_ENUM:        /* confirmed */
1007                 case TKIND_RECORD:      /* FIXME: mostly untested */
1008                     break;
1009                 case TKIND_DISPATCH:    /* will be done in VT_USERDEFINED case */
1010                 case TKIND_INTERFACE:   /* will be done in VT_USERDEFINED case */
1011                     derefhere=FALSE;
1012                     break;
1013                 default:
1014                     FIXME("unhandled switch cases tattr->typekind %d\n", tattr->typekind);
1015                     derefhere=FALSE;
1016                     break;
1017                 }
1018                 ITypeInfo_ReleaseTypeAttr(tinfo2, tattr);
1019                 ITypeInfo_Release(tinfo2);
1020             }
1021             /* read it in all cases, we need to know if we have 
1022              * NULL pointer or not.
1023              */
1024             hres = xbuf_get(buf,(LPBYTE)&cookie,sizeof(cookie));
1025             if (hres) {
1026                 ERR("Failed to load pointer cookie.\n");
1027                 return hres;
1028             }
1029             if (cookie != 0x42424242) {
1030                 /* we read a NULL ptr from the remote side */
1031                 if (debugout) TRACE_(olerelay)("NULL");
1032                 *arg = 0;
1033                 return S_OK;
1034             }
1035             if (debugout) TRACE_(olerelay)("*");
1036             if (alloc) {
1037                 /* Allocate space for the referenced struct */
1038                 if (derefhere)
1039                     *arg=(DWORD)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,_xsize(tdesc->u.lptdesc, tinfo));
1040             }
1041             if (derefhere)
1042                 return deserialize_param(tinfo, readit, debugout, alloc, tdesc->u.lptdesc, (LPDWORD)*arg, buf);
1043             else
1044                 return deserialize_param(tinfo, readit, debugout, alloc, tdesc->u.lptdesc, arg, buf);
1045         }
1046         case VT_UNKNOWN:
1047             /* FIXME: UNKNOWN is unknown ..., but allocate 4 byte for it */
1048             if (alloc)
1049                 *arg=(DWORD)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(DWORD));
1050             hres = S_OK;
1051             if (readit)
1052                 hres = _unmarshal_interface(buf,&IID_IUnknown,(LPUNKNOWN*)arg);
1053             if (debugout)
1054                 TRACE_(olerelay)("unk(%p)",arg);
1055             return hres;
1056         case VT_DISPATCH:
1057             hres = S_OK;
1058             if (readit)
1059                 hres = _unmarshal_interface(buf,&IID_IDispatch,(LPUNKNOWN*)arg);
1060             if (debugout)
1061                 TRACE_(olerelay)("idisp(%p)",arg);
1062             return hres;
1063         case VT_VOID:
1064             if (debugout) TRACE_(olerelay)("<void>");
1065             return S_OK;
1066         case VT_USERDEFINED: {
1067             ITypeInfo   *tinfo2;
1068             TYPEATTR    *tattr;
1069
1070             hres = ITypeInfo_GetRefTypeInfo(tinfo,tdesc->u.hreftype,&tinfo2);
1071             if (hres) {
1072                 ERR("Could not get typeinfo of hreftype %x for VT_USERDEFINED.\n",tdesc->u.hreftype);
1073                 return hres;
1074             }
1075             hres = ITypeInfo_GetTypeAttr(tinfo2,&tattr);
1076             if (hres) {
1077                 ERR("Could not get typeattr in VT_USERDEFINED.\n");
1078             } else {
1079                 switch (tattr->typekind) {
1080                 case TKIND_DISPATCH:
1081                 case TKIND_INTERFACE:
1082                     if (readit)
1083                         hres = _unmarshal_interface(buf,&(tattr->guid),(LPUNKNOWN*)arg);
1084                     break;
1085                 case TKIND_RECORD: {
1086                     int i;
1087
1088                     if (debugout) TRACE_(olerelay)("{");
1089                     for (i=0;i<tattr->cVars;i++) {
1090                         VARDESC *vdesc;
1091
1092                         hres = ITypeInfo2_GetVarDesc(tinfo2, i, &vdesc);
1093                         if (hres) {
1094                             ERR("Could not get vardesc of %d\n",i);
1095                             ITypeInfo_ReleaseTypeAttr(tinfo2, tattr);
1096                             ITypeInfo_Release(tinfo2);
1097                             return hres;
1098                         }
1099                         hres = deserialize_param(
1100                             tinfo2,
1101                             readit,
1102                             debugout,
1103                             alloc,
1104                             &vdesc->elemdescVar.tdesc,
1105                             (DWORD*)(((LPBYTE)arg)+vdesc->u.oInst),
1106                             buf
1107                         );
1108                         ITypeInfo2_ReleaseVarDesc(tinfo2, vdesc);
1109                         if (debugout && (i<tattr->cVars-1)) TRACE_(olerelay)(",");
1110                     }
1111                     if (debugout) TRACE_(olerelay)("}");
1112                     break;
1113                 }
1114                 case TKIND_ALIAS:
1115                     hres = deserialize_param(tinfo2,readit,debugout,alloc,&tattr->tdescAlias,arg,buf);
1116                     break;
1117                 case TKIND_ENUM:
1118                     if (readit) {
1119                         hres = xbuf_get(buf,(LPBYTE)arg,sizeof(DWORD));
1120                         if (hres) ERR("Failed to read enum (4 byte)\n");
1121                     }
1122                     if (debugout) TRACE_(olerelay)("%x",*arg);
1123                     break;
1124                 default:
1125                     ERR("Unhandled typekind %d\n",tattr->typekind);
1126                     hres = E_FAIL;
1127                     break;
1128                 }
1129                 ITypeInfo_ReleaseTypeAttr(tinfo2, tattr);
1130             }
1131             if (hres)
1132                 ERR("failed to stuballoc in TKIND_RECORD.\n");
1133             ITypeInfo_Release(tinfo2);
1134             return hres;
1135         }
1136         case VT_CARRAY: {
1137             /* arg is pointing to the start of the array. */
1138             ARRAYDESC *adesc = tdesc->u.lpadesc;
1139             int         arrsize,i;
1140             arrsize = 1;
1141             if (adesc->cDims > 1) FIXME("cDims > 1 in VT_CARRAY. Does it work?\n");
1142             for (i=0;i<adesc->cDims;i++)
1143                 arrsize *= adesc->rgbounds[i].cElements;
1144             *arg=(DWORD)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,_xsize(tdesc->u.lptdesc, tinfo) * arrsize);
1145             for (i=0;i<arrsize;i++)
1146                 deserialize_param(
1147                     tinfo,
1148                     readit,
1149                     debugout,
1150                     alloc,
1151                     &adesc->tdescElem,
1152                     (DWORD*)((LPBYTE)(*arg)+i*_xsize(&adesc->tdescElem, tinfo)),
1153                     buf
1154                 );
1155             return S_OK;
1156         }
1157     case VT_SAFEARRAY: {
1158             if (readit)
1159             {
1160                 ULONG flags = MAKELONG(MSHCTX_DIFFERENTMACHINE, NDR_LOCAL_DATA_REPRESENTATION);
1161                 unsigned char *buffer;
1162                 buffer = LPSAFEARRAY_UserUnmarshal(&flags, buf->base + buf->curoff, (LPSAFEARRAY *)arg);
1163                 buf->curoff = buffer - buf->base;
1164             }
1165             return S_OK;
1166         }
1167         default:
1168             ERR("No handler for VT type %d!\n",tdesc->vt);
1169             return S_OK;
1170         }
1171     }
1172 }
1173
1174 /* Retrieves a function's funcdesc, searching back into inherited interfaces. */
1175 static HRESULT get_funcdesc(ITypeInfo *tinfo, int iMethod, ITypeInfo **tactual, const FUNCDESC **fdesc,
1176                             BSTR *iname, BSTR *fname, UINT *num)
1177 {
1178     HRESULT hr;
1179     UINT i, impl_types;
1180     UINT inherited_funcs = 0;
1181     TYPEATTR *attr;
1182
1183     if (fname) *fname = NULL;
1184     if (iname) *iname = NULL;
1185     if (num) *num = 0;
1186     *tactual = NULL;
1187
1188     hr = ITypeInfo_GetTypeAttr(tinfo, &attr);
1189     if (FAILED(hr))
1190     {
1191         ERR("GetTypeAttr failed with %x\n",hr);
1192         return hr;
1193     }
1194
1195     if(attr->typekind == TKIND_DISPATCH)
1196     {
1197         if(attr->wTypeFlags & TYPEFLAG_FDUAL)
1198         {
1199             HREFTYPE href;
1200             ITypeInfo *tinfo2;
1201
1202             hr = ITypeInfo_GetRefTypeOfImplType(tinfo, -1, &href);
1203             if(FAILED(hr))
1204             {
1205                 ERR("Cannot get interface href from dual dispinterface\n");
1206                 ITypeInfo_ReleaseTypeAttr(tinfo, attr);
1207                 return hr;
1208             }
1209             hr = ITypeInfo_GetRefTypeInfo(tinfo, href, &tinfo2);
1210             if(FAILED(hr))
1211             {
1212                 ERR("Cannot get interface from dual dispinterface\n");
1213                 ITypeInfo_ReleaseTypeAttr(tinfo, attr);
1214                 return hr;
1215             }
1216             hr = get_funcdesc(tinfo2, iMethod, tactual, fdesc, iname, fname, num);
1217             ITypeInfo_Release(tinfo2);
1218             ITypeInfo_ReleaseTypeAttr(tinfo, attr);
1219             return hr;
1220         }
1221         ERR("Shouldn't be called with a non-dual dispinterface\n");
1222         return E_FAIL;
1223     }
1224
1225     impl_types = attr->cImplTypes;
1226     ITypeInfo_ReleaseTypeAttr(tinfo, attr);
1227
1228     for (i = 0; i < impl_types; i++)
1229     {
1230         HREFTYPE href;
1231         ITypeInfo *pSubTypeInfo;
1232         UINT sub_funcs;
1233
1234         hr = ITypeInfo_GetRefTypeOfImplType(tinfo, i, &href);
1235         if (FAILED(hr)) return hr;
1236         hr = ITypeInfo_GetRefTypeInfo(tinfo, href, &pSubTypeInfo);
1237         if (FAILED(hr)) return hr;
1238
1239         hr = get_funcdesc(pSubTypeInfo, iMethod, tactual, fdesc, iname, fname, &sub_funcs);
1240         inherited_funcs += sub_funcs;
1241         ITypeInfo_Release(pSubTypeInfo);
1242         if(SUCCEEDED(hr)) return hr;
1243     }
1244     if(iMethod < inherited_funcs)
1245     {
1246         ERR("shouldn't be here\n");
1247         return E_INVALIDARG;
1248     }
1249
1250     for(i = inherited_funcs; i <= iMethod; i++)
1251     {
1252         hr = ITypeInfoImpl_GetInternalFuncDesc(tinfo, i - inherited_funcs, fdesc);
1253         if(FAILED(hr))
1254         {
1255             if(num) *num = i;
1256             return hr;
1257         }
1258     }
1259
1260     /* found it. We don't care about num so zero it */
1261     if(num) *num = 0;
1262     *tactual = tinfo;
1263     ITypeInfo_AddRef(*tactual);
1264     if (fname) ITypeInfo_GetDocumentation(tinfo,(*fdesc)->memid,fname,NULL,NULL,NULL);
1265     if (iname) ITypeInfo_GetDocumentation(tinfo,-1,iname,NULL,NULL,NULL);
1266     return S_OK;
1267 }
1268
1269 static inline BOOL is_in_elem(const ELEMDESC *elem)
1270 {
1271     return (elem->u.paramdesc.wParamFlags & PARAMFLAG_FIN || !elem->u.paramdesc.wParamFlags);
1272 }
1273
1274 static inline BOOL is_out_elem(const ELEMDESC *elem)
1275 {
1276     return (elem->u.paramdesc.wParamFlags & PARAMFLAG_FOUT || !elem->u.paramdesc.wParamFlags);
1277 }
1278
1279 static DWORD
1280 xCall(LPVOID retptr, int method, TMProxyImpl *tpinfo /*, args */)
1281 {
1282     DWORD               *args = ((DWORD*)&tpinfo)+1, *xargs;
1283     const FUNCDESC      *fdesc;
1284     HRESULT             hres;
1285     int                 i, relaydeb = TRACE_ON(olerelay);
1286     marshal_state       buf;
1287     RPCOLEMESSAGE       msg;
1288     ULONG               status;
1289     BSTR                fname,iname;
1290     BSTR                names[10];
1291     UINT                nrofnames;
1292     DWORD               remoteresult = 0;
1293     ITypeInfo           *tinfo;
1294     IRpcChannelBuffer *chanbuf;
1295
1296     EnterCriticalSection(&tpinfo->crit);
1297
1298     hres = get_funcdesc(tpinfo->tinfo,method,&tinfo,&fdesc,&iname,&fname,NULL);
1299     if (hres) {
1300         ERR("Did not find typeinfo/funcdesc entry for method %d!\n",method);
1301         LeaveCriticalSection(&tpinfo->crit);
1302         return E_FAIL;
1303     }
1304
1305     if (!tpinfo->chanbuf)
1306     {
1307         WARN("Tried to use disconnected proxy\n");
1308         ITypeInfo_Release(tinfo);
1309         LeaveCriticalSection(&tpinfo->crit);
1310         return RPC_E_DISCONNECTED;
1311     }
1312     chanbuf = tpinfo->chanbuf;
1313     IRpcChannelBuffer_AddRef(chanbuf);
1314
1315     LeaveCriticalSection(&tpinfo->crit);
1316
1317     if (relaydeb) {
1318        TRACE_(olerelay)("->");
1319         if (iname)
1320             TRACE_(olerelay)("%s:",relaystr(iname));
1321         if (fname)
1322             TRACE_(olerelay)("%s(%d)",relaystr(fname),method);
1323         else
1324             TRACE_(olerelay)("%d",method);
1325         TRACE_(olerelay)("(");
1326     }
1327
1328     SysFreeString(iname);
1329     SysFreeString(fname);
1330
1331     memset(&buf,0,sizeof(buf));
1332
1333     /* normal typelib driven serializing */
1334
1335     /* Need them for hack below */
1336     memset(names,0,sizeof(names));
1337     if (ITypeInfo_GetNames(tinfo,fdesc->memid,names,sizeof(names)/sizeof(names[0]),&nrofnames))
1338         nrofnames = 0;
1339     if (nrofnames > sizeof(names)/sizeof(names[0]))
1340         ERR("Need more names!\n");
1341
1342     xargs = args;
1343     for (i=0;i<fdesc->cParams;i++) {
1344         ELEMDESC        *elem = fdesc->lprgelemdescParam+i;
1345         if (relaydeb) {
1346             if (i) TRACE_(olerelay)(",");
1347             if (i+1<nrofnames && names[i+1])
1348                 TRACE_(olerelay)("%s=",relaystr(names[i+1]));
1349         }
1350         /* No need to marshal other data than FIN and any VT_PTR. */
1351         if (!is_in_elem(elem) && (elem->tdesc.vt != VT_PTR)) {
1352             xargs+=_argsize(&elem->tdesc, tinfo);
1353             if (relaydeb) TRACE_(olerelay)("[out]");
1354             continue;
1355         }
1356         hres = serialize_param(
1357             tinfo,
1358             is_in_elem(elem),
1359             relaydeb,
1360             FALSE,
1361             &elem->tdesc,
1362             xargs,
1363             &buf
1364         );
1365
1366         if (hres) {
1367             ERR("Failed to serialize param, hres %x\n",hres);
1368             break;
1369         }
1370         xargs+=_argsize(&elem->tdesc, tinfo);
1371     }
1372     if (relaydeb) TRACE_(olerelay)(")");
1373
1374     memset(&msg,0,sizeof(msg));
1375     msg.cbBuffer = buf.curoff;
1376     msg.iMethod  = method;
1377     hres = IRpcChannelBuffer_GetBuffer(chanbuf,&msg,&(tpinfo->iid));
1378     if (hres) {
1379         ERR("RpcChannelBuffer GetBuffer failed, %x\n",hres);
1380         goto exit;
1381     }
1382     memcpy(msg.Buffer,buf.base,buf.curoff);
1383     if (relaydeb) TRACE_(olerelay)("\n");
1384     hres = IRpcChannelBuffer_SendReceive(chanbuf,&msg,&status);
1385     if (hres) {
1386         ERR("RpcChannelBuffer SendReceive failed, %x\n",hres);
1387         goto exit;
1388     }
1389
1390     if (relaydeb) TRACE_(olerelay)(" status = %08x (",status);
1391     if (buf.base)
1392         buf.base = HeapReAlloc(GetProcessHeap(),0,buf.base,msg.cbBuffer);
1393     else
1394         buf.base = HeapAlloc(GetProcessHeap(),0,msg.cbBuffer);
1395     buf.size = msg.cbBuffer;
1396     memcpy(buf.base,msg.Buffer,buf.size);
1397     buf.curoff = 0;
1398
1399     /* generic deserializer using typelib description */
1400     xargs = args;
1401     status = S_OK;
1402     for (i=0;i<fdesc->cParams;i++) {
1403         ELEMDESC        *elem = fdesc->lprgelemdescParam+i;
1404
1405         if (relaydeb) {
1406             if (i) TRACE_(olerelay)(",");
1407             if (i+1<nrofnames && names[i+1]) TRACE_(olerelay)("%s=",relaystr(names[i+1]));
1408         }
1409         /* No need to marshal other data than FOUT and any VT_PTR */
1410         if (!is_out_elem(elem) && (elem->tdesc.vt != VT_PTR)) {
1411             xargs += _argsize(&elem->tdesc, tinfo);
1412             if (relaydeb) TRACE_(olerelay)("[in]");
1413             continue;
1414         }
1415         hres = deserialize_param(
1416             tinfo,
1417             is_out_elem(elem),
1418             relaydeb,
1419             FALSE,
1420             &(elem->tdesc),
1421             xargs,
1422             &buf
1423         );
1424         if (hres) {
1425             ERR("Failed to unmarshall param, hres %x\n",hres);
1426             status = hres;
1427             break;
1428         }
1429         xargs += _argsize(&elem->tdesc, tinfo);
1430     }
1431
1432     hres = xbuf_get(&buf, (LPBYTE)&remoteresult, sizeof(DWORD));
1433     if (hres != S_OK)
1434         goto exit;
1435     if (relaydeb) TRACE_(olerelay)(") = %08x\n", remoteresult);
1436
1437     hres = remoteresult;
1438
1439 exit:
1440     IRpcChannelBuffer_FreeBuffer(chanbuf,&msg);
1441     for (i = 0; i < nrofnames; i++)
1442         SysFreeString(names[i]);
1443     HeapFree(GetProcessHeap(),0,buf.base);
1444     IRpcChannelBuffer_Release(chanbuf);
1445     ITypeInfo_Release(tinfo);
1446     TRACE("-- 0x%08x\n", hres);
1447     return hres;
1448 }
1449
1450 static HRESULT WINAPI ProxyIUnknown_QueryInterface(IUnknown *iface, REFIID riid, void **ppv)
1451 {
1452     TMProxyImpl *proxy = (TMProxyImpl *)iface;
1453
1454     TRACE("(%s, %p)\n", debugstr_guid(riid), ppv);
1455
1456     if (proxy->outerunknown)
1457         return IUnknown_QueryInterface(proxy->outerunknown, riid, ppv);
1458
1459     FIXME("No interface\n");
1460     return E_NOINTERFACE;
1461 }
1462
1463 static ULONG WINAPI ProxyIUnknown_AddRef(IUnknown *iface)
1464 {
1465     TMProxyImpl *proxy = (TMProxyImpl *)iface;
1466
1467     TRACE("\n");
1468
1469     if (proxy->outerunknown)
1470         return IUnknown_AddRef(proxy->outerunknown);
1471
1472     return 2; /* FIXME */
1473 }
1474
1475 static ULONG WINAPI ProxyIUnknown_Release(IUnknown *iface)
1476 {
1477     TMProxyImpl *proxy = (TMProxyImpl *)iface;
1478
1479     TRACE("\n");
1480
1481     if (proxy->outerunknown)
1482         return IUnknown_Release(proxy->outerunknown);
1483
1484     return 1; /* FIXME */
1485 }
1486
1487 static HRESULT WINAPI ProxyIDispatch_GetTypeInfoCount(LPDISPATCH iface, UINT * pctinfo)
1488 {
1489     TMProxyImpl *This = (TMProxyImpl *)iface;
1490
1491     TRACE("(%p)\n", pctinfo);
1492
1493     return IDispatch_GetTypeInfoCount(This->dispatch, pctinfo);
1494 }
1495
1496 static HRESULT WINAPI ProxyIDispatch_GetTypeInfo(LPDISPATCH iface, UINT iTInfo, LCID lcid, ITypeInfo** ppTInfo)
1497 {
1498     TMProxyImpl *This = (TMProxyImpl *)iface;
1499
1500     TRACE("(%d, %x, %p)\n", iTInfo, lcid, ppTInfo);
1501
1502     return IDispatch_GetTypeInfo(This->dispatch, iTInfo, lcid, ppTInfo);
1503 }
1504
1505 static HRESULT WINAPI ProxyIDispatch_GetIDsOfNames(LPDISPATCH iface, REFIID riid, LPOLESTR * rgszNames, UINT cNames, LCID lcid, DISPID * rgDispId)
1506 {
1507     TMProxyImpl *This = (TMProxyImpl *)iface;
1508
1509     TRACE("(%s, %p, %d, 0x%x, %p)\n", debugstr_guid(riid), rgszNames, cNames, lcid, rgDispId);
1510
1511     return IDispatch_GetIDsOfNames(This->dispatch, riid, rgszNames,
1512                                    cNames, lcid, rgDispId);
1513 }
1514
1515 static HRESULT WINAPI ProxyIDispatch_Invoke(LPDISPATCH iface, DISPID dispIdMember, REFIID riid, LCID lcid,
1516                                             WORD wFlags, DISPPARAMS * pDispParams, VARIANT * pVarResult,
1517                                             EXCEPINFO * pExcepInfo, UINT * puArgErr)
1518 {
1519     TMProxyImpl *This = (TMProxyImpl *)iface;
1520
1521     TRACE("(%d, %s, 0x%x, 0x%x, %p, %p, %p, %p)\n", dispIdMember,
1522           debugstr_guid(riid), lcid, wFlags, pDispParams, pVarResult,
1523           pExcepInfo, puArgErr);
1524
1525     return IDispatch_Invoke(This->dispatch, dispIdMember, riid, lcid,
1526                             wFlags, pDispParams, pVarResult, pExcepInfo,
1527                             puArgErr);
1528 }
1529
1530 typedef struct
1531 {
1532     IRpcChannelBuffer     IRpcChannelBuffer_iface;
1533     LONG                  refs;
1534     /* the IDispatch-derived interface we are handling */
1535     IID                   tmarshal_iid;
1536     IRpcChannelBuffer    *pDelegateChannel;
1537 } TMarshalDispatchChannel;
1538
1539 static inline TMarshalDispatchChannel *impl_from_IRpcChannelBuffer(IRpcChannelBuffer *iface)
1540 {
1541     return CONTAINING_RECORD(iface, TMarshalDispatchChannel, IRpcChannelBuffer_iface);
1542 }
1543
1544 static HRESULT WINAPI TMarshalDispatchChannel_QueryInterface(LPRPCCHANNELBUFFER iface, REFIID riid, LPVOID *ppv)
1545 {
1546     *ppv = NULL;
1547     if (IsEqualIID(riid,&IID_IRpcChannelBuffer) || IsEqualIID(riid,&IID_IUnknown))
1548     {
1549         *ppv = iface;
1550         IUnknown_AddRef(iface);
1551         return S_OK;
1552     }
1553     return E_NOINTERFACE;
1554 }
1555
1556 static ULONG WINAPI TMarshalDispatchChannel_AddRef(LPRPCCHANNELBUFFER iface)
1557 {
1558     TMarshalDispatchChannel *This = impl_from_IRpcChannelBuffer(iface);
1559     return InterlockedIncrement(&This->refs);
1560 }
1561
1562 static ULONG WINAPI TMarshalDispatchChannel_Release(LPRPCCHANNELBUFFER iface)
1563 {
1564     TMarshalDispatchChannel *This = impl_from_IRpcChannelBuffer(iface);
1565     ULONG ref;
1566
1567     ref = InterlockedDecrement(&This->refs);
1568     if (ref)
1569         return ref;
1570
1571         IRpcChannelBuffer_Release(This->pDelegateChannel);
1572     HeapFree(GetProcessHeap(), 0, This);
1573     return 0;
1574 }
1575
1576 static HRESULT WINAPI TMarshalDispatchChannel_GetBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg, REFIID riid)
1577 {
1578     TMarshalDispatchChannel *This = impl_from_IRpcChannelBuffer(iface);
1579     TRACE("(%p, %s)\n", olemsg, debugstr_guid(riid));
1580     /* Note: we are pretending to invoke a method on the interface identified
1581      * by tmarshal_iid so that we can re-use the IDispatch proxy/stub code
1582      * without the RPC runtime getting confused by not exporting an IDispatch interface */
1583     return IRpcChannelBuffer_GetBuffer(This->pDelegateChannel, olemsg, &This->tmarshal_iid);
1584 }
1585
1586 static HRESULT WINAPI TMarshalDispatchChannel_SendReceive(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE *olemsg, ULONG *pstatus)
1587 {
1588     TMarshalDispatchChannel *This = impl_from_IRpcChannelBuffer(iface);
1589     TRACE("(%p, %p)\n", olemsg, pstatus);
1590     return IRpcChannelBuffer_SendReceive(This->pDelegateChannel, olemsg, pstatus);
1591 }
1592
1593 static HRESULT WINAPI TMarshalDispatchChannel_FreeBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg)
1594 {
1595     TMarshalDispatchChannel *This = impl_from_IRpcChannelBuffer(iface);
1596     TRACE("(%p)\n", olemsg);
1597     return IRpcChannelBuffer_FreeBuffer(This->pDelegateChannel, olemsg);
1598 }
1599
1600 static HRESULT WINAPI TMarshalDispatchChannel_GetDestCtx(LPRPCCHANNELBUFFER iface, DWORD* pdwDestContext, void** ppvDestContext)
1601 {
1602     TMarshalDispatchChannel *This = impl_from_IRpcChannelBuffer(iface);
1603     TRACE("(%p,%p)\n", pdwDestContext, ppvDestContext);
1604     return IRpcChannelBuffer_GetDestCtx(This->pDelegateChannel, pdwDestContext, ppvDestContext);
1605 }
1606
1607 static HRESULT WINAPI TMarshalDispatchChannel_IsConnected(LPRPCCHANNELBUFFER iface)
1608 {
1609     TMarshalDispatchChannel *This = impl_from_IRpcChannelBuffer(iface);
1610     TRACE("()\n");
1611     return IRpcChannelBuffer_IsConnected(This->pDelegateChannel);
1612 }
1613
1614 static const IRpcChannelBufferVtbl TMarshalDispatchChannelVtbl =
1615 {
1616     TMarshalDispatchChannel_QueryInterface,
1617     TMarshalDispatchChannel_AddRef,
1618     TMarshalDispatchChannel_Release,
1619     TMarshalDispatchChannel_GetBuffer,
1620     TMarshalDispatchChannel_SendReceive,
1621     TMarshalDispatchChannel_FreeBuffer,
1622     TMarshalDispatchChannel_GetDestCtx,
1623     TMarshalDispatchChannel_IsConnected
1624 };
1625
1626 static HRESULT TMarshalDispatchChannel_Create(
1627     IRpcChannelBuffer *pDelegateChannel, REFIID tmarshal_riid,
1628     IRpcChannelBuffer **ppChannel)
1629 {
1630     TMarshalDispatchChannel *This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
1631     if (!This)
1632         return E_OUTOFMEMORY;
1633
1634     This->IRpcChannelBuffer_iface.lpVtbl = &TMarshalDispatchChannelVtbl;
1635     This->refs = 1;
1636     IRpcChannelBuffer_AddRef(pDelegateChannel);
1637     This->pDelegateChannel = pDelegateChannel;
1638     This->tmarshal_iid = *tmarshal_riid;
1639
1640     *ppChannel = &This->IRpcChannelBuffer_iface;
1641     return S_OK;
1642 }
1643
1644
1645 static inline HRESULT get_facbuf_for_iid(REFIID riid, IPSFactoryBuffer **facbuf)
1646 {
1647     HRESULT       hr;
1648     CLSID         clsid;
1649
1650     if ((hr = CoGetPSClsid(riid, &clsid)))
1651         return hr;
1652     return CoGetClassObject(&clsid, CLSCTX_INPROC_SERVER, NULL,
1653                              &IID_IPSFactoryBuffer, (LPVOID*)facbuf);
1654 }
1655
1656 static HRESULT init_proxy_entry_point(TMProxyImpl *proxy, unsigned int num)
1657 {
1658     int j;
1659     /* nrofargs without This */
1660     int nrofargs;
1661     ITypeInfo *tinfo2;
1662     TMAsmProxy  *xasm = proxy->asmstubs + num;
1663     HRESULT hres;
1664     const FUNCDESC *fdesc;
1665
1666     hres = get_funcdesc(proxy->tinfo, num, &tinfo2, &fdesc, NULL, NULL, NULL);
1667     if (hres) {
1668         ERR("GetFuncDesc %x should not fail here.\n",hres);
1669         return hres;
1670     }
1671     ITypeInfo_Release(tinfo2);
1672     /* some args take more than 4 byte on the stack */
1673     nrofargs = 0;
1674     for (j=0;j<fdesc->cParams;j++)
1675         nrofargs += _argsize(&fdesc->lprgelemdescParam[j].tdesc, proxy->tinfo);
1676
1677 #ifdef __i386__
1678     if (fdesc->callconv != CC_STDCALL) {
1679         ERR("calling convention is not stdcall????\n");
1680         return E_FAIL;
1681     }
1682 /* popl %eax    -       return ptr
1683  * pushl <nr>
1684  * pushl %eax
1685  * call xCall
1686  * lret <nr> (+4)
1687  *
1688  *
1689  * arg3 arg2 arg1 <method> <returnptr>
1690  */
1691     xasm->popleax       = 0x58;
1692     xasm->pushlval      = 0x68;
1693     xasm->nr            = num;
1694     xasm->pushleax      = 0x50;
1695     xasm->lcall         = 0xe8; /* relative jump */
1696     xasm->xcall         = (DWORD)xCall;
1697     xasm->xcall        -= (DWORD)&(xasm->lret);
1698     xasm->lret          = 0xc2;
1699     xasm->bytestopop    = (nrofargs+2)*4; /* pop args, This, iMethod */
1700     xasm->nop           = 0x90;
1701     proxy->lpvtbl[num]  = xasm;
1702 #else
1703     FIXME("not implemented on non i386\n");
1704     return E_FAIL;
1705 #endif
1706     return S_OK;
1707 }
1708
1709 static HRESULT WINAPI
1710 PSFacBuf_CreateProxy(
1711     LPPSFACTORYBUFFER iface, IUnknown* pUnkOuter, REFIID riid,
1712     IRpcProxyBuffer **ppProxy, LPVOID *ppv)
1713 {
1714     HRESULT     hres;
1715     ITypeInfo   *tinfo;
1716     unsigned int i, nroffuncs;
1717     TMProxyImpl *proxy;
1718     TYPEATTR    *typeattr;
1719     BOOL        defer_to_dispatch = FALSE;
1720
1721     TRACE("(...%s...)\n",debugstr_guid(riid));
1722     hres = _get_typeinfo_for_iid(riid,&tinfo);
1723     if (hres) {
1724         ERR("No typeinfo for %s?\n",debugstr_guid(riid));
1725         return hres;
1726     }
1727
1728     hres = num_of_funcs(tinfo, &nroffuncs);
1729     if (FAILED(hres)) {
1730         ERR("Cannot get number of functions for typeinfo %s\n",debugstr_guid(riid));
1731         ITypeInfo_Release(tinfo);
1732         return hres;
1733     }
1734
1735     proxy = CoTaskMemAlloc(sizeof(TMProxyImpl));
1736     if (!proxy) return E_OUTOFMEMORY;
1737
1738     assert(sizeof(TMAsmProxy) == 16);
1739
1740     proxy->dispatch = NULL;
1741     proxy->dispatch_proxy = NULL;
1742     proxy->outerunknown = pUnkOuter;
1743     proxy->asmstubs = VirtualAlloc(NULL, sizeof(TMAsmProxy) * nroffuncs, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
1744     if (!proxy->asmstubs) {
1745         ERR("Could not commit pages for proxy thunks\n");
1746         CoTaskMemFree(proxy);
1747         return E_OUTOFMEMORY;
1748     }
1749     proxy->IRpcProxyBuffer_iface.lpVtbl = &tmproxyvtable;
1750     /* one reference for the proxy */
1751     proxy->ref          = 1;
1752     proxy->tinfo        = tinfo;
1753     proxy->iid          = *riid;
1754     proxy->chanbuf      = 0;
1755
1756     InitializeCriticalSection(&proxy->crit);
1757     proxy->crit.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": TMProxyImpl.crit");
1758
1759     proxy->lpvtbl = HeapAlloc(GetProcessHeap(),0,sizeof(LPBYTE)*nroffuncs);
1760
1761     /* if we derive from IDispatch then defer to its proxy for its methods */
1762     hres = ITypeInfo_GetTypeAttr(tinfo, &typeattr);
1763     if (hres == S_OK)
1764     {
1765         if (typeattr->wTypeFlags & TYPEFLAG_FDISPATCHABLE)
1766         {
1767             IPSFactoryBuffer *factory_buffer;
1768             hres = get_facbuf_for_iid(&IID_IDispatch, &factory_buffer);
1769             if (hres == S_OK)
1770             {
1771                 hres = IPSFactoryBuffer_CreateProxy(factory_buffer, NULL,
1772                     &IID_IDispatch, &proxy->dispatch_proxy,
1773                     (void **)&proxy->dispatch);
1774                 IPSFactoryBuffer_Release(factory_buffer);
1775             }
1776             if ((hres == S_OK) && (nroffuncs < 7))
1777             {
1778                 ERR("nroffuncs calculated incorrectly (%d)\n", nroffuncs);
1779                 hres = E_UNEXPECTED;
1780             }
1781             if (hres == S_OK)
1782             {
1783                 defer_to_dispatch = TRUE;
1784             }
1785         }
1786         ITypeInfo_ReleaseTypeAttr(tinfo, typeattr);
1787     }
1788
1789     for (i=0;i<nroffuncs;i++) {
1790         switch (i) {
1791         case 0:
1792                 proxy->lpvtbl[i] = ProxyIUnknown_QueryInterface;
1793                 break;
1794         case 1:
1795                 proxy->lpvtbl[i] = ProxyIUnknown_AddRef;
1796                 break;
1797         case 2:
1798                 proxy->lpvtbl[i] = ProxyIUnknown_Release;
1799                 break;
1800         case 3:
1801                 if(!defer_to_dispatch)
1802                 {
1803                     hres = init_proxy_entry_point(proxy, i);
1804                     if(FAILED(hres)) return hres;
1805                 }
1806                 else proxy->lpvtbl[3] = ProxyIDispatch_GetTypeInfoCount;
1807                 break;
1808         case 4:
1809                 if(!defer_to_dispatch)
1810                 {
1811                     hres = init_proxy_entry_point(proxy, i);
1812                     if(FAILED(hres)) return hres;
1813                 }
1814                 else proxy->lpvtbl[4] = ProxyIDispatch_GetTypeInfo;
1815                 break;
1816         case 5:
1817                 if(!defer_to_dispatch)
1818                 {
1819                     hres = init_proxy_entry_point(proxy, i);
1820                     if(FAILED(hres)) return hres;
1821                 }
1822                 else proxy->lpvtbl[5] = ProxyIDispatch_GetIDsOfNames;
1823                 break;
1824         case 6:
1825                 if(!defer_to_dispatch)
1826                 {
1827                     hres = init_proxy_entry_point(proxy, i);
1828                     if(FAILED(hres)) return hres;
1829                 }
1830                 else proxy->lpvtbl[6] = ProxyIDispatch_Invoke;
1831                 break;
1832         default:
1833                 hres = init_proxy_entry_point(proxy, i);
1834                 if(FAILED(hres)) return hres;
1835         }
1836     }
1837
1838     if (hres == S_OK)
1839     {
1840         *ppv = proxy;
1841         *ppProxy = &proxy->IRpcProxyBuffer_iface;
1842         IUnknown_AddRef((IUnknown *)*ppv);
1843         return S_OK;
1844     }
1845     else
1846         TMProxyImpl_Release(&proxy->IRpcProxyBuffer_iface);
1847     return hres;
1848 }
1849
1850 typedef struct _TMStubImpl {
1851     IRpcStubBuffer              IRpcStubBuffer_iface;
1852     LONG                        ref;
1853
1854     LPUNKNOWN                   pUnk;
1855     ITypeInfo                   *tinfo;
1856     IID                         iid;
1857     IRpcStubBuffer              *dispatch_stub;
1858     BOOL                        dispatch_derivative;
1859 } TMStubImpl;
1860
1861 static inline TMStubImpl *impl_from_IRpcStubBuffer(IRpcStubBuffer *iface)
1862 {
1863     return CONTAINING_RECORD(iface, TMStubImpl, IRpcStubBuffer_iface);
1864 }
1865
1866 static HRESULT WINAPI
1867 TMStubImpl_QueryInterface(LPRPCSTUBBUFFER iface, REFIID riid, LPVOID *ppv)
1868 {
1869     if (IsEqualIID(riid,&IID_IRpcStubBuffer)||IsEqualIID(riid,&IID_IUnknown)){
1870         *ppv = iface;
1871         IRpcStubBuffer_AddRef(iface);
1872         return S_OK;
1873     }
1874     FIXME("%s, not supported IID.\n",debugstr_guid(riid));
1875     return E_NOINTERFACE;
1876 }
1877
1878 static ULONG WINAPI
1879 TMStubImpl_AddRef(LPRPCSTUBBUFFER iface)
1880 {
1881     TMStubImpl *This = impl_from_IRpcStubBuffer(iface);
1882     ULONG refCount = InterlockedIncrement(&This->ref);
1883
1884     TRACE("(%p)->(ref before=%u)\n", This, refCount - 1);
1885
1886     return refCount;
1887 }
1888
1889 static ULONG WINAPI
1890 TMStubImpl_Release(LPRPCSTUBBUFFER iface)
1891 {
1892     TMStubImpl *This = impl_from_IRpcStubBuffer(iface);
1893     ULONG refCount = InterlockedDecrement(&This->ref);
1894
1895     TRACE("(%p)->(ref before=%u)\n", This, refCount + 1);
1896
1897     if (!refCount)
1898     {
1899         IRpcStubBuffer_Disconnect(iface);
1900         ITypeInfo_Release(This->tinfo);
1901         if (This->dispatch_stub)
1902             IRpcStubBuffer_Release(This->dispatch_stub);
1903         CoTaskMemFree(This);
1904     }
1905     return refCount;
1906 }
1907
1908 static HRESULT WINAPI
1909 TMStubImpl_Connect(LPRPCSTUBBUFFER iface, LPUNKNOWN pUnkServer)
1910 {
1911     TMStubImpl *This = impl_from_IRpcStubBuffer(iface);
1912
1913     TRACE("(%p)->(%p)\n", This, pUnkServer);
1914
1915     IUnknown_AddRef(pUnkServer);
1916     This->pUnk = pUnkServer;
1917
1918     if (This->dispatch_stub)
1919         IRpcStubBuffer_Connect(This->dispatch_stub, pUnkServer);
1920
1921     return S_OK;
1922 }
1923
1924 static void WINAPI
1925 TMStubImpl_Disconnect(LPRPCSTUBBUFFER iface)
1926 {
1927     TMStubImpl *This = impl_from_IRpcStubBuffer(iface);
1928
1929     TRACE("(%p)->()\n", This);
1930
1931     if (This->pUnk)
1932     {
1933         IUnknown_Release(This->pUnk);
1934         This->pUnk = NULL;
1935     }
1936
1937     if (This->dispatch_stub)
1938         IRpcStubBuffer_Disconnect(This->dispatch_stub);
1939 }
1940
1941 static HRESULT WINAPI
1942 TMStubImpl_Invoke(
1943     LPRPCSTUBBUFFER iface, RPCOLEMESSAGE* xmsg,IRpcChannelBuffer*rpcchanbuf)
1944 {
1945 #ifdef __i386__
1946     int         i;
1947     const FUNCDESC *fdesc;
1948     TMStubImpl *This = impl_from_IRpcStubBuffer(iface);
1949     HRESULT     hres;
1950     DWORD       *args = NULL, res, *xargs, nrofargs;
1951     marshal_state       buf;
1952     UINT        nrofnames = 0;
1953     BSTR        names[10];
1954     BSTR        iname = NULL;
1955     ITypeInfo   *tinfo = NULL;
1956
1957     TRACE("...\n");
1958
1959     if (xmsg->iMethod < 3) {
1960         ERR("IUnknown methods cannot be marshaled by the typelib marshaler\n");
1961         return E_UNEXPECTED;
1962     }
1963
1964     if (This->dispatch_derivative && xmsg->iMethod < sizeof(IDispatchVtbl)/sizeof(void *))
1965     {
1966         IPSFactoryBuffer *factory_buffer;
1967         hres = get_facbuf_for_iid(&IID_IDispatch, &factory_buffer);
1968         if (hres == S_OK)
1969         {
1970             hres = IPSFactoryBuffer_CreateStub(factory_buffer, &IID_IDispatch,
1971                 This->pUnk, &This->dispatch_stub);
1972             IPSFactoryBuffer_Release(factory_buffer);
1973         }
1974         if (hres != S_OK)
1975             return hres;
1976         return IRpcStubBuffer_Invoke(This->dispatch_stub, xmsg, rpcchanbuf);
1977     }
1978
1979     memset(&buf,0,sizeof(buf));
1980     buf.size    = xmsg->cbBuffer;
1981     buf.base    = HeapAlloc(GetProcessHeap(), 0, xmsg->cbBuffer);
1982     memcpy(buf.base, xmsg->Buffer, xmsg->cbBuffer);
1983     buf.curoff  = 0;
1984
1985     hres = get_funcdesc(This->tinfo,xmsg->iMethod,&tinfo,&fdesc,&iname,NULL,NULL);
1986     if (hres) {
1987         ERR("GetFuncDesc on method %d failed with %x\n",xmsg->iMethod,hres);
1988         return hres;
1989     }
1990
1991     if (iname && !lstrcmpW(iname, IDispatchW))
1992     {
1993         ERR("IDispatch cannot be marshaled by the typelib marshaler\n");
1994         hres = E_UNEXPECTED;
1995         SysFreeString (iname);
1996         goto exit;
1997     }
1998
1999     SysFreeString (iname);
2000
2001     /* Need them for hack below */
2002     memset(names,0,sizeof(names));
2003     ITypeInfo_GetNames(tinfo,fdesc->memid,names,sizeof(names)/sizeof(names[0]),&nrofnames);
2004     if (nrofnames > sizeof(names)/sizeof(names[0])) {
2005         ERR("Need more names!\n");
2006     }
2007
2008     /*dump_FUNCDESC(fdesc);*/
2009     nrofargs = 0;
2010     for (i=0;i<fdesc->cParams;i++)
2011         nrofargs += _argsize(&fdesc->lprgelemdescParam[i].tdesc, tinfo);
2012     args = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,(nrofargs+1)*sizeof(DWORD));
2013     if (!args)
2014     {
2015         hres = E_OUTOFMEMORY;
2016         goto exit;
2017     }
2018
2019     /* Allocate all stuff used by call. */
2020     xargs = args+1;
2021     for (i=0;i<fdesc->cParams;i++) {
2022         ELEMDESC        *elem = fdesc->lprgelemdescParam+i;
2023
2024         hres = deserialize_param(
2025            tinfo,
2026            is_in_elem(elem),
2027            FALSE,
2028            TRUE,
2029            &(elem->tdesc),
2030            xargs,
2031            &buf
2032         );
2033         xargs += _argsize(&elem->tdesc, tinfo);
2034         if (hres) {
2035             ERR("Failed to deserialize param %s, hres %x\n",relaystr(names[i+1]),hres);
2036             break;
2037         }
2038     }
2039
2040     args[0] = (DWORD)This->pUnk;
2041
2042     __TRY
2043     {
2044         res = _invoke(
2045             (*((FARPROC**)args[0]))[fdesc->oVft/4],
2046             fdesc->callconv,
2047             (xargs-args),
2048             args
2049         );
2050     }
2051     __EXCEPT_ALL
2052     {
2053         DWORD dwExceptionCode = GetExceptionCode();
2054         ERR("invoke call failed with exception 0x%08x (%d)\n", dwExceptionCode, dwExceptionCode);
2055         if (FAILED(dwExceptionCode))
2056             hres = dwExceptionCode;
2057         else
2058             hres = HRESULT_FROM_WIN32(dwExceptionCode);
2059     }
2060     __ENDTRY
2061
2062     if (hres != S_OK)
2063         goto exit;
2064
2065     buf.curoff = 0;
2066
2067     xargs = args+1;
2068     for (i=0;i<fdesc->cParams;i++) {
2069         ELEMDESC        *elem = fdesc->lprgelemdescParam+i;
2070         hres = serialize_param(
2071            tinfo,
2072            is_out_elem(elem),
2073            FALSE,
2074            TRUE,
2075            &elem->tdesc,
2076            xargs,
2077            &buf
2078         );
2079         xargs += _argsize(&elem->tdesc, tinfo);
2080         if (hres) {
2081             ERR("Failed to stuballoc param, hres %x\n",hres);
2082             break;
2083         }
2084     }
2085
2086     hres = xbuf_add (&buf, (LPBYTE)&res, sizeof(DWORD));
2087
2088     if (hres != S_OK)
2089         goto exit;
2090
2091     xmsg->cbBuffer      = buf.curoff;
2092     hres = IRpcChannelBuffer_GetBuffer(rpcchanbuf, xmsg, &This->iid);
2093     if (hres != S_OK)
2094         ERR("IRpcChannelBuffer_GetBuffer failed with error 0x%08x\n", hres);
2095
2096     if (hres == S_OK)
2097         memcpy(xmsg->Buffer, buf.base, buf.curoff);
2098
2099 exit:
2100     for (i = 0; i < nrofnames; i++)
2101         SysFreeString(names[i]);
2102
2103     ITypeInfo_Release(tinfo);
2104     HeapFree(GetProcessHeap(), 0, args);
2105
2106     HeapFree(GetProcessHeap(), 0, buf.base);
2107
2108     TRACE("returning\n");
2109     return hres;
2110 #else
2111     FIXME( "not implemented on non-i386\n" );
2112     return E_FAIL;
2113 #endif
2114 }
2115
2116 static LPRPCSTUBBUFFER WINAPI
2117 TMStubImpl_IsIIDSupported(LPRPCSTUBBUFFER iface, REFIID riid) {
2118     FIXME("Huh (%s)?\n",debugstr_guid(riid));
2119     return NULL;
2120 }
2121
2122 static ULONG WINAPI
2123 TMStubImpl_CountRefs(LPRPCSTUBBUFFER iface) {
2124     TMStubImpl *This = impl_from_IRpcStubBuffer(iface);
2125
2126     FIXME("()\n");
2127     return This->ref; /*FIXME? */
2128 }
2129
2130 static HRESULT WINAPI
2131 TMStubImpl_DebugServerQueryInterface(LPRPCSTUBBUFFER iface, LPVOID *ppv) {
2132     return E_NOTIMPL;
2133 }
2134
2135 static void WINAPI
2136 TMStubImpl_DebugServerRelease(LPRPCSTUBBUFFER iface, LPVOID ppv) {
2137     return;
2138 }
2139
2140 static const IRpcStubBufferVtbl tmstubvtbl = {
2141     TMStubImpl_QueryInterface,
2142     TMStubImpl_AddRef,
2143     TMStubImpl_Release,
2144     TMStubImpl_Connect,
2145     TMStubImpl_Disconnect,
2146     TMStubImpl_Invoke,
2147     TMStubImpl_IsIIDSupported,
2148     TMStubImpl_CountRefs,
2149     TMStubImpl_DebugServerQueryInterface,
2150     TMStubImpl_DebugServerRelease
2151 };
2152
2153 static HRESULT WINAPI
2154 PSFacBuf_CreateStub(
2155     LPPSFACTORYBUFFER iface, REFIID riid,IUnknown *pUnkServer,
2156     IRpcStubBuffer** ppStub
2157 ) {
2158     HRESULT hres;
2159     ITypeInfo   *tinfo;
2160     TMStubImpl  *stub;
2161     TYPEATTR *typeattr;
2162
2163     TRACE("(%s,%p,%p)\n",debugstr_guid(riid),pUnkServer,ppStub);
2164
2165     hres = _get_typeinfo_for_iid(riid,&tinfo);
2166     if (hres) {
2167         ERR("No typeinfo for %s?\n",debugstr_guid(riid));
2168         return hres;
2169     }
2170
2171     stub = CoTaskMemAlloc(sizeof(TMStubImpl));
2172     if (!stub)
2173         return E_OUTOFMEMORY;
2174     stub->IRpcStubBuffer_iface.lpVtbl = &tmstubvtbl;
2175     stub->ref           = 1;
2176     stub->tinfo         = tinfo;
2177     stub->dispatch_stub = NULL;
2178     stub->dispatch_derivative = FALSE;
2179     stub->iid           = *riid;
2180     hres = IRpcStubBuffer_Connect(&stub->IRpcStubBuffer_iface,pUnkServer);
2181     *ppStub = &stub->IRpcStubBuffer_iface;
2182     TRACE("IRpcStubBuffer: %p\n", stub);
2183     if (hres)
2184         ERR("Connect to pUnkServer failed?\n");
2185
2186     /* if we derive from IDispatch then defer to its stub for some of its methods */
2187     hres = ITypeInfo_GetTypeAttr(tinfo, &typeattr);
2188     if (hres == S_OK)
2189     {
2190         if (typeattr->wTypeFlags & TYPEFLAG_FDISPATCHABLE)
2191             stub->dispatch_derivative = TRUE;
2192         ITypeInfo_ReleaseTypeAttr(tinfo, typeattr);
2193     }
2194
2195     return hres;
2196 }
2197
2198 static const IPSFactoryBufferVtbl psfacbufvtbl = {
2199     PSFacBuf_QueryInterface,
2200     PSFacBuf_AddRef,
2201     PSFacBuf_Release,
2202     PSFacBuf_CreateProxy,
2203     PSFacBuf_CreateStub
2204 };
2205
2206 /* This is the whole PSFactoryBuffer object, just the vtableptr */
2207 static const IPSFactoryBufferVtbl *lppsfac = &psfacbufvtbl;
2208
2209 /***********************************************************************
2210  *           TMARSHAL_DllGetClassObject
2211  */
2212 HRESULT TMARSHAL_DllGetClassObject(REFCLSID rclsid, REFIID iid,LPVOID *ppv)
2213 {
2214     if (IsEqualIID(iid,&IID_IPSFactoryBuffer)) {
2215         *ppv = &lppsfac;
2216         return S_OK;
2217     }
2218     return E_NOINTERFACE;
2219 }