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