widl: Generate a registration script along with the typelib when creating a resource...
[wine] / tools / widl / typegen.c
1 /*
2  * Format String Generator for IDL Compiler
3  *
4  * Copyright 2005-2006 Eric Kohl
5  * Copyright 2005-2006 Robert Shearman
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
22 #include "config.h"
23 #include "wine/port.h"
24
25 #include <stdio.h>
26 #include <stdlib.h>
27 #ifdef HAVE_UNISTD_H
28 # include <unistd.h>
29 #endif
30 #include <string.h>
31 #include <assert.h>
32 #include <ctype.h>
33 #include <limits.h>
34
35 #include "widl.h"
36 #include "utils.h"
37 #include "parser.h"
38 #include "header.h"
39 #include "typetree.h"
40
41 #include "typegen.h"
42 #include "expr.h"
43
44 /* round size up to multiple of alignment */
45 #define ROUND_SIZE(size, alignment) (((size) + ((alignment) - 1)) & ~((alignment) - 1))
46 /* value to add on to round size up to a multiple of alignment */
47 #define ROUNDING(size, alignment) (((alignment) - 1) - (((size) + ((alignment) - 1)) & ((alignment) - 1)))
48
49 static const type_t *current_structure;
50 static const var_t *current_func;
51 static const type_t *current_iface;
52
53 static struct list expr_eval_routines = LIST_INIT(expr_eval_routines);
54 struct expr_eval_routine
55 {
56     struct list   entry;
57     const type_t *iface;
58     const type_t *cont_type;
59     char         *name;
60     unsigned int  baseoff;
61     const expr_t *expr;
62 };
63
64 enum type_context
65 {
66     TYPE_CONTEXT_TOPLEVELPARAM,
67     TYPE_CONTEXT_PARAM,
68     TYPE_CONTEXT_CONTAINER,
69     TYPE_CONTEXT_CONTAINER_NO_POINTERS,
70 };
71
72 /* parameter flags in Oif mode */
73 static const unsigned short MustSize = 0x0001;
74 static const unsigned short MustFree = 0x0002;
75 static const unsigned short IsPipe = 0x0004;
76 static const unsigned short IsIn = 0x0008;
77 static const unsigned short IsOut = 0x0010;
78 static const unsigned short IsReturn = 0x0020;
79 static const unsigned short IsBasetype = 0x0040;
80 static const unsigned short IsByValue = 0x0080;
81 static const unsigned short IsSimpleRef = 0x0100;
82 /* static const unsigned short IsDontCallFreeInst = 0x0200; */
83 /* static const unsigned short SaveForAsyncFinish = 0x0400; */
84
85 static unsigned int field_memsize(const type_t *type, unsigned int *offset);
86 static unsigned int fields_memsize(const var_list_t *fields, unsigned int *align);
87 static unsigned int type_memsize_and_alignment(const type_t *t, unsigned int *align);
88 static unsigned int write_struct_tfs(FILE *file, type_t *type, const char *name, unsigned int *tfsoff);
89 static int write_embedded_types(FILE *file, const attr_list_t *attrs, type_t *type,
90                                 const char *name, int write_ptr, unsigned int *tfsoff);
91 static const var_t *find_array_or_string_in_struct(const type_t *type);
92 static unsigned int write_string_tfs(FILE *file, const attr_list_t *attrs,
93                                      type_t *type, enum type_context context,
94                                      const char *name, unsigned int *typestring_offset);
95 static unsigned int get_required_buffer_size_type( const type_t *type, const char *name,
96                                                    const attr_list_t *attrs, int toplevel_param,
97                                                    unsigned int *alignment );
98 static unsigned int get_function_buffer_size( const var_t *func, enum pass pass );
99
100 static const char *string_of_type(unsigned char type)
101 {
102     switch (type)
103     {
104     case RPC_FC_BYTE: return "FC_BYTE";
105     case RPC_FC_CHAR: return "FC_CHAR";
106     case RPC_FC_SMALL: return "FC_SMALL";
107     case RPC_FC_USMALL: return "FC_USMALL";
108     case RPC_FC_WCHAR: return "FC_WCHAR";
109     case RPC_FC_SHORT: return "FC_SHORT";
110     case RPC_FC_USHORT: return "FC_USHORT";
111     case RPC_FC_LONG: return "FC_LONG";
112     case RPC_FC_ULONG: return "FC_ULONG";
113     case RPC_FC_FLOAT: return "FC_FLOAT";
114     case RPC_FC_HYPER: return "FC_HYPER";
115     case RPC_FC_DOUBLE: return "FC_DOUBLE";
116     case RPC_FC_ENUM16: return "FC_ENUM16";
117     case RPC_FC_ENUM32: return "FC_ENUM32";
118     case RPC_FC_IGNORE: return "FC_IGNORE";
119     case RPC_FC_ERROR_STATUS_T: return "FC_ERROR_STATUS_T";
120     case RPC_FC_RP: return "FC_RP";
121     case RPC_FC_UP: return "FC_UP";
122     case RPC_FC_OP: return "FC_OP";
123     case RPC_FC_FP: return "FC_FP";
124     case RPC_FC_ENCAPSULATED_UNION: return "FC_ENCAPSULATED_UNION";
125     case RPC_FC_NON_ENCAPSULATED_UNION: return "FC_NON_ENCAPSULATED_UNION";
126     case RPC_FC_STRUCT: return "FC_STRUCT";
127     case RPC_FC_PSTRUCT: return "FC_PSTRUCT";
128     case RPC_FC_CSTRUCT: return "FC_CSTRUCT";
129     case RPC_FC_CPSTRUCT: return "FC_CPSTRUCT";
130     case RPC_FC_CVSTRUCT: return "FC_CVSTRUCT";
131     case RPC_FC_BOGUS_STRUCT: return "FC_BOGUS_STRUCT";
132     case RPC_FC_SMFARRAY: return "FC_SMFARRAY";
133     case RPC_FC_LGFARRAY: return "FC_LGFARRAY";
134     case RPC_FC_SMVARRAY: return "FC_SMVARRAY";
135     case RPC_FC_LGVARRAY: return "FC_LGVARRAY";
136     case RPC_FC_CARRAY: return "FC_CARRAY";
137     case RPC_FC_CVARRAY: return "FC_CVARRAY";
138     case RPC_FC_BOGUS_ARRAY: return "FC_BOGUS_ARRAY";
139     case RPC_FC_ALIGNM2: return "FC_ALIGNM2";
140     case RPC_FC_ALIGNM4: return "FC_ALIGNM4";
141     case RPC_FC_ALIGNM8: return "FC_ALIGNM8";
142     case RPC_FC_POINTER: return "FC_POINTER";
143     case RPC_FC_C_CSTRING: return "FC_C_CSTRING";
144     case RPC_FC_C_WSTRING: return "FC_C_WSTRING";
145     case RPC_FC_CSTRING: return "FC_CSTRING";
146     case RPC_FC_WSTRING: return "FC_WSTRING";
147     case RPC_FC_BYTE_COUNT_POINTER: return "FC_BYTE_COUNT_POINTER";
148     case RPC_FC_TRANSMIT_AS: return "FC_TRANSMIT_AS";
149     case RPC_FC_REPRESENT_AS: return "FC_REPRESENT_AS";
150     case RPC_FC_IP: return "FC_IP";
151     case RPC_FC_BIND_CONTEXT: return "FC_BIND_CONTEXT";
152     case RPC_FC_BIND_GENERIC: return "FC_BIND_GENERIC";
153     case RPC_FC_BIND_PRIMITIVE: return "FC_BIND_PRIMITIVE";
154     case RPC_FC_AUTO_HANDLE: return "FC_AUTO_HANDLE";
155     case RPC_FC_CALLBACK_HANDLE: return "FC_CALLBACK_HANDLE";
156     case RPC_FC_STRUCTPAD1: return "FC_STRUCTPAD1";
157     case RPC_FC_STRUCTPAD2: return "FC_STRUCTPAD2";
158     case RPC_FC_STRUCTPAD3: return "FC_STRUCTPAD3";
159     case RPC_FC_STRUCTPAD4: return "FC_STRUCTPAD4";
160     case RPC_FC_STRUCTPAD5: return "FC_STRUCTPAD5";
161     case RPC_FC_STRUCTPAD6: return "FC_STRUCTPAD6";
162     case RPC_FC_STRUCTPAD7: return "FC_STRUCTPAD7";
163     case RPC_FC_STRING_SIZED: return "FC_STRING_SIZED";
164     case RPC_FC_NO_REPEAT: return "FC_NO_REPEAT";
165     case RPC_FC_FIXED_REPEAT: return "FC_FIXED_REPEAT";
166     case RPC_FC_VARIABLE_REPEAT: return "FC_VARIABLE_REPEAT";
167     case RPC_FC_FIXED_OFFSET: return "FC_FIXED_OFFSET";
168     case RPC_FC_VARIABLE_OFFSET: return "FC_VARIABLE_OFFSET";
169     case RPC_FC_PP: return "FC_PP";
170     case RPC_FC_EMBEDDED_COMPLEX: return "FC_EMBEDDED_COMPLEX";
171     case RPC_FC_DEREFERENCE: return "FC_DEREFERENCE";
172     case RPC_FC_DIV_2: return "FC_DIV_2";
173     case RPC_FC_MULT_2: return "FC_MULT_2";
174     case RPC_FC_ADD_1: return "FC_ADD_1";
175     case RPC_FC_SUB_1: return "FC_SUB_1";
176     case RPC_FC_CALLBACK: return "FC_CALLBACK";
177     case RPC_FC_CONSTANT_IID: return "FC_CONSTANT_IID";
178     case RPC_FC_END: return "FC_END";
179     case RPC_FC_PAD: return "FC_PAD";
180     case RPC_FC_USER_MARSHAL: return "FC_USER_MARSHAL";
181     case RPC_FC_RANGE: return "FC_RANGE";
182     case RPC_FC_INT3264: return "FC_INT3264";
183     case RPC_FC_UINT3264: return "FC_UINT3264";
184     default:
185         error("string_of_type: unknown type 0x%02x\n", type);
186         return NULL;
187     }
188 }
189
190 static void *get_aliaschain_attrp(const type_t *type, enum attr_type attr)
191 {
192     const type_t *t = type;
193     for (;;)
194     {
195         if (is_attr(t->attrs, attr))
196             return get_attrp(t->attrs, attr);
197         else if (type_is_alias(t))
198             t = type_alias_get_aliasee(t);
199         else return NULL;
200     }
201 }
202
203 unsigned char get_basic_fc(const type_t *type)
204 {
205     int sign = type_basic_get_sign(type);
206     switch (type_basic_get_type(type))
207     {
208     case TYPE_BASIC_INT8: return (sign <= 0 ? RPC_FC_SMALL : RPC_FC_USMALL);
209     case TYPE_BASIC_INT16: return (sign <= 0 ? RPC_FC_SHORT : RPC_FC_USHORT);
210     case TYPE_BASIC_INT32: return (sign <= 0 ? RPC_FC_LONG : RPC_FC_ULONG);
211     case TYPE_BASIC_INT64: return RPC_FC_HYPER;
212     case TYPE_BASIC_INT: return (sign <= 0 ? RPC_FC_LONG : RPC_FC_ULONG);
213     case TYPE_BASIC_INT3264: return (sign <= 0 ? RPC_FC_INT3264 : RPC_FC_UINT3264);
214     case TYPE_BASIC_BYTE: return RPC_FC_BYTE;
215     case TYPE_BASIC_CHAR: return RPC_FC_CHAR;
216     case TYPE_BASIC_WCHAR: return RPC_FC_WCHAR;
217     case TYPE_BASIC_HYPER: return RPC_FC_HYPER;
218     case TYPE_BASIC_FLOAT: return RPC_FC_FLOAT;
219     case TYPE_BASIC_DOUBLE: return RPC_FC_DOUBLE;
220     case TYPE_BASIC_ERROR_STATUS_T: return RPC_FC_ERROR_STATUS_T;
221     case TYPE_BASIC_HANDLE: return RPC_FC_BIND_PRIMITIVE;
222     }
223     return 0;
224 }
225
226 static unsigned char get_basic_fc_signed(const type_t *type)
227 {
228     switch (type_basic_get_type(type))
229     {
230     case TYPE_BASIC_INT8: return RPC_FC_SMALL;
231     case TYPE_BASIC_INT16: return RPC_FC_SHORT;
232     case TYPE_BASIC_INT32: return RPC_FC_LONG;
233     case TYPE_BASIC_INT64: return RPC_FC_HYPER;
234     case TYPE_BASIC_INT: return RPC_FC_LONG;
235     case TYPE_BASIC_INT3264: return RPC_FC_INT3264;
236     case TYPE_BASIC_BYTE: return RPC_FC_BYTE;
237     case TYPE_BASIC_CHAR: return RPC_FC_CHAR;
238     case TYPE_BASIC_WCHAR: return RPC_FC_WCHAR;
239     case TYPE_BASIC_HYPER: return RPC_FC_HYPER;
240     case TYPE_BASIC_FLOAT: return RPC_FC_FLOAT;
241     case TYPE_BASIC_DOUBLE: return RPC_FC_DOUBLE;
242     case TYPE_BASIC_ERROR_STATUS_T: return RPC_FC_ERROR_STATUS_T;
243     case TYPE_BASIC_HANDLE: return RPC_FC_BIND_PRIMITIVE;
244     }
245     return 0;
246 }
247
248 static inline unsigned int clamp_align(unsigned int align)
249 {
250     unsigned int packing = (pointer_size == 4) ? win32_packing : win64_packing;
251     if(align > packing) align = packing;
252     return align;
253 }
254
255 unsigned char get_pointer_fc(const type_t *type, const attr_list_t *attrs, int toplevel_param)
256 {
257     const type_t *t;
258     int pointer_type;
259
260     assert(is_ptr(type) || is_array(type));
261
262     pointer_type = get_attrv(attrs, ATTR_POINTERTYPE);
263     if (pointer_type)
264         return pointer_type;
265
266     for (t = type; type_is_alias(t); t = type_alias_get_aliasee(t))
267     {
268         pointer_type = get_attrv(t->attrs, ATTR_POINTERTYPE);
269         if (pointer_type)
270             return pointer_type;
271     }
272
273     if (toplevel_param)
274         return RPC_FC_RP;
275     else if (is_ptr(type))
276         return type_pointer_get_default_fc(type);
277     else
278         return type_array_get_ptr_default_fc(type);
279 }
280
281 static unsigned char get_pointer_fc_context( const type_t *type, const attr_list_t *attrs,
282                                              enum type_context context )
283 {
284     int pointer_fc = get_pointer_fc(type, attrs, context == TYPE_CONTEXT_TOPLEVELPARAM);
285
286     if (pointer_fc == RPC_FC_UP && is_attr( attrs, ATTR_OUT ) &&
287         context == TYPE_CONTEXT_PARAM && is_object( current_iface ))
288         pointer_fc = RPC_FC_OP;
289
290     return pointer_fc;
291 }
292
293 static unsigned char get_enum_fc(const type_t *type)
294 {
295     assert(type_get_type(type) == TYPE_ENUM);
296     if (is_aliaschain_attr(type, ATTR_V1ENUM))
297         return RPC_FC_ENUM32;
298     else
299         return RPC_FC_ENUM16;
300 }
301
302 static type_t *get_user_type(const type_t *t, const char **pname)
303 {
304     for (;;)
305     {
306         type_t *ut = get_attrp(t->attrs, ATTR_WIREMARSHAL);
307         if (ut)
308         {
309             if (pname)
310                 *pname = t->name;
311             return ut;
312         }
313
314         if (type_is_alias(t))
315             t = type_alias_get_aliasee(t);
316         else
317             return NULL;
318     }
319 }
320
321 static int is_user_type(const type_t *t)
322 {
323     return get_user_type(t, NULL) != NULL;
324 }
325
326 enum typegen_type typegen_detect_type(const type_t *type, const attr_list_t *attrs, unsigned int flags)
327 {
328     if (is_user_type(type))
329         return TGT_USER_TYPE;
330
331     if (is_aliaschain_attr(type, ATTR_CONTEXTHANDLE))
332         return TGT_CTXT_HANDLE;
333
334     if (!(flags & TDT_IGNORE_STRINGS) && is_string_type(attrs, type))
335         return TGT_STRING;
336
337     switch (type_get_type(type))
338     {
339     case TYPE_BASIC:
340         if (!(flags & TDT_IGNORE_RANGES) &&
341             (is_attr(attrs, ATTR_RANGE) || is_aliaschain_attr(type, ATTR_RANGE)))
342             return TGT_RANGE;
343         return TGT_BASIC;
344     case TYPE_ENUM:
345         if (!(flags & TDT_IGNORE_RANGES) &&
346             (is_attr(attrs, ATTR_RANGE) || is_aliaschain_attr(type, ATTR_RANGE)))
347             return TGT_RANGE;
348         return TGT_ENUM;
349     case TYPE_POINTER:
350         if (type_get_type(type_pointer_get_ref(type)) == TYPE_INTERFACE ||
351             (type_get_type(type_pointer_get_ref(type)) == TYPE_VOID && is_attr(attrs, ATTR_IIDIS)))
352             return TGT_IFACE_POINTER;
353         else if (is_aliaschain_attr(type_pointer_get_ref(type), ATTR_CONTEXTHANDLE))
354             return TGT_CTXT_HANDLE_POINTER;
355         else
356             return TGT_POINTER;
357     case TYPE_STRUCT:
358         return TGT_STRUCT;
359     case TYPE_ENCAPSULATED_UNION:
360     case TYPE_UNION:
361         return TGT_UNION;
362     case TYPE_ARRAY:
363         return TGT_ARRAY;
364     case TYPE_FUNCTION:
365     case TYPE_COCLASS:
366     case TYPE_INTERFACE:
367     case TYPE_MODULE:
368     case TYPE_VOID:
369     case TYPE_ALIAS:
370     case TYPE_BITFIELD:
371         break;
372     }
373     return TGT_INVALID;
374 }
375
376 static int cant_be_null(const var_t *v)
377 {
378     switch (typegen_detect_type(v->type, v->attrs, TDT_IGNORE_STRINGS))
379     {
380     case TGT_ARRAY:
381         if (!type_array_is_decl_as_ptr( v->type )) return 0;
382         /* fall through */
383     case TGT_POINTER:
384         return (get_pointer_fc(v->type, v->attrs, TRUE) == RPC_FC_RP);
385     case TGT_CTXT_HANDLE_POINTER:
386         return TRUE;
387     default:
388         return 0;
389     }
390
391 }
392
393 static int get_padding(const var_list_t *fields)
394 {
395     unsigned short offset = 0;
396     unsigned int salign = 1;
397     const var_t *f;
398
399     if (!fields)
400         return 0;
401
402     LIST_FOR_EACH_ENTRY(f, fields, const var_t, entry)
403     {
404         type_t *ft = f->type;
405         unsigned int align = 0;
406         unsigned int size = type_memsize_and_alignment(ft, &align);
407         align = clamp_align(align);
408         if (align > salign) salign = align;
409         offset = ROUND_SIZE(offset, align);
410         offset += size;
411     }
412
413     return ROUNDING(offset, salign);
414 }
415
416 static unsigned int get_stack_size( const type_t *type, const attr_list_t *attrs, int *by_value )
417 {
418     unsigned int stack_size;
419     int by_val;
420
421     switch (typegen_detect_type( type, attrs, TDT_ALL_TYPES ))
422     {
423     case TGT_BASIC:
424     case TGT_ENUM:
425     case TGT_RANGE:
426     case TGT_STRUCT:
427     case TGT_UNION:
428     case TGT_USER_TYPE:
429         stack_size = type_memsize( type );
430         by_val = (pointer_size < 8 || stack_size <= pointer_size); /* FIXME: should be platform-specific */
431         break;
432     default:
433         by_val = 0;
434         break;
435     }
436     if (!by_val) stack_size = pointer_size;
437     if (by_value) *by_value = by_val;
438     return ROUND_SIZE( stack_size, pointer_size );
439 }
440
441 static unsigned char get_contexthandle_flags( const type_t *iface, const attr_list_t *attrs,
442                                               const type_t *type )
443 {
444     unsigned char flags = 0;
445
446     if (is_attr(iface->attrs, ATTR_STRICTCONTEXTHANDLE)) flags |= NDR_STRICT_CONTEXT_HANDLE;
447
448     if (is_ptr(type) &&
449         !is_attr( type->attrs, ATTR_CONTEXTHANDLE ) &&
450         !is_attr( attrs, ATTR_CONTEXTHANDLE ))
451         flags |= 0x80;
452
453     if (is_attr(attrs, ATTR_IN))
454     {
455         flags |= 0x40;
456         if (!is_attr(attrs, ATTR_OUT)) flags |= NDR_CONTEXT_HANDLE_CANNOT_BE_NULL;
457     }
458     if (is_attr(attrs, ATTR_OUT)) flags |= 0x20;
459
460     return flags;
461 }
462
463 static unsigned int get_rpc_flags( const attr_list_t *attrs )
464 {
465     unsigned int flags = 0;
466
467     if (is_attr( attrs, ATTR_IDEMPOTENT )) flags |= 0x0001;
468     if (is_attr( attrs, ATTR_BROADCAST )) flags |= 0x0002;
469     if (is_attr( attrs, ATTR_MAYBE )) flags |= 0x0004;
470     if (is_attr( attrs, ATTR_MESSAGE )) flags |= 0x0100;
471     if (is_attr( attrs, ATTR_ASYNC )) flags |= 0x4000;
472     return flags;
473 }
474
475 unsigned char get_struct_fc(const type_t *type)
476 {
477   int has_pointer = 0;
478   int has_conformance = 0;
479   int has_variance = 0;
480   var_t *field;
481   var_list_t *fields;
482
483   fields = type_struct_get_fields(type);
484
485   if (get_padding(fields))
486     return RPC_FC_BOGUS_STRUCT;
487
488   if (fields) LIST_FOR_EACH_ENTRY( field, fields, var_t, entry )
489   {
490     type_t *t = field->type;
491     enum typegen_type typegen_type;
492
493     typegen_type = typegen_detect_type(t, field->attrs, TDT_IGNORE_STRINGS);
494
495     if (typegen_type == TGT_ARRAY && !type_array_is_decl_as_ptr(t))
496     {
497         if (is_string_type(field->attrs, field->type))
498         {
499             if (is_conformant_array(t))
500                 has_conformance = 1;
501             has_variance = 1;
502             continue;
503         }
504
505         if (is_array(type_array_get_element(field->type)))
506             return RPC_FC_BOGUS_STRUCT;
507
508         if (type_array_has_conformance(field->type))
509         {
510             has_conformance = 1;
511             if (list_next(fields, &field->entry))
512                 error_loc("field '%s' deriving from a conformant array must be the last field in the structure\n",
513                         field->name);
514         }
515         if (type_array_has_variance(t))
516             has_variance = 1;
517
518         t = type_array_get_element(t);
519         typegen_type = typegen_detect_type(t, field->attrs, TDT_IGNORE_STRINGS);
520     }
521
522     switch (typegen_type)
523     {
524     case TGT_USER_TYPE:
525     case TGT_IFACE_POINTER:
526         return RPC_FC_BOGUS_STRUCT;
527     case TGT_BASIC:
528         if (type_basic_get_type(t) == TYPE_BASIC_INT3264 && pointer_size != 4)
529             return RPC_FC_BOGUS_STRUCT;
530         break;
531     case TGT_ENUM:
532         if (get_enum_fc(t) == RPC_FC_ENUM16)
533             return RPC_FC_BOGUS_STRUCT;
534         break;
535     case TGT_POINTER:
536     case TGT_ARRAY:
537         if (get_pointer_fc(t, field->attrs, FALSE) == RPC_FC_RP || pointer_size != 4)
538             return RPC_FC_BOGUS_STRUCT;
539         has_pointer = 1;
540         break;
541     case TGT_UNION:
542         return RPC_FC_BOGUS_STRUCT;
543     case TGT_STRUCT:
544     {
545         unsigned char fc = get_struct_fc(t);
546         switch (fc)
547         {
548         case RPC_FC_STRUCT:
549             break;
550         case RPC_FC_CVSTRUCT:
551             has_conformance = 1;
552             has_variance = 1;
553             has_pointer = 1;
554             break;
555
556         case RPC_FC_CPSTRUCT:
557             has_conformance = 1;
558             if (list_next( fields, &field->entry ))
559                 error_loc("field '%s' deriving from a conformant array must be the last field in the structure\n",
560                         field->name);
561             has_pointer = 1;
562             break;
563
564         case RPC_FC_CSTRUCT:
565             has_conformance = 1;
566             if (list_next( fields, &field->entry ))
567                 error_loc("field '%s' deriving from a conformant array must be the last field in the structure\n",
568                       field->name);
569             break;
570
571         case RPC_FC_PSTRUCT:
572             has_pointer = 1;
573             break;
574
575         default:
576             error_loc("Unknown struct member %s with type (0x%02x)\n", field->name, fc);
577             /* fallthru - treat it as complex */
578
579         /* as soon as we see one of these these members, it's bogus... */
580         case RPC_FC_BOGUS_STRUCT:
581             return RPC_FC_BOGUS_STRUCT;
582         }
583         break;
584     }
585     case TGT_RANGE:
586         return RPC_FC_BOGUS_STRUCT;
587     case TGT_STRING:
588         /* shouldn't get here because of TDT_IGNORE_STRINGS above. fall through */
589     case TGT_INVALID:
590     case TGT_CTXT_HANDLE:
591     case TGT_CTXT_HANDLE_POINTER:
592         /* checking after parsing should mean that we don't get here. if we do,
593          * it's a checker bug */
594         assert(0);
595     }
596   }
597
598   if( has_variance )
599   {
600     if ( has_conformance )
601       return RPC_FC_CVSTRUCT;
602     else
603       return RPC_FC_BOGUS_STRUCT;
604   }
605   if( has_conformance && has_pointer )
606     return RPC_FC_CPSTRUCT;
607   if( has_conformance )
608     return RPC_FC_CSTRUCT;
609   if( has_pointer )
610     return RPC_FC_PSTRUCT;
611   return RPC_FC_STRUCT;
612 }
613
614 static unsigned char get_array_fc(const type_t *type)
615 {
616     unsigned char fc;
617     const expr_t *size_is;
618     const type_t *elem_type;
619
620     elem_type = type_array_get_element(type);
621     size_is = type_array_get_conformance(type);
622
623     if (!size_is)
624     {
625         unsigned int size = type_memsize(elem_type);
626         if (size * type_array_get_dim(type) > 0xffffuL)
627             fc = RPC_FC_LGFARRAY;
628         else
629             fc = RPC_FC_SMFARRAY;
630     }
631     else
632         fc = RPC_FC_CARRAY;
633
634     if (type_array_has_variance(type))
635     {
636         if (fc == RPC_FC_SMFARRAY)
637             fc = RPC_FC_SMVARRAY;
638         else if (fc == RPC_FC_LGFARRAY)
639             fc = RPC_FC_LGVARRAY;
640         else if (fc == RPC_FC_CARRAY)
641             fc = RPC_FC_CVARRAY;
642     }
643
644     switch (typegen_detect_type(elem_type, NULL, TDT_IGNORE_STRINGS))
645     {
646     case TGT_USER_TYPE:
647         fc = RPC_FC_BOGUS_ARRAY;
648         break;
649     case TGT_BASIC:
650         if (type_basic_get_type(elem_type) == TYPE_BASIC_INT3264 &&
651             pointer_size != 4)
652             fc = RPC_FC_BOGUS_ARRAY;
653         break;
654     case TGT_STRUCT:
655         switch (get_struct_fc(elem_type))
656         {
657         case RPC_FC_BOGUS_STRUCT:
658             fc = RPC_FC_BOGUS_ARRAY;
659             break;
660         }
661         break;
662     case TGT_ENUM:
663         /* is 16-bit enum - if so, wire size differs from mem size and so
664          * the array cannot be block copied, which means the array is complex */
665         if (get_enum_fc(elem_type) == RPC_FC_ENUM16)
666             fc = RPC_FC_BOGUS_ARRAY;
667         break;
668     case TGT_UNION:
669     case TGT_IFACE_POINTER:
670         fc = RPC_FC_BOGUS_ARRAY;
671         break;
672     case TGT_POINTER:
673         /* ref pointers cannot just be block copied. unique pointers to
674          * interfaces need special treatment. either case means the array is
675          * complex */
676         if (get_pointer_fc(elem_type, NULL, FALSE) == RPC_FC_RP || pointer_size != 4)
677             fc = RPC_FC_BOGUS_ARRAY;
678         break;
679     case TGT_RANGE:
680         fc = RPC_FC_BOGUS_ARRAY;
681         break;
682     case TGT_CTXT_HANDLE:
683     case TGT_CTXT_HANDLE_POINTER:
684     case TGT_STRING:
685     case TGT_INVALID:
686     case TGT_ARRAY:
687         /* nothing to do for everything else */
688         break;
689     }
690
691     return fc;
692 }
693
694 static int is_non_complex_struct(const type_t *type)
695 {
696     return (type_get_type(type) == TYPE_STRUCT &&
697             get_struct_fc(type) != RPC_FC_BOGUS_STRUCT);
698 }
699
700 static int type_has_pointers(const type_t *type)
701 {
702     switch (typegen_detect_type(type, NULL, TDT_IGNORE_STRINGS))
703     {
704     case TGT_USER_TYPE:
705         return FALSE;
706     case TGT_POINTER:
707         return TRUE;
708     case TGT_ARRAY:
709         return type_array_is_decl_as_ptr(type) || type_has_pointers(type_array_get_element(type));
710     case TGT_STRUCT:
711     {
712         var_list_t *fields = type_struct_get_fields(type);
713         const var_t *field;
714         if (fields) LIST_FOR_EACH_ENTRY( field, fields, const var_t, entry )
715         {
716             if (type_has_pointers(field->type))
717                 return TRUE;
718         }
719         break;
720     }
721     case TGT_UNION:
722     {
723         var_list_t *fields;
724         const var_t *field;
725         fields = type_union_get_cases(type);
726         if (fields) LIST_FOR_EACH_ENTRY( field, fields, const var_t, entry )
727         {
728             if (field->type && type_has_pointers(field->type))
729                 return TRUE;
730         }
731         break;
732     }
733     case TGT_CTXT_HANDLE:
734     case TGT_CTXT_HANDLE_POINTER:
735     case TGT_STRING:
736     case TGT_IFACE_POINTER:
737     case TGT_BASIC:
738     case TGT_ENUM:
739     case TGT_RANGE:
740     case TGT_INVALID:
741         break;
742     }
743
744     return FALSE;
745 }
746
747 static int type_has_full_pointer(const type_t *type, const attr_list_t *attrs,
748                                  int toplevel_param)
749 {
750     switch (typegen_detect_type(type, NULL, TDT_IGNORE_STRINGS))
751     {
752     case TGT_USER_TYPE:
753         return FALSE;
754     case TGT_POINTER:
755         if (get_pointer_fc(type, attrs, toplevel_param) == RPC_FC_FP)
756             return TRUE;
757         else
758             return FALSE;
759     case TGT_ARRAY:
760         if (get_pointer_fc(type, attrs, toplevel_param) == RPC_FC_FP)
761             return TRUE;
762         else
763             return type_has_full_pointer(type_array_get_element(type), NULL, FALSE);
764     case TGT_STRUCT:
765     {
766         var_list_t *fields = type_struct_get_fields(type);
767         const var_t *field;
768         if (fields) LIST_FOR_EACH_ENTRY( field, fields, const var_t, entry )
769         {
770             if (type_has_full_pointer(field->type, field->attrs, FALSE))
771                 return TRUE;
772         }
773         break;
774     }
775     case TGT_UNION:
776     {
777         var_list_t *fields;
778         const var_t *field;
779         fields = type_union_get_cases(type);
780         if (fields) LIST_FOR_EACH_ENTRY( field, fields, const var_t, entry )
781         {
782             if (field->type && type_has_full_pointer(field->type, field->attrs, FALSE))
783                 return TRUE;
784         }
785         break;
786     }
787     case TGT_CTXT_HANDLE:
788     case TGT_CTXT_HANDLE_POINTER:
789     case TGT_STRING:
790     case TGT_IFACE_POINTER:
791     case TGT_BASIC:
792     case TGT_ENUM:
793     case TGT_RANGE:
794     case TGT_INVALID:
795         break;
796     }
797
798     return FALSE;
799 }
800
801 static unsigned short user_type_offset(const char *name)
802 {
803     user_type_t *ut;
804     unsigned short off = 0;
805     LIST_FOR_EACH_ENTRY(ut, &user_type_list, user_type_t, entry)
806     {
807         if (strcmp(name, ut->name) == 0)
808             return off;
809         ++off;
810     }
811     error("user_type_offset: couldn't find type (%s)\n", name);
812     return 0;
813 }
814
815 static void update_tfsoff(type_t *type, unsigned int offset, FILE *file)
816 {
817     type->typestring_offset = offset;
818     if (file) type->tfswrite = FALSE;
819 }
820
821 static void guard_rec(type_t *type)
822 {
823     /* types that contain references to themselves (like a linked list),
824        need to be shielded from infinite recursion when writing embedded
825        types  */
826     if (type->typestring_offset)
827         type->tfswrite = FALSE;
828     else
829         type->typestring_offset = 1;
830 }
831
832 static int is_embedded_complex(const type_t *type)
833 {
834     switch (typegen_detect_type(type, NULL, TDT_ALL_TYPES))
835     {
836     case TGT_USER_TYPE:
837     case TGT_STRUCT:
838     case TGT_UNION:
839     case TGT_ARRAY:
840     case TGT_IFACE_POINTER:
841         return TRUE;
842     default:
843         return FALSE;
844     }
845 }
846
847 static const char *get_context_handle_type_name(const type_t *type)
848 {
849     const type_t *t;
850     for (t = type;
851          is_ptr(t) || type_is_alias(t);
852          t = type_is_alias(t) ? type_alias_get_aliasee(t) : type_pointer_get_ref(t))
853         if (is_attr(t->attrs, ATTR_CONTEXTHANDLE))
854             return t->name;
855     assert(0);
856     return NULL;
857 }
858
859 #define WRITE_FCTYPE(file, fctype, typestring_offset) \
860     do { \
861         if (file) \
862             fprintf(file, "/* %2u */\n", typestring_offset); \
863         print_file((file), 2, "0x%02x,    /* " #fctype " */\n", RPC_##fctype); \
864     } \
865     while (0)
866
867 static void print_file(FILE *file, int indent, const char *format, ...) __attribute__((format (printf, 3, 4)));
868 static void print_file(FILE *file, int indent, const char *format, ...)
869 {
870     va_list va;
871     va_start(va, format);
872     print(file, indent, format, va);
873     va_end(va);
874 }
875
876 void print(FILE *file, int indent, const char *format, va_list va)
877 {
878     if (file)
879     {
880         if (format[0] != '\n')
881             while (0 < indent--)
882                 fprintf(file, "    ");
883         vfprintf(file, format, va);
884     }
885 }
886
887
888 static void write_var_init(FILE *file, int indent, const type_t *t, const char *n, const char *local_var_prefix)
889 {
890     if (decl_indirect(t))
891     {
892         print_file(file, indent, "MIDL_memset(&%s%s, 0, sizeof(%s%s));\n",
893                    local_var_prefix, n, local_var_prefix, n);
894         print_file(file, indent, "%s_p_%s = &%s%s;\n", local_var_prefix, n, local_var_prefix, n);
895     }
896     else if (is_ptr(t) || is_array(t))
897         print_file(file, indent, "%s%s = 0;\n", local_var_prefix, n);
898 }
899
900 void write_parameters_init(FILE *file, int indent, const var_t *func, const char *local_var_prefix)
901 {
902     const var_t *var;
903
904     if (!is_void(type_function_get_rettype(func->type)))
905         write_var_init(file, indent, type_function_get_rettype(func->type), "_RetVal", local_var_prefix);
906
907     if (!type_get_function_args(func->type))
908         return;
909
910     LIST_FOR_EACH_ENTRY( var, type_get_function_args(func->type), const var_t, entry )
911         write_var_init(file, indent, var->type, var->name, local_var_prefix);
912
913     fprintf(file, "\n");
914 }
915
916 static void write_formatdesc(FILE *f, int indent, const char *str)
917 {
918     print_file(f, indent, "typedef struct _MIDL_%s_FORMAT_STRING\n", str);
919     print_file(f, indent, "{\n");
920     print_file(f, indent + 1, "short Pad;\n");
921     print_file(f, indent + 1, "unsigned char Format[%s_FORMAT_STRING_SIZE];\n", str);
922     print_file(f, indent, "} MIDL_%s_FORMAT_STRING;\n", str);
923     print_file(f, indent, "\n");
924 }
925
926 void write_formatstringsdecl(FILE *f, int indent, const statement_list_t *stmts, type_pred_t pred)
927 {
928     clear_all_offsets();
929
930     print_file(f, indent, "#define TYPE_FORMAT_STRING_SIZE %d\n",
931                get_size_typeformatstring(stmts, pred));
932
933     print_file(f, indent, "#define PROC_FORMAT_STRING_SIZE %d\n",
934                get_size_procformatstring(stmts, pred));
935
936     fprintf(f, "\n");
937     write_formatdesc(f, indent, "TYPE");
938     write_formatdesc(f, indent, "PROC");
939     fprintf(f, "\n");
940     print_file(f, indent, "static const MIDL_TYPE_FORMAT_STRING __MIDL_TypeFormatString;\n");
941     print_file(f, indent, "static const MIDL_PROC_FORMAT_STRING __MIDL_ProcFormatString;\n");
942     print_file(f, indent, "\n");
943 }
944
945 int decl_indirect(const type_t *t)
946 {
947     if (is_user_type(t))
948         return TRUE;
949     return (type_get_type(t) != TYPE_BASIC &&
950             type_get_type(t) != TYPE_ENUM &&
951             type_get_type(t) != TYPE_POINTER &&
952             type_get_type(t) != TYPE_ARRAY);
953 }
954
955 static unsigned char get_parameter_fc( const type_t *type, const attr_list_t *attrs, int is_return,
956                                        unsigned short *flags, unsigned int *stack_size,
957                                        unsigned int *typestring_offset )
958 {
959     unsigned int alignment, server_size = 0, buffer_size = 0;
960     unsigned char fc = 0;
961     int is_byval;
962     int is_in = is_attr(attrs, ATTR_IN);
963     int is_out = is_attr(attrs, ATTR_OUT);
964
965     if (is_return) is_out = TRUE;
966     else if (!is_in && !is_out) is_in = TRUE;
967
968     *flags = 0;
969     *stack_size = get_stack_size( type, attrs, &is_byval );
970     *typestring_offset = type->typestring_offset;
971
972     if (is_in)     *flags |= IsIn;
973     if (is_out)    *flags |= IsOut;
974     if (is_return) *flags |= IsReturn;
975
976     if (!is_string_type( attrs, type ))
977         buffer_size = get_required_buffer_size_type( type, NULL, attrs, TRUE, &alignment );
978
979     switch (typegen_detect_type( type, attrs, TDT_ALL_TYPES ))
980     {
981     case TGT_BASIC:
982         *flags |= IsBasetype;
983         fc = get_basic_fc_signed( type );
984         if (fc == RPC_FC_BIND_PRIMITIVE)
985         {
986             buffer_size = 4;  /* actually 0 but avoids setting MustSize */
987             fc = RPC_FC_LONG;
988         }
989         break;
990     case TGT_ENUM:
991         *flags |= IsBasetype;
992         fc = get_enum_fc( type );
993         break;
994     case TGT_RANGE:
995         *flags |= IsByValue;
996         break;
997     case TGT_STRUCT:
998     case TGT_UNION:
999     case TGT_USER_TYPE:
1000         *flags |= MustFree | (is_byval ? IsByValue : IsSimpleRef);
1001         break;
1002     case TGT_IFACE_POINTER:
1003         *flags |= MustFree;
1004         break;
1005     case TGT_ARRAY:
1006         *flags |= MustFree;
1007         if (type_array_is_decl_as_ptr(type) && type->details.array.ptr_tfsoff &&
1008             get_pointer_fc( type, attrs, !is_return ) == RPC_FC_RP)
1009             *flags |= IsSimpleRef;
1010         break;
1011     case TGT_STRING:
1012         *flags |= MustFree;
1013         if (is_declptr( type ) && get_pointer_fc( type, attrs, !is_return ) == RPC_FC_RP)
1014         {
1015             /* skip over pointer description straight to string description */
1016             if (is_conformant_array( type )) *typestring_offset += 4;
1017             else *typestring_offset += 2;
1018             *flags |= IsSimpleRef;
1019         }
1020         break;
1021     case TGT_CTXT_HANDLE_POINTER:
1022         *flags |= IsSimpleRef;
1023         *typestring_offset += 4;
1024         /* fall through */
1025     case TGT_CTXT_HANDLE:
1026         buffer_size = 20;
1027         break;
1028     case TGT_POINTER:
1029         if (get_pointer_fc( type, attrs, !is_return ) == RPC_FC_RP)
1030         {
1031             const type_t *ref = type_pointer_get_ref( type );
1032
1033             if (!is_string_type( attrs, ref ))
1034                 buffer_size = get_required_buffer_size_type( ref, NULL, NULL, TRUE, &alignment );
1035
1036             switch (typegen_detect_type( ref, NULL, TDT_ALL_TYPES ))
1037             {
1038             case TGT_BASIC:
1039                 *flags |= IsSimpleRef | IsBasetype;
1040                 fc = get_basic_fc( ref );
1041                 if (!is_in && is_out) server_size = pointer_size;
1042                 break;
1043             case TGT_ENUM:
1044                 if ((fc = get_enum_fc( ref )) == RPC_FC_ENUM32)
1045                 {
1046                     *flags |= IsSimpleRef | IsBasetype;
1047                     if (!is_in && is_out) server_size = pointer_size;
1048                 }
1049                 else
1050                 {
1051                     server_size = pointer_size;
1052                 }
1053                 break;
1054             case TGT_UNION:
1055             case TGT_USER_TYPE:
1056             case TGT_RANGE:
1057                 *flags |= IsSimpleRef | MustFree;
1058                 *typestring_offset = ref->typestring_offset;
1059                 if (!is_in && is_out) server_size = type_memsize( ref );
1060                 break;
1061             case TGT_STRING:
1062             case TGT_POINTER:
1063             case TGT_ARRAY:
1064             case TGT_CTXT_HANDLE:
1065             case TGT_CTXT_HANDLE_POINTER:
1066                 *flags |= MustFree;
1067                 server_size = pointer_size;
1068                 break;
1069             case TGT_IFACE_POINTER:
1070                 *flags |= MustFree;
1071                 if (is_in && is_out) server_size = pointer_size;
1072                 break;
1073             case TGT_STRUCT:
1074                 *flags |= IsSimpleRef | MustFree;
1075                 *typestring_offset = ref->typestring_offset;
1076                 switch (get_struct_fc(ref))
1077                 {
1078                 case RPC_FC_STRUCT:
1079                 case RPC_FC_PSTRUCT:
1080                 case RPC_FC_BOGUS_STRUCT:
1081                     if (!is_in && is_out) server_size = type_memsize( ref );
1082                     break;
1083                 default:
1084                     break;
1085                 }
1086                 break;
1087             case TGT_INVALID:
1088                 assert(0);
1089             }
1090         }
1091         else  /* not ref pointer */
1092         {
1093             *flags |= MustFree;
1094         }
1095         break;
1096     case TGT_INVALID:
1097         assert(0);
1098     }
1099
1100     if (!buffer_size) *flags |= MustSize;
1101
1102     if (server_size)
1103     {
1104         server_size = (server_size + 7) / 8;
1105         if (server_size < 8) *flags |= server_size << 13;
1106     }
1107     return fc;
1108 }
1109
1110 static unsigned char get_func_oi2_flags( const var_t *func )
1111 {
1112     const var_t *var;
1113     var_list_t *args = type_get_function_args( func->type );
1114     type_t *ret_type = type_function_get_rettype( func->type );
1115     unsigned char oi2_flags = 0x40;  /* HasExtensions */
1116     unsigned short flags;
1117     unsigned int stack_size, typestring_offset;
1118
1119     if (args) LIST_FOR_EACH_ENTRY( var, args, const var_t, entry )
1120     {
1121         get_parameter_fc( var->type, var->attrs, 0, &flags, &stack_size, &typestring_offset );
1122         if (flags & MustSize)
1123         {
1124             if (flags & IsIn) oi2_flags |= 0x02; /* ClientMustSize */
1125             if (flags & IsOut) oi2_flags |= 0x01;  /* ServerMustSize */
1126         }
1127     }
1128
1129     if (!is_void( ret_type ))
1130     {
1131         oi2_flags |= 0x04;  /* HasRet */
1132         get_parameter_fc( ret_type, NULL, 1, &flags, &stack_size, &typestring_offset );
1133         if (flags & MustSize) oi2_flags |= 0x01;  /* ServerMustSize */
1134     }
1135     return oi2_flags;
1136 }
1137
1138 static unsigned int write_new_procformatstring_type(FILE *file, int indent,
1139                                                     const type_t *type,
1140                                                     const attr_list_t *attrs,
1141                                                     int is_return, unsigned int *stack_offset)
1142 {
1143     char buffer[64];
1144     unsigned int stack_size, typestring_offset;
1145     unsigned short flags;
1146     unsigned char fc = get_parameter_fc( type, attrs, is_return, &flags, &stack_size, &typestring_offset );
1147
1148     strcpy( buffer, "/* flags:" );
1149     if (flags & MustSize) strcat( buffer, " must size," );
1150     if (flags & MustFree) strcat( buffer, " must free," );
1151     if (flags & IsPipe) strcat( buffer, " pipe," );
1152     if (flags & IsIn) strcat( buffer, " in," );
1153     if (flags & IsOut) strcat( buffer, " out," );
1154     if (flags & IsReturn) strcat( buffer, " return," );
1155     if (flags & IsBasetype) strcat( buffer, " base type," );
1156     if (flags & IsByValue) strcat( buffer, " by value," );
1157     if (flags & IsSimpleRef) strcat( buffer, " simple ref," );
1158     if (flags >> 13) sprintf( buffer + strlen(buffer), " srv size=%u,", (flags >> 13) * 8 );
1159     strcpy( buffer + strlen( buffer ) - 1, " */" );
1160     print_file( file, indent, "NdrFcShort(0x%hx),\t%s\n", flags, buffer );
1161     print_file( file, indent, "NdrFcShort(0x%hx),       /* stack offset = %hu */\n",
1162                 *stack_offset, *stack_offset );
1163     if (flags & IsBasetype)
1164     {
1165         print_file( file, indent, "0x%02x,      /* %s */\n", fc, string_of_type(fc) );
1166         print_file( file, indent, "0x0,\n" );
1167     }
1168     else
1169         print_file( file, indent, "NdrFcShort(0x%x),    /* type offset = %u */\n",
1170                     typestring_offset, typestring_offset );
1171     *stack_offset += max( stack_size, pointer_size );
1172     return 6;
1173 }
1174
1175 static unsigned int write_old_procformatstring_type(FILE *file, int indent,
1176                                                     const type_t *type,
1177                                                     const attr_list_t *attrs,
1178                                                     int is_return, int is_interpreted)
1179 {
1180     unsigned int size;
1181
1182     int is_in = is_attr(attrs, ATTR_IN);
1183     int is_out = is_attr(attrs, ATTR_OUT);
1184
1185     if (!is_in && !is_out) is_in = TRUE;
1186
1187     if (type_get_type(type) == TYPE_BASIC ||
1188         type_get_type(type) == TYPE_ENUM)
1189     {
1190         unsigned char fc;
1191
1192         if (is_return)
1193             print_file(file, indent, "0x53,    /* FC_RETURN_PARAM_BASETYPE */\n");
1194         else
1195             print_file(file, indent, "0x4e,    /* FC_IN_PARAM_BASETYPE */\n");
1196
1197         if (type_get_type(type) == TYPE_ENUM)
1198         {
1199             fc = get_enum_fc(type);
1200         }
1201         else
1202         {
1203             fc = get_basic_fc_signed(type);
1204
1205             if (fc == RPC_FC_BIND_PRIMITIVE)
1206                 fc = RPC_FC_IGNORE;
1207         }
1208
1209         print_file(file, indent, "0x%02x,    /* %s */\n",
1210                    fc, string_of_type(fc));
1211         size = 2; /* includes param type prefix */
1212     }
1213     else
1214     {
1215         unsigned short offset = type->typestring_offset;
1216
1217         if (is_interpreted && is_array(type) &&
1218             type_array_is_decl_as_ptr(type) &&
1219             type->details.array.ptr_tfsoff)
1220             offset = type->details.array.ptr_tfsoff;
1221
1222         if (is_return)
1223             print_file(file, indent, "0x52,    /* FC_RETURN_PARAM */\n");
1224         else if (is_in && is_out)
1225             print_file(file, indent, "0x50,    /* FC_IN_OUT_PARAM */\n");
1226         else if (is_out)
1227             print_file(file, indent, "0x51,    /* FC_OUT_PARAM */\n");
1228         else
1229             print_file(file, indent, "0x4d,    /* FC_IN_PARAM */\n");
1230
1231         size = get_stack_size( type, attrs, NULL );
1232         print_file(file, indent, "0x%02x,\n", size / pointer_size );
1233         print_file(file, indent, "NdrFcShort(0x%x),     /* type offset = %u */\n", offset, offset);
1234         size = 4; /* includes param type prefix */
1235     }
1236     return size;
1237 }
1238
1239 int is_interpreted_func( const type_t *iface, const var_t *func )
1240 {
1241     const char *str;
1242     const var_t *var;
1243     const var_list_t *args = type_get_function_args( func->type );
1244     const type_t *ret_type = type_function_get_rettype( func->type );
1245
1246     if (type_get_type( ret_type ) == TYPE_BASIC)
1247     {
1248         switch (type_basic_get_type( ret_type ))
1249         {
1250         case TYPE_BASIC_INT64:
1251         case TYPE_BASIC_HYPER:
1252             /* return value must fit in a long_ptr */
1253             if (pointer_size < 8) return 0;
1254             break;
1255         case TYPE_BASIC_FLOAT:
1256         case TYPE_BASIC_DOUBLE:
1257             /* floating point values can't be returned */
1258             return 0;
1259         default:
1260             break;
1261         }
1262     }
1263     if (get_stub_mode() != MODE_Oif && args)
1264     {
1265         LIST_FOR_EACH_ENTRY( var, args, const var_t, entry )
1266             switch (type_get_type( var->type ))
1267             {
1268             case TYPE_BASIC:
1269                 switch (type_basic_get_type( var->type ))
1270                 {
1271                 /* floating point arguments are not supported in Oi mode */
1272                 case TYPE_BASIC_FLOAT:  return 0;
1273                 case TYPE_BASIC_DOUBLE: return 0;
1274                 default: break;
1275                 }
1276                 break;
1277             /* unions passed by value are not supported in Oi mode */
1278             case TYPE_UNION: return 0;
1279             case TYPE_ENCAPSULATED_UNION: return 0;
1280             default: break;
1281             }
1282     }
1283
1284     if ((str = get_attrp( func->attrs, ATTR_OPTIMIZE ))) return !strcmp( str, "i" );
1285     if ((str = get_attrp( iface->attrs, ATTR_OPTIMIZE ))) return !strcmp( str, "i" );
1286     return (get_stub_mode() != MODE_Os);
1287 }
1288
1289 static void write_proc_func_header( FILE *file, int indent, const type_t *iface,
1290                                     const var_t *func, unsigned int *offset,
1291                                     unsigned short num_proc )
1292 {
1293     var_t *var;
1294     var_list_t *args = type_get_function_args( func->type );
1295     unsigned char explicit_fc, implicit_fc;
1296     unsigned char handle_flags;
1297     const var_t *handle_var = get_func_handle_var( iface, func, &explicit_fc, &implicit_fc );
1298     unsigned char oi_flags = RPC_FC_PROC_OIF_RPCFLAGS | RPC_FC_PROC_OIF_NEWINIT;
1299     unsigned int rpc_flags = get_rpc_flags( func->attrs );
1300     unsigned int nb_args = 0;
1301     unsigned int stack_size = 0;
1302     unsigned short param_num = 0;
1303     unsigned short handle_stack_offset = 0;
1304     unsigned short handle_param_num = 0;
1305
1306     if (is_full_pointer_function( func )) oi_flags |= RPC_FC_PROC_OIF_FULLPTR;
1307     if (is_object( iface ))
1308     {
1309         oi_flags |= RPC_FC_PROC_OIF_OBJECT;
1310         if (get_stub_mode() == MODE_Oif) oi_flags |= RPC_FC_PROC_OIF_OBJ_V2;
1311         stack_size += pointer_size;
1312     }
1313
1314     if (args) LIST_FOR_EACH_ENTRY( var, args, var_t, entry )
1315     {
1316         if (var == handle_var)
1317         {
1318             handle_stack_offset = stack_size;
1319             handle_param_num = param_num;
1320         }
1321         stack_size += get_stack_size( var->type, var->attrs, NULL );
1322         param_num++;
1323         nb_args++;
1324     }
1325     if (!is_void( type_function_get_rettype( func->type )))
1326     {
1327         stack_size += pointer_size;
1328         nb_args++;
1329     }
1330
1331     print_file( file, 0, "/* %u (procedure %s::%s) */\n", *offset, iface->name, func->name );
1332     print_file( file, indent, "0x%02x,\t/* %s */\n", implicit_fc,
1333                 implicit_fc ? string_of_type(implicit_fc) : "explicit handle" );
1334     print_file( file, indent, "0x%02x,\n", oi_flags );
1335     print_file( file, indent, "NdrFcLong(0x%x),\n", rpc_flags );
1336     print_file( file, indent, "NdrFcShort(0x%hx),\t/* method %hu */\n", num_proc, num_proc );
1337     print_file( file, indent, "NdrFcShort(0x%hx),\t/* stack size = %hu */\n", stack_size, stack_size );
1338     *offset += 10;
1339
1340     if (!implicit_fc)
1341     {
1342         switch (explicit_fc)
1343         {
1344         case RPC_FC_BIND_PRIMITIVE:
1345             handle_flags = 0;
1346             print_file( file, indent, "0x%02x,\t/* %s */\n", explicit_fc, string_of_type(explicit_fc) );
1347             print_file( file, indent, "0x%02x,\n", handle_flags );
1348             print_file( file, indent, "NdrFcShort(0x%hx),\t/* stack offset = %hu */\n",
1349                         handle_stack_offset, handle_stack_offset );
1350             *offset += 4;
1351             break;
1352         case RPC_FC_BIND_GENERIC:
1353             handle_flags = type_memsize( handle_var->type );
1354             print_file( file, indent, "0x%02x,\t/* %s */\n", explicit_fc, string_of_type(explicit_fc) );
1355             print_file( file, indent, "0x%02x,\n", handle_flags );
1356             print_file( file, indent, "NdrFcShort(0x%hx),\t/* stack offset = %hu */\n",
1357                         handle_stack_offset, handle_stack_offset );
1358             print_file( file, indent, "0x%02x,\n", get_generic_handle_offset( handle_var->type ) );
1359             print_file( file, indent, "0x%x,\t/* FC_PAD */\n", RPC_FC_PAD);
1360             *offset += 6;
1361             break;
1362         case RPC_FC_BIND_CONTEXT:
1363             handle_flags = get_contexthandle_flags( iface, handle_var->attrs, handle_var->type );
1364             print_file( file, indent, "0x%02x,\t/* %s */\n", explicit_fc, string_of_type(explicit_fc) );
1365             print_file( file, indent, "0x%02x,\n", handle_flags );
1366             print_file( file, indent, "NdrFcShort(0x%hx),\t/* stack offset = %hu */\n",
1367                         handle_stack_offset, handle_stack_offset );
1368             print_file( file, indent, "0x%02x,\n", get_context_handle_offset( handle_var->type ) );
1369             print_file( file, indent, "0x%02x,\t/* param %hu */\n", handle_param_num, handle_param_num );
1370             *offset += 6;
1371             break;
1372         }
1373     }
1374
1375     if (get_stub_mode() == MODE_Oif)
1376     {
1377         unsigned char oi2_flags = get_func_oi2_flags( func );
1378         unsigned char ext_flags = 0;
1379         unsigned int size;
1380
1381         if (is_attr( func->attrs, ATTR_NOTIFY )) ext_flags |= 0x08;  /* HasNotify */
1382         if (is_attr( func->attrs, ATTR_NOTIFYFLAG )) ext_flags |= 0x10;  /* HasNotify2 */
1383
1384         size = get_function_buffer_size( func, PASS_IN );
1385         print_file( file, indent, "NdrFcShort(0x%x),\t/* client buffer = %hu */\n", size, size );
1386         size = get_function_buffer_size( func, PASS_OUT );
1387         print_file( file, indent, "NdrFcShort(0x%x),\t/* server buffer = %hu */\n", size, size );
1388         print_file( file, indent, "0x%02x,\n", oi2_flags );
1389         print_file( file, indent, "0x%02x,\t/* %u params */\n", nb_args, nb_args );
1390         print_file( file, indent, "0x%02x,\n", pointer_size == 8 ? 10 : 8 );
1391         print_file( file, indent, "0x%02x,\n", ext_flags );
1392         print_file( file, indent, "NdrFcShort(0x0),\n" );  /* server corr hint */
1393         print_file( file, indent, "NdrFcShort(0x0),\n" );  /* client corr hint */
1394         print_file( file, indent, "NdrFcShort(0x0),\n" );  /* FIXME: notify index */
1395         *offset += 14;
1396         if (pointer_size == 8)
1397         {
1398             unsigned short pos = 0, fpu_mask = 0;
1399
1400             if (is_object( iface )) pos += 2;
1401             if (args) LIST_FOR_EACH_ENTRY( var, args, var_t, entry )
1402             {
1403                 if (type_get_type( var->type ) == TYPE_BASIC)
1404                 {
1405                     switch (type_basic_get_type( var->type ))
1406                     {
1407                     case TYPE_BASIC_FLOAT:  fpu_mask |= 1 << pos; break;
1408                     case TYPE_BASIC_DOUBLE: fpu_mask |= 2 << pos; break;
1409                     default: break;
1410                     }
1411                 }
1412                 pos += 2;
1413                 if (pos >= 16) break;
1414             }
1415             print_file( file, indent, "NdrFcShort(0x%x),\n", fpu_mask );  /* floating point mask */
1416             *offset += 2;
1417         }
1418     }
1419 }
1420
1421 static void write_procformatstring_func( FILE *file, int indent, const type_t *iface,
1422                                          const var_t *func, unsigned int *offset,
1423                                          unsigned short num_proc )
1424 {
1425     unsigned int stack_offset = is_object( iface ) ? pointer_size : 0;
1426     int is_interpreted = is_interpreted_func( iface, func );
1427     int is_new_style = is_interpreted && (get_stub_mode() == MODE_Oif);
1428
1429     if (is_interpreted) write_proc_func_header( file, indent, iface, func, offset, num_proc );
1430
1431     /* emit argument data */
1432     if (type_get_function_args(func->type))
1433     {
1434         const var_t *var;
1435         LIST_FOR_EACH_ENTRY( var, type_get_function_args(func->type), const var_t, entry )
1436         {
1437             print_file( file, 0, "/* %u (parameter %s) */\n", *offset, var->name );
1438             if (is_new_style)
1439                 *offset += write_new_procformatstring_type(file, indent, var->type, var->attrs,
1440                                                            FALSE, &stack_offset);
1441             else
1442                 *offset += write_old_procformatstring_type(file, indent, var->type, var->attrs,
1443                                                            FALSE, is_interpreted);
1444         }
1445     }
1446
1447     /* emit return value data */
1448     if (is_void(type_function_get_rettype(func->type)))
1449     {
1450         if (!is_new_style)
1451         {
1452             print_file(file, 0, "/* %u (void) */\n", *offset);
1453             print_file(file, indent, "0x5b,    /* FC_END */\n");
1454             print_file(file, indent, "0x5c,    /* FC_PAD */\n");
1455             *offset += 2;
1456         }
1457     }
1458     else
1459     {
1460         print_file( file, 0, "/* %u (return value) */\n", *offset );
1461         if (is_new_style)
1462             *offset += write_new_procformatstring_type(file, indent, type_function_get_rettype(func->type),
1463                                                        NULL, TRUE, &stack_offset);
1464         else
1465             *offset += write_old_procformatstring_type(file, indent, type_function_get_rettype(func->type),
1466                                                        NULL, TRUE, is_interpreted);
1467     }
1468 }
1469
1470 static void write_procformatstring_stmts(FILE *file, int indent, const statement_list_t *stmts,
1471                                          type_pred_t pred, unsigned int *offset)
1472 {
1473     const statement_t *stmt;
1474     if (stmts) LIST_FOR_EACH_ENTRY( stmt, stmts, const statement_t, entry )
1475     {
1476         if (stmt->type == STMT_TYPE && type_get_type(stmt->u.type) == TYPE_INTERFACE)
1477         {
1478             const statement_t *stmt_func;
1479             const type_t *iface = stmt->u.type;
1480             const type_t *parent = type_iface_get_inherit( iface );
1481             int count = parent ? count_methods( parent ) : 0;
1482
1483             if (!pred(iface)) continue;
1484             STATEMENTS_FOR_EACH_FUNC(stmt_func, type_iface_get_stmts(iface))
1485             {
1486                 var_t *func = stmt_func->u.var;
1487                 if (is_local(func->attrs)) continue;
1488                 write_procformatstring_func( file, indent, iface, func, offset, count++ );
1489             }
1490         }
1491         else if (stmt->type == STMT_LIBRARY)
1492             write_procformatstring_stmts(file, indent, stmt->u.lib->stmts, pred, offset);
1493     }
1494 }
1495
1496 void write_procformatstring(FILE *file, const statement_list_t *stmts, type_pred_t pred)
1497 {
1498     int indent = 0;
1499     unsigned int offset = 0;
1500
1501     print_file(file, indent, "static const MIDL_PROC_FORMAT_STRING __MIDL_ProcFormatString =\n");
1502     print_file(file, indent, "{\n");
1503     indent++;
1504     print_file(file, indent, "0,\n");
1505     print_file(file, indent, "{\n");
1506     indent++;
1507
1508     write_procformatstring_stmts(file, indent, stmts, pred, &offset);
1509
1510     print_file(file, indent, "0x0\n");
1511     indent--;
1512     print_file(file, indent, "}\n");
1513     indent--;
1514     print_file(file, indent, "};\n");
1515     print_file(file, indent, "\n");
1516 }
1517
1518 void write_procformatstring_offsets( FILE *file, const type_t *iface )
1519 {
1520     const statement_t *stmt;
1521     int indent = 0;
1522
1523     print_file( file, indent,  "static const unsigned short %s_FormatStringOffsetTable[] =\n",
1524                 iface->name );
1525     print_file( file, indent,  "{\n" );
1526     indent++;
1527     STATEMENTS_FOR_EACH_FUNC( stmt, type_iface_get_stmts(iface) )
1528     {
1529         var_t *func = stmt->u.var;
1530         if (is_local( func->attrs )) continue;
1531         print_file( file, indent,  "%u,  /* %s */\n", func->procstring_offset, func->name );
1532     }
1533     indent--;
1534     print_file( file, indent,  "};\n\n" );
1535 }
1536
1537 static int write_base_type(FILE *file, const type_t *type, unsigned int *typestring_offset)
1538 {
1539     unsigned char fc;
1540
1541     if (type_get_type(type) == TYPE_BASIC)
1542         fc = get_basic_fc_signed(type);
1543     else if (type_get_type(type) == TYPE_ENUM)
1544         fc = get_enum_fc(type);
1545     else
1546         return 0;
1547
1548     print_file(file, 2, "0x%02x,\t/* %s */\n", fc, string_of_type(fc));
1549     *typestring_offset += 1;
1550     return 1;
1551 }
1552
1553 /* write conformance / variance descriptor */
1554 static unsigned int write_conf_or_var_desc(FILE *file, const type_t *cont_type,
1555                                            unsigned int baseoff, const type_t *type,
1556                                            const expr_t *expr)
1557 {
1558     unsigned char operator_type = 0;
1559     unsigned char conftype = RPC_FC_NORMAL_CONFORMANCE;
1560     const char *conftype_string = "field";
1561     const expr_t *subexpr;
1562     const type_t *iface = NULL;
1563     const char *name;
1564
1565     if (!expr)
1566     {
1567         print_file(file, 2, "NdrFcLong(0xffffffff),\t/* -1 */\n");
1568         return 4;
1569     }
1570
1571     if (expr->is_const)
1572     {
1573         if (expr->cval > UCHAR_MAX * (USHRT_MAX + 1) + USHRT_MAX)
1574             error("write_conf_or_var_desc: constant value %d is greater than "
1575                   "the maximum constant size of %d\n", expr->cval,
1576                   UCHAR_MAX * (USHRT_MAX + 1) + USHRT_MAX);
1577
1578         print_file(file, 2, "0x%x, /* Corr desc: constant, val = %d */\n",
1579                    RPC_FC_CONSTANT_CONFORMANCE, expr->cval);
1580         print_file(file, 2, "0x%x,\n", expr->cval >> 16);
1581         print_file(file, 2, "NdrFcShort(0x%hx),\n", (unsigned short)expr->cval);
1582
1583         return 4;
1584     }
1585
1586     if (!cont_type)  /* top-level conformance */
1587     {
1588         conftype = RPC_FC_TOP_LEVEL_CONFORMANCE;
1589         conftype_string = "parameter";
1590         cont_type = current_func->type;
1591         name = current_func->name;
1592         iface = current_iface;
1593     }
1594     else
1595     {
1596         name = cont_type->name;
1597         if (is_ptr(type) || (is_array(type) && type_array_is_decl_as_ptr(type)))
1598         {
1599             conftype = RPC_FC_POINTER_CONFORMANCE;
1600             conftype_string = "field pointer";
1601         }
1602     }
1603
1604     subexpr = expr;
1605     switch (subexpr->type)
1606     {
1607     case EXPR_PPTR:
1608         subexpr = subexpr->ref;
1609         operator_type = RPC_FC_DEREFERENCE;
1610         break;
1611     case EXPR_DIV:
1612         if (subexpr->u.ext->is_const && (subexpr->u.ext->cval == 2))
1613         {
1614             subexpr = subexpr->ref;
1615             operator_type = RPC_FC_DIV_2;
1616         }
1617         break;
1618     case EXPR_MUL:
1619         if (subexpr->u.ext->is_const && (subexpr->u.ext->cval == 2))
1620         {
1621             subexpr = subexpr->ref;
1622             operator_type = RPC_FC_MULT_2;
1623         }
1624         break;
1625     case EXPR_SUB:
1626         if (subexpr->u.ext->is_const && (subexpr->u.ext->cval == 1))
1627         {
1628             subexpr = subexpr->ref;
1629             operator_type = RPC_FC_SUB_1;
1630         }
1631         break;
1632     case EXPR_ADD:
1633         if (subexpr->u.ext->is_const && (subexpr->u.ext->cval == 1))
1634         {
1635             subexpr = subexpr->ref;
1636             operator_type = RPC_FC_ADD_1;
1637         }
1638         break;
1639     default:
1640         break;
1641     }
1642
1643     if (subexpr->type == EXPR_IDENTIFIER)
1644     {
1645         const type_t *correlation_variable = NULL;
1646         unsigned char param_type = 0;
1647         unsigned int offset = 0;
1648         const var_t *var;
1649         struct expr_loc expr_loc;
1650
1651         if (type_get_type(cont_type) == TYPE_FUNCTION)
1652         {
1653             var_list_t *args = type_get_function_args( cont_type );
1654
1655             if (is_object( iface )) offset += pointer_size;
1656             if (args) LIST_FOR_EACH_ENTRY( var, args, const var_t, entry )
1657             {
1658                 if (var->name && !strcmp(var->name, subexpr->u.sval))
1659                 {
1660                     expr_loc.v = var;
1661                     correlation_variable = var->type;
1662                     break;
1663                 }
1664                 offset += get_stack_size( var->type, var->attrs, NULL );
1665             }
1666         }
1667         else
1668         {
1669             var_list_t *fields = type_struct_get_fields( cont_type );
1670
1671             if (fields) LIST_FOR_EACH_ENTRY( var, fields, const var_t, entry )
1672             {
1673                 unsigned int size = field_memsize( var->type, &offset );
1674                 if (var->name && !strcmp(var->name, subexpr->u.sval))
1675                 {
1676                     expr_loc.v = var;
1677                     correlation_variable = var->type;
1678                     break;
1679                 }
1680                 offset += size;
1681             }
1682         }
1683
1684         if (!correlation_variable)
1685             error("write_conf_or_var_desc: couldn't find variable %s in %s\n", subexpr->u.sval, name);
1686         expr_loc.attr = NULL;
1687         correlation_variable = expr_resolve_type(&expr_loc, cont_type, expr);
1688
1689         offset -= baseoff;
1690
1691         if (type_get_type(correlation_variable) == TYPE_BASIC)
1692         {
1693             switch (get_basic_fc(correlation_variable))
1694             {
1695             case RPC_FC_CHAR:
1696             case RPC_FC_SMALL:
1697                 param_type = RPC_FC_SMALL;
1698                 break;
1699             case RPC_FC_BYTE:
1700             case RPC_FC_USMALL:
1701                 param_type = RPC_FC_USMALL;
1702                 break;
1703             case RPC_FC_WCHAR:
1704             case RPC_FC_SHORT:
1705                 param_type = RPC_FC_SHORT;
1706                 break;
1707             case RPC_FC_USHORT:
1708                 param_type = RPC_FC_USHORT;
1709                 break;
1710             case RPC_FC_LONG:
1711                 param_type = RPC_FC_LONG;
1712                 break;
1713             case RPC_FC_ULONG:
1714                 param_type = RPC_FC_ULONG;
1715                 break;
1716             default:
1717                 error("write_conf_or_var_desc: conformance variable type not supported 0x%x\n",
1718                       get_basic_fc(correlation_variable));
1719             }
1720         }
1721         else if (type_get_type(correlation_variable) == TYPE_ENUM)
1722         {
1723             if (get_enum_fc(correlation_variable) == RPC_FC_ENUM32)
1724                 param_type = RPC_FC_LONG;
1725             else
1726                 param_type = RPC_FC_SHORT;
1727         }
1728         else if (type_get_type(correlation_variable) == TYPE_POINTER)
1729         {
1730             if (pointer_size == 8)
1731                 param_type = RPC_FC_HYPER;
1732             else
1733                 param_type = RPC_FC_LONG;
1734         }
1735         else
1736         {
1737             error("write_conf_or_var_desc: non-arithmetic type used as correlation variable %s\n",
1738                   subexpr->u.sval);
1739             return 0;
1740         }
1741
1742         print_file(file, 2, "0x%x,\t/* Corr desc: %s %s, %s */\n",
1743                    conftype | param_type, conftype_string, subexpr->u.sval, string_of_type(param_type));
1744         print_file(file, 2, "0x%x,\t/* %s */\n", operator_type,
1745                    operator_type ? string_of_type(operator_type) : "no operators");
1746         print_file(file, 2, "NdrFcShort(0x%hx),\t/* offset = %d */\n",
1747                    (unsigned short)offset, offset);
1748     }
1749     else if (!iface || is_interpreted_func( iface, current_func ))
1750     {
1751         unsigned int callback_offset = 0;
1752         struct expr_eval_routine *eval;
1753         int found = 0;
1754
1755         LIST_FOR_EACH_ENTRY(eval, &expr_eval_routines, struct expr_eval_routine, entry)
1756         {
1757             if (eval->cont_type == cont_type ||
1758                 (type_get_type( eval->cont_type ) == type_get_type( cont_type ) &&
1759                  eval->iface == iface &&
1760                  eval->name && name && !strcmp(eval->name, name) &&
1761                  !compare_expr(eval->expr, expr)))
1762             {
1763                 found = 1;
1764                 break;
1765             }
1766             callback_offset++;
1767         }
1768
1769         if (!found)
1770         {
1771             eval = xmalloc (sizeof(*eval));
1772             eval->iface = iface;
1773             eval->cont_type = cont_type;
1774             eval->name = xstrdup( name );
1775             eval->baseoff = baseoff;
1776             eval->expr = expr;
1777             list_add_tail (&expr_eval_routines, &eval->entry);
1778         }
1779
1780         if (callback_offset > USHRT_MAX)
1781             error("Maximum number of callback routines reached\n");
1782
1783         print_file(file, 2, "0x%x,\t/* Corr desc: %s in %s */\n", conftype, conftype_string, name);
1784         print_file(file, 2, "0x%x,\t/* %s */\n", RPC_FC_CALLBACK, "FC_CALLBACK");
1785         print_file(file, 2, "NdrFcShort(0x%hx),\t/* %u */\n", (unsigned short)callback_offset, callback_offset);
1786     }
1787     else  /* output a dummy corr desc that isn't used */
1788     {
1789         print_file(file, 2, "0x%x,\t/* Corr desc: unused for %s */\n", conftype, name);
1790         print_file(file, 2, "0x0,\n" );
1791         print_file(file, 2, "NdrFcShort(0x0),\n" );
1792     }
1793     return 4;
1794 }
1795
1796 /* return size and start offset of a data field based on current offset */
1797 static unsigned int field_memsize(const type_t *type, unsigned int *offset)
1798 {
1799     unsigned int align = 0;
1800     unsigned int size = type_memsize_and_alignment( type, &align );
1801
1802     *offset = ROUND_SIZE( *offset, align );
1803     return size;
1804 }
1805
1806 static unsigned int fields_memsize(const var_list_t *fields, unsigned int *align)
1807 {
1808     unsigned int size = 0;
1809     unsigned int max_align;
1810     const var_t *v;
1811
1812     if (!fields) return 0;
1813     LIST_FOR_EACH_ENTRY( v, fields, const var_t, entry )
1814     {
1815         unsigned int falign = 0;
1816         unsigned int fsize = type_memsize_and_alignment(v->type, &falign);
1817         if (*align < falign) *align = falign;
1818         falign = clamp_align(falign);
1819         size = ROUND_SIZE(size, falign);
1820         size += fsize;
1821     }
1822
1823     max_align = clamp_align(*align);
1824     size = ROUND_SIZE(size, max_align);
1825
1826     return size;
1827 }
1828
1829 static unsigned int union_memsize(const var_list_t *fields, unsigned int *pmaxa)
1830 {
1831     unsigned int size, maxs = 0;
1832     unsigned int align = *pmaxa;
1833     const var_t *v;
1834
1835     if (fields) LIST_FOR_EACH_ENTRY( v, fields, const var_t, entry )
1836     {
1837         /* we could have an empty default field with NULL type */
1838         if (v->type)
1839         {
1840             size = type_memsize_and_alignment(v->type, &align);
1841             if (maxs < size) maxs = size;
1842             if (*pmaxa < align) *pmaxa = align;
1843         }
1844     }
1845
1846     return maxs;
1847 }
1848
1849 static unsigned int type_memsize_and_alignment(const type_t *t, unsigned int *align)
1850 {
1851     unsigned int size = 0;
1852
1853     switch (type_get_type(t))
1854     {
1855     case TYPE_BASIC:
1856         switch (get_basic_fc(t))
1857         {
1858         case RPC_FC_BYTE:
1859         case RPC_FC_CHAR:
1860         case RPC_FC_USMALL:
1861         case RPC_FC_SMALL:
1862             size = 1;
1863             if (size > *align) *align = size;
1864             break;
1865         case RPC_FC_WCHAR:
1866         case RPC_FC_USHORT:
1867         case RPC_FC_SHORT:
1868             size = 2;
1869             if (size > *align) *align = size;
1870             break;
1871         case RPC_FC_ULONG:
1872         case RPC_FC_LONG:
1873         case RPC_FC_ERROR_STATUS_T:
1874         case RPC_FC_FLOAT:
1875             size = 4;
1876             if (size > *align) *align = size;
1877             break;
1878         case RPC_FC_HYPER:
1879         case RPC_FC_DOUBLE:
1880             size = 8;
1881             if (size > *align) *align = size;
1882             break;
1883         case RPC_FC_INT3264:
1884         case RPC_FC_UINT3264:
1885         case RPC_FC_BIND_PRIMITIVE:
1886             assert( pointer_size );
1887             size = pointer_size;
1888             if (size > *align) *align = size;
1889             break;
1890         default:
1891             error("type_memsize: Unknown type 0x%x\n", get_basic_fc(t));
1892             size = 0;
1893         }
1894         break;
1895     case TYPE_ENUM:
1896         switch (get_enum_fc(t))
1897         {
1898         case RPC_FC_ENUM16:
1899         case RPC_FC_ENUM32:
1900             size = 4;
1901             if (size > *align) *align = size;
1902             break;
1903         default:
1904             error("type_memsize: Unknown enum type\n");
1905             size = 0;
1906         }
1907         break;
1908     case TYPE_STRUCT:
1909         size = fields_memsize(type_struct_get_fields(t), align);
1910         break;
1911     case TYPE_ENCAPSULATED_UNION:
1912         size = fields_memsize(type_encapsulated_union_get_fields(t), align);
1913         break;
1914     case TYPE_UNION:
1915         size = union_memsize(type_union_get_cases(t), align);
1916         break;
1917     case TYPE_POINTER:
1918         assert( pointer_size );
1919         size = pointer_size;
1920         if (size > *align) *align = size;
1921         break;
1922     case TYPE_ARRAY:
1923         if (!type_array_is_decl_as_ptr(t))
1924         {
1925             if (is_conformant_array(t))
1926             {
1927                 type_memsize_and_alignment(type_array_get_element(t), align);
1928                 size = 0;
1929             }
1930             else
1931                 size = type_array_get_dim(t) *
1932                     type_memsize_and_alignment(type_array_get_element(t), align);
1933         }
1934         else /* declared as a pointer */
1935         {
1936             assert( pointer_size );
1937             size = pointer_size;
1938             if (size > *align) *align = size;
1939         }
1940         break;
1941     case TYPE_INTERFACE:
1942     case TYPE_ALIAS:
1943     case TYPE_VOID:
1944     case TYPE_COCLASS:
1945     case TYPE_MODULE:
1946     case TYPE_FUNCTION:
1947     case TYPE_BITFIELD:
1948         /* these types should not be encountered here due to language
1949          * restrictions (interface, void, coclass, module), logical
1950          * restrictions (alias - due to type_get_type call above) or
1951          * checking restrictions (function, bitfield). */
1952         assert(0);
1953     }
1954
1955     return size;
1956 }
1957
1958 unsigned int type_memsize(const type_t *t)
1959 {
1960     unsigned int align = 0;
1961     return type_memsize_and_alignment( t, &align );
1962 }
1963
1964 static unsigned int type_buffer_alignment(const type_t *t)
1965 {
1966     const var_list_t *fields;
1967     const var_t *var;
1968     unsigned int max = 0, align;
1969
1970     switch (type_get_type(t))
1971     {
1972     case TYPE_BASIC:
1973         switch (get_basic_fc(t))
1974         {
1975         case RPC_FC_BYTE:
1976         case RPC_FC_CHAR:
1977         case RPC_FC_USMALL:
1978         case RPC_FC_SMALL:
1979             return 1;
1980         case RPC_FC_WCHAR:
1981         case RPC_FC_USHORT:
1982         case RPC_FC_SHORT:
1983             return 2;
1984         case RPC_FC_ULONG:
1985         case RPC_FC_LONG:
1986         case RPC_FC_ERROR_STATUS_T:
1987         case RPC_FC_FLOAT:
1988         case RPC_FC_INT3264:
1989         case RPC_FC_UINT3264:
1990             return 4;
1991         case RPC_FC_HYPER:
1992         case RPC_FC_DOUBLE:
1993             return 8;
1994         default:
1995             error("type_buffer_alignment: Unknown type 0x%x\n", get_basic_fc(t));
1996         }
1997         break;
1998     case TYPE_ENUM:
1999         switch (get_enum_fc(t))
2000         {
2001         case RPC_FC_ENUM16:
2002             return 2;
2003         case RPC_FC_ENUM32:
2004             return 4;
2005         default:
2006             error("type_buffer_alignment: Unknown enum type\n");
2007         }
2008         break;
2009     case TYPE_STRUCT:
2010         if (!(fields = type_struct_get_fields(t))) break;
2011         LIST_FOR_EACH_ENTRY( var, fields, const var_t, entry )
2012         {
2013             if (!var->type) continue;
2014             align = type_buffer_alignment( var->type );
2015             if (max < align) max = align;
2016         }
2017         break;
2018     case TYPE_ENCAPSULATED_UNION:
2019         if (!(fields = type_encapsulated_union_get_fields(t))) break;
2020         LIST_FOR_EACH_ENTRY( var, fields, const var_t, entry )
2021         {
2022             if (!var->type) continue;
2023             align = type_buffer_alignment( var->type );
2024             if (max < align) max = align;
2025         }
2026         break;
2027     case TYPE_UNION:
2028         if (!(fields = type_union_get_cases(t))) break;
2029         LIST_FOR_EACH_ENTRY( var, fields, const var_t, entry )
2030         {
2031             if (!var->type) continue;
2032             align = type_buffer_alignment( var->type );
2033             if (max < align) max = align;
2034         }
2035         break;
2036     case TYPE_ARRAY:
2037         if (!type_array_is_decl_as_ptr(t))
2038             return type_buffer_alignment( type_array_get_element(t) );
2039         /* else fall through */
2040     case TYPE_POINTER:
2041         return 4;
2042     case TYPE_INTERFACE:
2043     case TYPE_ALIAS:
2044     case TYPE_VOID:
2045     case TYPE_COCLASS:
2046     case TYPE_MODULE:
2047     case TYPE_FUNCTION:
2048     case TYPE_BITFIELD:
2049         /* these types should not be encountered here due to language
2050          * restrictions (interface, void, coclass, module), logical
2051          * restrictions (alias - due to type_get_type call above) or
2052          * checking restrictions (function, bitfield). */
2053         assert(0);
2054     }
2055     return max;
2056 }
2057
2058 int is_full_pointer_function(const var_t *func)
2059 {
2060     const var_t *var;
2061     if (type_has_full_pointer(type_function_get_rettype(func->type), func->attrs, TRUE))
2062         return TRUE;
2063     if (!type_get_function_args(func->type))
2064         return FALSE;
2065     LIST_FOR_EACH_ENTRY( var, type_get_function_args(func->type), const var_t, entry )
2066         if (type_has_full_pointer( var->type, var->attrs, TRUE ))
2067             return TRUE;
2068     return FALSE;
2069 }
2070
2071 void write_full_pointer_init(FILE *file, int indent, const var_t *func, int is_server)
2072 {
2073     print_file(file, indent, "__frame->_StubMsg.FullPtrXlatTables = NdrFullPointerXlatInit(0,%s);\n",
2074                    is_server ? "XLAT_SERVER" : "XLAT_CLIENT");
2075     fprintf(file, "\n");
2076 }
2077
2078 void write_full_pointer_free(FILE *file, int indent, const var_t *func)
2079 {
2080     print_file(file, indent, "NdrFullPointerXlatFree(__frame->_StubMsg.FullPtrXlatTables);\n");
2081     fprintf(file, "\n");
2082 }
2083
2084 static unsigned int write_nonsimple_pointer(FILE *file, const attr_list_t *attrs,
2085                                             const type_t *type,
2086                                             enum type_context context,
2087                                             unsigned int offset,
2088                                             unsigned int *typeformat_offset)
2089 {
2090     unsigned int start_offset = *typeformat_offset;
2091     short reloff = offset - (*typeformat_offset + 2);
2092     int in_attr, out_attr;
2093     int pointer_type;
2094     unsigned char flags = 0;
2095
2096     pointer_type = get_pointer_fc_context(type, attrs, context);
2097
2098     in_attr = is_attr(attrs, ATTR_IN);
2099     out_attr = is_attr(attrs, ATTR_OUT);
2100     if (!in_attr && !out_attr) in_attr = 1;
2101
2102     if (out_attr && !in_attr && pointer_type == RPC_FC_RP)
2103         flags |= RPC_FC_P_ONSTACK;
2104
2105     if (is_ptr(type))
2106     {
2107         type_t *ref = type_pointer_get_ref(type);
2108         if(is_declptr(ref) && !is_user_type(ref))
2109             flags |= RPC_FC_P_DEREF;
2110     }
2111
2112     print_file(file, 2, "0x%x, 0x%x,\t\t/* %s",
2113                pointer_type,
2114                flags,
2115                string_of_type(pointer_type));
2116     if (file)
2117     {
2118         if (flags & RPC_FC_P_ONSTACK)
2119             fprintf(file, " [allocated_on_stack]");
2120         if (flags & RPC_FC_P_DEREF)
2121             fprintf(file, " [pointer_deref]");
2122         fprintf(file, " */\n");
2123     }
2124
2125     print_file(file, 2, "NdrFcShort(0x%hx),\t/* Offset= %hd (%u) */\n", reloff, reloff, offset);
2126     *typeformat_offset += 4;
2127
2128     return start_offset;
2129 }
2130
2131 static unsigned int write_simple_pointer(FILE *file, const attr_list_t *attrs,
2132                                          const type_t *type, enum type_context context)
2133 {
2134     unsigned char fc;
2135     unsigned char pointer_fc;
2136     const type_t *ref;
2137     int in_attr = is_attr(attrs, ATTR_IN);
2138     int out_attr = is_attr(attrs, ATTR_OUT);
2139     unsigned char flags = RPC_FC_P_SIMPLEPOINTER;
2140
2141     /* for historical reasons, write_simple_pointer also handled string types,
2142      * but no longer does. catch bad uses of the function with this check */
2143     if (is_string_type(attrs, type))
2144         error("write_simple_pointer: can't handle type %s which is a string type\n", type->name);
2145
2146     pointer_fc = get_pointer_fc_context(type, attrs, context);
2147
2148     ref = type_pointer_get_ref(type);
2149     if (type_get_type(ref) == TYPE_ENUM)
2150         fc = get_enum_fc(ref);
2151     else
2152         fc = get_basic_fc(ref);
2153
2154     if (out_attr && !in_attr)
2155         flags |= RPC_FC_P_ONSTACK;
2156
2157     print_file(file, 2, "0x%02x, 0x%x,\t/* %s %s[simple_pointer] */\n",
2158                pointer_fc, flags, string_of_type(pointer_fc),
2159                flags & RPC_FC_P_ONSTACK ? "[allocated_on_stack] " : "");
2160     print_file(file, 2, "0x%02x,\t/* %s */\n", fc, string_of_type(fc));
2161     print_file(file, 2, "0x5c,\t/* FC_PAD */\n");
2162     return 4;
2163 }
2164
2165 static void print_start_tfs_comment(FILE *file, type_t *t, unsigned int tfsoff)
2166 {
2167     print_file(file, 0, "/* %u (", tfsoff);
2168     write_type_decl(file, t, NULL);
2169     print_file(file, 0, ") */\n");
2170 }
2171
2172 static unsigned int write_pointer_tfs(FILE *file, const attr_list_t *attrs,
2173                                       type_t *type, unsigned int ref_offset,
2174                                       enum type_context context,
2175                                       unsigned int *typestring_offset)
2176 {
2177     unsigned int offset = *typestring_offset;
2178     type_t *ref = type_pointer_get_ref(type);
2179
2180     print_start_tfs_comment(file, type, offset);
2181     update_tfsoff(type, offset, file);
2182
2183     switch (typegen_detect_type(ref, attrs, TDT_ALL_TYPES))
2184     {
2185     case TGT_BASIC:
2186     case TGT_ENUM:
2187         *typestring_offset += write_simple_pointer(file, attrs, type, context);
2188         break;
2189     default:
2190         if (ref_offset)
2191             write_nonsimple_pointer(file, attrs, type, context, ref_offset, typestring_offset);
2192         break;
2193     }
2194
2195     return offset;
2196 }
2197
2198 static int processed(const type_t *type)
2199 {
2200     return type->typestring_offset && !type->tfswrite;
2201 }
2202
2203 static int user_type_has_variable_size(const type_t *t)
2204 {
2205     if (is_ptr(t))
2206         return TRUE;
2207     else if (type_get_type(t) == TYPE_STRUCT)
2208     {
2209         switch (get_struct_fc(t))
2210         {
2211         case RPC_FC_PSTRUCT:
2212         case RPC_FC_CSTRUCT:
2213         case RPC_FC_CPSTRUCT:
2214         case RPC_FC_CVSTRUCT:
2215             return TRUE;
2216         }
2217     }
2218     /* Note: Since this only applies to user types, we can't have a conformant
2219        array here, and strings should get filed under pointer in this case.  */
2220     return FALSE;
2221 }
2222
2223 static unsigned int write_user_tfs(FILE *file, type_t *type, unsigned int *tfsoff)
2224 {
2225     unsigned int start, absoff, flags;
2226     const char *name = NULL;
2227     type_t *utype = get_user_type(type, &name);
2228     unsigned int usize = type_memsize(utype);
2229     unsigned int ualign = type_buffer_alignment(utype);
2230     unsigned int size = type_memsize(type);
2231     unsigned short funoff = user_type_offset(name);
2232     short reloff;
2233
2234     if (processed(type)) return type->typestring_offset;
2235
2236     guard_rec(type);
2237
2238     if(user_type_has_variable_size(utype)) usize = 0;
2239
2240     if (type_get_type(utype) == TYPE_BASIC ||
2241         type_get_type(utype) == TYPE_ENUM)
2242     {
2243         unsigned char fc;
2244
2245         if (type_get_type(utype) == TYPE_ENUM)
2246             fc = get_enum_fc(utype);
2247         else
2248             fc = get_basic_fc(utype);
2249
2250         absoff = *tfsoff;
2251         print_start_tfs_comment(file, utype, absoff);
2252         print_file(file, 2, "0x%x,\t/* %s */\n", fc, string_of_type(fc));
2253         print_file(file, 2, "0x5c,\t/* FC_PAD */\n");
2254         *tfsoff += 2;
2255     }
2256     else
2257     {
2258         if (!processed(utype))
2259             write_embedded_types(file, NULL, utype, utype->name, TRUE, tfsoff);
2260         absoff = utype->typestring_offset;
2261     }
2262
2263     if (type_get_type(utype) == TYPE_POINTER && get_pointer_fc(utype, NULL, FALSE) == RPC_FC_RP)
2264         flags = 0x40;
2265     else if (type_get_type(utype) == TYPE_POINTER && get_pointer_fc(utype, NULL, FALSE) == RPC_FC_UP)
2266         flags = 0x80;
2267     else
2268         flags = 0;
2269
2270     start = *tfsoff;
2271     update_tfsoff(type, start, file);
2272     print_start_tfs_comment(file, type, start);
2273     print_file(file, 2, "0x%x,\t/* FC_USER_MARSHAL */\n", RPC_FC_USER_MARSHAL);
2274     print_file(file, 2, "0x%x,\t/* Alignment= %d, Flags= %02x */\n",
2275                flags | (ualign - 1), ualign - 1, flags);
2276     print_file(file, 2, "NdrFcShort(0x%hx),\t/* Function offset= %hu */\n", funoff, funoff);
2277     print_file(file, 2, "NdrFcShort(0x%hx),\t/* %u */\n", (unsigned short)size, size);
2278     print_file(file, 2, "NdrFcShort(0x%hx),\t/* %u */\n", (unsigned short)usize, usize);
2279     *tfsoff += 8;
2280     reloff = absoff - *tfsoff;
2281     print_file(file, 2, "NdrFcShort(0x%hx),\t/* Offset= %hd (%u) */\n", reloff, reloff, absoff);
2282     *tfsoff += 2;
2283     return start;
2284 }
2285
2286 static void write_member_type(FILE *file, const type_t *cont,
2287                               int cont_is_complex, const attr_list_t *attrs,
2288                               const type_t *type, unsigned int *corroff,
2289                               unsigned int *tfsoff)
2290 {
2291     if (is_embedded_complex(type) && !is_conformant_array(type))
2292     {
2293         unsigned int absoff;
2294         short reloff;
2295
2296         if (type_get_type(type) == TYPE_UNION && is_attr(attrs, ATTR_SWITCHIS))
2297         {
2298             absoff = *corroff;
2299             *corroff += 8;
2300         }
2301         else
2302         {
2303             absoff = type->typestring_offset;
2304         }
2305         reloff = absoff - (*tfsoff + 2);
2306
2307         print_file(file, 2, "0x4c,\t/* FC_EMBEDDED_COMPLEX */\n");
2308         /* padding is represented using FC_STRUCTPAD* types, so presumably
2309          * this is left over in the format for historical purposes in MIDL
2310          * or rpcrt4. */
2311         print_file(file, 2, "0x0,\n");
2312         print_file(file, 2, "NdrFcShort(0x%hx),\t/* Offset= %hd (%u) */\n",
2313                    reloff, reloff, absoff);
2314         *tfsoff += 4;
2315     }
2316     else if (is_ptr(type) || is_conformant_array(type))
2317     {
2318         unsigned char fc = cont_is_complex ? RPC_FC_POINTER : RPC_FC_LONG;
2319         print_file(file, 2, "0x%x,\t/* %s */\n", fc, string_of_type(fc));
2320         *tfsoff += 1;
2321     }
2322     else if (!write_base_type(file, type, tfsoff))
2323         error("Unsupported member type %d\n", type_get_type(type));
2324 }
2325
2326 static void write_array_element_type(FILE *file, const type_t *type,
2327                                      int cont_is_complex, unsigned int *tfsoff)
2328 {
2329     type_t *elem = type_array_get_element(type);
2330
2331     if (!is_embedded_complex(elem) && is_ptr(elem))
2332     {
2333         type_t *ref = type_pointer_get_ref(elem);
2334
2335         if (processed(ref))
2336         {
2337             write_nonsimple_pointer(file, NULL, elem, TYPE_CONTEXT_CONTAINER,
2338                                     ref->typestring_offset, tfsoff);
2339             return;
2340         }
2341         if (!is_string_type(NULL, elem) &&
2342             (type_get_type(ref) == TYPE_BASIC || type_get_type(ref) == TYPE_ENUM))
2343         {
2344             *tfsoff += write_simple_pointer(file, NULL, elem, TYPE_CONTEXT_CONTAINER);
2345             return;
2346         }
2347     }
2348     return write_member_type(file, type, cont_is_complex, NULL, elem, NULL, tfsoff);
2349 }
2350
2351 static void write_end(FILE *file, unsigned int *tfsoff)
2352 {
2353     if (*tfsoff % 2 == 0)
2354     {
2355         print_file(file, 2, "0x%x,\t\t/* FC_PAD */\n", RPC_FC_PAD);
2356         *tfsoff += 1;
2357     }
2358     print_file(file, 2, "0x%x,\t\t/* FC_END */\n", RPC_FC_END);
2359     *tfsoff += 1;
2360 }
2361
2362 static void write_descriptors(FILE *file, type_t *type, unsigned int *tfsoff)
2363 {
2364     unsigned int offset = 0;
2365     var_list_t *fs = type_struct_get_fields(type);
2366     var_t *f;
2367
2368     if (fs) LIST_FOR_EACH_ENTRY(f, fs, var_t, entry)
2369     {
2370         type_t *ft = f->type;
2371         unsigned int size = field_memsize( ft, &offset );
2372         if (type_get_type(ft) == TYPE_UNION && is_attr(f->attrs, ATTR_SWITCHIS))
2373         {
2374             short reloff;
2375             unsigned int absoff = ft->typestring_offset;
2376             if (is_attr(ft->attrs, ATTR_SWITCHTYPE))
2377                 absoff += 8; /* we already have a corr descr, skip it */
2378             reloff = absoff - (*tfsoff + 6);
2379             print_file(file, 0, "/* %d */\n", *tfsoff);
2380             print_file(file, 2, "0x%x,\t/* FC_NON_ENCAPSULATED_UNION */\n", RPC_FC_NON_ENCAPSULATED_UNION);
2381             print_file(file, 2, "0x%x,\t/* FIXME: always FC_LONG */\n", RPC_FC_LONG);
2382             write_conf_or_var_desc(file, current_structure, offset, ft,
2383                                    get_attrp(f->attrs, ATTR_SWITCHIS));
2384             print_file(file, 2, "NdrFcShort(%hd),\t/* Offset= %hd (%u) */\n",
2385                        reloff, reloff, absoff);
2386             *tfsoff += 8;
2387         }
2388         offset += size;
2389     }
2390 }
2391
2392 static int write_pointer_description_offsets(
2393     FILE *file, const attr_list_t *attrs, type_t *type,
2394     unsigned int *offset_in_memory, unsigned int *offset_in_buffer,
2395     unsigned int *typestring_offset)
2396 {
2397     int written = 0;
2398
2399     if ((is_ptr(type) && type_get_type(type_pointer_get_ref(type)) != TYPE_INTERFACE) ||
2400         (is_array(type) && type_array_is_decl_as_ptr(type)))
2401     {
2402         if (offset_in_memory && offset_in_buffer)
2403         {
2404             unsigned int memsize;
2405
2406             /* pointer instance
2407              *
2408              * note that MSDN states that for pointer layouts in structures,
2409              * this is a negative offset from the end of the structure, but
2410              * this statement is incorrect. all offsets are positive */
2411             print_file(file, 2, "NdrFcShort(0x%hx),\t/* Memory offset = %d */\n", (unsigned short)*offset_in_memory, *offset_in_memory);
2412             print_file(file, 2, "NdrFcShort(0x%hx),\t/* Buffer offset = %d */\n", (unsigned short)*offset_in_buffer, *offset_in_buffer);
2413
2414             memsize = type_memsize(type);
2415             *offset_in_memory += memsize;
2416             /* increment these separately as in the case of conformant (varying)
2417              * structures these start at different values */
2418             *offset_in_buffer += memsize;
2419         }
2420         *typestring_offset += 4;
2421
2422         if (is_ptr(type))
2423         {
2424             type_t *ref = type_pointer_get_ref(type);
2425
2426             if (is_string_type(attrs, type))
2427                 write_string_tfs(file, attrs, type, TYPE_CONTEXT_CONTAINER, NULL, typestring_offset);
2428             else if (processed(ref))
2429                 write_nonsimple_pointer(file, attrs, type, TYPE_CONTEXT_CONTAINER,
2430                                         ref->typestring_offset, typestring_offset);
2431             else if (type_get_type(ref) == TYPE_BASIC || type_get_type(ref) == TYPE_ENUM)
2432                 *typestring_offset += write_simple_pointer(file, attrs, type, TYPE_CONTEXT_CONTAINER);
2433             else
2434                 error("write_pointer_description_offsets: type format string unknown\n");
2435         }
2436         else
2437         {
2438             unsigned int offset = type->typestring_offset;
2439             /* skip over the pointer that is written for strings, since a
2440              * pointer has to be written in-place here */
2441             if (is_string_type(attrs, type))
2442                 offset += 4;
2443             write_nonsimple_pointer(file, attrs, type, TYPE_CONTEXT_CONTAINER, offset, typestring_offset);
2444         }
2445
2446         return 1;
2447     }
2448
2449     if (is_array(type))
2450     {
2451         return write_pointer_description_offsets(
2452             file, attrs, type_array_get_element(type), offset_in_memory,
2453             offset_in_buffer, typestring_offset);
2454     }
2455     else if (is_non_complex_struct(type))
2456     {
2457         /* otherwise search for interesting fields to parse */
2458         const var_t *v;
2459         LIST_FOR_EACH_ENTRY( v, type_struct_get_fields(type), const var_t, entry )
2460         {
2461             if (offset_in_memory && offset_in_buffer)
2462             {
2463                 unsigned int padding;
2464                 unsigned int align = 0;
2465                 type_memsize_and_alignment(v->type, &align);
2466                 padding = ROUNDING(*offset_in_memory, align);
2467                 *offset_in_memory += padding;
2468                 *offset_in_buffer += padding;
2469             }
2470             written += write_pointer_description_offsets(
2471                 file, v->attrs, v->type, offset_in_memory, offset_in_buffer,
2472                 typestring_offset);
2473         }
2474     }
2475     else
2476     {
2477         if (offset_in_memory && offset_in_buffer)
2478         {
2479             unsigned int memsize = type_memsize(type);
2480             *offset_in_memory += memsize;
2481             /* increment these separately as in the case of conformant (varying)
2482              * structures these start at different values */
2483             *offset_in_buffer += memsize;
2484         }
2485     }
2486
2487     return written;
2488 }
2489
2490 static int write_no_repeat_pointer_descriptions(
2491     FILE *file, const attr_list_t *attrs, type_t *type,
2492     unsigned int *offset_in_memory, unsigned int *offset_in_buffer,
2493     unsigned int *typestring_offset)
2494 {
2495     int written = 0;
2496
2497     if (is_ptr(type) ||
2498         (is_conformant_array(type) && type_array_is_decl_as_ptr(type)))
2499     {
2500         print_file(file, 2, "0x%02x, /* FC_NO_REPEAT */\n", RPC_FC_NO_REPEAT);
2501         print_file(file, 2, "0x%02x, /* FC_PAD */\n", RPC_FC_PAD);
2502         *typestring_offset += 2;
2503
2504         return write_pointer_description_offsets(file, attrs, type,
2505                        offset_in_memory, offset_in_buffer, typestring_offset);
2506     }
2507
2508     if (is_non_complex_struct(type))
2509     {
2510         const var_t *v;
2511         LIST_FOR_EACH_ENTRY( v, type_struct_get_fields(type), const var_t, entry )
2512         {
2513             if (offset_in_memory && offset_in_buffer)
2514             {
2515                 unsigned int padding;
2516                 unsigned int align = 0;
2517                 type_memsize_and_alignment(v->type, &align);
2518                 padding = ROUNDING(*offset_in_memory, align);
2519                 *offset_in_memory += padding;
2520                 *offset_in_buffer += padding;
2521             }
2522             written += write_no_repeat_pointer_descriptions(
2523                 file, v->attrs, v->type,
2524                 offset_in_memory, offset_in_buffer, typestring_offset);
2525         }
2526     }
2527     else
2528     {
2529         unsigned int memsize = type_memsize(type);
2530         *offset_in_memory += memsize;
2531         /* increment these separately as in the case of conformant (varying)
2532          * structures these start at different values */
2533         *offset_in_buffer += memsize;
2534     }
2535
2536     return written;
2537 }
2538
2539 /* Note: if file is NULL return value is number of pointers to write, else
2540  * it is the number of type format characters written */
2541 static int write_fixed_array_pointer_descriptions(
2542     FILE *file, const attr_list_t *attrs, type_t *type,
2543     unsigned int *offset_in_memory, unsigned int *offset_in_buffer,
2544     unsigned int *typestring_offset)
2545 {
2546     int pointer_count = 0;
2547
2548     if (type_get_type(type) == TYPE_ARRAY &&
2549         !type_array_has_conformance(type) && !type_array_has_variance(type))
2550     {
2551         unsigned int temp = 0;
2552         /* unfortunately, this needs to be done in two passes to avoid
2553          * writing out redundant FC_FIXED_REPEAT descriptions */
2554         pointer_count = write_pointer_description_offsets(
2555             NULL, attrs, type_array_get_element(type), NULL, NULL, &temp);
2556         if (pointer_count > 0)
2557         {
2558             unsigned int increment_size;
2559             unsigned int offset_of_array_pointer_mem = 0;
2560             unsigned int offset_of_array_pointer_buf = 0;
2561
2562             increment_size = type_memsize(type_array_get_element(type));
2563
2564             print_file(file, 2, "0x%02x, /* FC_FIXED_REPEAT */\n", RPC_FC_FIXED_REPEAT);
2565             print_file(file, 2, "0x%02x, /* FC_PAD */\n", RPC_FC_PAD);
2566             print_file(file, 2, "NdrFcShort(0x%hx),\t/* Iterations = %d */\n", (unsigned short)type_array_get_dim(type), type_array_get_dim(type));
2567             print_file(file, 2, "NdrFcShort(0x%hx),\t/* Increment = %d */\n", (unsigned short)increment_size, increment_size);
2568             print_file(file, 2, "NdrFcShort(0x%hx),\t/* Offset to array = %d */\n", (unsigned short)*offset_in_memory, *offset_in_memory);
2569             print_file(file, 2, "NdrFcShort(0x%hx),\t/* Number of pointers = %d */\n", (unsigned short)pointer_count, pointer_count);
2570             *typestring_offset += 10;
2571
2572             pointer_count = write_pointer_description_offsets(
2573                 file, attrs, type, &offset_of_array_pointer_mem,
2574                 &offset_of_array_pointer_buf, typestring_offset);
2575         }
2576     }
2577     else if (type_get_type(type) == TYPE_STRUCT)
2578     {
2579         const var_t *v;
2580         LIST_FOR_EACH_ENTRY( v, type_struct_get_fields(type), const var_t, entry )
2581         {
2582             if (offset_in_memory && offset_in_buffer)
2583             {
2584                 unsigned int padding;
2585                 unsigned int align = 0;
2586                 type_memsize_and_alignment(v->type, &align);
2587                 padding = ROUNDING(*offset_in_memory, align);
2588                 *offset_in_memory += padding;
2589                 *offset_in_buffer += padding;
2590             }
2591             pointer_count += write_fixed_array_pointer_descriptions(
2592                 file, v->attrs, v->type, offset_in_memory, offset_in_buffer,
2593                 typestring_offset);
2594         }
2595     }
2596     else
2597     {
2598         if (offset_in_memory && offset_in_buffer)
2599         {
2600             unsigned int memsize;
2601             memsize = type_memsize(type);
2602             *offset_in_memory += memsize;
2603             /* increment these separately as in the case of conformant (varying)
2604              * structures these start at different values */
2605             *offset_in_buffer += memsize;
2606         }
2607     }
2608
2609     return pointer_count;
2610 }
2611
2612 /* Note: if file is NULL return value is number of pointers to write, else
2613  * it is the number of type format characters written */
2614 static int write_conformant_array_pointer_descriptions(
2615     FILE *file, const attr_list_t *attrs, type_t *type,
2616     unsigned int offset_in_memory, unsigned int *typestring_offset)
2617 {
2618     int pointer_count = 0;
2619
2620     if (is_conformant_array(type) && !type_array_has_variance(type))
2621     {
2622         unsigned int temp = 0;
2623         /* unfortunately, this needs to be done in two passes to avoid
2624          * writing out redundant FC_VARIABLE_REPEAT descriptions */
2625         pointer_count = write_pointer_description_offsets(
2626             NULL, attrs, type_array_get_element(type), NULL, NULL, &temp);
2627         if (pointer_count > 0)
2628         {
2629             unsigned int increment_size;
2630             unsigned int offset_of_array_pointer_mem = offset_in_memory;
2631             unsigned int offset_of_array_pointer_buf = offset_in_memory;
2632
2633             increment_size = type_memsize(type_array_get_element(type));
2634
2635             if (increment_size > USHRT_MAX)
2636                 error("array size of %u bytes is too large\n", increment_size);
2637
2638             print_file(file, 2, "0x%02x, /* FC_VARIABLE_REPEAT */\n", RPC_FC_VARIABLE_REPEAT);
2639             print_file(file, 2, "0x%02x, /* FC_FIXED_OFFSET */\n", RPC_FC_FIXED_OFFSET);
2640             print_file(file, 2, "NdrFcShort(0x%hx),\t/* Increment = %d */\n", (unsigned short)increment_size, increment_size);
2641             print_file(file, 2, "NdrFcShort(0x%hx),\t/* Offset to array = %d */\n", (unsigned short)offset_in_memory, offset_in_memory);
2642             print_file(file, 2, "NdrFcShort(0x%hx),\t/* Number of pointers = %d */\n", (unsigned short)pointer_count, pointer_count);
2643             *typestring_offset += 8;
2644
2645             pointer_count = write_pointer_description_offsets(
2646                 file, attrs, type_array_get_element(type),
2647                 &offset_of_array_pointer_mem, &offset_of_array_pointer_buf,
2648                 typestring_offset);
2649         }
2650     }
2651
2652     return pointer_count;
2653 }
2654
2655 /* Note: if file is NULL return value is number of pointers to write, else
2656  * it is the number of type format characters written */
2657 static int write_varying_array_pointer_descriptions(
2658     FILE *file, const attr_list_t *attrs, type_t *type,
2659     unsigned int *offset_in_memory, unsigned int *offset_in_buffer,
2660     unsigned int *typestring_offset)
2661 {
2662     int pointer_count = 0;
2663
2664     if (is_array(type) && type_array_has_variance(type))
2665     {
2666         unsigned int temp = 0;
2667         /* unfortunately, this needs to be done in two passes to avoid
2668          * writing out redundant FC_VARIABLE_REPEAT descriptions */
2669         pointer_count = write_pointer_description_offsets(
2670             NULL, attrs, type_array_get_element(type), NULL, NULL, &temp);
2671         if (pointer_count > 0)
2672         {
2673             unsigned int increment_size;
2674
2675             increment_size = type_memsize(type_array_get_element(type));
2676
2677             if (increment_size > USHRT_MAX)
2678                 error("array size of %u bytes is too large\n", increment_size);
2679
2680             print_file(file, 2, "0x%02x, /* FC_VARIABLE_REPEAT */\n", RPC_FC_VARIABLE_REPEAT);
2681             print_file(file, 2, "0x%02x, /* FC_VARIABLE_OFFSET */\n", RPC_FC_VARIABLE_OFFSET);
2682             print_file(file, 2, "NdrFcShort(0x%hx),\t/* Increment = %d */\n", (unsigned short)increment_size, increment_size);
2683             print_file(file, 2, "NdrFcShort(0x%hx),\t/* Offset to array = %d */\n", (unsigned short)*offset_in_memory, *offset_in_memory);
2684             print_file(file, 2, "NdrFcShort(0x%hx),\t/* Number of pointers = %d */\n", (unsigned short)pointer_count, pointer_count);
2685             *typestring_offset += 8;
2686
2687             pointer_count = write_pointer_description_offsets(
2688                 file, attrs, type_array_get_element(type), offset_in_memory,
2689                 offset_in_buffer, typestring_offset);
2690         }
2691     }
2692     else if (type_get_type(type) == TYPE_STRUCT)
2693     {
2694         const var_t *v;
2695         LIST_FOR_EACH_ENTRY( v, type_struct_get_fields(type), const var_t, entry )
2696         {
2697             if (offset_in_memory && offset_in_buffer)
2698             {
2699                 unsigned int align = 0, padding;
2700
2701                 if (is_array(v->type) && type_array_has_variance(v->type))
2702                 {
2703                     *offset_in_buffer = ROUND_SIZE(*offset_in_buffer, 4);
2704                     /* skip over variance and offset in buffer */
2705                     *offset_in_buffer += 8;
2706                 }
2707
2708                 type_memsize_and_alignment(v->type, &align);
2709                 padding = ROUNDING(*offset_in_memory, align);
2710                 *offset_in_memory += padding;
2711                 *offset_in_buffer += padding;
2712             }
2713             pointer_count += write_varying_array_pointer_descriptions(
2714                 file, v->attrs, v->type, offset_in_memory, offset_in_buffer,
2715                 typestring_offset);
2716         }
2717     }
2718     else
2719     {
2720         if (offset_in_memory && offset_in_buffer)
2721         {
2722             unsigned int memsize = type_memsize(type);
2723             *offset_in_memory += memsize;
2724             /* increment these separately as in the case of conformant (varying)
2725              * structures these start at different values */
2726             *offset_in_buffer += memsize;
2727         }
2728     }
2729
2730     return pointer_count;
2731 }
2732
2733 static void write_pointer_description(FILE *file, type_t *type,
2734                                       unsigned int *typestring_offset)
2735 {
2736     unsigned int offset_in_buffer;
2737     unsigned int offset_in_memory;
2738
2739     /* pass 1: search for single instance of a pointer (i.e. don't descend
2740      * into arrays) */
2741     if (!is_array(type))
2742     {
2743         offset_in_memory = 0;
2744         offset_in_buffer = 0;
2745         write_no_repeat_pointer_descriptions(
2746             file, NULL, type,
2747             &offset_in_memory, &offset_in_buffer, typestring_offset);
2748     }
2749
2750     /* pass 2: search for pointers in fixed arrays */
2751     offset_in_memory = 0;
2752     offset_in_buffer = 0;
2753     write_fixed_array_pointer_descriptions(
2754         file, NULL, type,
2755         &offset_in_memory, &offset_in_buffer, typestring_offset);
2756
2757     /* pass 3: search for pointers in conformant only arrays (but don't descend
2758      * into conformant varying or varying arrays) */
2759     if (is_conformant_array(type) &&
2760         (type_array_is_decl_as_ptr(type) || !current_structure))
2761         write_conformant_array_pointer_descriptions(
2762             file, NULL, type, 0, typestring_offset);
2763     else if (type_get_type(type) == TYPE_STRUCT &&
2764              get_struct_fc(type) == RPC_FC_CPSTRUCT)
2765     {
2766         type_t *carray = find_array_or_string_in_struct(type)->type;
2767         write_conformant_array_pointer_descriptions( file, NULL, carray,
2768                                                      type_memsize(type), typestring_offset);
2769     }
2770
2771     /* pass 4: search for pointers in varying arrays */
2772     offset_in_memory = 0;
2773     offset_in_buffer = 0;
2774     write_varying_array_pointer_descriptions(
2775             file, NULL, type,
2776             &offset_in_memory, &offset_in_buffer, typestring_offset);
2777 }
2778
2779 int is_declptr(const type_t *t)
2780 {
2781   return is_ptr(t) || (type_get_type(t) == TYPE_ARRAY && type_array_is_decl_as_ptr(t));
2782 }
2783
2784 static unsigned int write_string_tfs(FILE *file, const attr_list_t *attrs,
2785                                      type_t *type, enum type_context context,
2786                                      const char *name, unsigned int *typestring_offset)
2787 {
2788     unsigned int start_offset;
2789     unsigned char rtype;
2790     type_t *elem_type;
2791     int is_processed = processed(type);
2792
2793     start_offset = *typestring_offset;
2794
2795     if (is_declptr(type))
2796     {
2797         unsigned char flag = is_conformant_array(type) ? 0 : RPC_FC_P_SIMPLEPOINTER;
2798         int pointer_type = get_pointer_fc_context(type, attrs, context);
2799         if (!pointer_type)
2800             pointer_type = RPC_FC_RP;
2801         print_start_tfs_comment(file, type, *typestring_offset);
2802         print_file(file, 2,"0x%x, 0x%x,\t/* %s%s */\n",
2803                    pointer_type, flag, string_of_type(pointer_type),
2804                    flag ? " [simple_pointer]" : "");
2805         *typestring_offset += 2;
2806         if (!flag)
2807         {
2808             print_file(file, 2, "NdrFcShort(0x2),\n");
2809             *typestring_offset += 2;
2810         }
2811         is_processed = FALSE;
2812     }
2813
2814     if (is_array(type))
2815         elem_type = type_array_get_element(type);
2816     else
2817         elem_type = type_pointer_get_ref(type);
2818
2819     if (type_get_type(elem_type) != TYPE_BASIC)
2820     {
2821         error("write_string_tfs: Unimplemented for non-basic type %s\n", name);
2822         return start_offset;
2823     }
2824
2825     rtype = get_basic_fc(elem_type);
2826     if ((rtype != RPC_FC_BYTE) && (rtype != RPC_FC_CHAR) && (rtype != RPC_FC_WCHAR))
2827     {
2828         error("write_string_tfs: Unimplemented for type 0x%x of name: %s\n", rtype, name);
2829         return start_offset;
2830     }
2831
2832     if (type_get_type(type) == TYPE_ARRAY && !type_array_has_conformance(type))
2833     {
2834         unsigned int dim = type_array_get_dim(type);
2835
2836         if (is_processed) return start_offset;
2837
2838         /* FIXME: multi-dimensional array */
2839         if (0xffffu < dim)
2840             error("array size for parameter %s exceeds %u bytes by %u bytes\n",
2841                   name, 0xffffu, dim - 0xffffu);
2842
2843         if (rtype == RPC_FC_WCHAR)
2844             WRITE_FCTYPE(file, FC_WSTRING, *typestring_offset);
2845         else
2846             WRITE_FCTYPE(file, FC_CSTRING, *typestring_offset);
2847         print_file(file, 2, "0x%x, /* FC_PAD */\n", RPC_FC_PAD);
2848         *typestring_offset += 2;
2849
2850         print_file(file, 2, "NdrFcShort(0x%hx),\t/* %d */\n", (unsigned short)dim, dim);
2851         *typestring_offset += 2;
2852
2853         update_tfsoff(type, start_offset, file);
2854         return start_offset;
2855     }
2856     else if (is_conformant_array(type))
2857     {
2858         if (rtype == RPC_FC_WCHAR)
2859             WRITE_FCTYPE(file, FC_C_WSTRING, *typestring_offset);
2860         else
2861             WRITE_FCTYPE(file, FC_C_CSTRING, *typestring_offset);
2862         print_file(file, 2, "0x%x, /* FC_STRING_SIZED */\n", RPC_FC_STRING_SIZED);
2863         *typestring_offset += 2;
2864
2865         *typestring_offset += write_conf_or_var_desc(
2866             file, current_structure,
2867             (!type_array_is_decl_as_ptr(type) && current_structure
2868              ? type_memsize(current_structure)
2869              : 0),
2870             type, type_array_get_conformance(type));
2871
2872         update_tfsoff(type, start_offset, file);
2873         return start_offset;
2874     }
2875     else
2876     {
2877         if (is_processed) return start_offset;
2878
2879         if (rtype == RPC_FC_WCHAR)
2880             WRITE_FCTYPE(file, FC_C_WSTRING, *typestring_offset);
2881         else
2882             WRITE_FCTYPE(file, FC_C_CSTRING, *typestring_offset);
2883         print_file(file, 2, "0x%x, /* FC_PAD */\n", RPC_FC_PAD);
2884         *typestring_offset += 2;
2885
2886         update_tfsoff(type, start_offset, file);
2887         return start_offset;
2888     }
2889 }
2890
2891 static unsigned int write_array_tfs(FILE *file, const attr_list_t *attrs, type_t *type,
2892                                     const char *name, unsigned int *typestring_offset)
2893 {
2894     const expr_t *length_is = type_array_get_variance(type);
2895     const expr_t *size_is = type_array_get_conformance(type);
2896     unsigned int align;
2897     unsigned int size;
2898     unsigned int start_offset;
2899     unsigned char fc;
2900     int pointer_type = get_attrv(attrs, ATTR_POINTERTYPE);
2901     unsigned int baseoff
2902         = !type_array_is_decl_as_ptr(type) && current_structure
2903         ? type_memsize(current_structure)
2904         : 0;
2905
2906     if (!pointer_type)
2907         pointer_type = RPC_FC_RP;
2908
2909     write_embedded_types(file, attrs, type_array_get_element(type), name, FALSE, typestring_offset);
2910
2911     size = type_memsize(is_conformant_array(type) ? type_array_get_element(type) : type);
2912     align = type_buffer_alignment(is_conformant_array(type) ? type_array_get_element(type) : type);
2913     fc = get_array_fc(type);
2914
2915     start_offset = *typestring_offset;
2916     update_tfsoff(type, start_offset, file);
2917     print_start_tfs_comment(file, type, start_offset);
2918     print_file(file, 2, "0x%02x,\t/* %s */\n", fc, string_of_type(fc));
2919     print_file(file, 2, "0x%x,\t/* %d */\n", align - 1, align - 1);
2920     *typestring_offset += 2;
2921
2922     align = 0;
2923     if (fc != RPC_FC_BOGUS_ARRAY)
2924     {
2925         if (fc == RPC_FC_LGFARRAY || fc == RPC_FC_LGVARRAY)
2926         {
2927             print_file(file, 2, "NdrFcLong(0x%x),\t/* %u */\n", size, size);
2928             *typestring_offset += 4;
2929         }
2930         else
2931         {
2932             print_file(file, 2, "NdrFcShort(0x%hx),\t/* %u */\n", (unsigned short)size, size);
2933             *typestring_offset += 2;
2934         }
2935
2936         if (is_conformant_array(type))
2937             *typestring_offset
2938                 += write_conf_or_var_desc(file, current_structure, baseoff,
2939                                           type, size_is);
2940
2941         if (fc == RPC_FC_SMVARRAY || fc == RPC_FC_LGVARRAY)
2942         {
2943             unsigned int elsize = type_memsize(type_array_get_element(type));
2944             unsigned int dim = type_array_get_dim(type);
2945
2946             if (fc == RPC_FC_LGVARRAY)
2947             {
2948                 print_file(file, 2, "NdrFcLong(0x%x),\t/* %u */\n", dim, dim);
2949                 *typestring_offset += 4;
2950             }
2951             else
2952             {
2953                 print_file(file, 2, "NdrFcShort(0x%hx),\t/* %u */\n", (unsigned short)dim, dim);
2954                 *typestring_offset += 2;
2955             }
2956
2957             print_file(file, 2, "NdrFcShort(0x%hx),\t/* %u */\n", (unsigned short)elsize, elsize);
2958             *typestring_offset += 2;
2959         }
2960
2961         if (length_is)
2962             *typestring_offset
2963                 += write_conf_or_var_desc(file, current_structure, baseoff,
2964                                           type, length_is);
2965
2966         if (type_has_pointers(type_array_get_element(type)) &&
2967             (type_array_is_decl_as_ptr(type) || !current_structure))
2968         {
2969             print_file(file, 2, "0x%x, /* FC_PP */\n", RPC_FC_PP);
2970             print_file(file, 2, "0x%x, /* FC_PAD */\n", RPC_FC_PAD);
2971             *typestring_offset += 2;
2972             write_pointer_description(file, type, typestring_offset);
2973             print_file(file, 2, "0x%x, /* FC_END */\n", RPC_FC_END);
2974             *typestring_offset += 1;
2975         }
2976
2977         write_array_element_type(file, type, FALSE, typestring_offset);
2978         write_end(file, typestring_offset);
2979     }
2980     else
2981     {
2982         unsigned int dim = size_is ? 0 : type_array_get_dim(type);
2983         print_file(file, 2, "NdrFcShort(0x%hx),\t/* %u */\n", (unsigned short)dim, dim);
2984         *typestring_offset += 2;
2985         *typestring_offset
2986             += write_conf_or_var_desc(file, current_structure, baseoff,
2987                                       type, size_is);
2988         *typestring_offset
2989             += write_conf_or_var_desc(file, current_structure, baseoff,
2990                                       type, length_is);
2991
2992         write_array_element_type(file, type, TRUE, typestring_offset);
2993         write_end(file, typestring_offset);
2994     }
2995
2996     return start_offset;
2997 }
2998
2999 static const var_t *find_array_or_string_in_struct(const type_t *type)
3000 {
3001     const var_list_t *fields = type_struct_get_fields(type);
3002     const var_t *last_field;
3003     const type_t *ft;
3004
3005     if (!fields || list_empty(fields))
3006         return NULL;
3007
3008     last_field = LIST_ENTRY( list_tail(fields), const var_t, entry );
3009     ft = last_field->type;
3010
3011     if (is_conformant_array(ft) && !type_array_is_decl_as_ptr(ft))
3012         return last_field;
3013
3014     if (type_get_type(ft) == TYPE_STRUCT)
3015         return find_array_or_string_in_struct(ft);
3016     else
3017         return NULL;
3018 }
3019
3020 static void write_struct_members(FILE *file, const type_t *type,
3021                                  int is_complex, unsigned int *corroff,
3022                                  unsigned int *typestring_offset)
3023 {
3024     const var_t *field;
3025     unsigned short offset = 0;
3026     unsigned int salign = 1;
3027     int padding;
3028     var_list_t *fields = type_struct_get_fields(type);
3029
3030     if (fields) LIST_FOR_EACH_ENTRY( field, fields, const var_t, entry )
3031     {
3032         type_t *ft = field->type;
3033         unsigned int align = 0;
3034         unsigned int size = type_memsize_and_alignment(ft, &align);
3035         align = clamp_align(align);
3036         if (salign < align) salign = align;
3037
3038         if (!is_conformant_array(ft) || type_array_is_decl_as_ptr(ft))
3039         {
3040             if ((align - 1) & offset)
3041             {
3042                 unsigned char fc = 0;
3043                 switch (align)
3044                 {
3045                 case 2:
3046                     fc = RPC_FC_ALIGNM2;
3047                     break;
3048                 case 4:
3049                     fc = RPC_FC_ALIGNM4;
3050                     break;
3051                 case 8:
3052                     fc = RPC_FC_ALIGNM8;
3053                     break;
3054                 default:
3055                     error("write_struct_members: cannot align type %d\n", type_get_type(ft));
3056                 }
3057                 print_file(file, 2, "0x%x,\t/* %s */\n", fc, string_of_type(fc));
3058                 offset = ROUND_SIZE(offset, align);
3059                 *typestring_offset += 1;
3060             }
3061             write_member_type(file, type, is_complex, field->attrs, field->type, corroff,
3062                               typestring_offset);
3063             offset += size;
3064         }
3065     }
3066
3067     padding = ROUNDING(offset, salign);
3068     if (padding)
3069     {
3070         print_file(file, 2, "0x%x,\t/* FC_STRUCTPAD%d */\n",
3071                    RPC_FC_STRUCTPAD1 + padding - 1,
3072                    padding);
3073         *typestring_offset += 1;
3074     }
3075
3076     write_end(file, typestring_offset);
3077 }
3078
3079 static unsigned int write_struct_tfs(FILE *file, type_t *type,
3080                                      const char *name, unsigned int *tfsoff)
3081 {
3082     const type_t *save_current_structure = current_structure;
3083     unsigned int total_size;
3084     const var_t *array;
3085     unsigned int start_offset;
3086     unsigned int align;
3087     unsigned int corroff;
3088     var_t *f;
3089     unsigned char fc = get_struct_fc(type);
3090     var_list_t *fields = type_struct_get_fields(type);
3091
3092     if (processed(type)) return type->typestring_offset;
3093
3094     guard_rec(type);
3095     current_structure = type;
3096
3097     total_size = type_memsize(type);
3098     align = type_buffer_alignment(type);
3099     if (total_size > USHRT_MAX)
3100         error("structure size for %s exceeds %d bytes by %d bytes\n",
3101               name, USHRT_MAX, total_size - USHRT_MAX);
3102
3103     if (fields) LIST_FOR_EACH_ENTRY(f, fields, var_t, entry)
3104         write_embedded_types(file, f->attrs, f->type, f->name, FALSE, tfsoff);
3105
3106     array = find_array_or_string_in_struct(type);
3107     if (array && !processed(array->type))
3108     {
3109         if(is_string_type(array->attrs, array->type))
3110             write_string_tfs(file, array->attrs, array->type, TYPE_CONTEXT_CONTAINER, array->name, tfsoff);
3111         else
3112             write_array_tfs(file, array->attrs, array->type, array->name, tfsoff);
3113     }
3114
3115     corroff = *tfsoff;
3116     write_descriptors(file, type, tfsoff);
3117
3118     start_offset = *tfsoff;
3119     update_tfsoff(type, start_offset, file);
3120     print_start_tfs_comment(file, type, start_offset);
3121     print_file(file, 2, "0x%x,\t/* %s */\n", fc, string_of_type(fc));
3122     print_file(file, 2, "0x%x,\t/* %d */\n", align - 1, align - 1);
3123     print_file(file, 2, "NdrFcShort(0x%hx),\t/* %d */\n", (unsigned short)total_size, total_size);
3124     *tfsoff += 4;
3125
3126     if (array)
3127     {
3128         unsigned int absoff = array->type->typestring_offset;
3129         short reloff = absoff - *tfsoff;
3130         print_file(file, 2, "NdrFcShort(0x%hx),\t/* Offset= %hd (%u) */\n",
3131                    reloff, reloff, absoff);
3132         *tfsoff += 2;
3133     }
3134     else if (fc == RPC_FC_BOGUS_STRUCT)
3135     {
3136         print_file(file, 2, "NdrFcShort(0x0),\n");
3137         *tfsoff += 2;
3138     }
3139
3140     if (fc == RPC_FC_BOGUS_STRUCT)
3141     {
3142         /* On the sizing pass, type->ptrdesc may be zero, but it's ok as
3143            nothing is written to file yet.  On the actual writing pass,
3144            this will have been updated.  */
3145         unsigned int absoff = type->ptrdesc ? type->ptrdesc : *tfsoff;
3146         int reloff = absoff - *tfsoff;
3147         assert( reloff >= 0 );
3148         print_file(file, 2, "NdrFcShort(0x%hx),\t/* Offset= %d (%u) */\n",
3149                    (unsigned short)reloff, reloff, absoff);
3150         *tfsoff += 2;
3151     }
3152     else if ((fc == RPC_FC_PSTRUCT) ||
3153              (fc == RPC_FC_CPSTRUCT) ||
3154              (fc == RPC_FC_CVSTRUCT && type_has_pointers(type)))
3155     {
3156         print_file(file, 2, "0x%x, /* FC_PP */\n", RPC_FC_PP);
3157         print_file(file, 2, "0x%x, /* FC_PAD */\n", RPC_FC_PAD);
3158         *tfsoff += 2;
3159         write_pointer_description(file, type, tfsoff);
3160         print_file(file, 2, "0x%x, /* FC_END */\n", RPC_FC_END);
3161         *tfsoff += 1;
3162     }
3163
3164     write_struct_members(file, type, fc == RPC_FC_BOGUS_STRUCT, &corroff,
3165                          tfsoff);
3166
3167     if (fc == RPC_FC_BOGUS_STRUCT)
3168     {
3169         const var_t *f;
3170
3171         type->ptrdesc = *tfsoff;
3172         if (fields) LIST_FOR_EACH_ENTRY(f, fields, const var_t, entry)
3173         {
3174             type_t *ft = f->type;
3175             switch (typegen_detect_type(ft, f->attrs, TDT_IGNORE_STRINGS))
3176             {
3177             case TGT_POINTER:
3178                 if (is_string_type(f->attrs, ft))
3179                     write_string_tfs(file, f->attrs, ft, TYPE_CONTEXT_CONTAINER, f->name, tfsoff);
3180                 else
3181                     write_pointer_tfs(file, f->attrs, ft,
3182                                       type_pointer_get_ref(ft)->typestring_offset,
3183                                       TYPE_CONTEXT_CONTAINER, tfsoff);
3184                 break;
3185             case TGT_ARRAY:
3186                 if (type_array_is_decl_as_ptr(ft))
3187                 {
3188                     unsigned int offset;
3189
3190                     print_file(file, 0, "/* %d */\n", *tfsoff);
3191
3192                     offset = ft->typestring_offset;
3193                     /* skip over the pointer that is written for strings, since a
3194                      * pointer has to be written in-place here */
3195                     if (is_string_type(f->attrs, ft))
3196                         offset += 4;
3197                     write_nonsimple_pointer(file, f->attrs, ft, TYPE_CONTEXT_CONTAINER, offset, tfsoff);
3198                 }
3199                 break;
3200             default:
3201                 break;
3202             }
3203         }
3204         if (type->ptrdesc == *tfsoff)
3205             type->ptrdesc = 0;
3206     }
3207
3208     current_structure = save_current_structure;
3209     return start_offset;
3210 }
3211
3212 static void write_branch_type(FILE *file, const type_t *t, unsigned int *tfsoff)
3213 {
3214     if (t == NULL)
3215     {
3216         print_file(file, 2, "NdrFcShort(0x0),\t/* No type */\n");
3217     }
3218     else
3219     {
3220         if (type_get_type(t) == TYPE_BASIC || type_get_type(t) == TYPE_ENUM)
3221         {
3222             unsigned char fc;
3223             if (type_get_type(t) == TYPE_BASIC)
3224                 fc = get_basic_fc(t);
3225             else
3226                 fc = get_enum_fc(t);
3227             print_file(file, 2, "NdrFcShort(0x80%02x),\t/* Simple arm type: %s */\n",
3228                        fc, string_of_type(fc));
3229         }
3230         else if (t->typestring_offset)
3231         {
3232             short reloff = t->typestring_offset - *tfsoff;
3233             print_file(file, 2, "NdrFcShort(0x%hx),\t/* Offset= %d (%d) */\n",
3234                        reloff, reloff, t->typestring_offset);
3235         }
3236         else
3237             error("write_branch_type: type unimplemented %d\n", type_get_type(t));
3238     }
3239
3240     *tfsoff += 2;
3241 }
3242
3243 static unsigned int write_union_tfs(FILE *file, const attr_list_t *attrs,
3244                                     type_t *type, unsigned int *tfsoff)
3245 {
3246     unsigned int start_offset;
3247     unsigned int size;
3248     var_list_t *fields;
3249     unsigned int nbranch = 0;
3250     type_t *deftype = NULL;
3251     short nodeftype = 0xffff;
3252     var_t *f;
3253
3254     if (processed(type) &&
3255         (type_get_type(type) == TYPE_ENCAPSULATED_UNION || !is_attr(type->attrs, ATTR_SWITCHTYPE)))
3256         return type->typestring_offset;
3257
3258     guard_rec(type);
3259
3260     size = type_memsize(type);
3261
3262     fields = type_union_get_cases(type);
3263
3264     if (fields) LIST_FOR_EACH_ENTRY(f, fields, var_t, entry)
3265     {
3266         expr_list_t *cases = get_attrp(f->attrs, ATTR_CASE);
3267         if (cases)
3268             nbranch += list_count(cases);
3269         if (f->type)
3270             write_embedded_types(file, f->attrs, f->type, f->name, TRUE, tfsoff);
3271     }
3272
3273     start_offset = *tfsoff;
3274     update_tfsoff(type, start_offset, file);
3275     print_start_tfs_comment(file, type, start_offset);
3276     if (type_get_type(type) == TYPE_ENCAPSULATED_UNION)
3277     {
3278         const var_t *sv = type_union_get_switch_value(type);
3279         const type_t *st = sv->type;
3280         unsigned char fc;
3281
3282         if (type_get_type(st) == TYPE_BASIC)
3283         {
3284             fc = get_basic_fc(st);
3285             switch (fc)
3286             {
3287             case RPC_FC_CHAR:
3288             case RPC_FC_SMALL:
3289             case RPC_FC_BYTE:
3290             case RPC_FC_USMALL:
3291             case RPC_FC_WCHAR:
3292             case RPC_FC_SHORT:
3293             case RPC_FC_USHORT:
3294             case RPC_FC_LONG:
3295             case RPC_FC_ULONG:
3296                 break;
3297             default:
3298                 fc = 0;
3299                 error("union switch type must be an integer, char, or enum\n");
3300             }
3301         }
3302         else if (type_get_type(st) == TYPE_ENUM)
3303             fc = get_enum_fc(st);
3304         else
3305             error("union switch type must be an integer, char, or enum\n");
3306
3307         print_file(file, 2, "0x%x,\t/* FC_ENCAPSULATED_UNION */\n", RPC_FC_ENCAPSULATED_UNION);
3308         print_file(file, 2, "0x%x,\t/* Switch type= %s */\n",
3309                    0x40 | fc, string_of_type(fc));
3310         *tfsoff += 2;
3311     }
3312     else if (is_attr(type->attrs, ATTR_SWITCHTYPE))
3313     {
3314         const expr_t *switch_is = get_attrp(attrs, ATTR_SWITCHIS);
3315         const type_t *st = get_attrp(type->attrs, ATTR_SWITCHTYPE);
3316         unsigned char fc;
3317
3318         if (type_get_type(st) == TYPE_BASIC)
3319         {
3320             fc = get_basic_fc(st);
3321             switch (fc)
3322             {
3323             case RPC_FC_CHAR:
3324             case RPC_FC_SMALL:
3325             case RPC_FC_USMALL:
3326             case RPC_FC_SHORT:
3327             case RPC_FC_USHORT:
3328             case RPC_FC_LONG:
3329             case RPC_FC_ULONG:
3330             case RPC_FC_ENUM16:
3331             case RPC_FC_ENUM32:
3332                 break;
3333             default:
3334                 fc = 0;
3335                 error("union switch type must be an integer, char, or enum\n");
3336             }
3337         }
3338         else if (type_get_type(st) == TYPE_ENUM)
3339             fc = get_enum_fc(st);
3340         else
3341             error("union switch type must be an integer, char, or enum\n");
3342
3343         print_file(file, 2, "0x%x,\t/* FC_NON_ENCAPSULATED_UNION */\n", RPC_FC_NON_ENCAPSULATED_UNION);
3344         print_file(file, 2, "0x%x,\t/* Switch type= %s */\n",
3345                    fc, string_of_type(fc));
3346         *tfsoff += 2;
3347         *tfsoff += write_conf_or_var_desc(file, current_structure, 0, st, switch_is );
3348         print_file(file, 2, "NdrFcShort(0x2),\t/* Offset= 2 (%u) */\n", *tfsoff + 2);
3349         *tfsoff += 2;
3350         print_file(file, 0, "/* %u */\n", *tfsoff);
3351     }
3352
3353     print_file(file, 2, "NdrFcShort(0x%hx),\t/* %d */\n", (unsigned short)size, size);
3354     print_file(file, 2, "NdrFcShort(0x%hx),\t/* %d */\n", (unsigned short)nbranch, nbranch);
3355     *tfsoff += 4;
3356
3357     if (fields) LIST_FOR_EACH_ENTRY(f, fields, var_t, entry)
3358     {
3359         type_t *ft = f->type;
3360         expr_list_t *cases = get_attrp(f->attrs, ATTR_CASE);
3361         int deflt = is_attr(f->attrs, ATTR_DEFAULT);
3362         expr_t *c;
3363
3364         if (cases == NULL && !deflt)
3365             error("union field %s with neither case nor default attribute\n", f->name);
3366
3367         if (cases) LIST_FOR_EACH_ENTRY(c, cases, expr_t, entry)
3368         {
3369             /* MIDL doesn't check for duplicate cases, even though that seems
3370                like a reasonable thing to do, it just dumps them to the TFS
3371                like we're going to do here.  */
3372             print_file(file, 2, "NdrFcLong(0x%x),\t/* %d */\n", c->cval, c->cval);
3373             *tfsoff += 4;
3374             write_branch_type(file, ft, tfsoff);
3375         }
3376
3377         /* MIDL allows multiple default branches, even though that seems
3378            illogical, it just chooses the last one, which is what we will
3379            do.  */
3380         if (deflt)
3381         {
3382             deftype = ft;
3383             nodeftype = 0;
3384         }
3385     }
3386
3387     if (deftype)
3388     {
3389         write_branch_type(file, deftype, tfsoff);
3390     }
3391     else
3392     {
3393         print_file(file, 2, "NdrFcShort(0x%hx),\n", nodeftype);
3394         *tfsoff += 2;
3395     }
3396
3397     return start_offset;
3398 }
3399
3400 static unsigned int write_ip_tfs(FILE *file, const attr_list_t *attrs, type_t *type,
3401                                  unsigned int *typeformat_offset)
3402 {
3403     unsigned int i;
3404     unsigned int start_offset = *typeformat_offset;
3405     expr_t *iid = get_attrp(attrs, ATTR_IIDIS);
3406
3407     if (!iid && processed(type)) return type->typestring_offset;
3408
3409     print_start_tfs_comment(file, type, start_offset);
3410     update_tfsoff(type, start_offset, file);
3411
3412     if (iid)
3413     {
3414         print_file(file, 2, "0x2f,  /* FC_IP */\n");
3415         print_file(file, 2, "0x5c,  /* FC_PAD */\n");
3416         *typeformat_offset
3417             += write_conf_or_var_desc(file, current_structure, 0, type, iid) + 2;
3418     }
3419     else
3420     {
3421         const type_t *base = is_ptr(type) ? type_pointer_get_ref(type) : type;
3422         const UUID *uuid = get_attrp(base->attrs, ATTR_UUID);
3423
3424         if (! uuid)
3425             error("%s: interface %s missing UUID\n", __FUNCTION__, base->name);
3426
3427         print_file(file, 2, "0x2f,\t/* FC_IP */\n");
3428         print_file(file, 2, "0x5a,\t/* FC_CONSTANT_IID */\n");
3429         print_file(file, 2, "NdrFcLong(0x%08x),\n", uuid->Data1);
3430         print_file(file, 2, "NdrFcShort(0x%04x),\n", uuid->Data2);
3431         print_file(file, 2, "NdrFcShort(0x%04x),\n", uuid->Data3);
3432         for (i = 0; i < 8; ++i)
3433             print_file(file, 2, "0x%02x,\n", uuid->Data4[i]);
3434
3435         if (file)
3436             fprintf(file, "\n");
3437
3438         *typeformat_offset += 18;
3439     }
3440     return start_offset;
3441 }
3442
3443 static unsigned int write_contexthandle_tfs(FILE *file,
3444                                             const attr_list_t *attrs,
3445                                             type_t *type,
3446                                             int toplevel_param,
3447                                             unsigned int *typeformat_offset)
3448 {
3449     unsigned int start_offset = *typeformat_offset;
3450     unsigned char flags = get_contexthandle_flags( current_iface, attrs, type );
3451
3452     print_start_tfs_comment(file, type, start_offset);
3453
3454     if (flags & 0x80)  /* via ptr */
3455     {
3456         int pointer_type = get_pointer_fc( type, attrs, toplevel_param );
3457         if (!pointer_type) pointer_type = RPC_FC_RP;
3458         *typeformat_offset += 4;
3459         print_file(file, 2,"0x%x, 0x0,\t/* %s */\n", pointer_type, string_of_type(pointer_type) );
3460         print_file(file, 2, "NdrFcShort(0x2),\t /* Offset= 2 (%u) */\n", *typeformat_offset);
3461         print_file(file, 0, "/* %2u */\n", *typeformat_offset);
3462     }
3463
3464     print_file(file, 2, "0x%02x,\t/* FC_BIND_CONTEXT */\n", RPC_FC_BIND_CONTEXT);
3465     print_file(file, 2, "0x%x,\t/* Context flags: ", flags);
3466     /* return and can't be null values overlap */
3467     if (((flags & 0x21) != 0x21) && (flags & NDR_CONTEXT_HANDLE_CANNOT_BE_NULL))
3468         print_file(file, 0, "can't be null, ");
3469     if (flags & NDR_CONTEXT_HANDLE_SERIALIZE)
3470         print_file(file, 0, "serialize, ");
3471     if (flags & NDR_CONTEXT_HANDLE_NO_SERIALIZE)
3472         print_file(file, 0, "no serialize, ");
3473     if (flags & NDR_STRICT_CONTEXT_HANDLE)
3474         print_file(file, 0, "strict, ");
3475     if ((flags & 0x21) == 0x20)
3476         print_file(file, 0, "out, ");
3477     if ((flags & 0x21) == 0x21)
3478         print_file(file, 0, "return, ");
3479     if (flags & 0x40)
3480         print_file(file, 0, "in, ");
3481     if (flags & 0x80)
3482         print_file(file, 0, "via ptr, ");
3483     print_file(file, 0, "*/\n");
3484     print_file(file, 2, "0x%x,\t/* rundown routine */\n", get_context_handle_offset( type ));
3485     print_file(file, 2, "0, /* FIXME: param num */\n");
3486     *typeformat_offset += 4;
3487
3488     update_tfsoff( type, start_offset, file );
3489     return start_offset;
3490 }
3491
3492 static unsigned int write_range_tfs(FILE *file, const attr_list_t *attrs,
3493                                     type_t *type, expr_list_t *range_list,
3494                                     unsigned int *typeformat_offset)
3495 {
3496     unsigned char fc;
3497     unsigned int start_offset = *typeformat_offset;
3498     const expr_t *range_min = LIST_ENTRY(list_head(range_list), const expr_t, entry);
3499     const expr_t *range_max = LIST_ENTRY(list_next(range_list, list_head(range_list)), const expr_t, entry);
3500
3501     if (type_get_type(type) == TYPE_BASIC)
3502         fc = get_basic_fc(type);
3503     else
3504         fc = get_enum_fc(type);
3505
3506     /* fc must fit in lower 4-bits of 8-bit field below */
3507     assert(fc <= 0xf);
3508
3509     print_file(file, 0, "/* %u */\n", *typeformat_offset);
3510     print_file(file, 2, "0x%x,\t/* FC_RANGE */\n", RPC_FC_RANGE);
3511     print_file(file, 2, "0x%x,\t/* %s */\n", fc, string_of_type(fc));
3512     print_file(file, 2, "NdrFcLong(0x%x),\t/* %u */\n", range_min->cval, range_min->cval);
3513     print_file(file, 2, "NdrFcLong(0x%x),\t/* %u */\n", range_max->cval, range_max->cval);
3514     update_tfsoff( type, start_offset, file );
3515     *typeformat_offset += 10;
3516
3517     return start_offset;
3518 }
3519
3520 static unsigned int write_type_tfs(FILE *file, int indent,
3521                                    const attr_list_t *attrs, type_t *type,
3522                                    const char *name,
3523                                    enum type_context context,
3524                                    unsigned int *typeformat_offset)
3525 {
3526     unsigned int offset;
3527
3528     switch (typegen_detect_type(type, attrs, TDT_ALL_TYPES))
3529     {
3530     case TGT_CTXT_HANDLE:
3531     case TGT_CTXT_HANDLE_POINTER:
3532         return write_contexthandle_tfs(file, attrs, type,
3533                                        context == TYPE_CONTEXT_TOPLEVELPARAM, typeformat_offset);
3534     case TGT_USER_TYPE:
3535         return write_user_tfs(file, type, typeformat_offset);
3536     case TGT_STRING:
3537         return write_string_tfs(file, attrs, type, context, name, typeformat_offset);
3538     case TGT_ARRAY:
3539     {
3540         unsigned int off;
3541         /* conformant and pointer arrays are handled specially */
3542         if ((context != TYPE_CONTEXT_CONTAINER &&
3543              context != TYPE_CONTEXT_CONTAINER_NO_POINTERS) ||
3544             !is_conformant_array(type) || type_array_is_decl_as_ptr(type))
3545             off = write_array_tfs(file, attrs, type, name, typeformat_offset);
3546         else
3547             off = 0;
3548         if (context != TYPE_CONTEXT_CONTAINER &&
3549             context != TYPE_CONTEXT_CONTAINER_NO_POINTERS)
3550         {
3551             int ptr_type;
3552             ptr_type = get_pointer_fc(type, attrs,
3553                                       context == TYPE_CONTEXT_TOPLEVELPARAM);
3554             if (ptr_type != RPC_FC_RP || type_array_is_decl_as_ptr(type))
3555             {
3556                 unsigned int absoff = type->typestring_offset;
3557                 short reloff = absoff - (*typeformat_offset + 2);
3558                 off = *typeformat_offset;
3559                 print_file(file, 0, "/* %d */\n", off);
3560                 print_file(file, 2, "0x%x, 0x0,\t/* %s */\n", ptr_type,
3561                            string_of_type(ptr_type));
3562                 print_file(file, 2, "NdrFcShort(0x%hx),\t/* Offset= %hd (%u) */\n",
3563                            reloff, reloff, absoff);
3564                 if (ptr_type != RPC_FC_RP) update_tfsoff( type, off, file );
3565                 *typeformat_offset += 4;
3566             }
3567             type->details.array.ptr_tfsoff = off;
3568         }
3569         return off;
3570     }
3571     case TGT_STRUCT:
3572         return write_struct_tfs(file, type, name, typeformat_offset);
3573     case TGT_UNION:
3574         return write_union_tfs(file, attrs, type, typeformat_offset);
3575     case TGT_ENUM:
3576     case TGT_BASIC:
3577         /* nothing to do */
3578         return 0;
3579     case TGT_RANGE:
3580     {
3581         expr_list_t *range_list = get_attrp(attrs, ATTR_RANGE);
3582         if (!range_list)
3583             range_list = get_aliaschain_attrp(type, ATTR_RANGE);
3584         return write_range_tfs(file, attrs, type, range_list, typeformat_offset);
3585     }
3586     case TGT_IFACE_POINTER:
3587         return write_ip_tfs(file, attrs, type, typeformat_offset);
3588     case TGT_POINTER:
3589     {
3590         enum type_context ref_context;
3591         if (context == TYPE_CONTEXT_TOPLEVELPARAM)
3592             ref_context = TYPE_CONTEXT_PARAM;
3593         else if (context == TYPE_CONTEXT_CONTAINER_NO_POINTERS)
3594             ref_context = TYPE_CONTEXT_CONTAINER;
3595         else
3596             ref_context = context;
3597         offset = write_type_tfs( file, indent, attrs, type_pointer_get_ref(type), name,
3598                                  ref_context, typeformat_offset);
3599         if (context == TYPE_CONTEXT_CONTAINER_NO_POINTERS)
3600             return 0;
3601         return write_pointer_tfs(file, attrs, type, offset, context, typeformat_offset);
3602     }
3603     case TGT_INVALID:
3604         break;
3605     }
3606     error("invalid type %s for var %s\n", type->name, name);
3607     return 0;
3608 }
3609
3610 static int write_embedded_types(FILE *file, const attr_list_t *attrs, type_t *type,
3611                                 const char *name, int write_ptr, unsigned int *tfsoff)
3612 {
3613     return write_type_tfs(file, 2, attrs, type, name, write_ptr ? TYPE_CONTEXT_CONTAINER : TYPE_CONTEXT_CONTAINER_NO_POINTERS, tfsoff);
3614 }
3615
3616 static unsigned int process_tfs_stmts(FILE *file, const statement_list_t *stmts,
3617                                       type_pred_t pred, unsigned int *typeformat_offset)
3618 {
3619     const var_t *var;
3620     const statement_t *stmt;
3621
3622     if (stmts) LIST_FOR_EACH_ENTRY( stmt, stmts, const statement_t, entry )
3623     {
3624         const type_t *iface;
3625         const statement_t *stmt_func;
3626
3627         if (stmt->type == STMT_LIBRARY)
3628         {
3629             process_tfs_stmts(file, stmt->u.lib->stmts, pred, typeformat_offset);
3630             continue;
3631         }
3632         else if (stmt->type != STMT_TYPE || type_get_type(stmt->u.type) != TYPE_INTERFACE)
3633             continue;
3634
3635         iface = stmt->u.type;
3636         if (!pred(iface))
3637             continue;
3638
3639         current_iface = iface;
3640         STATEMENTS_FOR_EACH_FUNC( stmt_func, type_iface_get_stmts(iface) )
3641         {
3642             const var_t *func = stmt_func->u.var;
3643             current_func = func;
3644             if (is_local(func->attrs)) continue;
3645
3646             if (!is_void(type_function_get_rettype(func->type)))
3647             {
3648                 write_type_tfs( file, 2, func->attrs, type_function_get_rettype(func->type),
3649                                 func->name, TYPE_CONTEXT_PARAM, typeformat_offset);
3650             }
3651
3652             if (type_get_function_args(func->type))
3653                 LIST_FOR_EACH_ENTRY( var, type_get_function_args(func->type), const var_t, entry )
3654                     write_type_tfs( file, 2, var->attrs, var->type, var->name,
3655                                     TYPE_CONTEXT_TOPLEVELPARAM, typeformat_offset );
3656         }
3657     }
3658
3659     return *typeformat_offset + 1;
3660 }
3661
3662 static unsigned int process_tfs(FILE *file, const statement_list_t *stmts, type_pred_t pred)
3663 {
3664     unsigned int typeformat_offset = 2;
3665
3666     return process_tfs_stmts(file, stmts, pred, &typeformat_offset);
3667 }
3668
3669
3670 void write_typeformatstring(FILE *file, const statement_list_t *stmts, type_pred_t pred)
3671 {
3672     int indent = 0;
3673
3674     print_file(file, indent, "static const MIDL_TYPE_FORMAT_STRING __MIDL_TypeFormatString =\n");
3675     print_file(file, indent, "{\n");
3676     indent++;
3677     print_file(file, indent, "0,\n");
3678     print_file(file, indent, "{\n");
3679     indent++;
3680     print_file(file, indent, "NdrFcShort(0x0),\n");
3681
3682     set_all_tfswrite(TRUE);
3683     process_tfs(file, stmts, pred);
3684
3685     print_file(file, indent, "0x0\n");
3686     indent--;
3687     print_file(file, indent, "}\n");
3688     indent--;
3689     print_file(file, indent, "};\n");
3690     print_file(file, indent, "\n");
3691 }
3692
3693 static unsigned int get_required_buffer_size_type(
3694     const type_t *type, const char *name, const attr_list_t *attrs, int toplevel_param, unsigned int *alignment)
3695 {
3696     *alignment = 0;
3697     switch (typegen_detect_type(type, NULL, TDT_IGNORE_RANGES))
3698     {
3699     case TGT_USER_TYPE:
3700     {
3701         const char *uname;
3702         const type_t *utype = get_user_type(type, &uname);
3703         return get_required_buffer_size_type(utype, uname, NULL, FALSE, alignment);
3704     }
3705     case TGT_BASIC:
3706         switch (get_basic_fc(type))
3707         {
3708         case RPC_FC_BYTE:
3709         case RPC_FC_CHAR:
3710         case RPC_FC_USMALL:
3711         case RPC_FC_SMALL:
3712             *alignment = 4;
3713             return 1;
3714
3715         case RPC_FC_WCHAR:
3716         case RPC_FC_USHORT:
3717         case RPC_FC_SHORT:
3718             *alignment = 4;
3719             return 2;
3720
3721         case RPC_FC_ULONG:
3722         case RPC_FC_LONG:
3723         case RPC_FC_FLOAT:
3724         case RPC_FC_ERROR_STATUS_T:
3725             *alignment = 4;
3726             return 4;
3727
3728         case RPC_FC_HYPER:
3729         case RPC_FC_DOUBLE:
3730             *alignment = 8;
3731             return 8;
3732
3733         case RPC_FC_INT3264:
3734         case RPC_FC_UINT3264:
3735             assert( pointer_size );
3736             *alignment = pointer_size;
3737             return pointer_size;
3738
3739         case RPC_FC_IGNORE:
3740         case RPC_FC_BIND_PRIMITIVE:
3741             return 0;
3742
3743         default:
3744             error("get_required_buffer_size: unknown basic type 0x%02x\n",
3745                   get_basic_fc(type));
3746             return 0;
3747         }
3748         break;
3749
3750     case TGT_ENUM:
3751         switch (get_enum_fc(type))
3752         {
3753         case RPC_FC_ENUM32:
3754             *alignment = 4;
3755             return 4;
3756         case RPC_FC_ENUM16:
3757             *alignment = 4;
3758             return 2;
3759         }
3760         break;
3761
3762     case TGT_STRUCT:
3763         if (get_struct_fc(type) == RPC_FC_STRUCT)
3764         {
3765             if (!type_struct_get_fields(type)) return 0;
3766             return fields_memsize(type_struct_get_fields(type), alignment);
3767         }
3768         break;
3769
3770     case TGT_POINTER:
3771         {
3772             unsigned int size, align;
3773             const type_t *ref = type_pointer_get_ref(type);
3774             if (is_string_type( attrs, ref )) break;
3775             if (!(size = get_required_buffer_size_type( ref, name, NULL, FALSE, &align ))) break;
3776             if (get_pointer_fc(type, attrs, toplevel_param) != RPC_FC_RP)
3777             {
3778                 size += 4 + align;
3779                 align = 4;
3780             }
3781             *alignment = align;
3782             return size;
3783         }
3784
3785     case TGT_ARRAY:
3786         if (get_pointer_fc(type, attrs, toplevel_param) == RPC_FC_RP)
3787         {
3788             switch (get_array_fc(type))
3789             {
3790             case RPC_FC_SMFARRAY:
3791             case RPC_FC_LGFARRAY:
3792                 return type_array_get_dim(type) *
3793                     get_required_buffer_size_type(type_array_get_element(type), name,
3794                                                   NULL, FALSE, alignment);
3795             }
3796         }
3797         break;
3798
3799     default:
3800         break;
3801     }
3802     return 0;
3803 }
3804
3805 static unsigned int get_required_buffer_size(const var_t *var, unsigned int *alignment, enum pass pass)
3806 {
3807     int in_attr = is_attr(var->attrs, ATTR_IN);
3808     int out_attr = is_attr(var->attrs, ATTR_OUT);
3809
3810     if (!in_attr && !out_attr)
3811         in_attr = 1;
3812
3813     *alignment = 0;
3814
3815     if ((pass == PASS_IN && in_attr) || (pass == PASS_OUT && out_attr) ||
3816         pass == PASS_RETURN)
3817     {
3818         if (is_ptrchain_attr(var, ATTR_CONTEXTHANDLE))
3819         {
3820             *alignment = 4;
3821             return 20;
3822         }
3823
3824         if (!is_string_type(var->attrs, var->type))
3825             return get_required_buffer_size_type(var->type, var->name,
3826                                                  var->attrs, TRUE, alignment);
3827     }
3828     return 0;
3829 }
3830
3831 static unsigned int get_function_buffer_size( const var_t *func, enum pass pass )
3832 {
3833     const var_t *var;
3834     unsigned int total_size = 0, alignment;
3835
3836     if (type_get_function_args(func->type))
3837     {
3838         LIST_FOR_EACH_ENTRY( var, type_get_function_args(func->type), const var_t, entry )
3839         {
3840             total_size += get_required_buffer_size(var, &alignment, pass);
3841             total_size += alignment;
3842         }
3843     }
3844
3845     if (pass == PASS_OUT && !is_void(type_function_get_rettype(func->type)))
3846     {
3847         var_t v = *func;
3848         v.type = type_function_get_rettype(func->type);
3849         total_size += get_required_buffer_size(&v, &alignment, PASS_RETURN);
3850         total_size += alignment;
3851     }
3852     return total_size;
3853 }
3854
3855 static void print_phase_function(FILE *file, int indent, const char *type,
3856                                  const char *local_var_prefix, enum remoting_phase phase,
3857                                  const var_t *var, unsigned int type_offset)
3858 {
3859     const char *function;
3860     switch (phase)
3861     {
3862     case PHASE_BUFFERSIZE:
3863         function = "BufferSize";
3864         break;
3865     case PHASE_MARSHAL:
3866         function = "Marshall";
3867         break;
3868     case PHASE_UNMARSHAL:
3869         function = "Unmarshall";
3870         break;
3871     case PHASE_FREE:
3872         function = "Free";
3873         break;
3874     default:
3875         assert(0);
3876         return;
3877     }
3878
3879     print_file(file, indent, "Ndr%s%s(\n", type, function);
3880     indent++;
3881     print_file(file, indent, "&__frame->_StubMsg,\n");
3882     print_file(file, indent, "%s%s%s%s%s,\n",
3883                (phase == PHASE_UNMARSHAL) ? "(unsigned char **)" : "(unsigned char *)",
3884                (phase == PHASE_UNMARSHAL || decl_indirect(var->type)) ? "&" : "",
3885                local_var_prefix,
3886                (phase == PHASE_UNMARSHAL && decl_indirect(var->type)) ? "_p_" : "",
3887                var->name);
3888     print_file(file, indent, "(PFORMAT_STRING)&__MIDL_TypeFormatString.Format[%d]%s\n",
3889                type_offset, (phase == PHASE_UNMARSHAL) ? "," : ");");
3890     if (phase == PHASE_UNMARSHAL)
3891         print_file(file, indent, "0);\n");
3892     indent--;
3893 }
3894
3895 void print_phase_basetype(FILE *file, int indent, const char *local_var_prefix,
3896                           enum remoting_phase phase, enum pass pass, const var_t *var,
3897                           const char *varname)
3898 {
3899     type_t *type = var->type;
3900     unsigned int alignment = 0;
3901
3902     /* no work to do for other phases, buffer sizing is done elsewhere */
3903     if (phase != PHASE_MARSHAL && phase != PHASE_UNMARSHAL)
3904         return;
3905
3906     if (type_get_type(type) == TYPE_ENUM ||
3907         (type_get_type(type) == TYPE_BASIC &&
3908          type_basic_get_type(type) == TYPE_BASIC_INT3264 &&
3909          pointer_size != 4))
3910     {
3911         unsigned char fc;
3912
3913         if (type_get_type(type) == TYPE_ENUM)
3914             fc = get_enum_fc(type);
3915         else
3916             fc = get_basic_fc(type);
3917
3918         if (phase == PHASE_MARSHAL)
3919             print_file(file, indent, "NdrSimpleTypeMarshall(\n");
3920         else
3921             print_file(file, indent, "NdrSimpleTypeUnmarshall(\n");
3922         print_file(file, indent+1, "&__frame->_StubMsg,\n");
3923         print_file(file, indent+1, "(unsigned char *)&%s%s,\n",
3924                    local_var_prefix,
3925                    var->name);
3926         print_file(file, indent+1, "0x%02x /* %s */);\n", fc, string_of_type(fc));
3927     }
3928     else
3929     {
3930         const type_t *ref = is_ptr(type) ? type_pointer_get_ref(type) : type;
3931         switch (get_basic_fc(ref))
3932         {
3933         case RPC_FC_BYTE:
3934         case RPC_FC_CHAR:
3935         case RPC_FC_SMALL:
3936         case RPC_FC_USMALL:
3937             alignment = 1;
3938             break;
3939
3940         case RPC_FC_WCHAR:
3941         case RPC_FC_USHORT:
3942         case RPC_FC_SHORT:
3943             alignment = 2;
3944             break;
3945
3946         case RPC_FC_ULONG:
3947         case RPC_FC_LONG:
3948         case RPC_FC_FLOAT:
3949         case RPC_FC_ERROR_STATUS_T:
3950         /* pointer_size must be 4 if we got here in these two cases */
3951         case RPC_FC_INT3264:
3952         case RPC_FC_UINT3264:
3953             alignment = 4;
3954             break;
3955
3956         case RPC_FC_HYPER:
3957         case RPC_FC_DOUBLE:
3958             alignment = 8;
3959             break;
3960
3961         case RPC_FC_IGNORE:
3962         case RPC_FC_BIND_PRIMITIVE:
3963             /* no marshalling needed */
3964             return;
3965
3966         default:
3967             error("print_phase_basetype: Unsupported type: %s (0x%02x, ptr_level: 0)\n",
3968                   var->name, get_basic_fc(ref));
3969         }
3970
3971         if (phase == PHASE_MARSHAL && alignment > 1)
3972             print_file(file, indent, "MIDL_memset(__frame->_StubMsg.Buffer, 0, (0x%x - (ULONG_PTR)__frame->_StubMsg.Buffer) & 0x%x);\n", alignment, alignment - 1);
3973         print_file(file, indent, "__frame->_StubMsg.Buffer = (unsigned char *)(((ULONG_PTR)__frame->_StubMsg.Buffer + %u) & ~0x%x);\n",
3974                     alignment - 1, alignment - 1);
3975
3976         if (phase == PHASE_MARSHAL)
3977         {
3978             print_file(file, indent, "*(");
3979             write_type_decl(file, is_ptr(type) ? type_pointer_get_ref(type) : type, NULL);
3980             if (is_ptr(type))
3981                 fprintf(file, " *)__frame->_StubMsg.Buffer = *");
3982             else
3983                 fprintf(file, " *)__frame->_StubMsg.Buffer = ");
3984             fprintf(file, "%s%s", local_var_prefix, varname);
3985             fprintf(file, ";\n");
3986         }
3987         else if (phase == PHASE_UNMARSHAL)
3988         {
3989             print_file(file, indent, "if (__frame->_StubMsg.Buffer + sizeof(");
3990             write_type_decl(file, is_ptr(type) ? type_pointer_get_ref(type) : type, NULL);
3991             fprintf(file, ") > __frame->_StubMsg.BufferEnd)\n");
3992             print_file(file, indent, "{\n");
3993             print_file(file, indent + 1, "RpcRaiseException(RPC_X_BAD_STUB_DATA);\n");
3994             print_file(file, indent, "}\n");
3995             print_file(file, indent, "%s%s%s",
3996                        (pass == PASS_IN || pass == PASS_RETURN) ? "" : "*",
3997                        local_var_prefix, varname);
3998             if (pass == PASS_IN && is_ptr(type))
3999                 fprintf(file, " = (");
4000             else
4001                 fprintf(file, " = *(");
4002             write_type_decl(file, is_ptr(type) ? type_pointer_get_ref(type) : type, NULL);
4003             fprintf(file, " *)__frame->_StubMsg.Buffer;\n");
4004         }
4005
4006         print_file(file, indent, "__frame->_StubMsg.Buffer += sizeof(");
4007         write_type_decl(file, is_ptr(type) ? type_pointer_get_ref(type) : type, NULL);
4008         fprintf(file, ");\n");
4009     }
4010 }
4011
4012 /* returns whether the MaxCount, Offset or ActualCount members need to be
4013  * filled in for the specified phase */
4014 static inline int is_conformance_needed_for_phase(enum remoting_phase phase)
4015 {
4016     return (phase != PHASE_UNMARSHAL);
4017 }
4018
4019 expr_t *get_size_is_expr(const type_t *t, const char *name)
4020 {
4021     expr_t *x = NULL;
4022
4023     for ( ; is_array(t); t = type_array_get_element(t))
4024         if (type_array_has_conformance(t) &&
4025             type_array_get_conformance(t)->type != EXPR_VOID)
4026         {
4027             if (!x)
4028                 x = type_array_get_conformance(t);
4029             else
4030                 error("%s: multidimensional conformant"
4031                       " arrays not supported at the top level\n",
4032                       name);
4033         }
4034
4035     return x;
4036 }
4037
4038 void write_parameter_conf_or_var_exprs(FILE *file, int indent, const char *local_var_prefix,
4039                                        enum remoting_phase phase, const var_t *var, int valid_variance)
4040 {
4041     const type_t *type = var->type;
4042     /* get fundamental type for the argument */
4043     for (;;)
4044     {
4045         switch (typegen_detect_type(type, var->attrs, TDT_IGNORE_STRINGS|TDT_IGNORE_RANGES))
4046         {
4047         case TGT_ARRAY:
4048             if (is_conformance_needed_for_phase(phase))
4049             {
4050                 if (type_array_has_conformance(type) &&
4051                     type_array_get_conformance(type)->type != EXPR_VOID)
4052                 {
4053                     print_file(file, indent, "__frame->_StubMsg.MaxCount = (ULONG_PTR)");
4054                     write_expr(file, type_array_get_conformance(type), 1, 1, NULL, NULL, local_var_prefix);
4055                     fprintf(file, ";\n\n");
4056                 }
4057                 if (type_array_has_variance(type))
4058                 {
4059                     print_file(file, indent, "__frame->_StubMsg.Offset = 0;\n"); /* FIXME */
4060                     if (valid_variance)
4061                     {
4062                         print_file(file, indent, "__frame->_StubMsg.ActualCount = (ULONG_PTR)");
4063                         write_expr(file, type_array_get_variance(type), 1, 1, NULL, NULL, local_var_prefix);
4064                         fprintf(file, ";\n\n");
4065                     }
4066                     else
4067                         print_file(file, indent, "__frame->_StubMsg.ActualCount = __frame->_StubMsg.MaxCount;\n\n");
4068                 }
4069             }
4070             break;
4071         case TGT_UNION:
4072             if (type_get_type(type) == TYPE_UNION &&
4073                 is_conformance_needed_for_phase(phase))
4074             {
4075                 print_file(file, indent, "__frame->_StubMsg.MaxCount = (ULONG_PTR)");
4076                 write_expr(file, get_attrp(var->attrs, ATTR_SWITCHIS), 1, 1, NULL, NULL, local_var_prefix);
4077                 fprintf(file, ";\n\n");
4078             }
4079             break;
4080         case TGT_IFACE_POINTER:
4081         {
4082             expr_t *iid;
4083
4084             if (is_conformance_needed_for_phase(phase) && (iid = get_attrp( var->attrs, ATTR_IIDIS )))
4085             {
4086                 print_file( file, indent, "__frame->_StubMsg.MaxCount = (ULONG_PTR) " );
4087                 write_expr( file, iid, 1, 1, NULL, NULL, local_var_prefix );
4088                 fprintf( file, ";\n\n" );
4089             }
4090             break;
4091         }
4092         case TGT_POINTER:
4093             type = type_pointer_get_ref(type);
4094             continue;
4095         case TGT_INVALID:
4096         case TGT_USER_TYPE:
4097         case TGT_CTXT_HANDLE:
4098         case TGT_CTXT_HANDLE_POINTER:
4099         case TGT_STRING:
4100         case TGT_BASIC:
4101         case TGT_ENUM:
4102         case TGT_STRUCT:
4103         case TGT_RANGE:
4104             break;
4105         }
4106         break;
4107     }
4108 }
4109
4110 static void write_remoting_arg(FILE *file, int indent, const var_t *func, const char *local_var_prefix,
4111                                enum pass pass, enum remoting_phase phase, const var_t *var)
4112 {
4113     int in_attr, out_attr, pointer_type;
4114     const char *type_str = NULL;
4115     const type_t *type = var->type;
4116     unsigned int alignment, start_offset = type->typestring_offset;
4117
4118     if (is_ptr(type) || is_array(type))
4119         pointer_type = get_pointer_fc(type, var->attrs, pass != PASS_RETURN);
4120     else
4121         pointer_type = 0;
4122
4123     in_attr = is_attr(var->attrs, ATTR_IN);
4124     out_attr = is_attr(var->attrs, ATTR_OUT);
4125     if (!in_attr && !out_attr)
4126         in_attr = 1;
4127
4128     if (phase != PHASE_FREE)
4129         switch (pass)
4130         {
4131         case PASS_IN:
4132             if (!in_attr) return;
4133             break;
4134         case PASS_OUT:
4135             if (!out_attr) return;
4136             break;
4137         case PASS_RETURN:
4138             break;
4139         }
4140
4141     if (phase == PHASE_BUFFERSIZE && get_required_buffer_size( var, &alignment, pass )) return;
4142
4143     write_parameter_conf_or_var_exprs(file, indent, local_var_prefix, phase, var, TRUE);
4144
4145     switch (typegen_detect_type(type, var->attrs, TDT_ALL_TYPES))
4146     {
4147     case TGT_CTXT_HANDLE:
4148     case TGT_CTXT_HANDLE_POINTER:
4149         if (phase == PHASE_MARSHAL)
4150         {
4151             if (pass == PASS_IN)
4152             {
4153                 /* if the context_handle attribute appears in the chain of types
4154                  * without pointers being followed, then the context handle must
4155                  * be direct, otherwise it is a pointer */
4156                 int is_ch_ptr = is_aliaschain_attr(type, ATTR_CONTEXTHANDLE) ? FALSE : TRUE;
4157                 print_file(file, indent, "NdrClientContextMarshall(\n");
4158                 print_file(file, indent + 1, "&__frame->_StubMsg,\n");
4159                 print_file(file, indent + 1, "(NDR_CCONTEXT)%s%s%s,\n", is_ch_ptr ? "*" : "", local_var_prefix, var->name);
4160                 print_file(file, indent + 1, "%s);\n", in_attr && out_attr ? "1" : "0");
4161             }
4162             else
4163             {
4164                 print_file(file, indent, "NdrServerContextNewMarshall(\n");
4165                 print_file(file, indent + 1, "&__frame->_StubMsg,\n");
4166                 print_file(file, indent + 1, "(NDR_SCONTEXT)%s%s,\n", local_var_prefix, var->name);
4167                 print_file(file, indent + 1, "(NDR_RUNDOWN)%s_rundown,\n", get_context_handle_type_name(var->type));
4168                 print_file(file, indent + 1, "(PFORMAT_STRING)&__MIDL_TypeFormatString.Format[%d]);\n", start_offset);
4169             }
4170         }
4171         else if (phase == PHASE_UNMARSHAL)
4172         {
4173             if (pass == PASS_OUT)
4174             {
4175                 if (!in_attr)
4176                     print_file(file, indent, "*%s%s = 0;\n", local_var_prefix, var->name);
4177                 print_file(file, indent, "NdrClientContextUnmarshall(\n");
4178                 print_file(file, indent + 1, "&__frame->_StubMsg,\n");
4179                 print_file(file, indent + 1, "(NDR_CCONTEXT *)%s%s,\n", local_var_prefix, var->name);
4180                 print_file(file, indent + 1, "__frame->_Handle);\n");
4181             }
4182             else
4183             {
4184                 print_file(file, indent, "%s%s = NdrServerContextNewUnmarshall(\n", local_var_prefix, var->name);
4185                 print_file(file, indent + 1, "&__frame->_StubMsg,\n");
4186                 print_file(file, indent + 1, "(PFORMAT_STRING)&__MIDL_TypeFormatString.Format[%d]);\n", start_offset);
4187             }
4188         }
4189         break;
4190     case TGT_USER_TYPE:
4191         print_phase_function(file, indent, "UserMarshal", local_var_prefix, phase, var, start_offset);
4192         break;
4193     case TGT_STRING:
4194         if (phase == PHASE_FREE || pass == PASS_RETURN ||
4195             pointer_type != RPC_FC_RP)
4196         {
4197             /* strings returned are assumed to be global and hence don't
4198              * need freeing */
4199             if (is_declptr(type) && !(phase == PHASE_FREE && pass == PASS_RETURN))
4200                 print_phase_function(file, indent, "Pointer", local_var_prefix,
4201                                      phase, var, start_offset);
4202             else if (pointer_type == RPC_FC_RP && phase == PHASE_FREE &&
4203                 !in_attr && is_conformant_array(type))
4204             {
4205                 print_file(file, indent, "if (%s%s)\n", local_var_prefix, var->name);
4206                 indent++;
4207                 print_file(file, indent, "__frame->_StubMsg.pfnFree(%s%s);\n", local_var_prefix, var->name);
4208             }
4209         }
4210         else
4211         {
4212             unsigned int real_start_offset = start_offset;
4213             /* skip over pointer description straight to string description */
4214             if (is_declptr(type))
4215             {
4216                 if (is_conformant_array(type))
4217                     real_start_offset += 4;
4218                 else
4219                     real_start_offset += 2;
4220             }
4221             if (is_array(type) && !is_conformant_array(type))
4222                 print_phase_function(file, indent, "NonConformantString",
4223                                      local_var_prefix, phase, var,
4224                                      real_start_offset);
4225             else
4226                 print_phase_function(file, indent, "ConformantString", local_var_prefix,
4227                                      phase, var, real_start_offset);
4228         }
4229         break;
4230     case TGT_ARRAY:
4231     {
4232         unsigned char tc = get_array_fc(type);
4233         const char *array_type = NULL;
4234
4235         /* We already have the size_is expression since it's at the
4236            top level, but do checks for multidimensional conformant
4237            arrays.  When we handle them, we'll need to extend this
4238            function to return a list, and then we'll actually use
4239            the return value.  */
4240         get_size_is_expr(type, var->name);
4241
4242         switch (tc)
4243         {
4244         case RPC_FC_SMFARRAY:
4245         case RPC_FC_LGFARRAY:
4246             array_type = "FixedArray";
4247             break;
4248         case RPC_FC_SMVARRAY:
4249         case RPC_FC_LGVARRAY:
4250             array_type = "VaryingArray";
4251             break;
4252         case RPC_FC_CARRAY:
4253             array_type = "ConformantArray";
4254             break;
4255         case RPC_FC_CVARRAY:
4256             array_type = "ConformantVaryingArray";
4257             break;
4258         case RPC_FC_BOGUS_ARRAY:
4259             array_type = "ComplexArray";
4260             break;
4261         }
4262
4263         if (pointer_type != RPC_FC_RP) array_type = "Pointer";
4264
4265         if (phase == PHASE_FREE && pointer_type == RPC_FC_RP)
4266         {
4267             /* these are all unmarshalled by allocating memory */
4268             if (tc == RPC_FC_BOGUS_ARRAY ||
4269                 tc == RPC_FC_CVARRAY ||
4270                 ((tc == RPC_FC_SMVARRAY || tc == RPC_FC_LGVARRAY) && in_attr) ||
4271                 (tc == RPC_FC_CARRAY && !in_attr))
4272             {
4273                 if (type_array_is_decl_as_ptr(type) && type->details.array.ptr_tfsoff)
4274                 {
4275                     print_phase_function(file, indent, "Pointer", local_var_prefix, phase, var,
4276                                          type->details.array.ptr_tfsoff);
4277                     break;
4278                 }
4279                 print_phase_function(file, indent, array_type, local_var_prefix, phase, var, start_offset);
4280                 print_file(file, indent, "if (%s%s)\n", local_var_prefix, var->name);
4281                 indent++;
4282                 print_file(file, indent, "__frame->_StubMsg.pfnFree(%s%s);\n", local_var_prefix, var->name);
4283                 break;
4284             }
4285         }
4286         print_phase_function(file, indent, array_type, local_var_prefix, phase, var, start_offset);
4287         break;
4288     }
4289     case TGT_BASIC:
4290         print_phase_basetype(file, indent, local_var_prefix, phase, pass, var, var->name);
4291         break;
4292     case TGT_ENUM:
4293         print_phase_basetype(file, indent, local_var_prefix, phase, pass, var, var->name);
4294         break;
4295     case TGT_RANGE:
4296         print_phase_basetype(file, indent, local_var_prefix, phase, pass, var, var->name);
4297         /* Note: this goes beyond what MIDL does - it only supports arguments
4298          * with the [range] attribute in Oicf mode */
4299         if (phase == PHASE_UNMARSHAL)
4300         {
4301             const expr_t *range_min;
4302             const expr_t *range_max;
4303             expr_list_t *range_list = get_attrp(var->attrs, ATTR_RANGE);
4304             if (!range_list)
4305                 range_list = get_aliaschain_attrp(type, ATTR_RANGE);
4306             range_min = LIST_ENTRY(list_head(range_list), const expr_t, entry);
4307             range_max = LIST_ENTRY(list_next(range_list, list_head(range_list)), const expr_t, entry);
4308
4309             print_file(file, indent, "if ((%s%s < (", local_var_prefix, var->name);
4310             write_type_decl(file, var->type, NULL);
4311             fprintf(file, ")0x%x) || (%s%s > (", range_min->cval, local_var_prefix, var->name);
4312             write_type_decl(file, var->type, NULL);
4313             fprintf(file, ")0x%x))\n", range_max->cval);
4314             print_file(file, indent, "{\n");
4315             print_file(file, indent+1, "RpcRaiseException(RPC_S_INVALID_BOUND);\n");
4316             print_file(file, indent, "}\n");
4317         }
4318         break;
4319     case TGT_STRUCT:
4320         switch (get_struct_fc(type))
4321         {
4322         case RPC_FC_STRUCT:
4323             if (phase == PHASE_MARSHAL || phase == PHASE_UNMARSHAL)
4324                 print_phase_function(file, indent, "SimpleStruct", local_var_prefix, phase, var, start_offset);
4325             break;
4326         case RPC_FC_PSTRUCT:
4327             print_phase_function(file, indent, "SimpleStruct", local_var_prefix, phase, var, start_offset);
4328             break;
4329         case RPC_FC_CSTRUCT:
4330         case RPC_FC_CPSTRUCT:
4331             print_phase_function(file, indent, "ConformantStruct", local_var_prefix, phase, var, start_offset);
4332             break;
4333         case RPC_FC_CVSTRUCT:
4334             print_phase_function(file, indent, "ConformantVaryingStruct", local_var_prefix, phase, var, start_offset);
4335             break;
4336         case RPC_FC_BOGUS_STRUCT:
4337             print_phase_function(file, indent, "ComplexStruct", local_var_prefix, phase, var, start_offset);
4338             break;
4339         default:
4340             error("write_remoting_arguments: Unsupported type: %s (0x%02x)\n", var->name, get_struct_fc(type));
4341         }
4342         break;
4343     case TGT_UNION:
4344     {
4345         const char *union_type = NULL;
4346
4347         if (type_get_type(type) == TYPE_UNION)
4348             union_type = "NonEncapsulatedUnion";
4349         else if (type_get_type(type) == TYPE_ENCAPSULATED_UNION)
4350             union_type = "EncapsulatedUnion";
4351
4352         print_phase_function(file, indent, union_type, local_var_prefix,
4353                              phase, var, start_offset);
4354         break;
4355     }
4356     case TGT_POINTER:
4357     {
4358         const type_t *ref = type_pointer_get_ref(type);
4359         if (pointer_type == RPC_FC_RP) switch (typegen_detect_type(ref, NULL, TDT_ALL_TYPES))
4360         {
4361         case TGT_BASIC:
4362             print_phase_basetype(file, indent, local_var_prefix, phase, pass, var, var->name);
4363             break;
4364         case TGT_ENUM:
4365             /* base types have known sizes, so don't need a sizing pass
4366              * and don't have any memory to free and so don't need a
4367              * freeing pass */
4368             if (phase == PHASE_MARSHAL || phase == PHASE_UNMARSHAL)
4369                 print_phase_function(file, indent, "Pointer", local_var_prefix, phase, var, start_offset);
4370             break;
4371         case TGT_STRUCT:
4372             switch (get_struct_fc(ref))
4373             {
4374             case RPC_FC_STRUCT:
4375                 /* simple structs have known sizes, so don't need a sizing
4376                  * pass and don't have any memory to free and so don't
4377                  * need a freeing pass */
4378                 if (phase == PHASE_MARSHAL || phase == PHASE_UNMARSHAL)
4379                     type_str = "SimpleStruct";
4380                 else if (phase == PHASE_FREE && pass == PASS_RETURN)
4381                 {
4382                     print_file(file, indent, "if (%s%s)\n", local_var_prefix, var->name);
4383                     indent++;
4384                     print_file(file, indent, "__frame->_StubMsg.pfnFree(%s%s);\n", local_var_prefix, var->name);
4385                     indent--;
4386                 }
4387                 break;
4388             case RPC_FC_PSTRUCT:
4389                 type_str = "SimpleStruct";
4390                 break;
4391             case RPC_FC_CSTRUCT:
4392             case RPC_FC_CPSTRUCT:
4393                 type_str = "ConformantStruct";
4394                 break;
4395             case RPC_FC_CVSTRUCT:
4396                 type_str = "ConformantVaryingStruct";
4397                 break;
4398             case RPC_FC_BOGUS_STRUCT:
4399                 type_str = "ComplexStruct";
4400                 break;
4401             default:
4402                 error("write_remoting_arguments: Unsupported type: %s (0x%02x)\n", var->name, get_struct_fc(ref));
4403             }
4404
4405             if (type_str)
4406             {
4407                 if (phase == PHASE_FREE)
4408                     type_str = "Pointer";
4409                 else
4410                     start_offset = ref->typestring_offset;
4411                 print_phase_function(file, indent, type_str, local_var_prefix, phase, var, start_offset);
4412             }
4413             break;
4414         case TGT_UNION:
4415             if (phase == PHASE_FREE)
4416                 type_str = "Pointer";
4417             else
4418             {
4419                 if (type_get_type(ref) == TYPE_UNION)
4420                     type_str = "NonEncapsulatedUnion";
4421                 else if (type_get_type(ref) == TYPE_ENCAPSULATED_UNION)
4422                     type_str = "EncapsulatedUnion";
4423
4424                 start_offset = ref->typestring_offset;
4425             }
4426
4427             print_phase_function(file, indent, type_str, local_var_prefix,
4428                                  phase, var, start_offset);
4429             break;
4430         case TGT_USER_TYPE:
4431             if (phase != PHASE_FREE)
4432             {
4433                 type_str = "UserMarshal";
4434                 start_offset = ref->typestring_offset;
4435             }
4436             else type_str = "Pointer";
4437
4438             print_phase_function(file, indent, type_str, local_var_prefix, phase, var, start_offset);
4439             break;
4440         case TGT_STRING:
4441         case TGT_POINTER:
4442         case TGT_ARRAY:
4443         case TGT_RANGE:
4444         case TGT_IFACE_POINTER:
4445         case TGT_CTXT_HANDLE:
4446         case TGT_CTXT_HANDLE_POINTER:
4447             print_phase_function(file, indent, "Pointer", local_var_prefix, phase, var, start_offset);
4448             break;
4449         case TGT_INVALID:
4450             assert(0);
4451             break;
4452         }
4453         else
4454             print_phase_function(file, indent, "Pointer", local_var_prefix, phase, var, start_offset);
4455         break;
4456     }
4457     case TGT_IFACE_POINTER:
4458         print_phase_function(file, indent, "InterfacePointer", local_var_prefix, phase, var, start_offset);
4459         break;
4460     case TGT_INVALID:
4461         assert(0);
4462         break;
4463     }
4464     fprintf(file, "\n");
4465 }
4466
4467 void write_remoting_arguments(FILE *file, int indent, const var_t *func, const char *local_var_prefix,
4468                               enum pass pass, enum remoting_phase phase)
4469 {
4470     if (phase == PHASE_BUFFERSIZE && pass != PASS_RETURN)
4471     {
4472         unsigned int size = get_function_buffer_size( func, pass );
4473         print_file(file, indent, "__frame->_StubMsg.BufferLength = %u;\n", size);
4474     }
4475
4476     if (pass == PASS_RETURN)
4477     {
4478         var_t var;
4479         var = *func;
4480         var.type = type_function_get_rettype(func->type);
4481         var.name = xstrdup( "_RetVal" );
4482         write_remoting_arg( file, indent, func, local_var_prefix, pass, phase, &var );
4483         free( var.name );
4484     }
4485     else
4486     {
4487         const var_t *var;
4488         if (!type_get_function_args(func->type))
4489             return;
4490         LIST_FOR_EACH_ENTRY( var, type_get_function_args(func->type), const var_t, entry )
4491             write_remoting_arg( file, indent, func, local_var_prefix, pass, phase, var );
4492     }
4493 }
4494
4495
4496 unsigned int get_size_procformatstring_func(const type_t *iface, const var_t *func)
4497 {
4498     unsigned int offset = 0;
4499     write_procformatstring_func( NULL, 0, iface, func, &offset, 0 );
4500     return offset;
4501 }
4502
4503 unsigned int get_size_procformatstring(const statement_list_t *stmts, type_pred_t pred)
4504 {
4505     const statement_t *stmt;
4506     unsigned int size = 1;
4507
4508     if (stmts) LIST_FOR_EACH_ENTRY( stmt, stmts, const statement_t, entry )
4509     {
4510         const type_t *iface;
4511         const statement_t *stmt_func;
4512
4513         if (stmt->type == STMT_LIBRARY)
4514         {
4515             size += get_size_procformatstring(stmt->u.lib->stmts, pred) - 1;
4516             continue;
4517         }
4518         else if (stmt->type != STMT_TYPE || type_get_type(stmt->u.type) != TYPE_INTERFACE)
4519             continue;
4520
4521         iface = stmt->u.type;
4522         if (!pred(iface))
4523             continue;
4524
4525         STATEMENTS_FOR_EACH_FUNC( stmt_func, type_iface_get_stmts(iface) )
4526         {
4527             const var_t *func = stmt_func->u.var;
4528             if (!is_local(func->attrs))
4529                 size += get_size_procformatstring_func( iface, func );
4530         }
4531     }
4532     return size;
4533 }
4534
4535 unsigned int get_size_typeformatstring(const statement_list_t *stmts, type_pred_t pred)
4536 {
4537     set_all_tfswrite(FALSE);
4538     return process_tfs(NULL, stmts, pred);
4539 }
4540
4541 void declare_stub_args( FILE *file, int indent, const var_t *func )
4542 {
4543     int in_attr, out_attr;
4544     int i = 0;
4545     const var_t *var;
4546
4547     /* declare return value '_RetVal' */
4548     if (!is_void(type_function_get_rettype(func->type)))
4549     {
4550         print_file(file, indent, "%s", "");
4551         write_type_decl_left(file, type_function_get_rettype(func->type));
4552         fprintf(file, " _RetVal;\n");
4553     }
4554
4555     if (!type_get_function_args(func->type))
4556         return;
4557
4558     LIST_FOR_EACH_ENTRY( var, type_get_function_args(func->type), const var_t, entry )
4559     {
4560         in_attr = is_attr(var->attrs, ATTR_IN);
4561         out_attr = is_attr(var->attrs, ATTR_OUT);
4562         if (!out_attr && !in_attr)
4563             in_attr = 1;
4564
4565         if (is_context_handle(var->type))
4566             print_file(file, indent, "NDR_SCONTEXT %s;\n", var->name);
4567         else
4568         {
4569             if (!in_attr && !is_conformant_array(var->type))
4570             {
4571                 type_t *type_to_print;
4572                 char name[16];
4573                 print_file(file, indent, "%s", "");
4574                 if (type_get_type(var->type) == TYPE_ARRAY &&
4575                     !type_array_is_decl_as_ptr(var->type))
4576                     type_to_print = var->type;
4577                 else
4578                     type_to_print = type_pointer_get_ref(var->type);
4579                 sprintf(name, "_W%u", i++);
4580                 write_type_decl(file, type_to_print, name);
4581                 fprintf(file, ";\n");
4582             }
4583
4584             print_file(file, indent, "%s", "");
4585             write_type_decl_left(file, var->type);
4586             fprintf(file, " ");
4587             if (type_get_type(var->type) == TYPE_ARRAY &&
4588                 !type_array_is_decl_as_ptr(var->type)) {
4589                 fprintf(file, "(*%s)", var->name);
4590             } else
4591                 fprintf(file, "%s", var->name);
4592             write_type_right(file, var->type, FALSE);
4593             fprintf(file, ";\n");
4594
4595             if (decl_indirect(var->type))
4596                 print_file(file, indent, "void *_p_%s;\n", var->name);
4597         }
4598     }
4599 }
4600
4601
4602 void assign_stub_out_args( FILE *file, int indent, const var_t *func, const char *local_var_prefix )
4603 {
4604     int in_attr, out_attr;
4605     int i = 0, sep = 0;
4606     const var_t *var;
4607
4608     if (!type_get_function_args(func->type))
4609         return;
4610
4611     LIST_FOR_EACH_ENTRY( var, type_get_function_args(func->type), const var_t, entry )
4612     {
4613         in_attr = is_attr(var->attrs, ATTR_IN);
4614         out_attr = is_attr(var->attrs, ATTR_OUT);
4615         if (!out_attr && !in_attr)
4616             in_attr = 1;
4617
4618         if (!in_attr)
4619         {
4620             print_file(file, indent, "%s%s", local_var_prefix, var->name);
4621
4622             switch (typegen_detect_type(var->type, var->attrs, TDT_IGNORE_STRINGS))
4623             {
4624             case TGT_CTXT_HANDLE_POINTER:
4625                 fprintf(file, " = NdrContextHandleInitialize(\n");
4626                 print_file(file, indent + 1, "&__frame->_StubMsg,\n");
4627                 print_file(file, indent + 1, "(PFORMAT_STRING)&__MIDL_TypeFormatString.Format[%d]);\n",
4628                            var->type->typestring_offset);
4629                 break;
4630             case TGT_ARRAY:
4631                 if (type_array_has_conformance(var->type))
4632                 {
4633                     unsigned int size;
4634                     type_t *type;
4635
4636                     fprintf(file, " = NdrAllocate(&__frame->_StubMsg, ");
4637                     for (type = var->type;
4638                          is_array(type) && type_array_has_conformance(type);
4639                          type = type_array_get_element(type))
4640                     {
4641                         write_expr(file, type_array_get_conformance(type), TRUE,
4642                                    TRUE, NULL, NULL, local_var_prefix);
4643                         fprintf(file, " * ");
4644                     }
4645                     size = type_memsize(type);
4646                     fprintf(file, "%u);\n", size);
4647
4648                     print_file(file, indent, "memset(%s%s, 0, ", local_var_prefix, var->name);
4649                     for (type = var->type;
4650                          is_array(type) && type_array_has_conformance(type);
4651                          type = type_array_get_element(type))
4652                     {
4653                         write_expr(file, type_array_get_conformance(type), TRUE,
4654                                    TRUE, NULL, NULL, local_var_prefix);
4655                         fprintf(file, " * ");
4656                     }
4657                     size = type_memsize(type);
4658                     fprintf(file, "%u);\n", size);
4659                 }
4660                 else
4661                     fprintf(file, " = &%s_W%u;\n", local_var_prefix, i++);
4662                 break;
4663             case TGT_POINTER:
4664                 fprintf(file, " = &%s_W%u;\n", local_var_prefix, i);
4665                 switch (typegen_detect_type(type_pointer_get_ref(var->type), var->attrs, TDT_IGNORE_STRINGS))
4666                 {
4667                 case TGT_BASIC:
4668                 case TGT_ENUM:
4669                 case TGT_POINTER:
4670                 case TGT_RANGE:
4671                 case TGT_IFACE_POINTER:
4672                     print_file(file, indent, "%s_W%u = 0;\n", local_var_prefix, i);
4673                     break;
4674                 case TGT_USER_TYPE:
4675                     print_file(file, indent, "memset(&%s_W%u, 0, sizeof(%s_W%u));\n",
4676                                local_var_prefix, i, local_var_prefix, i);
4677                     break;
4678                 case TGT_STRUCT:
4679                 case TGT_UNION:
4680                 case TGT_ARRAY:
4681                 case TGT_CTXT_HANDLE:
4682                 case TGT_CTXT_HANDLE_POINTER:
4683                 case TGT_INVALID:
4684                 case TGT_STRING:
4685                     /* not initialised */
4686                     break;
4687                 }
4688                 i++;
4689                 break;
4690             default:
4691                 break;
4692             }
4693
4694             sep = 1;
4695         }
4696     }
4697     if (sep)
4698         fprintf(file, "\n");
4699 }
4700
4701
4702 void write_func_param_struct( FILE *file, const type_t *iface, const type_t *func,
4703                               const char *var_decl, int add_retval )
4704 {
4705     type_t *rettype = type_function_get_rettype( func );
4706     const var_list_t *args = type_get_function_args( func );
4707     const var_t *arg;
4708     int needs_packing;
4709     unsigned int align = 0;
4710
4711     if (args)
4712         LIST_FOR_EACH_ENTRY( arg, args, const var_t, entry )
4713             if (!is_array( arg->type )) type_memsize_and_alignment( arg->type, &align );
4714
4715     needs_packing = (align > pointer_size);
4716
4717     if (needs_packing) print_file( file, 0, "#include <pshpack%u.h>\n", pointer_size );
4718     print_file(file, 1, "struct _PARAM_STRUCT\n" );
4719     print_file(file, 1, "{\n" );
4720     if (is_object( iface )) print_file(file, 2, "%s *This;\n", iface->name );
4721
4722     if (args) LIST_FOR_EACH_ENTRY( arg, args, const var_t, entry )
4723     {
4724         print_file(file, 2, "%s", "");
4725         write_type_left( file, (type_t *)arg->type, TRUE );
4726         if (needs_space_after( arg->type )) fputc( ' ', file );
4727         if (is_array( arg->type ) && !type_array_is_decl_as_ptr( arg->type )) fputc( '*', file );
4728
4729         /* FIXME: should check for large args being passed by pointer */
4730         align = 0;
4731         if (is_array( arg->type ) || is_ptr( arg->type )) align = pointer_size;
4732         else type_memsize_and_alignment( arg->type, &align );
4733
4734         if (align >= pointer_size)
4735             fprintf( file, "%s;\n", arg->name );
4736         else
4737             fprintf( file, "%s DECLSPEC_ALIGN(%u);\n", arg->name, pointer_size );
4738     }
4739     if (add_retval && !is_void( rettype ))
4740     {
4741         print_file(file, 2, "%s", "");
4742         write_type_decl( file, rettype, "_RetVal" );
4743         if (is_array( rettype ) || is_ptr( rettype ) || type_memsize( rettype ) == pointer_size)
4744             fprintf( file, ";\n" );
4745         else
4746             fprintf( file, " DECLSPEC_ALIGN(%u);\n", pointer_size );
4747     }
4748     print_file(file, 1, "} %s;\n", var_decl );
4749     if (needs_packing) print_file( file, 0, "#include <poppack.h>\n" );
4750     print_file( file, 0, "\n" );
4751 }
4752
4753 void write_pointer_checks( FILE *file, int indent, const var_t *func )
4754 {
4755     const var_list_t *args = type_get_function_args( func->type );
4756     const var_t *var;
4757
4758     if (!args) return;
4759
4760     LIST_FOR_EACH_ENTRY( var, args, const var_t, entry )
4761         if (cant_be_null( var ))
4762             print_file( file, indent, "if (!%s) RpcRaiseException(RPC_X_NULL_REF_POINTER);\n", var->name );
4763 }
4764
4765 int write_expr_eval_routines(FILE *file, const char *iface)
4766 {
4767     static const char *var_name = "pS";
4768     static const char *var_name_expr = "pS->";
4769     int result = 0;
4770     struct expr_eval_routine *eval;
4771     unsigned short callback_offset = 0;
4772
4773     LIST_FOR_EACH_ENTRY(eval, &expr_eval_routines, struct expr_eval_routine, entry)
4774     {
4775         const char *name = eval->name;
4776         result = 1;
4777
4778         print_file(file, 0, "static void __RPC_USER %s_%sExprEval_%04u(PMIDL_STUB_MESSAGE pStubMsg)\n",
4779                    eval->iface ? eval->iface->name : iface, name, callback_offset);
4780         print_file(file, 0, "{\n");
4781         if (type_get_type( eval->cont_type ) == TYPE_FUNCTION)
4782         {
4783             write_func_param_struct( file, eval->iface, eval->cont_type,
4784                                      "*pS = (struct _PARAM_STRUCT *)pStubMsg->StackTop", FALSE );
4785         }
4786         else
4787         {
4788             print_file(file, 1, "%s", "");
4789             write_type_left(file, (type_t *)eval->cont_type, TRUE);
4790             fprintf(file, " *%s = (", var_name);
4791             write_type_left(file, (type_t *)eval->cont_type, TRUE);
4792             fprintf(file, " *)(pStubMsg->StackTop - %u);\n", eval->baseoff);
4793         }
4794         print_file(file, 1, "pStubMsg->Offset = 0;\n"); /* FIXME */
4795         print_file(file, 1, "pStubMsg->MaxCount = (ULONG_PTR)");
4796         write_expr(file, eval->expr, 1, 1, var_name_expr, eval->cont_type, "");
4797         fprintf(file, ";\n");
4798         print_file(file, 0, "}\n\n");
4799         callback_offset++;
4800     }
4801     return result;
4802 }
4803
4804 void write_expr_eval_routine_list(FILE *file, const char *iface)
4805 {
4806     struct expr_eval_routine *eval;
4807     struct expr_eval_routine *cursor;
4808     unsigned short callback_offset = 0;
4809
4810     fprintf(file, "static const EXPR_EVAL ExprEvalRoutines[] =\n");
4811     fprintf(file, "{\n");
4812
4813     LIST_FOR_EACH_ENTRY_SAFE(eval, cursor, &expr_eval_routines, struct expr_eval_routine, entry)
4814     {
4815         print_file(file, 1, "%s_%sExprEval_%04u,\n",
4816                    eval->iface ? eval->iface->name : iface, eval->name, callback_offset);
4817         callback_offset++;
4818         list_remove(&eval->entry);
4819         free(eval->name);
4820         free(eval);
4821     }
4822
4823     fprintf(file, "};\n\n");
4824 }
4825
4826 void write_user_quad_list(FILE *file)
4827 {
4828     user_type_t *ut;
4829
4830     if (list_empty(&user_type_list))
4831         return;
4832
4833     fprintf(file, "static const USER_MARSHAL_ROUTINE_QUADRUPLE UserMarshalRoutines[] =\n");
4834     fprintf(file, "{\n");
4835     LIST_FOR_EACH_ENTRY(ut, &user_type_list, user_type_t, entry)
4836     {
4837         const char *sep = &ut->entry == list_tail(&user_type_list) ? "" : ",";
4838         print_file(file, 1, "{\n");
4839         print_file(file, 2, "(USER_MARSHAL_SIZING_ROUTINE)%s_UserSize,\n", ut->name);
4840         print_file(file, 2, "(USER_MARSHAL_MARSHALLING_ROUTINE)%s_UserMarshal,\n", ut->name);
4841         print_file(file, 2, "(USER_MARSHAL_UNMARSHALLING_ROUTINE)%s_UserUnmarshal,\n", ut->name);
4842         print_file(file, 2, "(USER_MARSHAL_FREEING_ROUTINE)%s_UserFree\n", ut->name);
4843         print_file(file, 1, "}%s\n", sep);
4844     }
4845     fprintf(file, "};\n\n");
4846 }
4847
4848 void write_endpoints( FILE *f, const char *prefix, const str_list_t *list )
4849 {
4850     const struct str_list_entry_t *endpoint;
4851     const char *p;
4852
4853     /* this should be an array of RPC_PROTSEQ_ENDPOINT but we want const strings */
4854     print_file( f, 0, "static const unsigned char * const %s__RpcProtseqEndpoint[][2] =\n{\n", prefix );
4855     LIST_FOR_EACH_ENTRY( endpoint, list, const struct str_list_entry_t, entry )
4856     {
4857         print_file( f, 1, "{ (const unsigned char *)\"" );
4858         for (p = endpoint->str; *p && *p != ':'; p++)
4859         {
4860             if (*p == '"' || *p == '\\') fputc( '\\', f );
4861             fputc( *p, f );
4862         }
4863         if (!*p) goto error;
4864         if (p[1] != '[') goto error;
4865
4866         fprintf( f, "\", (const unsigned char *)\"" );
4867         for (p += 2; *p && *p != ']'; p++)
4868         {
4869             if (*p == '"' || *p == '\\') fputc( '\\', f );
4870             fputc( *p, f );
4871         }
4872         if (*p != ']') goto error;
4873         fprintf( f, "\" },\n" );
4874     }
4875     print_file( f, 0, "};\n\n" );
4876     return;
4877
4878 error:
4879     error("Invalid endpoint syntax '%s'\n", endpoint->str);
4880 }
4881
4882 void write_client_call_routine( FILE *file, const type_t *iface, const var_t *func,
4883                                 const char *prefix, unsigned int proc_offset )
4884 {
4885     type_t *rettype = type_function_get_rettype( func->type );
4886     int has_ret = !is_void( rettype );
4887     const var_list_t *args = type_get_function_args( func->type );
4888     const var_t *arg;
4889     int len, needs_params = 0;
4890
4891     /* we need a param structure if we have more than one arg */
4892     if (pointer_size == 4 && args) needs_params = is_object( iface ) || list_count( args ) > 1;
4893
4894     print_file( file, 0, "{\n");
4895     if (needs_params)
4896     {
4897         if (has_ret) print_file( file, 1, "%s", "CLIENT_CALL_RETURN _RetVal;\n" );
4898         write_func_param_struct( file, iface, func->type, "__params", FALSE );
4899         if (is_object( iface )) print_file( file, 1, "__params.This = This;\n" );
4900         if (args)
4901             LIST_FOR_EACH_ENTRY( arg, args, const var_t, entry )
4902                 print_file( file, 1, "__params.%s = %s;\n", arg->name, arg->name );
4903     }
4904     else if (has_ret) print_file( file, 1, "%s", "CLIENT_CALL_RETURN _RetVal;\n\n" );
4905
4906     len = fprintf( file, "    %s%s( ",
4907                    has_ret ? "_RetVal = " : "",
4908                    get_stub_mode() == MODE_Oif ? "NdrClientCall2" : "NdrClientCall" );
4909     fprintf( file, "&%s_StubDesc,", prefix );
4910     fprintf( file, "\n%*s&__MIDL_ProcFormatString.Format[%u]", len, "", proc_offset );
4911     if (needs_params)
4912     {
4913         fprintf( file, ",\n%*s&__params", len, "" );
4914     }
4915     else if (pointer_size == 8)
4916     {
4917         if (is_object( iface )) fprintf( file, ",\n%*sThis", len, "" );
4918         if (args)
4919             LIST_FOR_EACH_ENTRY( arg, args, const var_t, entry )
4920                 fprintf( file, ",\n%*s%s", len, "", arg->name );
4921     }
4922     else
4923     {
4924         if (is_object( iface )) fprintf( file, ",\n%*s&This", len, "" );
4925         else if (args)
4926         {
4927             arg = LIST_ENTRY( list_head(args), const var_t, entry );
4928             fprintf( file, ",\n%*s&%s", len, "", arg->name );
4929         }
4930     }
4931     fprintf( file, " );\n" );
4932     if (has_ret)
4933     {
4934         print_file( file, 1, "return (" );
4935         write_type_decl_left(file, rettype);
4936         fprintf( file, ")%s;\n", pointer_size == 8 ? "_RetVal.Simple" : "*(LONG_PTR *)&_RetVal" );
4937     }
4938     print_file( file, 0, "}\n\n");
4939 }
4940
4941 void write_exceptions( FILE *file )
4942 {
4943     fprintf( file, "#ifndef USE_COMPILER_EXCEPTIONS\n");
4944     fprintf( file, "\n");
4945     fprintf( file, "#include \"wine/exception.h\"\n");
4946     fprintf( file, "#undef RpcTryExcept\n");
4947     fprintf( file, "#undef RpcExcept\n");
4948     fprintf( file, "#undef RpcEndExcept\n");
4949     fprintf( file, "#undef RpcTryFinally\n");
4950     fprintf( file, "#undef RpcFinally\n");
4951     fprintf( file, "#undef RpcEndFinally\n");
4952     fprintf( file, "#undef RpcExceptionCode\n");
4953     fprintf( file, "#undef RpcAbnormalTermination\n");
4954     fprintf( file, "\n");
4955     fprintf( file, "struct __exception_frame;\n");
4956     fprintf( file, "typedef int (*__filter_func)(struct __exception_frame *);\n");
4957     fprintf( file, "typedef void (*__finally_func)(struct __exception_frame *);\n");
4958     fprintf( file, "\n");
4959     fprintf( file, "#define __DECL_EXCEPTION_FRAME \\\n");
4960     fprintf( file, "    EXCEPTION_REGISTRATION_RECORD frame; \\\n");
4961     fprintf( file, "    __filter_func                 filter; \\\n");
4962     fprintf( file, "    __finally_func                finally; \\\n");
4963     fprintf( file, "    sigjmp_buf                    jmp; \\\n");
4964     fprintf( file, "    DWORD                         code; \\\n");
4965     fprintf( file, "    unsigned char                 abnormal_termination; \\\n");
4966     fprintf( file, "    unsigned char                 filter_level; \\\n");
4967     fprintf( file, "    unsigned char                 finally_level;\n");
4968     fprintf( file, "\n");
4969     fprintf( file, "struct __exception_frame\n{\n");
4970     fprintf( file, "    __DECL_EXCEPTION_FRAME\n");
4971     fprintf( file, "};\n");
4972     fprintf( file, "\n");
4973     fprintf( file, "static inline void __widl_unwind_target(void)\n" );
4974     fprintf( file, "{\n");
4975     fprintf( file, "    struct __exception_frame *exc_frame = (struct __exception_frame *)__wine_get_frame();\n" );
4976     fprintf( file, "    if (exc_frame->finally_level > exc_frame->filter_level)\n" );
4977     fprintf( file, "    {\n");
4978     fprintf( file, "        exc_frame->abnormal_termination = 1;\n");
4979     fprintf( file, "        exc_frame->finally( exc_frame );\n");
4980     fprintf( file, "        __wine_pop_frame( &exc_frame->frame );\n");
4981     fprintf( file, "    }\n");
4982     fprintf( file, "    exc_frame->filter_level = 0;\n");
4983     fprintf( file, "    siglongjmp( exc_frame->jmp, 1 );\n");
4984     fprintf( file, "}\n");
4985     fprintf( file, "\n");
4986     fprintf( file, "static DWORD __widl_exception_handler( EXCEPTION_RECORD *record,\n");
4987     fprintf( file, "                                       EXCEPTION_REGISTRATION_RECORD *frame,\n");
4988     fprintf( file, "                                       CONTEXT *context,\n");
4989     fprintf( file, "                                       EXCEPTION_REGISTRATION_RECORD **pdispatcher )\n");
4990     fprintf( file, "{\n");
4991     fprintf( file, "    struct __exception_frame *exc_frame = (struct __exception_frame *)frame;\n");
4992     fprintf( file, "\n");
4993     fprintf( file, "    if (record->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND | EH_NESTED_CALL))\n");
4994     fprintf( file, "    {\n" );
4995     fprintf( file, "        if (exc_frame->finally_level && (record->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND)))\n");
4996     fprintf( file, "        {\n" );
4997     fprintf( file, "            exc_frame->abnormal_termination = 1;\n");
4998     fprintf( file, "            exc_frame->finally( exc_frame );\n");
4999     fprintf( file, "        }\n" );
5000     fprintf( file, "        return ExceptionContinueSearch;\n");
5001     fprintf( file, "    }\n" );
5002     fprintf( file, "    exc_frame->code = record->ExceptionCode;\n");
5003     fprintf( file, "    if (exc_frame->filter_level && exc_frame->filter( exc_frame ) == EXCEPTION_EXECUTE_HANDLER)\n" );
5004     fprintf( file, "        __wine_rtl_unwind( frame, record, __widl_unwind_target );\n");
5005     fprintf( file, "    return ExceptionContinueSearch;\n");
5006     fprintf( file, "}\n");
5007     fprintf( file, "\n");
5008     fprintf( file, "#define RpcTryExcept \\\n");
5009     fprintf( file, "    if (!sigsetjmp( __frame->jmp, 0 )) \\\n");
5010     fprintf( file, "    { \\\n");
5011     fprintf( file, "        if (!__frame->finally_level) \\\n" );
5012     fprintf( file, "            __wine_push_frame( &__frame->frame ); \\\n");
5013     fprintf( file, "        __frame->filter_level = __frame->finally_level + 1;\n" );
5014     fprintf( file, "\n");
5015     fprintf( file, "#define RpcExcept(expr) \\\n");
5016     fprintf( file, "        if (!__frame->finally_level) \\\n" );
5017     fprintf( file, "            __wine_pop_frame( &__frame->frame ); \\\n");
5018     fprintf( file, "        __frame->filter_level = 0; \\\n" );
5019     fprintf( file, "    } \\\n");
5020     fprintf( file, "    else \\\n");
5021     fprintf( file, "\n");
5022     fprintf( file, "#define RpcEndExcept\n");
5023     fprintf( file, "\n");
5024     fprintf( file, "#define RpcExceptionCode() (__frame->code)\n");
5025     fprintf( file, "\n");
5026     fprintf( file, "#define RpcTryFinally \\\n");
5027     fprintf( file, "    if (!__frame->filter_level) \\\n");
5028     fprintf( file, "        __wine_push_frame( &__frame->frame ); \\\n");
5029     fprintf( file, "    __frame->finally_level = __frame->filter_level + 1;\n");
5030     fprintf( file, "\n");
5031     fprintf( file, "#define RpcFinally \\\n");
5032     fprintf( file, "    if (!__frame->filter_level) \\\n");
5033     fprintf( file, "        __wine_pop_frame( &__frame->frame ); \\\n");
5034     fprintf( file, "    __frame->finally_level = 0;\n");
5035     fprintf( file, "\n");
5036     fprintf( file, "#define RpcEndFinally\n");
5037     fprintf( file, "\n");
5038     fprintf( file, "#define RpcAbnormalTermination() (__frame->abnormal_termination)\n");
5039     fprintf( file, "\n");
5040     fprintf( file, "#define RpcExceptionInit(filter_func,finally_func) \\\n");
5041     fprintf( file, "    do { \\\n");
5042     fprintf( file, "        __frame->frame.Handler = __widl_exception_handler; \\\n");
5043     fprintf( file, "        __frame->filter = (__filter_func)(filter_func); \\\n" );
5044     fprintf( file, "        __frame->finally = (__finally_func)(finally_func); \\\n");
5045     fprintf( file, "        __frame->abnormal_termination = 0; \\\n");
5046     fprintf( file, "        __frame->filter_level = 0; \\\n");
5047     fprintf( file, "        __frame->finally_level = 0; \\\n");
5048     fprintf( file, "    } while (0)\n");
5049     fprintf( file, "\n");
5050     fprintf( file, "#else /* USE_COMPILER_EXCEPTIONS */\n");
5051     fprintf( file, "\n");
5052     fprintf( file, "#define RpcExceptionInit(filter_func,finally_func) \\\n");
5053     fprintf( file, "    do { (void)(filter_func); } while(0)\n");
5054     fprintf( file, "\n");
5055     fprintf( file, "#define __DECL_EXCEPTION_FRAME \\\n");
5056     fprintf( file, "    DWORD code;\n");
5057     fprintf( file, "\n");
5058     fprintf( file, "#endif /* USE_COMPILER_EXCEPTIONS */\n");
5059 }