oleaut32: Add some missing simple types to _argsize and _xsize.
[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,0);
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 = (LPVOID)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\\win32",tlguid,ver);
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 = (LPVOID)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     default:
528         return 1;
529     }
530 }
531
532 /* how much space do we use on the heap (in bytes) */
533 static int
534 _xsize(const TYPEDESC *td, ITypeInfo *tinfo) {
535     switch (td->vt) {
536     case VT_DATE:
537         return sizeof(DATE);
538     case VT_CY:
539         return sizeof(CY);
540     /* FIXME: VT_BOOL should return 2? */
541     case VT_VARIANT:
542         return sizeof(VARIANT)+3; /* FIXME: why the +3? */
543     case VT_CARRAY: {
544         int i, arrsize = 1;
545         const ARRAYDESC *adesc = td->u.lpadesc;
546
547         for (i=0;i<adesc->cDims;i++)
548             arrsize *= adesc->rgbounds[i].cElements;
549         return arrsize*_xsize(&adesc->tdescElem, tinfo);
550     }
551     case VT_UI8:
552     case VT_I8:
553     case VT_R8:
554         return 8;
555     case VT_UI2:
556     case VT_I2:
557         return 2;
558     case VT_UI1:
559     case VT_I1:
560         return 1;
561     default:
562         return 4;
563     }
564 }
565
566 static HRESULT
567 serialize_param(
568     ITypeInfo           *tinfo,
569     BOOL                writeit,
570     BOOL                debugout,
571     BOOL                dealloc,
572     TYPEDESC            *tdesc,
573     DWORD               *arg,
574     marshal_state       *buf)
575 {
576     HRESULT hres = S_OK;
577
578     TRACE("(tdesc.vt %s)\n",debugstr_vt(tdesc->vt));
579
580     switch (tdesc->vt) {
581     case VT_EMPTY: /* nothing. empty variant for instance */
582         return S_OK;
583     case VT_I8:
584     case VT_UI8:
585     case VT_R8:
586     case VT_CY:
587         hres = S_OK;
588         if (debugout) TRACE_(olerelay)("%x%x\n",arg[0],arg[1]);
589         if (writeit)
590             hres = xbuf_add(buf,(LPBYTE)arg,8);
591         return hres;
592     case VT_BOOL:
593     case VT_ERROR:
594     case VT_INT:
595     case VT_UINT:
596     case VT_I4:
597     case VT_R4:
598     case VT_UI4:
599         hres = S_OK;
600         if (debugout) TRACE_(olerelay)("%x\n",*arg);
601         if (writeit)
602             hres = xbuf_add(buf,(LPBYTE)arg,sizeof(DWORD));
603         return hres;
604     case VT_I2:
605     case VT_UI2:
606         hres = S_OK;
607         if (debugout) TRACE_(olerelay)("%04x\n",*arg & 0xffff);
608         if (writeit)
609             hres = xbuf_add(buf,(LPBYTE)arg,sizeof(DWORD));
610         return hres;
611     case VT_I1:
612     case VT_UI1:
613         hres = S_OK;
614         if (debugout) TRACE_(olerelay)("%02x\n",*arg & 0xff);
615         if (writeit)
616             hres = xbuf_add(buf,(LPBYTE)arg,sizeof(DWORD));
617         return hres;
618     case VT_I4|VT_BYREF:
619         hres = S_OK;
620         if (debugout) TRACE_(olerelay)("&0x%x\n",*arg);
621         if (writeit)
622             hres = xbuf_add(buf,(LPBYTE)(DWORD*)*arg,sizeof(DWORD));
623         /* do not dealloc at this time */
624         return hres;
625     case VT_VARIANT: {
626         TYPEDESC        tdesc2;
627         VARIANT         *vt = (VARIANT*)arg;
628         DWORD           vttype = V_VT(vt);
629
630         if (debugout) TRACE_(olerelay)("Vt(%s%s)(",debugstr_vt(vttype),debugstr_vf(vttype));
631         tdesc2.vt = vttype;
632         if (writeit) {
633             hres = xbuf_add(buf,(LPBYTE)&vttype,sizeof(vttype));
634             if (hres) return hres;
635         }
636         /* need to recurse since we need to free the stuff */
637         hres = serialize_param(tinfo,writeit,debugout,dealloc,&tdesc2,(DWORD*)&(V_I4(vt)),buf);
638         if (debugout) TRACE_(olerelay)(")");
639         return hres;
640     }
641     case VT_BSTR|VT_BYREF: {
642         if (debugout) TRACE_(olerelay)("[byref]'%s'", *(BSTR*)*arg ? relaystr(*((BSTR*)*arg)) : "<bstr NULL>");
643         if (writeit) {
644             /* ptr to ptr to magic widestring, basically */
645             BSTR *bstr = (BSTR *) *arg;
646             DWORD len;
647             if (!*bstr) {
648                 /* -1 means "null string" which is equivalent to empty string */
649                 len = -1;     
650                 hres = xbuf_add(buf, (LPBYTE)&len,sizeof(DWORD));
651                 if (hres) return hres;
652             } else {
653                 len = *((DWORD*)*bstr-1)/sizeof(WCHAR);
654                 hres = xbuf_add(buf,(LPBYTE)&len,sizeof(DWORD));
655                 if (hres) return hres;
656                 hres = xbuf_add(buf,(LPBYTE)*bstr,len * sizeof(WCHAR));
657                 if (hres) return hres;
658             }
659         }
660
661         if (dealloc && arg) {
662             BSTR *str = *((BSTR **)arg);
663             SysFreeString(*str);
664         }
665         return S_OK;
666     }
667     
668     case VT_BSTR: {
669         if (debugout) {
670             if (*arg)
671                    TRACE_(olerelay)("%s",relaystr((WCHAR*)*arg));
672             else
673                     TRACE_(olerelay)("<bstr NULL>");
674         }
675         if (writeit) {
676             BSTR bstr = (BSTR)*arg;
677             DWORD len;
678             if (!bstr) {
679                 len = -1;
680                 hres = xbuf_add(buf,(LPBYTE)&len,sizeof(DWORD));
681                 if (hres) return hres;
682             } else {
683                 len = *((DWORD*)bstr-1)/sizeof(WCHAR);
684                 hres = xbuf_add(buf,(LPBYTE)&len,sizeof(DWORD));
685                 if (hres) return hres;
686                 hres = xbuf_add(buf,(LPBYTE)bstr,len * sizeof(WCHAR));
687                 if (hres) return hres;
688             }
689         }
690
691         if (dealloc && arg)
692             SysFreeString((BSTR)*arg);
693         return S_OK;
694     }
695     case VT_PTR: {
696         DWORD cookie;
697         BOOL        derefhere = TRUE;
698
699         if (tdesc->u.lptdesc->vt == VT_USERDEFINED) {
700             ITypeInfo   *tinfo2;
701             TYPEATTR    *tattr;
702
703             hres = ITypeInfo_GetRefTypeInfo(tinfo,tdesc->u.lptdesc->u.hreftype,&tinfo2);
704             if (hres) {
705                 ERR("Could not get typeinfo of hreftype %x for VT_USERDEFINED.\n",tdesc->u.lptdesc->u.hreftype);
706                 return hres;
707             }
708             ITypeInfo_GetTypeAttr(tinfo2,&tattr);
709             switch (tattr->typekind) {
710             case TKIND_ALIAS:
711                 if (tattr->tdescAlias.vt == VT_USERDEFINED)
712                 {
713                     DWORD href = tattr->tdescAlias.u.hreftype;
714                     ITypeInfo_ReleaseTypeAttr(tinfo, tattr);
715                     ITypeInfo_Release(tinfo2);
716                     hres = ITypeInfo_GetRefTypeInfo(tinfo,href,&tinfo2);
717                     if (hres) {
718                         ERR("Could not get typeinfo of hreftype %x for VT_USERDEFINED.\n",tdesc->u.lptdesc->u.hreftype);
719                         return hres;
720                     }
721                     ITypeInfo_GetTypeAttr(tinfo2,&tattr);
722                     derefhere = (tattr->typekind != TKIND_DISPATCH && tattr->typekind != TKIND_INTERFACE);
723                 }
724                 break;
725             case TKIND_ENUM:    /* confirmed */
726             case TKIND_RECORD:  /* FIXME: mostly untested */
727                 break;
728             case TKIND_DISPATCH:        /* will be done in VT_USERDEFINED case */
729             case TKIND_INTERFACE:       /* will be done in VT_USERDEFINED case */
730                 derefhere=FALSE;
731                 break;
732             default:
733                 FIXME("unhandled switch cases tattr->typekind %d\n", tattr->typekind);
734                 derefhere=FALSE;
735                 break;
736             }
737             ITypeInfo_ReleaseTypeAttr(tinfo, tattr);
738             ITypeInfo_Release(tinfo2);
739         }
740
741         if (debugout) TRACE_(olerelay)("*");
742         /* Write always, so the other side knows when it gets a NULL pointer.
743          */
744         cookie = *arg ? 0x42424242 : 0;
745         hres = xbuf_add(buf,(LPBYTE)&cookie,sizeof(cookie));
746         if (hres)
747             return hres;
748         if (!*arg) {
749             if (debugout) TRACE_(olerelay)("NULL");
750             return S_OK;
751         }
752         hres = serialize_param(tinfo,writeit,debugout,dealloc,tdesc->u.lptdesc,(DWORD*)*arg,buf);
753         if (derefhere && dealloc) HeapFree(GetProcessHeap(),0,(LPVOID)*arg);
754         return hres;
755     }
756     case VT_UNKNOWN:
757         if (debugout) TRACE_(olerelay)("unk(0x%x)",*arg);
758         if (writeit)
759             hres = _marshal_interface(buf,&IID_IUnknown,(LPUNKNOWN)*arg);
760         if (dealloc && *(IUnknown **)arg)
761             IUnknown_Release((LPUNKNOWN)*arg);
762         return hres;
763     case VT_DISPATCH:
764         if (debugout) TRACE_(olerelay)("idisp(0x%x)",*arg);
765         if (writeit)
766             hres = _marshal_interface(buf,&IID_IDispatch,(LPUNKNOWN)*arg);
767         if (dealloc && *(IUnknown **)arg)
768             IUnknown_Release((LPUNKNOWN)*arg);
769         return hres;
770     case VT_VOID:
771         if (debugout) TRACE_(olerelay)("<void>");
772         return S_OK;
773     case VT_USERDEFINED: {
774         ITypeInfo       *tinfo2;
775         TYPEATTR        *tattr;
776
777         hres = ITypeInfo_GetRefTypeInfo(tinfo,tdesc->u.hreftype,&tinfo2);
778         if (hres) {
779             ERR("Could not get typeinfo of hreftype %x for VT_USERDEFINED.\n",tdesc->u.hreftype);
780             return hres;
781         }
782         ITypeInfo_GetTypeAttr(tinfo2,&tattr);
783         switch (tattr->typekind) {
784         case TKIND_DISPATCH:
785         case TKIND_INTERFACE:
786             if (writeit)
787                hres=_marshal_interface(buf,&(tattr->guid),(LPUNKNOWN)arg);
788             if (dealloc)
789                 IUnknown_Release((LPUNKNOWN)arg);
790             break;
791         case TKIND_RECORD: {
792             int i;
793             if (debugout) TRACE_(olerelay)("{");
794             for (i=0;i<tattr->cVars;i++) {
795                 VARDESC *vdesc;
796                 ELEMDESC *elem2;
797                 TYPEDESC *tdesc2;
798
799                 hres = ITypeInfo2_GetVarDesc(tinfo2, i, &vdesc);
800                 if (hres) {
801                     ERR("Could not get vardesc of %d\n",i);
802                     return hres;
803                 }
804                 elem2 = &vdesc->elemdescVar;
805                 tdesc2 = &elem2->tdesc;
806                 hres = serialize_param(
807                     tinfo2,
808                     writeit,
809                     debugout,
810                     dealloc,
811                     tdesc2,
812                     (DWORD*)(((LPBYTE)arg)+vdesc->u.oInst),
813                     buf
814                 );
815                 ITypeInfo_ReleaseVarDesc(tinfo2, vdesc);
816                 if (hres!=S_OK)
817                     return hres;
818                 if (debugout && (i<(tattr->cVars-1)))
819                     TRACE_(olerelay)(",");
820             }
821             if (debugout) TRACE_(olerelay)("}");
822             break;
823         }
824         case TKIND_ALIAS:
825             hres = serialize_param(tinfo2,writeit,debugout,dealloc,&tattr->tdescAlias,arg,buf);
826             break;
827         case TKIND_ENUM:
828             hres = S_OK;
829             if (debugout) TRACE_(olerelay)("%x",*arg);
830             if (writeit)
831                 hres = xbuf_add(buf,(LPBYTE)arg,sizeof(DWORD));
832             break;
833         default:
834             FIXME("Unhandled typekind %d\n",tattr->typekind);
835             hres = E_FAIL;
836             break;
837         }
838         ITypeInfo_ReleaseTypeAttr(tinfo2, tattr);
839         ITypeInfo_Release(tinfo2);
840         return hres;
841     }
842     case VT_CARRAY: {
843         ARRAYDESC *adesc = tdesc->u.lpadesc;
844         int i, arrsize = 1;
845
846         if (debugout) TRACE_(olerelay)("carr");
847         for (i=0;i<adesc->cDims;i++) {
848             if (debugout) TRACE_(olerelay)("[%d]",adesc->rgbounds[i].cElements);
849             arrsize *= adesc->rgbounds[i].cElements;
850         }
851         if (debugout) TRACE_(olerelay)("(vt %s)",debugstr_vt(adesc->tdescElem.vt));
852         if (debugout) TRACE_(olerelay)("[");
853         for (i=0;i<arrsize;i++) {
854             hres = serialize_param(tinfo, writeit, debugout, dealloc, &adesc->tdescElem, (DWORD*)((LPBYTE)arg+i*_xsize(&adesc->tdescElem, tinfo)), buf);
855             if (hres)
856                 return hres;
857             if (debugout && (i<arrsize-1)) TRACE_(olerelay)(",");
858         }
859         if (debugout) TRACE_(olerelay)("]");
860         return S_OK;
861     }
862     case VT_SAFEARRAY: {
863         if (writeit)
864         {
865             ULONG flags = MAKELONG(MSHCTX_DIFFERENTMACHINE, NDR_LOCAL_DATA_REPRESENTATION);
866             ULONG size = LPSAFEARRAY_UserSize(&flags, buf->curoff, (LPSAFEARRAY *)arg);
867             xbuf_resize(buf, size);
868             LPSAFEARRAY_UserMarshal(&flags, buf->base + buf->curoff, (LPSAFEARRAY *)arg);
869             buf->curoff = size;
870         }
871         return S_OK;
872     }
873     default:
874         ERR("Unhandled marshal type %d.\n",tdesc->vt);
875         return S_OK;
876     }
877 }
878
879 static HRESULT
880 deserialize_param(
881     ITypeInfo           *tinfo,
882     BOOL                readit,
883     BOOL                debugout,
884     BOOL                alloc,
885     TYPEDESC            *tdesc,
886     DWORD               *arg,
887     marshal_state       *buf)
888 {
889     HRESULT hres = S_OK;
890
891     TRACE("vt %s at %p\n",debugstr_vt(tdesc->vt),arg);
892
893     while (1) {
894         switch (tdesc->vt) {
895         case VT_EMPTY:
896             if (debugout) TRACE_(olerelay)("<empty>\n");
897             return S_OK;
898         case VT_NULL:
899             if (debugout) TRACE_(olerelay)("<null>\n");
900             return S_OK;
901         case VT_VARIANT: {
902             VARIANT     *vt = (VARIANT*)arg;
903
904             if (readit) {
905                 DWORD   vttype;
906                 TYPEDESC        tdesc2;
907                 hres = xbuf_get(buf,(LPBYTE)&vttype,sizeof(vttype));
908                 if (hres) {
909                     FIXME("vt type not read?\n");
910                     return hres;
911                 }
912                 memset(&tdesc2,0,sizeof(tdesc2));
913                 tdesc2.vt = vttype;
914                 V_VT(vt)  = vttype;
915                 if (debugout) TRACE_(olerelay)("Vt(%s%s)(",debugstr_vt(vttype),debugstr_vf(vttype));
916                 hres = deserialize_param(tinfo, readit, debugout, alloc, &tdesc2, (DWORD*)&(V_I4(vt)), buf);
917                 TRACE_(olerelay)(")");
918                 return hres;
919             } else {
920                 VariantInit(vt);
921                 return S_OK;
922             }
923         }
924         case VT_I8:
925         case VT_UI8:
926         case VT_R8:
927         case VT_CY:
928             if (readit) {
929                 hres = xbuf_get(buf,(LPBYTE)arg,8);
930                 if (hres) ERR("Failed to read integer 8 byte\n");
931             }
932             if (debugout) TRACE_(olerelay)("%x%x",arg[0],arg[1]);
933             return hres;
934         case VT_ERROR:
935         case VT_BOOL:
936         case VT_I4:
937         case VT_INT:
938         case VT_UINT:
939         case VT_R4:
940         case VT_UI4:
941             if (readit) {
942                 hres = xbuf_get(buf,(LPBYTE)arg,sizeof(DWORD));
943                 if (hres) ERR("Failed to read integer 4 byte\n");
944             }
945             if (debugout) TRACE_(olerelay)("%x",*arg);
946             return hres;
947         case VT_I2:
948         case VT_UI2:
949             if (readit) {
950                 DWORD x;
951                 hres = xbuf_get(buf,(LPBYTE)&x,sizeof(DWORD));
952                 if (hres) ERR("Failed to read integer 4 byte\n");
953                 memcpy(arg,&x,2);
954             }
955             if (debugout) TRACE_(olerelay)("%04x",*arg & 0xffff);
956             return hres;
957         case VT_I1:
958         case VT_UI1:
959             if (readit) {
960                 DWORD x;
961                 hres = xbuf_get(buf,(LPBYTE)&x,sizeof(DWORD));
962                 if (hres) ERR("Failed to read integer 4 byte\n");
963                 memcpy(arg,&x,1);
964             }
965             if (debugout) TRACE_(olerelay)("%02x",*arg & 0xff);
966             return hres;
967         case VT_I4|VT_BYREF:
968             hres = S_OK;
969             if (alloc)
970                 *arg = (DWORD)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(DWORD));
971             if (readit) {
972                 hres = xbuf_get(buf,(LPBYTE)*arg,sizeof(DWORD));
973                 if (hres) ERR("Failed to read integer 4 byte\n");
974             }
975             if (debugout) TRACE_(olerelay)("&0x%x",*(DWORD*)*arg);
976             return hres;
977         case VT_BSTR|VT_BYREF: {
978             BSTR **bstr = (BSTR **)arg;
979             WCHAR       *str;
980             DWORD       len;
981
982             if (readit) {
983                 hres = xbuf_get(buf,(LPBYTE)&len,sizeof(DWORD));
984                 if (hres) {
985                     ERR("failed to read bstr klen\n");
986                     return hres;
987                 }
988                 if (len == -1) {
989                     *bstr = CoTaskMemAlloc(sizeof(BSTR *));
990                     **bstr = NULL;
991                     if (debugout) TRACE_(olerelay)("<bstr NULL>");
992                 } else {
993                     str  = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,(len+1)*sizeof(WCHAR));
994                     hres = xbuf_get(buf,(LPBYTE)str,len*sizeof(WCHAR));
995                     if (hres) {
996                         ERR("Failed to read BSTR.\n");
997                         HeapFree(GetProcessHeap(),0,str);
998                         return hres;
999                     }
1000                     *bstr = CoTaskMemAlloc(sizeof(BSTR *));
1001                     **bstr = SysAllocStringLen(str,len);
1002                     if (debugout) TRACE_(olerelay)("%s",relaystr(str));
1003                     HeapFree(GetProcessHeap(),0,str);
1004                 }
1005             } else {
1006                 *bstr = NULL;
1007             }
1008             return S_OK;
1009         }
1010         case VT_BSTR: {
1011             WCHAR       *str;
1012             DWORD       len;
1013
1014             if (readit) {
1015                 hres = xbuf_get(buf,(LPBYTE)&len,sizeof(DWORD));
1016                 if (hres) {
1017                     ERR("failed to read bstr klen\n");
1018                     return hres;
1019                 }
1020                 if (len == -1) {
1021                     *arg = 0;
1022                     if (debugout) TRACE_(olerelay)("<bstr NULL>");
1023                 } else {
1024                     str  = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,(len+1)*sizeof(WCHAR));
1025                     hres = xbuf_get(buf,(LPBYTE)str,len*sizeof(WCHAR));
1026                     if (hres) {
1027                         ERR("Failed to read BSTR.\n");
1028                         HeapFree(GetProcessHeap(),0,str);
1029                         return hres;
1030                     }
1031                     *arg = (DWORD)SysAllocStringLen(str,len);
1032                     if (debugout) TRACE_(olerelay)("%s",relaystr(str));
1033                     HeapFree(GetProcessHeap(),0,str);
1034                 }
1035             } else {
1036                 *arg = 0;
1037             }
1038             return S_OK;
1039         }
1040         case VT_PTR: {
1041             DWORD       cookie;
1042             BOOL        derefhere = TRUE;
1043
1044             if (tdesc->u.lptdesc->vt == VT_USERDEFINED) {
1045                 ITypeInfo       *tinfo2;
1046                 TYPEATTR        *tattr;
1047
1048                 hres = ITypeInfo_GetRefTypeInfo(tinfo,tdesc->u.lptdesc->u.hreftype,&tinfo2);
1049                 if (hres) {
1050                     ERR("Could not get typeinfo of hreftype %x for VT_USERDEFINED.\n",tdesc->u.lptdesc->u.hreftype);
1051                     return hres;
1052                 }
1053                 ITypeInfo_GetTypeAttr(tinfo2,&tattr);
1054                 switch (tattr->typekind) {
1055                 case TKIND_ALIAS:
1056                     if (tattr->tdescAlias.vt == VT_USERDEFINED)
1057                     {
1058                         DWORD href = tattr->tdescAlias.u.hreftype;
1059                         ITypeInfo_ReleaseTypeAttr(tinfo, tattr);
1060                         ITypeInfo_Release(tinfo2);
1061                         hres = ITypeInfo_GetRefTypeInfo(tinfo,href,&tinfo2);
1062                         if (hres) {
1063                             ERR("Could not get typeinfo of hreftype %x for VT_USERDEFINED.\n",tdesc->u.lptdesc->u.hreftype);
1064                             return hres;
1065                         }
1066                         ITypeInfo_GetTypeAttr(tinfo2,&tattr);
1067                         derefhere = (tattr->typekind != TKIND_DISPATCH && tattr->typekind != TKIND_INTERFACE);
1068                     }
1069                     break;
1070                 case TKIND_ENUM:        /* confirmed */
1071                 case TKIND_RECORD:      /* FIXME: mostly untested */
1072                     break;
1073                 case TKIND_DISPATCH:    /* will be done in VT_USERDEFINED case */
1074                 case TKIND_INTERFACE:   /* will be done in VT_USERDEFINED case */
1075                     derefhere=FALSE;
1076                     break;
1077                 default:
1078                     FIXME("unhandled switch cases tattr->typekind %d\n", tattr->typekind);
1079                     derefhere=FALSE;
1080                     break;
1081                 }
1082                 ITypeInfo_ReleaseTypeAttr(tinfo2, tattr);
1083                 ITypeInfo_Release(tinfo2);
1084             }
1085             /* read it in all cases, we need to know if we have 
1086              * NULL pointer or not.
1087              */
1088             hres = xbuf_get(buf,(LPBYTE)&cookie,sizeof(cookie));
1089             if (hres) {
1090                 ERR("Failed to load pointer cookie.\n");
1091                 return hres;
1092             }
1093             if (cookie != 0x42424242) {
1094                 /* we read a NULL ptr from the remote side */
1095                 if (debugout) TRACE_(olerelay)("NULL");
1096                 *arg = 0;
1097                 return S_OK;
1098             }
1099             if (debugout) TRACE_(olerelay)("*");
1100             if (alloc) {
1101                 /* Allocate space for the referenced struct */
1102                 if (derefhere)
1103                     *arg=(DWORD)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,_xsize(tdesc->u.lptdesc, tinfo));
1104             }
1105             if (derefhere)
1106                 return deserialize_param(tinfo, readit, debugout, alloc, tdesc->u.lptdesc, (LPDWORD)*arg, buf);
1107             else
1108                 return deserialize_param(tinfo, readit, debugout, alloc, tdesc->u.lptdesc, arg, buf);
1109         }
1110         case VT_UNKNOWN:
1111             /* FIXME: UNKNOWN is unknown ..., but allocate 4 byte for it */
1112             if (alloc)
1113                 *arg=(DWORD)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(DWORD));
1114             hres = S_OK;
1115             if (readit)
1116                 hres = _unmarshal_interface(buf,&IID_IUnknown,(LPUNKNOWN*)arg);
1117             if (debugout)
1118                 TRACE_(olerelay)("unk(%p)",arg);
1119             return hres;
1120         case VT_DISPATCH:
1121             hres = S_OK;
1122             if (readit)
1123                 hres = _unmarshal_interface(buf,&IID_IDispatch,(LPUNKNOWN*)arg);
1124             if (debugout)
1125                 TRACE_(olerelay)("idisp(%p)",arg);
1126             return hres;
1127         case VT_VOID:
1128             if (debugout) TRACE_(olerelay)("<void>");
1129             return S_OK;
1130         case VT_USERDEFINED: {
1131             ITypeInfo   *tinfo2;
1132             TYPEATTR    *tattr;
1133
1134             hres = ITypeInfo_GetRefTypeInfo(tinfo,tdesc->u.hreftype,&tinfo2);
1135             if (hres) {
1136                 ERR("Could not get typeinfo of hreftype %x for VT_USERDEFINED.\n",tdesc->u.hreftype);
1137                 return hres;
1138             }
1139             hres = ITypeInfo_GetTypeAttr(tinfo2,&tattr);
1140             if (hres) {
1141                 ERR("Could not get typeattr in VT_USERDEFINED.\n");
1142             } else {
1143                 switch (tattr->typekind) {
1144                 case TKIND_DISPATCH:
1145                 case TKIND_INTERFACE:
1146                     if (readit)
1147                         hres = _unmarshal_interface(buf,&(tattr->guid),(LPUNKNOWN*)arg);
1148                     break;
1149                 case TKIND_RECORD: {
1150                     int i;
1151
1152                     if (alloc)
1153                         *arg = (DWORD)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,tattr->cbSizeInstance);
1154
1155                     if (debugout) TRACE_(olerelay)("{");
1156                     for (i=0;i<tattr->cVars;i++) {
1157                         VARDESC *vdesc;
1158
1159                         hres = ITypeInfo2_GetVarDesc(tinfo2, i, &vdesc);
1160                         if (hres) {
1161                             ERR("Could not get vardesc of %d\n",i);
1162                             ITypeInfo_ReleaseTypeAttr(tinfo2, tattr);
1163                             ITypeInfo_Release(tinfo2);
1164                             return hres;
1165                         }
1166                         hres = deserialize_param(
1167                             tinfo2,
1168                             readit,
1169                             debugout,
1170                             alloc,
1171                             &vdesc->elemdescVar.tdesc,
1172                             (DWORD*)(((LPBYTE)*arg)+vdesc->u.oInst),
1173                             buf
1174                         );
1175                         ITypeInfo2_ReleaseVarDesc(tinfo2, vdesc);
1176                         if (debugout && (i<tattr->cVars-1)) TRACE_(olerelay)(",");
1177                     }
1178                     if (debugout) TRACE_(olerelay)("}");
1179                     break;
1180                 }
1181                 case TKIND_ALIAS:
1182                     hres = deserialize_param(tinfo2,readit,debugout,alloc,&tattr->tdescAlias,arg,buf);
1183                     break;
1184                 case TKIND_ENUM:
1185                     if (readit) {
1186                         hres = xbuf_get(buf,(LPBYTE)arg,sizeof(DWORD));
1187                         if (hres) ERR("Failed to read enum (4 byte)\n");
1188                     }
1189                     if (debugout) TRACE_(olerelay)("%x",*arg);
1190                     break;
1191                 default:
1192                     ERR("Unhandled typekind %d\n",tattr->typekind);
1193                     hres = E_FAIL;
1194                     break;
1195                 }
1196                 ITypeInfo_ReleaseTypeAttr(tinfo2, tattr);
1197             }
1198             if (hres)
1199                 ERR("failed to stuballoc in TKIND_RECORD.\n");
1200             ITypeInfo_Release(tinfo2);
1201             return hres;
1202         }
1203         case VT_CARRAY: {
1204             /* arg is pointing to the start of the array. */
1205             ARRAYDESC *adesc = tdesc->u.lpadesc;
1206             int         arrsize,i;
1207             arrsize = 1;
1208             if (adesc->cDims > 1) FIXME("cDims > 1 in VT_CARRAY. Does it work?\n");
1209             for (i=0;i<adesc->cDims;i++)
1210                 arrsize *= adesc->rgbounds[i].cElements;
1211             for (i=0;i<arrsize;i++)
1212                 deserialize_param(
1213                     tinfo,
1214                     readit,
1215                     debugout,
1216                     alloc,
1217                     &adesc->tdescElem,
1218                     (DWORD*)((LPBYTE)(arg)+i*_xsize(&adesc->tdescElem, tinfo)),
1219                     buf
1220                 );
1221             return S_OK;
1222         }
1223     case VT_SAFEARRAY: {
1224             if (readit)
1225             {
1226                 ULONG flags = MAKELONG(MSHCTX_DIFFERENTMACHINE, NDR_LOCAL_DATA_REPRESENTATION);
1227                 unsigned char *buffer;
1228                 buffer = LPSAFEARRAY_UserUnmarshal(&flags, buf->base + buf->curoff, (LPSAFEARRAY *)arg);
1229                 buf->curoff = buffer - buf->base;
1230             }
1231             return S_OK;
1232         }
1233         default:
1234             ERR("No handler for VT type %d!\n",tdesc->vt);
1235             return S_OK;
1236         }
1237     }
1238 }
1239
1240 /* Retrieves a function's funcdesc, searching back into inherited interfaces. */
1241 static HRESULT get_funcdesc(ITypeInfo *tinfo, int iMethod, ITypeInfo **tactual, const FUNCDESC **fdesc,
1242                             BSTR *iname, BSTR *fname, UINT *num)
1243 {
1244     HRESULT hr;
1245     UINT i, impl_types;
1246     UINT inherited_funcs = 0;
1247     TYPEATTR *attr;
1248
1249     if (fname) *fname = NULL;
1250     if (iname) *iname = NULL;
1251     if (num) *num = 0;
1252     *tactual = NULL;
1253
1254     hr = ITypeInfo_GetTypeAttr(tinfo, &attr);
1255     if (FAILED(hr))
1256     {
1257         ERR("GetTypeAttr failed with %x\n",hr);
1258         return hr;
1259     }
1260
1261     if(attr->typekind == TKIND_DISPATCH)
1262     {
1263         if(attr->wTypeFlags & TYPEFLAG_FDUAL)
1264         {
1265             HREFTYPE href;
1266             ITypeInfo *tinfo2;
1267
1268             hr = ITypeInfo_GetRefTypeOfImplType(tinfo, -1, &href);
1269             if(FAILED(hr))
1270             {
1271                 ERR("Cannot get interface href from dual dispinterface\n");
1272                 ITypeInfo_ReleaseTypeAttr(tinfo, attr);
1273                 return hr;
1274             }
1275             hr = ITypeInfo_GetRefTypeInfo(tinfo, href, &tinfo2);
1276             if(FAILED(hr))
1277             {
1278                 ERR("Cannot get interface from dual dispinterface\n");
1279                 ITypeInfo_ReleaseTypeAttr(tinfo, attr);
1280                 return hr;
1281             }
1282             hr = get_funcdesc(tinfo2, iMethod, tactual, fdesc, iname, fname, num);
1283             ITypeInfo_Release(tinfo2);
1284             ITypeInfo_ReleaseTypeAttr(tinfo, attr);
1285             return hr;
1286         }
1287         ERR("Shouldn't be called with a non-dual dispinterface\n");
1288         return E_FAIL;
1289     }
1290
1291     impl_types = attr->cImplTypes;
1292     ITypeInfo_ReleaseTypeAttr(tinfo, attr);
1293
1294     for (i = 0; i < impl_types; i++)
1295     {
1296         HREFTYPE href;
1297         ITypeInfo *pSubTypeInfo;
1298         UINT sub_funcs;
1299
1300         hr = ITypeInfo_GetRefTypeOfImplType(tinfo, i, &href);
1301         if (FAILED(hr)) return hr;
1302         hr = ITypeInfo_GetRefTypeInfo(tinfo, href, &pSubTypeInfo);
1303         if (FAILED(hr)) return hr;
1304
1305         hr = get_funcdesc(pSubTypeInfo, iMethod, tactual, fdesc, iname, fname, &sub_funcs);
1306         inherited_funcs += sub_funcs;
1307         ITypeInfo_Release(pSubTypeInfo);
1308         if(SUCCEEDED(hr)) return hr;
1309     }
1310     if(iMethod < inherited_funcs)
1311     {
1312         ERR("shouldn't be here\n");
1313         return E_INVALIDARG;
1314     }
1315
1316     for(i = inherited_funcs; i <= iMethod; i++)
1317     {
1318         hr = ITypeInfoImpl_GetInternalFuncDesc(tinfo, i - inherited_funcs, fdesc);
1319         if(FAILED(hr))
1320         {
1321             if(num) *num = i;
1322             return hr;
1323         }
1324     }
1325
1326     /* found it. We don't care about num so zero it */
1327     if(num) *num = 0;
1328     *tactual = tinfo;
1329     ITypeInfo_AddRef(*tactual);
1330     if (fname) ITypeInfo_GetDocumentation(tinfo,(*fdesc)->memid,fname,NULL,NULL,NULL);
1331     if (iname) ITypeInfo_GetDocumentation(tinfo,-1,iname,NULL,NULL,NULL);
1332     return S_OK;
1333 }
1334
1335 static inline BOOL is_in_elem(const ELEMDESC *elem)
1336 {
1337     return (elem->u.paramdesc.wParamFlags & PARAMFLAG_FIN || !elem->u.paramdesc.wParamFlags);
1338 }
1339
1340 static inline BOOL is_out_elem(const ELEMDESC *elem)
1341 {
1342     return (elem->u.paramdesc.wParamFlags & PARAMFLAG_FOUT || !elem->u.paramdesc.wParamFlags);
1343 }
1344
1345 static DWORD
1346 xCall(LPVOID retptr, int method, TMProxyImpl *tpinfo /*, args */)
1347 {
1348     DWORD               *args = ((DWORD*)&tpinfo)+1, *xargs;
1349     const FUNCDESC      *fdesc;
1350     HRESULT             hres;
1351     int                 i, relaydeb = TRACE_ON(olerelay);
1352     marshal_state       buf;
1353     RPCOLEMESSAGE       msg;
1354     ULONG               status;
1355     BSTR                fname,iname;
1356     BSTR                names[10];
1357     UINT                nrofnames;
1358     DWORD               remoteresult = 0;
1359     ITypeInfo           *tinfo;
1360     IRpcChannelBuffer *chanbuf;
1361
1362     EnterCriticalSection(&tpinfo->crit);
1363
1364     hres = get_funcdesc(tpinfo->tinfo,method,&tinfo,&fdesc,&iname,&fname,NULL);
1365     if (hres) {
1366         ERR("Did not find typeinfo/funcdesc entry for method %d!\n",method);
1367         LeaveCriticalSection(&tpinfo->crit);
1368         return E_FAIL;
1369     }
1370
1371     if (!tpinfo->chanbuf)
1372     {
1373         WARN("Tried to use disconnected proxy\n");
1374         ITypeInfo_Release(tinfo);
1375         LeaveCriticalSection(&tpinfo->crit);
1376         return RPC_E_DISCONNECTED;
1377     }
1378     chanbuf = tpinfo->chanbuf;
1379     IRpcChannelBuffer_AddRef(chanbuf);
1380
1381     LeaveCriticalSection(&tpinfo->crit);
1382
1383     if (relaydeb) {
1384        TRACE_(olerelay)("->");
1385         if (iname)
1386             TRACE_(olerelay)("%s:",relaystr(iname));
1387         if (fname)
1388             TRACE_(olerelay)("%s(%d)",relaystr(fname),method);
1389         else
1390             TRACE_(olerelay)("%d",method);
1391         TRACE_(olerelay)("(");
1392     }
1393
1394     if (iname) SysFreeString(iname);
1395     if (fname) SysFreeString(fname);
1396
1397     memset(&buf,0,sizeof(buf));
1398
1399     /* normal typelib driven serializing */
1400
1401     /* Need them for hack below */
1402     memset(names,0,sizeof(names));
1403     if (ITypeInfo_GetNames(tinfo,fdesc->memid,names,sizeof(names)/sizeof(names[0]),&nrofnames))
1404         nrofnames = 0;
1405     if (nrofnames > sizeof(names)/sizeof(names[0]))
1406         ERR("Need more names!\n");
1407
1408     xargs = args;
1409     for (i=0;i<fdesc->cParams;i++) {
1410         ELEMDESC        *elem = fdesc->lprgelemdescParam+i;
1411         if (relaydeb) {
1412             if (i) TRACE_(olerelay)(",");
1413             if (i+1<nrofnames && names[i+1])
1414                 TRACE_(olerelay)("%s=",relaystr(names[i+1]));
1415         }
1416         /* No need to marshal other data than FIN and any VT_PTR. */
1417         if (!is_in_elem(elem) && (elem->tdesc.vt != VT_PTR)) {
1418             xargs+=_argsize(&elem->tdesc, tinfo);
1419             if (relaydeb) TRACE_(olerelay)("[out]");
1420             continue;
1421         }
1422         hres = serialize_param(
1423             tinfo,
1424             is_in_elem(elem),
1425             relaydeb,
1426             FALSE,
1427             &elem->tdesc,
1428             xargs,
1429             &buf
1430         );
1431
1432         if (hres) {
1433             ERR("Failed to serialize param, hres %x\n",hres);
1434             break;
1435         }
1436         xargs+=_argsize(&elem->tdesc, tinfo);
1437     }
1438     if (relaydeb) TRACE_(olerelay)(")");
1439
1440     memset(&msg,0,sizeof(msg));
1441     msg.cbBuffer = buf.curoff;
1442     msg.iMethod  = method;
1443     hres = IRpcChannelBuffer_GetBuffer(chanbuf,&msg,&(tpinfo->iid));
1444     if (hres) {
1445         ERR("RpcChannelBuffer GetBuffer failed, %x\n",hres);
1446         goto exit;
1447     }
1448     memcpy(msg.Buffer,buf.base,buf.curoff);
1449     if (relaydeb) TRACE_(olerelay)("\n");
1450     hres = IRpcChannelBuffer_SendReceive(chanbuf,&msg,&status);
1451     if (hres) {
1452         ERR("RpcChannelBuffer SendReceive failed, %x\n",hres);
1453         goto exit;
1454     }
1455
1456     if (relaydeb) TRACE_(olerelay)(" status = %08x (",status);
1457     if (buf.base)
1458         buf.base = HeapReAlloc(GetProcessHeap(),0,buf.base,msg.cbBuffer);
1459     else
1460         buf.base = HeapAlloc(GetProcessHeap(),0,msg.cbBuffer);
1461     buf.size = msg.cbBuffer;
1462     memcpy(buf.base,msg.Buffer,buf.size);
1463     buf.curoff = 0;
1464
1465     /* generic deserializer using typelib description */
1466     xargs = args;
1467     status = S_OK;
1468     for (i=0;i<fdesc->cParams;i++) {
1469         ELEMDESC        *elem = fdesc->lprgelemdescParam+i;
1470
1471         if (relaydeb) {
1472             if (i) TRACE_(olerelay)(",");
1473             if (i+1<nrofnames && names[i+1]) TRACE_(olerelay)("%s=",relaystr(names[i+1]));
1474         }
1475         /* No need to marshal other data than FOUT and any VT_PTR */
1476         if (!is_out_elem(elem) && (elem->tdesc.vt != VT_PTR)) {
1477             xargs += _argsize(&elem->tdesc, tinfo);
1478             if (relaydeb) TRACE_(olerelay)("[in]");
1479             continue;
1480         }
1481         hres = deserialize_param(
1482             tinfo,
1483             is_out_elem(elem),
1484             relaydeb,
1485             FALSE,
1486             &(elem->tdesc),
1487             xargs,
1488             &buf
1489         );
1490         if (hres) {
1491             ERR("Failed to unmarshall param, hres %x\n",hres);
1492             status = hres;
1493             break;
1494         }
1495         xargs += _argsize(&elem->tdesc, tinfo);
1496     }
1497
1498     hres = xbuf_get(&buf, (LPBYTE)&remoteresult, sizeof(DWORD));
1499     if (hres != S_OK)
1500         goto exit;
1501     if (relaydeb) TRACE_(olerelay)(") = %08x\n", remoteresult);
1502
1503     hres = remoteresult;
1504
1505 exit:
1506     IRpcChannelBuffer_FreeBuffer(chanbuf,&msg);
1507     for (i = 0; i < nrofnames; i++)
1508         SysFreeString(names[i]);
1509     HeapFree(GetProcessHeap(),0,buf.base);
1510     IRpcChannelBuffer_Release(chanbuf);
1511     ITypeInfo_Release(tinfo);
1512     TRACE("-- 0x%08x\n", hres);
1513     return hres;
1514 }
1515
1516 static HRESULT WINAPI ProxyIUnknown_QueryInterface(IUnknown *iface, REFIID riid, void **ppv)
1517 {
1518     TMProxyImpl *proxy = (TMProxyImpl *)iface;
1519
1520     TRACE("(%s, %p)\n", debugstr_guid(riid), ppv);
1521
1522     if (proxy->outerunknown)
1523         return IUnknown_QueryInterface(proxy->outerunknown, riid, ppv);
1524
1525     FIXME("No interface\n");
1526     return E_NOINTERFACE;
1527 }
1528
1529 static ULONG WINAPI ProxyIUnknown_AddRef(IUnknown *iface)
1530 {
1531     TMProxyImpl *proxy = (TMProxyImpl *)iface;
1532
1533     TRACE("\n");
1534
1535     if (proxy->outerunknown)
1536         return IUnknown_AddRef(proxy->outerunknown);
1537
1538     return 2; /* FIXME */
1539 }
1540
1541 static ULONG WINAPI ProxyIUnknown_Release(IUnknown *iface)
1542 {
1543     TMProxyImpl *proxy = (TMProxyImpl *)iface;
1544
1545     TRACE("\n");
1546
1547     if (proxy->outerunknown)
1548         return IUnknown_Release(proxy->outerunknown);
1549
1550     return 1; /* FIXME */
1551 }
1552
1553 static HRESULT WINAPI ProxyIDispatch_GetTypeInfoCount(LPDISPATCH iface, UINT * pctinfo)
1554 {
1555     TMProxyImpl *This = (TMProxyImpl *)iface;
1556
1557     TRACE("(%p)\n", pctinfo);
1558
1559     return IDispatch_GetTypeInfoCount(This->dispatch, pctinfo);
1560 }
1561
1562 static HRESULT WINAPI ProxyIDispatch_GetTypeInfo(LPDISPATCH iface, UINT iTInfo, LCID lcid, ITypeInfo** ppTInfo)
1563 {
1564     TMProxyImpl *This = (TMProxyImpl *)iface;
1565
1566     TRACE("(%d, %x, %p)\n", iTInfo, lcid, ppTInfo);
1567
1568     return IDispatch_GetTypeInfo(This->dispatch, iTInfo, lcid, ppTInfo);
1569 }
1570
1571 static HRESULT WINAPI ProxyIDispatch_GetIDsOfNames(LPDISPATCH iface, REFIID riid, LPOLESTR * rgszNames, UINT cNames, LCID lcid, DISPID * rgDispId)
1572 {
1573     TMProxyImpl *This = (TMProxyImpl *)iface;
1574
1575     TRACE("(%s, %p, %d, 0x%x, %p)\n", debugstr_guid(riid), rgszNames, cNames, lcid, rgDispId);
1576
1577     return IDispatch_GetIDsOfNames(This->dispatch, riid, rgszNames,
1578                                    cNames, lcid, rgDispId);
1579 }
1580
1581 static HRESULT WINAPI ProxyIDispatch_Invoke(LPDISPATCH iface, DISPID dispIdMember, REFIID riid, LCID lcid,
1582                                             WORD wFlags, DISPPARAMS * pDispParams, VARIANT * pVarResult,
1583                                             EXCEPINFO * pExcepInfo, UINT * puArgErr)
1584 {
1585     TMProxyImpl *This = (TMProxyImpl *)iface;
1586
1587     TRACE("(%d, %s, 0x%x, 0x%x, %p, %p, %p, %p)\n", dispIdMember,
1588           debugstr_guid(riid), lcid, wFlags, pDispParams, pVarResult,
1589           pExcepInfo, puArgErr);
1590
1591     return IDispatch_Invoke(This->dispatch, dispIdMember, riid, lcid,
1592                             wFlags, pDispParams, pVarResult, pExcepInfo,
1593                             puArgErr);
1594 }
1595
1596 typedef struct
1597 {
1598     const IRpcChannelBufferVtbl *lpVtbl;
1599     LONG                  refs;
1600     /* the IDispatch-derived interface we are handling */
1601         IID                   tmarshal_iid;
1602     IRpcChannelBuffer    *pDelegateChannel;
1603 } TMarshalDispatchChannel;
1604
1605 static HRESULT WINAPI TMarshalDispatchChannel_QueryInterface(LPRPCCHANNELBUFFER iface, REFIID riid, LPVOID *ppv)
1606 {
1607     *ppv = NULL;
1608     if (IsEqualIID(riid,&IID_IRpcChannelBuffer) || IsEqualIID(riid,&IID_IUnknown))
1609     {
1610         *ppv = (LPVOID)iface;
1611         IUnknown_AddRef(iface);
1612         return S_OK;
1613     }
1614     return E_NOINTERFACE;
1615 }
1616
1617 static ULONG WINAPI TMarshalDispatchChannel_AddRef(LPRPCCHANNELBUFFER iface)
1618 {
1619     TMarshalDispatchChannel *This = (TMarshalDispatchChannel *)iface;
1620     return InterlockedIncrement(&This->refs);
1621 }
1622
1623 static ULONG WINAPI TMarshalDispatchChannel_Release(LPRPCCHANNELBUFFER iface)
1624 {
1625     TMarshalDispatchChannel *This = (TMarshalDispatchChannel *)iface;
1626     ULONG ref;
1627
1628     ref = InterlockedDecrement(&This->refs);
1629     if (ref)
1630         return ref;
1631
1632         IRpcChannelBuffer_Release(This->pDelegateChannel);
1633     HeapFree(GetProcessHeap(), 0, This);
1634     return 0;
1635 }
1636
1637 static HRESULT WINAPI TMarshalDispatchChannel_GetBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg, REFIID riid)
1638 {
1639     TMarshalDispatchChannel *This = (TMarshalDispatchChannel *)iface;
1640     TRACE("(%p, %s)\n", olemsg, debugstr_guid(riid));
1641     /* Note: we are pretending to invoke a method on the interface identified
1642      * by tmarshal_iid so that we can re-use the IDispatch proxy/stub code
1643      * without the RPC runtime getting confused by not exporting an IDispatch interface */
1644     return IRpcChannelBuffer_GetBuffer(This->pDelegateChannel, olemsg, &This->tmarshal_iid);
1645 }
1646
1647 static HRESULT WINAPI TMarshalDispatchChannel_SendReceive(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE *olemsg, ULONG *pstatus)
1648 {
1649     TMarshalDispatchChannel *This = (TMarshalDispatchChannel *)iface;
1650     TRACE("(%p, %p)\n", olemsg, pstatus);
1651     return IRpcChannelBuffer_SendReceive(This->pDelegateChannel, olemsg, pstatus);
1652 }
1653
1654 static HRESULT WINAPI TMarshalDispatchChannel_FreeBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg)
1655 {
1656     TMarshalDispatchChannel *This = (TMarshalDispatchChannel *)iface;
1657     TRACE("(%p)\n", olemsg);
1658     return IRpcChannelBuffer_FreeBuffer(This->pDelegateChannel, olemsg);
1659 }
1660
1661 static HRESULT WINAPI TMarshalDispatchChannel_GetDestCtx(LPRPCCHANNELBUFFER iface, DWORD* pdwDestContext, void** ppvDestContext)
1662 {
1663     TMarshalDispatchChannel *This = (TMarshalDispatchChannel *)iface;
1664     TRACE("(%p,%p)\n", pdwDestContext, ppvDestContext);
1665     return IRpcChannelBuffer_GetDestCtx(This->pDelegateChannel, pdwDestContext, ppvDestContext);
1666 }
1667
1668 static HRESULT WINAPI TMarshalDispatchChannel_IsConnected(LPRPCCHANNELBUFFER iface)
1669 {
1670     TMarshalDispatchChannel *This = (TMarshalDispatchChannel *)iface;
1671     TRACE("()\n");
1672     return IRpcChannelBuffer_IsConnected(This->pDelegateChannel);
1673 }
1674
1675 static const IRpcChannelBufferVtbl TMarshalDispatchChannelVtbl =
1676 {
1677     TMarshalDispatchChannel_QueryInterface,
1678     TMarshalDispatchChannel_AddRef,
1679     TMarshalDispatchChannel_Release,
1680     TMarshalDispatchChannel_GetBuffer,
1681     TMarshalDispatchChannel_SendReceive,
1682     TMarshalDispatchChannel_FreeBuffer,
1683     TMarshalDispatchChannel_GetDestCtx,
1684     TMarshalDispatchChannel_IsConnected
1685 };
1686
1687 static HRESULT TMarshalDispatchChannel_Create(
1688     IRpcChannelBuffer *pDelegateChannel, REFIID tmarshal_riid,
1689     IRpcChannelBuffer **ppChannel)
1690 {
1691     TMarshalDispatchChannel *This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
1692     if (!This)
1693         return E_OUTOFMEMORY;
1694
1695     This->lpVtbl = &TMarshalDispatchChannelVtbl;
1696     This->refs = 1;
1697     IRpcChannelBuffer_AddRef(pDelegateChannel);
1698     This->pDelegateChannel = pDelegateChannel;
1699     This->tmarshal_iid = *tmarshal_riid;
1700
1701     *ppChannel = (IRpcChannelBuffer *)&This->lpVtbl;
1702     return S_OK;
1703 }
1704
1705
1706 static inline HRESULT get_facbuf_for_iid(REFIID riid, IPSFactoryBuffer **facbuf)
1707 {
1708     HRESULT       hr;
1709     CLSID         clsid;
1710
1711     if ((hr = CoGetPSClsid(riid, &clsid)))
1712         return hr;
1713     return CoGetClassObject(&clsid, CLSCTX_INPROC_SERVER, NULL,
1714                              &IID_IPSFactoryBuffer, (LPVOID*)facbuf);
1715 }
1716
1717 static HRESULT init_proxy_entry_point(TMProxyImpl *proxy, unsigned int num)
1718 {
1719     int j;
1720     /* nrofargs without This */
1721     int nrofargs;
1722     ITypeInfo *tinfo2;
1723     TMAsmProxy  *xasm = proxy->asmstubs + num;
1724     HRESULT hres;
1725     const FUNCDESC *fdesc;
1726
1727     hres = get_funcdesc(proxy->tinfo, num, &tinfo2, &fdesc, NULL, NULL, NULL);
1728     if (hres) {
1729         ERR("GetFuncDesc %x should not fail here.\n",hres);
1730         return hres;
1731     }
1732     ITypeInfo_Release(tinfo2);
1733     /* some args take more than 4 byte on the stack */
1734     nrofargs = 0;
1735     for (j=0;j<fdesc->cParams;j++)
1736         nrofargs += _argsize(&fdesc->lprgelemdescParam[j].tdesc, proxy->tinfo);
1737
1738 #ifdef __i386__
1739     if (fdesc->callconv != CC_STDCALL) {
1740         ERR("calling convention is not stdcall????\n");
1741         return E_FAIL;
1742     }
1743 /* popl %eax    -       return ptr
1744  * pushl <nr>
1745  * pushl %eax
1746  * call xCall
1747  * lret <nr> (+4)
1748  *
1749  *
1750  * arg3 arg2 arg1 <method> <returnptr>
1751  */
1752     xasm->popleax       = 0x58;
1753     xasm->pushlval      = 0x68;
1754     xasm->nr            = num;
1755     xasm->pushleax      = 0x50;
1756     xasm->lcall         = 0xe8; /* relative jump */
1757     xasm->xcall         = (DWORD)xCall;
1758     xasm->xcall        -= (DWORD)&(xasm->lret);
1759     xasm->lret          = 0xc2;
1760     xasm->bytestopop    = (nrofargs+2)*4; /* pop args, This, iMethod */
1761     xasm->nop           = 0x90;
1762     proxy->lpvtbl[num]  = xasm;
1763 #else
1764     FIXME("not implemented on non i386\n");
1765     return E_FAIL;
1766 #endif
1767     return S_OK;
1768 }
1769
1770 static HRESULT WINAPI
1771 PSFacBuf_CreateProxy(
1772     LPPSFACTORYBUFFER iface, IUnknown* pUnkOuter, REFIID riid,
1773     IRpcProxyBuffer **ppProxy, LPVOID *ppv)
1774 {
1775     HRESULT     hres;
1776     ITypeInfo   *tinfo;
1777     unsigned int i, nroffuncs;
1778     TMProxyImpl *proxy;
1779     TYPEATTR    *typeattr;
1780     BOOL        defer_to_dispatch = FALSE;
1781
1782     TRACE("(...%s...)\n",debugstr_guid(riid));
1783     hres = _get_typeinfo_for_iid(riid,&tinfo);
1784     if (hres) {
1785         ERR("No typeinfo for %s?\n",debugstr_guid(riid));
1786         return hres;
1787     }
1788
1789     hres = num_of_funcs(tinfo, &nroffuncs);
1790     if (FAILED(hres)) {
1791         ERR("Cannot get number of functions for typeinfo %s\n",debugstr_guid(riid));
1792         ITypeInfo_Release(tinfo);
1793         return hres;
1794     }
1795
1796     proxy = CoTaskMemAlloc(sizeof(TMProxyImpl));
1797     if (!proxy) return E_OUTOFMEMORY;
1798
1799     assert(sizeof(TMAsmProxy) == 16);
1800
1801     proxy->dispatch = NULL;
1802     proxy->dispatch_proxy = NULL;
1803     proxy->outerunknown = pUnkOuter;
1804     proxy->asmstubs = VirtualAlloc(NULL, sizeof(TMAsmProxy) * nroffuncs, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
1805     if (!proxy->asmstubs) {
1806         ERR("Could not commit pages for proxy thunks\n");
1807         CoTaskMemFree(proxy);
1808         return E_OUTOFMEMORY;
1809     }
1810     proxy->lpvtbl2      = &tmproxyvtable;
1811     /* one reference for the proxy */
1812     proxy->ref          = 1;
1813     proxy->tinfo        = tinfo;
1814     proxy->iid          = *riid;
1815     proxy->chanbuf      = 0;
1816
1817     InitializeCriticalSection(&proxy->crit);
1818     proxy->crit.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": TMProxyImpl.crit");
1819
1820     proxy->lpvtbl = HeapAlloc(GetProcessHeap(),0,sizeof(LPBYTE)*nroffuncs);
1821
1822     /* if we derive from IDispatch then defer to its proxy for its methods */
1823     hres = ITypeInfo_GetTypeAttr(tinfo, &typeattr);
1824     if (hres == S_OK)
1825     {
1826         if (typeattr->wTypeFlags & TYPEFLAG_FDISPATCHABLE)
1827         {
1828             IPSFactoryBuffer *factory_buffer;
1829             hres = get_facbuf_for_iid(&IID_IDispatch, &factory_buffer);
1830             if (hres == S_OK)
1831             {
1832                 hres = IPSFactoryBuffer_CreateProxy(factory_buffer, NULL,
1833                     &IID_IDispatch, &proxy->dispatch_proxy,
1834                     (void **)&proxy->dispatch);
1835                 IPSFactoryBuffer_Release(factory_buffer);
1836             }
1837             if ((hres == S_OK) && (nroffuncs < 7))
1838             {
1839                 ERR("nroffuncs calculated incorrectly (%d)\n", nroffuncs);
1840                 hres = E_UNEXPECTED;
1841             }
1842             if (hres == S_OK)
1843             {
1844                 defer_to_dispatch = TRUE;
1845             }
1846         }
1847         ITypeInfo_ReleaseTypeAttr(tinfo, typeattr);
1848     }
1849
1850     for (i=0;i<nroffuncs;i++) {
1851         switch (i) {
1852         case 0:
1853                 proxy->lpvtbl[i] = ProxyIUnknown_QueryInterface;
1854                 break;
1855         case 1:
1856                 proxy->lpvtbl[i] = ProxyIUnknown_AddRef;
1857                 break;
1858         case 2:
1859                 proxy->lpvtbl[i] = ProxyIUnknown_Release;
1860                 break;
1861         case 3:
1862                 if(!defer_to_dispatch)
1863                 {
1864                     hres = init_proxy_entry_point(proxy, i);
1865                     if(FAILED(hres)) return hres;
1866                 }
1867                 else proxy->lpvtbl[3] = ProxyIDispatch_GetTypeInfoCount;
1868                 break;
1869         case 4:
1870                 if(!defer_to_dispatch)
1871                 {
1872                     hres = init_proxy_entry_point(proxy, i);
1873                     if(FAILED(hres)) return hres;
1874                 }
1875                 else proxy->lpvtbl[4] = ProxyIDispatch_GetTypeInfo;
1876                 break;
1877         case 5:
1878                 if(!defer_to_dispatch)
1879                 {
1880                     hres = init_proxy_entry_point(proxy, i);
1881                     if(FAILED(hres)) return hres;
1882                 }
1883                 else proxy->lpvtbl[5] = ProxyIDispatch_GetIDsOfNames;
1884                 break;
1885         case 6:
1886                 if(!defer_to_dispatch)
1887                 {
1888                     hres = init_proxy_entry_point(proxy, i);
1889                     if(FAILED(hres)) return hres;
1890                 }
1891                 else proxy->lpvtbl[6] = ProxyIDispatch_Invoke;
1892                 break;
1893         default:
1894                 hres = init_proxy_entry_point(proxy, i);
1895                 if(FAILED(hres)) return hres;
1896         }
1897     }
1898
1899     if (hres == S_OK)
1900     {
1901         *ppv            = (LPVOID)proxy;
1902         *ppProxy                = (IRpcProxyBuffer *)&(proxy->lpvtbl2);
1903         IUnknown_AddRef((IUnknown *)*ppv);
1904         return S_OK;
1905     }
1906     else
1907         TMProxyImpl_Release((IRpcProxyBuffer *)&proxy->lpvtbl2);
1908     return hres;
1909 }
1910
1911 typedef struct _TMStubImpl {
1912     const IRpcStubBufferVtbl   *lpvtbl;
1913     LONG                        ref;
1914
1915     LPUNKNOWN                   pUnk;
1916     ITypeInfo                   *tinfo;
1917     IID                         iid;
1918     IRpcStubBuffer              *dispatch_stub;
1919     BOOL                        dispatch_derivative;
1920 } TMStubImpl;
1921
1922 static HRESULT WINAPI
1923 TMStubImpl_QueryInterface(LPRPCSTUBBUFFER iface, REFIID riid, LPVOID *ppv)
1924 {
1925     if (IsEqualIID(riid,&IID_IRpcStubBuffer)||IsEqualIID(riid,&IID_IUnknown)){
1926         *ppv = (LPVOID)iface;
1927         IRpcStubBuffer_AddRef(iface);
1928         return S_OK;
1929     }
1930     FIXME("%s, not supported IID.\n",debugstr_guid(riid));
1931     return E_NOINTERFACE;
1932 }
1933
1934 static ULONG WINAPI
1935 TMStubImpl_AddRef(LPRPCSTUBBUFFER iface)
1936 {
1937     TMStubImpl *This = (TMStubImpl *)iface;
1938     ULONG refCount = InterlockedIncrement(&This->ref);
1939         
1940     TRACE("(%p)->(ref before=%u)\n", This, refCount - 1);
1941
1942     return refCount;
1943 }
1944
1945 static ULONG WINAPI
1946 TMStubImpl_Release(LPRPCSTUBBUFFER iface)
1947 {
1948     TMStubImpl *This = (TMStubImpl *)iface;
1949     ULONG refCount = InterlockedDecrement(&This->ref);
1950
1951     TRACE("(%p)->(ref before=%u)\n", This, refCount + 1);
1952
1953     if (!refCount)
1954     {
1955         IRpcStubBuffer_Disconnect(iface);
1956         ITypeInfo_Release(This->tinfo);
1957         if (This->dispatch_stub)
1958             IRpcStubBuffer_Release(This->dispatch_stub);
1959         CoTaskMemFree(This);
1960     }
1961     return refCount;
1962 }
1963
1964 static HRESULT WINAPI
1965 TMStubImpl_Connect(LPRPCSTUBBUFFER iface, LPUNKNOWN pUnkServer)
1966 {
1967     TMStubImpl *This = (TMStubImpl *)iface;
1968
1969     TRACE("(%p)->(%p)\n", This, pUnkServer);
1970
1971     IUnknown_AddRef(pUnkServer);
1972     This->pUnk = pUnkServer;
1973
1974     if (This->dispatch_stub)
1975         IRpcStubBuffer_Connect(This->dispatch_stub, pUnkServer);
1976
1977     return S_OK;
1978 }
1979
1980 static void WINAPI
1981 TMStubImpl_Disconnect(LPRPCSTUBBUFFER iface)
1982 {
1983     TMStubImpl *This = (TMStubImpl *)iface;
1984
1985     TRACE("(%p)->()\n", This);
1986
1987     if (This->pUnk)
1988     {
1989         IUnknown_Release(This->pUnk);
1990         This->pUnk = NULL;
1991     }
1992
1993     if (This->dispatch_stub)
1994         IRpcStubBuffer_Disconnect(This->dispatch_stub);
1995 }
1996
1997 static HRESULT WINAPI
1998 TMStubImpl_Invoke(
1999     LPRPCSTUBBUFFER iface, RPCOLEMESSAGE* xmsg,IRpcChannelBuffer*rpcchanbuf)
2000 {
2001     int         i;
2002     const FUNCDESC *fdesc;
2003     TMStubImpl *This = (TMStubImpl *)iface;
2004     HRESULT     hres;
2005     DWORD       *args = NULL, res, *xargs, nrofargs;
2006     marshal_state       buf;
2007     UINT        nrofnames = 0;
2008     BSTR        names[10];
2009     BSTR        iname = NULL;
2010     ITypeInfo   *tinfo = NULL;
2011
2012     TRACE("...\n");
2013
2014     if (xmsg->iMethod < 3) {
2015         ERR("IUnknown methods cannot be marshaled by the typelib marshaler\n");
2016         return E_UNEXPECTED;
2017     }
2018
2019     if (This->dispatch_derivative && xmsg->iMethod < sizeof(IDispatchVtbl)/sizeof(void *))
2020     {
2021         IPSFactoryBuffer *factory_buffer;
2022         hres = get_facbuf_for_iid(&IID_IDispatch, &factory_buffer);
2023         if (hres == S_OK)
2024         {
2025             hres = IPSFactoryBuffer_CreateStub(factory_buffer, &IID_IDispatch,
2026                 This->pUnk, &This->dispatch_stub);
2027             IPSFactoryBuffer_Release(factory_buffer);
2028         }
2029         if (hres != S_OK)
2030             return hres;
2031         return IRpcStubBuffer_Invoke(This->dispatch_stub, xmsg, rpcchanbuf);
2032     }
2033
2034     memset(&buf,0,sizeof(buf));
2035     buf.size    = xmsg->cbBuffer;
2036     buf.base    = HeapAlloc(GetProcessHeap(), 0, xmsg->cbBuffer);
2037     memcpy(buf.base, xmsg->Buffer, xmsg->cbBuffer);
2038     buf.curoff  = 0;
2039
2040     hres = get_funcdesc(This->tinfo,xmsg->iMethod,&tinfo,&fdesc,&iname,NULL,NULL);
2041     if (hres) {
2042         ERR("GetFuncDesc on method %d failed with %x\n",xmsg->iMethod,hres);
2043         return hres;
2044     }
2045
2046     if (iname && !lstrcmpW(iname, IDispatchW))
2047     {
2048         ERR("IDispatch cannot be marshaled by the typelib marshaler\n");
2049         hres = E_UNEXPECTED;
2050         SysFreeString (iname);
2051         goto exit;
2052     }
2053
2054     if (iname) SysFreeString (iname);
2055
2056     /* Need them for hack below */
2057     memset(names,0,sizeof(names));
2058     ITypeInfo_GetNames(tinfo,fdesc->memid,names,sizeof(names)/sizeof(names[0]),&nrofnames);
2059     if (nrofnames > sizeof(names)/sizeof(names[0])) {
2060         ERR("Need more names!\n");
2061     }
2062
2063     /*dump_FUNCDESC(fdesc);*/
2064     nrofargs = 0;
2065     for (i=0;i<fdesc->cParams;i++)
2066         nrofargs += _argsize(&fdesc->lprgelemdescParam[i].tdesc, tinfo);
2067     args = HeapAlloc(GetProcessHeap(),0,(nrofargs+1)*sizeof(DWORD));
2068     if (!args)
2069     {
2070         hres = E_OUTOFMEMORY;
2071         goto exit;
2072     }
2073
2074     /* Allocate all stuff used by call. */
2075     xargs = args+1;
2076     for (i=0;i<fdesc->cParams;i++) {
2077         ELEMDESC        *elem = fdesc->lprgelemdescParam+i;
2078
2079         hres = deserialize_param(
2080            tinfo,
2081            is_in_elem(elem),
2082            FALSE,
2083            TRUE,
2084            &(elem->tdesc),
2085            xargs,
2086            &buf
2087         );
2088         xargs += _argsize(&elem->tdesc, tinfo);
2089         if (hres) {
2090             ERR("Failed to deserialize param %s, hres %x\n",relaystr(names[i+1]),hres);
2091             break;
2092         }
2093     }
2094
2095     args[0] = (DWORD)This->pUnk;
2096
2097     __TRY
2098     {
2099         res = _invoke(
2100             (*((FARPROC**)args[0]))[fdesc->oVft/4],
2101             fdesc->callconv,
2102             (xargs-args),
2103             args
2104         );
2105     }
2106     __EXCEPT_ALL
2107     {
2108         DWORD dwExceptionCode = GetExceptionCode();
2109         ERR("invoke call failed with exception 0x%08x (%d)\n", dwExceptionCode, dwExceptionCode);
2110         if (FAILED(dwExceptionCode))
2111             hres = dwExceptionCode;
2112         else
2113             hres = HRESULT_FROM_WIN32(dwExceptionCode);
2114     }
2115     __ENDTRY
2116
2117     if (hres != S_OK)
2118         goto exit;
2119
2120     buf.curoff = 0;
2121
2122     xargs = args+1;
2123     for (i=0;i<fdesc->cParams;i++) {
2124         ELEMDESC        *elem = fdesc->lprgelemdescParam+i;
2125         hres = serialize_param(
2126            tinfo,
2127            is_out_elem(elem),
2128            FALSE,
2129            TRUE,
2130            &elem->tdesc,
2131            xargs,
2132            &buf
2133         );
2134         xargs += _argsize(&elem->tdesc, tinfo);
2135         if (hres) {
2136             ERR("Failed to stuballoc param, hres %x\n",hres);
2137             break;
2138         }
2139     }
2140
2141     hres = xbuf_add (&buf, (LPBYTE)&res, sizeof(DWORD));
2142
2143     if (hres != S_OK)
2144         goto exit;
2145
2146     xmsg->cbBuffer      = buf.curoff;
2147     hres = IRpcChannelBuffer_GetBuffer(rpcchanbuf, xmsg, &This->iid);
2148     if (hres != S_OK)
2149         ERR("IRpcChannelBuffer_GetBuffer failed with error 0x%08x\n", hres);
2150
2151     if (hres == S_OK)
2152         memcpy(xmsg->Buffer, buf.base, buf.curoff);
2153
2154 exit:
2155     for (i = 0; i < nrofnames; i++)
2156         SysFreeString(names[i]);
2157
2158     ITypeInfo_Release(tinfo);
2159     HeapFree(GetProcessHeap(), 0, args);
2160
2161     HeapFree(GetProcessHeap(), 0, buf.base);
2162
2163     TRACE("returning\n");
2164     return hres;
2165 }
2166
2167 static LPRPCSTUBBUFFER WINAPI
2168 TMStubImpl_IsIIDSupported(LPRPCSTUBBUFFER iface, REFIID riid) {
2169     FIXME("Huh (%s)?\n",debugstr_guid(riid));
2170     return NULL;
2171 }
2172
2173 static ULONG WINAPI
2174 TMStubImpl_CountRefs(LPRPCSTUBBUFFER iface) {
2175     TMStubImpl *This = (TMStubImpl *)iface;
2176
2177     FIXME("()\n");
2178     return This->ref; /*FIXME? */
2179 }
2180
2181 static HRESULT WINAPI
2182 TMStubImpl_DebugServerQueryInterface(LPRPCSTUBBUFFER iface, LPVOID *ppv) {
2183     return E_NOTIMPL;
2184 }
2185
2186 static void WINAPI
2187 TMStubImpl_DebugServerRelease(LPRPCSTUBBUFFER iface, LPVOID ppv) {
2188     return;
2189 }
2190
2191 static const IRpcStubBufferVtbl tmstubvtbl = {
2192     TMStubImpl_QueryInterface,
2193     TMStubImpl_AddRef,
2194     TMStubImpl_Release,
2195     TMStubImpl_Connect,
2196     TMStubImpl_Disconnect,
2197     TMStubImpl_Invoke,
2198     TMStubImpl_IsIIDSupported,
2199     TMStubImpl_CountRefs,
2200     TMStubImpl_DebugServerQueryInterface,
2201     TMStubImpl_DebugServerRelease
2202 };
2203
2204 static HRESULT WINAPI
2205 PSFacBuf_CreateStub(
2206     LPPSFACTORYBUFFER iface, REFIID riid,IUnknown *pUnkServer,
2207     IRpcStubBuffer** ppStub
2208 ) {
2209     HRESULT hres;
2210     ITypeInfo   *tinfo;
2211     TMStubImpl  *stub;
2212     TYPEATTR *typeattr;
2213
2214     TRACE("(%s,%p,%p)\n",debugstr_guid(riid),pUnkServer,ppStub);
2215
2216     hres = _get_typeinfo_for_iid(riid,&tinfo);
2217     if (hres) {
2218         ERR("No typeinfo for %s?\n",debugstr_guid(riid));
2219         return hres;
2220     }
2221
2222     stub = CoTaskMemAlloc(sizeof(TMStubImpl));
2223     if (!stub)
2224         return E_OUTOFMEMORY;
2225     stub->lpvtbl        = &tmstubvtbl;
2226     stub->ref           = 1;
2227     stub->tinfo         = tinfo;
2228     stub->dispatch_stub = NULL;
2229     stub->dispatch_derivative = FALSE;
2230     stub->iid           = *riid;
2231     hres = IRpcStubBuffer_Connect((LPRPCSTUBBUFFER)stub,pUnkServer);
2232     *ppStub             = (LPRPCSTUBBUFFER)stub;
2233     TRACE("IRpcStubBuffer: %p\n", stub);
2234     if (hres)
2235         ERR("Connect to pUnkServer failed?\n");
2236
2237     /* if we derive from IDispatch then defer to its stub for some of its methods */
2238     hres = ITypeInfo_GetTypeAttr(tinfo, &typeattr);
2239     if (hres == S_OK)
2240     {
2241         if (typeattr->wTypeFlags & TYPEFLAG_FDISPATCHABLE)
2242             stub->dispatch_derivative = TRUE;
2243         ITypeInfo_ReleaseTypeAttr(tinfo, typeattr);
2244     }
2245
2246     return hres;
2247 }
2248
2249 static const IPSFactoryBufferVtbl psfacbufvtbl = {
2250     PSFacBuf_QueryInterface,
2251     PSFacBuf_AddRef,
2252     PSFacBuf_Release,
2253     PSFacBuf_CreateProxy,
2254     PSFacBuf_CreateStub
2255 };
2256
2257 /* This is the whole PSFactoryBuffer object, just the vtableptr */
2258 static const IPSFactoryBufferVtbl *lppsfac = &psfacbufvtbl;
2259
2260 /***********************************************************************
2261  *           TMARSHAL_DllGetClassObject
2262  */
2263 HRESULT TMARSHAL_DllGetClassObject(REFCLSID rclsid, REFIID iid,LPVOID *ppv)
2264 {
2265     if (IsEqualIID(iid,&IID_IPSFactoryBuffer)) {
2266         *ppv = &lppsfac;
2267         return S_OK;
2268     }
2269     return E_NOINTERFACE;
2270 }