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