rpcrt4: Fix parameter stack size computation in the old-style stubless marshaller.
[wine] / dlls / rpcrt4 / ndr_stubless.c
1 /*
2  * NDR -Oi,-Oif,-Oicf Interpreter
3  *
4  * Copyright 2001 Ove Kåven, TransGaming Technologies
5  * Copyright 2003-5 Robert Shearman (for CodeWeavers)
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:
22  *  - Pipes
23  *  - Some types of binding handles
24  */
25
26 #include "config.h"
27 #include "wine/port.h"
28
29 #include <stdarg.h>
30 #include <stdio.h>
31 #include <string.h>
32
33 #include "windef.h"
34 #include "winbase.h"
35 #include "winerror.h"
36
37 #include "objbase.h"
38 #include "rpc.h"
39 #include "rpcproxy.h"
40
41 #include "wine/exception.h"
42 #include "wine/debug.h"
43 #include "wine/rpcfc.h"
44
45 #include "cpsf.h"
46 #include "ndr_misc.h"
47 #include "ndr_stubless.h"
48
49 WINE_DEFAULT_DEBUG_CHANNEL(rpc);
50
51 #define NDR_TABLE_MASK 127
52
53 static inline void call_buffer_sizer(PMIDL_STUB_MESSAGE pStubMsg, unsigned char *pMemory, PFORMAT_STRING pFormat)
54 {
55     NDR_BUFFERSIZE m = NdrBufferSizer[pFormat[0] & NDR_TABLE_MASK];
56     if (m) m(pStubMsg, pMemory, pFormat);
57     else
58     {
59         FIXME("format type 0x%x not implemented\n", pFormat[0]);
60         RpcRaiseException(RPC_X_BAD_STUB_DATA);
61     }
62 }
63
64 static inline unsigned char *call_marshaller(PMIDL_STUB_MESSAGE pStubMsg, unsigned char *pMemory, PFORMAT_STRING pFormat)
65 {
66     NDR_MARSHALL m = NdrMarshaller[pFormat[0] & NDR_TABLE_MASK];
67     if (m) return m(pStubMsg, pMemory, pFormat);
68     else
69     {
70         FIXME("format type 0x%x not implemented\n", pFormat[0]);
71         RpcRaiseException(RPC_X_BAD_STUB_DATA);
72         return NULL;
73     }
74 }
75
76 static inline unsigned char *call_unmarshaller(PMIDL_STUB_MESSAGE pStubMsg, unsigned char **ppMemory, PFORMAT_STRING pFormat, unsigned char fMustAlloc)
77 {
78     NDR_UNMARSHALL m = NdrUnmarshaller[pFormat[0] & NDR_TABLE_MASK];
79     if (m) return m(pStubMsg, ppMemory, pFormat, fMustAlloc);
80     else
81     {
82         FIXME("format type 0x%x not implemented\n", pFormat[0]);
83         RpcRaiseException(RPC_X_BAD_STUB_DATA);
84         return NULL;
85     }
86 }
87
88 static inline void call_freer(PMIDL_STUB_MESSAGE pStubMsg, unsigned char *pMemory, PFORMAT_STRING pFormat)
89 {
90     NDR_FREE m = NdrFreer[pFormat[0] & NDR_TABLE_MASK];
91     if (m) m(pStubMsg, pMemory, pFormat);
92 }
93
94 #define STUBLESS_UNMARSHAL  1
95 #define STUBLESS_INITOUT    2
96 #define STUBLESS_CALLSERVER 3
97 #define STUBLESS_CALCSIZE   4
98 #define STUBLESS_GETBUFFER  5
99 #define STUBLESS_MARSHAL    6
100 #define STUBLESS_FREE       7
101
102 void WINAPI NdrRpcSmSetClientToOsf(PMIDL_STUB_MESSAGE pMessage)
103 {
104 #if 0 /* these functions are not defined yet */
105     pMessage->pfnAllocate = NdrRpcSmClientAllocate;
106     pMessage->pfnFree = NdrRpcSmClientFree;
107 #endif
108 }
109
110 static void dump_RPC_FC_PROC_PF(PARAM_ATTRIBUTES param_attributes)
111 {
112     if (param_attributes.MustSize) TRACE(" MustSize");
113     if (param_attributes.MustFree) TRACE(" MustFree");
114     if (param_attributes.IsPipe) TRACE(" IsPipe");
115     if (param_attributes.IsIn) TRACE(" IsIn");
116     if (param_attributes.IsOut) TRACE(" IsOut");
117     if (param_attributes.IsReturn) TRACE(" IsReturn");
118     if (param_attributes.IsBasetype) TRACE(" IsBasetype");
119     if (param_attributes.IsByValue) TRACE(" IsByValue");
120     if (param_attributes.IsSimpleRef) TRACE(" IsSimpleRef");
121     if (param_attributes.IsDontCallFreeInst) TRACE(" IsDontCallFreeInst");
122     if (param_attributes.SaveForAsyncFinish) TRACE(" SaveForAsyncFinish");
123     if (param_attributes.ServerAllocSize) TRACE(" ServerAllocSize = %d", param_attributes.ServerAllocSize * 8);
124 }
125
126 static void dump_INTERPRETER_OPT_FLAGS(INTERPRETER_OPT_FLAGS Oi2Flags)
127 {
128     if (Oi2Flags.ServerMustSize) TRACE(" ServerMustSize");
129     if (Oi2Flags.ClientMustSize) TRACE(" ClientMustSize");
130     if (Oi2Flags.HasReturn) TRACE(" HasReturn");
131     if (Oi2Flags.HasPipes) TRACE(" HasPipes");
132     if (Oi2Flags.Unused) TRACE(" Unused");
133     if (Oi2Flags.HasAsyncUuid) TRACE(" HasAsyncUuid");
134     if (Oi2Flags.HasExtensions) TRACE(" HasExtensions");
135     if (Oi2Flags.HasAsyncHandle) TRACE(" HasAsyncHandle");
136     TRACE("\n");
137 }
138
139 #define ARG_FROM_OFFSET(args, offset) ((args) + (offset))
140
141 static PFORMAT_STRING client_get_handle(
142     PMIDL_STUB_MESSAGE pStubMsg, const NDR_PROC_HEADER *pProcHeader,
143     PFORMAT_STRING pFormat, handle_t *phBinding)
144 {
145     /* binding */
146     switch (pProcHeader->handle_type)
147     {
148     /* explicit binding: parse additional section */
149     case RPC_FC_BIND_EXPLICIT:
150         switch (*pFormat) /* handle_type */
151         {
152         case RPC_FC_BIND_PRIMITIVE: /* explicit primitive */
153             {
154                 const NDR_EHD_PRIMITIVE *pDesc = (const NDR_EHD_PRIMITIVE *)pFormat;
155
156                 TRACE("Explicit primitive handle @ %d\n", pDesc->offset);
157
158                 if (pDesc->flag) /* pointer to binding */
159                     *phBinding = **(handle_t **)ARG_FROM_OFFSET(pStubMsg->StackTop, pDesc->offset);
160                 else
161                     *phBinding = *(handle_t *)ARG_FROM_OFFSET(pStubMsg->StackTop, pDesc->offset);
162                 return pFormat + sizeof(NDR_EHD_PRIMITIVE);
163             }
164         case RPC_FC_BIND_GENERIC: /* explicit generic */
165             {
166                 const NDR_EHD_GENERIC *pDesc = (const NDR_EHD_GENERIC *)pFormat;
167                 void *pObject = NULL;
168                 void *pArg;
169                 const GENERIC_BINDING_ROUTINE_PAIR *pGenPair;
170
171                 TRACE("Explicit generic binding handle #%d\n", pDesc->binding_routine_pair_index);
172
173                 if (pDesc->flag_and_size & HANDLE_PARAM_IS_VIA_PTR)
174                     pArg = *(void **)ARG_FROM_OFFSET(pStubMsg->StackTop, pDesc->offset);
175                 else
176                     pArg = ARG_FROM_OFFSET(pStubMsg->StackTop, pDesc->offset);
177                 memcpy(&pObject, pArg, pDesc->flag_and_size & 0xf);
178                 pGenPair = &pStubMsg->StubDesc->aGenericBindingRoutinePairs[pDesc->binding_routine_pair_index];
179                 *phBinding = pGenPair->pfnBind(pObject);
180                 return pFormat + sizeof(NDR_EHD_GENERIC);
181             }
182         case RPC_FC_BIND_CONTEXT: /* explicit context */
183             {
184                 const NDR_EHD_CONTEXT *pDesc = (const NDR_EHD_CONTEXT *)pFormat;
185                 NDR_CCONTEXT context_handle;
186                 TRACE("Explicit bind context\n");
187                 if (pDesc->flags & HANDLE_PARAM_IS_VIA_PTR)
188                 {
189                     TRACE("\tHANDLE_PARAM_IS_VIA_PTR\n");
190                     context_handle = **(NDR_CCONTEXT **)ARG_FROM_OFFSET(pStubMsg->StackTop, pDesc->offset);
191                 }
192                 else
193                     context_handle = *(NDR_CCONTEXT *)ARG_FROM_OFFSET(pStubMsg->StackTop, pDesc->offset);
194                 if ((pDesc->flags & NDR_CONTEXT_HANDLE_CANNOT_BE_NULL) &&
195                     !context_handle)
196                 {
197                     ERR("null context handle isn't allowed\n");
198                     RpcRaiseException(RPC_X_SS_IN_NULL_CONTEXT);
199                     return NULL;
200                 }
201                 *phBinding = NDRCContextBinding(context_handle);
202                 /* FIXME: should we store this structure in stubMsg.pContext? */
203                 return pFormat + sizeof(NDR_EHD_CONTEXT);
204             }
205         default:
206             ERR("bad explicit binding handle type (0x%02x)\n", pProcHeader->handle_type);
207             RpcRaiseException(RPC_X_BAD_STUB_DATA);
208         }
209         break;
210     case RPC_FC_BIND_GENERIC: /* implicit generic */
211         FIXME("RPC_FC_BIND_GENERIC\n");
212         RpcRaiseException(RPC_X_BAD_STUB_DATA); /* FIXME: remove when implemented */
213         break;
214     case RPC_FC_BIND_PRIMITIVE: /* implicit primitive */
215         TRACE("Implicit primitive handle\n");
216         *phBinding = *pStubMsg->StubDesc->IMPLICIT_HANDLE_INFO.pPrimitiveHandle;
217         break;
218     case RPC_FC_CALLBACK_HANDLE: /* implicit callback */
219         FIXME("RPC_FC_CALLBACK_HANDLE\n");
220         break;
221     case RPC_FC_AUTO_HANDLE: /* implicit auto handle */
222         /* strictly speaking, it isn't necessary to set hBinding here
223          * since it isn't actually used (hence the automatic in its name),
224          * but then why does MIDL generate a valid entry in the
225          * MIDL_STUB_DESC for it? */
226         TRACE("Implicit auto handle\n");
227         *phBinding = *pStubMsg->StubDesc->IMPLICIT_HANDLE_INFO.pAutoHandle;
228         break;
229     default:
230         ERR("bad implicit binding handle type (0x%02x)\n", pProcHeader->handle_type);
231         RpcRaiseException(RPC_X_BAD_STUB_DATA);
232     }
233     return pFormat;
234 }
235
236 static void client_free_handle(
237     PMIDL_STUB_MESSAGE pStubMsg, const NDR_PROC_HEADER *pProcHeader,
238     PFORMAT_STRING pFormat, handle_t hBinding)
239 {
240     /* binding */
241     switch (pProcHeader->handle_type)
242     {
243     /* explicit binding: parse additional section */
244     case RPC_FC_BIND_EXPLICIT:
245         switch (*pFormat) /* handle_type */
246         {
247         case RPC_FC_BIND_GENERIC: /* explicit generic */
248             {
249                 const NDR_EHD_GENERIC *pDesc = (const NDR_EHD_GENERIC *)pFormat;
250                 void *pObject = NULL;
251                 void *pArg;
252                 const GENERIC_BINDING_ROUTINE_PAIR *pGenPair;
253
254                 TRACE("Explicit generic binding handle #%d\n", pDesc->binding_routine_pair_index);
255
256                 if (pDesc->flag_and_size & HANDLE_PARAM_IS_VIA_PTR)
257                     pArg = *(void **)ARG_FROM_OFFSET(pStubMsg->StackTop, pDesc->offset);
258                 else
259                     pArg = ARG_FROM_OFFSET(pStubMsg->StackTop, pDesc->offset);
260                 memcpy(&pObject, pArg, pDesc->flag_and_size & 0xf);
261                 pGenPair = &pStubMsg->StubDesc->aGenericBindingRoutinePairs[pDesc->binding_routine_pair_index];
262                 pGenPair->pfnUnbind(pObject, hBinding);
263                 break;
264             }
265         case RPC_FC_BIND_CONTEXT: /* explicit context */
266         case RPC_FC_BIND_PRIMITIVE: /* explicit primitive */
267             break;
268         default:
269             ERR("bad explicit binding handle type (0x%02x)\n", pProcHeader->handle_type);
270             RpcRaiseException(RPC_X_BAD_STUB_DATA);
271         }
272         break;
273     case RPC_FC_BIND_GENERIC: /* implicit generic */
274         FIXME("RPC_FC_BIND_GENERIC\n");
275         RpcRaiseException(RPC_X_BAD_STUB_DATA); /* FIXME: remove when implemented */
276         break;
277     case RPC_FC_CALLBACK_HANDLE: /* implicit callback */
278     case RPC_FC_BIND_PRIMITIVE: /* implicit primitive */
279     case RPC_FC_AUTO_HANDLE: /* implicit auto handle */
280         break;
281     default:
282         ERR("bad implicit binding handle type (0x%02x)\n", pProcHeader->handle_type);
283         RpcRaiseException(RPC_X_BAD_STUB_DATA);
284     }
285 }
286
287 static void client_do_args(PMIDL_STUB_MESSAGE pStubMsg, PFORMAT_STRING pFormat,
288     int phase, unsigned char *args, unsigned short number_of_params,
289     unsigned char *pRetVal)
290 {
291     /* current format string offset */
292     int current_offset = 0;
293     /* current stack offset */
294     unsigned short current_stack_offset = 0;
295     /* counter */
296     unsigned short i;
297
298     for (i = 0; i < number_of_params; i++)
299     {
300         const NDR_PARAM_OIF_BASETYPE *pParam =
301             (const NDR_PARAM_OIF_BASETYPE *)&pFormat[current_offset];
302         unsigned char * pArg;
303
304         current_stack_offset = pParam->stack_offset;
305         pArg = ARG_FROM_OFFSET(args, current_stack_offset);
306
307         TRACE("param[%d]: new format\n", i);
308         TRACE("\tparam_attributes:"); dump_RPC_FC_PROC_PF(pParam->param_attributes); TRACE("\n");
309         TRACE("\tstack_offset: 0x%x\n", current_stack_offset);
310         TRACE("\tmemory addr (before): %p\n", pArg);
311
312         if (pParam->param_attributes.IsBasetype)
313         {
314             const unsigned char * pTypeFormat =
315                 &pParam->type_format_char;
316
317             if (pParam->param_attributes.IsSimpleRef)
318                 pArg = *(unsigned char **)pArg;
319
320             TRACE("\tbase type: 0x%02x\n", *pTypeFormat);
321
322             switch (phase)
323             {
324             case PROXY_CALCSIZE:
325                 if (pParam->param_attributes.IsIn)
326                     call_buffer_sizer(pStubMsg, pArg, pTypeFormat);
327                 break;
328             case PROXY_MARSHAL:
329                 if (pParam->param_attributes.IsIn)
330                     call_marshaller(pStubMsg, pArg, pTypeFormat);
331                 break;
332             case PROXY_UNMARSHAL:
333                 if (pParam->param_attributes.IsOut)
334                 {
335                     if (pParam->param_attributes.IsReturn)
336                         call_unmarshaller(pStubMsg, &pRetVal, pTypeFormat, 0);
337                     else
338                         call_unmarshaller(pStubMsg, &pArg, pTypeFormat, 0);
339                     TRACE("pRetVal = %p\n", pRetVal);
340                 }
341                 break;
342             default:
343                 RpcRaiseException(RPC_S_INTERNAL_ERROR);
344             }
345
346             current_offset += sizeof(NDR_PARAM_OIF_BASETYPE);
347         }
348         else
349         {
350             const NDR_PARAM_OIF_OTHER *pParamOther =
351                 (const NDR_PARAM_OIF_OTHER *)&pFormat[current_offset];
352
353             const unsigned char * pTypeFormat =
354                 &(pStubMsg->StubDesc->pFormatTypes[pParamOther->type_offset]);
355
356             /* if a simple ref pointer then we have to do the
357              * check for the pointer being non-NULL. */
358             if (pParam->param_attributes.IsSimpleRef)
359             {
360                 if (!*(unsigned char **)pArg)
361                     RpcRaiseException(RPC_X_NULL_REF_POINTER);
362             }
363
364             TRACE("\tcomplex type: 0x%02x\n", *pTypeFormat);
365
366             switch (phase)
367             {
368             case PROXY_CALCSIZE:
369                 if (pParam->param_attributes.IsIn)
370                 {
371                     if (pParam->param_attributes.IsByValue)
372                         call_buffer_sizer(pStubMsg, pArg, pTypeFormat);
373                     else
374                         call_buffer_sizer(pStubMsg, *(unsigned char **)pArg, pTypeFormat);
375                 }
376                 break;
377             case PROXY_MARSHAL:
378                 if (pParam->param_attributes.IsIn)
379                 {
380                     if (pParam->param_attributes.IsByValue)
381                         call_marshaller(pStubMsg, pArg, pTypeFormat);
382                     else
383                         call_marshaller(pStubMsg, *(unsigned char **)pArg, pTypeFormat);
384                 }
385                 break;
386             case PROXY_UNMARSHAL:
387                 if (pParam->param_attributes.IsOut)
388                 {
389                     if (pParam->param_attributes.IsReturn)
390                         call_unmarshaller(pStubMsg, &pRetVal, pTypeFormat, 0);
391                     else if (pParam->param_attributes.IsByValue)
392                         call_unmarshaller(pStubMsg, &pArg, pTypeFormat, 0);
393                     else
394                         call_unmarshaller(pStubMsg, (unsigned char **)pArg, pTypeFormat, 0);
395                 }
396                 break;
397             default:
398                 RpcRaiseException(RPC_S_INTERNAL_ERROR);
399             }
400
401             current_offset += sizeof(NDR_PARAM_OIF_OTHER);
402         }
403         TRACE("\tmemory addr (after): %p\n", pArg);
404     }
405 }
406
407 static unsigned int type_stack_size(unsigned char fc)
408 {
409     switch (fc)
410     {
411     case RPC_FC_BYTE:
412     case RPC_FC_CHAR:
413     case RPC_FC_SMALL:
414     case RPC_FC_USMALL:
415     case RPC_FC_WCHAR:
416     case RPC_FC_SHORT:
417     case RPC_FC_USHORT:
418     case RPC_FC_LONG:
419     case RPC_FC_ULONG:
420     case RPC_FC_INT3264:
421     case RPC_FC_UINT3264:
422     case RPC_FC_ENUM16:
423     case RPC_FC_ENUM32:
424     case RPC_FC_FLOAT:
425     case RPC_FC_ERROR_STATUS_T:
426     case RPC_FC_IGNORE:
427         return sizeof(void *);
428     case RPC_FC_DOUBLE:
429         return sizeof(double);
430     case RPC_FC_HYPER:
431         return sizeof(ULONGLONG);
432     default:
433         ERR("invalid base type 0x%x\n", fc);
434         RpcRaiseException(RPC_S_INTERNAL_ERROR);
435     }
436 }
437
438 static BOOL is_by_value( PFORMAT_STRING format )
439 {
440     switch (*format)
441     {
442     case RPC_FC_USER_MARSHAL:
443     case RPC_FC_STRUCT:
444     case RPC_FC_PSTRUCT:
445     case RPC_FC_CSTRUCT:
446     case RPC_FC_CPSTRUCT:
447     case RPC_FC_CVSTRUCT:
448     case RPC_FC_BOGUS_STRUCT:
449         return TRUE;
450     default:
451         return FALSE;
452     }
453 }
454
455 void client_do_args_old_format(PMIDL_STUB_MESSAGE pStubMsg,
456     PFORMAT_STRING pFormat, int phase, unsigned char *args,
457     unsigned short stack_size,
458     unsigned char *pRetVal, BOOL object_proc, BOOL ignore_retval)
459 {
460     /* current format string offset */
461     int current_offset = 0;
462     /* current stack offset */
463     unsigned short current_stack_offset = object_proc ? sizeof(void *) : 0;
464     /* counter */
465     unsigned short i;
466
467     /* NOTE: V1 style format doesn't terminate on the number_of_params
468      * condition as it doesn't have this attribute. Instead it
469      * terminates when the stack size given in the header is exceeded.
470      */
471     for (i = 0; TRUE; i++)
472     {
473         const NDR_PARAM_OI_BASETYPE *pParam =
474             (const NDR_PARAM_OI_BASETYPE *)&pFormat[current_offset];
475         unsigned char * pArg = ARG_FROM_OFFSET(args, current_stack_offset);
476
477         /* no more parameters; exit loop */
478         if (current_stack_offset >= stack_size)
479             break;
480
481         TRACE("param[%d]: old format\n", i);
482         TRACE("\tparam_direction: 0x%x\n", pParam->param_direction);
483         TRACE("\tstack_offset: 0x%x\n", current_stack_offset);
484         TRACE("\tmemory addr (before): %p\n", pArg);
485
486         if (pParam->param_direction == RPC_FC_IN_PARAM_BASETYPE ||
487             pParam->param_direction == RPC_FC_RETURN_PARAM_BASETYPE)
488         {
489             const unsigned char * pTypeFormat =
490                 &pParam->type_format_char;
491
492             TRACE("\tbase type 0x%02x\n", *pTypeFormat);
493
494             switch (phase)
495             {
496             case PROXY_CALCSIZE:
497                 if (pParam->param_direction == RPC_FC_IN_PARAM_BASETYPE)
498                     call_buffer_sizer(pStubMsg, pArg, pTypeFormat);
499                 break;
500             case PROXY_MARSHAL:
501                 if (pParam->param_direction == RPC_FC_IN_PARAM_BASETYPE)
502                     call_marshaller(pStubMsg, pArg, pTypeFormat);
503                 break;
504             case PROXY_UNMARSHAL:
505                 if (!ignore_retval &&
506                     pParam->param_direction == RPC_FC_RETURN_PARAM_BASETYPE)
507                 {
508                     if (pParam->param_direction & RPC_FC_RETURN_PARAM)
509                         call_unmarshaller(pStubMsg, &pRetVal, pTypeFormat, 0);
510                     else
511                         call_unmarshaller(pStubMsg, &pArg, pTypeFormat, 0);
512                 }
513                 break;
514             default:
515                 RpcRaiseException(RPC_S_INTERNAL_ERROR);
516             }
517
518             current_stack_offset += type_stack_size(*pTypeFormat);
519             current_offset += sizeof(NDR_PARAM_OI_BASETYPE);
520         }
521         else
522         {
523             const NDR_PARAM_OI_OTHER *pParamOther = (const NDR_PARAM_OI_OTHER *)&pFormat[current_offset];
524             const unsigned char *pTypeFormat = &pStubMsg->StubDesc->pFormatTypes[pParamOther->type_offset];
525             const BOOL by_value = is_by_value( pTypeFormat );
526
527             TRACE("\tcomplex type 0x%02x\n", *pTypeFormat);
528
529             switch (phase)
530             {
531             case PROXY_CALCSIZE:
532                 if (pParam->param_direction == RPC_FC_IN_PARAM ||
533                     pParam->param_direction == RPC_FC_IN_OUT_PARAM)
534                 {
535                     if (!by_value) pArg = *(unsigned char **)pArg;
536                     call_buffer_sizer(pStubMsg, pArg, pTypeFormat);
537                 }
538                 break;
539             case PROXY_MARSHAL:
540                 if (pParam->param_direction == RPC_FC_IN_PARAM ||
541                     pParam->param_direction == RPC_FC_IN_OUT_PARAM)
542                 {
543                     if (!by_value) pArg = *(unsigned char **)pArg;
544                     call_marshaller(pStubMsg, pArg, pTypeFormat);
545                 }
546                 break;
547             case PROXY_UNMARSHAL:
548                 if (pParam->param_direction == RPC_FC_IN_OUT_PARAM ||
549                     pParam->param_direction == RPC_FC_OUT_PARAM)
550                 {
551                     if (by_value)
552                         call_unmarshaller(pStubMsg, &pArg, pTypeFormat, 0);
553                     else
554                         call_unmarshaller(pStubMsg, (unsigned char **)pArg, pTypeFormat, 0);
555                 }
556                 else if (pParam->param_direction == RPC_FC_RETURN_PARAM)
557                     call_unmarshaller(pStubMsg, (unsigned char **)pRetVal, pTypeFormat, 0);
558                 break;
559             default:
560                 RpcRaiseException(RPC_S_INTERNAL_ERROR);
561             }
562
563             current_stack_offset += pParamOther->stack_size * sizeof(void *);
564             current_offset += sizeof(NDR_PARAM_OI_OTHER);
565         }
566     }
567 }
568
569 CLIENT_CALL_RETURN WINAPIV NdrClientCall2(PMIDL_STUB_DESC pStubDesc, PFORMAT_STRING pFormat, ...)
570 {
571     /* pointer to start of stack where arguments start */
572     RPC_MESSAGE rpcMsg;
573     MIDL_STUB_MESSAGE stubMsg;
574     handle_t hBinding = NULL;
575     /* procedure number */
576     unsigned short procedure_number;
577     /* size of stack */
578     unsigned short stack_size;
579     /* number of parameters. optional for client to give it to us */
580     unsigned char number_of_params = ~0;
581     /* cache of Oif_flags from v2 procedure header */
582     INTERPRETER_OPT_FLAGS Oif_flags = { 0 };
583     /* cache of extension flags from NDR_PROC_HEADER_EXTS */
584     INTERPRETER_OPT_FLAGS2 ext_flags = { 0 };
585     /* the type of pass we are currently doing */
586     int phase;
587     /* header for procedure string */
588     const NDR_PROC_HEADER * pProcHeader = (const NDR_PROC_HEADER *)&pFormat[0];
589     /* -Oif or -Oicf generated format */
590     BOOL bV2Format = FALSE;
591     /* the value to return to the client from the remote procedure */
592     LONG_PTR RetVal = 0;
593     /* the pointer to the object when in OLE mode */
594     void * This = NULL;
595     PFORMAT_STRING pHandleFormat;
596     /* correlation cache */
597     ULONG_PTR NdrCorrCache[256];
598     __ms_va_list args;
599
600     TRACE("pStubDesc %p, pFormat %p, ...\n", pStubDesc, pFormat);
601
602     TRACE("NDR Version: 0x%x\n", pStubDesc->Version);
603
604     if (pProcHeader->Oi_flags & RPC_FC_PROC_OIF_RPCFLAGS)
605     {
606         const NDR_PROC_HEADER_RPC *pProcHeader = (const NDR_PROC_HEADER_RPC *)&pFormat[0];
607         stack_size = pProcHeader->stack_size;
608         procedure_number = pProcHeader->proc_num;
609         pFormat += sizeof(NDR_PROC_HEADER_RPC);
610     }
611     else
612     {
613         stack_size = pProcHeader->stack_size;
614         procedure_number = pProcHeader->proc_num;
615         pFormat += sizeof(NDR_PROC_HEADER);
616     }
617     TRACE("stack size: 0x%x\n", stack_size);
618     TRACE("proc num: %d\n", procedure_number);
619
620     /* create the full pointer translation tables, if requested */
621     if (pProcHeader->Oi_flags & RPC_FC_PROC_OIF_FULLPTR)
622         stubMsg.FullPtrXlatTables = NdrFullPointerXlatInit(0,XLAT_CLIENT);
623
624     if (pProcHeader->Oi_flags & RPC_FC_PROC_OIF_OBJECT)
625     {
626         /* object is always the first argument */
627         This = **(void *const **)(&pFormat+1);
628         NdrProxyInitialize(This, &rpcMsg, &stubMsg, pStubDesc, procedure_number);
629     }
630     else
631         NdrClientInitializeNew(&rpcMsg, &stubMsg, pStubDesc, procedure_number);
632
633     TRACE("Oi_flags = 0x%02x\n", pProcHeader->Oi_flags);
634     TRACE("MIDL stub version = 0x%x\n", pStubDesc->MIDLVersion);
635
636     /* needed for conformance of top-level objects */
637     __ms_va_start( args, pFormat );
638     stubMsg.StackTop = va_arg( args, unsigned char * );
639     __ms_va_end( args );
640
641     pHandleFormat = pFormat;
642
643     /* we only need a handle if this isn't an object method */
644     if (!(pProcHeader->Oi_flags & RPC_FC_PROC_OIF_OBJECT))
645     {
646         pFormat = client_get_handle(&stubMsg, pProcHeader, pHandleFormat, &hBinding);
647         if (!pFormat) goto done;
648     }
649
650     bV2Format = (pStubDesc->Version >= 0x20000);
651
652     if (bV2Format)
653     {
654         const NDR_PROC_PARTIAL_OIF_HEADER *pOIFHeader =
655             (const NDR_PROC_PARTIAL_OIF_HEADER *)pFormat;
656
657         Oif_flags = pOIFHeader->Oi2Flags;
658         number_of_params = pOIFHeader->number_of_params;
659
660         pFormat += sizeof(NDR_PROC_PARTIAL_OIF_HEADER);
661     }
662
663     TRACE("Oif_flags = "); dump_INTERPRETER_OPT_FLAGS(Oif_flags);
664
665     if (Oif_flags.HasExtensions)
666     {
667         const NDR_PROC_HEADER_EXTS *pExtensions =
668             (const NDR_PROC_HEADER_EXTS *)pFormat;
669         ext_flags = pExtensions->Flags2;
670         pFormat += pExtensions->Size;
671     }
672
673     stubMsg.BufferLength = 0;
674
675     /* store the RPC flags away */
676     if (pProcHeader->Oi_flags & RPC_FC_PROC_OIF_RPCFLAGS)
677         rpcMsg.RpcFlags = ((const NDR_PROC_HEADER_RPC *)pProcHeader)->rpc_flags;
678
679     /* use alternate memory allocation routines */
680     if (pProcHeader->Oi_flags & RPC_FC_PROC_OIF_RPCSSALLOC)
681         NdrRpcSmSetClientToOsf(&stubMsg);
682
683     if (Oif_flags.HasPipes)
684     {
685         FIXME("pipes not supported yet\n");
686         RpcRaiseException(RPC_X_WRONG_STUB_VERSION); /* FIXME: remove when implemented */
687         /* init pipes package */
688         /* NdrPipesInitialize(...) */
689     }
690     if (ext_flags.HasNewCorrDesc)
691     {
692         /* initialize extra correlation package */
693         NdrCorrelationInitialize(&stubMsg, NdrCorrCache, sizeof(NdrCorrCache), 0);
694     }
695
696     /* order of phases:
697      * 1. PROXY_CALCSIZE - calculate the buffer size
698      * 2. PROXY_GETBUFFER - allocate the buffer
699      * 3. PROXY_MARHSAL - marshal [in] params into the buffer
700      * 4. PROXY_SENDRECEIVE - send/receive buffer
701      * 5. PROXY_UNMARHSAL - unmarshal [out] params from buffer
702      */
703     if ((pProcHeader->Oi_flags & RPC_FC_PROC_OIF_OBJECT) ||
704         (pProcHeader->Oi_flags & RPC_FC_PROC_OIF_HAS_COMM_OR_FAULT))
705     {
706         __TRY
707         {
708             for (phase = PROXY_CALCSIZE; phase <= PROXY_UNMARSHAL; phase++)
709             {
710                 TRACE("phase = %d\n", phase);
711                 switch (phase)
712                 {
713                 case PROXY_GETBUFFER:
714                     if (pProcHeader->Oi_flags & RPC_FC_PROC_OIF_OBJECT)
715                     {
716                         /* allocate the buffer */
717                         NdrProxyGetBuffer(This, &stubMsg);
718                     }
719                     else
720                     {
721                         /* allocate the buffer */
722                         if (Oif_flags.HasPipes)
723                             /* NdrGetPipeBuffer(...) */
724                             FIXME("pipes not supported yet\n");
725                         else
726                         {
727                             if (pProcHeader->handle_type == RPC_FC_AUTO_HANDLE)
728 #if 0
729                                 NdrNsGetBuffer(&stubMsg, stubMsg.BufferLength, hBinding);
730 #else
731                                 FIXME("using auto handle - call NdrNsGetBuffer when it gets implemented\n");
732 #endif
733                             else
734                                 NdrGetBuffer(&stubMsg, stubMsg.BufferLength, hBinding);
735                         }
736                     }
737                     break;
738                 case PROXY_SENDRECEIVE:
739                     if (pProcHeader->Oi_flags & RPC_FC_PROC_OIF_OBJECT)
740                     {
741                         /* send the [in] params and receive the [out] and [retval]
742                          * params */
743                         NdrProxySendReceive(This, &stubMsg);
744                     }
745                     else
746                     {
747                         /* send the [in] params and receive the [out] and [retval]
748                          * params */
749                         if (Oif_flags.HasPipes)
750                             /* NdrPipesSendReceive(...) */
751                             FIXME("pipes not supported yet\n");
752                         else
753                         {
754                             if (pProcHeader->handle_type == RPC_FC_AUTO_HANDLE)
755 #if 0
756                                 NdrNsSendReceive(&stubMsg, stubMsg.Buffer, pStubDesc->IMPLICIT_HANDLE_INFO.pAutoHandle);
757 #else
758                                 FIXME("using auto handle - call NdrNsSendReceive when it gets implemented\n");
759 #endif
760                             else
761                                 NdrSendReceive(&stubMsg, stubMsg.Buffer);
762                         }
763                     }
764
765                     /* convert strings, floating point values and endianess into our
766                      * preferred format */
767                     if ((rpcMsg.DataRepresentation & 0x0000FFFFUL) != NDR_LOCAL_DATA_REPRESENTATION)
768                         NdrConvert(&stubMsg, pFormat);
769
770                     break;
771                 case PROXY_CALCSIZE:
772                 case PROXY_MARSHAL:
773                 case PROXY_UNMARSHAL:
774                     if (bV2Format)
775                         client_do_args(&stubMsg, pFormat, phase, stubMsg.StackTop,
776                             number_of_params, (unsigned char *)&RetVal);
777                     else
778                         client_do_args_old_format(&stubMsg, pFormat, phase,
779                             stubMsg.StackTop, stack_size, (unsigned char *)&RetVal,
780                             (pProcHeader->Oi_flags & RPC_FC_PROC_OIF_OBJECT), FALSE);
781                     break;
782                 default:
783                     ERR("shouldn't reach here. phase %d\n", phase);
784                     break;
785                 }
786             }
787         }
788         __EXCEPT_ALL
789         {
790             if (pProcHeader->Oi_flags & RPC_FC_PROC_OIF_OBJECT)
791                 RetVal = NdrProxyErrorHandler(GetExceptionCode());
792             else
793             {
794                 const COMM_FAULT_OFFSETS *comm_fault_offsets = &pStubDesc->CommFaultOffsets[procedure_number];
795                 ULONG *comm_status;
796                 ULONG *fault_status;
797
798                 TRACE("comm_fault_offsets = {0x%hx, 0x%hx}\n", comm_fault_offsets->CommOffset, comm_fault_offsets->FaultOffset);
799
800                 if (comm_fault_offsets->CommOffset == -1)
801                     comm_status = (ULONG *)&RetVal;
802                 else if (comm_fault_offsets->CommOffset >= 0)
803                     comm_status = *(ULONG **)ARG_FROM_OFFSET(stubMsg.StackTop, comm_fault_offsets->CommOffset);
804                 else
805                     comm_status = NULL;
806
807                 if (comm_fault_offsets->FaultOffset == -1)
808                     fault_status = (ULONG *)&RetVal;
809                 else if (comm_fault_offsets->FaultOffset >= 0)
810                     fault_status = *(ULONG **)ARG_FROM_OFFSET(stubMsg.StackTop, comm_fault_offsets->CommOffset);
811                 else
812                     fault_status = NULL;
813
814                 NdrMapCommAndFaultStatus(&stubMsg, comm_status, fault_status,
815                                          GetExceptionCode());
816             }
817         }
818         __ENDTRY
819     }
820     else
821     {
822         /* order of phases:
823          * 1. PROXY_CALCSIZE - calculate the buffer size
824          * 2. PROXY_GETBUFFER - allocate the buffer
825          * 3. PROXY_MARHSAL - marshal [in] params into the buffer
826          * 4. PROXY_SENDRECEIVE - send/receive buffer
827          * 5. PROXY_UNMARHSAL - unmarshal [out] params from buffer
828          */
829         for (phase = PROXY_CALCSIZE; phase <= PROXY_UNMARSHAL; phase++)
830         {
831             TRACE("phase = %d\n", phase);
832             switch (phase)
833             {
834             case PROXY_GETBUFFER:
835                 /* allocate the buffer */
836                 if (Oif_flags.HasPipes)
837                     /* NdrGetPipeBuffer(...) */
838                     FIXME("pipes not supported yet\n");
839                 else
840                 {
841                     if (pProcHeader->handle_type == RPC_FC_AUTO_HANDLE)
842 #if 0
843                         NdrNsGetBuffer(&stubMsg, stubMsg.BufferLength, hBinding);
844 #else
845                         FIXME("using auto handle - call NdrNsGetBuffer when it gets implemented\n");
846 #endif
847                     else
848                         NdrGetBuffer(&stubMsg, stubMsg.BufferLength, hBinding);
849                 }
850                 break;
851             case PROXY_SENDRECEIVE:
852                 /* send the [in] params and receive the [out] and [retval]
853                  * params */
854                 if (Oif_flags.HasPipes)
855                     /* NdrPipesSendReceive(...) */
856                     FIXME("pipes not supported yet\n");
857                 else
858                 {
859                     if (pProcHeader->handle_type == RPC_FC_AUTO_HANDLE)
860 #if 0
861                         NdrNsSendReceive(&stubMsg, stubMsg.Buffer, pStubDesc->IMPLICIT_HANDLE_INFO.pAutoHandle);
862 #else
863                         FIXME("using auto handle - call NdrNsSendReceive when it gets implemented\n");
864 #endif
865                     else
866                         NdrSendReceive(&stubMsg, stubMsg.Buffer);
867                 }
868
869                 /* convert strings, floating point values and endianess into our
870                  * preferred format */
871                 if ((rpcMsg.DataRepresentation & 0x0000FFFFUL) != NDR_LOCAL_DATA_REPRESENTATION)
872                     NdrConvert(&stubMsg, pFormat);
873
874                 break;
875             case PROXY_CALCSIZE:
876             case PROXY_MARSHAL:
877             case PROXY_UNMARSHAL:
878                 if (bV2Format)
879                     client_do_args(&stubMsg, pFormat, phase, stubMsg.StackTop,
880                         number_of_params, (unsigned char *)&RetVal);
881                 else
882                     client_do_args_old_format(&stubMsg, pFormat, phase,
883                         stubMsg.StackTop, stack_size, (unsigned char *)&RetVal,
884                         (pProcHeader->Oi_flags & RPC_FC_PROC_OIF_OBJECT), FALSE);
885                 break;
886             default:
887                 ERR("shouldn't reach here. phase %d\n", phase);
888                 break;
889             }
890         }
891     }
892
893     if (ext_flags.HasNewCorrDesc)
894     {
895         /* free extra correlation package */
896         NdrCorrelationFree(&stubMsg);
897     }
898
899     if (Oif_flags.HasPipes)
900     {
901         /* NdrPipesDone(...) */
902     }
903
904     /* free the full pointer translation tables */
905     if (pProcHeader->Oi_flags & RPC_FC_PROC_OIF_FULLPTR)
906         NdrFullPointerXlatFree(stubMsg.FullPtrXlatTables);
907
908     /* free marshalling buffer */
909     if (pProcHeader->Oi_flags & RPC_FC_PROC_OIF_OBJECT)
910         NdrProxyFreeBuffer(This, &stubMsg);
911     else
912     {
913         NdrFreeBuffer(&stubMsg);
914         client_free_handle(&stubMsg, pProcHeader, pHandleFormat, hBinding);
915     }
916
917 done:
918     TRACE("RetVal = 0x%lx\n", RetVal);
919     return *(CLIENT_CALL_RETURN *)&RetVal;
920 }
921
922 /* Calls a function with the specified arguments, restoring the stack
923  * properly afterwards as we don't know the calling convention of the
924  * function */
925 #if defined __i386__ && defined _MSC_VER
926 __declspec(naked) LONG_PTR __cdecl call_server_func(SERVER_ROUTINE func, unsigned char * args, unsigned int stack_size)
927 {
928     __asm
929     {
930         push ebp
931         push edi            ; Save registers
932         push esi
933         mov ebp, esp
934         mov eax, [ebp+16]   ; Get stack size
935         sub esp, eax        ; Make room in stack for arguments
936         mov edi, esp
937         mov ecx, eax
938         mov esi, [ebp+12]
939         shr ecx, 2
940         cld
941         rep movsd           ; Copy dword blocks
942         call [ebp+8]        ; Call function
943         lea esp, [ebp-8]    ; Restore stack
944         pop esi             ; Restore registers
945         pop edi
946         pop ebp
947         ret
948     }
949 }
950 #elif defined __i386__ && defined __GNUC__
951 LONG_PTR __cdecl call_server_func(SERVER_ROUTINE func, unsigned char * args, unsigned int stack_size);
952 __ASM_GLOBAL_FUNC(call_server_func,
953     "pushl %ebp\n\t"
954     __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
955     __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
956     "movl %esp,%ebp\n\t"
957     __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
958     "pushl %edi\n\t"            /* Save registers */
959     __ASM_CFI(".cfi_rel_offset %edi,-4\n\t")
960     "pushl %esi\n\t"
961     __ASM_CFI(".cfi_rel_offset %esi,-8\n\t")
962     "movl 16(%ebp), %eax\n\t"   /* Get stack size */
963     "subl %eax, %esp\n\t"       /* Make room in stack for arguments */
964     "andl $~15, %esp\n\t"       /* Make sure stack has 16-byte alignment for Mac OS X */
965     "movl %esp, %edi\n\t"
966     "movl %eax, %ecx\n\t"
967     "movl 12(%ebp), %esi\n\t"
968     "shrl $2, %ecx\n\t"         /* divide by 4 */
969     "cld\n\t"
970     "rep; movsl\n\t"            /* Copy dword blocks */
971     "call *8(%ebp)\n\t"         /* Call function */
972     "leal -8(%ebp), %esp\n\t"   /* Restore stack */
973     "popl %esi\n\t"             /* Restore registers */
974     __ASM_CFI(".cfi_same_value %esi\n\t")
975     "popl %edi\n\t"
976     __ASM_CFI(".cfi_same_value %edi\n\t")
977     "popl %ebp\n\t"
978     __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
979     __ASM_CFI(".cfi_same_value %ebp\n\t")
980     "ret" )
981 #else
982 #warning call_server_func not implemented for your architecture
983 LONG_PTR __cdecl call_server_func(SERVER_ROUTINE func, unsigned char * args, unsigned short stack_size)
984 {
985     FIXME("Not implemented for your architecture\n");
986     return 0;
987 }
988 #endif
989
990 static DWORD calc_arg_size(MIDL_STUB_MESSAGE *pStubMsg, PFORMAT_STRING pFormat)
991 {
992     DWORD size;
993     switch(*pFormat)
994     {
995     case RPC_FC_STRUCT:
996         size = *(const WORD*)(pFormat + 2);
997         break;
998     case RPC_FC_BOGUS_STRUCT:
999         size = *(const WORD*)(pFormat + 2);
1000         if(*(const WORD*)(pFormat + 4))
1001             FIXME("Unhandled conformant description\n");
1002         break;
1003     case RPC_FC_CARRAY:
1004         size = *(const WORD*)(pFormat + 2);
1005         ComputeConformance(pStubMsg, NULL, pFormat + 4, 0);
1006         size *= pStubMsg->MaxCount;
1007         break;
1008     case RPC_FC_SMFARRAY:
1009         size = *(const WORD*)(pFormat + 2);
1010         break;
1011     case RPC_FC_LGFARRAY:
1012         size = *(const DWORD*)(pFormat + 2);
1013         break;
1014     case RPC_FC_BOGUS_ARRAY:
1015         pFormat = ComputeConformance(pStubMsg, NULL, pFormat + 4, *(const WORD*)&pFormat[2]);
1016         TRACE("conformance = %ld\n", pStubMsg->MaxCount);
1017         pFormat = ComputeVariance(pStubMsg, NULL, pFormat, pStubMsg->MaxCount);
1018         size = ComplexStructSize(pStubMsg, pFormat);
1019         size *= pStubMsg->MaxCount;
1020         break;
1021     case RPC_FC_C_CSTRING:
1022     case RPC_FC_C_WSTRING:
1023         if (*pFormat == RPC_FC_C_CSTRING)
1024             size = sizeof(CHAR);
1025         else
1026             size = sizeof(WCHAR);
1027         if (pFormat[1] == RPC_FC_STRING_SIZED)
1028             ComputeConformance(pStubMsg, NULL, pFormat + 2, 0);
1029         else
1030             pStubMsg->MaxCount = 0;
1031         size *= pStubMsg->MaxCount;
1032         break;
1033     default:
1034         FIXME("Unhandled type %02x\n", *pFormat);
1035         /* fallthrough */
1036     case RPC_FC_RP:
1037         size = sizeof(void *);
1038         break;
1039     }
1040     return size;
1041 }
1042
1043 static LONG_PTR *stub_do_args(MIDL_STUB_MESSAGE *pStubMsg,
1044                               PFORMAT_STRING pFormat, int phase,
1045                               unsigned char *args,
1046                               unsigned short number_of_params)
1047 {
1048     /* counter */
1049     unsigned short i;
1050     /* current format string offset */
1051     int current_offset = 0;
1052     /* current stack offset */
1053     unsigned short current_stack_offset = 0;
1054     /* location to put retval into */
1055     LONG_PTR *retval_ptr = NULL;
1056
1057     for (i = 0; i < number_of_params; i++)
1058     {
1059         const NDR_PARAM_OIF_BASETYPE *pParam =
1060         (const NDR_PARAM_OIF_BASETYPE *)&pFormat[current_offset];
1061         unsigned char *pArg;
1062
1063         current_stack_offset = pParam->stack_offset;
1064         pArg = args + current_stack_offset;
1065
1066         TRACE("param[%d]: new format\n", i);
1067         TRACE("\tparam_attributes:"); dump_RPC_FC_PROC_PF(pParam->param_attributes); TRACE("\n");
1068         TRACE("\tstack_offset: 0x%x\n", current_stack_offset);
1069         TRACE("\tmemory addr (before): %p -> %p\n", pArg, *(unsigned char **)pArg);
1070
1071         if (pParam->param_attributes.IsBasetype)
1072         {
1073             const unsigned char *pTypeFormat =
1074             &pParam->type_format_char;
1075
1076             TRACE("\tbase type: 0x%02x\n", *pTypeFormat);
1077
1078             /* make a note of the address of the return value parameter for later */
1079             if (pParam->param_attributes.IsReturn)
1080                 retval_ptr = (LONG_PTR *)pArg;
1081
1082             switch (phase)
1083             {
1084                 case STUBLESS_MARSHAL:
1085                     if (pParam->param_attributes.IsOut || pParam->param_attributes.IsReturn)
1086                     {
1087                         if (pParam->param_attributes.IsSimpleRef)
1088                             call_marshaller(pStubMsg, *(unsigned char **)pArg, pTypeFormat);
1089                         else
1090                             call_marshaller(pStubMsg, pArg, pTypeFormat);
1091                     }
1092                     break;
1093                 case STUBLESS_FREE:
1094                     if (pParam->param_attributes.ServerAllocSize)
1095                         HeapFree(GetProcessHeap(), 0, *(void **)pArg);
1096                     break;
1097                 case STUBLESS_INITOUT:
1098                     break;
1099                 case STUBLESS_UNMARSHAL:
1100                     if (pParam->param_attributes.ServerAllocSize)
1101                         *(void **)pArg = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1102                                                    pParam->param_attributes.ServerAllocSize * 8);
1103
1104                     if (pParam->param_attributes.IsIn)
1105                     {
1106                         if (pParam->param_attributes.IsSimpleRef)
1107                             call_unmarshaller(pStubMsg, (unsigned char **)pArg, pTypeFormat, 0);
1108                         else
1109                             call_unmarshaller(pStubMsg, &pArg, pTypeFormat, 0);
1110                     }
1111                     break;
1112                 case STUBLESS_CALCSIZE:
1113                     if (pParam->param_attributes.IsOut || pParam->param_attributes.IsReturn)
1114                     {
1115                         if (pParam->param_attributes.IsSimpleRef)
1116                             call_buffer_sizer(pStubMsg, *(unsigned char **)pArg, pTypeFormat);
1117                         else
1118                             call_buffer_sizer(pStubMsg, pArg, pTypeFormat);
1119                     }
1120                     break;
1121                 default:
1122                     RpcRaiseException(RPC_S_INTERNAL_ERROR);
1123             }
1124
1125             current_offset += sizeof(NDR_PARAM_OIF_BASETYPE);
1126         }
1127         else
1128         {
1129             const NDR_PARAM_OIF_OTHER *pParamOther =
1130             (const NDR_PARAM_OIF_OTHER *)&pFormat[current_offset];
1131
1132             const unsigned char * pTypeFormat =
1133                 &(pStubMsg->StubDesc->pFormatTypes[pParamOther->type_offset]);
1134
1135             TRACE("\tcomplex type 0x%02x\n", *pTypeFormat);
1136
1137             switch (phase)
1138             {
1139                 case STUBLESS_MARSHAL:
1140                     if (pParam->param_attributes.IsOut || pParam->param_attributes.IsReturn)
1141                     {
1142                         if (pParam->param_attributes.IsByValue)
1143                             call_marshaller(pStubMsg, pArg, pTypeFormat);
1144                         else
1145                             call_marshaller(pStubMsg, *(unsigned char **)pArg, pTypeFormat);
1146                     }
1147                     break;
1148                 case STUBLESS_FREE:
1149                     if (pParam->param_attributes.MustFree)
1150                     {
1151                         if (pParam->param_attributes.IsByValue)
1152                             call_freer(pStubMsg, pArg, pTypeFormat);
1153                         else
1154                             call_freer(pStubMsg, *(unsigned char **)pArg, pTypeFormat);
1155                     }
1156
1157                     if (pParam->param_attributes.IsOut &&
1158                         !pParam->param_attributes.IsIn &&
1159                         !pParam->param_attributes.IsByValue &&
1160                         !pParam->param_attributes.ServerAllocSize)
1161                     {
1162                         if (*pTypeFormat != RPC_FC_BIND_CONTEXT)
1163                             pStubMsg->pfnFree(*(void **)pArg);
1164                     }
1165
1166                     if (pParam->param_attributes.ServerAllocSize)
1167                         HeapFree(GetProcessHeap(), 0, *(void **)pArg);
1168                     break;
1169                 case STUBLESS_INITOUT:
1170                     if (!pParam->param_attributes.IsIn &&
1171                              pParam->param_attributes.IsOut &&
1172                              !pParam->param_attributes.ServerAllocSize &&
1173                              !pParam->param_attributes.IsByValue)
1174                     {
1175                         if (*pTypeFormat == RPC_FC_BIND_CONTEXT)
1176                         {
1177                             NDR_SCONTEXT ctxt = NdrContextHandleInitialize(
1178                                 pStubMsg, pTypeFormat);
1179                             *(void **)pArg = NDRSContextValue(ctxt);
1180                         }
1181                         else
1182                         {
1183                             DWORD size = calc_arg_size(pStubMsg, pTypeFormat);
1184
1185                             if(size)
1186                             {
1187                                 *(void **)pArg = NdrAllocate(pStubMsg, size);
1188                                 memset(*(void **)pArg, 0, size);
1189                             }
1190                         }
1191                     }
1192                     break;
1193                 case STUBLESS_UNMARSHAL:
1194                     if (pParam->param_attributes.ServerAllocSize)
1195                         *(void **)pArg = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1196                                                    pParam->param_attributes.ServerAllocSize * 8);
1197
1198                     if (pParam->param_attributes.IsIn)
1199                     {
1200                         if (pParam->param_attributes.IsByValue)
1201                             call_unmarshaller(pStubMsg, &pArg, pTypeFormat, 0);
1202                         else
1203                             call_unmarshaller(pStubMsg, (unsigned char **)pArg, pTypeFormat, 0);
1204                     }
1205                     break;
1206                 case STUBLESS_CALCSIZE:
1207                     if (pParam->param_attributes.IsOut || pParam->param_attributes.IsReturn)
1208                     {
1209                         if (pParam->param_attributes.IsByValue)
1210                             call_buffer_sizer(pStubMsg, pArg, pTypeFormat);
1211                         else
1212                             call_buffer_sizer(pStubMsg, *(unsigned char **)pArg, pTypeFormat);
1213                     }
1214                     break;
1215                 default:
1216                     RpcRaiseException(RPC_S_INTERNAL_ERROR);
1217             }
1218
1219             current_offset += sizeof(NDR_PARAM_OIF_OTHER);
1220         }
1221         TRACE("\tmemory addr (after): %p -> %p\n", pArg, *(unsigned char **)pArg);
1222     }
1223
1224     return retval_ptr;
1225 }
1226
1227 static LONG_PTR *stub_do_old_args(MIDL_STUB_MESSAGE *pStubMsg,
1228                                   PFORMAT_STRING pFormat, int phase,
1229                                   unsigned char *args,
1230                                   unsigned short stack_size, BOOL object)
1231 {
1232     /* counter */
1233     unsigned short i;
1234     /* current format string offset */
1235     int current_offset = 0;
1236     /* current stack offset */
1237     unsigned short current_stack_offset = object ? sizeof(void *) : 0;
1238     /* location to put retval into */
1239     LONG_PTR *retval_ptr = NULL;
1240
1241     for (i = 0; TRUE; i++)
1242     {
1243         const NDR_PARAM_OI_BASETYPE *pParam =
1244         (const NDR_PARAM_OI_BASETYPE *)&pFormat[current_offset];
1245         unsigned char *pArg = args + current_stack_offset;
1246
1247         /* no more parameters; exit loop */
1248         if (current_stack_offset >= stack_size)
1249             break;
1250
1251         TRACE("param[%d]: old format\n", i);
1252         TRACE("\tparam_direction: 0x%x\n", pParam->param_direction);
1253         TRACE("\tstack_offset: 0x%x\n", current_stack_offset);
1254
1255         if (pParam->param_direction == RPC_FC_IN_PARAM_BASETYPE ||
1256             pParam->param_direction == RPC_FC_RETURN_PARAM_BASETYPE)
1257         {
1258             const unsigned char *pTypeFormat =
1259             &pParam->type_format_char;
1260
1261             TRACE("\tbase type 0x%02x\n", *pTypeFormat);
1262
1263             if (pParam->param_direction == RPC_FC_RETURN_PARAM_BASETYPE)
1264                 retval_ptr = (LONG_PTR *)pArg;
1265
1266             switch (phase)
1267             {
1268                 case STUBLESS_MARSHAL:
1269                     if (pParam->param_direction == RPC_FC_RETURN_PARAM_BASETYPE)
1270                         call_marshaller(pStubMsg, pArg, pTypeFormat);
1271                     break;
1272                 case STUBLESS_FREE:
1273                     if (pParam->param_direction == RPC_FC_IN_PARAM_BASETYPE)
1274                         call_freer(pStubMsg, pArg, pTypeFormat);
1275                     break;
1276                 case STUBLESS_INITOUT:
1277                     break;
1278                 case STUBLESS_UNMARSHAL:
1279                     if (pParam->param_direction == RPC_FC_IN_PARAM_BASETYPE)
1280                         call_unmarshaller(pStubMsg, &pArg, pTypeFormat, 0);
1281                     break;
1282                 case STUBLESS_CALCSIZE:
1283                     if (pParam->param_direction == RPC_FC_RETURN_PARAM_BASETYPE)
1284                         call_buffer_sizer(pStubMsg, pArg, pTypeFormat);
1285                     break;
1286                 default:
1287                     RpcRaiseException(RPC_S_INTERNAL_ERROR);
1288             }
1289
1290             current_stack_offset += type_stack_size(*pTypeFormat);
1291             current_offset += sizeof(NDR_PARAM_OI_BASETYPE);
1292         }
1293         else
1294         {
1295             const NDR_PARAM_OI_OTHER *pParamOther =
1296             (const NDR_PARAM_OI_OTHER *)&pFormat[current_offset];
1297
1298             const unsigned char * pTypeFormat =
1299                 &pStubMsg->StubDesc->pFormatTypes[pParamOther->type_offset];
1300             const BOOL by_value = is_by_value( pTypeFormat );
1301
1302             TRACE("\tcomplex type 0x%02x\n", *pTypeFormat);
1303
1304             if (pParam->param_direction == RPC_FC_RETURN_PARAM)
1305                 retval_ptr = (LONG_PTR *)pArg;
1306
1307             switch (phase)
1308             {
1309                 case STUBLESS_MARSHAL:
1310                     if (pParam->param_direction == RPC_FC_OUT_PARAM ||
1311                         pParam->param_direction == RPC_FC_IN_OUT_PARAM ||
1312                         pParam->param_direction == RPC_FC_RETURN_PARAM)
1313                     {
1314                         if (!by_value) pArg = *(unsigned char **)pArg;
1315                         call_marshaller(pStubMsg, pArg, pTypeFormat);
1316                     }
1317                     break;
1318                 case STUBLESS_FREE:
1319                     if (pParam->param_direction == RPC_FC_IN_OUT_PARAM ||
1320                         pParam->param_direction == RPC_FC_IN_PARAM)
1321                     {
1322                         if (!by_value) pArg = *(unsigned char **)pArg;
1323                         call_freer(pStubMsg, pArg, pTypeFormat);
1324                     }
1325                     else if (pParam->param_direction == RPC_FC_OUT_PARAM && !by_value)
1326                         pStubMsg->pfnFree(*(void **)pArg);
1327                     break;
1328                 case STUBLESS_INITOUT:
1329                     if (pParam->param_direction == RPC_FC_OUT_PARAM && !by_value)
1330                     {
1331                         DWORD size = calc_arg_size(pStubMsg, pTypeFormat);
1332
1333                         if(size)
1334                         {
1335                             *(void **)pArg = NdrAllocate(pStubMsg, size);
1336                             memset(*(void **)pArg, 0, size);
1337                         }
1338                     }
1339                     break;
1340                 case STUBLESS_UNMARSHAL:
1341                     if (pParam->param_direction == RPC_FC_IN_OUT_PARAM ||
1342                         pParam->param_direction == RPC_FC_IN_PARAM)
1343                     {
1344                         if (by_value)
1345                             call_unmarshaller(pStubMsg, &pArg, pTypeFormat, 0);
1346                         else
1347                             call_unmarshaller(pStubMsg, (unsigned char **)pArg, pTypeFormat, 0);
1348                     }
1349                     break;
1350                 case STUBLESS_CALCSIZE:
1351                     if (pParam->param_direction == RPC_FC_OUT_PARAM ||
1352                         pParam->param_direction == RPC_FC_IN_OUT_PARAM ||
1353                         pParam->param_direction == RPC_FC_RETURN_PARAM)
1354                     {
1355                         if (!by_value) pArg = *(unsigned char **)pArg;
1356                         call_buffer_sizer(pStubMsg, pArg, pTypeFormat);
1357                     }
1358                     break;
1359                 default:
1360                     RpcRaiseException(RPC_S_INTERNAL_ERROR);
1361             }
1362
1363             current_stack_offset += pParamOther->stack_size * sizeof(void *);
1364             current_offset += sizeof(NDR_PARAM_OI_OTHER);
1365         }
1366     }
1367
1368     return retval_ptr;
1369 }
1370
1371 /***********************************************************************
1372  *            NdrStubCall2 [RPCRT4.@]
1373  *
1374  * Unmarshals [in] parameters, calls either a method in an object or a server
1375  * function, marshals any [out] parameters and frees any allocated data.
1376  *
1377  * NOTES
1378  *  Used by stubless MIDL-generated code.
1379  */
1380 LONG WINAPI NdrStubCall2(
1381     struct IRpcStubBuffer * pThis,
1382     struct IRpcChannelBuffer * pChannel,
1383     PRPC_MESSAGE pRpcMsg,
1384     DWORD * pdwStubPhase)
1385 {
1386     const MIDL_SERVER_INFO *pServerInfo;
1387     const MIDL_STUB_DESC *pStubDesc;
1388     PFORMAT_STRING pFormat;
1389     MIDL_STUB_MESSAGE stubMsg;
1390     /* pointer to start of stack to pass into stub implementation */
1391     unsigned char * args;
1392     /* size of stack */
1393     unsigned short stack_size;
1394     /* number of parameters. optional for client to give it to us */
1395     unsigned char number_of_params = ~0;
1396     /* cache of Oif_flags from v2 procedure header */
1397     INTERPRETER_OPT_FLAGS Oif_flags = { 0 };
1398     /* cache of extension flags from NDR_PROC_HEADER_EXTS */
1399     INTERPRETER_OPT_FLAGS2 ext_flags = { 0 };
1400     /* the type of pass we are currently doing */
1401     int phase;
1402     /* header for procedure string */
1403     const NDR_PROC_HEADER *pProcHeader;
1404     /* offset in format string for start of params */
1405     int parameter_start_offset;
1406     /* current format string offset */
1407     int current_offset;
1408     /* -Oif or -Oicf generated format */
1409     BOOL bV2Format = FALSE;
1410     /* location to put retval into */
1411     LONG_PTR *retval_ptr = NULL;
1412
1413     TRACE("pThis %p, pChannel %p, pRpcMsg %p, pdwStubPhase %p\n", pThis, pChannel, pRpcMsg, pdwStubPhase);
1414
1415     if (pThis)
1416         pServerInfo = CStdStubBuffer_GetServerInfo(pThis);
1417     else
1418         pServerInfo = ((RPC_SERVER_INTERFACE *)pRpcMsg->RpcInterfaceInformation)->InterpreterInfo;
1419
1420     pStubDesc = pServerInfo->pStubDesc;
1421     pFormat = pServerInfo->ProcString + pServerInfo->FmtStringOffset[pRpcMsg->ProcNum];
1422     pProcHeader = (const NDR_PROC_HEADER *)&pFormat[0];
1423
1424     TRACE("NDR Version: 0x%x\n", pStubDesc->Version);
1425
1426     if (pProcHeader->Oi_flags & RPC_FC_PROC_OIF_RPCFLAGS)
1427     {
1428         const NDR_PROC_HEADER_RPC *pProcHeader = (const NDR_PROC_HEADER_RPC *)&pFormat[0];
1429         stack_size = pProcHeader->stack_size;
1430         current_offset = sizeof(NDR_PROC_HEADER_RPC);
1431
1432     }
1433     else
1434     {
1435         stack_size = pProcHeader->stack_size;
1436         current_offset = sizeof(NDR_PROC_HEADER);
1437     }
1438
1439     TRACE("Oi_flags = 0x%02x\n", pProcHeader->Oi_flags);
1440
1441     /* binding */
1442     switch (pProcHeader->handle_type)
1443     {
1444     /* explicit binding: parse additional section */
1445     case RPC_FC_BIND_EXPLICIT:
1446         switch (pFormat[current_offset]) /* handle_type */
1447         {
1448         case RPC_FC_BIND_PRIMITIVE: /* explicit primitive */
1449             current_offset += sizeof(NDR_EHD_PRIMITIVE);
1450             break;
1451         case RPC_FC_BIND_GENERIC: /* explicit generic */
1452             current_offset += sizeof(NDR_EHD_GENERIC);
1453             break;
1454         case RPC_FC_BIND_CONTEXT: /* explicit context */
1455             current_offset += sizeof(NDR_EHD_CONTEXT);
1456             break;
1457         default:
1458             ERR("bad explicit binding handle type (0x%02x)\n", pProcHeader->handle_type);
1459             RpcRaiseException(RPC_X_BAD_STUB_DATA);
1460         }
1461         break;
1462     case RPC_FC_BIND_GENERIC: /* implicit generic */
1463     case RPC_FC_BIND_PRIMITIVE: /* implicit primitive */
1464     case RPC_FC_CALLBACK_HANDLE: /* implicit callback */
1465     case RPC_FC_AUTO_HANDLE: /* implicit auto handle */
1466         break;
1467     default:
1468         ERR("bad implicit binding handle type (0x%02x)\n", pProcHeader->handle_type);
1469         RpcRaiseException(RPC_X_BAD_STUB_DATA);
1470     }
1471
1472     bV2Format = (pStubDesc->Version >= 0x20000);
1473
1474     if (bV2Format)
1475     {
1476         const NDR_PROC_PARTIAL_OIF_HEADER *pOIFHeader =
1477             (const NDR_PROC_PARTIAL_OIF_HEADER *)&pFormat[current_offset];
1478
1479         Oif_flags = pOIFHeader->Oi2Flags;
1480         number_of_params = pOIFHeader->number_of_params;
1481
1482         current_offset += sizeof(NDR_PROC_PARTIAL_OIF_HEADER);
1483     }
1484
1485     TRACE("Oif_flags = "); dump_INTERPRETER_OPT_FLAGS(Oif_flags);
1486
1487     if (Oif_flags.HasExtensions)
1488     {
1489         const NDR_PROC_HEADER_EXTS *pExtensions =
1490             (const NDR_PROC_HEADER_EXTS *)&pFormat[current_offset];
1491         ext_flags = pExtensions->Flags2;
1492         current_offset += pExtensions->Size;
1493     }
1494
1495     if (pProcHeader->Oi_flags & RPC_FC_PROC_OIF_OBJECT)
1496         NdrStubInitialize(pRpcMsg, &stubMsg, pStubDesc, pChannel);
1497     else
1498         NdrServerInitializeNew(pRpcMsg, &stubMsg, pStubDesc);
1499
1500     /* create the full pointer translation tables, if requested */
1501     if (pProcHeader->Oi_flags & RPC_FC_PROC_OIF_FULLPTR)
1502         stubMsg.FullPtrXlatTables = NdrFullPointerXlatInit(0,XLAT_SERVER);
1503
1504     /* store the RPC flags away */
1505     if (pProcHeader->Oi_flags & RPC_FC_PROC_OIF_RPCFLAGS)
1506         pRpcMsg->RpcFlags = ((const NDR_PROC_HEADER_RPC *)pProcHeader)->rpc_flags;
1507
1508     /* use alternate memory allocation routines */
1509     if (pProcHeader->Oi_flags & RPC_FC_PROC_OIF_RPCSSALLOC)
1510 #if 0
1511           NdrRpcSsEnableAllocate(&stubMsg);
1512 #else
1513           FIXME("Set RPCSS memory allocation routines\n");
1514 #endif
1515
1516     if (Oif_flags.HasPipes)
1517     {
1518         FIXME("pipes not supported yet\n");
1519         RpcRaiseException(RPC_X_WRONG_STUB_VERSION); /* FIXME: remove when implemented */
1520         /* init pipes package */
1521         /* NdrPipesInitialize(...) */
1522     }
1523     if (ext_flags.HasNewCorrDesc)
1524     {
1525         /* initialize extra correlation package */
1526         FIXME("new correlation description not implemented\n");
1527         stubMsg.fHasNewCorrDesc = TRUE;
1528     }
1529
1530     /* convert strings, floating point values and endianess into our
1531      * preferred format */
1532     if ((pRpcMsg->DataRepresentation & 0x0000FFFFUL) != NDR_LOCAL_DATA_REPRESENTATION)
1533         NdrConvert(&stubMsg, pFormat);
1534
1535     parameter_start_offset = current_offset;
1536
1537     TRACE("allocating memory for stack of size %x\n", stack_size);
1538
1539     args = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, stack_size);
1540     stubMsg.StackTop = args; /* used by conformance of top-level objects */
1541
1542     /* add the implicit This pointer as the first arg to the function if we
1543      * are calling an object method */
1544     if (pThis)
1545         *(void **)args = ((CStdStubBuffer *)pThis)->pvServerObject;
1546
1547     for (phase = STUBLESS_UNMARSHAL; phase <= STUBLESS_FREE; phase++)
1548     {
1549         TRACE("phase = %d\n", phase);
1550         switch (phase)
1551         {
1552         case STUBLESS_CALLSERVER:
1553             /* call the server function */
1554             if (pServerInfo->ThunkTable && pServerInfo->ThunkTable[pRpcMsg->ProcNum])
1555                 pServerInfo->ThunkTable[pRpcMsg->ProcNum](&stubMsg);
1556             else
1557             {
1558                 SERVER_ROUTINE func;
1559                 LONG_PTR retval;
1560
1561                 if (pProcHeader->Oi_flags & RPC_FC_PROC_OIF_OBJECT)
1562                 {
1563                     SERVER_ROUTINE *vtbl = *(SERVER_ROUTINE **)((CStdStubBuffer *)pThis)->pvServerObject;
1564                     func = vtbl[pRpcMsg->ProcNum];
1565                 }
1566                 else
1567                     func = pServerInfo->DispatchTable[pRpcMsg->ProcNum];
1568
1569                 /* FIXME: what happens with return values that don't fit into a single register on x86? */
1570                 retval = call_server_func(func, args, stack_size);
1571
1572                 if (retval_ptr)
1573                 {
1574                     TRACE("stub implementation returned 0x%lx\n", retval);
1575                     *retval_ptr = retval;
1576                 }
1577                 else
1578                     TRACE("void stub implementation\n");
1579             }
1580
1581             stubMsg.Buffer = NULL;
1582             stubMsg.BufferLength = 0;
1583
1584             break;
1585         case STUBLESS_GETBUFFER:
1586             if (pProcHeader->Oi_flags & RPC_FC_PROC_OIF_OBJECT)
1587                 NdrStubGetBuffer(pThis, pChannel, &stubMsg);
1588             else
1589             {
1590                 RPC_STATUS Status;
1591
1592                 pRpcMsg->BufferLength = stubMsg.BufferLength;
1593                 /* allocate buffer for [out] and [ret] params */
1594                 Status = I_RpcGetBuffer(pRpcMsg); 
1595                 if (Status)
1596                     RpcRaiseException(Status);
1597                 stubMsg.Buffer = pRpcMsg->Buffer;
1598             }
1599             break;
1600         case STUBLESS_UNMARSHAL:
1601         case STUBLESS_INITOUT:
1602         case STUBLESS_CALCSIZE:
1603         case STUBLESS_MARSHAL:
1604         case STUBLESS_FREE:
1605             if (bV2Format)
1606                 retval_ptr = stub_do_args(&stubMsg, &pFormat[parameter_start_offset],
1607                                           phase, args, number_of_params);
1608             else
1609                 retval_ptr = stub_do_old_args(&stubMsg, &pFormat[parameter_start_offset],
1610                                               phase, args, stack_size,
1611                                               (pProcHeader->Oi_flags & RPC_FC_PROC_OIF_OBJECT));
1612
1613             break;
1614         default:
1615             ERR("shouldn't reach here. phase %d\n", phase);
1616             break;
1617         }
1618     }
1619
1620     pRpcMsg->BufferLength = (unsigned int)(stubMsg.Buffer - (unsigned char *)pRpcMsg->Buffer);
1621
1622     if (ext_flags.HasNewCorrDesc)
1623     {
1624         /* free extra correlation package */
1625         /* NdrCorrelationFree(&stubMsg); */
1626     }
1627
1628     if (Oif_flags.HasPipes)
1629     {
1630         /* NdrPipesDone(...) */
1631     }
1632
1633     /* free the full pointer translation tables */
1634     if (pProcHeader->Oi_flags & RPC_FC_PROC_OIF_FULLPTR)
1635         NdrFullPointerXlatFree(stubMsg.FullPtrXlatTables);
1636
1637     /* free server function stack */
1638     HeapFree(GetProcessHeap(), 0, args);
1639
1640     return S_OK;
1641 }
1642
1643 /***********************************************************************
1644  *            NdrServerCall2 [RPCRT4.@]
1645  */
1646 void WINAPI NdrServerCall2(PRPC_MESSAGE pRpcMsg)
1647 {
1648     DWORD dwPhase;
1649     NdrStubCall2(NULL, NULL, pRpcMsg, &dwPhase);
1650 }
1651
1652 /***********************************************************************
1653  *            NdrClientCall [RPCRT4.@]
1654  */
1655 CLIENT_CALL_RETURN WINAPIV NdrClientCall( PMIDL_STUB_DESC desc, PFORMAT_STRING format, ... )
1656 {
1657     __ms_va_list args;
1658     CLIENT_CALL_RETURN ret;
1659
1660     __ms_va_start( args, format );
1661     ret = NdrClientCall2( desc, format, va_arg( args, unsigned char * ));
1662     __ms_va_end( args );
1663     return ret;
1664 }
1665
1666 /***********************************************************************
1667  *            NdrStubCall [RPCRT4.@]
1668  */
1669 LONG WINAPI NdrStubCall( struct IRpcStubBuffer *This, struct IRpcChannelBuffer *channel,
1670                          PRPC_MESSAGE msg, DWORD *phase )
1671 {
1672     return NdrStubCall2( This, channel, msg, phase );
1673 }
1674
1675 /***********************************************************************
1676  *            NdrServerCall [RPCRT4.@]
1677  */
1678 void WINAPI NdrServerCall( PRPC_MESSAGE msg )
1679 {
1680     DWORD phase;
1681     NdrStubCall( NULL, NULL, msg, &phase );
1682 }
1683
1684 struct async_call_data
1685 {
1686     MIDL_STUB_MESSAGE *pStubMsg;
1687     const NDR_PROC_HEADER *pProcHeader;
1688     PFORMAT_STRING pHandleFormat;
1689     PFORMAT_STRING pParamFormat;
1690     RPC_BINDING_HANDLE hBinding;
1691     /* size of stack */
1692     unsigned short stack_size;
1693     /* number of parameters. optional for client to give it to us */
1694     unsigned char number_of_params;
1695     /* correlation cache */
1696     ULONG_PTR NdrCorrCache[256];
1697 };
1698
1699 CLIENT_CALL_RETURN WINAPIV NdrAsyncClientCall(PMIDL_STUB_DESC pStubDesc,
1700   PFORMAT_STRING pFormat, ...)
1701 {
1702     /* pointer to start of stack where arguments start */
1703     PRPC_MESSAGE pRpcMsg;
1704     PMIDL_STUB_MESSAGE pStubMsg;
1705     RPC_ASYNC_STATE *pAsync;
1706     struct async_call_data *async_call_data;
1707     /* procedure number */
1708     unsigned short procedure_number;
1709     /* cache of Oif_flags from v2 procedure header */
1710     INTERPRETER_OPT_FLAGS Oif_flags = { 0 };
1711     /* cache of extension flags from NDR_PROC_HEADER_EXTS */
1712     INTERPRETER_OPT_FLAGS2 ext_flags = { 0 };
1713     /* the type of pass we are currently doing */
1714     int phase;
1715     /* header for procedure string */
1716     const NDR_PROC_HEADER * pProcHeader = (const NDR_PROC_HEADER *)&pFormat[0];
1717     /* -Oif or -Oicf generated format */
1718     BOOL bV2Format = FALSE;
1719     LONG_PTR RetVal;
1720     __ms_va_list args;
1721
1722     TRACE("pStubDesc %p, pFormat %p, ...\n", pStubDesc, pFormat);
1723
1724     /* Later NDR language versions probably won't be backwards compatible */
1725     if (pStubDesc->Version > 0x50002)
1726     {
1727         FIXME("Incompatible stub description version: 0x%x\n", pStubDesc->Version);
1728         RpcRaiseException(RPC_X_WRONG_STUB_VERSION);
1729     }
1730
1731     async_call_data = I_RpcAllocate(sizeof(*async_call_data) + sizeof(MIDL_STUB_MESSAGE) + sizeof(RPC_MESSAGE));
1732     if (!async_call_data) RpcRaiseException(ERROR_OUTOFMEMORY);
1733     async_call_data->number_of_params = ~0;
1734     async_call_data->pProcHeader = pProcHeader;
1735
1736     async_call_data->pStubMsg = pStubMsg = (PMIDL_STUB_MESSAGE)(async_call_data + 1);
1737     pRpcMsg = (PRPC_MESSAGE)(pStubMsg + 1);
1738
1739     if (pProcHeader->Oi_flags & RPC_FC_PROC_OIF_RPCFLAGS)
1740     {
1741         const NDR_PROC_HEADER_RPC *pProcHeader = (const NDR_PROC_HEADER_RPC *)&pFormat[0];
1742         async_call_data->stack_size = pProcHeader->stack_size;
1743         procedure_number = pProcHeader->proc_num;
1744         pFormat += sizeof(NDR_PROC_HEADER_RPC);
1745     }
1746     else
1747     {
1748         async_call_data->stack_size = pProcHeader->stack_size;
1749         procedure_number = pProcHeader->proc_num;
1750         pFormat += sizeof(NDR_PROC_HEADER);
1751     }
1752     TRACE("stack size: 0x%x\n", async_call_data->stack_size);
1753     TRACE("proc num: %d\n", procedure_number);
1754
1755     /* create the full pointer translation tables, if requested */
1756     if (pProcHeader->Oi_flags & RPC_FC_PROC_OIF_FULLPTR)
1757         pStubMsg->FullPtrXlatTables = NdrFullPointerXlatInit(0,XLAT_CLIENT);
1758
1759     if (pProcHeader->Oi_flags & RPC_FC_PROC_OIF_OBJECT)
1760     {
1761         ERR("objects not supported\n");
1762         I_RpcFree(async_call_data);
1763         RpcRaiseException(RPC_X_BAD_STUB_DATA);
1764     }
1765
1766     NdrClientInitializeNew(pRpcMsg, pStubMsg, pStubDesc, procedure_number);
1767
1768     TRACE("Oi_flags = 0x%02x\n", pProcHeader->Oi_flags);
1769     TRACE("MIDL stub version = 0x%x\n", pStubDesc->MIDLVersion);
1770
1771     /* needed for conformance of top-level objects */
1772     pStubMsg->StackTop = I_RpcAllocate(async_call_data->stack_size);
1773     __ms_va_start( args, pFormat );
1774     memcpy(pStubMsg->StackTop, va_arg( args, unsigned char * ), async_call_data->stack_size);
1775     __ms_va_end( args );
1776
1777     pAsync = *(RPC_ASYNC_STATE **)pStubMsg->StackTop;
1778     pAsync->StubInfo = async_call_data;
1779     async_call_data->pHandleFormat = pFormat;
1780
1781     pFormat = client_get_handle(pStubMsg, pProcHeader, async_call_data->pHandleFormat, &async_call_data->hBinding);
1782     if (!pFormat) goto done;
1783
1784     bV2Format = (pStubDesc->Version >= 0x20000);
1785
1786     if (bV2Format)
1787     {
1788         const NDR_PROC_PARTIAL_OIF_HEADER *pOIFHeader =
1789             (const NDR_PROC_PARTIAL_OIF_HEADER *)pFormat;
1790
1791         Oif_flags = pOIFHeader->Oi2Flags;
1792         async_call_data->number_of_params = pOIFHeader->number_of_params;
1793
1794         pFormat += sizeof(NDR_PROC_PARTIAL_OIF_HEADER);
1795     }
1796
1797     TRACE("Oif_flags = "); dump_INTERPRETER_OPT_FLAGS(Oif_flags);
1798
1799     if (Oif_flags.HasExtensions)
1800     {
1801         const NDR_PROC_HEADER_EXTS *pExtensions =
1802             (const NDR_PROC_HEADER_EXTS *)pFormat;
1803         ext_flags = pExtensions->Flags2;
1804         pFormat += pExtensions->Size;
1805     }
1806
1807     async_call_data->pParamFormat = pFormat;
1808
1809     pStubMsg->BufferLength = 0;
1810
1811     /* store the RPC flags away */
1812     if (pProcHeader->Oi_flags & RPC_FC_PROC_OIF_RPCFLAGS)
1813         pRpcMsg->RpcFlags = ((const NDR_PROC_HEADER_RPC *)pProcHeader)->rpc_flags;
1814
1815     /* use alternate memory allocation routines */
1816     if (pProcHeader->Oi_flags & RPC_FC_PROC_OIF_RPCSSALLOC)
1817         NdrRpcSmSetClientToOsf(pStubMsg);
1818
1819     if (Oif_flags.HasPipes)
1820     {
1821         FIXME("pipes not supported yet\n");
1822         RpcRaiseException(RPC_X_WRONG_STUB_VERSION); /* FIXME: remove when implemented */
1823         /* init pipes package */
1824         /* NdrPipesInitialize(...) */
1825     }
1826     if (ext_flags.HasNewCorrDesc)
1827     {
1828         /* initialize extra correlation package */
1829         NdrCorrelationInitialize(pStubMsg, async_call_data->NdrCorrCache, sizeof(async_call_data->NdrCorrCache), 0);
1830     }
1831
1832     /* order of phases:
1833      * 1. PROXY_CALCSIZE - calculate the buffer size
1834      * 2. PROXY_GETBUFFER - allocate the buffer
1835      * 3. PROXY_MARHSAL - marshal [in] params into the buffer
1836      * 4. PROXY_SENDRECEIVE - send buffer
1837      * Then in NdrpCompleteAsyncClientCall:
1838      * 1. PROXY_SENDRECEIVE - receive buffer
1839      * 2. PROXY_UNMARHSAL - unmarshal [out] params from buffer
1840      */
1841     for (phase = PROXY_CALCSIZE; phase <= PROXY_SENDRECEIVE; phase++)
1842     {
1843         RPC_STATUS status;
1844         TRACE("phase = %d\n", phase);
1845         switch (phase)
1846         {
1847         case PROXY_GETBUFFER:
1848             /* allocate the buffer */
1849             if (Oif_flags.HasPipes)
1850                 /* NdrGetPipeBuffer(...) */
1851                 FIXME("pipes not supported yet\n");
1852             else
1853             {
1854                 if (pProcHeader->handle_type == RPC_FC_AUTO_HANDLE)
1855 #if 0
1856                     NdrNsGetBuffer(pStubMsg, pStubMsg->BufferLength, async_call_data->hBinding);
1857 #else
1858                     FIXME("using auto handle - call NdrNsGetBuffer when it gets implemented\n");
1859 #endif
1860                 else
1861                     NdrGetBuffer(pStubMsg, pStubMsg->BufferLength, async_call_data->hBinding);
1862             }
1863             pRpcMsg->RpcFlags |= RPC_BUFFER_ASYNC;
1864             status = I_RpcAsyncSetHandle(pRpcMsg, pAsync);
1865             if (status != RPC_S_OK)
1866                 RpcRaiseException(status);
1867             break;
1868         case PROXY_SENDRECEIVE:
1869             pRpcMsg->RpcFlags |= RPC_BUFFER_ASYNC;
1870             /* send the [in] params only */
1871             if (Oif_flags.HasPipes)
1872                 /* NdrPipesSend(...) */
1873                 FIXME("pipes not supported yet\n");
1874             else
1875             {
1876                 if (pProcHeader->handle_type == RPC_FC_AUTO_HANDLE)
1877 #if 0
1878                     NdrNsSend(&stubMsg, stubMsg.Buffer, pStubDesc->IMPLICIT_HANDLE_INFO.pAutoHandle);
1879 #else
1880                     FIXME("using auto handle - call NdrNsSend when it gets implemented\n");
1881 #endif
1882                 else
1883                 {
1884                     pStubMsg->RpcMsg->BufferLength = pStubMsg->Buffer - (unsigned char *)pStubMsg->RpcMsg->Buffer;
1885                     status = I_RpcSend(pStubMsg->RpcMsg);
1886                     if (status != RPC_S_OK)
1887                         RpcRaiseException(status);
1888                 }
1889             }
1890
1891             break;
1892         case PROXY_CALCSIZE:
1893         case PROXY_MARSHAL:
1894             if (bV2Format)
1895                 client_do_args(pStubMsg, pFormat, phase, pStubMsg->StackTop,
1896                     async_call_data->number_of_params, NULL);
1897             else
1898                 client_do_args_old_format(pStubMsg, pFormat, phase,
1899                     pStubMsg->StackTop, async_call_data->stack_size, NULL,
1900                     (pProcHeader->Oi_flags & RPC_FC_PROC_OIF_OBJECT), FALSE);
1901             break;
1902         default:
1903             ERR("shouldn't reach here. phase %d\n", phase);
1904             break;
1905         }
1906     }
1907
1908 done:
1909     TRACE("returning 0\n");
1910     RetVal = 0;
1911     return *(CLIENT_CALL_RETURN *)&RetVal;
1912 }
1913
1914 RPC_STATUS NdrpCompleteAsyncClientCall(RPC_ASYNC_STATE *pAsync, void *Reply)
1915 {
1916     /* pointer to start of stack where arguments start */
1917     PMIDL_STUB_MESSAGE pStubMsg;
1918     struct async_call_data *async_call_data;
1919     /* the type of pass we are currently doing */
1920     int phase;
1921     /* header for procedure string */
1922     const NDR_PROC_HEADER * pProcHeader;
1923     /* -Oif or -Oicf generated format */
1924     BOOL bV2Format;
1925     RPC_STATUS status = RPC_S_OK;
1926
1927     if (!pAsync->StubInfo)
1928         return RPC_S_INVALID_ASYNC_HANDLE;
1929
1930     async_call_data = pAsync->StubInfo;
1931     pStubMsg = async_call_data->pStubMsg;
1932     pProcHeader = async_call_data->pProcHeader;
1933
1934     bV2Format = (pStubMsg->StubDesc->Version >= 0x20000);
1935
1936     /* order of phases:
1937      * 1. PROXY_CALCSIZE - calculate the buffer size
1938      * 2. PROXY_GETBUFFER - allocate the buffer
1939      * 3. PROXY_MARHSAL - marshal [in] params into the buffer
1940      * 4. PROXY_SENDRECEIVE - send buffer
1941      * Then in NdrpCompleteAsyncClientCall:
1942      * 1. PROXY_SENDRECEIVE - receive buffer
1943      * 2. PROXY_UNMARHSAL - unmarshal [out] params from buffer
1944      */
1945     for (phase = PROXY_SENDRECEIVE; phase <= PROXY_UNMARSHAL; phase++)
1946     {
1947         switch (phase)
1948         {
1949         case PROXY_SENDRECEIVE:
1950             pStubMsg->RpcMsg->RpcFlags |= RPC_BUFFER_ASYNC;
1951             /* receive the [out] params */
1952             if (pProcHeader->handle_type == RPC_FC_AUTO_HANDLE)
1953 #if 0
1954                 NdrNsReceive(&stubMsg, stubMsg.Buffer, pStubDesc->IMPLICIT_HANDLE_INFO.pAutoHandle);
1955 #else
1956                 FIXME("using auto handle - call NdrNsReceive when it gets implemented\n");
1957 #endif
1958             else
1959             {
1960                 status = I_RpcReceive(pStubMsg->RpcMsg);
1961                 if (status != RPC_S_OK)
1962                     goto cleanup;
1963                 pStubMsg->BufferLength = pStubMsg->RpcMsg->BufferLength;
1964                 pStubMsg->BufferStart = pStubMsg->RpcMsg->Buffer;
1965                 pStubMsg->BufferEnd = pStubMsg->BufferStart + pStubMsg->BufferLength;
1966                 pStubMsg->Buffer = pStubMsg->BufferStart;
1967             }
1968
1969             /* convert strings, floating point values and endianess into our
1970              * preferred format */
1971 #if 0
1972             if ((pStubMsg->RpcMsg.DataRepresentation & 0x0000FFFFUL) != NDR_LOCAL_DATA_REPRESENTATION)
1973                 NdrConvert(pStubMsg, pFormat);
1974 #endif
1975
1976             break;
1977         case PROXY_UNMARSHAL:
1978             if (bV2Format)
1979                 client_do_args(pStubMsg, async_call_data->pParamFormat, phase, pStubMsg->StackTop,
1980                     async_call_data->number_of_params, Reply);
1981             else
1982                 client_do_args_old_format(pStubMsg, async_call_data->pParamFormat, phase,
1983                     pStubMsg->StackTop, async_call_data->stack_size, Reply, FALSE, FALSE);
1984             break;
1985         default:
1986             ERR("shouldn't reach here. phase %d\n", phase);
1987             break;
1988         }
1989     }
1990
1991 cleanup:
1992     if (pStubMsg->fHasNewCorrDesc)
1993     {
1994         /* free extra correlation package */
1995         NdrCorrelationFree(pStubMsg);
1996     }
1997
1998     /* free the full pointer translation tables */
1999     if (pProcHeader->Oi_flags & RPC_FC_PROC_OIF_FULLPTR)
2000         NdrFullPointerXlatFree(pStubMsg->FullPtrXlatTables);
2001
2002     /* free marshalling buffer */
2003     NdrFreeBuffer(pStubMsg);
2004     client_free_handle(pStubMsg, pProcHeader, async_call_data->pHandleFormat, async_call_data->hBinding);
2005
2006     I_RpcFree(pStubMsg->StackTop);
2007     I_RpcFree(async_call_data);
2008
2009     TRACE("-- 0x%x\n", status);
2010     return status;
2011 }
2012
2013 RPCRTAPI LONG RPC_ENTRY NdrAsyncStubCall(struct IRpcStubBuffer* pThis,
2014     struct IRpcChannelBuffer* pChannel, PRPC_MESSAGE pRpcMsg,
2015     DWORD * pdwStubPhase)
2016 {
2017     FIXME("unimplemented, expect crash!\n");
2018     return 0;
2019 }