dsound: Restore old format on SetFormat failure.
[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 "wine/debug.h"
41
42 WINE_DEFAULT_DEBUG_CHANNEL(ole);
43
44 /* I don't know what MS's std proxy structure looks like,
45    so this probably doesn't match, but that shouldn't matter */
46 typedef struct {
47   const IRpcProxyBufferVtbl *lpVtbl;
48   LPVOID *PVtbl;
49   LONG RefCount;
50   const IID* piid;
51   LPUNKNOWN pUnkOuter;
52   IUnknown *base_object;  /* must be at offset 0x10 from PVtbl */
53   IRpcProxyBuffer *base_proxy;
54   PCInterfaceName name;
55   LPPSFACTORYBUFFER pPSFactory;
56   LPRPCCHANNELBUFFER pChannel;
57 } StdProxyImpl;
58
59 static const IRpcProxyBufferVtbl StdProxy_Vtbl;
60
61 #define ICOM_THIS_MULTI(impl,field,iface) impl* const This=(impl*)((char*)(iface) - offsetof(impl,field))
62
63 #if defined(__i386__)
64
65 #include "pshpack1.h"
66
67 struct thunk {
68   BYTE mov_eax;
69   DWORD index;
70   BYTE jmp;
71   LONG handler;
72 };
73
74 #include "poppack.h"
75
76 extern void call_stubless_func(void);
77 __ASM_GLOBAL_FUNC(call_stubless_func,
78                   "pushl %eax\n\t"  /* method index */
79                   __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
80                   "pushl %esp\n\t"  /* pointer to index */
81                   __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
82                   "call " __ASM_NAME("ObjectStubless") __ASM_STDCALL(4) "\n\t"
83                   __ASM_CFI(".cfi_adjust_cfa_offset -4\n\t")
84                   "popl %edx\n\t"  /* args size */
85                   __ASM_CFI(".cfi_adjust_cfa_offset -4\n\t")
86                   "movl (%esp),%ecx\n\t"  /* return address */
87                   "addl %edx,%esp\n\t"
88                   "jmp *%ecx" );
89
90 HRESULT WINAPI ObjectStubless(DWORD *args)
91 {
92     DWORD index = args[0];
93     void **iface = (void **)args[2];
94     const void **vtbl = (const void **)*iface;
95     const MIDL_STUBLESS_PROXY_INFO *stubless = *(const MIDL_STUBLESS_PROXY_INFO **)(vtbl - 2);
96     const PFORMAT_STRING fs = stubless->ProcFormatString + stubless->FormatStringOffset[index];
97
98     /* store bytes to remove from stack */
99     args[0] = *(const WORD*)(fs + 8);
100     TRACE("(%p)->(%d)([%d bytes]) ret=%08x\n", iface, index, args[0], args[1]);
101
102     return NdrClientCall2(stubless->pStubDesc, fs, args + 2);
103 }
104
105 #define BLOCK_SIZE 1024
106 #define MAX_BLOCKS 64  /* 64k methods should be enough for anybody */
107
108 static const struct thunk *method_blocks[MAX_BLOCKS];
109
110 static const struct thunk *allocate_block( unsigned int num )
111 {
112     unsigned int i;
113     struct thunk *prev, *block;
114
115     block = VirtualAlloc( NULL, BLOCK_SIZE * sizeof(*block),
116                           MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE );
117     if (!block) return NULL;
118
119     for (i = 0; i < BLOCK_SIZE; i++)
120     {
121         block[i].mov_eax = 0xb8; /* movl $n,%eax */
122         block[i].index   = BLOCK_SIZE * num + i + 3;
123         block[i].jmp     = 0xe9; /* jmp */
124         block[i].handler = (char *)call_stubless_func - (char *)(&block[i].handler + 1);
125     }
126     VirtualProtect( block, BLOCK_SIZE * sizeof(*block), PAGE_EXECUTE_READ, NULL );
127     prev = InterlockedCompareExchangePointer( (void **)&method_blocks[num], block, NULL );
128     if (prev) /* someone beat us to it */
129     {
130         VirtualFree( block, 0, MEM_RELEASE );
131         block = prev;
132     }
133     return block;
134 }
135
136 static BOOL fill_stubless_table( IUnknownVtbl *vtbl, DWORD num )
137 {
138     const void **entry = (const void **)(vtbl + 1);
139     DWORD i, j;
140
141     if (num - 3 > BLOCK_SIZE * MAX_BLOCKS)
142     {
143         FIXME( "%u methods not supported\n", num );
144         return FALSE;
145     }
146     for (i = 0; i < (num - 3 + BLOCK_SIZE - 1) / BLOCK_SIZE; i++)
147     {
148         const struct thunk *block = method_blocks[i];
149         if (!block && !(block = allocate_block( i ))) return FALSE;
150         for (j = 0; j < BLOCK_SIZE && j < num - 3 - i * BLOCK_SIZE; j++, entry++)
151             if (*entry == (LPVOID)-1) *entry = &block[j];
152     }
153     return TRUE;
154 }
155
156 #else  /* __i386__ */
157
158 static BOOL fill_stubless_table( IUnknownVtbl *vtbl, DWORD num )
159 {
160     ERR("stubless proxies are not supported on this architecture\n");
161     return FALSE;
162 }
163
164 #endif  /* __i386__ */
165
166 HRESULT StdProxy_Construct(REFIID riid,
167                            LPUNKNOWN pUnkOuter,
168                            const ProxyFileInfo *ProxyInfo,
169                            int Index,
170                            LPPSFACTORYBUFFER pPSFactory,
171                            LPRPCPROXYBUFFER *ppProxy,
172                            LPVOID *ppvObj)
173 {
174   StdProxyImpl *This;
175   PCInterfaceName name = ProxyInfo->pNamesArray[Index];
176   CInterfaceProxyVtbl *vtbl = ProxyInfo->pProxyVtblList[Index];
177
178   TRACE("(%p,%p,%p,%p,%p) %s\n", pUnkOuter, vtbl, pPSFactory, ppProxy, ppvObj, name);
179
180   /* TableVersion = 2 means it is the stubless version of CInterfaceProxyVtbl */
181   if (ProxyInfo->TableVersion > 1) {
182     ULONG count = ProxyInfo->pStubVtblList[Index]->header.DispatchTableCount;
183     vtbl = (CInterfaceProxyVtbl *)((const void **)vtbl + 1);
184     TRACE("stubless vtbl %p: count=%d\n", vtbl->Vtbl, count );
185     fill_stubless_table( (IUnknownVtbl *)vtbl->Vtbl, count );
186   }
187
188   if (!IsEqualGUID(vtbl->header.piid, riid)) {
189     ERR("IID mismatch during proxy creation\n");
190     return RPC_E_UNEXPECTED;
191   }
192
193   This = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(StdProxyImpl));
194   if (!This) return E_OUTOFMEMORY;
195
196   if (!pUnkOuter) pUnkOuter = (IUnknown *)This;
197   This->lpVtbl = &StdProxy_Vtbl;
198   This->PVtbl = vtbl->Vtbl;
199   /* one reference for the proxy */
200   This->RefCount = 1;
201   This->piid = vtbl->header.piid;
202   This->base_object = NULL;
203   This->base_proxy = NULL;
204   This->pUnkOuter = pUnkOuter;
205   This->name = name;
206   This->pPSFactory = pPSFactory;
207   This->pChannel = NULL;
208
209   if(ProxyInfo->pDelegatedIIDs && ProxyInfo->pDelegatedIIDs[Index])
210   {
211       HRESULT r = create_proxy( ProxyInfo->pDelegatedIIDs[Index], NULL,
212                                 &This->base_proxy, (void **)&This->base_object );
213       if (FAILED(r))
214       {
215           HeapFree( GetProcessHeap(), 0, This );
216           return r;
217       }
218   }
219
220   *ppProxy = (LPRPCPROXYBUFFER)&This->lpVtbl;
221   *ppvObj = &This->PVtbl;
222   IUnknown_AddRef((IUnknown *)*ppvObj);
223   IPSFactoryBuffer_AddRef(pPSFactory);
224
225   TRACE( "iid=%s this %p proxy %p obj %p vtbl %p base proxy %p base obj %p\n",
226          debugstr_guid(riid), This, *ppProxy, *ppvObj, This->PVtbl, This->base_proxy, This->base_object );
227   return S_OK;
228 }
229
230 static void StdProxy_Destruct(LPRPCPROXYBUFFER iface)
231 {
232   ICOM_THIS_MULTI(StdProxyImpl,lpVtbl,iface);
233
234   if (This->pChannel)
235     IRpcProxyBuffer_Disconnect(iface);
236
237   if (This->base_object) IUnknown_Release( This->base_object );
238   if (This->base_proxy) IRpcProxyBuffer_Release( This->base_proxy );
239
240   IPSFactoryBuffer_Release(This->pPSFactory);
241   HeapFree(GetProcessHeap(),0,This);
242 }
243
244 static HRESULT WINAPI StdProxy_QueryInterface(LPRPCPROXYBUFFER iface,
245                                              REFIID riid,
246                                              LPVOID *obj)
247 {
248   ICOM_THIS_MULTI(StdProxyImpl,lpVtbl,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->lpVtbl;
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   ICOM_THIS_MULTI(StdProxyImpl,lpVtbl,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   ICOM_THIS_MULTI(StdProxyImpl,lpVtbl,iface);
279   TRACE("(%p)->Release()\n",This);
280
281   refs = InterlockedDecrement(&This->RefCount);
282   if (!refs)
283     StdProxy_Destruct((LPRPCPROXYBUFFER)&This->lpVtbl);
284   return refs;
285 }
286
287 static HRESULT WINAPI StdProxy_Connect(LPRPCPROXYBUFFER iface,
288                                       LPRPCCHANNELBUFFER pChannel)
289 {
290   ICOM_THIS_MULTI(StdProxyImpl,lpVtbl,iface);
291   TRACE("(%p)->Connect(%p)\n",This,pChannel);
292
293   This->pChannel = pChannel;
294   IRpcChannelBuffer_AddRef(pChannel);
295   if (This->base_proxy) IRpcProxyBuffer_Connect( This->base_proxy, pChannel );
296   return S_OK;
297 }
298
299 static VOID WINAPI StdProxy_Disconnect(LPRPCPROXYBUFFER iface)
300 {
301   ICOM_THIS_MULTI(StdProxyImpl,lpVtbl,iface);
302   TRACE("(%p)->Disconnect()\n",This);
303
304   if (This->base_proxy) IRpcProxyBuffer_Disconnect( This->base_proxy );
305
306   IRpcChannelBuffer_Release(This->pChannel);
307   This->pChannel = NULL;
308 }
309
310 static const IRpcProxyBufferVtbl StdProxy_Vtbl =
311 {
312   StdProxy_QueryInterface,
313   StdProxy_AddRef,
314   StdProxy_Release,
315   StdProxy_Connect,
316   StdProxy_Disconnect
317 };
318
319 static void StdProxy_GetChannel(LPVOID iface,
320                                    LPRPCCHANNELBUFFER *ppChannel)
321 {
322   ICOM_THIS_MULTI(StdProxyImpl,PVtbl,iface);
323   TRACE("(%p)->GetChannel(%p) %s\n",This,ppChannel,This->name);
324
325   *ppChannel = This->pChannel;
326 }
327
328 static void StdProxy_GetIID(LPVOID iface,
329                                const IID **ppiid)
330 {
331   ICOM_THIS_MULTI(StdProxyImpl,PVtbl,iface);
332   TRACE("(%p)->GetIID(%p) %s\n",This,ppiid,This->name);
333
334   *ppiid = This->piid;
335 }
336
337 HRESULT WINAPI IUnknown_QueryInterface_Proxy(LPUNKNOWN iface,
338                                             REFIID riid,
339                                             LPVOID *ppvObj)
340 {
341   ICOM_THIS_MULTI(StdProxyImpl,PVtbl,iface);
342   TRACE("(%p)->QueryInterface(%s,%p) %s\n",This,debugstr_guid(riid),ppvObj,This->name);
343   return IUnknown_QueryInterface(This->pUnkOuter,riid,ppvObj);
344 }
345
346 ULONG WINAPI IUnknown_AddRef_Proxy(LPUNKNOWN iface)
347 {
348   ICOM_THIS_MULTI(StdProxyImpl,PVtbl,iface);
349   TRACE("(%p)->AddRef() %s\n",This,This->name);
350   return IUnknown_AddRef(This->pUnkOuter);
351 }
352
353 ULONG WINAPI IUnknown_Release_Proxy(LPUNKNOWN iface)
354 {
355   ICOM_THIS_MULTI(StdProxyImpl,PVtbl,iface);
356   TRACE("(%p)->Release() %s\n",This,This->name);
357   return IUnknown_Release(This->pUnkOuter);
358 }
359
360 /***********************************************************************
361  *           NdrProxyInitialize [RPCRT4.@]
362  */
363 void WINAPI NdrProxyInitialize(void *This,
364                               PRPC_MESSAGE pRpcMsg,
365                               PMIDL_STUB_MESSAGE pStubMsg,
366                               PMIDL_STUB_DESC pStubDescriptor,
367                               unsigned int ProcNum)
368 {
369   TRACE("(%p,%p,%p,%p,%d)\n", This, pRpcMsg, pStubMsg, pStubDescriptor, ProcNum);
370   NdrClientInitializeNew(pRpcMsg, pStubMsg, pStubDescriptor, ProcNum);
371   StdProxy_GetChannel(This, &pStubMsg->pRpcChannelBuffer);
372   IRpcChannelBuffer_GetDestCtx(pStubMsg->pRpcChannelBuffer,
373                                &pStubMsg->dwDestContext,
374                                &pStubMsg->pvDestContext);
375   TRACE("channel=%p\n", pStubMsg->pRpcChannelBuffer);
376 }
377
378 /***********************************************************************
379  *           NdrProxyGetBuffer [RPCRT4.@]
380  */
381 void WINAPI NdrProxyGetBuffer(void *This,
382                              PMIDL_STUB_MESSAGE pStubMsg)
383 {
384   HRESULT hr;
385   const IID *riid = NULL;
386
387   TRACE("(%p,%p)\n", This, pStubMsg);
388   pStubMsg->RpcMsg->BufferLength = pStubMsg->BufferLength;
389   pStubMsg->dwStubPhase = PROXY_GETBUFFER;
390   StdProxy_GetIID(This, &riid);
391   hr = IRpcChannelBuffer_GetBuffer(pStubMsg->pRpcChannelBuffer,
392                                   (RPCOLEMESSAGE*)pStubMsg->RpcMsg,
393                                   riid);
394   if (FAILED(hr))
395   {
396     RpcRaiseException(hr);
397     return;
398   }
399   pStubMsg->fBufferValid = TRUE;
400   pStubMsg->BufferStart = pStubMsg->RpcMsg->Buffer;
401   pStubMsg->BufferEnd = pStubMsg->BufferStart + pStubMsg->BufferLength;
402   pStubMsg->Buffer = pStubMsg->BufferStart;
403   pStubMsg->dwStubPhase = PROXY_MARSHAL;
404 }
405
406 /***********************************************************************
407  *           NdrProxySendReceive [RPCRT4.@]
408  */
409 void WINAPI NdrProxySendReceive(void *This,
410                                PMIDL_STUB_MESSAGE pStubMsg)
411 {
412   ULONG Status = 0;
413   HRESULT hr;
414
415   TRACE("(%p,%p)\n", This, pStubMsg);
416
417   if (!pStubMsg->pRpcChannelBuffer)
418   {
419     WARN("Trying to use disconnected proxy %p\n", This);
420     RpcRaiseException(RPC_E_DISCONNECTED);
421   }
422
423   pStubMsg->dwStubPhase = PROXY_SENDRECEIVE;
424   /* avoid sending uninitialised parts of the buffer on the wire */
425   pStubMsg->RpcMsg->BufferLength = pStubMsg->Buffer - (unsigned char *)pStubMsg->RpcMsg->Buffer;
426   hr = IRpcChannelBuffer_SendReceive(pStubMsg->pRpcChannelBuffer,
427                                     (RPCOLEMESSAGE*)pStubMsg->RpcMsg,
428                                     &Status);
429   pStubMsg->dwStubPhase = PROXY_UNMARSHAL;
430   pStubMsg->BufferLength = pStubMsg->RpcMsg->BufferLength;
431   pStubMsg->BufferStart = pStubMsg->RpcMsg->Buffer;
432   pStubMsg->BufferEnd = pStubMsg->BufferStart + pStubMsg->BufferLength;
433   pStubMsg->Buffer = pStubMsg->BufferStart;
434
435   /* raise exception if call failed */
436   if (hr == RPC_S_CALL_FAILED) RpcRaiseException(*(DWORD*)pStubMsg->Buffer);
437   else if (FAILED(hr)) RpcRaiseException(hr);
438 }
439
440 /***********************************************************************
441  *           NdrProxyFreeBuffer [RPCRT4.@]
442  */
443 void WINAPI NdrProxyFreeBuffer(void *This,
444                               PMIDL_STUB_MESSAGE pStubMsg)
445 {
446   TRACE("(%p,%p)\n", This, pStubMsg);
447
448   if (pStubMsg->fBufferValid)
449   {
450     IRpcChannelBuffer_FreeBuffer(pStubMsg->pRpcChannelBuffer,
451                                  (RPCOLEMESSAGE*)pStubMsg->RpcMsg);
452     pStubMsg->fBufferValid = TRUE;
453   }
454 }
455
456 /***********************************************************************
457  *           NdrProxyErrorHandler [RPCRT4.@]
458  */
459 HRESULT WINAPI NdrProxyErrorHandler(DWORD dwExceptionCode)
460 {
461   WARN("(0x%08x): a proxy call failed\n", dwExceptionCode);
462
463   if (FAILED(dwExceptionCode))
464     return dwExceptionCode;
465   else
466     return HRESULT_FROM_WIN32(dwExceptionCode);
467 }
468
469 HRESULT WINAPI
470 CreateProxyFromTypeInfo( LPTYPEINFO pTypeInfo, LPUNKNOWN pUnkOuter, REFIID riid,
471                          LPRPCPROXYBUFFER *ppProxy, LPVOID *ppv )
472 {
473     typedef INT (WINAPI *MessageBoxA)(HWND,LPCSTR,LPCSTR,UINT);
474     HMODULE hUser32 = LoadLibraryA("user32");
475     MessageBoxA pMessageBoxA = (void *)GetProcAddress(hUser32, "MessageBoxA");
476
477     FIXME("%p %p %s %p %p\n", pTypeInfo, pUnkOuter, debugstr_guid(riid), ppProxy, ppv);
478     if (pMessageBoxA)
479     {
480         pMessageBoxA(NULL,
481             "The native implementation of OLEAUT32.DLL cannot be used "
482             "with Wine's RPCRT4.DLL. Remove OLEAUT32.DLL and try again.\n",
483             "Wine: Unimplemented CreateProxyFromTypeInfo",
484             0x10);
485         ExitProcess(1);
486     }
487     return E_NOTIMPL;
488 }
489
490 HRESULT WINAPI
491 CreateStubFromTypeInfo(ITypeInfo *pTypeInfo, REFIID riid, IUnknown *pUnkServer,
492                        IRpcStubBuffer **ppStub )
493 {
494     typedef INT (WINAPI *MessageBoxA)(HWND,LPCSTR,LPCSTR,UINT);
495     HMODULE hUser32 = LoadLibraryA("user32");
496     MessageBoxA pMessageBoxA = (void *)GetProcAddress(hUser32, "MessageBoxA");
497
498     FIXME("%p %s %p %p\n", pTypeInfo, debugstr_guid(riid), pUnkServer, ppStub);
499     if (pMessageBoxA)
500     {
501         pMessageBoxA(NULL,
502             "The native implementation of OLEAUT32.DLL cannot be used "
503             "with Wine's RPCRT4.DLL. Remove OLEAUT32.DLL and try again.\n",
504             "Wine: Unimplemented CreateProxyFromTypeInfo",
505             0x10);
506         ExitProcess(1);
507     }
508     return E_NOTIMPL;
509 }