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