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