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