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