oleaut32: Implement the ability to marshall VT_CARRAY's of user defined types.
[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             *arg=(DWORD)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,_xsize(tdesc->u.lptdesc, tinfo) * arrsize);
1251             for (i=0;i<arrsize;i++)
1252                 deserialize_param(
1253                     tinfo,
1254                     readit,
1255                     debugout,
1256                     alloc,
1257                     &adesc->tdescElem,
1258                     (DWORD*)((LPBYTE)(*arg)+i*_xsize(&adesc->tdescElem, tinfo)),
1259                     buf
1260                 );
1261             return S_OK;
1262         }
1263     case VT_SAFEARRAY: {
1264             if (readit)
1265             {
1266                 ULONG flags = MAKELONG(MSHCTX_DIFFERENTMACHINE, NDR_LOCAL_DATA_REPRESENTATION);
1267                 unsigned char *buffer;
1268                 buffer = LPSAFEARRAY_UserUnmarshal(&flags, buf->base + buf->curoff, (LPSAFEARRAY *)arg);
1269                 buf->curoff = buffer - buf->base;
1270             }
1271             return S_OK;
1272         }
1273         default:
1274             ERR("No handler for VT type %d!\n",tdesc->vt);
1275             return S_OK;
1276         }
1277     }
1278 }
1279
1280 /* Retrieves a function's funcdesc, searching back into inherited interfaces. */
1281 static HRESULT get_funcdesc(ITypeInfo *tinfo, int iMethod, ITypeInfo **tactual, const FUNCDESC **fdesc,
1282                             BSTR *iname, BSTR *fname, UINT *num)
1283 {
1284     HRESULT hr;
1285     UINT i, impl_types;
1286     UINT inherited_funcs = 0;
1287     TYPEATTR *attr;
1288
1289     if (fname) *fname = NULL;
1290     if (iname) *iname = NULL;
1291     if (num) *num = 0;
1292     *tactual = NULL;
1293
1294     hr = ITypeInfo_GetTypeAttr(tinfo, &attr);
1295     if (FAILED(hr))
1296     {
1297         ERR("GetTypeAttr failed with %x\n",hr);
1298         return hr;
1299     }
1300
1301     if(attr->typekind == TKIND_DISPATCH)
1302     {
1303         if(attr->wTypeFlags & TYPEFLAG_FDUAL)
1304         {
1305             HREFTYPE href;
1306             ITypeInfo *tinfo2;
1307
1308             hr = ITypeInfo_GetRefTypeOfImplType(tinfo, -1, &href);
1309             if(FAILED(hr))
1310             {
1311                 ERR("Cannot get interface href from dual dispinterface\n");
1312                 ITypeInfo_ReleaseTypeAttr(tinfo, attr);
1313                 return hr;
1314             }
1315             hr = ITypeInfo_GetRefTypeInfo(tinfo, href, &tinfo2);
1316             if(FAILED(hr))
1317             {
1318                 ERR("Cannot get interface from dual dispinterface\n");
1319                 ITypeInfo_ReleaseTypeAttr(tinfo, attr);
1320                 return hr;
1321             }
1322             hr = get_funcdesc(tinfo2, iMethod, tactual, fdesc, iname, fname, num);
1323             ITypeInfo_Release(tinfo2);
1324             ITypeInfo_ReleaseTypeAttr(tinfo, attr);
1325             return hr;
1326         }
1327         ERR("Shouldn't be called with a non-dual dispinterface\n");
1328         return E_FAIL;
1329     }
1330
1331     impl_types = attr->cImplTypes;
1332     ITypeInfo_ReleaseTypeAttr(tinfo, attr);
1333
1334     for (i = 0; i < impl_types; i++)
1335     {
1336         HREFTYPE href;
1337         ITypeInfo *pSubTypeInfo;
1338         UINT sub_funcs;
1339
1340         hr = ITypeInfo_GetRefTypeOfImplType(tinfo, i, &href);
1341         if (FAILED(hr)) return hr;
1342         hr = ITypeInfo_GetRefTypeInfo(tinfo, href, &pSubTypeInfo);
1343         if (FAILED(hr)) return hr;
1344
1345         hr = get_funcdesc(pSubTypeInfo, iMethod, tactual, fdesc, iname, fname, &sub_funcs);
1346         inherited_funcs += sub_funcs;
1347         ITypeInfo_Release(pSubTypeInfo);
1348         if(SUCCEEDED(hr)) return hr;
1349     }
1350     if(iMethod < inherited_funcs)
1351     {
1352         ERR("shouldn't be here\n");
1353         return E_INVALIDARG;
1354     }
1355
1356     for(i = inherited_funcs; i <= iMethod; i++)
1357     {
1358         hr = ITypeInfoImpl_GetInternalFuncDesc(tinfo, i - inherited_funcs, fdesc);
1359         if(FAILED(hr))
1360         {
1361             if(num) *num = i;
1362             return hr;
1363         }
1364     }
1365
1366     /* found it. We don't care about num so zero it */
1367     if(num) *num = 0;
1368     *tactual = tinfo;
1369     ITypeInfo_AddRef(*tactual);
1370     if (fname) ITypeInfo_GetDocumentation(tinfo,(*fdesc)->memid,fname,NULL,NULL,NULL);
1371     if (iname) ITypeInfo_GetDocumentation(tinfo,-1,iname,NULL,NULL,NULL);
1372     return S_OK;
1373 }
1374
1375 static inline BOOL is_in_elem(const ELEMDESC *elem)
1376 {
1377     return (elem->u.paramdesc.wParamFlags & PARAMFLAG_FIN || !elem->u.paramdesc.wParamFlags);
1378 }
1379
1380 static inline BOOL is_out_elem(const ELEMDESC *elem)
1381 {
1382     return (elem->u.paramdesc.wParamFlags & PARAMFLAG_FOUT || !elem->u.paramdesc.wParamFlags);
1383 }
1384
1385 static DWORD
1386 xCall(LPVOID retptr, int method, TMProxyImpl *tpinfo /*, args */)
1387 {
1388     DWORD               *args = ((DWORD*)&tpinfo)+1, *xargs;
1389     const FUNCDESC      *fdesc;
1390     HRESULT             hres;
1391     int                 i, relaydeb = TRACE_ON(olerelay);
1392     marshal_state       buf;
1393     RPCOLEMESSAGE       msg;
1394     ULONG               status;
1395     BSTR                fname,iname;
1396     BSTR                names[10];
1397     UINT                nrofnames;
1398     DWORD               remoteresult = 0;
1399     ITypeInfo           *tinfo;
1400     IRpcChannelBuffer *chanbuf;
1401
1402     EnterCriticalSection(&tpinfo->crit);
1403
1404     hres = get_funcdesc(tpinfo->tinfo,method,&tinfo,&fdesc,&iname,&fname,NULL);
1405     if (hres) {
1406         ERR("Did not find typeinfo/funcdesc entry for method %d!\n",method);
1407         LeaveCriticalSection(&tpinfo->crit);
1408         return E_FAIL;
1409     }
1410
1411     if (!tpinfo->chanbuf)
1412     {
1413         WARN("Tried to use disconnected proxy\n");
1414         ITypeInfo_Release(tinfo);
1415         LeaveCriticalSection(&tpinfo->crit);
1416         return RPC_E_DISCONNECTED;
1417     }
1418     chanbuf = tpinfo->chanbuf;
1419     IRpcChannelBuffer_AddRef(chanbuf);
1420
1421     LeaveCriticalSection(&tpinfo->crit);
1422
1423     if (relaydeb) {
1424        TRACE_(olerelay)("->");
1425         if (iname)
1426             TRACE_(olerelay)("%s:",relaystr(iname));
1427         if (fname)
1428             TRACE_(olerelay)("%s(%d)",relaystr(fname),method);
1429         else
1430             TRACE_(olerelay)("%d",method);
1431         TRACE_(olerelay)("(");
1432     }
1433
1434     SysFreeString(iname);
1435     SysFreeString(fname);
1436
1437     memset(&buf,0,sizeof(buf));
1438
1439     /* normal typelib driven serializing */
1440
1441     /* Need them for hack below */
1442     memset(names,0,sizeof(names));
1443     if (ITypeInfo_GetNames(tinfo,fdesc->memid,names,sizeof(names)/sizeof(names[0]),&nrofnames))
1444         nrofnames = 0;
1445     if (nrofnames > sizeof(names)/sizeof(names[0]))
1446         ERR("Need more names!\n");
1447
1448     xargs = args;
1449     for (i=0;i<fdesc->cParams;i++) {
1450         ELEMDESC        *elem = fdesc->lprgelemdescParam+i;
1451         if (relaydeb) {
1452             if (i) TRACE_(olerelay)(",");
1453             if (i+1<nrofnames && names[i+1])
1454                 TRACE_(olerelay)("%s=",relaystr(names[i+1]));
1455         }
1456         /* No need to marshal other data than FIN and any VT_PTR. */
1457         if (!is_in_elem(elem) && (elem->tdesc.vt != VT_PTR)) {
1458             xargs+=_argsize(&elem->tdesc, tinfo);
1459             if (relaydeb) TRACE_(olerelay)("[out]");
1460             continue;
1461         }
1462         hres = serialize_param(
1463             tinfo,
1464             is_in_elem(elem),
1465             relaydeb,
1466             FALSE,
1467             &elem->tdesc,
1468             xargs,
1469             &buf
1470         );
1471
1472         if (hres) {
1473             ERR("Failed to serialize param, hres %x\n",hres);
1474             break;
1475         }
1476         xargs+=_argsize(&elem->tdesc, tinfo);
1477     }
1478     if (relaydeb) TRACE_(olerelay)(")");
1479
1480     memset(&msg,0,sizeof(msg));
1481     msg.cbBuffer = buf.curoff;
1482     msg.iMethod  = method;
1483     hres = IRpcChannelBuffer_GetBuffer(chanbuf,&msg,&(tpinfo->iid));
1484     if (hres) {
1485         ERR("RpcChannelBuffer GetBuffer failed, %x\n",hres);
1486         goto exit;
1487     }
1488     memcpy(msg.Buffer,buf.base,buf.curoff);
1489     if (relaydeb) TRACE_(olerelay)("\n");
1490     hres = IRpcChannelBuffer_SendReceive(chanbuf,&msg,&status);
1491     if (hres) {
1492         ERR("RpcChannelBuffer SendReceive failed, %x\n",hres);
1493         goto exit;
1494     }
1495
1496     if (relaydeb) TRACE_(olerelay)(" status = %08x (",status);
1497     if (buf.base)
1498         buf.base = HeapReAlloc(GetProcessHeap(),0,buf.base,msg.cbBuffer);
1499     else
1500         buf.base = HeapAlloc(GetProcessHeap(),0,msg.cbBuffer);
1501     buf.size = msg.cbBuffer;
1502     memcpy(buf.base,msg.Buffer,buf.size);
1503     buf.curoff = 0;
1504
1505     /* generic deserializer using typelib description */
1506     xargs = args;
1507     status = S_OK;
1508     for (i=0;i<fdesc->cParams;i++) {
1509         ELEMDESC        *elem = fdesc->lprgelemdescParam+i;
1510
1511         if (relaydeb) {
1512             if (i) TRACE_(olerelay)(",");
1513             if (i+1<nrofnames && names[i+1]) TRACE_(olerelay)("%s=",relaystr(names[i+1]));
1514         }
1515         /* No need to marshal other data than FOUT and any VT_PTR */
1516         if (!is_out_elem(elem) && (elem->tdesc.vt != VT_PTR)) {
1517             xargs += _argsize(&elem->tdesc, tinfo);
1518             if (relaydeb) TRACE_(olerelay)("[in]");
1519             continue;
1520         }
1521         hres = deserialize_param(
1522             tinfo,
1523             is_out_elem(elem),
1524             relaydeb,
1525             FALSE,
1526             &(elem->tdesc),
1527             xargs,
1528             &buf
1529         );
1530         if (hres) {
1531             ERR("Failed to unmarshall param, hres %x\n",hres);
1532             status = hres;
1533             break;
1534         }
1535         xargs += _argsize(&elem->tdesc, tinfo);
1536     }
1537
1538     hres = xbuf_get(&buf, (LPBYTE)&remoteresult, sizeof(DWORD));
1539     if (hres != S_OK)
1540         goto exit;
1541     if (relaydeb) TRACE_(olerelay)(") = %08x\n", remoteresult);
1542
1543     hres = remoteresult;
1544
1545 exit:
1546     IRpcChannelBuffer_FreeBuffer(chanbuf,&msg);
1547     for (i = 0; i < nrofnames; i++)
1548         SysFreeString(names[i]);
1549     HeapFree(GetProcessHeap(),0,buf.base);
1550     IRpcChannelBuffer_Release(chanbuf);
1551     ITypeInfo_Release(tinfo);
1552     TRACE("-- 0x%08x\n", hres);
1553     return hres;
1554 }
1555
1556 static HRESULT WINAPI ProxyIUnknown_QueryInterface(IUnknown *iface, REFIID riid, void **ppv)
1557 {
1558     TMProxyImpl *proxy = (TMProxyImpl *)iface;
1559
1560     TRACE("(%s, %p)\n", debugstr_guid(riid), ppv);
1561
1562     if (proxy->outerunknown)
1563         return IUnknown_QueryInterface(proxy->outerunknown, riid, ppv);
1564
1565     FIXME("No interface\n");
1566     return E_NOINTERFACE;
1567 }
1568
1569 static ULONG WINAPI ProxyIUnknown_AddRef(IUnknown *iface)
1570 {
1571     TMProxyImpl *proxy = (TMProxyImpl *)iface;
1572
1573     TRACE("\n");
1574
1575     if (proxy->outerunknown)
1576         return IUnknown_AddRef(proxy->outerunknown);
1577
1578     return 2; /* FIXME */
1579 }
1580
1581 static ULONG WINAPI ProxyIUnknown_Release(IUnknown *iface)
1582 {
1583     TMProxyImpl *proxy = (TMProxyImpl *)iface;
1584
1585     TRACE("\n");
1586
1587     if (proxy->outerunknown)
1588         return IUnknown_Release(proxy->outerunknown);
1589
1590     return 1; /* FIXME */
1591 }
1592
1593 static HRESULT WINAPI ProxyIDispatch_GetTypeInfoCount(LPDISPATCH iface, UINT * pctinfo)
1594 {
1595     TMProxyImpl *This = (TMProxyImpl *)iface;
1596
1597     TRACE("(%p)\n", pctinfo);
1598
1599     return IDispatch_GetTypeInfoCount(This->dispatch, pctinfo);
1600 }
1601
1602 static HRESULT WINAPI ProxyIDispatch_GetTypeInfo(LPDISPATCH iface, UINT iTInfo, LCID lcid, ITypeInfo** ppTInfo)
1603 {
1604     TMProxyImpl *This = (TMProxyImpl *)iface;
1605
1606     TRACE("(%d, %x, %p)\n", iTInfo, lcid, ppTInfo);
1607
1608     return IDispatch_GetTypeInfo(This->dispatch, iTInfo, lcid, ppTInfo);
1609 }
1610
1611 static HRESULT WINAPI ProxyIDispatch_GetIDsOfNames(LPDISPATCH iface, REFIID riid, LPOLESTR * rgszNames, UINT cNames, LCID lcid, DISPID * rgDispId)
1612 {
1613     TMProxyImpl *This = (TMProxyImpl *)iface;
1614
1615     TRACE("(%s, %p, %d, 0x%x, %p)\n", debugstr_guid(riid), rgszNames, cNames, lcid, rgDispId);
1616
1617     return IDispatch_GetIDsOfNames(This->dispatch, riid, rgszNames,
1618                                    cNames, lcid, rgDispId);
1619 }
1620
1621 static HRESULT WINAPI ProxyIDispatch_Invoke(LPDISPATCH iface, DISPID dispIdMember, REFIID riid, LCID lcid,
1622                                             WORD wFlags, DISPPARAMS * pDispParams, VARIANT * pVarResult,
1623                                             EXCEPINFO * pExcepInfo, UINT * puArgErr)
1624 {
1625     TMProxyImpl *This = (TMProxyImpl *)iface;
1626
1627     TRACE("(%d, %s, 0x%x, 0x%x, %p, %p, %p, %p)\n", dispIdMember,
1628           debugstr_guid(riid), lcid, wFlags, pDispParams, pVarResult,
1629           pExcepInfo, puArgErr);
1630
1631     return IDispatch_Invoke(This->dispatch, dispIdMember, riid, lcid,
1632                             wFlags, pDispParams, pVarResult, pExcepInfo,
1633                             puArgErr);
1634 }
1635
1636 typedef struct
1637 {
1638     const IRpcChannelBufferVtbl *lpVtbl;
1639     LONG                  refs;
1640     /* the IDispatch-derived interface we are handling */
1641         IID                   tmarshal_iid;
1642     IRpcChannelBuffer    *pDelegateChannel;
1643 } TMarshalDispatchChannel;
1644
1645 static HRESULT WINAPI TMarshalDispatchChannel_QueryInterface(LPRPCCHANNELBUFFER iface, REFIID riid, LPVOID *ppv)
1646 {
1647     *ppv = NULL;
1648     if (IsEqualIID(riid,&IID_IRpcChannelBuffer) || IsEqualIID(riid,&IID_IUnknown))
1649     {
1650         *ppv = iface;
1651         IUnknown_AddRef(iface);
1652         return S_OK;
1653     }
1654     return E_NOINTERFACE;
1655 }
1656
1657 static ULONG WINAPI TMarshalDispatchChannel_AddRef(LPRPCCHANNELBUFFER iface)
1658 {
1659     TMarshalDispatchChannel *This = (TMarshalDispatchChannel *)iface;
1660     return InterlockedIncrement(&This->refs);
1661 }
1662
1663 static ULONG WINAPI TMarshalDispatchChannel_Release(LPRPCCHANNELBUFFER iface)
1664 {
1665     TMarshalDispatchChannel *This = (TMarshalDispatchChannel *)iface;
1666     ULONG ref;
1667
1668     ref = InterlockedDecrement(&This->refs);
1669     if (ref)
1670         return ref;
1671
1672         IRpcChannelBuffer_Release(This->pDelegateChannel);
1673     HeapFree(GetProcessHeap(), 0, This);
1674     return 0;
1675 }
1676
1677 static HRESULT WINAPI TMarshalDispatchChannel_GetBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg, REFIID riid)
1678 {
1679     TMarshalDispatchChannel *This = (TMarshalDispatchChannel *)iface;
1680     TRACE("(%p, %s)\n", olemsg, debugstr_guid(riid));
1681     /* Note: we are pretending to invoke a method on the interface identified
1682      * by tmarshal_iid so that we can re-use the IDispatch proxy/stub code
1683      * without the RPC runtime getting confused by not exporting an IDispatch interface */
1684     return IRpcChannelBuffer_GetBuffer(This->pDelegateChannel, olemsg, &This->tmarshal_iid);
1685 }
1686
1687 static HRESULT WINAPI TMarshalDispatchChannel_SendReceive(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE *olemsg, ULONG *pstatus)
1688 {
1689     TMarshalDispatchChannel *This = (TMarshalDispatchChannel *)iface;
1690     TRACE("(%p, %p)\n", olemsg, pstatus);
1691     return IRpcChannelBuffer_SendReceive(This->pDelegateChannel, olemsg, pstatus);
1692 }
1693
1694 static HRESULT WINAPI TMarshalDispatchChannel_FreeBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg)
1695 {
1696     TMarshalDispatchChannel *This = (TMarshalDispatchChannel *)iface;
1697     TRACE("(%p)\n", olemsg);
1698     return IRpcChannelBuffer_FreeBuffer(This->pDelegateChannel, olemsg);
1699 }
1700
1701 static HRESULT WINAPI TMarshalDispatchChannel_GetDestCtx(LPRPCCHANNELBUFFER iface, DWORD* pdwDestContext, void** ppvDestContext)
1702 {
1703     TMarshalDispatchChannel *This = (TMarshalDispatchChannel *)iface;
1704     TRACE("(%p,%p)\n", pdwDestContext, ppvDestContext);
1705     return IRpcChannelBuffer_GetDestCtx(This->pDelegateChannel, pdwDestContext, ppvDestContext);
1706 }
1707
1708 static HRESULT WINAPI TMarshalDispatchChannel_IsConnected(LPRPCCHANNELBUFFER iface)
1709 {
1710     TMarshalDispatchChannel *This = (TMarshalDispatchChannel *)iface;
1711     TRACE("()\n");
1712     return IRpcChannelBuffer_IsConnected(This->pDelegateChannel);
1713 }
1714
1715 static const IRpcChannelBufferVtbl TMarshalDispatchChannelVtbl =
1716 {
1717     TMarshalDispatchChannel_QueryInterface,
1718     TMarshalDispatchChannel_AddRef,
1719     TMarshalDispatchChannel_Release,
1720     TMarshalDispatchChannel_GetBuffer,
1721     TMarshalDispatchChannel_SendReceive,
1722     TMarshalDispatchChannel_FreeBuffer,
1723     TMarshalDispatchChannel_GetDestCtx,
1724     TMarshalDispatchChannel_IsConnected
1725 };
1726
1727 static HRESULT TMarshalDispatchChannel_Create(
1728     IRpcChannelBuffer *pDelegateChannel, REFIID tmarshal_riid,
1729     IRpcChannelBuffer **ppChannel)
1730 {
1731     TMarshalDispatchChannel *This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
1732     if (!This)
1733         return E_OUTOFMEMORY;
1734
1735     This->lpVtbl = &TMarshalDispatchChannelVtbl;
1736     This->refs = 1;
1737     IRpcChannelBuffer_AddRef(pDelegateChannel);
1738     This->pDelegateChannel = pDelegateChannel;
1739     This->tmarshal_iid = *tmarshal_riid;
1740
1741     *ppChannel = (IRpcChannelBuffer *)&This->lpVtbl;
1742     return S_OK;
1743 }
1744
1745
1746 static inline HRESULT get_facbuf_for_iid(REFIID riid, IPSFactoryBuffer **facbuf)
1747 {
1748     HRESULT       hr;
1749     CLSID         clsid;
1750
1751     if ((hr = CoGetPSClsid(riid, &clsid)))
1752         return hr;
1753     return CoGetClassObject(&clsid, CLSCTX_INPROC_SERVER, NULL,
1754                              &IID_IPSFactoryBuffer, (LPVOID*)facbuf);
1755 }
1756
1757 static HRESULT init_proxy_entry_point(TMProxyImpl *proxy, unsigned int num)
1758 {
1759     int j;
1760     /* nrofargs without This */
1761     int nrofargs;
1762     ITypeInfo *tinfo2;
1763     TMAsmProxy  *xasm = proxy->asmstubs + num;
1764     HRESULT hres;
1765     const FUNCDESC *fdesc;
1766
1767     hres = get_funcdesc(proxy->tinfo, num, &tinfo2, &fdesc, NULL, NULL, NULL);
1768     if (hres) {
1769         ERR("GetFuncDesc %x should not fail here.\n",hres);
1770         return hres;
1771     }
1772     ITypeInfo_Release(tinfo2);
1773     /* some args take more than 4 byte on the stack */
1774     nrofargs = 0;
1775     for (j=0;j<fdesc->cParams;j++)
1776         nrofargs += _argsize(&fdesc->lprgelemdescParam[j].tdesc, proxy->tinfo);
1777
1778 #ifdef __i386__
1779     if (fdesc->callconv != CC_STDCALL) {
1780         ERR("calling convention is not stdcall????\n");
1781         return E_FAIL;
1782     }
1783 /* popl %eax    -       return ptr
1784  * pushl <nr>
1785  * pushl %eax
1786  * call xCall
1787  * lret <nr> (+4)
1788  *
1789  *
1790  * arg3 arg2 arg1 <method> <returnptr>
1791  */
1792     xasm->popleax       = 0x58;
1793     xasm->pushlval      = 0x68;
1794     xasm->nr            = num;
1795     xasm->pushleax      = 0x50;
1796     xasm->lcall         = 0xe8; /* relative jump */
1797     xasm->xcall         = (DWORD)xCall;
1798     xasm->xcall        -= (DWORD)&(xasm->lret);
1799     xasm->lret          = 0xc2;
1800     xasm->bytestopop    = (nrofargs+2)*4; /* pop args, This, iMethod */
1801     xasm->nop           = 0x90;
1802     proxy->lpvtbl[num]  = xasm;
1803 #else
1804     FIXME("not implemented on non i386\n");
1805     return E_FAIL;
1806 #endif
1807     return S_OK;
1808 }
1809
1810 static HRESULT WINAPI
1811 PSFacBuf_CreateProxy(
1812     LPPSFACTORYBUFFER iface, IUnknown* pUnkOuter, REFIID riid,
1813     IRpcProxyBuffer **ppProxy, LPVOID *ppv)
1814 {
1815     HRESULT     hres;
1816     ITypeInfo   *tinfo;
1817     unsigned int i, nroffuncs;
1818     TMProxyImpl *proxy;
1819     TYPEATTR    *typeattr;
1820     BOOL        defer_to_dispatch = FALSE;
1821
1822     TRACE("(...%s...)\n",debugstr_guid(riid));
1823     hres = _get_typeinfo_for_iid(riid,&tinfo);
1824     if (hres) {
1825         ERR("No typeinfo for %s?\n",debugstr_guid(riid));
1826         return hres;
1827     }
1828
1829     hres = num_of_funcs(tinfo, &nroffuncs);
1830     if (FAILED(hres)) {
1831         ERR("Cannot get number of functions for typeinfo %s\n",debugstr_guid(riid));
1832         ITypeInfo_Release(tinfo);
1833         return hres;
1834     }
1835
1836     proxy = CoTaskMemAlloc(sizeof(TMProxyImpl));
1837     if (!proxy) return E_OUTOFMEMORY;
1838
1839     assert(sizeof(TMAsmProxy) == 16);
1840
1841     proxy->dispatch = NULL;
1842     proxy->dispatch_proxy = NULL;
1843     proxy->outerunknown = pUnkOuter;
1844     proxy->asmstubs = VirtualAlloc(NULL, sizeof(TMAsmProxy) * nroffuncs, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
1845     if (!proxy->asmstubs) {
1846         ERR("Could not commit pages for proxy thunks\n");
1847         CoTaskMemFree(proxy);
1848         return E_OUTOFMEMORY;
1849     }
1850     proxy->lpvtbl2      = &tmproxyvtable;
1851     /* one reference for the proxy */
1852     proxy->ref          = 1;
1853     proxy->tinfo        = tinfo;
1854     proxy->iid          = *riid;
1855     proxy->chanbuf      = 0;
1856
1857     InitializeCriticalSection(&proxy->crit);
1858     proxy->crit.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": TMProxyImpl.crit");
1859
1860     proxy->lpvtbl = HeapAlloc(GetProcessHeap(),0,sizeof(LPBYTE)*nroffuncs);
1861
1862     /* if we derive from IDispatch then defer to its proxy for its methods */
1863     hres = ITypeInfo_GetTypeAttr(tinfo, &typeattr);
1864     if (hres == S_OK)
1865     {
1866         if (typeattr->wTypeFlags & TYPEFLAG_FDISPATCHABLE)
1867         {
1868             IPSFactoryBuffer *factory_buffer;
1869             hres = get_facbuf_for_iid(&IID_IDispatch, &factory_buffer);
1870             if (hres == S_OK)
1871             {
1872                 hres = IPSFactoryBuffer_CreateProxy(factory_buffer, NULL,
1873                     &IID_IDispatch, &proxy->dispatch_proxy,
1874                     (void **)&proxy->dispatch);
1875                 IPSFactoryBuffer_Release(factory_buffer);
1876             }
1877             if ((hres == S_OK) && (nroffuncs < 7))
1878             {
1879                 ERR("nroffuncs calculated incorrectly (%d)\n", nroffuncs);
1880                 hres = E_UNEXPECTED;
1881             }
1882             if (hres == S_OK)
1883             {
1884                 defer_to_dispatch = TRUE;
1885             }
1886         }
1887         ITypeInfo_ReleaseTypeAttr(tinfo, typeattr);
1888     }
1889
1890     for (i=0;i<nroffuncs;i++) {
1891         switch (i) {
1892         case 0:
1893                 proxy->lpvtbl[i] = ProxyIUnknown_QueryInterface;
1894                 break;
1895         case 1:
1896                 proxy->lpvtbl[i] = ProxyIUnknown_AddRef;
1897                 break;
1898         case 2:
1899                 proxy->lpvtbl[i] = ProxyIUnknown_Release;
1900                 break;
1901         case 3:
1902                 if(!defer_to_dispatch)
1903                 {
1904                     hres = init_proxy_entry_point(proxy, i);
1905                     if(FAILED(hres)) return hres;
1906                 }
1907                 else proxy->lpvtbl[3] = ProxyIDispatch_GetTypeInfoCount;
1908                 break;
1909         case 4:
1910                 if(!defer_to_dispatch)
1911                 {
1912                     hres = init_proxy_entry_point(proxy, i);
1913                     if(FAILED(hres)) return hres;
1914                 }
1915                 else proxy->lpvtbl[4] = ProxyIDispatch_GetTypeInfo;
1916                 break;
1917         case 5:
1918                 if(!defer_to_dispatch)
1919                 {
1920                     hres = init_proxy_entry_point(proxy, i);
1921                     if(FAILED(hres)) return hres;
1922                 }
1923                 else proxy->lpvtbl[5] = ProxyIDispatch_GetIDsOfNames;
1924                 break;
1925         case 6:
1926                 if(!defer_to_dispatch)
1927                 {
1928                     hres = init_proxy_entry_point(proxy, i);
1929                     if(FAILED(hres)) return hres;
1930                 }
1931                 else proxy->lpvtbl[6] = ProxyIDispatch_Invoke;
1932                 break;
1933         default:
1934                 hres = init_proxy_entry_point(proxy, i);
1935                 if(FAILED(hres)) return hres;
1936         }
1937     }
1938
1939     if (hres == S_OK)
1940     {
1941         *ppv = proxy;
1942         *ppProxy = (IRpcProxyBuffer *)&(proxy->lpvtbl2);
1943         IUnknown_AddRef((IUnknown *)*ppv);
1944         return S_OK;
1945     }
1946     else
1947         TMProxyImpl_Release((IRpcProxyBuffer *)&proxy->lpvtbl2);
1948     return hres;
1949 }
1950
1951 typedef struct _TMStubImpl {
1952     const IRpcStubBufferVtbl   *lpvtbl;
1953     LONG                        ref;
1954
1955     LPUNKNOWN                   pUnk;
1956     ITypeInfo                   *tinfo;
1957     IID                         iid;
1958     IRpcStubBuffer              *dispatch_stub;
1959     BOOL                        dispatch_derivative;
1960 } TMStubImpl;
1961
1962 static HRESULT WINAPI
1963 TMStubImpl_QueryInterface(LPRPCSTUBBUFFER iface, REFIID riid, LPVOID *ppv)
1964 {
1965     if (IsEqualIID(riid,&IID_IRpcStubBuffer)||IsEqualIID(riid,&IID_IUnknown)){
1966         *ppv = iface;
1967         IRpcStubBuffer_AddRef(iface);
1968         return S_OK;
1969     }
1970     FIXME("%s, not supported IID.\n",debugstr_guid(riid));
1971     return E_NOINTERFACE;
1972 }
1973
1974 static ULONG WINAPI
1975 TMStubImpl_AddRef(LPRPCSTUBBUFFER iface)
1976 {
1977     TMStubImpl *This = (TMStubImpl *)iface;
1978     ULONG refCount = InterlockedIncrement(&This->ref);
1979         
1980     TRACE("(%p)->(ref before=%u)\n", This, refCount - 1);
1981
1982     return refCount;
1983 }
1984
1985 static ULONG WINAPI
1986 TMStubImpl_Release(LPRPCSTUBBUFFER iface)
1987 {
1988     TMStubImpl *This = (TMStubImpl *)iface;
1989     ULONG refCount = InterlockedDecrement(&This->ref);
1990
1991     TRACE("(%p)->(ref before=%u)\n", This, refCount + 1);
1992
1993     if (!refCount)
1994     {
1995         IRpcStubBuffer_Disconnect(iface);
1996         ITypeInfo_Release(This->tinfo);
1997         if (This->dispatch_stub)
1998             IRpcStubBuffer_Release(This->dispatch_stub);
1999         CoTaskMemFree(This);
2000     }
2001     return refCount;
2002 }
2003
2004 static HRESULT WINAPI
2005 TMStubImpl_Connect(LPRPCSTUBBUFFER iface, LPUNKNOWN pUnkServer)
2006 {
2007     TMStubImpl *This = (TMStubImpl *)iface;
2008
2009     TRACE("(%p)->(%p)\n", This, pUnkServer);
2010
2011     IUnknown_AddRef(pUnkServer);
2012     This->pUnk = pUnkServer;
2013
2014     if (This->dispatch_stub)
2015         IRpcStubBuffer_Connect(This->dispatch_stub, pUnkServer);
2016
2017     return S_OK;
2018 }
2019
2020 static void WINAPI
2021 TMStubImpl_Disconnect(LPRPCSTUBBUFFER iface)
2022 {
2023     TMStubImpl *This = (TMStubImpl *)iface;
2024
2025     TRACE("(%p)->()\n", This);
2026
2027     if (This->pUnk)
2028     {
2029         IUnknown_Release(This->pUnk);
2030         This->pUnk = NULL;
2031     }
2032
2033     if (This->dispatch_stub)
2034         IRpcStubBuffer_Disconnect(This->dispatch_stub);
2035 }
2036
2037 static HRESULT WINAPI
2038 TMStubImpl_Invoke(
2039     LPRPCSTUBBUFFER iface, RPCOLEMESSAGE* xmsg,IRpcChannelBuffer*rpcchanbuf)
2040 {
2041 #ifdef __i386__
2042     int         i;
2043     const FUNCDESC *fdesc;
2044     TMStubImpl *This = (TMStubImpl *)iface;
2045     HRESULT     hres;
2046     DWORD       *args = NULL, res, *xargs, nrofargs;
2047     marshal_state       buf;
2048     UINT        nrofnames = 0;
2049     BSTR        names[10];
2050     BSTR        iname = NULL;
2051     ITypeInfo   *tinfo = NULL;
2052
2053     TRACE("...\n");
2054
2055     if (xmsg->iMethod < 3) {
2056         ERR("IUnknown methods cannot be marshaled by the typelib marshaler\n");
2057         return E_UNEXPECTED;
2058     }
2059
2060     if (This->dispatch_derivative && xmsg->iMethod < sizeof(IDispatchVtbl)/sizeof(void *))
2061     {
2062         IPSFactoryBuffer *factory_buffer;
2063         hres = get_facbuf_for_iid(&IID_IDispatch, &factory_buffer);
2064         if (hres == S_OK)
2065         {
2066             hres = IPSFactoryBuffer_CreateStub(factory_buffer, &IID_IDispatch,
2067                 This->pUnk, &This->dispatch_stub);
2068             IPSFactoryBuffer_Release(factory_buffer);
2069         }
2070         if (hres != S_OK)
2071             return hres;
2072         return IRpcStubBuffer_Invoke(This->dispatch_stub, xmsg, rpcchanbuf);
2073     }
2074
2075     memset(&buf,0,sizeof(buf));
2076     buf.size    = xmsg->cbBuffer;
2077     buf.base    = HeapAlloc(GetProcessHeap(), 0, xmsg->cbBuffer);
2078     memcpy(buf.base, xmsg->Buffer, xmsg->cbBuffer);
2079     buf.curoff  = 0;
2080
2081     hres = get_funcdesc(This->tinfo,xmsg->iMethod,&tinfo,&fdesc,&iname,NULL,NULL);
2082     if (hres) {
2083         ERR("GetFuncDesc on method %d failed with %x\n",xmsg->iMethod,hres);
2084         return hres;
2085     }
2086
2087     if (iname && !lstrcmpW(iname, IDispatchW))
2088     {
2089         ERR("IDispatch cannot be marshaled by the typelib marshaler\n");
2090         hres = E_UNEXPECTED;
2091         SysFreeString (iname);
2092         goto exit;
2093     }
2094
2095     SysFreeString (iname);
2096
2097     /* Need them for hack below */
2098     memset(names,0,sizeof(names));
2099     ITypeInfo_GetNames(tinfo,fdesc->memid,names,sizeof(names)/sizeof(names[0]),&nrofnames);
2100     if (nrofnames > sizeof(names)/sizeof(names[0])) {
2101         ERR("Need more names!\n");
2102     }
2103
2104     /*dump_FUNCDESC(fdesc);*/
2105     nrofargs = 0;
2106     for (i=0;i<fdesc->cParams;i++)
2107         nrofargs += _argsize(&fdesc->lprgelemdescParam[i].tdesc, tinfo);
2108     args = HeapAlloc(GetProcessHeap(),0,(nrofargs+1)*sizeof(DWORD));
2109     if (!args)
2110     {
2111         hres = E_OUTOFMEMORY;
2112         goto exit;
2113     }
2114
2115     /* Allocate all stuff used by call. */
2116     xargs = args+1;
2117     for (i=0;i<fdesc->cParams;i++) {
2118         ELEMDESC        *elem = fdesc->lprgelemdescParam+i;
2119
2120         hres = deserialize_param(
2121            tinfo,
2122            is_in_elem(elem),
2123            FALSE,
2124            TRUE,
2125            &(elem->tdesc),
2126            xargs,
2127            &buf
2128         );
2129         xargs += _argsize(&elem->tdesc, tinfo);
2130         if (hres) {
2131             ERR("Failed to deserialize param %s, hres %x\n",relaystr(names[i+1]),hres);
2132             break;
2133         }
2134     }
2135
2136     args[0] = (DWORD)This->pUnk;
2137
2138     __TRY
2139     {
2140         res = _invoke(
2141             (*((FARPROC**)args[0]))[fdesc->oVft/4],
2142             fdesc->callconv,
2143             (xargs-args),
2144             args
2145         );
2146     }
2147     __EXCEPT_ALL
2148     {
2149         DWORD dwExceptionCode = GetExceptionCode();
2150         ERR("invoke call failed with exception 0x%08x (%d)\n", dwExceptionCode, dwExceptionCode);
2151         if (FAILED(dwExceptionCode))
2152             hres = dwExceptionCode;
2153         else
2154             hres = HRESULT_FROM_WIN32(dwExceptionCode);
2155     }
2156     __ENDTRY
2157
2158     if (hres != S_OK)
2159         goto exit;
2160
2161     buf.curoff = 0;
2162
2163     xargs = args+1;
2164     for (i=0;i<fdesc->cParams;i++) {
2165         ELEMDESC        *elem = fdesc->lprgelemdescParam+i;
2166         hres = serialize_param(
2167            tinfo,
2168            is_out_elem(elem),
2169            FALSE,
2170            TRUE,
2171            &elem->tdesc,
2172            xargs,
2173            &buf
2174         );
2175         xargs += _argsize(&elem->tdesc, tinfo);
2176         if (hres) {
2177             ERR("Failed to stuballoc param, hres %x\n",hres);
2178             break;
2179         }
2180     }
2181
2182     hres = xbuf_add (&buf, (LPBYTE)&res, sizeof(DWORD));
2183
2184     if (hres != S_OK)
2185         goto exit;
2186
2187     xmsg->cbBuffer      = buf.curoff;
2188     hres = IRpcChannelBuffer_GetBuffer(rpcchanbuf, xmsg, &This->iid);
2189     if (hres != S_OK)
2190         ERR("IRpcChannelBuffer_GetBuffer failed with error 0x%08x\n", hres);
2191
2192     if (hres == S_OK)
2193         memcpy(xmsg->Buffer, buf.base, buf.curoff);
2194
2195 exit:
2196     for (i = 0; i < nrofnames; i++)
2197         SysFreeString(names[i]);
2198
2199     ITypeInfo_Release(tinfo);
2200     HeapFree(GetProcessHeap(), 0, args);
2201
2202     HeapFree(GetProcessHeap(), 0, buf.base);
2203
2204     TRACE("returning\n");
2205     return hres;
2206 #else
2207     FIXME( "not implemented on non-i386\n" );
2208     return E_FAIL;
2209 #endif
2210 }
2211
2212 static LPRPCSTUBBUFFER WINAPI
2213 TMStubImpl_IsIIDSupported(LPRPCSTUBBUFFER iface, REFIID riid) {
2214     FIXME("Huh (%s)?\n",debugstr_guid(riid));
2215     return NULL;
2216 }
2217
2218 static ULONG WINAPI
2219 TMStubImpl_CountRefs(LPRPCSTUBBUFFER iface) {
2220     TMStubImpl *This = (TMStubImpl *)iface;
2221
2222     FIXME("()\n");
2223     return This->ref; /*FIXME? */
2224 }
2225
2226 static HRESULT WINAPI
2227 TMStubImpl_DebugServerQueryInterface(LPRPCSTUBBUFFER iface, LPVOID *ppv) {
2228     return E_NOTIMPL;
2229 }
2230
2231 static void WINAPI
2232 TMStubImpl_DebugServerRelease(LPRPCSTUBBUFFER iface, LPVOID ppv) {
2233     return;
2234 }
2235
2236 static const IRpcStubBufferVtbl tmstubvtbl = {
2237     TMStubImpl_QueryInterface,
2238     TMStubImpl_AddRef,
2239     TMStubImpl_Release,
2240     TMStubImpl_Connect,
2241     TMStubImpl_Disconnect,
2242     TMStubImpl_Invoke,
2243     TMStubImpl_IsIIDSupported,
2244     TMStubImpl_CountRefs,
2245     TMStubImpl_DebugServerQueryInterface,
2246     TMStubImpl_DebugServerRelease
2247 };
2248
2249 static HRESULT WINAPI
2250 PSFacBuf_CreateStub(
2251     LPPSFACTORYBUFFER iface, REFIID riid,IUnknown *pUnkServer,
2252     IRpcStubBuffer** ppStub
2253 ) {
2254     HRESULT hres;
2255     ITypeInfo   *tinfo;
2256     TMStubImpl  *stub;
2257     TYPEATTR *typeattr;
2258
2259     TRACE("(%s,%p,%p)\n",debugstr_guid(riid),pUnkServer,ppStub);
2260
2261     hres = _get_typeinfo_for_iid(riid,&tinfo);
2262     if (hres) {
2263         ERR("No typeinfo for %s?\n",debugstr_guid(riid));
2264         return hres;
2265     }
2266
2267     stub = CoTaskMemAlloc(sizeof(TMStubImpl));
2268     if (!stub)
2269         return E_OUTOFMEMORY;
2270     stub->lpvtbl        = &tmstubvtbl;
2271     stub->ref           = 1;
2272     stub->tinfo         = tinfo;
2273     stub->dispatch_stub = NULL;
2274     stub->dispatch_derivative = FALSE;
2275     stub->iid           = *riid;
2276     hres = IRpcStubBuffer_Connect((LPRPCSTUBBUFFER)stub,pUnkServer);
2277     *ppStub             = (LPRPCSTUBBUFFER)stub;
2278     TRACE("IRpcStubBuffer: %p\n", stub);
2279     if (hres)
2280         ERR("Connect to pUnkServer failed?\n");
2281
2282     /* if we derive from IDispatch then defer to its stub for some of its methods */
2283     hres = ITypeInfo_GetTypeAttr(tinfo, &typeattr);
2284     if (hres == S_OK)
2285     {
2286         if (typeattr->wTypeFlags & TYPEFLAG_FDISPATCHABLE)
2287             stub->dispatch_derivative = TRUE;
2288         ITypeInfo_ReleaseTypeAttr(tinfo, typeattr);
2289     }
2290
2291     return hres;
2292 }
2293
2294 static const IPSFactoryBufferVtbl psfacbufvtbl = {
2295     PSFacBuf_QueryInterface,
2296     PSFacBuf_AddRef,
2297     PSFacBuf_Release,
2298     PSFacBuf_CreateProxy,
2299     PSFacBuf_CreateStub
2300 };
2301
2302 /* This is the whole PSFactoryBuffer object, just the vtableptr */
2303 static const IPSFactoryBufferVtbl *lppsfac = &psfacbufvtbl;
2304
2305 /***********************************************************************
2306  *           TMARSHAL_DllGetClassObject
2307  */
2308 HRESULT TMARSHAL_DllGetClassObject(REFCLSID rclsid, REFIID iid,LPVOID *ppv)
2309 {
2310     if (IsEqualIID(iid,&IID_IPSFactoryBuffer)) {
2311         *ppv = &lppsfac;
2312         return S_OK;
2313     }
2314     return E_NOINTERFACE;
2315 }