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