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