If using the default values, also set dwType to REG_SZ as our default
[wine] / dlls / oleaut32 / tmarshal.c
1 /*
2  *      TYPELIB Marshaler
3  *
4  *      Copyright 2002  Marcus Meissner
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20
21 #include "config.h"
22
23 #include <assert.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <stdarg.h>
27 #include <stdio.h>
28 #include <ctype.h>
29
30 #define NONAMELESSUNION
31 #define NONAMELESSSTRUCT
32 #include "winerror.h"
33 #include "windef.h"
34 #include "winbase.h"
35 #include "winnls.h"
36 #include "winreg.h"
37 #include "winuser.h"
38
39 #include "ole2.h"
40 #include "wine/unicode.h"
41 #include "ole2disp.h"
42 #include "typelib.h"
43 #include "wine/debug.h"
44 #include "winternl.h"
45
46 static const WCHAR riidW[5] = {'r','i','i','d',0};
47 static const WCHAR pdispparamsW[] = {'p','d','i','s','p','p','a','r','a','m','s',0};
48 static const WCHAR ppvObjectW[] = {'p','p','v','O','b','j','e','c','t',0};
49
50 WINE_DEFAULT_DEBUG_CHANNEL(ole);
51 WINE_DECLARE_DEBUG_CHANNEL(olerelay);
52
53 typedef struct _marshal_state {
54     LPBYTE      base;
55     int         size;
56     int         curoff;
57
58     BOOL        thisisiid;
59     IID         iid;    /* HACK: for VT_VOID */
60 } marshal_state;
61
62 static HRESULT
63 xbuf_add(marshal_state *buf, LPBYTE stuff, DWORD size) {
64     while (buf->size - buf->curoff < size) {
65         if (buf->base) {
66             buf->size += 100;
67             buf->base = HeapReAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,buf->base,buf->size);
68             if (!buf->base)
69                 return E_OUTOFMEMORY;
70         } else {
71             buf->base = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,32);
72             buf->size = 32;
73             if (!buf->base)
74                 return E_OUTOFMEMORY;
75         }
76     }
77     memcpy(buf->base+buf->curoff,stuff,size);
78     buf->curoff += size;
79     return S_OK;
80 }
81
82 static HRESULT
83 xbuf_get(marshal_state *buf, LPBYTE stuff, DWORD size) {
84     if (buf->size < buf->curoff+size) return E_FAIL;
85     memcpy(stuff,buf->base+buf->curoff,size);
86     buf->curoff += size;
87     return S_OK;
88 }
89
90 static HRESULT
91 xbuf_skip(marshal_state *buf, DWORD size) {
92     if (buf->size < buf->curoff+size) return E_FAIL;
93     buf->curoff += size;
94     return S_OK;
95 }
96
97 static HRESULT
98 _unmarshal_interface(marshal_state *buf, REFIID riid, LPUNKNOWN *pUnk) {
99     IStream             *pStm;
100     ULARGE_INTEGER      newpos;
101     LARGE_INTEGER       seekto;
102     ULONG               res;
103     HRESULT             hres;
104     DWORD               xsize;
105
106     TRACE("...%s...\n",debugstr_guid(riid));
107     *pUnk = NULL;
108     hres = xbuf_get(buf,(LPBYTE)&xsize,sizeof(xsize));
109     if (hres) return hres;
110     if (xsize == 0) return S_OK;
111     hres = CreateStreamOnHGlobal(0,TRUE,&pStm);
112     if (hres) {
113         FIXME("Stream create failed %lx\n",hres);
114         return hres;
115     }
116     hres = IStream_Write(pStm,buf->base+buf->curoff,xsize,&res);
117     if (hres) { FIXME("stream write %lx\n",hres); return hres; }
118     memset(&seekto,0,sizeof(seekto));
119     hres = IStream_Seek(pStm,seekto,SEEK_SET,&newpos);
120     if (hres) { FIXME("Failed Seek %lx\n",hres); return hres;}
121     hres = CoUnmarshalInterface(pStm,riid,(LPVOID*)pUnk);
122     if (hres) {
123         FIXME("Marshalling interface %s failed with %lx\n",debugstr_guid(riid),hres);
124         return hres;
125     }
126     IStream_Release(pStm);
127     return xbuf_skip(buf,xsize);
128 }
129
130 static HRESULT
131 _marshal_interface(marshal_state *buf, REFIID riid, LPUNKNOWN pUnk) {
132     LPUNKNOWN           newiface;
133     LPBYTE              tempbuf;
134     IStream             *pStm;
135     STATSTG             ststg;
136     ULARGE_INTEGER      newpos;
137     LARGE_INTEGER       seekto;
138     ULONG               res;
139     DWORD               xsize;
140     HRESULT             hres;
141
142     hres = S_OK;
143     if (!pUnk)
144         goto fail;
145
146     TRACE("...%s...\n",debugstr_guid(riid));
147     hres=IUnknown_QueryInterface(pUnk,riid,(LPVOID*)&newiface);
148     if (hres) {
149         TRACE("%p does not support iface %s\n",pUnk,debugstr_guid(riid));
150         goto fail;
151     }
152     hres = CreateStreamOnHGlobal(0,TRUE,&pStm);
153     if (hres) {
154         FIXME("Stream create failed %lx\n",hres);
155         goto fail;
156     }
157     hres = CoMarshalInterface(pStm,riid,newiface,0,NULL,0);
158     IUnknown_Release(newiface);
159     if (hres) {
160         FIXME("Marshalling interface %s failed with %lx\n",
161                 debugstr_guid(riid),hres
162         );
163         goto fail;
164     }
165     hres = IStream_Stat(pStm,&ststg,0);
166     tempbuf = HeapAlloc(GetProcessHeap(), 0, ststg.cbSize.s.LowPart);
167     memset(&seekto,0,sizeof(seekto));
168     hres = IStream_Seek(pStm,seekto,SEEK_SET,&newpos);
169     if (hres) { FIXME("Failed Seek %lx\n",hres); goto fail;}
170     hres = IStream_Read(pStm,tempbuf,ststg.cbSize.s.LowPart,&res);
171     if (hres) { FIXME("Failed Read %lx\n",hres); goto fail;}
172     IStream_Release(pStm);
173     xsize = ststg.cbSize.s.LowPart;
174     xbuf_add(buf,(LPBYTE)&xsize,sizeof(xsize));
175     hres = xbuf_add(buf,tempbuf,ststg.cbSize.s.LowPart);
176     HeapFree(GetProcessHeap(),0,tempbuf);
177     return hres;
178 fail:
179     xsize = 0;
180     xbuf_add(buf,(LPBYTE)&xsize,sizeof(xsize));
181     return hres;
182 }
183
184 /********************* OLE Proxy/Stub Factory ********************************/
185 static HRESULT WINAPI
186 PSFacBuf_QueryInterface(LPPSFACTORYBUFFER iface, REFIID iid, LPVOID *ppv) {
187     if (IsEqualIID(iid,&IID_IPSFactoryBuffer)||IsEqualIID(iid,&IID_IUnknown)) {
188         *ppv = (LPVOID)iface;
189         /* No ref counting, static class */
190         return S_OK;
191     }
192     FIXME("(%s) unknown IID?\n",debugstr_guid(iid));
193     return E_NOINTERFACE;
194 }
195
196 static ULONG WINAPI PSFacBuf_AddRef(LPPSFACTORYBUFFER iface) { return 2; }
197 static ULONG WINAPI PSFacBuf_Release(LPPSFACTORYBUFFER iface) { return 1; }
198
199 static HRESULT
200 _get_typeinfo_for_iid(REFIID riid, ITypeInfo**ti) {
201     HRESULT     hres;
202     HKEY        ikey;
203     char        tlguid[200],typelibkey[300],interfacekey[300],ver[100];
204     char        tlfn[260];
205     OLECHAR     tlfnW[260];
206     DWORD       tlguidlen, verlen, type, tlfnlen;
207     ITypeLib    *tl;
208
209     sprintf( interfacekey, "Interface\\{%08lx-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}\\Typelib",
210         riid->Data1, riid->Data2, riid->Data3,
211         riid->Data4[0], riid->Data4[1], riid->Data4[2], riid->Data4[3],
212         riid->Data4[4], riid->Data4[5], riid->Data4[6], riid->Data4[7]
213     );
214
215     if (RegOpenKeyA(HKEY_CLASSES_ROOT,interfacekey,&ikey)) {
216         FIXME("No %s key found.\n",interfacekey);
217         return E_FAIL;
218     }
219     type = (1<<REG_SZ);
220     tlguidlen = sizeof(tlguid);
221     if (RegQueryValueExA(ikey,NULL,NULL,&type,tlguid,&tlguidlen)) {
222         FIXME("Getting typelib guid failed.\n");
223         RegCloseKey(ikey);
224         return E_FAIL;
225     }
226     type = (1<<REG_SZ);
227     verlen = sizeof(ver);
228     if (RegQueryValueExA(ikey,"Version",NULL,&type,ver,&verlen)) {
229         FIXME("Could not get version value?\n");
230         RegCloseKey(ikey);
231         return E_FAIL;
232     }
233     RegCloseKey(ikey);
234     sprintf(typelibkey,"Typelib\\%s\\%s\\0\\win32",tlguid,ver);
235     tlfnlen = sizeof(tlfn);
236     if (RegQueryValueA(HKEY_CLASSES_ROOT,typelibkey,tlfn,&tlfnlen)) {
237         FIXME("Could not get typelib fn?\n");
238         return E_FAIL;
239     }
240     MultiByteToWideChar(CP_ACP, 0, tlfn, -1, tlfnW, -1);
241     hres = LoadTypeLib(tlfnW,&tl);
242     if (hres) {
243         ERR("Failed to load typelib for %s, but it should be there.\n",debugstr_guid(riid));
244         return hres;
245     }
246     hres = ITypeLib_GetTypeInfoOfGuid(tl,riid,ti);
247     if (hres) {
248         ERR("typelib does not contain info for %s?\n",debugstr_guid(riid));
249         ITypeLib_Release(tl);
250         return hres;
251     }
252     /* FIXME: do this?  ITypeLib_Release(tl); */
253     return hres;
254 }
255
256 /* Determine nr of functions. Since we use the toplevel interface and all
257  * inherited ones have lower numbers, we are ok to not to descent into
258  * the inheritance tree I think.
259  */
260 static int _nroffuncs(ITypeInfo *tinfo) {
261     int         n, max = 0;
262     FUNCDESC    *fdesc;
263     HRESULT     hres;
264
265     n=0;
266     while (1) {
267         hres = ITypeInfo_GetFuncDesc(tinfo,n,&fdesc);
268         if (hres)
269             return max+1;
270         if (fdesc->oVft/4 > max)
271             max = fdesc->oVft/4;
272         n++;
273     }
274     /*NOTREACHED*/
275 }
276
277 typedef struct _TMAsmProxy {
278     BYTE        popleax;
279     BYTE        pushlval;
280     BYTE        nr;
281     BYTE        pushleax;
282     BYTE        lcall;
283     DWORD       xcall;
284     BYTE        lret;
285     WORD        bytestopop;
286 } WINE_PACKED TMAsmProxy;
287
288 typedef struct _TMProxyImpl {
289     DWORD                               *lpvtbl;
290     ICOM_VTABLE(IRpcProxyBuffer)        *lpvtbl2;
291     DWORD                               ref;
292
293     TMAsmProxy                          *asmstubs;
294     ITypeInfo*                          tinfo;
295     IRpcChannelBuffer*                  chanbuf;
296     IID                                 iid;
297 } TMProxyImpl;
298
299 static HRESULT WINAPI
300 TMProxyImpl_QueryInterface(LPRPCPROXYBUFFER iface, REFIID riid, LPVOID *ppv) {
301     TRACE("()\n");
302     if (IsEqualIID(riid,&IID_IUnknown)||IsEqualIID(riid,&IID_IRpcProxyBuffer)) {
303         *ppv = (LPVOID)iface;
304         IRpcProxyBuffer_AddRef(iface);
305         return S_OK;
306     }
307     FIXME("no interface for %s\n",debugstr_guid(riid));
308     return E_NOINTERFACE;
309 }
310
311 static ULONG WINAPI
312 TMProxyImpl_AddRef(LPRPCPROXYBUFFER iface) {
313     ICOM_THIS_MULTI(TMProxyImpl,lpvtbl2,iface);
314
315     TRACE("()\n");
316     This->ref++;
317     return This->ref;
318 }
319
320 static ULONG WINAPI
321 TMProxyImpl_Release(LPRPCPROXYBUFFER iface) {
322     ICOM_THIS_MULTI(TMProxyImpl,lpvtbl2,iface);
323
324     TRACE("()\n");
325     This->ref--;
326     if (This->ref) return This->ref;
327     if (This->chanbuf) IRpcChannelBuffer_Release(This->chanbuf);
328     HeapFree(GetProcessHeap(),0,This);
329     return 0;
330 }
331
332 static HRESULT WINAPI
333 TMProxyImpl_Connect(
334     LPRPCPROXYBUFFER iface,IRpcChannelBuffer* pRpcChannelBuffer
335 ) {
336     ICOM_THIS_MULTI(TMProxyImpl,lpvtbl2,iface);
337
338     TRACE("(%p)\n",pRpcChannelBuffer);
339     This->chanbuf = pRpcChannelBuffer;
340     IRpcChannelBuffer_AddRef(This->chanbuf);
341     return S_OK;
342 }
343
344 static void WINAPI
345 TMProxyImpl_Disconnect(LPRPCPROXYBUFFER iface) {
346     ICOM_THIS_MULTI(TMProxyImpl,lpvtbl2,iface);
347
348     FIXME("()\n");
349     IRpcChannelBuffer_Release(This->chanbuf);
350     This->chanbuf = NULL;
351 }
352
353
354 static ICOM_VTABLE(IRpcProxyBuffer) tmproxyvtable = {
355     ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
356     TMProxyImpl_QueryInterface,
357     TMProxyImpl_AddRef,
358     TMProxyImpl_Release,
359     TMProxyImpl_Connect,
360     TMProxyImpl_Disconnect
361 };
362
363 /* how much space do we use on stack in DWORD steps. */
364 int const
365 _argsize(DWORD vt) {
366     switch (vt) {
367     case VT_DATE:
368         return sizeof(DATE)/sizeof(DWORD);
369     case VT_VARIANT:
370         return (sizeof(VARIANT)+3)/sizeof(DWORD);
371     default:
372         return 1;
373     }
374 }
375
376 static int
377 _xsize(TYPEDESC *td) {
378     switch (td->vt) {
379     case VT_DATE:
380         return sizeof(DATE);
381     case VT_VARIANT:
382         return sizeof(VARIANT)+3;
383     case VT_CARRAY: {
384         int i, arrsize = 1;
385         ARRAYDESC *adesc = td->u.lpadesc;
386
387         for (i=0;i<adesc->cDims;i++)
388             arrsize *= adesc->rgbounds[i].cElements;
389         return arrsize*_xsize(&adesc->tdescElem);
390     }
391     case VT_UI2:
392     case VT_I2:
393         return 2;
394     case VT_UI1:
395     case VT_I1:
396         return 1;
397     default:
398         return 4;
399     }
400 }
401
402 static HRESULT
403 serialize_param(
404     ITypeInfo           *tinfo,
405     BOOL                writeit,
406     BOOL                debugout,
407     BOOL                dealloc,
408     TYPEDESC            *tdesc,
409     DWORD               *arg,
410     marshal_state       *buf
411 ) {
412     HRESULT hres = S_OK;
413
414     TRACE("(tdesc.vt %d)\n",tdesc->vt);
415
416     switch (tdesc->vt) {
417     case VT_EMPTY: /* nothing. empty variant for instance */
418         return S_OK;
419     case VT_BOOL:
420     case VT_ERROR:
421     case VT_UI4:
422     case VT_UINT:
423     case VT_I4:
424     case VT_R4:
425     case VT_UI2:
426     case VT_UI1:
427         hres = S_OK;
428         if (debugout) MESSAGE("%lx",*arg);
429         if (writeit)
430             hres = xbuf_add(buf,(LPBYTE)arg,sizeof(DWORD));
431         return hres;
432     case VT_VARIANT: {
433         TYPEDESC        tdesc2;
434         VARIANT         *vt = (VARIANT*)arg;
435         DWORD           vttype = V_VT(vt);
436
437         if (debugout) MESSAGE("Vt(%ld)(",vttype);
438         tdesc2.vt = vttype;
439         if (writeit) {
440             hres = xbuf_add(buf,(LPBYTE)&vttype,sizeof(vttype));
441             if (hres) return hres;
442         }
443         /* need to recurse since we need to free the stuff */
444         hres = serialize_param(tinfo,writeit,debugout,dealloc,&tdesc2,&(V_I4(vt)),buf);
445         if (debugout) MESSAGE(")");
446         return hres;
447     }
448     case VT_BSTR: {
449         if (debugout) {
450             if (arg)
451                     MESSAGE("%s",debugstr_w((BSTR)*arg));
452             else
453                     MESSAGE("<bstr NULL>");
454         }
455         if (writeit) {
456             if (!*arg) {
457                 DWORD fakelen = -1;
458                 hres = xbuf_add(buf,(LPBYTE)&fakelen,4);
459                 if (hres)
460                     return hres;
461             } else {
462                 DWORD *bstr = ((DWORD*)(*arg))-1;
463
464                 hres = xbuf_add(buf,(LPBYTE)bstr,bstr[0]+4);
465                 if (hres)
466                     return hres;
467             }
468         }
469         if (dealloc && arg)
470             SysFreeString((BSTR)arg);
471         return S_OK;
472     }
473     case VT_PTR: {
474         DWORD cookie;
475
476         if (debugout) MESSAGE("*");
477         if (writeit) {
478             cookie = *arg ? 0x42424242 : 0;
479             hres = xbuf_add(buf,(LPBYTE)&cookie,sizeof(cookie));
480             if (hres)
481                 return hres;
482         }
483         if (!*arg) {
484             if (debugout) MESSAGE("NULL");
485             return S_OK;
486         }
487         hres = serialize_param(tinfo,writeit,debugout,dealloc,tdesc->u.lptdesc,(DWORD*)*arg,buf);
488         if (dealloc) HeapFree(GetProcessHeap(),0,(LPVOID)arg);
489         return hres;
490     }
491     case VT_UNKNOWN:
492         if (debugout) MESSAGE("unk(0x%lx)",*arg);
493         if (writeit)
494             hres = _marshal_interface(buf,&IID_IUnknown,(LPUNKNOWN)*arg);
495         return hres;
496     case VT_DISPATCH:
497         if (debugout) MESSAGE("idisp(0x%lx)",*arg);
498         if (writeit)
499             hres = _marshal_interface(buf,&IID_IDispatch,(LPUNKNOWN)*arg);
500         return hres;
501     case VT_VOID:
502         if (debugout) MESSAGE("<void>");
503         return S_OK;
504     case VT_USERDEFINED: {
505         ITypeInfo       *tinfo2;
506         TYPEATTR        *tattr;
507
508         hres = ITypeInfo_GetRefTypeInfo(tinfo,tdesc->u.hreftype,&tinfo2);
509         if (hres) {
510             FIXME("Could not get typeinfo of hreftype %lx for VT_USERDEFINED.\n",tdesc->u.hreftype);
511             return hres;
512         }
513         ITypeInfo_GetTypeAttr(tinfo2,&tattr);
514         switch (tattr->typekind) {
515         case TKIND_DISPATCH:
516         case TKIND_INTERFACE:
517             if (writeit)
518                hres=_marshal_interface(buf,&(tattr->guid),(LPUNKNOWN)arg);
519             break;
520         case TKIND_RECORD: {
521             int i;
522             if (debugout) MESSAGE("{");
523             for (i=0;i<tattr->cVars;i++) {
524                 VARDESC *vdesc;
525                 ELEMDESC *elem2;
526                 TYPEDESC *tdesc2;
527
528                 hres = ITypeInfo2_GetVarDesc(tinfo2, i, &vdesc);
529                 if (hres) {
530                     FIXME("Could not get vardesc of %d\n",i);
531                     return hres;
532                 }
533                 /* Need them for hack below */
534                 /*
535                 memset(names,0,sizeof(names));
536                 hres = ITypeInfo_GetNames(tinfo2,vdesc->memid,names,sizeof(names)/sizeof(names[0]),&nrofnames);
537                 if (nrofnames > sizeof(names)/sizeof(names[0])) {
538                     ERR("Need more names!\n");
539                 }
540                 if (!hres && debugout)
541                     MESSAGE("%s=",debugstr_w(names[0]));
542                 */
543                 elem2 = &vdesc->elemdescVar;
544                 tdesc2 = &elem2->tdesc;
545                 hres = serialize_param(
546                     tinfo2,
547                     writeit,
548                     debugout,
549                     dealloc,
550                     tdesc2,
551                     (DWORD*)(((LPBYTE)arg)+vdesc->u.oInst),
552                     buf
553                 );
554                 if (hres!=S_OK)
555                     return hres;
556                 if (debugout && (i<(tattr->cVars-1)))
557                     MESSAGE(",");
558             }
559             if (buf->thisisiid && (tattr->cbSizeInstance==sizeof(GUID)))
560                 memcpy(&(buf->iid),arg,sizeof(buf->iid));
561             if (debugout) MESSAGE("}");
562             break;
563         }
564         default:
565             FIXME("Unhandled typekind %d\n",tattr->typekind);
566             hres = E_FAIL;
567             break;
568         }
569         ITypeInfo_Release(tinfo2);
570         return hres;
571     }
572     case VT_CARRAY: {
573         ARRAYDESC *adesc = tdesc->u.lpadesc;
574         int i, arrsize = 1;
575
576         if (debugout) MESSAGE("carr");
577         for (i=0;i<adesc->cDims;i++) {
578             if (debugout) MESSAGE("[%ld]",adesc->rgbounds[i].cElements);
579             arrsize *= adesc->rgbounds[i].cElements;
580         }
581         if (debugout) MESSAGE("[");
582         for (i=0;i<arrsize;i++) {
583             hres = serialize_param(tinfo, writeit, debugout, dealloc, &adesc->tdescElem, (DWORD*)((LPBYTE)arg+i*_xsize(&adesc->tdescElem)), buf);
584             if (hres)
585                 return hres;
586             if (debugout && (i<arrsize-1)) MESSAGE(",");
587         }
588         if (debugout) MESSAGE("]");
589         return S_OK;
590     }
591     default:
592         ERR("Unhandled marshal type %d.\n",tdesc->vt);
593         return S_OK;
594     }
595 }
596
597 static HRESULT
598 serialize_LPVOID_ptr(
599     ITypeInfo           *tinfo,
600     BOOL                writeit,
601     BOOL                debugout,
602     BOOL                dealloc,
603     TYPEDESC            *tdesc,
604     DWORD               *arg,
605     marshal_state       *buf
606 ) {
607     HRESULT     hres;
608     DWORD       cookie;
609
610     if ((tdesc->vt != VT_PTR)                   ||
611         (tdesc->u.lptdesc->vt != VT_PTR)        ||
612         (tdesc->u.lptdesc->u.lptdesc->vt != VT_VOID)
613     ) {
614         FIXME("ppvObject not expressed as VT_PTR -> VT_PTR -> VT_VOID?\n");
615         return E_FAIL;
616     }
617     cookie = (*arg) ? 0x42424242: 0x0;
618     if (writeit) {
619         hres = xbuf_add(buf, (LPVOID)&cookie, sizeof(cookie));
620         if (hres)
621             return hres;
622     }
623     if (!*arg) {
624         if (debugout) MESSAGE("<lpvoid NULL>");
625         return S_OK;
626     }
627     if (debugout)
628         MESSAGE("ppv(%p)",*(LPUNKNOWN*)*arg);
629     if (writeit) {
630         hres = _marshal_interface(buf,&(buf->iid),*(LPUNKNOWN*)*arg);
631         if (hres)
632             return hres;
633     }
634     if (dealloc)
635         HeapFree(GetProcessHeap(),0,(LPVOID)*arg);
636     return S_OK;
637 }
638
639 static HRESULT
640 serialize_DISPPARAM_ptr(
641     ITypeInfo           *tinfo,
642     BOOL                writeit,
643     BOOL                debugout,
644     BOOL                dealloc,
645     TYPEDESC            *tdesc,
646     DWORD               *arg,
647     marshal_state       *buf
648 ) {
649     DWORD       cookie;
650     HRESULT     hres;
651     DISPPARAMS  *disp;
652     int         i;
653
654     if ((tdesc->vt != VT_PTR) || (tdesc->u.lptdesc->vt != VT_USERDEFINED)) {
655         FIXME("DISPPARAMS not expressed as VT_PTR -> VT_USERDEFINED?\n");
656         return E_FAIL;
657     }
658
659     cookie = *arg ? 0x42424242 : 0x0;
660     if (writeit) {
661         hres = xbuf_add(buf,(LPBYTE)&cookie,sizeof(cookie));
662         if (hres)
663             return hres;
664     }
665     if (!*arg) {
666         if (debugout) MESSAGE("<DISPPARAMS NULL>");
667         return S_OK;
668     }
669     disp = (DISPPARAMS*)*arg;
670     if (writeit) {
671         hres = xbuf_add(buf,(LPBYTE)&disp->cArgs,sizeof(disp->cArgs));
672         if (hres)
673             return hres;
674     }
675     if (debugout) MESSAGE("D{");
676     for (i=0;i<disp->cArgs;i++) {
677         TYPEDESC        vtdesc;
678
679         vtdesc.vt = VT_VARIANT;
680         serialize_param(
681             tinfo,
682             writeit,
683             debugout,
684             dealloc,
685             &vtdesc,
686             (DWORD*)(disp->rgvarg+i),
687             buf
688         );
689         if (debugout && (i<disp->cArgs-1))
690             MESSAGE(",");
691     }
692     if (dealloc)
693         HeapFree(GetProcessHeap(),0,disp->rgvarg);
694     if (writeit) {
695         hres = xbuf_add(buf,(LPBYTE)&disp->cNamedArgs,sizeof(disp->cNamedArgs));
696         if (hres)
697             return hres;
698     }
699     if (debugout) MESSAGE("}{");
700     for (i=0;i<disp->cNamedArgs;i++) {
701         TYPEDESC        vtdesc;
702
703         vtdesc.vt = VT_UINT;
704         serialize_param(
705             tinfo,
706             writeit,
707             debugout,
708             dealloc,
709             &vtdesc,
710             (DWORD*)(disp->rgdispidNamedArgs+i),
711             buf
712         );
713         if (debugout && (i<disp->cNamedArgs-1))
714             MESSAGE(",");
715     }
716     if (debugout) MESSAGE("}");
717     if (dealloc) {
718         HeapFree(GetProcessHeap(),0,disp->rgdispidNamedArgs);
719         HeapFree(GetProcessHeap(),0,disp);
720     }
721     return S_OK;
722 }
723
724 static HRESULT
725 deserialize_param(
726     ITypeInfo           *tinfo,
727     BOOL                readit,
728     BOOL                debugout,
729     BOOL                alloc,
730     TYPEDESC            *tdesc,
731     DWORD               *arg,
732     marshal_state       *buf
733 ) {
734     HRESULT hres = S_OK;
735
736     TRACE("vt %d at %p\n",tdesc->vt,arg);
737
738     while (1) {
739         switch (tdesc->vt) {
740         case VT_EMPTY:
741             if (debugout) MESSAGE("<empty>");
742             return S_OK;
743         case VT_NULL:
744             if (debugout) MESSAGE("<null>");
745             return S_OK;
746         case VT_VARIANT: {
747             VARIANT     *vt = (VARIANT*)arg;
748
749             if (readit) {
750                 DWORD   vttype;
751                 TYPEDESC        tdesc2;
752                 hres = xbuf_get(buf,(LPBYTE)&vttype,sizeof(vttype));
753                 if (hres) {
754                     FIXME("vt type not read?\n");
755                     return hres;
756                 }
757                 memset(&tdesc2,0,sizeof(tdesc2));
758                 tdesc2.vt = vttype;
759                 V_VT(vt)  = vttype;
760                 if (debugout) MESSAGE("Vt(%ld)(",vttype);
761                 hres = deserialize_param(tinfo, readit, debugout, alloc, &tdesc2, &(V_I4(vt)), buf);
762                 MESSAGE(")");
763                 return hres;
764             } else {
765                 VariantInit(vt);
766                 return S_OK;
767             }
768         }
769         case VT_ERROR:
770         case VT_BOOL: case VT_I4: case VT_UI4: case VT_UINT: case VT_R4:
771         case VT_UI2:
772         case VT_UI1:
773             if (readit) {
774                 hres = xbuf_get(buf,(LPBYTE)arg,sizeof(DWORD));
775                 if (hres) FIXME("Failed to read integer 4 byte\n");
776             }
777             if (debugout) MESSAGE("%lx",*arg);
778             return hres;
779         case VT_BSTR: {
780             WCHAR       *str;
781             DWORD       len;
782
783             if (readit) {
784                 hres = xbuf_get(buf,(LPBYTE)&len,sizeof(DWORD));
785                 if (hres) {
786                     FIXME("failed to read bstr klen\n");
787                     return hres;
788                 }
789                 if (len == -1) {
790                     *arg = 0;
791                     if (debugout) MESSAGE("<bstr NULL>");
792                 } else {
793                     str  = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,len+sizeof(WCHAR));
794                     hres = xbuf_get(buf,(LPBYTE)str,len);
795                     if (hres) {
796                         FIXME("Failed to read BSTR.\n");
797                         return hres;
798                     }
799                     *arg = (DWORD)SysAllocStringLen(str,len);
800                     if (debugout) MESSAGE("%s",debugstr_w(str));
801                     HeapFree(GetProcessHeap(),0,str);
802                 }
803             } else {
804                 *arg = 0;
805             }
806             return S_OK;
807         }
808         case VT_PTR: {
809             DWORD       cookie;
810             BOOL        derefhere = 0;
811
812             derefhere = (tdesc->u.lptdesc->vt != VT_USERDEFINED);
813
814             if (readit) {
815                 hres = xbuf_get(buf,(LPBYTE)&cookie,sizeof(cookie));
816                 if (hres) {
817                     FIXME("Failed to load pointer cookie.\n");
818                     return hres;
819                 }
820                 if (cookie != 0x42424242) {
821                     if (debugout) MESSAGE("NULL");
822                     *arg = 0;
823                     return S_OK;
824                 }
825                 if (debugout) MESSAGE("*");
826             }
827             if (alloc) {
828                 if (derefhere)
829                     *arg=(DWORD)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,_xsize(tdesc->u.lptdesc));
830             }
831             if (derefhere)
832                 return deserialize_param(tinfo, readit, debugout, alloc, tdesc->u.lptdesc, (LPDWORD)*arg, buf);
833             else
834                 return deserialize_param(tinfo, readit, debugout, alloc, tdesc->u.lptdesc, arg, buf);
835         }
836         case VT_UNKNOWN:
837             /* FIXME: UNKNOWN is unknown ..., but allocate 4 byte for it */
838             if (alloc)
839                 *arg=(DWORD)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(DWORD));
840             hres = S_OK;
841             if (readit)
842                 hres = _unmarshal_interface(buf,&IID_IUnknown,(LPUNKNOWN*)arg);
843             if (debugout)
844                 MESSAGE("unk(%p)",arg);
845             return hres;
846         case VT_DISPATCH:
847             hres = S_OK;
848             if (readit)
849                 hres = _unmarshal_interface(buf,&IID_IDispatch,(LPUNKNOWN*)arg);
850             if (debugout)
851                 MESSAGE("idisp(%p)",arg);
852             return hres;
853         case VT_VOID:
854             if (debugout) MESSAGE("<void>");
855             return S_OK;
856         case VT_USERDEFINED: {
857             ITypeInfo   *tinfo2;
858             TYPEATTR    *tattr;
859
860             hres = ITypeInfo_GetRefTypeInfo(tinfo,tdesc->u.hreftype,&tinfo2);
861             if (hres) {
862                 FIXME("Could not get typeinfo of hreftype %lx for VT_USERDEFINED.\n",tdesc->u.hreftype);
863                 return hres;
864             }
865             hres = ITypeInfo_GetTypeAttr(tinfo2,&tattr);
866             if (hres) {
867                 FIXME("Could not get typeattr in VT_USERDEFINED.\n");
868             } else {
869                 if (alloc)
870                     *arg = (DWORD)HeapAlloc(GetProcessHeap(),0,tattr->cbSizeInstance);
871                 switch (tattr->typekind) {
872                 case TKIND_DISPATCH:
873                 case TKIND_INTERFACE:
874                     if (readit)
875                         hres = _unmarshal_interface(buf,&(tattr->guid),(LPUNKNOWN*)arg);
876                     break;
877                 case TKIND_RECORD: {
878                     int i;
879
880                     if (debugout) MESSAGE("{");
881                     for (i=0;i<tattr->cVars;i++) {
882                         VARDESC *vdesc;
883
884                         hres = ITypeInfo2_GetVarDesc(tinfo2, i, &vdesc);
885                         if (hres) {
886                             FIXME("Could not get vardesc of %d\n",i);
887                             return hres;
888                         }
889                         hres = deserialize_param(
890                             tinfo2,
891                             readit,
892                             debugout,
893                             alloc,
894                             &vdesc->elemdescVar.tdesc,
895                             (DWORD*)(((LPBYTE)*arg)+vdesc->u.oInst),
896                             buf
897                         );
898                         if (debugout && (i<tattr->cVars-1)) MESSAGE(",");
899                     }
900                     if (buf->thisisiid && (tattr->cbSizeInstance==sizeof(GUID)))
901                         memcpy(&(buf->iid),(LPBYTE)*arg,sizeof(buf->iid));
902                     if (debugout) MESSAGE("}");
903                     break;
904                 }
905                 default:
906                     ERR("Unhandled typekind %d\n",tattr->typekind);
907                     hres = E_FAIL;
908                     break;
909                 }
910             }
911             if (hres)
912                 FIXME("failed to stuballoc in TKIND_RECORD.\n");
913             ITypeInfo_Release(tinfo2);
914             return hres;
915         }
916         case VT_CARRAY: {
917             /* arg is pointing to the start of the array. */
918             ARRAYDESC *adesc = tdesc->u.lpadesc;
919             int         arrsize,i;
920             arrsize = 1;
921             if (adesc->cDims > 1) FIXME("cDims > 1 in VT_CARRAY. Does it work?\n");
922             for (i=0;i<adesc->cDims;i++)
923                 arrsize *= adesc->rgbounds[i].cElements;
924             for (i=0;i<arrsize;i++)
925                 deserialize_param(
926                     tinfo,
927                     readit,
928                     debugout,
929                     alloc,
930                     &adesc->tdescElem,
931                     (DWORD*)((LPBYTE)(arg)+i*_xsize(&adesc->tdescElem)),
932                     buf
933                 );
934             return S_OK;
935         }
936         default:
937             ERR("No handler for VT type %d!\n",tdesc->vt);
938             return S_OK;
939         }
940     }
941 }
942
943 static HRESULT
944 deserialize_LPVOID_ptr(
945     ITypeInfo           *tinfo,
946     BOOL                readit,
947     BOOL                debugout,
948     BOOL                alloc,
949     TYPEDESC            *tdesc,
950     DWORD               *arg,
951     marshal_state       *buf
952 ) {
953     HRESULT     hres;
954     DWORD       cookie;
955
956     if ((tdesc->vt != VT_PTR)                   ||
957         (tdesc->u.lptdesc->vt != VT_PTR)        ||
958         (tdesc->u.lptdesc->u.lptdesc->vt != VT_VOID)
959     ) {
960         FIXME("ppvObject not expressed as VT_PTR -> VT_PTR -> VT_VOID?\n");
961         return E_FAIL;
962     }
963     if (alloc)
964         *arg=(DWORD)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(LPVOID));
965     if (readit) {
966         hres = xbuf_get(buf, (LPVOID)&cookie, sizeof(cookie));
967         if (hres)
968             return hres;
969         if (cookie != 0x42424242) {
970             *(DWORD*)*arg = 0;
971             if (debugout) MESSAGE("<lpvoid NULL>");
972             return S_OK;
973         }
974     }
975     if (readit) {
976         hres = _unmarshal_interface(buf,&buf->iid,(LPUNKNOWN*)*arg);
977         if (hres)
978             return hres;
979     }
980     if (debugout) MESSAGE("ppv(%p)",(LPVOID)*arg);
981     return S_OK;
982 }
983
984 static HRESULT
985 deserialize_DISPPARAM_ptr(
986     ITypeInfo           *tinfo,
987     BOOL                readit,
988     BOOL                debugout,
989     BOOL                alloc,
990     TYPEDESC            *tdesc,
991     DWORD               *arg,
992     marshal_state       *buf
993 ) {
994     DWORD       cookie;
995     DISPPARAMS  *disps;
996     HRESULT     hres;
997     int         i;
998
999     if ((tdesc->vt != VT_PTR) || (tdesc->u.lptdesc->vt != VT_USERDEFINED)) {
1000         FIXME("DISPPARAMS not expressed as VT_PTR -> VT_USERDEFINED?\n");
1001         return E_FAIL;
1002     }
1003     if (readit) {
1004         hres = xbuf_get(buf,(LPBYTE)&cookie,sizeof(cookie));
1005         if (hres)
1006             return hres;
1007         if (cookie == 0) {
1008             *arg = 0;
1009             if (debugout) MESSAGE("<DISPPARAMS NULL>");
1010             return S_OK;
1011         }
1012     }
1013     if (alloc)
1014         *arg = (DWORD)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(DISPPARAMS));
1015     disps = (DISPPARAMS*)*arg;
1016     if (!readit)
1017         return S_OK;
1018     hres = xbuf_get(buf, (LPBYTE)&disps->cArgs, sizeof(disps->cArgs));
1019     if (hres)
1020         return hres;
1021     if (alloc)
1022         disps->rgvarg = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(VARIANT)*disps->cArgs);
1023     if (debugout) MESSAGE("D{");
1024     for (i=0; i< disps->cArgs; i++) {
1025         TYPEDESC vdesc;
1026
1027         vdesc.vt = VT_VARIANT;
1028         hres = deserialize_param(
1029             tinfo,
1030             readit,
1031             debugout,
1032             alloc,
1033             &vdesc,
1034             (DWORD*)(disps->rgvarg+i),
1035             buf
1036         );
1037     }
1038     if (debugout) MESSAGE("}{");
1039     hres = xbuf_get(buf, (LPBYTE)&disps->cNamedArgs, sizeof(disps->cNamedArgs));
1040     if (hres)
1041         return hres;
1042     if (disps->cNamedArgs) {
1043         if (alloc)
1044             disps->rgdispidNamedArgs = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(DISPID)*disps->cNamedArgs);
1045         for (i=0; i< disps->cNamedArgs; i++) {
1046             TYPEDESC vdesc;
1047
1048             vdesc.vt = VT_UINT;
1049             hres = deserialize_param(
1050                 tinfo,
1051                 readit,
1052                 debugout,
1053                 alloc,
1054                 &vdesc,
1055                 (DWORD*)(disps->rgdispidNamedArgs+i),
1056                 buf
1057             );
1058             if (debugout && i<(disps->cNamedArgs-1)) MESSAGE(",");
1059         }
1060     }
1061     if (debugout) MESSAGE("}");
1062     return S_OK;
1063 }
1064
1065 /* Searches function, also in inherited interfaces */
1066 static HRESULT
1067 _get_funcdesc(
1068     ITypeInfo *tinfo, int iMethod, FUNCDESC **fdesc, BSTR *iname, BSTR *fname
1069 ) {
1070     int i = 0, j = 0;
1071     HRESULT hres;
1072
1073     if (fname) *fname = NULL;
1074     if (iname) *iname = NULL;
1075
1076     while (1) {
1077         hres = ITypeInfo_GetFuncDesc(tinfo, i, fdesc);
1078         if (hres) {
1079             ITypeInfo   *tinfo2;
1080             HREFTYPE    href;
1081             TYPEATTR    *attr;
1082
1083             hres = ITypeInfo_GetTypeAttr(tinfo, &attr);
1084             if (hres) {
1085                 FIXME("GetTypeAttr failed with %lx\n",hres);
1086                 return hres;
1087             }
1088             /* Not found, so look in inherited ifaces. */
1089             for (j=0;j<attr->cImplTypes;j++) {
1090                 hres = ITypeInfo_GetRefTypeOfImplType(tinfo, j, &href);
1091                 if (hres) {
1092                     FIXME("Did not find a reftype for interface offset %d?\n",j);
1093                     break;
1094                 }
1095                 hres = ITypeInfo_GetRefTypeInfo(tinfo, href, &tinfo2);
1096                 if (hres) {
1097                     FIXME("Did not find a typeinfo for reftype %ld?\n",href);
1098                     continue;
1099                 }
1100                 hres = _get_funcdesc(tinfo2,iMethod,fdesc,iname,fname);
1101                 ITypeInfo_Release(tinfo2);
1102                 if (!hres) return S_OK;
1103             }
1104             return E_FAIL;
1105         }
1106         if (((*fdesc)->oVft/4) == iMethod) {
1107             if (fname)
1108                 ITypeInfo_GetDocumentation(tinfo,(*fdesc)->memid,fname,NULL,NULL,NULL);
1109             if (iname)
1110                 ITypeInfo_GetDocumentation(tinfo,-1,iname,NULL,NULL,NULL);
1111             return S_OK;
1112         }
1113         i++;
1114     }
1115     return E_FAIL;
1116 }
1117
1118 static DWORD
1119 xCall(LPVOID retptr, int method, TMProxyImpl *tpinfo /*, args */) {
1120     DWORD               *args = ((DWORD*)&tpinfo)+1, *xargs;
1121     FUNCDESC            *fdesc;
1122     HRESULT             hres;
1123     int                 i, relaydeb = TRACE_ON(olerelay);
1124     marshal_state       buf;
1125     RPCOLEMESSAGE       msg;
1126     ULONG               status;
1127     BSTR                fname,iname;
1128     BSTR                names[10];
1129     int                 nrofnames;
1130
1131     hres = _get_funcdesc(tpinfo->tinfo,method,&fdesc,&iname,&fname);
1132     if (hres) {
1133         ERR("Did not find typeinfo/funcdesc entry for method %d!\n",method);
1134         return 0;
1135     }
1136
1137     /*dump_FUNCDESC(fdesc);*/
1138     if (relaydeb) {
1139         TRACE_(olerelay)("->");
1140         if (iname)
1141             MESSAGE("%s:",debugstr_w(iname));
1142         if (fname)
1143             MESSAGE("%s(%d)",debugstr_w(fname),method);
1144         else
1145             MESSAGE("%d",method);
1146         MESSAGE("(");
1147         if (iname) SysFreeString(iname);
1148         if (fname) SysFreeString(fname);
1149     }
1150     /* Need them for hack below */
1151     memset(names,0,sizeof(names));
1152     if (ITypeInfo_GetNames(tpinfo->tinfo,fdesc->memid,names,sizeof(names)/sizeof(names[0]),&nrofnames))
1153         nrofnames = 0;
1154     if (nrofnames > sizeof(names)/sizeof(names[0]))
1155         ERR("Need more names!\n");
1156
1157     memset(&buf,0,sizeof(buf));
1158     buf.iid = IID_IUnknown;
1159     if (method == 0) {
1160         xbuf_add(&buf,(LPBYTE)args[0],sizeof(IID));
1161         if (relaydeb) MESSAGE("riid=%s,[out]",debugstr_guid((REFIID)args[0]));
1162     } else {
1163         xargs = args;
1164         for (i=0;i<fdesc->cParams;i++) {
1165             ELEMDESC    *elem = fdesc->lprgelemdescParam+i;
1166             BOOL        isserialized = FALSE;
1167             if (relaydeb) {
1168                 if (i) MESSAGE(",");
1169                 if (i+1<nrofnames && names[i+1])
1170                     MESSAGE("%s=",debugstr_w(names[i+1]));
1171             }
1172             /* No need to marshal other data than FIN */
1173             if (!(elem->u.paramdesc.wParamFlags & PARAMFLAG_FIN)) {
1174                 xargs+=_argsize(elem->tdesc.vt);
1175                 if (relaydeb) MESSAGE("[out]");
1176                 continue;
1177             }
1178             if (((i+1)<nrofnames) && !IsBadStringPtrW(names[i+1],1)) {
1179                 /* If the parameter is 'riid', we use it as interface IID
1180                  * for a later ppvObject serialization.
1181                  */
1182                 buf.thisisiid = !lstrcmpW(names[i+1],riidW);
1183
1184                 /* DISPPARAMS* needs special serializer */
1185                 if (!lstrcmpW(names[i+1],pdispparamsW)) {
1186                     hres = serialize_DISPPARAM_ptr(
1187                         tpinfo->tinfo,
1188                         elem->u.paramdesc.wParamFlags & PARAMFLAG_FIN,
1189                         relaydeb,
1190                         FALSE,
1191                         &elem->tdesc,
1192                         xargs,
1193                         &buf
1194                     );
1195                     isserialized = TRUE;
1196                 }
1197                 if (!lstrcmpW(names[i+1],ppvObjectW)) {
1198                     hres = serialize_LPVOID_ptr(
1199                         tpinfo->tinfo,
1200                         elem->u.paramdesc.wParamFlags & PARAMFLAG_FIN,
1201                         relaydeb,
1202                         FALSE,
1203                         &elem->tdesc,
1204                         xargs,
1205                         &buf
1206                     );
1207                     if (hres == S_OK)
1208                         isserialized = TRUE;
1209                 }
1210             }
1211             if (!isserialized)
1212                 hres = serialize_param(
1213                     tpinfo->tinfo,
1214                     elem->u.paramdesc.wParamFlags & PARAMFLAG_FIN,
1215                     relaydeb,
1216                     FALSE,
1217                     &elem->tdesc,
1218                     xargs,
1219                     &buf
1220                 );
1221
1222             if (hres) {
1223                 FIXME("Failed to serialize param, hres %lx\n",hres);
1224                 break;
1225             }
1226             xargs+=_argsize(elem->tdesc.vt);
1227         }
1228     }
1229     if (relaydeb) MESSAGE(")");
1230     memset(&msg,0,sizeof(msg));
1231     msg.cbBuffer = buf.curoff;
1232     msg.iMethod  = method;
1233     hres = IRpcChannelBuffer_GetBuffer(tpinfo->chanbuf,&msg,&(tpinfo->iid));
1234     if (hres) {
1235         FIXME("RpcChannelBuffer GetBuffer failed, %lx\n",hres);
1236         return hres;
1237     }
1238     memcpy(msg.Buffer,buf.base,buf.curoff);
1239     if (relaydeb) MESSAGE("\n");
1240     hres = IRpcChannelBuffer_SendReceive(tpinfo->chanbuf,&msg,&status);
1241     if (hres) {
1242         FIXME("RpcChannelBuffer SendReceive failed, %lx\n",hres);
1243         return hres;
1244     }
1245     relaydeb = TRACE_ON(olerelay);
1246     if (relaydeb) MESSAGE(" = %08lx (",status);
1247     if (buf.base)
1248         buf.base = HeapReAlloc(GetProcessHeap(),0,buf.base,msg.cbBuffer);
1249     else
1250         buf.base = HeapAlloc(GetProcessHeap(),0,msg.cbBuffer);
1251     buf.size = msg.cbBuffer;
1252     memcpy(buf.base,msg.Buffer,buf.size);
1253     buf.curoff = 0;
1254     if (method == 0) {
1255         _unmarshal_interface(&buf,(REFIID)args[0],(LPUNKNOWN*)args[1]);
1256         if (relaydeb) MESSAGE("[in],%p",*((DWORD**)args[1]));
1257     } else {
1258         xargs = args;
1259         for (i=0;i<fdesc->cParams;i++) {
1260             ELEMDESC    *elem = fdesc->lprgelemdescParam+i;
1261             BOOL        isdeserialized = FALSE;
1262
1263             if (relaydeb) {
1264                 if (i) MESSAGE(",");
1265                 if (i+1<nrofnames && names[i+1]) MESSAGE("%s=",debugstr_w(names[i+1]));
1266             }
1267             /* No need to marshal other data than FOUT I think */
1268             if (!(elem->u.paramdesc.wParamFlags & PARAMFLAG_FOUT)) {
1269                 xargs += _argsize(elem->tdesc.vt);
1270                 if (relaydeb) MESSAGE("[in]");
1271                 continue;
1272             }
1273             if (((i+1)<nrofnames) && !IsBadStringPtrW(names[i+1],1)) {
1274                 /* If the parameter is 'riid', we use it as interface IID
1275                  * for a later ppvObject serialization.
1276                  */
1277                 buf.thisisiid = !lstrcmpW(names[i+1],riidW);
1278
1279                 /* deserialize DISPPARAM */
1280                 if (!lstrcmpW(names[i+1],pdispparamsW)) {
1281                     hres = deserialize_DISPPARAM_ptr(
1282                         tpinfo->tinfo,
1283                         elem->u.paramdesc.wParamFlags & PARAMFLAG_FOUT,
1284                         relaydeb,
1285                         FALSE,
1286                         &(elem->tdesc),
1287                         xargs,
1288                         &buf
1289                     );
1290                     if (hres) {
1291                         FIXME("Failed to deserialize DISPPARAM*, hres %lx\n",hres);
1292                         break;
1293                     }
1294                     isdeserialized = TRUE;
1295                 }
1296                 if (!lstrcmpW(names[i+1],ppvObjectW)) {
1297                     hres = deserialize_LPVOID_ptr(
1298                         tpinfo->tinfo,
1299                         elem->u.paramdesc.wParamFlags & PARAMFLAG_FOUT,
1300                         relaydeb,
1301                         FALSE,
1302                         &elem->tdesc,
1303                         xargs,
1304                         &buf
1305                     );
1306                     if (hres == S_OK)
1307                         isdeserialized = TRUE;
1308                 }
1309             }
1310             if (!isdeserialized)
1311                 hres = deserialize_param(
1312                     tpinfo->tinfo,
1313                     elem->u.paramdesc.wParamFlags & PARAMFLAG_FOUT,
1314                     relaydeb,
1315                     FALSE,
1316                     &(elem->tdesc),
1317                     xargs,
1318                     &buf
1319                 );
1320             if (hres) {
1321                 FIXME("Failed to unmarshall param, hres %lx\n",hres);
1322                 break;
1323             }
1324             xargs += _argsize(elem->tdesc.vt);
1325         }
1326     }
1327     if (relaydeb) MESSAGE(")\n\n");
1328     HeapFree(GetProcessHeap(),0,buf.base);
1329     return status;
1330 }
1331
1332 static HRESULT WINAPI
1333 PSFacBuf_CreateProxy(
1334     LPPSFACTORYBUFFER iface, IUnknown* pUnkOuter, REFIID riid,
1335     IRpcProxyBuffer **ppProxy, LPVOID *ppv
1336 ) {
1337     HRESULT     hres;
1338     ITypeInfo   *tinfo;
1339     int         i, nroffuncs;
1340     FUNCDESC    *fdesc;
1341     TMProxyImpl *proxy;
1342
1343     TRACE("(...%s...)\n",debugstr_guid(riid));
1344     hres = _get_typeinfo_for_iid(riid,&tinfo);
1345     if (hres) {
1346         FIXME("No typeinfo for %s?\n",debugstr_guid(riid));
1347         return hres;
1348     }
1349     nroffuncs = _nroffuncs(tinfo);
1350     proxy = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(TMProxyImpl));
1351     if (!proxy) return E_OUTOFMEMORY;
1352     proxy->asmstubs=HeapAlloc(GetProcessHeap(),0,sizeof(TMAsmProxy)*nroffuncs);
1353
1354     assert(sizeof(TMAsmProxy) == 12);
1355
1356     proxy->lpvtbl = HeapAlloc(GetProcessHeap(),0,sizeof(LPBYTE)*nroffuncs);
1357     for (i=0;i<nroffuncs;i++) {
1358         int             nrofargs;
1359         TMAsmProxy      *xasm = proxy->asmstubs+i;
1360
1361         /* nrofargs without This */
1362         switch (i) {
1363         case 0: nrofargs = 2;
1364                 break;
1365         case 1: case 2: nrofargs = 0;
1366                 break;
1367         default: {
1368                 int j;
1369                 hres = _get_funcdesc(tinfo,i,&fdesc,NULL,NULL);
1370                 if (hres) {
1371                     FIXME("GetFuncDesc %lx should not fail here.\n",hres);
1372                     return hres;
1373                 }
1374                 /* some args take more than 4 byte on the stack */
1375                 nrofargs = 0;
1376                 for (j=0;j<fdesc->cParams;j++)
1377                     nrofargs += _argsize(fdesc->lprgelemdescParam[j].tdesc.vt);
1378
1379                 if (fdesc->callconv != CC_STDCALL) {
1380                     ERR("calling convention is not stdcall????\n");
1381                     return E_FAIL;
1382                 }
1383                 break;
1384             }
1385         }
1386 /* popl %eax    -       return ptr
1387  * pushl <nr>
1388  * pushl %eax
1389  * call xCall
1390  * lret <nr> (+4)
1391  *
1392  *
1393  * arg3 arg2 arg1 <method> <returnptr>
1394  */
1395         xasm->popleax   = 0x58;
1396         xasm->pushlval  = 0x6a;
1397         xasm->nr        = i;
1398         xasm->pushleax  = 0x50;
1399         xasm->lcall     = 0xe8; /* relative jump */
1400         xasm->xcall     = (DWORD)xCall;
1401         xasm->xcall     -= (DWORD)&(xasm->lret);
1402         xasm->lret      = 0xc2;
1403         xasm->bytestopop= (nrofargs+2)*4; /* pop args, This, iMethod */
1404         proxy->lpvtbl[i] = (DWORD)xasm;
1405     }
1406     proxy->lpvtbl2      = &tmproxyvtable;
1407     proxy->ref          = 2;
1408     proxy->tinfo        = tinfo;
1409     memcpy(&proxy->iid,riid,sizeof(*riid));
1410     *ppv                = (LPVOID)proxy;
1411     *ppProxy            = (IRpcProxyBuffer *)&(proxy->lpvtbl2);
1412     return S_OK;
1413 }
1414
1415 typedef struct _TMStubImpl {
1416     ICOM_VTABLE(IRpcStubBuffer) *lpvtbl;
1417     DWORD                       ref;
1418
1419     LPUNKNOWN                   pUnk;
1420     ITypeInfo                   *tinfo;
1421     IID                         iid;
1422 } TMStubImpl;
1423
1424 static HRESULT WINAPI
1425 TMStubImpl_QueryInterface(LPRPCSTUBBUFFER iface, REFIID riid, LPVOID *ppv) {
1426     if (IsEqualIID(riid,&IID_IRpcStubBuffer)||IsEqualIID(riid,&IID_IUnknown)){
1427         *ppv = (LPVOID)iface;
1428         IRpcStubBuffer_AddRef(iface);
1429         return S_OK;
1430     }
1431     FIXME("%s, not supported IID.\n",debugstr_guid(riid));
1432     return E_NOINTERFACE;
1433 }
1434
1435 static ULONG WINAPI
1436 TMStubImpl_AddRef(LPRPCSTUBBUFFER iface) {
1437     ICOM_THIS(TMStubImpl,iface);
1438
1439     This->ref++;
1440     return This->ref;
1441 }
1442
1443 static ULONG WINAPI
1444 TMStubImpl_Release(LPRPCSTUBBUFFER iface) {
1445     ICOM_THIS(TMStubImpl,iface);
1446
1447     This->ref--;
1448     if (This->ref)
1449         return This->ref;
1450     HeapFree(GetProcessHeap(),0,This);
1451     return 0;
1452 }
1453
1454 static HRESULT WINAPI
1455 TMStubImpl_Connect(LPRPCSTUBBUFFER iface, LPUNKNOWN pUnkServer) {
1456     ICOM_THIS(TMStubImpl,iface);
1457
1458     IUnknown_AddRef(pUnkServer);
1459     This->pUnk = pUnkServer;
1460     return S_OK;
1461 }
1462
1463 static void WINAPI
1464 TMStubImpl_Disconnect(LPRPCSTUBBUFFER iface) {
1465     ICOM_THIS(TMStubImpl,iface);
1466
1467     IUnknown_Release(This->pUnk);
1468     This->pUnk = NULL;
1469     return;
1470 }
1471
1472 static HRESULT WINAPI
1473 TMStubImpl_Invoke(
1474     LPRPCSTUBBUFFER iface, RPCOLEMESSAGE* xmsg,IRpcChannelBuffer*rpcchanbuf
1475 ) {
1476     int         i;
1477     FUNCDESC    *fdesc;
1478     ICOM_THIS(TMStubImpl,iface);
1479     HRESULT     hres;
1480     DWORD       *args, res, *xargs, nrofargs;
1481     marshal_state       buf;
1482     int         nrofnames;
1483     BSTR        names[10];
1484
1485     memset(&buf,0,sizeof(buf));
1486     buf.size    = xmsg->cbBuffer;
1487     buf.base    = xmsg->Buffer;
1488     buf.curoff  = 0;
1489     buf.iid     = IID_IUnknown;
1490
1491     TRACE("...\n");
1492     if (xmsg->iMethod == 0) { /* QI */
1493         IID             xiid;
1494         /* in: IID, out: <iface> */
1495
1496         xbuf_get(&buf,(LPBYTE)&xiid,sizeof(xiid));
1497         buf.curoff = 0;
1498         hres = _marshal_interface(&buf,&xiid,This->pUnk);
1499         xmsg->Buffer    = buf.base; /* Might have been reallocated */
1500         xmsg->cbBuffer  = buf.size;
1501         return hres;
1502     }
1503     hres = _get_funcdesc(This->tinfo,xmsg->iMethod,&fdesc,NULL,NULL);
1504     if (hres) {
1505         FIXME("GetFuncDesc on method %ld failed with %lx\n",xmsg->iMethod,hres);
1506         return hres;
1507     }
1508     /* Need them for hack below */
1509     memset(names,0,sizeof(names));
1510     ITypeInfo_GetNames(This->tinfo,fdesc->memid,names,sizeof(names)/sizeof(names[0]),&nrofnames);
1511     if (nrofnames > sizeof(names)/sizeof(names[0])) {
1512         ERR("Need more names!\n");
1513     }
1514
1515     /*dump_FUNCDESC(fdesc);*/
1516     nrofargs = 0;
1517     for (i=0;i<fdesc->cParams;i++)
1518         nrofargs += _argsize(fdesc->lprgelemdescParam[i].tdesc.vt);
1519     args = HeapAlloc(GetProcessHeap(),0,(nrofargs+1)*sizeof(DWORD));
1520     if (!args) return E_OUTOFMEMORY;
1521
1522     /* Allocate all stuff used by call. */
1523     xargs = args+1;
1524     for (i=0;i<fdesc->cParams;i++) {
1525         ELEMDESC        *elem = fdesc->lprgelemdescParam+i;
1526         BOOL            isdeserialized = FALSE;
1527
1528         if (((i+1)<nrofnames) && !IsBadStringPtrW(names[i+1],1)) {
1529             /* If the parameter is 'riid', we use it as interface IID
1530              * for a later ppvObject serialization.
1531              */
1532             buf.thisisiid = !lstrcmpW(names[i+1],riidW);
1533
1534             /* deserialize DISPPARAM */
1535             if (!lstrcmpW(names[i+1],pdispparamsW)) {
1536                 hres = deserialize_DISPPARAM_ptr(
1537                     This->tinfo,
1538                     elem->u.paramdesc.wParamFlags & PARAMFLAG_FIN,
1539                     FALSE,
1540                     TRUE,
1541                     &(elem->tdesc),
1542                     xargs,
1543                     &buf
1544                 );
1545                 if (hres) {
1546                     FIXME("Failed to deserialize DISPPARAM*, hres %lx\n",hres);
1547                     break;
1548                 }
1549                 isdeserialized = TRUE;
1550             }
1551             if (!lstrcmpW(names[i+1],ppvObjectW)) {
1552                 hres = deserialize_LPVOID_ptr(
1553                     This->tinfo,
1554                     elem->u.paramdesc.wParamFlags & PARAMFLAG_FOUT,
1555                     FALSE,
1556                     TRUE,
1557                     &elem->tdesc,
1558                     xargs,
1559                     &buf
1560                 );
1561                 if (hres == S_OK)
1562                     isdeserialized = TRUE;
1563             }
1564         }
1565         if (!isdeserialized)
1566             hres = deserialize_param(
1567                 This->tinfo,
1568                 elem->u.paramdesc.wParamFlags & PARAMFLAG_FIN,
1569                 FALSE,
1570                 TRUE,
1571                 &(elem->tdesc),
1572                 xargs,
1573                 &buf
1574             );
1575         xargs += _argsize(elem->tdesc.vt);
1576         if (hres) {
1577             FIXME("Failed to deserialize param %s, hres %lx\n",debugstr_w(names[i+1]),hres);
1578             break;
1579         }
1580     }
1581     hres = IUnknown_QueryInterface(This->pUnk,&(This->iid),(LPVOID*)&(args[0]));
1582     if (hres) {
1583         ERR("Does not support iface %s\n",debugstr_guid(&(This->iid)));
1584         return hres;
1585     }
1586     res = _invoke(
1587             (*((FARPROC**)args[0]))[fdesc->oVft/4],
1588             fdesc->callconv,
1589             (xargs-args),
1590             args
1591     );
1592     IUnknown_Release((LPUNKNOWN)args[0]);
1593     buf.curoff = 0;
1594     xargs = args+1;
1595     for (i=0;i<fdesc->cParams;i++) {
1596         ELEMDESC        *elem = fdesc->lprgelemdescParam+i;
1597         BOOL            isserialized = FALSE;
1598
1599         if (((i+1)<nrofnames) && !IsBadStringPtrW(names[i+1],1)) {
1600             /* If the parameter is 'riid', we use it as interface IID
1601              * for a later ppvObject serialization.
1602              */
1603             buf.thisisiid = !lstrcmpW(names[i+1],riidW);
1604
1605             /* DISPPARAMS* needs special serializer */
1606             if (!lstrcmpW(names[i+1],pdispparamsW)) {
1607                 hres = serialize_DISPPARAM_ptr(
1608                     This->tinfo,
1609                     elem->u.paramdesc.wParamFlags & PARAMFLAG_FOUT,
1610                     FALSE,
1611                     TRUE,
1612                     &elem->tdesc,
1613                     xargs,
1614                     &buf
1615                 );
1616                 isserialized = TRUE;
1617             }
1618             if (!lstrcmpW(names[i+1],ppvObjectW)) {
1619                 hres = serialize_LPVOID_ptr(
1620                     This->tinfo,
1621                     elem->u.paramdesc.wParamFlags & PARAMFLAG_FOUT,
1622                     FALSE,
1623                     TRUE,
1624                     &elem->tdesc,
1625                     xargs,
1626                     &buf
1627                 );
1628                 if (hres == S_OK)
1629                     isserialized = TRUE;
1630             }
1631         }
1632         if (!isserialized)
1633             hres = serialize_param(
1634                This->tinfo,
1635                elem->u.paramdesc.wParamFlags & PARAMFLAG_FOUT,
1636                FALSE,
1637                TRUE,
1638                &elem->tdesc,
1639                xargs,
1640                &buf
1641             );
1642         xargs += _argsize(elem->tdesc.vt);
1643         if (hres) {
1644             FIXME("Failed to stuballoc param, hres %lx\n",hres);
1645             break;
1646         }
1647     }
1648     /* might need to use IRpcChannelBuffer_GetBuffer ? */
1649     xmsg->cbBuffer      = buf.curoff;
1650     xmsg->Buffer        = buf.base;
1651     HeapFree(GetProcessHeap(),0,args);
1652     return res;
1653 }
1654
1655 static LPRPCSTUBBUFFER WINAPI
1656 TMStubImpl_IsIIDSupported(LPRPCSTUBBUFFER iface, REFIID riid) {
1657     FIXME("Huh (%s)?\n",debugstr_guid(riid));
1658     return NULL;
1659 }
1660
1661 static ULONG WINAPI
1662 TMStubImpl_CountRefs(LPRPCSTUBBUFFER iface) {
1663     ICOM_THIS(TMStubImpl,iface);
1664
1665     return This->ref; /*FIXME? */
1666 }
1667
1668 static HRESULT WINAPI
1669 TMStubImpl_DebugServerQueryInterface(LPRPCSTUBBUFFER iface, LPVOID *ppv) {
1670     return E_NOTIMPL;
1671 }
1672
1673 static void WINAPI
1674 TMStubImpl_DebugServerRelease(LPRPCSTUBBUFFER iface, LPVOID ppv) {
1675     return;
1676 }
1677
1678 ICOM_VTABLE(IRpcStubBuffer) tmstubvtbl = {
1679     ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
1680     TMStubImpl_QueryInterface,
1681     TMStubImpl_AddRef,
1682     TMStubImpl_Release,
1683     TMStubImpl_Connect,
1684     TMStubImpl_Disconnect,
1685     TMStubImpl_Invoke,
1686     TMStubImpl_IsIIDSupported,
1687     TMStubImpl_CountRefs,
1688     TMStubImpl_DebugServerQueryInterface,
1689     TMStubImpl_DebugServerRelease
1690 };
1691
1692 static HRESULT WINAPI
1693 PSFacBuf_CreateStub(
1694     LPPSFACTORYBUFFER iface, REFIID riid,IUnknown *pUnkServer,
1695     IRpcStubBuffer** ppStub
1696 ) {
1697     HRESULT hres;
1698     ITypeInfo   *tinfo;
1699     TMStubImpl  *stub;
1700
1701     TRACE("(%s,%p,%p)\n",debugstr_guid(riid),pUnkServer,ppStub);
1702     hres = _get_typeinfo_for_iid(riid,&tinfo);
1703     if (hres) {
1704         FIXME("No typeinfo for %s?\n",debugstr_guid(riid));
1705         return hres;
1706     }
1707     stub = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(TMStubImpl));
1708     if (!stub)
1709         return E_OUTOFMEMORY;
1710     stub->lpvtbl        = &tmstubvtbl;
1711     stub->ref           = 1;
1712     stub->tinfo         = tinfo;
1713     memcpy(&(stub->iid),riid,sizeof(*riid));
1714     hres = IRpcStubBuffer_Connect((LPRPCSTUBBUFFER)stub,pUnkServer);
1715     *ppStub             = (LPRPCSTUBBUFFER)stub;
1716     if (hres)
1717         FIXME("Connect to pUnkServer failed?\n");
1718     return hres;
1719 }
1720
1721 static ICOM_VTABLE(IPSFactoryBuffer) psfacbufvtbl = {
1722     ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
1723     PSFacBuf_QueryInterface,
1724     PSFacBuf_AddRef,
1725     PSFacBuf_Release,
1726     PSFacBuf_CreateProxy,
1727     PSFacBuf_CreateStub
1728 };
1729
1730 /* This is the whole PSFactoryBuffer object, just the vtableptr */
1731 static ICOM_VTABLE(IPSFactoryBuffer) *lppsfac = &psfacbufvtbl;
1732
1733 /***********************************************************************
1734  *           DllGetClassObject [OLE32.63]
1735  */
1736 HRESULT WINAPI
1737 TypeLibFac_DllGetClassObject(REFCLSID rclsid, REFIID iid,LPVOID *ppv)
1738 {
1739     if (IsEqualIID(iid,&IID_IPSFactoryBuffer)) {
1740         *ppv = &lppsfac;
1741         return S_OK;
1742     }
1743     return E_NOINTERFACE;
1744 }