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