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