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