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