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