rpcrt4: Reimplement the stubless proxy entry point entirely in assembly.
[wine] / dlls / rpcrt4 / cproxy.c
1 /*
2  * COM proxy implementation
3  *
4  * Copyright 2001 Ove Kåven, TransGaming Technologies
5  * Copyright 2009 Alexandre Julliard
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20  * 
21  * TODO: Handle non-i386 architectures
22  */
23
24 #include "config.h"
25 #include "wine/port.h"
26
27 #include <stdarg.h>
28
29 #define COBJMACROS
30
31 #include "windef.h"
32 #include "winbase.h"
33 #include "winerror.h"
34
35 #include "objbase.h"
36 #include "rpcproxy.h"
37
38 #include "cpsf.h"
39 #include "ndr_misc.h"
40 #include "ndr_stubless.h"
41 #include "wine/debug.h"
42
43 WINE_DEFAULT_DEBUG_CHANNEL(ole);
44
45 /* I don't know what MS's std proxy structure looks like,
46    so this probably doesn't match, but that shouldn't matter */
47 typedef struct {
48   IRpcProxyBuffer IRpcProxyBuffer_iface;
49   LPVOID *PVtbl;
50   LONG RefCount;
51   const IID* piid;
52   LPUNKNOWN pUnkOuter;
53   IUnknown *base_object;  /* must be at offset 0x10 from PVtbl */
54   IRpcProxyBuffer *base_proxy;
55   PCInterfaceName name;
56   LPPSFACTORYBUFFER pPSFactory;
57   LPRPCCHANNELBUFFER pChannel;
58 } StdProxyImpl;
59
60 static const IRpcProxyBufferVtbl StdProxy_Vtbl;
61
62 static inline StdProxyImpl *impl_from_IRpcProxyBuffer(IRpcProxyBuffer *iface)
63 {
64     return CONTAINING_RECORD(iface, StdProxyImpl, IRpcProxyBuffer_iface);
65 }
66
67 static inline StdProxyImpl *impl_from_proxy_obj( void *iface )
68 {
69     return CONTAINING_RECORD(iface, StdProxyImpl, PVtbl);
70 }
71
72 #ifdef __i386__
73
74 extern void call_stubless_func(void);
75 __ASM_GLOBAL_FUNC(call_stubless_func,
76                   "movl 4(%esp),%ecx\n\t"         /* This pointer */
77                   "movl (%ecx),%ecx\n\t"          /* This->lpVtbl */
78                   "movl -8(%ecx),%ecx\n\t"        /* MIDL_STUBLESS_PROXY_INFO */
79                   "movl 8(%ecx),%edx\n\t"         /* info->FormatStringOffset */
80                   "movzwl (%edx,%eax,2),%edx\n\t" /* FormatStringOffset[index] */
81                   "addl 4(%ecx),%edx\n\t"         /* info->ProcFormatString + offset */
82                   "movzwl 8(%edx),%eax\n\t"       /* arguments size */
83                   "pushl %eax\n\t"
84                   __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
85                   "leal 8(%esp),%eax\n\t"         /* &This */
86                   "pushl %eax\n\t"
87                   __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
88                   "pushl %edx\n\t"                /* format string */
89                   __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
90                   "pushl (%ecx)\n\t"              /* info->pStubDesc */
91                   __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
92                   "call " __ASM_NAME("ndr_client_call") "\n\t"
93                   "leal 12(%esp),%esp\n\t"
94                   __ASM_CFI(".cfi_adjust_cfa_offset -12\n\t")
95                   "popl %edx\n\t"                 /* arguments size */
96                   __ASM_CFI(".cfi_adjust_cfa_offset -4\n\t")
97                   "movl (%esp),%ecx\n\t"  /* return address */
98                   "addl %edx,%esp\n\t"
99                   "jmp *%ecx" );
100
101 #include "pshpack1.h"
102 struct thunk
103 {
104   BYTE mov_eax;
105   DWORD index;
106   BYTE jmp;
107   LONG handler;
108 };
109 #include "poppack.h"
110
111 static inline void init_thunk( struct thunk *thunk, unsigned int index )
112 {
113     thunk->mov_eax = 0xb8; /* movl $n,%eax */
114     thunk->index   = index;
115     thunk->jmp     = 0xe9; /* jmp */
116     thunk->handler = (char *)call_stubless_func - (char *)(&thunk->handler + 1);
117 }
118
119 #else  /* __i386__ */
120
121 #warning You must implement stubless proxies for your CPU
122
123 struct thunk
124 {
125   DWORD index;
126 };
127
128 static inline void init_thunk( struct thunk *thunk, unsigned int index )
129 {
130     thunk->index = index;
131 }
132
133 #endif  /* __i386__ */
134
135 #define BLOCK_SIZE 1024
136 #define MAX_BLOCKS 64  /* 64k methods should be enough for anybody */
137
138 static const struct thunk *method_blocks[MAX_BLOCKS];
139
140 static const struct thunk *allocate_block( unsigned int num )
141 {
142     unsigned int i;
143     struct thunk *prev, *block;
144
145     block = VirtualAlloc( NULL, BLOCK_SIZE * sizeof(*block),
146                           MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE );
147     if (!block) return NULL;
148
149     for (i = 0; i < BLOCK_SIZE; i++) init_thunk( &block[i], BLOCK_SIZE * num + i + 3 );
150     VirtualProtect( block, BLOCK_SIZE * sizeof(*block), PAGE_EXECUTE_READ, NULL );
151     prev = InterlockedCompareExchangePointer( (void **)&method_blocks[num], block, NULL );
152     if (prev) /* someone beat us to it */
153     {
154         VirtualFree( block, 0, MEM_RELEASE );
155         block = prev;
156     }
157     return block;
158 }
159
160 static BOOL fill_stubless_table( IUnknownVtbl *vtbl, DWORD num )
161 {
162     const void **entry = (const void **)(vtbl + 1);
163     DWORD i, j;
164
165     if (num - 3 > BLOCK_SIZE * MAX_BLOCKS)
166     {
167         FIXME( "%u methods not supported\n", num );
168         return FALSE;
169     }
170     for (i = 0; i < (num - 3 + BLOCK_SIZE - 1) / BLOCK_SIZE; i++)
171     {
172         const struct thunk *block = method_blocks[i];
173         if (!block && !(block = allocate_block( i ))) return FALSE;
174         for (j = 0; j < BLOCK_SIZE && j < num - 3 - i * BLOCK_SIZE; j++, entry++)
175             if (*entry == (LPVOID)-1) *entry = &block[j];
176     }
177     return TRUE;
178 }
179
180 HRESULT StdProxy_Construct(REFIID riid,
181                            LPUNKNOWN pUnkOuter,
182                            const ProxyFileInfo *ProxyInfo,
183                            int Index,
184                            LPPSFACTORYBUFFER pPSFactory,
185                            LPRPCPROXYBUFFER *ppProxy,
186                            LPVOID *ppvObj)
187 {
188   StdProxyImpl *This;
189   PCInterfaceName name = ProxyInfo->pNamesArray[Index];
190   CInterfaceProxyVtbl *vtbl = ProxyInfo->pProxyVtblList[Index];
191
192   TRACE("(%p,%p,%p,%p,%p) %s\n", pUnkOuter, vtbl, pPSFactory, ppProxy, ppvObj, name);
193
194   /* TableVersion = 2 means it is the stubless version of CInterfaceProxyVtbl */
195   if (ProxyInfo->TableVersion > 1) {
196     ULONG count = ProxyInfo->pStubVtblList[Index]->header.DispatchTableCount;
197     vtbl = (CInterfaceProxyVtbl *)((const void **)vtbl + 1);
198     TRACE("stubless vtbl %p: count=%d\n", vtbl->Vtbl, count );
199     fill_stubless_table( (IUnknownVtbl *)vtbl->Vtbl, count );
200   }
201
202   if (!IsEqualGUID(vtbl->header.piid, riid)) {
203     ERR("IID mismatch during proxy creation\n");
204     return RPC_E_UNEXPECTED;
205   }
206
207   This = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(StdProxyImpl));
208   if (!This) return E_OUTOFMEMORY;
209
210   if (!pUnkOuter) pUnkOuter = (IUnknown *)This;
211   This->IRpcProxyBuffer_iface.lpVtbl = &StdProxy_Vtbl;
212   This->PVtbl = vtbl->Vtbl;
213   /* one reference for the proxy */
214   This->RefCount = 1;
215   This->piid = vtbl->header.piid;
216   This->base_object = NULL;
217   This->base_proxy = NULL;
218   This->pUnkOuter = pUnkOuter;
219   This->name = name;
220   This->pPSFactory = pPSFactory;
221   This->pChannel = NULL;
222
223   if(ProxyInfo->pDelegatedIIDs && ProxyInfo->pDelegatedIIDs[Index])
224   {
225       HRESULT r = create_proxy( ProxyInfo->pDelegatedIIDs[Index], NULL,
226                                 &This->base_proxy, (void **)&This->base_object );
227       if (FAILED(r))
228       {
229           HeapFree( GetProcessHeap(), 0, This );
230           return r;
231       }
232   }
233
234   *ppProxy = &This->IRpcProxyBuffer_iface;
235   *ppvObj = &This->PVtbl;
236   IUnknown_AddRef((IUnknown *)*ppvObj);
237   IPSFactoryBuffer_AddRef(pPSFactory);
238
239   TRACE( "iid=%s this %p proxy %p obj %p vtbl %p base proxy %p base obj %p\n",
240          debugstr_guid(riid), This, *ppProxy, *ppvObj, This->PVtbl, This->base_proxy, This->base_object );
241   return S_OK;
242 }
243
244 static HRESULT WINAPI StdProxy_QueryInterface(LPRPCPROXYBUFFER iface,
245                                              REFIID riid,
246                                              LPVOID *obj)
247 {
248   StdProxyImpl *This = impl_from_IRpcProxyBuffer(iface);
249   TRACE("(%p)->QueryInterface(%s,%p)\n",This,debugstr_guid(riid),obj);
250
251   if (IsEqualGUID(&IID_IUnknown,riid) ||
252       IsEqualGUID(This->piid,riid)) {
253     *obj = &This->PVtbl;
254     InterlockedIncrement(&This->RefCount);
255     return S_OK;
256   }
257
258   if (IsEqualGUID(&IID_IRpcProxyBuffer,riid)) {
259     *obj = &This->IRpcProxyBuffer_iface;
260     InterlockedIncrement(&This->RefCount);
261     return S_OK;
262   }
263
264   return E_NOINTERFACE;
265 }
266
267 static ULONG WINAPI StdProxy_AddRef(LPRPCPROXYBUFFER iface)
268 {
269   StdProxyImpl *This = impl_from_IRpcProxyBuffer(iface);
270   TRACE("(%p)->AddRef()\n",This);
271
272   return InterlockedIncrement(&This->RefCount);
273 }
274
275 static ULONG WINAPI StdProxy_Release(LPRPCPROXYBUFFER iface)
276 {
277   ULONG refs;
278   StdProxyImpl *This = impl_from_IRpcProxyBuffer(iface);
279   TRACE("(%p)->Release()\n",This);
280
281   refs = InterlockedDecrement(&This->RefCount);
282   if (!refs)
283   {
284     if (This->pChannel)
285       IRpcProxyBuffer_Disconnect(&This->IRpcProxyBuffer_iface);
286
287     if (This->base_object) IUnknown_Release( This->base_object );
288     if (This->base_proxy) IRpcProxyBuffer_Release( This->base_proxy );
289
290     IPSFactoryBuffer_Release(This->pPSFactory);
291     HeapFree(GetProcessHeap(),0,This);
292   }
293
294   return refs;
295 }
296
297 static HRESULT WINAPI StdProxy_Connect(LPRPCPROXYBUFFER iface,
298                                       LPRPCCHANNELBUFFER pChannel)
299 {
300   StdProxyImpl *This = impl_from_IRpcProxyBuffer(iface);
301   TRACE("(%p)->Connect(%p)\n",This,pChannel);
302
303   This->pChannel = pChannel;
304   IRpcChannelBuffer_AddRef(pChannel);
305   if (This->base_proxy) IRpcProxyBuffer_Connect( This->base_proxy, pChannel );
306   return S_OK;
307 }
308
309 static VOID WINAPI StdProxy_Disconnect(LPRPCPROXYBUFFER iface)
310 {
311   StdProxyImpl *This = impl_from_IRpcProxyBuffer(iface);
312   TRACE("(%p)->Disconnect()\n",This);
313
314   if (This->base_proxy) IRpcProxyBuffer_Disconnect( This->base_proxy );
315
316   IRpcChannelBuffer_Release(This->pChannel);
317   This->pChannel = NULL;
318 }
319
320 static const IRpcProxyBufferVtbl StdProxy_Vtbl =
321 {
322   StdProxy_QueryInterface,
323   StdProxy_AddRef,
324   StdProxy_Release,
325   StdProxy_Connect,
326   StdProxy_Disconnect
327 };
328
329 static void StdProxy_GetChannel(LPVOID iface,
330                                    LPRPCCHANNELBUFFER *ppChannel)
331 {
332   StdProxyImpl *This = impl_from_proxy_obj( iface );
333   TRACE("(%p)->GetChannel(%p) %s\n",This,ppChannel,This->name);
334
335   *ppChannel = This->pChannel;
336 }
337
338 static void StdProxy_GetIID(LPVOID iface,
339                                const IID **ppiid)
340 {
341   StdProxyImpl *This = impl_from_proxy_obj( iface );
342   TRACE("(%p)->GetIID(%p) %s\n",This,ppiid,This->name);
343
344   *ppiid = This->piid;
345 }
346
347 HRESULT WINAPI IUnknown_QueryInterface_Proxy(LPUNKNOWN iface,
348                                             REFIID riid,
349                                             LPVOID *ppvObj)
350 {
351   StdProxyImpl *This = impl_from_proxy_obj( iface );
352   TRACE("(%p)->QueryInterface(%s,%p) %s\n",This,debugstr_guid(riid),ppvObj,This->name);
353   return IUnknown_QueryInterface(This->pUnkOuter,riid,ppvObj);
354 }
355
356 ULONG WINAPI IUnknown_AddRef_Proxy(LPUNKNOWN iface)
357 {
358   StdProxyImpl *This = impl_from_proxy_obj( iface );
359   TRACE("(%p)->AddRef() %s\n",This,This->name);
360   return IUnknown_AddRef(This->pUnkOuter);
361 }
362
363 ULONG WINAPI IUnknown_Release_Proxy(LPUNKNOWN iface)
364 {
365   StdProxyImpl *This = impl_from_proxy_obj( iface );
366   TRACE("(%p)->Release() %s\n",This,This->name);
367   return IUnknown_Release(This->pUnkOuter);
368 }
369
370 /***********************************************************************
371  *           NdrProxyInitialize [RPCRT4.@]
372  */
373 void WINAPI NdrProxyInitialize(void *This,
374                               PRPC_MESSAGE pRpcMsg,
375                               PMIDL_STUB_MESSAGE pStubMsg,
376                               PMIDL_STUB_DESC pStubDescriptor,
377                               unsigned int ProcNum)
378 {
379   TRACE("(%p,%p,%p,%p,%d)\n", This, pRpcMsg, pStubMsg, pStubDescriptor, ProcNum);
380   NdrClientInitializeNew(pRpcMsg, pStubMsg, pStubDescriptor, ProcNum);
381   StdProxy_GetChannel(This, &pStubMsg->pRpcChannelBuffer);
382   IRpcChannelBuffer_GetDestCtx(pStubMsg->pRpcChannelBuffer,
383                                &pStubMsg->dwDestContext,
384                                &pStubMsg->pvDestContext);
385   TRACE("channel=%p\n", pStubMsg->pRpcChannelBuffer);
386 }
387
388 /***********************************************************************
389  *           NdrProxyGetBuffer [RPCRT4.@]
390  */
391 void WINAPI NdrProxyGetBuffer(void *This,
392                              PMIDL_STUB_MESSAGE pStubMsg)
393 {
394   HRESULT hr;
395   const IID *riid = NULL;
396
397   TRACE("(%p,%p)\n", This, pStubMsg);
398   pStubMsg->RpcMsg->BufferLength = pStubMsg->BufferLength;
399   pStubMsg->dwStubPhase = PROXY_GETBUFFER;
400   StdProxy_GetIID(This, &riid);
401   hr = IRpcChannelBuffer_GetBuffer(pStubMsg->pRpcChannelBuffer,
402                                   (RPCOLEMESSAGE*)pStubMsg->RpcMsg,
403                                   riid);
404   if (FAILED(hr))
405   {
406     RpcRaiseException(hr);
407     return;
408   }
409   pStubMsg->fBufferValid = TRUE;
410   pStubMsg->BufferStart = pStubMsg->RpcMsg->Buffer;
411   pStubMsg->BufferEnd = pStubMsg->BufferStart + pStubMsg->BufferLength;
412   pStubMsg->Buffer = pStubMsg->BufferStart;
413   pStubMsg->dwStubPhase = PROXY_MARSHAL;
414 }
415
416 /***********************************************************************
417  *           NdrProxySendReceive [RPCRT4.@]
418  */
419 void WINAPI NdrProxySendReceive(void *This,
420                                PMIDL_STUB_MESSAGE pStubMsg)
421 {
422   ULONG Status = 0;
423   HRESULT hr;
424
425   TRACE("(%p,%p)\n", This, pStubMsg);
426
427   if (!pStubMsg->pRpcChannelBuffer)
428   {
429     WARN("Trying to use disconnected proxy %p\n", This);
430     RpcRaiseException(RPC_E_DISCONNECTED);
431   }
432
433   pStubMsg->dwStubPhase = PROXY_SENDRECEIVE;
434   /* avoid sending uninitialised parts of the buffer on the wire */
435   pStubMsg->RpcMsg->BufferLength = pStubMsg->Buffer - (unsigned char *)pStubMsg->RpcMsg->Buffer;
436   hr = IRpcChannelBuffer_SendReceive(pStubMsg->pRpcChannelBuffer,
437                                     (RPCOLEMESSAGE*)pStubMsg->RpcMsg,
438                                     &Status);
439   pStubMsg->dwStubPhase = PROXY_UNMARSHAL;
440   pStubMsg->BufferLength = pStubMsg->RpcMsg->BufferLength;
441   pStubMsg->BufferStart = pStubMsg->RpcMsg->Buffer;
442   pStubMsg->BufferEnd = pStubMsg->BufferStart + pStubMsg->BufferLength;
443   pStubMsg->Buffer = pStubMsg->BufferStart;
444
445   /* raise exception if call failed */
446   if (hr == RPC_S_CALL_FAILED) RpcRaiseException(*(DWORD*)pStubMsg->Buffer);
447   else if (FAILED(hr)) RpcRaiseException(hr);
448 }
449
450 /***********************************************************************
451  *           NdrProxyFreeBuffer [RPCRT4.@]
452  */
453 void WINAPI NdrProxyFreeBuffer(void *This,
454                               PMIDL_STUB_MESSAGE pStubMsg)
455 {
456   TRACE("(%p,%p)\n", This, pStubMsg);
457
458   if (pStubMsg->fBufferValid)
459   {
460     IRpcChannelBuffer_FreeBuffer(pStubMsg->pRpcChannelBuffer,
461                                  (RPCOLEMESSAGE*)pStubMsg->RpcMsg);
462     pStubMsg->fBufferValid = TRUE;
463   }
464 }
465
466 /***********************************************************************
467  *           NdrProxyErrorHandler [RPCRT4.@]
468  */
469 HRESULT WINAPI NdrProxyErrorHandler(DWORD dwExceptionCode)
470 {
471   WARN("(0x%08x): a proxy call failed\n", dwExceptionCode);
472
473   if (FAILED(dwExceptionCode))
474     return dwExceptionCode;
475   else
476     return HRESULT_FROM_WIN32(dwExceptionCode);
477 }
478
479 HRESULT WINAPI
480 CreateProxyFromTypeInfo( LPTYPEINFO pTypeInfo, LPUNKNOWN pUnkOuter, REFIID riid,
481                          LPRPCPROXYBUFFER *ppProxy, LPVOID *ppv )
482 {
483     typedef INT (WINAPI *MessageBoxA)(HWND,LPCSTR,LPCSTR,UINT);
484     HMODULE hUser32 = LoadLibraryA("user32");
485     MessageBoxA pMessageBoxA = (void *)GetProcAddress(hUser32, "MessageBoxA");
486
487     FIXME("%p %p %s %p %p\n", pTypeInfo, pUnkOuter, debugstr_guid(riid), ppProxy, ppv);
488     if (pMessageBoxA)
489     {
490         pMessageBoxA(NULL,
491             "The native implementation of OLEAUT32.DLL cannot be used "
492             "with Wine's RPCRT4.DLL. Remove OLEAUT32.DLL and try again.\n",
493             "Wine: Unimplemented CreateProxyFromTypeInfo",
494             0x10);
495         ExitProcess(1);
496     }
497     return E_NOTIMPL;
498 }
499
500 HRESULT WINAPI
501 CreateStubFromTypeInfo(ITypeInfo *pTypeInfo, REFIID riid, IUnknown *pUnkServer,
502                        IRpcStubBuffer **ppStub )
503 {
504     typedef INT (WINAPI *MessageBoxA)(HWND,LPCSTR,LPCSTR,UINT);
505     HMODULE hUser32 = LoadLibraryA("user32");
506     MessageBoxA pMessageBoxA = (void *)GetProcAddress(hUser32, "MessageBoxA");
507
508     FIXME("%p %s %p %p\n", pTypeInfo, debugstr_guid(riid), pUnkServer, ppStub);
509     if (pMessageBoxA)
510     {
511         pMessageBoxA(NULL,
512             "The native implementation of OLEAUT32.DLL cannot be used "
513             "with Wine's RPCRT4.DLL. Remove OLEAUT32.DLL and try again.\n",
514             "Wine: Unimplemented CreateProxyFromTypeInfo",
515             0x10);
516         ExitProcess(1);
517     }
518     return E_NOTIMPL;
519 }