dinput: Silence incorrect warning and move it to a valid place.
[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     for (i = 0; i < nrofnames; i++)
1472         SysFreeString(names[i]);
1473     HeapFree(GetProcessHeap(),0,buf.base);
1474     IRpcChannelBuffer_Release(chanbuf);
1475     ITypeInfo_Release(tinfo);
1476     TRACE("-- 0x%08x\n", hres);
1477     return hres;
1478 }
1479
1480 static HRESULT WINAPI ProxyIUnknown_QueryInterface(IUnknown *iface, REFIID riid, void **ppv)
1481 {
1482     TMProxyImpl *proxy = (TMProxyImpl *)iface;
1483
1484     TRACE("(%s, %p)\n", debugstr_guid(riid), ppv);
1485
1486     if (proxy->outerunknown)
1487         return IUnknown_QueryInterface(proxy->outerunknown, riid, ppv);
1488
1489     FIXME("No interface\n");
1490     return E_NOINTERFACE;
1491 }
1492
1493 static ULONG WINAPI ProxyIUnknown_AddRef(IUnknown *iface)
1494 {
1495     TMProxyImpl *proxy = (TMProxyImpl *)iface;
1496
1497     TRACE("\n");
1498
1499     if (proxy->outerunknown)
1500         return IUnknown_AddRef(proxy->outerunknown);
1501
1502     return 2; /* FIXME */
1503 }
1504
1505 static ULONG WINAPI ProxyIUnknown_Release(IUnknown *iface)
1506 {
1507     TMProxyImpl *proxy = (TMProxyImpl *)iface;
1508
1509     TRACE("\n");
1510
1511     if (proxy->outerunknown)
1512         return IUnknown_Release(proxy->outerunknown);
1513
1514     return 1; /* FIXME */
1515 }
1516
1517 static HRESULT WINAPI ProxyIDispatch_GetTypeInfoCount(LPDISPATCH iface, UINT * pctinfo)
1518 {
1519     TMProxyImpl *This = (TMProxyImpl *)iface;
1520
1521     TRACE("(%p)\n", pctinfo);
1522
1523     return IDispatch_GetTypeInfoCount(This->dispatch, pctinfo);
1524 }
1525
1526 static HRESULT WINAPI ProxyIDispatch_GetTypeInfo(LPDISPATCH iface, UINT iTInfo, LCID lcid, ITypeInfo** ppTInfo)
1527 {
1528     TMProxyImpl *This = (TMProxyImpl *)iface;
1529
1530     TRACE("(%d, %x, %p)\n", iTInfo, lcid, ppTInfo);
1531
1532     return IDispatch_GetTypeInfo(This->dispatch, iTInfo, lcid, ppTInfo);
1533 }
1534
1535 static HRESULT WINAPI ProxyIDispatch_GetIDsOfNames(LPDISPATCH iface, REFIID riid, LPOLESTR * rgszNames, UINT cNames, LCID lcid, DISPID * rgDispId)
1536 {
1537     TMProxyImpl *This = (TMProxyImpl *)iface;
1538
1539     TRACE("(%s, %p, %d, 0x%x, %p)\n", debugstr_guid(riid), rgszNames, cNames, lcid, rgDispId);
1540
1541     return IDispatch_GetIDsOfNames(This->dispatch, riid, rgszNames,
1542                                    cNames, lcid, rgDispId);
1543 }
1544
1545 static HRESULT WINAPI ProxyIDispatch_Invoke(LPDISPATCH iface, DISPID dispIdMember, REFIID riid, LCID lcid,
1546                                             WORD wFlags, DISPPARAMS * pDispParams, VARIANT * pVarResult,
1547                                             EXCEPINFO * pExcepInfo, UINT * puArgErr)
1548 {
1549     TMProxyImpl *This = (TMProxyImpl *)iface;
1550
1551     TRACE("(%d, %s, 0x%x, 0x%x, %p, %p, %p, %p)\n", dispIdMember,
1552           debugstr_guid(riid), lcid, wFlags, pDispParams, pVarResult,
1553           pExcepInfo, puArgErr);
1554
1555     return IDispatch_Invoke(This->dispatch, dispIdMember, riid, lcid,
1556                             wFlags, pDispParams, pVarResult, pExcepInfo,
1557                             puArgErr);
1558 }
1559
1560 typedef struct
1561 {
1562     const IRpcChannelBufferVtbl *lpVtbl;
1563     LONG                  refs;
1564     /* the IDispatch-derived interface we are handling */
1565         IID                   tmarshal_iid;
1566     IRpcChannelBuffer    *pDelegateChannel;
1567 } TMarshalDispatchChannel;
1568
1569 static HRESULT WINAPI TMarshalDispatchChannel_QueryInterface(LPRPCCHANNELBUFFER iface, REFIID riid, LPVOID *ppv)
1570 {
1571     *ppv = NULL;
1572     if (IsEqualIID(riid,&IID_IRpcChannelBuffer) || IsEqualIID(riid,&IID_IUnknown))
1573     {
1574         *ppv = (LPVOID)iface;
1575         IUnknown_AddRef(iface);
1576         return S_OK;
1577     }
1578     return E_NOINTERFACE;
1579 }
1580
1581 static ULONG WINAPI TMarshalDispatchChannel_AddRef(LPRPCCHANNELBUFFER iface)
1582 {
1583     TMarshalDispatchChannel *This = (TMarshalDispatchChannel *)iface;
1584     return InterlockedIncrement(&This->refs);
1585 }
1586
1587 static ULONG WINAPI TMarshalDispatchChannel_Release(LPRPCCHANNELBUFFER iface)
1588 {
1589     TMarshalDispatchChannel *This = (TMarshalDispatchChannel *)iface;
1590     ULONG ref;
1591
1592     ref = InterlockedDecrement(&This->refs);
1593     if (ref)
1594         return ref;
1595
1596         IRpcChannelBuffer_Release(This->pDelegateChannel);
1597     HeapFree(GetProcessHeap(), 0, This);
1598     return 0;
1599 }
1600
1601 static HRESULT WINAPI TMarshalDispatchChannel_GetBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg, REFIID riid)
1602 {
1603     TMarshalDispatchChannel *This = (TMarshalDispatchChannel *)iface;
1604     TRACE("(%p, %s)\n", olemsg, debugstr_guid(riid));
1605     /* Note: we are pretending to invoke a method on the interface identified
1606      * by tmarshal_iid so that we can re-use the IDispatch proxy/stub code
1607      * without the RPC runtime getting confused by not exporting an IDispatch interface */
1608     return IRpcChannelBuffer_GetBuffer(This->pDelegateChannel, olemsg, &This->tmarshal_iid);
1609 }
1610
1611 static HRESULT WINAPI TMarshalDispatchChannel_SendReceive(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE *olemsg, ULONG *pstatus)
1612 {
1613     TMarshalDispatchChannel *This = (TMarshalDispatchChannel *)iface;
1614     TRACE("(%p, %p)\n", olemsg, pstatus);
1615     return IRpcChannelBuffer_SendReceive(This->pDelegateChannel, olemsg, pstatus);
1616 }
1617
1618 static HRESULT WINAPI TMarshalDispatchChannel_FreeBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg)
1619 {
1620     TMarshalDispatchChannel *This = (TMarshalDispatchChannel *)iface;
1621     TRACE("(%p)\n", olemsg);
1622     return IRpcChannelBuffer_FreeBuffer(This->pDelegateChannel, olemsg);
1623 }
1624
1625 static HRESULT WINAPI TMarshalDispatchChannel_GetDestCtx(LPRPCCHANNELBUFFER iface, DWORD* pdwDestContext, void** ppvDestContext)
1626 {
1627     TMarshalDispatchChannel *This = (TMarshalDispatchChannel *)iface;
1628     TRACE("(%p,%p)\n", pdwDestContext, ppvDestContext);
1629     return IRpcChannelBuffer_GetDestCtx(This->pDelegateChannel, pdwDestContext, ppvDestContext);
1630 }
1631
1632 static HRESULT WINAPI TMarshalDispatchChannel_IsConnected(LPRPCCHANNELBUFFER iface)
1633 {
1634     TMarshalDispatchChannel *This = (TMarshalDispatchChannel *)iface;
1635     TRACE("()\n");
1636     return IRpcChannelBuffer_IsConnected(This->pDelegateChannel);
1637 }
1638
1639 static const IRpcChannelBufferVtbl TMarshalDispatchChannelVtbl =
1640 {
1641     TMarshalDispatchChannel_QueryInterface,
1642     TMarshalDispatchChannel_AddRef,
1643     TMarshalDispatchChannel_Release,
1644     TMarshalDispatchChannel_GetBuffer,
1645     TMarshalDispatchChannel_SendReceive,
1646     TMarshalDispatchChannel_FreeBuffer,
1647     TMarshalDispatchChannel_GetDestCtx,
1648     TMarshalDispatchChannel_IsConnected
1649 };
1650
1651 static HRESULT TMarshalDispatchChannel_Create(
1652     IRpcChannelBuffer *pDelegateChannel, REFIID tmarshal_riid,
1653     IRpcChannelBuffer **ppChannel)
1654 {
1655     TMarshalDispatchChannel *This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
1656     if (!This)
1657         return E_OUTOFMEMORY;
1658
1659     This->lpVtbl = &TMarshalDispatchChannelVtbl;
1660     This->refs = 1;
1661     IRpcChannelBuffer_AddRef(pDelegateChannel);
1662     This->pDelegateChannel = pDelegateChannel;
1663     This->tmarshal_iid = *tmarshal_riid;
1664
1665     *ppChannel = (IRpcChannelBuffer *)&This->lpVtbl;
1666     return S_OK;
1667 }
1668
1669
1670 static inline HRESULT get_facbuf_for_iid(REFIID riid, IPSFactoryBuffer **facbuf)
1671 {
1672     HRESULT       hr;
1673     CLSID         clsid;
1674
1675     if ((hr = CoGetPSClsid(riid, &clsid)))
1676         return hr;
1677     return CoGetClassObject(&clsid, CLSCTX_INPROC_SERVER, NULL,
1678                              &IID_IPSFactoryBuffer, (LPVOID*)facbuf);
1679 }
1680
1681 static HRESULT init_proxy_entry_point(TMProxyImpl *proxy, unsigned int num)
1682 {
1683     int j;
1684     /* nrofargs without This */
1685     int nrofargs;
1686     ITypeInfo *tinfo2;
1687     TMAsmProxy  *xasm = proxy->asmstubs + num;
1688     HRESULT hres;
1689     const FUNCDESC *fdesc;
1690
1691     hres = get_funcdesc(proxy->tinfo, num, &tinfo2, &fdesc, NULL, NULL, NULL);
1692     if (hres) {
1693         ERR("GetFuncDesc %x should not fail here.\n",hres);
1694         return hres;
1695     }
1696     ITypeInfo_Release(tinfo2);
1697     /* some args take more than 4 byte on the stack */
1698     nrofargs = 0;
1699     for (j=0;j<fdesc->cParams;j++)
1700         nrofargs += _argsize(fdesc->lprgelemdescParam[j].tdesc.vt);
1701
1702 #ifdef __i386__
1703     if (fdesc->callconv != CC_STDCALL) {
1704         ERR("calling convention is not stdcall????\n");
1705         return E_FAIL;
1706     }
1707 /* popl %eax    -       return ptr
1708  * pushl <nr>
1709  * pushl %eax
1710  * call xCall
1711  * lret <nr> (+4)
1712  *
1713  *
1714  * arg3 arg2 arg1 <method> <returnptr>
1715  */
1716     xasm->popleax       = 0x58;
1717     xasm->pushlval      = 0x68;
1718     xasm->nr            = num;
1719     xasm->pushleax      = 0x50;
1720     xasm->lcall         = 0xe8; /* relative jump */
1721     xasm->xcall         = (DWORD)xCall;
1722     xasm->xcall        -= (DWORD)&(xasm->lret);
1723     xasm->lret          = 0xc2;
1724     xasm->bytestopop    = (nrofargs+2)*4; /* pop args, This, iMethod */
1725     xasm->nop           = 0x90;
1726     proxy->lpvtbl[num]  = xasm;
1727 #else
1728     FIXME("not implemented on non i386\n");
1729     return E_FAIL;
1730 #endif
1731     return S_OK;
1732 }
1733
1734 static HRESULT WINAPI
1735 PSFacBuf_CreateProxy(
1736     LPPSFACTORYBUFFER iface, IUnknown* pUnkOuter, REFIID riid,
1737     IRpcProxyBuffer **ppProxy, LPVOID *ppv)
1738 {
1739     HRESULT     hres;
1740     ITypeInfo   *tinfo;
1741     unsigned int i, nroffuncs;
1742     TMProxyImpl *proxy;
1743     TYPEATTR    *typeattr;
1744     BOOL        defer_to_dispatch = FALSE;
1745
1746     TRACE("(...%s...)\n",debugstr_guid(riid));
1747     hres = _get_typeinfo_for_iid(riid,&tinfo);
1748     if (hres) {
1749         ERR("No typeinfo for %s?\n",debugstr_guid(riid));
1750         return hres;
1751     }
1752
1753     hres = num_of_funcs(tinfo, &nroffuncs);
1754     if (FAILED(hres)) {
1755         ERR("Cannot get number of functions for typeinfo %s\n",debugstr_guid(riid));
1756         ITypeInfo_Release(tinfo);
1757         return hres;
1758     }
1759
1760     proxy = CoTaskMemAlloc(sizeof(TMProxyImpl));
1761     if (!proxy) return E_OUTOFMEMORY;
1762
1763     assert(sizeof(TMAsmProxy) == 16);
1764
1765     proxy->dispatch = NULL;
1766     proxy->dispatch_proxy = NULL;
1767     proxy->outerunknown = pUnkOuter;
1768     proxy->asmstubs = VirtualAlloc(NULL, sizeof(TMAsmProxy) * nroffuncs, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
1769     if (!proxy->asmstubs) {
1770         ERR("Could not commit pages for proxy thunks\n");
1771         CoTaskMemFree(proxy);
1772         return E_OUTOFMEMORY;
1773     }
1774     proxy->lpvtbl2      = &tmproxyvtable;
1775     /* one reference for the proxy */
1776     proxy->ref          = 1;
1777     proxy->tinfo        = tinfo;
1778     memcpy(&proxy->iid,riid,sizeof(*riid));
1779     proxy->chanbuf      = 0;
1780
1781     InitializeCriticalSection(&proxy->crit);
1782     proxy->crit.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": TMProxyImpl.crit");
1783
1784     proxy->lpvtbl = HeapAlloc(GetProcessHeap(),0,sizeof(LPBYTE)*nroffuncs);
1785
1786     /* if we derive from IDispatch then defer to its proxy for its methods */
1787     hres = ITypeInfo_GetTypeAttr(tinfo, &typeattr);
1788     if (hres == S_OK)
1789     {
1790         if (typeattr->wTypeFlags & TYPEFLAG_FDISPATCHABLE)
1791         {
1792             IPSFactoryBuffer *factory_buffer;
1793             hres = get_facbuf_for_iid(&IID_IDispatch, &factory_buffer);
1794             if (hres == S_OK)
1795             {
1796                 hres = IPSFactoryBuffer_CreateProxy(factory_buffer, NULL,
1797                     &IID_IDispatch, &proxy->dispatch_proxy,
1798                     (void **)&proxy->dispatch);
1799                 IPSFactoryBuffer_Release(factory_buffer);
1800             }
1801             if ((hres == S_OK) && (nroffuncs < 7))
1802             {
1803                 ERR("nroffuncs calculated incorrectly (%d)\n", nroffuncs);
1804                 hres = E_UNEXPECTED;
1805             }
1806             if (hres == S_OK)
1807             {
1808                 defer_to_dispatch = TRUE;
1809             }
1810         }
1811         ITypeInfo_ReleaseTypeAttr(tinfo, typeattr);
1812     }
1813
1814     for (i=0;i<nroffuncs;i++) {
1815         switch (i) {
1816         case 0:
1817                 proxy->lpvtbl[i] = ProxyIUnknown_QueryInterface;
1818                 break;
1819         case 1:
1820                 proxy->lpvtbl[i] = ProxyIUnknown_AddRef;
1821                 break;
1822         case 2:
1823                 proxy->lpvtbl[i] = ProxyIUnknown_Release;
1824                 break;
1825         case 3:
1826                 if(!defer_to_dispatch)
1827                 {
1828                     hres = init_proxy_entry_point(proxy, i);
1829                     if(FAILED(hres)) return hres;
1830                 }
1831                 else proxy->lpvtbl[3] = ProxyIDispatch_GetTypeInfoCount;
1832                 break;
1833         case 4:
1834                 if(!defer_to_dispatch)
1835                 {
1836                     hres = init_proxy_entry_point(proxy, i);
1837                     if(FAILED(hres)) return hres;
1838                 }
1839                 else proxy->lpvtbl[4] = ProxyIDispatch_GetTypeInfo;
1840                 break;
1841         case 5:
1842                 if(!defer_to_dispatch)
1843                 {
1844                     hres = init_proxy_entry_point(proxy, i);
1845                     if(FAILED(hres)) return hres;
1846                 }
1847                 else proxy->lpvtbl[5] = ProxyIDispatch_GetIDsOfNames;
1848                 break;
1849         case 6:
1850                 if(!defer_to_dispatch)
1851                 {
1852                     hres = init_proxy_entry_point(proxy, i);
1853                     if(FAILED(hres)) return hres;
1854                 }
1855                 else proxy->lpvtbl[6] = ProxyIDispatch_Invoke;
1856                 break;
1857         default:
1858                 hres = init_proxy_entry_point(proxy, i);
1859                 if(FAILED(hres)) return hres;
1860         }
1861     }
1862
1863     if (hres == S_OK)
1864     {
1865         *ppv            = (LPVOID)proxy;
1866         *ppProxy                = (IRpcProxyBuffer *)&(proxy->lpvtbl2);
1867         IUnknown_AddRef((IUnknown *)*ppv);
1868         return S_OK;
1869     }
1870     else
1871         TMProxyImpl_Release((IRpcProxyBuffer *)&proxy->lpvtbl2);
1872     return hres;
1873 }
1874
1875 typedef struct _TMStubImpl {
1876     const IRpcStubBufferVtbl   *lpvtbl;
1877     LONG                        ref;
1878
1879     LPUNKNOWN                   pUnk;
1880     ITypeInfo                   *tinfo;
1881     IID                         iid;
1882     IRpcStubBuffer              *dispatch_stub;
1883     BOOL                        dispatch_derivative;
1884 } TMStubImpl;
1885
1886 static HRESULT WINAPI
1887 TMStubImpl_QueryInterface(LPRPCSTUBBUFFER iface, REFIID riid, LPVOID *ppv)
1888 {
1889     if (IsEqualIID(riid,&IID_IRpcStubBuffer)||IsEqualIID(riid,&IID_IUnknown)){
1890         *ppv = (LPVOID)iface;
1891         IRpcStubBuffer_AddRef(iface);
1892         return S_OK;
1893     }
1894     FIXME("%s, not supported IID.\n",debugstr_guid(riid));
1895     return E_NOINTERFACE;
1896 }
1897
1898 static ULONG WINAPI
1899 TMStubImpl_AddRef(LPRPCSTUBBUFFER iface)
1900 {
1901     TMStubImpl *This = (TMStubImpl *)iface;
1902     ULONG refCount = InterlockedIncrement(&This->ref);
1903         
1904     TRACE("(%p)->(ref before=%u)\n", This, refCount - 1);
1905
1906     return refCount;
1907 }
1908
1909 static ULONG WINAPI
1910 TMStubImpl_Release(LPRPCSTUBBUFFER iface)
1911 {
1912     TMStubImpl *This = (TMStubImpl *)iface;
1913     ULONG refCount = InterlockedDecrement(&This->ref);
1914
1915     TRACE("(%p)->(ref before=%u)\n", This, refCount + 1);
1916
1917     if (!refCount)
1918     {
1919         IRpcStubBuffer_Disconnect(iface);
1920         ITypeInfo_Release(This->tinfo);
1921         if (This->dispatch_stub)
1922             IRpcStubBuffer_Release(This->dispatch_stub);
1923         CoTaskMemFree(This);
1924     }
1925     return refCount;
1926 }
1927
1928 static HRESULT WINAPI
1929 TMStubImpl_Connect(LPRPCSTUBBUFFER iface, LPUNKNOWN pUnkServer)
1930 {
1931     TMStubImpl *This = (TMStubImpl *)iface;
1932
1933     TRACE("(%p)->(%p)\n", This, pUnkServer);
1934
1935     IUnknown_AddRef(pUnkServer);
1936     This->pUnk = pUnkServer;
1937
1938     if (This->dispatch_stub)
1939         IRpcStubBuffer_Connect(This->dispatch_stub, pUnkServer);
1940
1941     return S_OK;
1942 }
1943
1944 static void WINAPI
1945 TMStubImpl_Disconnect(LPRPCSTUBBUFFER iface)
1946 {
1947     TMStubImpl *This = (TMStubImpl *)iface;
1948
1949     TRACE("(%p)->()\n", This);
1950
1951     if (This->pUnk)
1952     {
1953         IUnknown_Release(This->pUnk);
1954         This->pUnk = NULL;
1955     }
1956
1957     if (This->dispatch_stub)
1958         IRpcStubBuffer_Disconnect(This->dispatch_stub);
1959 }
1960
1961 static HRESULT WINAPI
1962 TMStubImpl_Invoke(
1963     LPRPCSTUBBUFFER iface, RPCOLEMESSAGE* xmsg,IRpcChannelBuffer*rpcchanbuf)
1964 {
1965     int         i;
1966     const FUNCDESC *fdesc;
1967     TMStubImpl *This = (TMStubImpl *)iface;
1968     HRESULT     hres;
1969     DWORD       *args = NULL, res, *xargs, nrofargs;
1970     marshal_state       buf;
1971     UINT        nrofnames = 0;
1972     BSTR        names[10];
1973     BSTR        iname = NULL;
1974     ITypeInfo   *tinfo = NULL;
1975
1976     TRACE("...\n");
1977
1978     if (xmsg->iMethod < 3) {
1979         ERR("IUnknown methods cannot be marshaled by the typelib marshaler\n");
1980         return E_UNEXPECTED;
1981     }
1982
1983     if (This->dispatch_derivative && xmsg->iMethod < sizeof(IDispatchVtbl)/sizeof(void *))
1984     {
1985         IPSFactoryBuffer *factory_buffer;
1986         hres = get_facbuf_for_iid(&IID_IDispatch, &factory_buffer);
1987         if (hres == S_OK)
1988         {
1989             hres = IPSFactoryBuffer_CreateStub(factory_buffer, &IID_IDispatch,
1990                 This->pUnk, &This->dispatch_stub);
1991             IPSFactoryBuffer_Release(factory_buffer);
1992         }
1993         if (hres != S_OK)
1994             return hres;
1995         return IRpcStubBuffer_Invoke(This->dispatch_stub, xmsg, rpcchanbuf);
1996     }
1997
1998     memset(&buf,0,sizeof(buf));
1999     buf.size    = xmsg->cbBuffer;
2000     buf.base    = HeapAlloc(GetProcessHeap(), 0, xmsg->cbBuffer);
2001     memcpy(buf.base, xmsg->Buffer, xmsg->cbBuffer);
2002     buf.curoff  = 0;
2003
2004     hres = get_funcdesc(This->tinfo,xmsg->iMethod,&tinfo,&fdesc,&iname,NULL,NULL);
2005     if (hres) {
2006         ERR("GetFuncDesc on method %d failed with %x\n",xmsg->iMethod,hres);
2007         return hres;
2008     }
2009
2010     if (iname && !lstrcmpW(iname, IDispatchW))
2011     {
2012         ERR("IDispatch cannot be marshaled by the typelib marshaler\n");
2013         hres = E_UNEXPECTED;
2014         SysFreeString (iname);
2015         goto exit;
2016     }
2017
2018     if (iname) SysFreeString (iname);
2019
2020     /* Need them for hack below */
2021     memset(names,0,sizeof(names));
2022     ITypeInfo_GetNames(tinfo,fdesc->memid,names,sizeof(names)/sizeof(names[0]),&nrofnames);
2023     if (nrofnames > sizeof(names)/sizeof(names[0])) {
2024         ERR("Need more names!\n");
2025     }
2026
2027     /*dump_FUNCDESC(fdesc);*/
2028     nrofargs = 0;
2029     for (i=0;i<fdesc->cParams;i++)
2030         nrofargs += _argsize(fdesc->lprgelemdescParam[i].tdesc.vt);
2031     args = HeapAlloc(GetProcessHeap(),0,(nrofargs+1)*sizeof(DWORD));
2032     if (!args)
2033     {
2034         hres = E_OUTOFMEMORY;
2035         goto exit;
2036     }
2037
2038     /* Allocate all stuff used by call. */
2039     xargs = args+1;
2040     for (i=0;i<fdesc->cParams;i++) {
2041         ELEMDESC        *elem = fdesc->lprgelemdescParam+i;
2042
2043         hres = deserialize_param(
2044            tinfo,
2045            is_in_elem(elem),
2046            FALSE,
2047            TRUE,
2048            &(elem->tdesc),
2049            xargs,
2050            &buf
2051         );
2052         xargs += _argsize(elem->tdesc.vt);
2053         if (hres) {
2054             ERR("Failed to deserialize param %s, hres %x\n",relaystr(names[i+1]),hres);
2055             break;
2056         }
2057     }
2058
2059     args[0] = (DWORD)This->pUnk;
2060
2061     __TRY
2062     {
2063         res = _invoke(
2064             (*((FARPROC**)args[0]))[fdesc->oVft/4],
2065             fdesc->callconv,
2066             (xargs-args),
2067             args
2068         );
2069     }
2070     __EXCEPT(NULL)
2071     {
2072         DWORD dwExceptionCode = GetExceptionCode();
2073         ERR("invoke call failed with exception 0x%08x (%d)\n", dwExceptionCode, dwExceptionCode);
2074         if (FAILED(dwExceptionCode))
2075             hres = dwExceptionCode;
2076         else
2077             hres = HRESULT_FROM_WIN32(dwExceptionCode);
2078     }
2079     __ENDTRY
2080
2081     if (hres != S_OK)
2082         goto exit;
2083
2084     buf.curoff = 0;
2085
2086     xargs = args+1;
2087     for (i=0;i<fdesc->cParams;i++) {
2088         ELEMDESC        *elem = fdesc->lprgelemdescParam+i;
2089         hres = serialize_param(
2090            tinfo,
2091            is_out_elem(elem),
2092            FALSE,
2093            TRUE,
2094            &elem->tdesc,
2095            xargs,
2096            &buf
2097         );
2098         xargs += _argsize(elem->tdesc.vt);
2099         if (hres) {
2100             ERR("Failed to stuballoc param, hres %x\n",hres);
2101             break;
2102         }
2103     }
2104
2105     hres = xbuf_add (&buf, (LPBYTE)&res, sizeof(DWORD));
2106
2107     if (hres != S_OK)
2108         goto exit;
2109
2110     xmsg->cbBuffer      = buf.curoff;
2111     hres = IRpcChannelBuffer_GetBuffer(rpcchanbuf, xmsg, &This->iid);
2112     if (hres != S_OK)
2113         ERR("IRpcChannelBuffer_GetBuffer failed with error 0x%08x\n", hres);
2114
2115     if (hres == S_OK)
2116         memcpy(xmsg->Buffer, buf.base, buf.curoff);
2117
2118 exit:
2119     for (i = 0; i < nrofnames; i++)
2120         SysFreeString(names[i]);
2121
2122     ITypeInfo_Release(tinfo);
2123     HeapFree(GetProcessHeap(), 0, args);
2124
2125     HeapFree(GetProcessHeap(), 0, buf.base);
2126
2127     TRACE("returning\n");
2128     return hres;
2129 }
2130
2131 static LPRPCSTUBBUFFER WINAPI
2132 TMStubImpl_IsIIDSupported(LPRPCSTUBBUFFER iface, REFIID riid) {
2133     FIXME("Huh (%s)?\n",debugstr_guid(riid));
2134     return NULL;
2135 }
2136
2137 static ULONG WINAPI
2138 TMStubImpl_CountRefs(LPRPCSTUBBUFFER iface) {
2139     TMStubImpl *This = (TMStubImpl *)iface;
2140
2141     FIXME("()\n");
2142     return This->ref; /*FIXME? */
2143 }
2144
2145 static HRESULT WINAPI
2146 TMStubImpl_DebugServerQueryInterface(LPRPCSTUBBUFFER iface, LPVOID *ppv) {
2147     return E_NOTIMPL;
2148 }
2149
2150 static void WINAPI
2151 TMStubImpl_DebugServerRelease(LPRPCSTUBBUFFER iface, LPVOID ppv) {
2152     return;
2153 }
2154
2155 static const IRpcStubBufferVtbl tmstubvtbl = {
2156     TMStubImpl_QueryInterface,
2157     TMStubImpl_AddRef,
2158     TMStubImpl_Release,
2159     TMStubImpl_Connect,
2160     TMStubImpl_Disconnect,
2161     TMStubImpl_Invoke,
2162     TMStubImpl_IsIIDSupported,
2163     TMStubImpl_CountRefs,
2164     TMStubImpl_DebugServerQueryInterface,
2165     TMStubImpl_DebugServerRelease
2166 };
2167
2168 static HRESULT WINAPI
2169 PSFacBuf_CreateStub(
2170     LPPSFACTORYBUFFER iface, REFIID riid,IUnknown *pUnkServer,
2171     IRpcStubBuffer** ppStub
2172 ) {
2173     HRESULT hres;
2174     ITypeInfo   *tinfo;
2175     TMStubImpl  *stub;
2176     TYPEATTR *typeattr;
2177
2178     TRACE("(%s,%p,%p)\n",debugstr_guid(riid),pUnkServer,ppStub);
2179
2180     hres = _get_typeinfo_for_iid(riid,&tinfo);
2181     if (hres) {
2182         ERR("No typeinfo for %s?\n",debugstr_guid(riid));
2183         return hres;
2184     }
2185
2186     stub = CoTaskMemAlloc(sizeof(TMStubImpl));
2187     if (!stub)
2188         return E_OUTOFMEMORY;
2189     stub->lpvtbl        = &tmstubvtbl;
2190     stub->ref           = 1;
2191     stub->tinfo         = tinfo;
2192     stub->dispatch_stub = NULL;
2193     stub->dispatch_derivative = FALSE;
2194     memcpy(&(stub->iid),riid,sizeof(*riid));
2195     hres = IRpcStubBuffer_Connect((LPRPCSTUBBUFFER)stub,pUnkServer);
2196     *ppStub             = (LPRPCSTUBBUFFER)stub;
2197     TRACE("IRpcStubBuffer: %p\n", stub);
2198     if (hres)
2199         ERR("Connect to pUnkServer failed?\n");
2200
2201     /* if we derive from IDispatch then defer to its stub for some of its methods */
2202     hres = ITypeInfo_GetTypeAttr(tinfo, &typeattr);
2203     if (hres == S_OK)
2204     {
2205         if (typeattr->wTypeFlags & TYPEFLAG_FDISPATCHABLE)
2206             stub->dispatch_derivative = TRUE;
2207         ITypeInfo_ReleaseTypeAttr(tinfo, typeattr);
2208     }
2209
2210     return hres;
2211 }
2212
2213 static const IPSFactoryBufferVtbl psfacbufvtbl = {
2214     PSFacBuf_QueryInterface,
2215     PSFacBuf_AddRef,
2216     PSFacBuf_Release,
2217     PSFacBuf_CreateProxy,
2218     PSFacBuf_CreateStub
2219 };
2220
2221 /* This is the whole PSFactoryBuffer object, just the vtableptr */
2222 static const IPSFactoryBufferVtbl *lppsfac = &psfacbufvtbl;
2223
2224 /***********************************************************************
2225  *           TMARSHAL_DllGetClassObject
2226  */
2227 HRESULT TMARSHAL_DllGetClassObject(REFCLSID rclsid, REFIID iid,LPVOID *ppv)
2228 {
2229     if (IsEqualIID(iid,&IID_IPSFactoryBuffer)) {
2230         *ppv = &lppsfac;
2231         return S_OK;
2232     }
2233     return E_NOINTERFACE;
2234 }