Fixed a race condition on RPC worker thread creation, and a typo.
[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 "ole2disp.h"
39 #include "typelib.h"
40 #include "wine/debug.h"
41 #include "winternl.h"
42
43 static const WCHAR riidW[5] = {'r','i','i','d',0};
44 static const WCHAR pdispparamsW[] = {'p','d','i','s','p','p','a','r','a','m','s',0};
45 static const WCHAR ppvObjectW[] = {'p','p','v','O','b','j','e','c','t',0};
46
47 WINE_DEFAULT_DEBUG_CHANNEL(ole);
48 WINE_DECLARE_DEBUG_CHANNEL(olerelay);
49
50 typedef struct _marshal_state {
51     LPBYTE      base;
52     int         size;
53     int         curoff;
54
55     BOOL        thisisiid;
56     IID         iid;    /* HACK: for VT_VOID */
57 } marshal_state;
58
59 static HRESULT
60 xbuf_add(marshal_state *buf, LPBYTE stuff, DWORD size) {
61     while (buf->size - buf->curoff < size) {
62         if (buf->base) {
63             buf->size += 100;
64             buf->base = HeapReAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,buf->base,buf->size);
65             if (!buf->base)
66                 return E_OUTOFMEMORY;
67         } else {
68             buf->base = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,32);
69             buf->size = 32;
70             if (!buf->base)
71                 return E_OUTOFMEMORY;
72         }
73     }
74     memcpy(buf->base+buf->curoff,stuff,size);
75     buf->curoff += size;
76     return S_OK;
77 }
78
79 static HRESULT
80 xbuf_get(marshal_state *buf, LPBYTE stuff, DWORD size) {
81     if (buf->size < buf->curoff+size) return E_FAIL;
82     memcpy(stuff,buf->base+buf->curoff,size);
83     buf->curoff += size;
84     return S_OK;
85 }
86
87 static HRESULT
88 xbuf_skip(marshal_state *buf, DWORD size) {
89     if (buf->size < buf->curoff+size) return E_FAIL;
90     buf->curoff += size;
91     return S_OK;
92 }
93
94 static HRESULT
95 _unmarshal_interface(marshal_state *buf, REFIID riid, LPUNKNOWN *pUnk) {
96     IStream             *pStm;
97     ULARGE_INTEGER      newpos;
98     LARGE_INTEGER       seekto;
99     ULONG               res;
100     HRESULT             hres;
101     DWORD               xsize;
102
103     TRACE("...%s...\n",debugstr_guid(riid));
104     *pUnk = NULL;
105     hres = xbuf_get(buf,(LPBYTE)&xsize,sizeof(xsize));
106     if (hres) return hres;
107     if (xsize == 0) return S_OK;
108     hres = CreateStreamOnHGlobal(0,TRUE,&pStm);
109     if (hres) {
110         FIXME("Stream create failed %lx\n",hres);
111         return hres;
112     }
113     hres = IStream_Write(pStm,buf->base+buf->curoff,xsize,&res);
114     if (hres) { FIXME("stream write %lx\n",hres); return hres; }
115     memset(&seekto,0,sizeof(seekto));
116     hres = IStream_Seek(pStm,seekto,SEEK_SET,&newpos);
117     if (hres) { FIXME("Failed Seek %lx\n",hres); return hres;}
118     hres = CoUnmarshalInterface(pStm,riid,(LPVOID*)pUnk);
119     if (hres) {
120         FIXME("Marshaling interface %s failed with %lx\n",debugstr_guid(riid),hres);
121         return hres;
122     }
123     IStream_Release(pStm);
124     return xbuf_skip(buf,xsize);
125 }
126
127 static HRESULT
128 _marshal_interface(marshal_state *buf, REFIID riid, LPUNKNOWN pUnk) {
129     LPUNKNOWN           newiface;
130     LPBYTE              tempbuf;
131     IStream             *pStm;
132     STATSTG             ststg;
133     ULARGE_INTEGER      newpos;
134     LARGE_INTEGER       seekto;
135     ULONG               res;
136     DWORD               xsize;
137     HRESULT             hres;
138
139     hres = S_OK;
140     if (!pUnk)
141         goto fail;
142
143     TRACE("...%s...\n",debugstr_guid(riid));
144     hres=IUnknown_QueryInterface(pUnk,riid,(LPVOID*)&newiface);
145     if (hres) {
146         TRACE("%p does not support iface %s\n",pUnk,debugstr_guid(riid));
147         goto fail;
148     }
149     hres = CreateStreamOnHGlobal(0,TRUE,&pStm);
150     if (hres) {
151         FIXME("Stream create failed %lx\n",hres);
152         goto fail;
153     }
154     hres = CoMarshalInterface(pStm,riid,newiface,0,NULL,0);
155     IUnknown_Release(newiface);
156     if (hres) {
157         FIXME("Marshaling interface %s failed with %lx\n",
158                 debugstr_guid(riid),hres
159         );
160         goto fail;
161     }
162     hres = IStream_Stat(pStm,&ststg,0);
163     tempbuf = HeapAlloc(GetProcessHeap(), 0, ststg.cbSize.s.LowPart);
164     memset(&seekto,0,sizeof(seekto));
165     hres = IStream_Seek(pStm,seekto,SEEK_SET,&newpos);
166     if (hres) { FIXME("Failed Seek %lx\n",hres); goto fail;}
167     hres = IStream_Read(pStm,tempbuf,ststg.cbSize.s.LowPart,&res);
168     if (hres) { FIXME("Failed Read %lx\n",hres); goto fail;}
169     IStream_Release(pStm);
170     xsize = ststg.cbSize.s.LowPart;
171     xbuf_add(buf,(LPBYTE)&xsize,sizeof(xsize));
172     hres = xbuf_add(buf,tempbuf,ststg.cbSize.s.LowPart);
173     HeapFree(GetProcessHeap(),0,tempbuf);
174     return hres;
175 fail:
176     xsize = 0;
177     xbuf_add(buf,(LPBYTE)&xsize,sizeof(xsize));
178     return hres;
179 }
180
181 /********************* OLE Proxy/Stub Factory ********************************/
182 static HRESULT WINAPI
183 PSFacBuf_QueryInterface(LPPSFACTORYBUFFER iface, REFIID iid, LPVOID *ppv) {
184     if (IsEqualIID(iid,&IID_IPSFactoryBuffer)||IsEqualIID(iid,&IID_IUnknown)) {
185         *ppv = (LPVOID)iface;
186         /* No ref counting, static class */
187         return S_OK;
188     }
189     FIXME("(%s) unknown IID?\n",debugstr_guid(iid));
190     return E_NOINTERFACE;
191 }
192
193 static ULONG WINAPI PSFacBuf_AddRef(LPPSFACTORYBUFFER iface) { return 2; }
194 static ULONG WINAPI PSFacBuf_Release(LPPSFACTORYBUFFER iface) { return 1; }
195
196 static HRESULT
197 _get_typeinfo_for_iid(REFIID riid, ITypeInfo**ti) {
198     HRESULT     hres;
199     HKEY        ikey;
200     char        tlguid[200],typelibkey[300],interfacekey[300],ver[100];
201     char        tlfn[260];
202     OLECHAR     tlfnW[260];
203     DWORD       tlguidlen, verlen, type, tlfnlen;
204     ITypeLib    *tl;
205
206     sprintf( interfacekey, "Interface\\{%08lx-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}\\Typelib",
207         riid->Data1, riid->Data2, riid->Data3,
208         riid->Data4[0], riid->Data4[1], riid->Data4[2], riid->Data4[3],
209         riid->Data4[4], riid->Data4[5], riid->Data4[6], riid->Data4[7]
210     );
211
212     if (RegOpenKeyA(HKEY_CLASSES_ROOT,interfacekey,&ikey)) {
213         FIXME("No %s key found.\n",interfacekey);
214         return E_FAIL;
215     }
216     type = (1<<REG_SZ);
217     tlguidlen = sizeof(tlguid);
218     if (RegQueryValueExA(ikey,NULL,NULL,&type,tlguid,&tlguidlen)) {
219         FIXME("Getting typelib guid failed.\n");
220         RegCloseKey(ikey);
221         return E_FAIL;
222     }
223     type = (1<<REG_SZ);
224     verlen = sizeof(ver);
225     if (RegQueryValueExA(ikey,"Version",NULL,&type,ver,&verlen)) {
226         FIXME("Could not get version value?\n");
227         RegCloseKey(ikey);
228         return E_FAIL;
229     }
230     RegCloseKey(ikey);
231     sprintf(typelibkey,"Typelib\\%s\\%s\\0\\win32",tlguid,ver);
232     tlfnlen = sizeof(tlfn);
233     if (RegQueryValueA(HKEY_CLASSES_ROOT,typelibkey,tlfn,&tlfnlen)) {
234         FIXME("Could not get typelib fn?\n");
235         return E_FAIL;
236     }
237     MultiByteToWideChar(CP_ACP, 0, tlfn, -1, tlfnW, -1);
238     hres = LoadTypeLib(tlfnW,&tl);
239     if (hres) {
240         ERR("Failed to load typelib for %s, but it should be there.\n",debugstr_guid(riid));
241         return hres;
242     }
243     hres = ITypeLib_GetTypeInfoOfGuid(tl,riid,ti);
244     if (hres) {
245         ERR("typelib does not contain info for %s?\n",debugstr_guid(riid));
246         ITypeLib_Release(tl);
247         return hres;
248     }
249     /* FIXME: do this?  ITypeLib_Release(tl); */
250     return hres;
251 }
252
253 /* Determine nr of functions. Since we use the toplevel interface and all
254  * inherited ones have lower numbers, we are ok to not to descent into
255  * the inheritance tree I think.
256  */
257 static int _nroffuncs(ITypeInfo *tinfo) {
258     int         n, max = 0;
259     FUNCDESC    *fdesc;
260     HRESULT     hres;
261
262     n=0;
263     while (1) {
264         hres = ITypeInfo_GetFuncDesc(tinfo,n,&fdesc);
265         if (fdesc->oVft/4 > max)
266             max = fdesc->oVft/4;
267         if (hres)
268             return max+1;
269         n++;
270     }
271     /*NOTREACHED*/
272 }
273
274 typedef struct _TMAsmProxy {
275     BYTE        popleax;
276     BYTE        pushlval;
277     BYTE        nr;
278     BYTE        pushleax;
279     BYTE        lcall;
280     DWORD       xcall;
281     BYTE        lret;
282     WORD        bytestopop;
283 } WINE_PACKED TMAsmProxy;
284
285 typedef struct _TMProxyImpl {
286     DWORD                               *lpvtbl;
287     ICOM_VTABLE(IRpcProxyBuffer)        *lpvtbl2;
288     DWORD                               ref;
289
290     TMAsmProxy                          *asmstubs;
291     ITypeInfo*                          tinfo;
292     IRpcChannelBuffer*                  chanbuf;
293     IID                                 iid;
294 } TMProxyImpl;
295
296 static HRESULT WINAPI
297 TMProxyImpl_QueryInterface(LPRPCPROXYBUFFER iface, REFIID riid, LPVOID *ppv) {
298     TRACE("()\n");
299     if (IsEqualIID(riid,&IID_IUnknown)||IsEqualIID(riid,&IID_IRpcProxyBuffer)) {
300         *ppv = (LPVOID)iface;
301         IRpcProxyBuffer_AddRef(iface);
302         return S_OK;
303     }
304     FIXME("no interface for %s\n",debugstr_guid(riid));
305     return E_NOINTERFACE;
306 }
307
308 static ULONG WINAPI
309 TMProxyImpl_AddRef(LPRPCPROXYBUFFER iface) {
310     ICOM_THIS_MULTI(TMProxyImpl,lpvtbl2,iface);
311
312     TRACE("()\n");
313     This->ref++;
314     return This->ref;
315 }
316
317 static ULONG WINAPI
318 TMProxyImpl_Release(LPRPCPROXYBUFFER iface) {
319     ICOM_THIS_MULTI(TMProxyImpl,lpvtbl2,iface);
320
321     TRACE("()\n");
322     This->ref--;
323     if (This->ref) return This->ref;
324     if (This->chanbuf) IRpcChannelBuffer_Release(This->chanbuf);
325     HeapFree(GetProcessHeap(),0,This);
326     return 0;
327 }
328
329 static HRESULT WINAPI
330 TMProxyImpl_Connect(
331     LPRPCPROXYBUFFER iface,IRpcChannelBuffer* pRpcChannelBuffer
332 ) {
333     ICOM_THIS_MULTI(TMProxyImpl,lpvtbl2,iface);
334
335     TRACE("(%p)\n",pRpcChannelBuffer);
336     This->chanbuf = pRpcChannelBuffer;
337     IRpcChannelBuffer_AddRef(This->chanbuf);
338     return S_OK;
339 }
340
341 static void WINAPI
342 TMProxyImpl_Disconnect(LPRPCPROXYBUFFER iface) {
343     ICOM_THIS_MULTI(TMProxyImpl,lpvtbl2,iface);
344
345     FIXME("()\n");
346     IRpcChannelBuffer_Release(This->chanbuf);
347     This->chanbuf = NULL;
348 }
349
350
351 static ICOM_VTABLE(IRpcProxyBuffer) tmproxyvtable = {
352     ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
353     TMProxyImpl_QueryInterface,
354     TMProxyImpl_AddRef,
355     TMProxyImpl_Release,
356     TMProxyImpl_Connect,
357     TMProxyImpl_Disconnect
358 };
359
360 /* how much space do we use on stack in DWORD steps. */
361 int const
362 _argsize(DWORD vt) {
363     switch (vt) {
364     case VT_DATE:
365         return sizeof(DATE)/sizeof(DWORD);
366     case VT_VARIANT:
367         return (sizeof(VARIANT)+3)/sizeof(DWORD);
368     default:
369         return 1;
370     }
371 }
372
373 static int
374 _xsize(TYPEDESC *td) {
375     switch (td->vt) {
376     case VT_DATE:
377         return sizeof(DATE);
378     case VT_VARIANT:
379         return sizeof(VARIANT)+3;
380     case VT_CARRAY: {
381         int i, arrsize = 1;
382         ARRAYDESC *adesc = td->u.lpadesc;
383
384         for (i=0;i<adesc->cDims;i++)
385             arrsize *= adesc->rgbounds[i].cElements;
386         return arrsize*_xsize(&adesc->tdescElem);
387     }
388     case VT_UI2:
389     case VT_I2:
390         return 2;
391     case VT_UI1:
392     case VT_I1:
393         return 1;
394     default:
395         return 4;
396     }
397 }
398
399 static HRESULT
400 serialize_param(
401     ITypeInfo           *tinfo,
402     BOOL                writeit,
403     BOOL                debugout,
404     BOOL                dealloc,
405     TYPEDESC            *tdesc,
406     DWORD               *arg,
407     marshal_state       *buf
408 ) {
409     HRESULT hres = S_OK;
410
411     TRACE("(tdesc.vt %d)\n",tdesc->vt);
412
413     switch (tdesc->vt) {
414     case VT_EMPTY: /* nothing. empty variant for instance */
415         return S_OK;
416     case VT_BOOL:
417     case VT_ERROR:
418     case VT_UI4:
419     case VT_UINT:
420     case VT_I4:
421     case VT_R4:
422     case VT_UI2:
423     case VT_UI1:
424         hres = S_OK;
425         if (debugout) MESSAGE("%lx",*arg);
426         if (writeit)
427             hres = xbuf_add(buf,(LPBYTE)arg,sizeof(DWORD));
428         return hres;
429     case VT_VARIANT: {
430         TYPEDESC        tdesc2;
431         VARIANT         *vt = (VARIANT*)arg;
432         DWORD           vttype = V_VT(vt);
433
434         if (debugout) MESSAGE("Vt(%ld)(",vttype);
435         tdesc2.vt = vttype;
436         if (writeit) {
437             hres = xbuf_add(buf,(LPBYTE)&vttype,sizeof(vttype));
438             if (hres) return hres;
439         }
440         /* need to recurse since we need to free the stuff */
441         hres = serialize_param(tinfo,writeit,debugout,dealloc,&tdesc2,&(V_I4(vt)),buf);
442         if (debugout) MESSAGE(")");
443         return hres;
444     }
445     case VT_BSTR: {
446         if (debugout) {
447             if (arg)
448                     MESSAGE("%s",debugstr_w((BSTR)*arg));
449             else
450                     MESSAGE("<bstr NULL>");
451         }
452         if (writeit) {
453             if (!*arg) {
454                 DWORD fakelen = -1;
455                 hres = xbuf_add(buf,(LPBYTE)&fakelen,4);
456                 if (hres)
457                     return hres;
458             } else {
459                 DWORD *bstr = ((DWORD*)(*arg))-1;
460
461                 hres = xbuf_add(buf,(LPBYTE)bstr,bstr[0]+4);
462                 if (hres)
463                     return hres;
464             }
465         }
466         if (dealloc && arg)
467             SysFreeString((BSTR)arg);
468         return S_OK;
469     }
470     case VT_PTR: {
471         DWORD cookie;
472
473         if (debugout) MESSAGE("*");
474         if (writeit) {
475             cookie = *arg ? 0x42424242 : 0;
476             hres = xbuf_add(buf,(LPBYTE)&cookie,sizeof(cookie));
477             if (hres)
478                 return hres;
479         }
480         if (!*arg) {
481             if (debugout) MESSAGE("NULL");
482             return S_OK;
483         }
484         hres = serialize_param(tinfo,writeit,debugout,dealloc,tdesc->u.lptdesc,(DWORD*)*arg,buf);
485         if (dealloc) HeapFree(GetProcessHeap(),0,(LPVOID)arg);
486         return hres;
487     }
488     case VT_UNKNOWN:
489         if (debugout) MESSAGE("unk(0x%lx)",*arg);
490         if (writeit)
491             hres = _marshal_interface(buf,&IID_IUnknown,(LPUNKNOWN)*arg);
492         return hres;
493     case VT_DISPATCH:
494         if (debugout) MESSAGE("idisp(0x%lx)",*arg);
495         if (writeit)
496             hres = _marshal_interface(buf,&IID_IDispatch,(LPUNKNOWN)*arg);
497         return hres;
498     case VT_VOID:
499         if (debugout) MESSAGE("<void>");
500         return S_OK;
501     case VT_USERDEFINED: {
502         ITypeInfo       *tinfo2;
503         TYPEATTR        *tattr;
504
505         hres = ITypeInfo_GetRefTypeInfo(tinfo,tdesc->u.hreftype,&tinfo2);
506         if (hres) {
507             FIXME("Could not get typeinfo of hreftype %lx for VT_USERDEFINED.\n",tdesc->u.hreftype);
508             return hres;
509         }
510         ITypeInfo_GetTypeAttr(tinfo2,&tattr);
511         switch (tattr->typekind) {
512         case TKIND_DISPATCH:
513         case TKIND_INTERFACE:
514             if (writeit)
515                hres=_marshal_interface(buf,&(tattr->guid),(LPUNKNOWN)arg);
516             break;
517         case TKIND_RECORD: {
518             int i;
519             if (debugout) MESSAGE("{");
520             for (i=0;i<tattr->cVars;i++) {
521                 VARDESC *vdesc;
522                 ELEMDESC *elem2;
523                 TYPEDESC *tdesc2;
524
525                 hres = ITypeInfo2_GetVarDesc(tinfo2, i, &vdesc);
526                 if (hres) {
527                     FIXME("Could not get vardesc of %d\n",i);
528                     return hres;
529                 }
530                 /* Need them for hack below */
531                 /*
532                 memset(names,0,sizeof(names));
533                 hres = ITypeInfo_GetNames(tinfo2,vdesc->memid,names,sizeof(names)/sizeof(names[0]),&nrofnames);
534                 if (nrofnames > sizeof(names)/sizeof(names[0])) {
535                     ERR("Need more names!\n");
536                 }
537                 if (!hres && debugout)
538                     MESSAGE("%s=",debugstr_w(names[0]));
539                 */
540                 elem2 = &vdesc->elemdescVar;
541                 tdesc2 = &elem2->tdesc;
542                 hres = serialize_param(
543                     tinfo2,
544                     writeit,
545                     debugout,
546                     dealloc,
547                     tdesc2,
548                     (DWORD*)(((LPBYTE)arg)+vdesc->u.oInst),
549                     buf
550                 );
551                 if (hres!=S_OK)
552                     return hres;
553                 if (debugout && (i<(tattr->cVars-1)))
554                     MESSAGE(",");
555             }
556             if (buf->thisisiid && (tattr->cbSizeInstance==sizeof(GUID)))
557                 memcpy(&(buf->iid),arg,sizeof(buf->iid));
558             if (debugout) MESSAGE("}");
559             break;
560         }
561         default:
562             FIXME("Unhandled typekind %d\n",tattr->typekind);
563             hres = E_FAIL;
564             break;
565         }
566         ITypeInfo_Release(tinfo2);
567         return hres;
568     }
569     case VT_CARRAY: {
570         ARRAYDESC *adesc = tdesc->u.lpadesc;
571         int i, arrsize = 1;
572
573         if (debugout) MESSAGE("carr");
574         for (i=0;i<adesc->cDims;i++) {
575             if (debugout) MESSAGE("[%ld]",adesc->rgbounds[i].cElements);
576             arrsize *= adesc->rgbounds[i].cElements;
577         }
578         if (debugout) MESSAGE("[");
579         for (i=0;i<arrsize;i++) {
580             hres = serialize_param(tinfo, writeit, debugout, dealloc, &adesc->tdescElem, (DWORD*)((LPBYTE)arg+i*_xsize(&adesc->tdescElem)), buf);
581             if (hres)
582                 return hres;
583             if (debugout && (i<arrsize-1)) MESSAGE(",");
584         }
585         if (debugout) MESSAGE("]");
586         return S_OK;
587     }
588     default:
589         ERR("Unhandled marshal type %d.\n",tdesc->vt);
590         return S_OK;
591     }
592 }
593
594 static HRESULT
595 serialize_LPVOID_ptr(
596     ITypeInfo           *tinfo,
597     BOOL                writeit,
598     BOOL                debugout,
599     BOOL                dealloc,
600     TYPEDESC            *tdesc,
601     DWORD               *arg,
602     marshal_state       *buf
603 ) {
604     HRESULT     hres;
605     DWORD       cookie;
606
607     if ((tdesc->vt != VT_PTR)                   ||
608         (tdesc->u.lptdesc->vt != VT_PTR)        ||
609         (tdesc->u.lptdesc->u.lptdesc->vt != VT_VOID)
610     ) {
611         FIXME("ppvObject not expressed as VT_PTR -> VT_PTR -> VT_VOID?\n");
612         return E_FAIL;
613     }
614     cookie = (*arg) ? 0x42424242: 0x0;
615     if (writeit) {
616         hres = xbuf_add(buf, (LPVOID)&cookie, sizeof(cookie));
617         if (hres)
618             return hres;
619     }
620     if (!*arg) {
621         if (debugout) MESSAGE("<lpvoid NULL>");
622         return S_OK;
623     }
624     if (debugout)
625         MESSAGE("ppv(%p)",*(LPUNKNOWN*)*arg);
626     if (writeit) {
627         hres = _marshal_interface(buf,&(buf->iid),*(LPUNKNOWN*)*arg);
628         if (hres)
629             return hres;
630     }
631     if (dealloc)
632         HeapFree(GetProcessHeap(),0,(LPVOID)*arg);
633     return S_OK;
634 }
635
636 static HRESULT
637 serialize_DISPPARAM_ptr(
638     ITypeInfo           *tinfo,
639     BOOL                writeit,
640     BOOL                debugout,
641     BOOL                dealloc,
642     TYPEDESC            *tdesc,
643     DWORD               *arg,
644     marshal_state       *buf
645 ) {
646     DWORD       cookie;
647     HRESULT     hres;
648     DISPPARAMS  *disp;
649     int         i;
650
651     if ((tdesc->vt != VT_PTR) || (tdesc->u.lptdesc->vt != VT_USERDEFINED)) {
652         FIXME("DISPPARAMS not expressed as VT_PTR -> VT_USERDEFINED?\n");
653         return E_FAIL;
654     }
655
656     cookie = *arg ? 0x42424242 : 0x0;
657     if (writeit) {
658         hres = xbuf_add(buf,(LPBYTE)&cookie,sizeof(cookie));
659         if (hres)
660             return hres;
661     }
662     if (!*arg) {
663         if (debugout) MESSAGE("<DISPPARAMS NULL>");
664         return S_OK;
665     }
666     disp = (DISPPARAMS*)*arg;
667     if (writeit) {
668         hres = xbuf_add(buf,(LPBYTE)&disp->cArgs,sizeof(disp->cArgs));
669         if (hres)
670             return hres;
671     }
672     if (debugout) MESSAGE("D{");
673     for (i=0;i<disp->cArgs;i++) {
674         TYPEDESC        vtdesc;
675
676         vtdesc.vt = VT_VARIANT;
677         serialize_param(
678             tinfo,
679             writeit,
680             debugout,
681             dealloc,
682             &vtdesc,
683             (DWORD*)(disp->rgvarg+i),
684             buf
685         );
686         if (debugout && (i<disp->cArgs-1))
687             MESSAGE(",");
688     }
689     if (dealloc)
690         HeapFree(GetProcessHeap(),0,disp->rgvarg);
691     if (writeit) {
692         hres = xbuf_add(buf,(LPBYTE)&disp->cNamedArgs,sizeof(disp->cNamedArgs));
693         if (hres)
694             return hres;
695     }
696     if (debugout) MESSAGE("}{");
697     for (i=0;i<disp->cNamedArgs;i++) {
698         TYPEDESC        vtdesc;
699
700         vtdesc.vt = VT_UINT;
701         serialize_param(
702             tinfo,
703             writeit,
704             debugout,
705             dealloc,
706             &vtdesc,
707             (DWORD*)(disp->rgdispidNamedArgs+i),
708             buf
709         );
710         if (debugout && (i<disp->cNamedArgs-1))
711             MESSAGE(",");
712     }
713     if (debugout) MESSAGE("}");
714     if (dealloc) {
715         HeapFree(GetProcessHeap(),0,disp->rgdispidNamedArgs);
716         HeapFree(GetProcessHeap(),0,disp);
717     }
718     return S_OK;
719 }
720
721 static HRESULT
722 deserialize_param(
723     ITypeInfo           *tinfo,
724     BOOL                readit,
725     BOOL                debugout,
726     BOOL                alloc,
727     TYPEDESC            *tdesc,
728     DWORD               *arg,
729     marshal_state       *buf
730 ) {
731     HRESULT hres = S_OK;
732
733     TRACE("vt %d at %p\n",tdesc->vt,arg);
734
735     while (1) {
736         switch (tdesc->vt) {
737         case VT_EMPTY:
738             if (debugout) MESSAGE("<empty>");
739             return S_OK;
740         case VT_NULL:
741             if (debugout) MESSAGE("<null>");
742             return S_OK;
743         case VT_VARIANT: {
744             VARIANT     *vt = (VARIANT*)arg;
745
746             if (readit) {
747                 DWORD   vttype;
748                 TYPEDESC        tdesc2;
749                 hres = xbuf_get(buf,(LPBYTE)&vttype,sizeof(vttype));
750                 if (hres) {
751                     FIXME("vt type not read?\n");
752                     return hres;
753                 }
754                 memset(&tdesc2,0,sizeof(tdesc2));
755                 tdesc2.vt = vttype;
756                 V_VT(vt)  = vttype;
757                 if (debugout) MESSAGE("Vt(%ld)(",vttype);
758                 hres = deserialize_param(tinfo, readit, debugout, alloc, &tdesc2, &(V_I4(vt)), buf);
759                 MESSAGE(")");
760                 return hres;
761             } else {
762                 VariantInit(vt);
763                 return S_OK;
764             }
765         }
766         case VT_ERROR:
767         case VT_BOOL: case VT_I4: case VT_UI4: case VT_UINT: case VT_R4:
768         case VT_UI2:
769         case VT_UI1:
770             if (readit) {
771                 hres = xbuf_get(buf,(LPBYTE)arg,sizeof(DWORD));
772                 if (hres) FIXME("Failed to read integer 4 byte\n");
773             }
774             if (debugout) MESSAGE("%lx",*arg);
775             return hres;
776         case VT_BSTR: {
777             WCHAR       *str;
778             DWORD       len;
779
780             if (readit) {
781                 hres = xbuf_get(buf,(LPBYTE)&len,sizeof(DWORD));
782                 if (hres) {
783                     FIXME("failed to read bstr klen\n");
784                     return hres;
785                 }
786                 if (len == -1) {
787                     *arg = 0;
788                     if (debugout) MESSAGE("<bstr NULL>");
789                 } else {
790                     str  = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,len+sizeof(WCHAR));
791                     hres = xbuf_get(buf,(LPBYTE)str,len);
792                     if (hres) {
793                         FIXME("Failed to read BSTR.\n");
794                         return hres;
795                     }
796                     *arg = (DWORD)SysAllocStringLen(str,len);
797                     if (debugout) MESSAGE("%s",debugstr_w(str));
798                     HeapFree(GetProcessHeap(),0,str);
799                 }
800             } else {
801                 *arg = 0;
802             }
803             return S_OK;
804         }
805         case VT_PTR: {
806             DWORD       cookie;
807             BOOL        derefhere = 0;
808
809             derefhere = (tdesc->u.lptdesc->vt != VT_USERDEFINED);
810
811             if (readit) {
812                 hres = xbuf_get(buf,(LPBYTE)&cookie,sizeof(cookie));
813                 if (hres) {
814                     FIXME("Failed to load pointer cookie.\n");
815                     return hres;
816                 }
817                 if (cookie != 0x42424242) {
818                     if (debugout) MESSAGE("NULL");
819                     *arg = 0;
820                     return S_OK;
821                 }
822                 if (debugout) MESSAGE("*");
823             }
824             if (alloc) {
825                 if (derefhere)
826                     *arg=(DWORD)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,_xsize(tdesc->u.lptdesc));
827             }
828             if (derefhere)
829                 return deserialize_param(tinfo, readit, debugout, alloc, tdesc->u.lptdesc, (LPDWORD)*arg, buf);
830             else
831                 return deserialize_param(tinfo, readit, debugout, alloc, tdesc->u.lptdesc, arg, buf);
832         }
833         case VT_UNKNOWN:
834             /* FIXME: UNKNOWN is unknown ..., but allocate 4 byte for it */
835             if (alloc)
836                 *arg=(DWORD)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(DWORD));
837             hres = S_OK;
838             if (readit)
839                 hres = _unmarshal_interface(buf,&IID_IUnknown,(LPUNKNOWN*)arg);
840             if (debugout)
841                 MESSAGE("unk(%p)",arg);
842             return hres;
843         case VT_DISPATCH:
844             hres = S_OK;
845             if (readit)
846                 hres = _unmarshal_interface(buf,&IID_IDispatch,(LPUNKNOWN*)arg);
847             if (debugout)
848                 MESSAGE("idisp(%p)",arg);
849             return hres;
850         case VT_VOID:
851             if (debugout) MESSAGE("<void>");
852             return S_OK;
853         case VT_USERDEFINED: {
854             ITypeInfo   *tinfo2;
855             TYPEATTR    *tattr;
856
857             hres = ITypeInfo_GetRefTypeInfo(tinfo,tdesc->u.hreftype,&tinfo2);
858             if (hres) {
859                 FIXME("Could not get typeinfo of hreftype %lx for VT_USERDEFINED.\n",tdesc->u.hreftype);
860                 return hres;
861             }
862             hres = ITypeInfo_GetTypeAttr(tinfo2,&tattr);
863             if (hres) {
864                 FIXME("Could not get typeattr in VT_USERDEFINED.\n");
865             } else {
866                 if (alloc)
867                     *arg = (DWORD)HeapAlloc(GetProcessHeap(),0,tattr->cbSizeInstance);
868                 switch (tattr->typekind) {
869                 case TKIND_DISPATCH:
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                     ERR("Unhandled typekind %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             (*((FARPROC**)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 }