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