widl: Separate declaration and initialisation for indirect arguments.
[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 "wine/list.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 func_t *current_func;
50 static const type_t *current_structure;
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 *structure;
58     unsigned int baseoff;
59     const expr_t *expr;
60 };
61
62 static size_t fields_memsize(const var_list_t *fields, unsigned int *align);
63 static size_t write_struct_tfs(FILE *file, type_t *type, const char *name, unsigned int *tfsoff);
64 static int write_embedded_types(FILE *file, const attr_list_t *attrs, type_t *type,
65                                 const char *name, int write_ptr, unsigned int *tfsoff);
66 static const var_t *find_array_or_string_in_struct(const type_t *type);
67 static size_t write_string_tfs(FILE *file, const attr_list_t *attrs,
68                                type_t *type,
69                                const char *name, unsigned int *typestring_offset);
70
71 const char *string_of_type(unsigned char type)
72 {
73     switch (type)
74     {
75     case RPC_FC_BYTE: return "FC_BYTE";
76     case RPC_FC_CHAR: return "FC_CHAR";
77     case RPC_FC_SMALL: return "FC_SMALL";
78     case RPC_FC_USMALL: return "FC_USMALL";
79     case RPC_FC_WCHAR: return "FC_WCHAR";
80     case RPC_FC_SHORT: return "FC_SHORT";
81     case RPC_FC_USHORT: return "FC_USHORT";
82     case RPC_FC_LONG: return "FC_LONG";
83     case RPC_FC_ULONG: return "FC_ULONG";
84     case RPC_FC_FLOAT: return "FC_FLOAT";
85     case RPC_FC_HYPER: return "FC_HYPER";
86     case RPC_FC_DOUBLE: return "FC_DOUBLE";
87     case RPC_FC_ENUM16: return "FC_ENUM16";
88     case RPC_FC_ENUM32: return "FC_ENUM32";
89     case RPC_FC_IGNORE: return "FC_IGNORE";
90     case RPC_FC_ERROR_STATUS_T: return "FC_ERROR_STATUS_T";
91     case RPC_FC_RP: return "FC_RP";
92     case RPC_FC_UP: return "FC_UP";
93     case RPC_FC_OP: return "FC_OP";
94     case RPC_FC_FP: return "FC_FP";
95     case RPC_FC_ENCAPSULATED_UNION: return "FC_ENCAPSULATED_UNION";
96     case RPC_FC_NON_ENCAPSULATED_UNION: return "FC_NON_ENCAPSULATED_UNION";
97     case RPC_FC_STRUCT: return "FC_STRUCT";
98     case RPC_FC_PSTRUCT: return "FC_PSTRUCT";
99     case RPC_FC_CSTRUCT: return "FC_CSTRUCT";
100     case RPC_FC_CPSTRUCT: return "FC_CPSTRUCT";
101     case RPC_FC_CVSTRUCT: return "FC_CVSTRUCT";
102     case RPC_FC_BOGUS_STRUCT: return "FC_BOGUS_STRUCT";
103     case RPC_FC_SMFARRAY: return "FC_SMFARRAY";
104     case RPC_FC_LGFARRAY: return "FC_LGFARRAY";
105     case RPC_FC_SMVARRAY: return "FC_SMVARRAY";
106     case RPC_FC_LGVARRAY: return "FC_LGVARRAY";
107     case RPC_FC_CARRAY: return "FC_CARRAY";
108     case RPC_FC_CVARRAY: return "FC_CVARRAY";
109     case RPC_FC_BOGUS_ARRAY: return "FC_BOGUS_ARRAY";
110     case RPC_FC_ALIGNM4: return "FC_ALIGNM4";
111     case RPC_FC_ALIGNM8: return "FC_ALIGNM8";
112     case RPC_FC_POINTER: return "FC_POINTER";
113     case RPC_FC_C_CSTRING: return "FC_C_CSTRING";
114     case RPC_FC_C_WSTRING: return "FC_C_WSTRING";
115     case RPC_FC_CSTRING: return "FC_CSTRING";
116     case RPC_FC_WSTRING: return "FC_WSTRING";
117     default:
118         error("string_of_type: unknown type 0x%02x\n", type);
119         return NULL;
120     }
121 }
122
123 int is_struct(unsigned char type)
124 {
125     switch (type)
126     {
127     case RPC_FC_STRUCT:
128     case RPC_FC_PSTRUCT:
129     case RPC_FC_CSTRUCT:
130     case RPC_FC_CPSTRUCT:
131     case RPC_FC_CVSTRUCT:
132     case RPC_FC_BOGUS_STRUCT:
133         return 1;
134     default:
135         return 0;
136     }
137 }
138
139 static int is_non_complex_struct(const type_t *type)
140 {
141     switch (type->type)
142     {
143     case RPC_FC_STRUCT:
144     case RPC_FC_PSTRUCT:
145     case RPC_FC_CSTRUCT:
146     case RPC_FC_CPSTRUCT:
147     case RPC_FC_CVSTRUCT:
148         return 1;
149     default:
150         return 0;
151     }
152 }
153
154 int is_union(unsigned char type)
155 {
156     switch (type)
157     {
158     case RPC_FC_ENCAPSULATED_UNION:
159     case RPC_FC_NON_ENCAPSULATED_UNION:
160         return 1;
161     default:
162         return 0;
163     }
164 }
165
166 static int type_has_pointers(const type_t *type)
167 {
168     if (is_user_type(type))
169         return FALSE;
170     else if (is_ptr(type))
171         return TRUE;
172     else if (is_array(type))
173         return type_has_pointers(type->ref);
174     else if (is_struct(type->type))
175     {
176         const var_t *field;
177         if (type->fields_or_args) LIST_FOR_EACH_ENTRY( field, type->fields_or_args, const var_t, entry )
178         {
179             if (type_has_pointers(field->type))
180                 return TRUE;
181         }
182     }
183     else if (is_union(type->type))
184     {
185         var_list_t *fields;
186         const var_t *field;
187         if (type->type == RPC_FC_ENCAPSULATED_UNION)
188         {
189             const var_t *uv = LIST_ENTRY(list_tail(type->fields_or_args), const var_t, entry);
190             fields = uv->type->fields_or_args;
191         }
192         else
193             fields = type->fields_or_args;
194         if (fields) LIST_FOR_EACH_ENTRY( field, fields, const var_t, entry )
195         {
196             if (field->type && type_has_pointers(field->type))
197                 return TRUE;
198         }
199     }
200
201     return FALSE;
202 }
203
204 static int type_has_full_pointer(const type_t *type)
205 {
206     if (is_user_type(type))
207         return FALSE;
208     else if (type->type == RPC_FC_FP)
209         return TRUE;
210     else if (is_ptr(type))
211         return FALSE;
212     else if (is_array(type))
213         return type_has_full_pointer(type->ref);
214     else if (is_struct(type->type))
215     {
216         const var_t *field;
217         if (type->fields_or_args) LIST_FOR_EACH_ENTRY( field, type->fields_or_args, const var_t, entry )
218         {
219             if (type_has_full_pointer(field->type))
220                 return TRUE;
221         }
222     }
223     else if (is_union(type->type))
224     {
225         var_list_t *fields;
226         const var_t *field;
227         if (type->type == RPC_FC_ENCAPSULATED_UNION)
228         {
229             const var_t *uv = LIST_ENTRY(list_tail(type->fields_or_args), const var_t, entry);
230             fields = uv->type->fields_or_args;
231         }
232         else
233             fields = type->fields_or_args;
234         if (fields) LIST_FOR_EACH_ENTRY( field, fields, const var_t, entry )
235         {
236             if (field->type && type_has_full_pointer(field->type))
237                 return TRUE;
238         }
239     }
240
241     return FALSE;
242 }
243
244 static unsigned short user_type_offset(const char *name)
245 {
246     user_type_t *ut;
247     unsigned short off = 0;
248     LIST_FOR_EACH_ENTRY(ut, &user_type_list, user_type_t, entry)
249     {
250         if (strcmp(name, ut->name) == 0)
251             return off;
252         ++off;
253     }
254     error("user_type_offset: couldn't find type (%s)\n", name);
255     return 0;
256 }
257
258 static void update_tfsoff(type_t *type, unsigned int offset, FILE *file)
259 {
260     type->typestring_offset = offset;
261     if (file) type->tfswrite = FALSE;
262 }
263
264 static void guard_rec(type_t *type)
265 {
266     /* types that contain references to themselves (like a linked list),
267        need to be shielded from infinite recursion when writing embedded
268        types  */
269     if (type->typestring_offset)
270         type->tfswrite = FALSE;
271     else
272         type->typestring_offset = 1;
273 }
274
275 static type_t *get_user_type(const type_t *t, const char **pname)
276 {
277     for (;;)
278     {
279         type_t *ut = get_attrp(t->attrs, ATTR_WIREMARSHAL);
280         if (ut)
281         {
282             if (pname)
283                 *pname = t->name;
284             return ut;
285         }
286
287         if (t->kind == TKIND_ALIAS)
288             t = t->orig;
289         else
290             return 0;
291     }
292 }
293
294 int is_user_type(const type_t *t)
295 {
296     return get_user_type(t, NULL) != NULL;
297 }
298
299 static int is_embedded_complex(const type_t *type)
300 {
301     unsigned char tc = type->type;
302     return is_struct(tc) || is_union(tc) || is_array(type) || is_user_type(type)
303         || (is_ptr(type) && type->ref->type == RPC_FC_IP);
304 }
305
306 static const char *get_context_handle_type_name(const type_t *type)
307 {
308     const type_t *t;
309     for (t = type; is_ptr(t); t = t->ref)
310         if (is_attr(t->attrs, ATTR_CONTEXTHANDLE))
311             return t->name;
312     assert(0);
313     return NULL;
314 }
315
316 #define WRITE_FCTYPE(file, fctype, typestring_offset) \
317     do { \
318         if (file) \
319             fprintf(file, "/* %2u */\n", typestring_offset); \
320         print_file((file), 2, "0x%02x,    /* " #fctype " */\n", RPC_##fctype); \
321     } \
322     while (0)
323
324 static void print_file(FILE *file, int indent, const char *format, ...)
325 {
326     va_list va;
327     va_start(va, format);
328     print(file, indent, format, va);
329     va_end(va);
330 }
331
332 void print(FILE *file, int indent, const char *format, va_list va)
333 {
334     if (file)
335     {
336         if (format[0] != '\n')
337             while (0 < indent--)
338                 fprintf(file, "    ");
339         vfprintf(file, format, va);
340     }
341 }
342
343
344 static void write_var_init(FILE *file, int indent, const type_t *t, const char *n, const char *local_var_prefix)
345 {
346     if (decl_indirect(t))
347     {
348         print_file(file, indent, "MIDL_memset(&%s%s, 0, sizeof(%s%s));\n",
349                    local_var_prefix, n, local_var_prefix, n);
350         print_file(file, indent, "%s_p_%s = &%s%s;\n", local_var_prefix, n, local_var_prefix, n);
351     }
352     else if (is_ptr(t) || is_array(t))
353         print_file(file, indent, "%s%s = 0;\n", local_var_prefix, n);
354 }
355
356 void write_parameters_init(FILE *file, int indent, const func_t *func, const char *local_var_prefix)
357 {
358     const var_t *var;
359
360     if (!is_void(get_func_return_type(func)))
361         write_var_init(file, indent, get_func_return_type(func), "_RetVal", local_var_prefix);
362
363     if (!func->args)
364         return;
365
366     LIST_FOR_EACH_ENTRY( var, func->args, const var_t, entry )
367         write_var_init(file, indent, var->type, var->name, local_var_prefix);
368
369     fprintf(file, "\n");
370 }
371
372 static void write_formatdesc(FILE *f, int indent, const char *str)
373 {
374     print_file(f, indent, "typedef struct _MIDL_%s_FORMAT_STRING\n", str);
375     print_file(f, indent, "{\n");
376     print_file(f, indent + 1, "short Pad;\n");
377     print_file(f, indent + 1, "unsigned char Format[%s_FORMAT_STRING_SIZE];\n", str);
378     print_file(f, indent, "} MIDL_%s_FORMAT_STRING;\n", str);
379     print_file(f, indent, "\n");
380 }
381
382 void write_formatstringsdecl(FILE *f, int indent, const statement_list_t *stmts, type_pred_t pred)
383 {
384     print_file(f, indent, "#define TYPE_FORMAT_STRING_SIZE %d\n",
385                get_size_typeformatstring(stmts, pred));
386
387     print_file(f, indent, "#define PROC_FORMAT_STRING_SIZE %d\n",
388                get_size_procformatstring(stmts, pred));
389
390     fprintf(f, "\n");
391     write_formatdesc(f, indent, "TYPE");
392     write_formatdesc(f, indent, "PROC");
393     fprintf(f, "\n");
394     print_file(f, indent, "static const MIDL_TYPE_FORMAT_STRING __MIDL_TypeFormatString;\n");
395     print_file(f, indent, "static const MIDL_PROC_FORMAT_STRING __MIDL_ProcFormatString;\n");
396     print_file(f, indent, "\n");
397 }
398
399 static inline int is_base_type(unsigned char type)
400 {
401     switch (type)
402     {
403     case RPC_FC_BYTE:
404     case RPC_FC_CHAR:
405     case RPC_FC_USMALL:
406     case RPC_FC_SMALL:
407     case RPC_FC_WCHAR:
408     case RPC_FC_USHORT:
409     case RPC_FC_SHORT:
410     case RPC_FC_ULONG:
411     case RPC_FC_LONG:
412     case RPC_FC_HYPER:
413     case RPC_FC_IGNORE:
414     case RPC_FC_FLOAT:
415     case RPC_FC_DOUBLE:
416     case RPC_FC_ENUM16:
417     case RPC_FC_ENUM32:
418     case RPC_FC_ERROR_STATUS_T:
419     case RPC_FC_BIND_PRIMITIVE:
420         return TRUE;
421
422     default:
423         return FALSE;
424     }
425 }
426
427 int decl_indirect(const type_t *t)
428 {
429     return is_user_type(t)
430         || (!is_base_type(t->type)
431             && !is_ptr(t)
432             && !is_array(t));
433 }
434
435 static size_t write_procformatstring_type(FILE *file, int indent,
436                                           const char *name,
437                                           const type_t *type,
438                                           const attr_list_t *attrs,
439                                           int is_return)
440 {
441     size_t size;
442
443     int is_in = is_attr(attrs, ATTR_IN);
444     int is_out = is_attr(attrs, ATTR_OUT);
445
446     if (!is_in && !is_out) is_in = TRUE;
447
448     if (!type->declarray && is_base_type(type->type))
449     {
450         if (is_return)
451             print_file(file, indent, "0x53,    /* FC_RETURN_PARAM_BASETYPE */\n");
452         else
453             print_file(file, indent, "0x4e,    /* FC_IN_PARAM_BASETYPE */\n");
454
455         if (type->type == RPC_FC_BIND_PRIMITIVE)
456         {
457             print_file(file, indent, "0x%02x,    /* FC_IGNORE */\n", RPC_FC_IGNORE);
458             size = 2; /* includes param type prefix */
459         }
460         else if (is_base_type(type->type))
461         {
462             print_file(file, indent, "0x%02x,    /* %s */\n", type->type, string_of_type(type->type));
463             size = 2; /* includes param type prefix */
464         }
465         else
466         {
467             error("Unknown/unsupported type: %s (0x%02x)\n", name, type->type);
468             size = 0;
469         }
470     }
471     else
472     {
473         if (is_return)
474             print_file(file, indent, "0x52,    /* FC_RETURN_PARAM */\n");
475         else if (is_in && is_out)
476             print_file(file, indent, "0x50,    /* FC_IN_OUT_PARAM */\n");
477         else if (is_out)
478             print_file(file, indent, "0x51,    /* FC_OUT_PARAM */\n");
479         else
480             print_file(file, indent, "0x4d,    /* FC_IN_PARAM */\n");
481
482         print_file(file, indent, "0x01,\n");
483         print_file(file, indent, "NdrFcShort(0x%x),\n", type->typestring_offset);
484         size = 4; /* includes param type prefix */
485     }
486     return size;
487 }
488
489 static void write_procformatstring_stmts(FILE *file, int indent, const statement_list_t *stmts, type_pred_t pred)
490 {
491     const statement_t *stmt;
492     if (stmts) LIST_FOR_EACH_ENTRY( stmt, stmts, const statement_t, entry )
493     {
494         if (stmt->type == STMT_TYPE && stmt->u.type->type == RPC_FC_IP)
495         {
496             const func_t *func;
497             if (!pred(stmt->u.type))
498                 continue;
499             if (stmt->u.type->funcs) LIST_FOR_EACH_ENTRY( func, stmt->u.type->funcs, const func_t, entry )
500             {
501                 if (is_local(func->def->attrs)) continue;
502                 /* emit argument data */
503                 if (func->args)
504                 {
505                     const var_t *var;
506                     LIST_FOR_EACH_ENTRY( var, func->args, const var_t, entry )
507                         write_procformatstring_type(file, indent, var->name, var->type, var->attrs, FALSE);
508                 }
509
510                 /* emit return value data */
511                 if (is_void(get_func_return_type(func)))
512                 {
513                     print_file(file, indent, "0x5b,    /* FC_END */\n");
514                     print_file(file, indent, "0x5c,    /* FC_PAD */\n");
515                 }
516                 else
517                     write_procformatstring_type(file, indent, "return value", get_func_return_type(func), NULL, TRUE);
518             }
519         }
520         else if (stmt->type == STMT_LIBRARY)
521             write_procformatstring_stmts(file, indent, stmt->u.lib->stmts, pred);
522     }
523 }
524
525 void write_procformatstring(FILE *file, const statement_list_t *stmts, type_pred_t pred)
526 {
527     int indent = 0;
528
529     print_file(file, indent, "static const MIDL_PROC_FORMAT_STRING __MIDL_ProcFormatString =\n");
530     print_file(file, indent, "{\n");
531     indent++;
532     print_file(file, indent, "0,\n");
533     print_file(file, indent, "{\n");
534     indent++;
535
536     write_procformatstring_stmts(file, indent, stmts, pred);
537
538     print_file(file, indent, "0x0\n");
539     indent--;
540     print_file(file, indent, "}\n");
541     indent--;
542     print_file(file, indent, "};\n");
543     print_file(file, indent, "\n");
544 }
545
546 static int write_base_type(FILE *file, const type_t *type, unsigned int *typestring_offset)
547 {
548     if (is_base_type(type->type))
549     {
550         print_file(file, 2, "0x%02x,\t/* %s */\n", type->type, string_of_type(type->type));
551         *typestring_offset += 1;
552         return 1;
553     }
554
555     return 0;
556 }
557
558 /* write conformance / variance descriptor */
559 static size_t write_conf_or_var_desc(FILE *file, const type_t *structure,
560                                      unsigned int baseoff, const type_t *type,
561                                      const expr_t *expr)
562 {
563     unsigned char operator_type = 0;
564     unsigned char conftype = RPC_FC_NORMAL_CONFORMANCE;
565     const char *conftype_string = "";
566     const char *operator_string = "no operators";
567     const expr_t *subexpr;
568
569     if (!expr)
570     {
571         print_file(file, 2, "NdrFcLong(0xffffffff),\t/* -1 */\n");
572         return 4;
573     }
574
575     if (!structure)
576     {
577         /* Top-level conformance calculations are done inline.  */
578         print_file (file, 2, "0x%x,\t/* Corr desc: parameter */\n",
579                     RPC_FC_TOP_LEVEL_CONFORMANCE);
580         print_file (file, 2, "0x0,\n");
581         print_file (file, 2, "NdrFcShort(0x0),\n");
582         return 4;
583     }
584
585     if (expr->is_const)
586     {
587         if (expr->cval > UCHAR_MAX * (USHRT_MAX + 1) + USHRT_MAX)
588             error("write_conf_or_var_desc: constant value %ld is greater than "
589                   "the maximum constant size of %d\n", expr->cval,
590                   UCHAR_MAX * (USHRT_MAX + 1) + USHRT_MAX);
591
592         print_file(file, 2, "0x%x, /* Corr desc: constant, val = %ld */\n",
593                    RPC_FC_CONSTANT_CONFORMANCE, expr->cval);
594         print_file(file, 2, "0x%x,\n", expr->cval & ~USHRT_MAX);
595         print_file(file, 2, "NdrFcShort(0x%x),\n", expr->cval & USHRT_MAX);
596
597         return 4;
598     }
599
600     if (is_ptr(type) || (is_array(type) && !type->declarray))
601     {
602         conftype = RPC_FC_POINTER_CONFORMANCE;
603         conftype_string = "field pointer, ";
604     }
605
606     subexpr = expr;
607     switch (subexpr->type)
608     {
609     case EXPR_PPTR:
610         subexpr = subexpr->ref;
611         operator_type = RPC_FC_DEREFERENCE;
612         operator_string = "FC_DEREFERENCE";
613         break;
614     case EXPR_DIV:
615         if (subexpr->u.ext->is_const && (subexpr->u.ext->cval == 2))
616         {
617             subexpr = subexpr->ref;
618             operator_type = RPC_FC_DIV_2;
619             operator_string = "FC_DIV_2";
620         }
621         break;
622     case EXPR_MUL:
623         if (subexpr->u.ext->is_const && (subexpr->u.ext->cval == 2))
624         {
625             subexpr = subexpr->ref;
626             operator_type = RPC_FC_MULT_2;
627             operator_string = "FC_MULT_2";
628         }
629         break;
630     case EXPR_SUB:
631         if (subexpr->u.ext->is_const && (subexpr->u.ext->cval == 1))
632         {
633             subexpr = subexpr->ref;
634             operator_type = RPC_FC_SUB_1;
635             operator_string = "FC_SUB_1";
636         }
637         break;
638     case EXPR_ADD:
639         if (subexpr->u.ext->is_const && (subexpr->u.ext->cval == 1))
640         {
641             subexpr = subexpr->ref;
642             operator_type = RPC_FC_ADD_1;
643             operator_string = "FC_ADD_1";
644         }
645         break;
646     default:
647         break;
648     }
649
650     if (subexpr->type == EXPR_IDENTIFIER)
651     {
652         const type_t *correlation_variable = NULL;
653         unsigned char correlation_variable_type;
654         unsigned char param_type = 0;
655         size_t offset = 0;
656         const var_t *var;
657
658         if (structure->fields_or_args) LIST_FOR_EACH_ENTRY( var, structure->fields_or_args, const var_t, entry )
659         {
660             unsigned int align = 0;
661             /* FIXME: take alignment into account */
662             if (var->name && !strcmp(var->name, subexpr->u.sval))
663             {
664                 correlation_variable = var->type;
665                 break;
666             }
667             offset += type_memsize(var->type, &align);
668         }
669         if (!correlation_variable)
670             error("write_conf_or_var_desc: couldn't find variable %s in structure\n",
671                   subexpr->u.sval);
672
673         correlation_variable = expr_resolve_type(NULL, structure, expr);
674
675         offset -= baseoff;
676         correlation_variable_type = correlation_variable->type;
677
678         switch (correlation_variable_type)
679         {
680         case RPC_FC_CHAR:
681         case RPC_FC_SMALL:
682             param_type = RPC_FC_SMALL;
683             break;
684         case RPC_FC_BYTE:
685         case RPC_FC_USMALL:
686             param_type = RPC_FC_USMALL;
687             break;
688         case RPC_FC_WCHAR:
689         case RPC_FC_SHORT:
690         case RPC_FC_ENUM16:
691             param_type = RPC_FC_SHORT;
692             break;
693         case RPC_FC_USHORT:
694             param_type = RPC_FC_USHORT;
695             break;
696         case RPC_FC_LONG:
697         case RPC_FC_ENUM32:
698             param_type = RPC_FC_LONG;
699             break;
700         case RPC_FC_ULONG:
701             param_type = RPC_FC_ULONG;
702             break;
703         default:
704             error("write_conf_or_var_desc: conformance variable type not supported 0x%x\n",
705                 correlation_variable_type);
706         }
707
708         print_file(file, 2, "0x%x, /* Corr desc: %s%s */\n",
709                    conftype | param_type, conftype_string, string_of_type(param_type));
710         print_file(file, 2, "0x%x, /* %s */\n", operator_type, operator_string);
711         print_file(file, 2, "NdrFcShort(0x%x), /* offset = %d */\n",
712                    offset, offset);
713     }
714     else
715     {
716         unsigned int callback_offset = 0;
717         struct expr_eval_routine *eval;
718         int found = 0;
719
720         LIST_FOR_EACH_ENTRY(eval, &expr_eval_routines, struct expr_eval_routine, entry)
721         {
722             if (!strcmp (eval->structure->name, structure->name)
723                 && !compare_expr (eval->expr, expr))
724             {
725                 found = 1;
726                 break;
727             }
728             callback_offset++;
729         }
730
731         if (!found)
732         {
733             eval = xmalloc (sizeof(*eval));
734             eval->structure = structure;
735             eval->baseoff = baseoff;
736             eval->expr = expr;
737             list_add_tail (&expr_eval_routines, &eval->entry);
738         }
739
740         if (callback_offset > USHRT_MAX)
741             error("Maximum number of callback routines reached\n");
742
743         print_file(file, 2, "0x%x, /* Corr desc: %s */\n", conftype, conftype_string);
744         print_file(file, 2, "0x%x, /* %s */\n", RPC_FC_CALLBACK, "FC_CALLBACK");
745         print_file(file, 2, "NdrFcShort(0x%x), /* %u */\n", callback_offset, callback_offset);
746     }
747     return 4;
748 }
749
750 static size_t fields_memsize(const var_list_t *fields, unsigned int *align)
751 {
752     int have_align = FALSE;
753     size_t size = 0;
754     const var_t *v;
755
756     if (!fields) return 0;
757     LIST_FOR_EACH_ENTRY( v, fields, const var_t, entry )
758     {
759         unsigned int falign = 0;
760         size_t fsize = type_memsize(v->type, &falign);
761         if (!have_align)
762         {
763             *align = falign;
764             have_align = TRUE;
765         }
766         size = ROUND_SIZE(size, falign);
767         size += fsize;
768     }
769
770     size = ROUND_SIZE(size, *align);
771     return size;
772 }
773
774 static size_t union_memsize(const var_list_t *fields, unsigned int *pmaxa)
775 {
776     size_t size, maxs = 0;
777     unsigned int align = *pmaxa;
778     const var_t *v;
779
780     if (fields) LIST_FOR_EACH_ENTRY( v, fields, const var_t, entry )
781     {
782         /* we could have an empty default field with NULL type */
783         if (v->type)
784         {
785             size = type_memsize(v->type, &align);
786             if (maxs < size) maxs = size;
787             if (*pmaxa < align) *pmaxa = align;
788         }
789     }
790
791     return maxs;
792 }
793
794 int get_padding(const var_list_t *fields)
795 {
796     unsigned short offset = 0;
797     int salign = -1;
798     const var_t *f;
799
800     if (!fields)
801         return 0;
802
803     LIST_FOR_EACH_ENTRY(f, fields, const var_t, entry)
804     {
805         type_t *ft = f->type;
806         unsigned int align = 0;
807         size_t size = type_memsize(ft, &align);
808         if (salign == -1)
809             salign = align;
810         offset = ROUND_SIZE(offset, align);
811         offset += size;
812     }
813
814     return ROUNDING(offset, salign);
815 }
816
817 size_t type_memsize(const type_t *t, unsigned int *align)
818 {
819     size_t size = 0;
820
821     if (t->kind == TKIND_ALIAS)
822         size = type_memsize(t->orig, align);
823     else if (t->declarray && is_conformant_array(t))
824     {
825         type_memsize(t->ref, align);
826         size = 0;
827     }
828     else if (is_ptr(t) || is_conformant_array(t))
829     {
830         size = sizeof(void *);
831         if (size > *align) *align = size;
832     }
833     else switch (t->type)
834     {
835     case RPC_FC_BYTE:
836     case RPC_FC_CHAR:
837     case RPC_FC_USMALL:
838     case RPC_FC_SMALL:
839         size = 1;
840         if (size > *align) *align = size;
841         break;
842     case RPC_FC_WCHAR:
843     case RPC_FC_USHORT:
844     case RPC_FC_SHORT:
845     case RPC_FC_ENUM16:
846         size = 2;
847         if (size > *align) *align = size;
848         break;
849     case RPC_FC_ULONG:
850     case RPC_FC_LONG:
851     case RPC_FC_ERROR_STATUS_T:
852     case RPC_FC_ENUM32:
853     case RPC_FC_FLOAT:
854         size = 4;
855         if (size > *align) *align = size;
856         break;
857     case RPC_FC_HYPER:
858     case RPC_FC_DOUBLE:
859         size = 8;
860         if (size > *align) *align = size;
861         break;
862     case RPC_FC_STRUCT:
863     case RPC_FC_CVSTRUCT:
864     case RPC_FC_CPSTRUCT:
865     case RPC_FC_CSTRUCT:
866     case RPC_FC_PSTRUCT:
867     case RPC_FC_BOGUS_STRUCT:
868         size = fields_memsize(t->fields_or_args, align);
869         break;
870     case RPC_FC_ENCAPSULATED_UNION:
871     case RPC_FC_NON_ENCAPSULATED_UNION:
872         size = union_memsize(t->fields_or_args, align);
873         break;
874     case RPC_FC_SMFARRAY:
875     case RPC_FC_LGFARRAY:
876     case RPC_FC_SMVARRAY:
877     case RPC_FC_LGVARRAY:
878     case RPC_FC_BOGUS_ARRAY:
879         size = t->dim * type_memsize(t->ref, align);
880         break;
881     default:
882         error("type_memsize: Unknown type %d\n", t->type);
883         size = 0;
884     }
885
886     return size;
887 }
888
889 int is_full_pointer_function(const func_t *func)
890 {
891     const var_t *var;
892     if (type_has_full_pointer(get_func_return_type(func)))
893         return TRUE;
894     if (!func->args)
895         return FALSE;
896     LIST_FOR_EACH_ENTRY( var, func->args, const var_t, entry )
897         if (type_has_full_pointer( var->type ))
898             return TRUE;
899     return FALSE;
900 }
901
902 void write_full_pointer_init(FILE *file, int indent, const func_t *func, int is_server)
903 {
904     print_file(file, indent, "__frame->_StubMsg.FullPtrXlatTables = NdrFullPointerXlatInit(0,%s);\n",
905                    is_server ? "XLAT_SERVER" : "XLAT_CLIENT");
906     fprintf(file, "\n");
907 }
908
909 void write_full_pointer_free(FILE *file, int indent, const func_t *func)
910 {
911     print_file(file, indent, "NdrFullPointerXlatFree(__frame->_StubMsg.FullPtrXlatTables);\n");
912     fprintf(file, "\n");
913 }
914
915 static unsigned int write_nonsimple_pointer(FILE *file, const type_t *type, size_t offset)
916 {
917     short absoff = type->ref->typestring_offset;
918     short reloff = absoff - (offset + 2);
919     int ptr_attr = is_ptr(type->ref) ? 0x10 : 0x0;
920
921     print_file(file, 2, "0x%02x, 0x%x,\t/* %s */\n",
922                type->type, ptr_attr, string_of_type(type->type));
923     print_file(file, 2, "NdrFcShort(0x%hx),\t/* Offset= %hd (%hd) */\n",
924                reloff, reloff, absoff);
925     return 4;
926 }
927
928 static unsigned int write_simple_pointer(FILE *file, const type_t *type)
929 {
930     unsigned char fc = type->ref->type;
931     /* for historical reasons, write_simple_pointer also handled string types,
932      * but no longer does. catch bad uses of the function with this check */
933     if (is_string_type(type->attrs, type))
934         error("write_simple_pointer: can't handle type %s which is a string type\n", type->name);
935     print_file(file, 2, "0x%02x, 0x8,\t/* %s [simple_pointer] */\n",
936                type->type, string_of_type(type->type));
937     print_file(file, 2, "0x%02x,\t/* %s */\n", fc, string_of_type(fc));
938     print_file(file, 2, "0x5c,\t/* FC_PAD */\n");
939     return 4;
940 }
941
942 static void print_start_tfs_comment(FILE *file, type_t *t, unsigned int tfsoff)
943 {
944     print_file(file, 0, "/* %u (", tfsoff);
945     write_type_decl(file, t, NULL);
946     print_file(file, 0, ") */\n");
947 }
948
949 static size_t write_pointer_tfs(FILE *file, type_t *type, unsigned int *typestring_offset)
950 {
951     unsigned int offset = *typestring_offset;
952
953     print_start_tfs_comment(file, type, offset);
954     update_tfsoff(type, offset, file);
955
956     if (type->ref->typestring_offset)
957         *typestring_offset += write_nonsimple_pointer(file, type, offset);
958     else if (is_base_type(type->ref->type))
959         *typestring_offset += write_simple_pointer(file, type);
960
961     return offset;
962 }
963
964 static int processed(const type_t *type)
965 {
966     return type->typestring_offset && !type->tfswrite;
967 }
968
969 static int user_type_has_variable_size(const type_t *t)
970 {
971     if (is_ptr(t))
972         return TRUE;
973     else
974         switch (t->type)
975         {
976         case RPC_FC_PSTRUCT:
977         case RPC_FC_CSTRUCT:
978         case RPC_FC_CPSTRUCT:
979         case RPC_FC_CVSTRUCT:
980             return TRUE;
981         }
982     /* Note: Since this only applies to user types, we can't have a conformant
983        array here, and strings should get filed under pointer in this case.  */
984     return FALSE;
985 }
986
987 static void write_user_tfs(FILE *file, type_t *type, unsigned int *tfsoff)
988 {
989     unsigned int start, absoff, flags;
990     unsigned int align = 0, ualign = 0;
991     const char *name = NULL;
992     type_t *utype = get_user_type(type, &name);
993     size_t usize = user_type_has_variable_size(utype) ? 0 : type_memsize(utype, &ualign);
994     size_t size = type_memsize(type, &align);
995     unsigned short funoff = user_type_offset(name);
996     short reloff;
997
998     guard_rec(type);
999
1000     if (is_base_type(utype->type))
1001     {
1002         absoff = *tfsoff;
1003         print_start_tfs_comment(file, utype, absoff);
1004         print_file(file, 2, "0x%x,\t/* %s */\n", utype->type, string_of_type(utype->type));
1005         print_file(file, 2, "0x5c,\t/* FC_PAD */\n");
1006         *tfsoff += 2;
1007     }
1008     else
1009     {
1010         if (!processed(utype))
1011             write_embedded_types(file, NULL, utype, utype->name, TRUE, tfsoff);
1012         absoff = utype->typestring_offset;
1013     }
1014
1015     if (utype->type == RPC_FC_RP)
1016         flags = 0x40;
1017     else if (utype->type == RPC_FC_UP)
1018         flags = 0x80;
1019     else
1020         flags = 0;
1021
1022     start = *tfsoff;
1023     update_tfsoff(type, start, file);
1024     print_start_tfs_comment(file, type, start);
1025     print_file(file, 2, "0x%x,\t/* FC_USER_MARSHAL */\n", RPC_FC_USER_MARSHAL);
1026     print_file(file, 2, "0x%x,\t/* Alignment= %d, Flags= %02x */\n",
1027                flags | (align - 1), align - 1, flags);
1028     print_file(file, 2, "NdrFcShort(0x%hx),\t/* Function offset= %hu */\n", funoff, funoff);
1029     print_file(file, 2, "NdrFcShort(0x%lx),\t/* %lu */\n", size, size);
1030     print_file(file, 2, "NdrFcShort(0x%lx),\t/* %lu */\n", usize, usize);
1031     *tfsoff += 8;
1032     reloff = absoff - *tfsoff;
1033     print_file(file, 2, "NdrFcShort(0x%hx),\t/* Offset= %hd (%lu) */\n", reloff, reloff, absoff);
1034     *tfsoff += 2;
1035 }
1036
1037 static void write_member_type(FILE *file, const type_t *cont,
1038                               const attr_list_t *attrs, const type_t *type,
1039                               unsigned int *corroff, unsigned int *tfsoff)
1040 {
1041     if (is_embedded_complex(type) && !is_conformant_array(type))
1042     {
1043         size_t absoff;
1044         short reloff;
1045
1046         if (is_union(type->type) && is_attr(attrs, ATTR_SWITCHIS))
1047         {
1048             absoff = *corroff;
1049             *corroff += 8;
1050         }
1051         else
1052         {
1053             absoff = type->typestring_offset;
1054         }
1055         reloff = absoff - (*tfsoff + 2);
1056
1057         print_file(file, 2, "0x4c,\t/* FC_EMBEDDED_COMPLEX */\n");
1058         /* FIXME: actually compute necessary padding */
1059         print_file(file, 2, "0x0,\t/* FIXME: padding */\n");
1060         print_file(file, 2, "NdrFcShort(0x%hx),\t/* Offset= %hd (%lu) */\n",
1061                    reloff, reloff, absoff);
1062         *tfsoff += 4;
1063     }
1064     else if (is_ptr(type) || is_conformant_array(type))
1065     {
1066         unsigned char fc = (cont->type == RPC_FC_BOGUS_STRUCT
1067                             ? RPC_FC_POINTER
1068                             : RPC_FC_LONG);
1069         print_file(file, 2, "0x%x,\t/* %s */\n", fc, string_of_type(fc));
1070         *tfsoff += 1;
1071     }
1072     else if (!write_base_type(file, type, tfsoff))
1073         error("Unsupported member type 0x%x\n", type->type);
1074 }
1075
1076 static void write_end(FILE *file, unsigned int *tfsoff)
1077 {
1078     if (*tfsoff % 2 == 0)
1079     {
1080         print_file(file, 2, "0x%x,\t\t/* FC_PAD */\n", RPC_FC_PAD);
1081         *tfsoff += 1;
1082     }
1083     print_file(file, 2, "0x%x,\t\t/* FC_END */\n", RPC_FC_END);
1084     *tfsoff += 1;
1085 }
1086
1087 static void write_descriptors(FILE *file, type_t *type, unsigned int *tfsoff)
1088 {
1089     unsigned int offset = 0;
1090     var_list_t *fs = type->fields_or_args;
1091     var_t *f;
1092
1093     if (fs) LIST_FOR_EACH_ENTRY(f, fs, var_t, entry)
1094     {
1095         unsigned int align = 0;
1096         type_t *ft = f->type;
1097         if (is_union(ft->type) && is_attr(f->attrs, ATTR_SWITCHIS))
1098         {
1099             unsigned int absoff = ft->typestring_offset;
1100             short reloff = absoff - (*tfsoff + 6);
1101             print_file(file, 0, "/* %d */\n", *tfsoff);
1102             print_file(file, 2, "0x%x,\t/* %s */\n", ft->type, string_of_type(ft->type));
1103             print_file(file, 2, "0x%x,\t/* FIXME: always FC_LONG */\n", RPC_FC_LONG);
1104             write_conf_or_var_desc(file, current_structure, offset, ft,
1105                                    get_attrp(f->attrs, ATTR_SWITCHIS));
1106             print_file(file, 2, "NdrFcShort(%hd),\t/* Offset= %hd (%u) */\n",
1107                        reloff, reloff, absoff);
1108             *tfsoff += 8;
1109         }
1110
1111         /* FIXME: take alignment into account */
1112         offset += type_memsize(ft, &align);
1113     }
1114 }
1115
1116 static int write_no_repeat_pointer_descriptions(
1117     FILE *file, type_t *type,
1118     size_t *offset_in_memory, size_t *offset_in_buffer,
1119     unsigned int *typestring_offset)
1120 {
1121     int written = 0;
1122     unsigned int align;
1123
1124     if (is_ptr(type) || (!type->declarray && is_conformant_array(type)))
1125     {
1126         size_t memsize;
1127
1128         print_file(file, 2, "0x%02x, /* FC_NO_REPEAT */\n", RPC_FC_NO_REPEAT);
1129         print_file(file, 2, "0x%02x, /* FC_PAD */\n", RPC_FC_PAD);
1130
1131         /* pointer instance */
1132         print_file(file, 2, "NdrFcShort(0x%x), /* Memory offset = %d */\n", *offset_in_memory, *offset_in_memory);
1133         print_file(file, 2, "NdrFcShort(0x%x), /* Buffer offset = %d */\n", *offset_in_buffer, *offset_in_buffer);
1134         *typestring_offset += 6;
1135
1136         if (is_ptr(type))
1137         {
1138             if (is_string_type(type->attrs, type))
1139                 write_string_tfs(file, NULL, type, NULL, typestring_offset);
1140             else
1141                 write_pointer_tfs(file, type, typestring_offset);
1142         }
1143         else
1144         {
1145             unsigned absoff = type->typestring_offset;
1146             short reloff = absoff - (*typestring_offset + 2);
1147             /* FIXME: get pointer attributes from field */
1148             print_file(file, 2, "0x%02x, 0x0,\t/* %s */\n", RPC_FC_UP, "FC_UP");
1149             print_file(file, 2, "NdrFcShort(0x%hx),\t/* Offset= %hd (%u) */\n",
1150                        reloff, reloff, absoff);
1151             *typestring_offset += 4;
1152         }
1153
1154         align = 0;
1155         memsize = type_memsize(type, &align);
1156         *offset_in_memory += memsize;
1157         /* increment these separately as in the case of conformant (varying)
1158          * structures these start at different values */
1159         *offset_in_buffer += memsize;
1160
1161         return 1;
1162     }
1163
1164     if (is_non_complex_struct(type))
1165     {
1166         const var_t *v;
1167         LIST_FOR_EACH_ENTRY( v, type->fields_or_args, const var_t, entry )
1168         {
1169             if (offset_in_memory && offset_in_buffer)
1170             {
1171                 size_t padding;
1172                 align = 0;
1173                 type_memsize(v->type, &align);
1174                 padding = ROUNDING(*offset_in_memory, align);
1175                 *offset_in_memory += padding;
1176                 *offset_in_buffer += padding;
1177             }
1178             written += write_no_repeat_pointer_descriptions(
1179                 file, v->type,
1180                 offset_in_memory, offset_in_buffer, typestring_offset);
1181         }
1182     }
1183     else
1184     {
1185         size_t memsize;
1186         align = 0;
1187         memsize = type_memsize(type, &align);
1188         *offset_in_memory += memsize;
1189         /* increment these separately as in the case of conformant (varying)
1190          * structures these start at different values */
1191         *offset_in_buffer += memsize;
1192     }
1193
1194     return written;
1195 }
1196
1197 static int write_pointer_description_offsets(
1198     FILE *file, const attr_list_t *attrs, type_t *type,
1199     size_t *offset_in_memory, size_t *offset_in_buffer,
1200     unsigned int *typestring_offset)
1201 {
1202     int written = 0;
1203     unsigned int align;
1204
1205     if (is_ptr(type) && type->ref->type != RPC_FC_IP)
1206     {
1207         if (offset_in_memory && offset_in_buffer)
1208         {
1209             size_t memsize;
1210
1211             /* pointer instance */
1212             /* FIXME: sometimes from end of structure, sometimes from beginning */
1213             print_file(file, 2, "NdrFcShort(0x%x), /* Memory offset = %d */\n", *offset_in_memory, *offset_in_memory);
1214             print_file(file, 2, "NdrFcShort(0x%x), /* Buffer offset = %d */\n", *offset_in_buffer, *offset_in_buffer);
1215
1216             align = 0;
1217             memsize = type_memsize(type, &align);
1218             *offset_in_memory += memsize;
1219             /* increment these separately as in the case of conformant (varying)
1220              * structures these start at different values */
1221             *offset_in_buffer += memsize;
1222         }
1223         *typestring_offset += 4;
1224
1225         if (is_string_type(attrs, type))
1226             write_string_tfs(file, NULL, type, NULL, typestring_offset);
1227         else if (processed(type->ref) || is_base_type(type->ref->type))
1228             write_pointer_tfs(file, type, typestring_offset);
1229         else
1230             error("write_pointer_description_offsets: type format string unknown\n");
1231
1232         return 1;
1233     }
1234
1235     if (is_array(type))
1236     {
1237         return write_pointer_description_offsets(
1238             file, attrs, type->ref, offset_in_memory, offset_in_buffer,
1239             typestring_offset);
1240     }
1241     else if (is_non_complex_struct(type))
1242     {
1243         /* otherwise search for interesting fields to parse */
1244         const var_t *v;
1245         LIST_FOR_EACH_ENTRY( v, type->fields_or_args, const var_t, entry )
1246         {
1247             if (offset_in_memory && offset_in_buffer)
1248             {
1249                 size_t padding;
1250                 align = 0;
1251                 type_memsize(v->type, &align);
1252                 padding = ROUNDING(*offset_in_memory, align);
1253                 *offset_in_memory += padding;
1254                 *offset_in_buffer += padding;
1255             }
1256             written += write_pointer_description_offsets(
1257                 file, v->attrs, v->type, offset_in_memory, offset_in_buffer,
1258                 typestring_offset);
1259         }
1260     }
1261     else
1262     {
1263         if (offset_in_memory && offset_in_buffer)
1264         {
1265             size_t memsize;
1266             align = 0;
1267             memsize = type_memsize(type, &align);
1268             *offset_in_memory += memsize;
1269             /* increment these separately as in the case of conformant (varying)
1270              * structures these start at different values */
1271             *offset_in_buffer += memsize;
1272         }
1273     }
1274
1275     return written;
1276 }
1277
1278 /* Note: if file is NULL return value is number of pointers to write, else
1279  * it is the number of type format characters written */
1280 static int write_fixed_array_pointer_descriptions(
1281     FILE *file, const attr_list_t *attrs, type_t *type,
1282     size_t *offset_in_memory, size_t *offset_in_buffer,
1283     unsigned int *typestring_offset)
1284 {
1285     unsigned int align;
1286     int pointer_count = 0;
1287
1288     if (type->type == RPC_FC_SMFARRAY || type->type == RPC_FC_LGFARRAY)
1289     {
1290         unsigned int temp = 0;
1291         /* unfortunately, this needs to be done in two passes to avoid
1292          * writing out redundant FC_FIXED_REPEAT descriptions */
1293         pointer_count = write_pointer_description_offsets(
1294             NULL, attrs, type->ref, NULL, NULL, &temp);
1295         if (pointer_count > 0)
1296         {
1297             unsigned int increment_size;
1298             size_t offset_of_array_pointer_mem = 0;
1299             size_t offset_of_array_pointer_buf = 0;
1300
1301             align = 0;
1302             increment_size = type_memsize(type->ref, &align);
1303
1304             print_file(file, 2, "0x%02x, /* FC_FIXED_REPEAT */\n", RPC_FC_FIXED_REPEAT);
1305             print_file(file, 2, "0x%02x, /* FC_PAD */\n", RPC_FC_PAD);
1306             print_file(file, 2, "NdrFcShort(0x%x), /* Iterations = %d */\n", type->dim, type->dim);
1307             print_file(file, 2, "NdrFcShort(0x%x), /* Increment = %d */\n", increment_size, increment_size);
1308             print_file(file, 2, "NdrFcShort(0x%x), /* Offset to array = %d */\n", *offset_in_memory, *offset_in_memory);
1309             print_file(file, 2, "NdrFcShort(0x%x), /* Number of pointers = %d */\n", pointer_count, pointer_count);
1310             *typestring_offset += 10;
1311
1312             pointer_count = write_pointer_description_offsets(
1313                 file, attrs, type, &offset_of_array_pointer_mem,
1314                 &offset_of_array_pointer_buf, typestring_offset);
1315         }
1316     }
1317     else if (is_struct(type->type))
1318     {
1319         const var_t *v;
1320         LIST_FOR_EACH_ENTRY( v, type->fields_or_args, const var_t, entry )
1321         {
1322             if (offset_in_memory && offset_in_buffer)
1323             {
1324                 size_t padding;
1325                 align = 0;
1326                 type_memsize(v->type, &align);
1327                 padding = ROUNDING(*offset_in_memory, align);
1328                 *offset_in_memory += padding;
1329                 *offset_in_buffer += padding;
1330             }
1331             pointer_count += write_fixed_array_pointer_descriptions(
1332                 file, v->attrs, v->type, offset_in_memory, offset_in_buffer,
1333                 typestring_offset);
1334         }
1335     }
1336     else
1337     {
1338         if (offset_in_memory && offset_in_buffer)
1339         {
1340             size_t memsize;
1341             align = 0;
1342             memsize = type_memsize(type, &align);
1343             *offset_in_memory += memsize;
1344             /* increment these separately as in the case of conformant (varying)
1345              * structures these start at different values */
1346             *offset_in_buffer += memsize;
1347         }
1348     }
1349
1350     return pointer_count;
1351 }
1352
1353 /* Note: if file is NULL return value is number of pointers to write, else
1354  * it is the number of type format characters written */
1355 static int write_conformant_array_pointer_descriptions(
1356     FILE *file, const attr_list_t *attrs, type_t *type,
1357     size_t offset_in_memory, unsigned int *typestring_offset)
1358 {
1359     unsigned int align;
1360     int pointer_count = 0;
1361
1362     if (is_conformant_array(type) && !type->length_is)
1363     {
1364         unsigned int temp = 0;
1365         /* unfortunately, this needs to be done in two passes to avoid
1366          * writing out redundant FC_VARIABLE_REPEAT descriptions */
1367         pointer_count = write_pointer_description_offsets(
1368             NULL, attrs, type->ref, NULL, NULL, &temp);
1369         if (pointer_count > 0)
1370         {
1371             unsigned int increment_size;
1372             size_t offset_of_array_pointer_mem = offset_in_memory;
1373             size_t offset_of_array_pointer_buf = offset_in_memory;
1374
1375             align = 0;
1376             increment_size = type_memsize(type->ref, &align);
1377
1378             if (increment_size > USHRT_MAX)
1379                 error("array size of %u bytes is too large\n", increment_size);
1380
1381             print_file(file, 2, "0x%02x, /* FC_VARIABLE_REPEAT */\n", RPC_FC_VARIABLE_REPEAT);
1382             print_file(file, 2, "0x%02x, /* FC_FIXED_OFFSET */\n", RPC_FC_FIXED_OFFSET);
1383             print_file(file, 2, "NdrFcShort(0x%x), /* Increment = %d */\n", increment_size, increment_size);
1384             print_file(file, 2, "NdrFcShort(0x%x), /* Offset to array = %d */\n", offset_in_memory, offset_in_memory);
1385             print_file(file, 2, "NdrFcShort(0x%x), /* Number of pointers = %d */\n", pointer_count, pointer_count);
1386             *typestring_offset += 8;
1387
1388             pointer_count = write_pointer_description_offsets(
1389                 file, attrs, type->ref, &offset_of_array_pointer_mem,
1390                 &offset_of_array_pointer_buf, typestring_offset);
1391         }
1392     }
1393
1394     return pointer_count;
1395 }
1396
1397 /* Note: if file is NULL return value is number of pointers to write, else
1398  * it is the number of type format characters written */
1399 static int write_varying_array_pointer_descriptions(
1400     FILE *file, const attr_list_t *attrs, type_t *type,
1401     size_t *offset_in_memory, size_t *offset_in_buffer,
1402     unsigned int *typestring_offset)
1403 {
1404     unsigned int align;
1405     int pointer_count = 0;
1406
1407     if (is_array(type) && type->length_is)
1408     {
1409         unsigned int temp = 0;
1410         /* unfortunately, this needs to be done in two passes to avoid
1411          * writing out redundant FC_VARIABLE_REPEAT descriptions */
1412         pointer_count = write_pointer_description_offsets(
1413             NULL, attrs, type->ref, NULL, NULL, &temp);
1414         if (pointer_count > 0)
1415         {
1416             unsigned int increment_size;
1417
1418             align = 0;
1419             increment_size = type_memsize(type->ref, &align);
1420
1421             if (increment_size > USHRT_MAX)
1422                 error("array size of %u bytes is too large\n", increment_size);
1423
1424             print_file(file, 2, "0x%02x, /* FC_VARIABLE_REPEAT */\n", RPC_FC_VARIABLE_REPEAT);
1425             print_file(file, 2, "0x%02x, /* FC_VARIABLE_OFFSET */\n", RPC_FC_VARIABLE_OFFSET);
1426             print_file(file, 2, "NdrFcShort(0x%x), /* Increment = %d */\n", increment_size, increment_size);
1427             print_file(file, 2, "NdrFcShort(0x%x), /* Offset to array = %d */\n", *offset_in_memory, *offset_in_memory);
1428             print_file(file, 2, "NdrFcShort(0x%x), /* Number of pointers = %d */\n", pointer_count, pointer_count);
1429             *typestring_offset += 8;
1430
1431             pointer_count = write_pointer_description_offsets(
1432                 file, attrs, type, offset_in_memory,
1433                 offset_in_buffer, typestring_offset);
1434         }
1435     }
1436     else if (is_struct(type->type))
1437     {
1438         const var_t *v;
1439         LIST_FOR_EACH_ENTRY( v, type->fields_or_args, const var_t, entry )
1440         {
1441             if (offset_in_memory && offset_in_buffer)
1442             {
1443                 size_t padding;
1444
1445                 if (is_array(v->type) && v->type->length_is)
1446                 {
1447                     *offset_in_buffer = ROUND_SIZE(*offset_in_buffer, 4);
1448                     /* skip over variance and offset in buffer */
1449                     *offset_in_buffer += 8;
1450                 }
1451
1452                 align = 0;
1453                 type_memsize(v->type, &align);
1454                 padding = ROUNDING(*offset_in_memory, align);
1455                 *offset_in_memory += padding;
1456                 *offset_in_buffer += padding;
1457             }
1458             pointer_count += write_varying_array_pointer_descriptions(
1459                 file, v->attrs, v->type, offset_in_memory, offset_in_buffer,
1460                 typestring_offset);
1461         }
1462     }
1463     else
1464     {
1465         if (offset_in_memory && offset_in_buffer)
1466         {
1467             size_t memsize;
1468             align = 0;
1469             memsize = type_memsize(type, &align);
1470             *offset_in_memory += memsize;
1471             /* increment these separately as in the case of conformant (varying)
1472              * structures these start at different values */
1473             *offset_in_buffer += memsize;
1474         }
1475     }
1476
1477     return pointer_count;
1478 }
1479
1480 static void write_pointer_description(FILE *file, type_t *type,
1481                                       unsigned int *typestring_offset)
1482 {
1483     size_t offset_in_buffer;
1484     size_t offset_in_memory;
1485
1486     /* pass 1: search for single instance of a pointer (i.e. don't descend
1487      * into arrays) */
1488     if (!is_array(type))
1489     {
1490         offset_in_memory = 0;
1491         offset_in_buffer = 0;
1492         write_no_repeat_pointer_descriptions(
1493             file, type,
1494             &offset_in_memory, &offset_in_buffer, typestring_offset);
1495     }
1496
1497     /* pass 2: search for pointers in fixed arrays */
1498     offset_in_memory = 0;
1499     offset_in_buffer = 0;
1500     write_fixed_array_pointer_descriptions(
1501         file, NULL, type,
1502         &offset_in_memory, &offset_in_buffer, typestring_offset);
1503
1504     /* pass 3: search for pointers in conformant only arrays (but don't descend
1505      * into conformant varying or varying arrays) */
1506     if ((!type->declarray || !current_structure) && is_conformant_array(type))
1507         write_conformant_array_pointer_descriptions(
1508             file, NULL, type, 0, typestring_offset);
1509     else if (type->type == RPC_FC_CPSTRUCT)
1510     {
1511         unsigned int align = 0;
1512         type_t *carray = find_array_or_string_in_struct(type)->type;
1513         write_conformant_array_pointer_descriptions(
1514             file, NULL, carray,
1515             type_memsize(type, &align),
1516             typestring_offset);
1517     }
1518
1519     /* pass 4: search for pointers in varying arrays */
1520     offset_in_memory = 0;
1521     offset_in_buffer = 0;
1522     write_varying_array_pointer_descriptions(
1523             file, NULL, type,
1524             &offset_in_memory, &offset_in_buffer, typestring_offset);
1525 }
1526
1527 int is_declptr(const type_t *t)
1528 {
1529   return is_ptr(t) || (is_conformant_array(t) && !t->declarray);
1530 }
1531
1532 static size_t write_string_tfs(FILE *file, const attr_list_t *attrs,
1533                                type_t *type,
1534                                const char *name, unsigned int *typestring_offset)
1535 {
1536     size_t start_offset;
1537     unsigned char rtype;
1538
1539     if (is_declptr(type))
1540     {
1541         unsigned char flag = is_conformant_array(type) ? 0 : RPC_FC_P_SIMPLEPOINTER;
1542         int pointer_type = is_ptr(type) ? type->type : get_attrv(attrs, ATTR_POINTERTYPE);
1543         if (!pointer_type)
1544             pointer_type = RPC_FC_RP;
1545         print_start_tfs_comment(file, type, *typestring_offset);
1546         print_file(file, 2,"0x%x, 0x%x,\t/* %s%s */\n",
1547                    pointer_type, flag, string_of_type(pointer_type),
1548                    flag ? " [simple_pointer]" : "");
1549         *typestring_offset += 2;
1550         if (!flag)
1551         {
1552             print_file(file, 2, "NdrFcShort(0x2),\n");
1553             *typestring_offset += 2;
1554         }
1555     }
1556
1557     start_offset = *typestring_offset;
1558     update_tfsoff(type, start_offset, file);
1559
1560     rtype = type->ref->type;
1561
1562     if ((rtype != RPC_FC_BYTE) && (rtype != RPC_FC_CHAR) && (rtype != RPC_FC_WCHAR))
1563     {
1564         error("write_string_tfs: Unimplemented for type 0x%x of name: %s\n", rtype, name);
1565         return start_offset;
1566     }
1567
1568     if (type->declarray && !is_conformant_array(type))
1569     {
1570         /* FIXME: multi-dimensional array */
1571         if (0xffffuL < type->dim)
1572             error("array size for parameter %s exceeds %u bytes by %lu bytes\n",
1573                   name, 0xffffu, type->dim - 0xffffu);
1574
1575         if (rtype == RPC_FC_CHAR)
1576             WRITE_FCTYPE(file, FC_CSTRING, *typestring_offset);
1577         else
1578             WRITE_FCTYPE(file, FC_WSTRING, *typestring_offset);
1579         print_file(file, 2, "0x%x, /* FC_PAD */\n", RPC_FC_PAD);
1580         *typestring_offset += 2;
1581
1582         print_file(file, 2, "NdrFcShort(0x%x), /* %d */\n", type->dim, type->dim);
1583         *typestring_offset += 2;
1584
1585         return start_offset;
1586     }
1587     else if (type->size_is)
1588     {
1589         unsigned int align = 0;
1590
1591         if (rtype == RPC_FC_CHAR)
1592             WRITE_FCTYPE(file, FC_C_CSTRING, *typestring_offset);
1593         else
1594             WRITE_FCTYPE(file, FC_C_WSTRING, *typestring_offset);
1595         print_file(file, 2, "0x%x, /* FC_STRING_SIZED */\n", RPC_FC_STRING_SIZED);
1596         *typestring_offset += 2;
1597
1598         *typestring_offset += write_conf_or_var_desc(
1599             file, current_structure,
1600             (type->declarray && current_structure
1601              ? type_memsize(current_structure, &align)
1602              : 0),
1603             type, type->size_is);
1604
1605         return start_offset;
1606     }
1607     else
1608     {
1609         if (rtype == RPC_FC_WCHAR)
1610             WRITE_FCTYPE(file, FC_C_WSTRING, *typestring_offset);
1611         else
1612             WRITE_FCTYPE(file, FC_C_CSTRING, *typestring_offset);
1613         print_file(file, 2, "0x%x, /* FC_PAD */\n", RPC_FC_PAD);
1614         *typestring_offset += 2;
1615
1616         return start_offset;
1617     }
1618 }
1619
1620 static size_t write_array_tfs(FILE *file, const attr_list_t *attrs, type_t *type,
1621                               const char *name, unsigned int *typestring_offset)
1622 {
1623     const expr_t *length_is = type->length_is;
1624     const expr_t *size_is = type->size_is;
1625     unsigned int align = 0;
1626     size_t size;
1627     size_t start_offset;
1628     int has_pointer;
1629     int pointer_type = get_attrv(attrs, ATTR_POINTERTYPE);
1630     unsigned int baseoff
1631         = type->declarray && current_structure
1632         ? type_memsize(current_structure, &align)
1633         : 0;
1634
1635     if (!pointer_type)
1636         pointer_type = RPC_FC_RP;
1637
1638     if (write_embedded_types(file, attrs, type->ref, name, FALSE, typestring_offset))
1639         has_pointer = TRUE;
1640     else
1641         has_pointer = type_has_pointers(type->ref);
1642
1643     align = 0;
1644     size = type_memsize((is_conformant_array(type) ? type->ref : type), &align);
1645
1646     start_offset = *typestring_offset;
1647     update_tfsoff(type, start_offset, file);
1648     print_start_tfs_comment(file, type, start_offset);
1649     print_file(file, 2, "0x%02x,\t/* %s */\n", type->type, string_of_type(type->type));
1650     print_file(file, 2, "0x%x,\t/* %d */\n", align - 1, align - 1);
1651     *typestring_offset += 2;
1652
1653     align = 0;
1654     if (type->type != RPC_FC_BOGUS_ARRAY)
1655     {
1656         unsigned char tc = type->type;
1657
1658         if (tc == RPC_FC_LGFARRAY || tc == RPC_FC_LGVARRAY)
1659         {
1660             print_file(file, 2, "NdrFcLong(0x%x),\t/* %lu */\n", size, size);
1661             *typestring_offset += 4;
1662         }
1663         else
1664         {
1665             print_file(file, 2, "NdrFcShort(0x%x),\t/* %lu */\n", size, size);
1666             *typestring_offset += 2;
1667         }
1668
1669         if (is_conformant_array(type))
1670             *typestring_offset
1671                 += write_conf_or_var_desc(file, current_structure, baseoff,
1672                                           type, size_is);
1673
1674         if (type->type == RPC_FC_SMVARRAY || type->type == RPC_FC_LGVARRAY)
1675         {
1676             unsigned int elalign = 0;
1677             size_t elsize = type_memsize(type->ref, &elalign);
1678
1679             if (type->type == RPC_FC_LGVARRAY)
1680             {
1681                 print_file(file, 2, "NdrFcLong(0x%x),\t/* %lu */\n", type->dim, type->dim);
1682                 *typestring_offset += 4;
1683             }
1684             else
1685             {
1686                 print_file(file, 2, "NdrFcShort(0x%x),\t/* %lu */\n", type->dim, type->dim);
1687                 *typestring_offset += 2;
1688             }
1689
1690             print_file(file, 2, "NdrFcShort(0x%x),\t/* %lu */\n", elsize, elsize);
1691             *typestring_offset += 2;
1692         }
1693
1694         if (length_is)
1695             *typestring_offset
1696                 += write_conf_or_var_desc(file, current_structure, baseoff,
1697                                           type, length_is);
1698
1699         if (has_pointer && (!type->declarray || !current_structure))
1700         {
1701             print_file(file, 2, "0x%x, /* FC_PP */\n", RPC_FC_PP);
1702             print_file(file, 2, "0x%x, /* FC_PAD */\n", RPC_FC_PAD);
1703             *typestring_offset += 2;
1704             write_pointer_description(file, type, typestring_offset);
1705             print_file(file, 2, "0x%x, /* FC_END */\n", RPC_FC_END);
1706             *typestring_offset += 1;
1707         }
1708
1709         write_member_type(file, type, NULL, type->ref, NULL, typestring_offset);
1710         write_end(file, typestring_offset);
1711     }
1712     else
1713     {
1714         unsigned int dim = size_is ? 0 : type->dim;
1715         print_file(file, 2, "NdrFcShort(0x%x),\t/* %u */\n", dim, dim);
1716         *typestring_offset += 2;
1717         *typestring_offset
1718             += write_conf_or_var_desc(file, current_structure, baseoff,
1719                                       type, size_is);
1720         *typestring_offset
1721             += write_conf_or_var_desc(file, current_structure, baseoff,
1722                                       type, length_is);
1723         write_member_type(file, type, NULL, type->ref, NULL, typestring_offset);
1724         write_end(file, typestring_offset);
1725     }
1726
1727     return start_offset;
1728 }
1729
1730 static const var_t *find_array_or_string_in_struct(const type_t *type)
1731 {
1732     const var_t *last_field;
1733     const type_t *ft;
1734
1735     if (!type->fields_or_args || list_empty(type->fields_or_args))
1736         return NULL;
1737
1738     last_field = LIST_ENTRY( list_tail(type->fields_or_args), const var_t, entry );
1739     ft = last_field->type;
1740
1741     if (ft->declarray && is_conformant_array(ft))
1742         return last_field;
1743
1744     if (ft->type == RPC_FC_CSTRUCT || ft->type == RPC_FC_CPSTRUCT || ft->type == RPC_FC_CVSTRUCT)
1745         return find_array_or_string_in_struct(ft);
1746     else
1747         return NULL;
1748 }
1749
1750 static void write_struct_members(FILE *file, const type_t *type,
1751                                  unsigned int *corroff, unsigned int *typestring_offset)
1752 {
1753     const var_t *field;
1754     unsigned short offset = 0;
1755     int salign = -1;
1756     int padding;
1757
1758     if (type->fields_or_args) LIST_FOR_EACH_ENTRY( field, type->fields_or_args, const var_t, entry )
1759     {
1760         type_t *ft = field->type;
1761         if (!ft->declarray || !is_conformant_array(ft))
1762         {
1763             unsigned int align = 0;
1764             size_t size = type_memsize(ft, &align);
1765             if (salign == -1)
1766                 salign = align;
1767             if ((align - 1) & offset)
1768             {
1769                 unsigned char fc = 0;
1770                 switch (align)
1771                 {
1772                 case 4:
1773                     fc = RPC_FC_ALIGNM4;
1774                     break;
1775                 case 8:
1776                     fc = RPC_FC_ALIGNM8;
1777                     break;
1778                 default:
1779                     error("write_struct_members: cannot align type %d\n", ft->type);
1780                 }
1781                 print_file(file, 2, "0x%x,\t/* %s */\n", fc, string_of_type(fc));
1782                 offset = ROUND_SIZE(offset, align);
1783                 *typestring_offset += 1;
1784             }
1785             write_member_type(file, type, field->attrs, field->type, corroff,
1786                               typestring_offset);
1787             offset += size;
1788         }
1789     }
1790
1791     padding = ROUNDING(offset, salign);
1792     if (padding)
1793     {
1794         print_file(file, 2, "0x%x,\t/* FC_STRUCTPAD%d */\n",
1795                    RPC_FC_STRUCTPAD1 + padding - 1,
1796                    padding);
1797         *typestring_offset += 1;
1798     }
1799
1800     write_end(file, typestring_offset);
1801 }
1802
1803 static size_t write_struct_tfs(FILE *file, type_t *type,
1804                                const char *name, unsigned int *tfsoff)
1805 {
1806     const type_t *save_current_structure = current_structure;
1807     unsigned int total_size;
1808     const var_t *array;
1809     size_t start_offset;
1810     size_t array_offset;
1811     int has_pointers = 0;
1812     unsigned int align = 0;
1813     unsigned int corroff;
1814     var_t *f;
1815
1816     guard_rec(type);
1817     current_structure = type;
1818
1819     total_size = type_memsize(type, &align);
1820     if (total_size > USHRT_MAX)
1821         error("structure size for %s exceeds %d bytes by %d bytes\n",
1822               name, USHRT_MAX, total_size - USHRT_MAX);
1823
1824     if (type->fields_or_args) LIST_FOR_EACH_ENTRY(f, type->fields_or_args, var_t, entry)
1825         has_pointers |= write_embedded_types(file, f->attrs, f->type, f->name,
1826                                              FALSE, tfsoff);
1827     if (!has_pointers) has_pointers = type_has_pointers(type);
1828
1829     array = find_array_or_string_in_struct(type);
1830     if (array && !processed(array->type))
1831         array_offset
1832             = is_attr(array->attrs, ATTR_STRING)
1833             ? write_string_tfs(file, array->attrs, array->type, array->name, tfsoff)
1834             : write_array_tfs(file, array->attrs, array->type, array->name, tfsoff);
1835
1836     corroff = *tfsoff;
1837     write_descriptors(file, type, tfsoff);
1838
1839     start_offset = *tfsoff;
1840     update_tfsoff(type, start_offset, file);
1841     print_start_tfs_comment(file, type, start_offset);
1842     print_file(file, 2, "0x%x,\t/* %s */\n", type->type, string_of_type(type->type));
1843     print_file(file, 2, "0x%x,\t/* %d */\n", align - 1, align - 1);
1844     print_file(file, 2, "NdrFcShort(0x%x),\t/* %d */\n", total_size, total_size);
1845     *tfsoff += 4;
1846
1847     if (array)
1848     {
1849         unsigned int absoff = array->type->typestring_offset;
1850         short reloff = absoff - *tfsoff;
1851         print_file(file, 2, "NdrFcShort(0x%hx),\t/* Offset= %hd (%lu) */\n",
1852                    reloff, reloff, absoff);
1853         *tfsoff += 2;
1854     }
1855     else if (type->type == RPC_FC_BOGUS_STRUCT)
1856     {
1857         print_file(file, 2, "NdrFcShort(0x0),\n");
1858         *tfsoff += 2;
1859     }
1860
1861     if (type->type == RPC_FC_BOGUS_STRUCT)
1862     {
1863         /* On the sizing pass, type->ptrdesc may be zero, but it's ok as
1864            nothing is written to file yet.  On the actual writing pass,
1865            this will have been updated.  */
1866         unsigned int absoff = type->ptrdesc ? type->ptrdesc : *tfsoff;
1867         short reloff = absoff - *tfsoff;
1868         print_file(file, 2, "NdrFcShort(0x%hx),\t/* Offset= %hd (%u) */\n",
1869                    reloff, reloff, absoff);
1870         *tfsoff += 2;
1871     }
1872     else if ((type->type == RPC_FC_PSTRUCT) ||
1873              (type->type == RPC_FC_CPSTRUCT) ||
1874              (type->type == RPC_FC_CVSTRUCT && has_pointers))
1875     {
1876         print_file(file, 2, "0x%x, /* FC_PP */\n", RPC_FC_PP);
1877         print_file(file, 2, "0x%x, /* FC_PAD */\n", RPC_FC_PAD);
1878         *tfsoff += 2;
1879         write_pointer_description(file, type, tfsoff);
1880         print_file(file, 2, "0x%x, /* FC_END */\n", RPC_FC_END);
1881         *tfsoff += 1;
1882     }
1883
1884     write_struct_members(file, type, &corroff, tfsoff);
1885
1886     if (type->type == RPC_FC_BOGUS_STRUCT)
1887     {
1888         const var_list_t *fs = type->fields_or_args;
1889         const var_t *f;
1890
1891         type->ptrdesc = *tfsoff;
1892         if (fs) LIST_FOR_EACH_ENTRY(f, fs, const var_t, entry)
1893         {
1894             type_t *ft = f->type;
1895             if (is_ptr(ft))
1896             {
1897                 if (is_string_type(f->attrs, ft))
1898                     write_string_tfs(file, f->attrs, ft, f->name, tfsoff);
1899                 else
1900                     write_pointer_tfs(file, ft, tfsoff);
1901             }
1902             else if (!ft->declarray && is_conformant_array(ft))
1903             {
1904                 unsigned int absoff = ft->typestring_offset;
1905                 short reloff = absoff - (*tfsoff + 2);
1906                 int ptr_type = get_attrv(f->attrs, ATTR_POINTERTYPE);
1907                 /* FIXME: We need to store pointer attributes for arrays
1908                    so we don't lose pointer_default info.  */
1909                 if (ptr_type == 0)
1910                     ptr_type = RPC_FC_UP;
1911                 print_file(file, 0, "/* %d */\n", *tfsoff);
1912                 print_file(file, 2, "0x%x, 0x0,\t/* %s */\n", ptr_type,
1913                            string_of_type(ptr_type));
1914                 print_file(file, 2, "NdrFcShort(0x%hx),\t/* Offset= %hd (%u) */\n",
1915                            reloff, reloff, absoff);
1916                 *tfsoff += 4;
1917             }
1918         }
1919         if (type->ptrdesc == *tfsoff)
1920             type->ptrdesc = 0;
1921     }
1922
1923     current_structure = save_current_structure;
1924     return start_offset;
1925 }
1926
1927 static size_t write_pointer_only_tfs(FILE *file, const attr_list_t *attrs, int pointer_type,
1928                                      unsigned char flags, size_t offset,
1929                                      unsigned int *typeformat_offset)
1930 {
1931     size_t start_offset = *typeformat_offset;
1932     short reloff = offset - (*typeformat_offset + 2);
1933     int in_attr, out_attr;
1934     in_attr = is_attr(attrs, ATTR_IN);
1935     out_attr = is_attr(attrs, ATTR_OUT);
1936     if (!in_attr && !out_attr) in_attr = 1;
1937
1938     if (out_attr && !in_attr && pointer_type == RPC_FC_RP)
1939         flags |= 0x04;
1940
1941     print_file(file, 2, "0x%x, 0x%x,\t\t/* %s",
1942                pointer_type,
1943                flags,
1944                string_of_type(pointer_type));
1945     if (file)
1946     {
1947         if (flags & 0x04)
1948             fprintf(file, " [allocated_on_stack]");
1949         if (flags & 0x10)
1950             fprintf(file, " [pointer_deref]");
1951         fprintf(file, " */\n");
1952     }
1953
1954     print_file(file, 2, "NdrFcShort(0x%x),\t/* %d */\n", reloff, offset);
1955     *typeformat_offset += 4;
1956
1957     return start_offset;
1958 }
1959
1960 static void write_branch_type(FILE *file, const type_t *t, unsigned int *tfsoff)
1961 {
1962     if (t == NULL)
1963     {
1964         print_file(file, 2, "NdrFcShort(0x0),\t/* No type */\n");
1965     }
1966     else if (is_base_type(t->type))
1967     {
1968         print_file(file, 2, "NdrFcShort(0x80%02x),\t/* Simple arm type: %s */\n",
1969                    t->type, string_of_type(t->type));
1970     }
1971     else if (t->typestring_offset)
1972     {
1973         short reloff = t->typestring_offset - *tfsoff;
1974         print_file(file, 2, "NdrFcShort(0x%x),\t/* Offset= %d (%d) */\n",
1975                    reloff, reloff, t->typestring_offset);
1976     }
1977     else
1978         error("write_branch_type: type unimplemented (0x%x)\n", t->type);
1979
1980     *tfsoff += 2;
1981 }
1982
1983 static size_t write_union_tfs(FILE *file, type_t *type, unsigned int *tfsoff)
1984 {
1985     unsigned int align = 0;
1986     unsigned int start_offset;
1987     size_t size = type_memsize(type, &align);
1988     var_list_t *fields;
1989     size_t nbranch = 0;
1990     type_t *deftype = NULL;
1991     short nodeftype = 0xffff;
1992     var_t *f;
1993
1994     guard_rec(type);
1995
1996     if (type->type == RPC_FC_ENCAPSULATED_UNION)
1997     {
1998         const var_t *uv = LIST_ENTRY(list_tail(type->fields_or_args), const var_t, entry);
1999         fields = uv->type->fields_or_args;
2000     }
2001     else
2002         fields = type->fields_or_args;
2003
2004     if (fields) LIST_FOR_EACH_ENTRY(f, fields, var_t, entry)
2005     {
2006         expr_list_t *cases = get_attrp(f->attrs, ATTR_CASE);
2007         if (cases)
2008             nbranch += list_count(cases);
2009         if (f->type)
2010             write_embedded_types(file, f->attrs, f->type, f->name, TRUE, tfsoff);
2011     }
2012
2013     start_offset = *tfsoff;
2014     update_tfsoff(type, start_offset, file);
2015     print_start_tfs_comment(file, type, start_offset);
2016     if (type->type == RPC_FC_ENCAPSULATED_UNION)
2017     {
2018         const var_t *sv = LIST_ENTRY(list_head(type->fields_or_args), const var_t, entry);
2019         const type_t *st = sv->type;
2020
2021         switch (st->type)
2022         {
2023         case RPC_FC_CHAR:
2024         case RPC_FC_SMALL:
2025         case RPC_FC_USMALL:
2026         case RPC_FC_SHORT:
2027         case RPC_FC_USHORT:
2028         case RPC_FC_LONG:
2029         case RPC_FC_ULONG:
2030         case RPC_FC_ENUM16:
2031         case RPC_FC_ENUM32:
2032             print_file(file, 2, "0x%x,\t/* %s */\n", type->type, string_of_type(type->type));
2033             print_file(file, 2, "0x%x,\t/* Switch type= %s */\n",
2034                        0x40 | st->type, string_of_type(st->type));
2035             *tfsoff += 2;
2036             break;
2037         default:
2038             error("union switch type must be an integer, char, or enum\n");
2039         }
2040     }
2041     else if (is_attr(type->attrs, ATTR_SWITCHTYPE))
2042     {
2043         static const expr_t dummy_expr;  /* FIXME */
2044         const type_t *st = get_attrp(type->attrs, ATTR_SWITCHTYPE);
2045
2046         switch (st->type)
2047         {
2048         case RPC_FC_CHAR:
2049         case RPC_FC_SMALL:
2050         case RPC_FC_USMALL:
2051         case RPC_FC_SHORT:
2052         case RPC_FC_USHORT:
2053         case RPC_FC_LONG:
2054         case RPC_FC_ULONG:
2055         case RPC_FC_ENUM16:
2056         case RPC_FC_ENUM32:
2057             print_file(file, 2, "0x%x,\t/* %s */\n", type->type, string_of_type(type->type));
2058             print_file(file, 2, "0x%x,\t/* Switch type= %s */\n",
2059                        st->type, string_of_type(st->type));
2060             *tfsoff += 2;
2061             break;
2062         default:
2063             error("union switch type must be an integer, char, or enum\n");
2064         }
2065
2066         *tfsoff += write_conf_or_var_desc(file, NULL, *tfsoff, st, &dummy_expr );
2067     }
2068
2069     print_file(file, 2, "NdrFcShort(0x%x),\t/* %d */\n", size, size);
2070     print_file(file, 2, "NdrFcShort(0x%x),\t/* %d */\n", nbranch, nbranch);
2071     *tfsoff += 4;
2072
2073     if (fields) LIST_FOR_EACH_ENTRY(f, fields, var_t, entry)
2074     {
2075         type_t *ft = f->type;
2076         expr_list_t *cases = get_attrp(f->attrs, ATTR_CASE);
2077         int deflt = is_attr(f->attrs, ATTR_DEFAULT);
2078         expr_t *c;
2079
2080         if (cases == NULL && !deflt)
2081             error("union field %s with neither case nor default attribute\n", f->name);
2082
2083         if (cases) LIST_FOR_EACH_ENTRY(c, cases, expr_t, entry)
2084         {
2085             /* MIDL doesn't check for duplicate cases, even though that seems
2086                like a reasonable thing to do, it just dumps them to the TFS
2087                like we're going to do here.  */
2088             print_file(file, 2, "NdrFcLong(0x%x),\t/* %d */\n", c->cval, c->cval);
2089             *tfsoff += 4;
2090             write_branch_type(file, ft, tfsoff);
2091         }
2092
2093         /* MIDL allows multiple default branches, even though that seems
2094            illogical, it just chooses the last one, which is what we will
2095            do.  */
2096         if (deflt)
2097         {
2098             deftype = ft;
2099             nodeftype = 0;
2100         }
2101     }
2102
2103     if (deftype)
2104     {
2105         write_branch_type(file, deftype, tfsoff);
2106     }
2107     else
2108     {
2109         print_file(file, 2, "NdrFcShort(0x%x),\n", nodeftype);
2110         *tfsoff += 2;
2111     }
2112
2113     return start_offset;
2114 }
2115
2116 static size_t write_ip_tfs(FILE *file, const attr_list_t *attrs, type_t *type,
2117                            unsigned int *typeformat_offset)
2118 {
2119     size_t i;
2120     size_t start_offset = *typeformat_offset;
2121     expr_t *iid = get_attrp(attrs, ATTR_IIDIS);
2122
2123     if (iid)
2124     {
2125         print_file(file, 2, "0x2f,  /* FC_IP */\n");
2126         print_file(file, 2, "0x5c,  /* FC_PAD */\n");
2127         *typeformat_offset
2128             += write_conf_or_var_desc(file, NULL, 0, type, iid) + 2;
2129     }
2130     else
2131     {
2132         const type_t *base = is_ptr(type) ? type->ref : type;
2133         const UUID *uuid = get_attrp(base->attrs, ATTR_UUID);
2134
2135         if (! uuid)
2136             error("%s: interface %s missing UUID\n", __FUNCTION__, base->name);
2137
2138         update_tfsoff(type, start_offset, file);
2139         print_start_tfs_comment(file, type, start_offset);
2140         print_file(file, 2, "0x2f,\t/* FC_IP */\n");
2141         print_file(file, 2, "0x5a,\t/* FC_CONSTANT_IID */\n");
2142         print_file(file, 2, "NdrFcLong(0x%08lx),\n", uuid->Data1);
2143         print_file(file, 2, "NdrFcShort(0x%04x),\n", uuid->Data2);
2144         print_file(file, 2, "NdrFcShort(0x%04x),\n", uuid->Data3);
2145         for (i = 0; i < 8; ++i)
2146             print_file(file, 2, "0x%02x,\n", uuid->Data4[i]);
2147
2148         if (file)
2149             fprintf(file, "\n");
2150
2151         *typeformat_offset += 18;
2152     }
2153     return start_offset;
2154 }
2155
2156 static size_t write_contexthandle_tfs(FILE *file, const type_t *type,
2157                                       const var_t *var,
2158                                       unsigned int *typeformat_offset)
2159 {
2160     size_t start_offset = *typeformat_offset;
2161     unsigned char flags = 0;
2162
2163     if (is_attr(current_iface->attrs, ATTR_STRICTCONTEXTHANDLE))
2164         flags |= NDR_STRICT_CONTEXT_HANDLE;
2165
2166     if (is_ptr(type))
2167         flags |= 0x80;
2168     if (is_attr(var->attrs, ATTR_IN))
2169     {
2170         flags |= 0x40;
2171         if (!is_attr(var->attrs, ATTR_OUT))
2172             flags |= NDR_CONTEXT_HANDLE_CANNOT_BE_NULL;
2173     }
2174     if (is_attr(var->attrs, ATTR_OUT))
2175         flags |= 0x20;
2176
2177     WRITE_FCTYPE(file, FC_BIND_CONTEXT, *typeformat_offset);
2178     print_file(file, 2, "0x%x,\t/* Context flags: ", flags);
2179     /* return and can't be null values overlap */
2180     if (((flags & 0x21) != 0x21) && (flags & NDR_CONTEXT_HANDLE_CANNOT_BE_NULL))
2181         print_file(file, 0, "can't be null, ");
2182     if (flags & NDR_CONTEXT_HANDLE_SERIALIZE)
2183         print_file(file, 0, "serialize, ");
2184     if (flags & NDR_CONTEXT_HANDLE_NO_SERIALIZE)
2185         print_file(file, 0, "no serialize, ");
2186     if (flags & NDR_STRICT_CONTEXT_HANDLE)
2187         print_file(file, 0, "strict, ");
2188     if ((flags & 0x21) == 0x20)
2189         print_file(file, 0, "out, ");
2190     if ((flags & 0x21) == 0x21)
2191         print_file(file, 0, "return, ");
2192     if (flags & 0x40)
2193         print_file(file, 0, "in, ");
2194     if (flags & 0x80)
2195         print_file(file, 0, "via ptr, ");
2196     print_file(file, 0, "*/\n");
2197     print_file(file, 2, "0, /* FIXME: rundown routine index*/\n");
2198     print_file(file, 2, "0, /* FIXME: param num */\n");
2199     *typeformat_offset += 4;
2200
2201     return start_offset;
2202 }
2203
2204 static size_t write_typeformatstring_var(FILE *file, int indent, const func_t *func,
2205                                          type_t *type, const var_t *var,
2206                                          unsigned int *typeformat_offset)
2207 {
2208     size_t offset;
2209
2210     if (is_context_handle(type))
2211         return write_contexthandle_tfs(file, type, var, typeformat_offset);
2212
2213     if (is_user_type(type))
2214     {
2215         write_user_tfs(file, type, typeformat_offset);
2216         return type->typestring_offset;
2217     }
2218
2219     if (is_string_type(var->attrs, type))
2220         return write_string_tfs(file, var->attrs, type, var->name, typeformat_offset);
2221
2222     if (is_array(type))
2223     {
2224         int ptr_type;
2225         size_t off;
2226         off = write_array_tfs(file, var->attrs, type, var->name, typeformat_offset);
2227         ptr_type = get_attrv(var->attrs, ATTR_POINTERTYPE);
2228         /* Top level pointers to conformant arrays may be handled specially
2229            since we can bypass the pointer, but if the array is buried
2230            beneath another pointer (e.g., "[size_is(,n)] int **p" then we
2231            always need to write the pointer.  */
2232         if (!ptr_type && var->type != type)
2233           /* FIXME:  This should use pointer_default, but the information
2234              isn't kept around for arrays.  */
2235           ptr_type = RPC_FC_UP;
2236         if (ptr_type && ptr_type != RPC_FC_RP)
2237         {
2238             unsigned int absoff = type->typestring_offset;
2239             short reloff = absoff - (*typeformat_offset + 2);
2240             off = *typeformat_offset;
2241             print_file(file, 0, "/* %d */\n", off);
2242             print_file(file, 2, "0x%x, 0x0,\t/* %s */\n", ptr_type,
2243                        string_of_type(ptr_type));
2244             print_file(file, 2, "NdrFcShort(0x%hx),\t/* Offset= %hd (%u) */\n",
2245                        reloff, reloff, absoff);
2246             *typeformat_offset += 4;
2247         }
2248         return off;
2249     }
2250
2251     if (!is_ptr(type))
2252     {
2253         /* basic types don't need a type format string */
2254         if (is_base_type(type->type))
2255             return 0;
2256
2257         switch (type->type)
2258         {
2259         case RPC_FC_STRUCT:
2260         case RPC_FC_PSTRUCT:
2261         case RPC_FC_CSTRUCT:
2262         case RPC_FC_CPSTRUCT:
2263         case RPC_FC_CVSTRUCT:
2264         case RPC_FC_BOGUS_STRUCT:
2265             return write_struct_tfs(file, type, var->name, typeformat_offset);
2266         case RPC_FC_ENCAPSULATED_UNION:
2267         case RPC_FC_NON_ENCAPSULATED_UNION:
2268             return write_union_tfs(file, type, typeformat_offset);
2269         case RPC_FC_IGNORE:
2270         case RPC_FC_BIND_PRIMITIVE:
2271             /* nothing to do */
2272             return 0;
2273         default:
2274             error("write_typeformatstring_var: Unsupported type 0x%x for variable %s\n", type->type, var->name);
2275         }
2276     }
2277     else if (last_ptr(type))
2278     {
2279         size_t start_offset = *typeformat_offset;
2280         int in_attr = is_attr(var->attrs, ATTR_IN);
2281         int out_attr = is_attr(var->attrs, ATTR_OUT);
2282         const type_t *base = type->ref;
2283
2284         if (base->type == RPC_FC_IP
2285             || (base->type == 0
2286                 && is_attr(var->attrs, ATTR_IIDIS)))
2287         {
2288             return write_ip_tfs(file, var->attrs, type, typeformat_offset);
2289         }
2290
2291         /* special case for pointers to base types */
2292         if (is_base_type(base->type))
2293         {
2294             print_file(file, indent, "0x%x, 0x%x,    /* %s %s[simple_pointer] */\n",
2295                        type->type, (!in_attr && out_attr) ? 0x0C : 0x08,
2296                        string_of_type(type->type),
2297                        (!in_attr && out_attr) ? "[allocated_on_stack] " : "");
2298             print_file(file, indent, "0x%02x,    /* %s */\n", base->type, string_of_type(base->type));
2299             print_file(file, indent, "0x5c,          /* FC_PAD */\n");
2300             *typeformat_offset += 4;
2301             return start_offset;
2302         }
2303     }
2304
2305     assert(is_ptr(type));
2306
2307     offset = write_typeformatstring_var(file, indent, func, type->ref, var, typeformat_offset);
2308     if (file)
2309         fprintf(file, "/* %2u */\n", *typeformat_offset);
2310     return write_pointer_only_tfs(file, var->attrs, type->type,
2311                            !last_ptr(type) ? 0x10 : 0,
2312                            offset, typeformat_offset);
2313 }
2314
2315 static int write_embedded_types(FILE *file, const attr_list_t *attrs, type_t *type,
2316                                 const char *name, int write_ptr, unsigned int *tfsoff)
2317 {
2318     int retmask = 0;
2319
2320     if (is_user_type(type))
2321     {
2322         write_user_tfs(file, type, tfsoff);
2323     }
2324     else if (is_string_type(attrs, type))
2325     {
2326         write_string_tfs(file, attrs, type, name, tfsoff);
2327     }
2328     else if (is_ptr(type))
2329     {
2330         type_t *ref = type->ref;
2331
2332         if (ref->type == RPC_FC_IP
2333             || (ref->type == 0
2334                 && is_attr(attrs, ATTR_IIDIS)))
2335         {
2336             write_ip_tfs(file, attrs, type, tfsoff);
2337         }
2338         else
2339         {
2340             if (!processed(ref) && !is_base_type(ref->type))
2341                 retmask |= write_embedded_types(file, NULL, ref, name, TRUE, tfsoff);
2342
2343             if (write_ptr)
2344                 write_pointer_tfs(file, type, tfsoff);
2345
2346             retmask |= 1;
2347         }
2348     }
2349     else if (type->declarray && is_conformant_array(type))
2350         ;    /* conformant arrays and strings are handled specially */
2351     else if (is_array(type))
2352     {
2353         write_array_tfs(file, attrs, type, name, tfsoff);
2354         if (is_conformant_array(type))
2355             retmask |= 1;
2356     }
2357     else if (is_struct(type->type))
2358     {
2359         if (!processed(type))
2360             write_struct_tfs(file, type, name, tfsoff);
2361     }
2362     else if (is_union(type->type))
2363     {
2364         if (!processed(type))
2365             write_union_tfs(file, type, tfsoff);
2366     }
2367     else if (!is_base_type(type->type))
2368         error("write_embedded_types: unknown embedded type for %s (0x%x)\n",
2369               name, type->type);
2370
2371     return retmask;
2372 }
2373
2374 static size_t process_tfs_stmts(FILE *file, const statement_list_t *stmts,
2375                                 type_pred_t pred, unsigned int *typeformat_offset)
2376 {
2377     const var_t *var;
2378     const statement_t *stmt;
2379
2380     if (stmts) LIST_FOR_EACH_ENTRY( stmt, stmts, const statement_t, entry )
2381     {
2382         const type_t *iface;
2383         if (stmt->type == STMT_LIBRARY)
2384         {
2385             process_tfs_stmts(file, stmt->u.lib->stmts, pred, typeformat_offset);
2386             continue;
2387         }
2388         else if (stmt->type != STMT_TYPE || stmt->u.type->type != RPC_FC_IP)
2389             continue;
2390
2391         iface = stmt->u.type;
2392         if (!pred(iface))
2393             continue;
2394
2395         if (iface->funcs)
2396         {
2397             const func_t *func;
2398             current_iface = iface;
2399             LIST_FOR_EACH_ENTRY( func, iface->funcs, const func_t, entry )
2400             {
2401                 if (is_local(func->def->attrs)) continue;
2402
2403                 if (!is_void(get_func_return_type(func)))
2404                 {
2405                     var_t v = *func->def;
2406                     v.type = get_func_return_type(func);
2407                     update_tfsoff(get_func_return_type(func),
2408                                   write_typeformatstring_var(
2409                                       file, 2, NULL, get_func_return_type(func),
2410                                       &v, typeformat_offset),
2411                                   file);
2412                 }
2413
2414                 current_func = func;
2415                 if (func->args)
2416                     LIST_FOR_EACH_ENTRY( var, func->args, const var_t, entry )
2417                         update_tfsoff(
2418                             var->type,
2419                             write_typeformatstring_var(
2420                                 file, 2, func, var->type, var,
2421                                 typeformat_offset),
2422                             file);
2423             }
2424         }
2425     }
2426
2427     return *typeformat_offset + 1;
2428 }
2429
2430 static size_t process_tfs(FILE *file, const statement_list_t *stmts, type_pred_t pred)
2431 {
2432     unsigned int typeformat_offset = 2;
2433
2434     return process_tfs_stmts(file, stmts, pred, &typeformat_offset);
2435 }
2436
2437
2438 void write_typeformatstring(FILE *file, const statement_list_t *stmts, type_pred_t pred)
2439 {
2440     int indent = 0;
2441
2442     print_file(file, indent, "static const MIDL_TYPE_FORMAT_STRING __MIDL_TypeFormatString =\n");
2443     print_file(file, indent, "{\n");
2444     indent++;
2445     print_file(file, indent, "0,\n");
2446     print_file(file, indent, "{\n");
2447     indent++;
2448     print_file(file, indent, "NdrFcShort(0x0),\n");
2449
2450     set_all_tfswrite(TRUE);
2451     process_tfs(file, stmts, pred);
2452
2453     print_file(file, indent, "0x0\n");
2454     indent--;
2455     print_file(file, indent, "}\n");
2456     indent--;
2457     print_file(file, indent, "};\n");
2458     print_file(file, indent, "\n");
2459 }
2460
2461 static unsigned int get_required_buffer_size_type(
2462     const type_t *type, const char *name, unsigned int *alignment)
2463 {
2464     const char *uname;
2465     const type_t *utype;
2466
2467     *alignment = 0;
2468     if ((utype = get_user_type(type, &uname)))
2469     {
2470         return get_required_buffer_size_type(utype, uname, alignment);
2471     }
2472     else
2473     {
2474         switch (type->type)
2475         {
2476         case RPC_FC_BYTE:
2477         case RPC_FC_CHAR:
2478         case RPC_FC_USMALL:
2479         case RPC_FC_SMALL:
2480             *alignment = 4;
2481             return 1;
2482
2483         case RPC_FC_WCHAR:
2484         case RPC_FC_USHORT:
2485         case RPC_FC_SHORT:
2486         case RPC_FC_ENUM16:
2487             *alignment = 4;
2488             return 2;
2489
2490         case RPC_FC_ULONG:
2491         case RPC_FC_LONG:
2492         case RPC_FC_ENUM32:
2493         case RPC_FC_FLOAT:
2494         case RPC_FC_ERROR_STATUS_T:
2495             *alignment = 4;
2496             return 4;
2497
2498         case RPC_FC_HYPER:
2499         case RPC_FC_DOUBLE:
2500             *alignment = 8;
2501             return 8;
2502
2503         case RPC_FC_IGNORE:
2504         case RPC_FC_BIND_PRIMITIVE:
2505             return 0;
2506
2507         case RPC_FC_STRUCT:
2508         case RPC_FC_PSTRUCT:
2509         {
2510             size_t size = 0;
2511             const var_t *field;
2512             if (!type->fields_or_args) return 0;
2513             LIST_FOR_EACH_ENTRY( field, type->fields_or_args, const var_t, entry )
2514             {
2515                 unsigned int alignment;
2516                 size += get_required_buffer_size_type(field->type, field->name,
2517                                                       &alignment);
2518             }
2519             return size;
2520         }
2521
2522         case RPC_FC_RP:
2523             return
2524                 is_base_type( type->ref->type ) || type->ref->type == RPC_FC_STRUCT
2525                 ? get_required_buffer_size_type( type->ref, name, alignment )
2526                 : 0;
2527
2528         case RPC_FC_SMFARRAY:
2529         case RPC_FC_LGFARRAY:
2530             return type->dim * get_required_buffer_size_type(type->ref, name, alignment);
2531
2532         default:
2533             return 0;
2534         }
2535     }
2536 }
2537
2538 static unsigned int get_required_buffer_size(const var_t *var, unsigned int *alignment, enum pass pass)
2539 {
2540     int in_attr = is_attr(var->attrs, ATTR_IN);
2541     int out_attr = is_attr(var->attrs, ATTR_OUT);
2542     const type_t *t;
2543
2544     if (!in_attr && !out_attr)
2545         in_attr = 1;
2546
2547     *alignment = 0;
2548
2549     for (t = var->type; is_ptr(t); t = t->ref)
2550         if (is_attr(t->attrs, ATTR_CONTEXTHANDLE))
2551         {
2552             *alignment = 4;
2553             return 20;
2554         }
2555
2556     if (pass == PASS_OUT)
2557     {
2558         if (out_attr && is_ptr(var->type))
2559         {
2560             type_t *type = var->type;
2561
2562             if (type->type == RPC_FC_STRUCT)
2563             {
2564                 const var_t *field;
2565                 unsigned int size = 36;
2566
2567                 if (!type->fields_or_args) return size;
2568                 LIST_FOR_EACH_ENTRY( field, type->fields_or_args, const var_t, entry )
2569                 {
2570                     unsigned int align;
2571                     size += get_required_buffer_size_type(
2572                         field->type, field->name, &align);
2573                 }
2574                 return size;
2575             }
2576         }
2577         return 0;
2578     }
2579     else
2580     {
2581         if ((!out_attr || in_attr) && !var->type->size_is
2582             && !is_attr(var->attrs, ATTR_STRING) && !var->type->declarray)
2583         {
2584             if (is_ptr(var->type))
2585             {
2586                 type_t *type = var->type;
2587
2588                 if (is_base_type(type->type))
2589                 {
2590                     return 25;
2591                 }
2592                 else if (type->type == RPC_FC_STRUCT)
2593                 {
2594                     unsigned int size = 36;
2595                     const var_t *field;
2596
2597                     if (!type->fields_or_args) return size;
2598                     LIST_FOR_EACH_ENTRY( field, type->fields_or_args, const var_t, entry )
2599                     {
2600                         unsigned int align;
2601                         size += get_required_buffer_size_type(
2602                             field->type, field->name, &align);
2603                     }
2604                     return size;
2605                 }
2606             }
2607         }
2608
2609         return get_required_buffer_size_type(var->type, var->name, alignment);
2610     }
2611 }
2612
2613 static unsigned int get_function_buffer_size( const func_t *func, enum pass pass )
2614 {
2615     const var_t *var;
2616     unsigned int total_size = 0, alignment;
2617
2618     if (func->args)
2619     {
2620         LIST_FOR_EACH_ENTRY( var, func->args, const var_t, entry )
2621         {
2622             total_size += get_required_buffer_size(var, &alignment, pass);
2623             total_size += alignment;
2624         }
2625     }
2626
2627     if (pass == PASS_OUT && !is_void(get_func_return_type(func)))
2628     {
2629         var_t v = *func->def;
2630         v.type = get_func_return_type(func);
2631         total_size += get_required_buffer_size(&v, &alignment, PASS_RETURN);
2632         total_size += alignment;
2633     }
2634     return total_size;
2635 }
2636
2637 static void print_phase_function(FILE *file, int indent, const char *type,
2638                                  const char *local_var_prefix, enum remoting_phase phase,
2639                                  const var_t *var, unsigned int type_offset)
2640 {
2641     const char *function;
2642     switch (phase)
2643     {
2644     case PHASE_BUFFERSIZE:
2645         function = "BufferSize";
2646         break;
2647     case PHASE_MARSHAL:
2648         function = "Marshall";
2649         break;
2650     case PHASE_UNMARSHAL:
2651         function = "Unmarshall";
2652         break;
2653     case PHASE_FREE:
2654         function = "Free";
2655         break;
2656     default:
2657         assert(0);
2658         return;
2659     }
2660
2661     print_file(file, indent, "Ndr%s%s(\n", type, function);
2662     indent++;
2663     print_file(file, indent, "&__frame->_StubMsg,\n");
2664     print_file(file, indent, "%s%s%s%s%s,\n",
2665                (phase == PHASE_UNMARSHAL) ? "(unsigned char **)" : "(unsigned char *)",
2666                (phase == PHASE_UNMARSHAL || decl_indirect(var->type)) ? "&" : "",
2667                local_var_prefix,
2668                (phase == PHASE_UNMARSHAL && decl_indirect(var->type)) ? "_p_" : "",
2669                var->name);
2670     print_file(file, indent, "(PFORMAT_STRING)&__MIDL_TypeFormatString.Format[%d]%s\n",
2671                type_offset, (phase == PHASE_UNMARSHAL) ? "," : ");");
2672     if (phase == PHASE_UNMARSHAL)
2673         print_file(file, indent, "0);\n");
2674     indent--;
2675 }
2676
2677 void print_phase_basetype(FILE *file, int indent, const char *local_var_prefix,
2678                           enum remoting_phase phase, enum pass pass, const var_t *var,
2679                           const char *varname)
2680 {
2681     type_t *type = var->type;
2682     unsigned int size;
2683     unsigned int alignment = 0;
2684     unsigned char rtype;
2685
2686     /* no work to do for other phases, buffer sizing is done elsewhere */
2687     if (phase != PHASE_MARSHAL && phase != PHASE_UNMARSHAL)
2688         return;
2689
2690     rtype = is_ptr(type) ? type->ref->type : type->type;
2691
2692     switch (rtype)
2693     {
2694         case RPC_FC_BYTE:
2695         case RPC_FC_CHAR:
2696         case RPC_FC_SMALL:
2697         case RPC_FC_USMALL:
2698             size = 1;
2699             alignment = 1;
2700             break;
2701
2702         case RPC_FC_WCHAR:
2703         case RPC_FC_USHORT:
2704         case RPC_FC_SHORT:
2705         case RPC_FC_ENUM16:
2706             size = 2;
2707             alignment = 2;
2708             break;
2709
2710         case RPC_FC_ULONG:
2711         case RPC_FC_LONG:
2712         case RPC_FC_ENUM32:
2713         case RPC_FC_FLOAT:
2714         case RPC_FC_ERROR_STATUS_T:
2715             size = 4;
2716             alignment = 4;
2717             break;
2718
2719         case RPC_FC_HYPER:
2720         case RPC_FC_DOUBLE:
2721             size = 8;
2722             alignment = 8;
2723             break;
2724
2725         case RPC_FC_IGNORE:
2726         case RPC_FC_BIND_PRIMITIVE:
2727             /* no marshalling needed */
2728             return;
2729
2730         default:
2731             error("print_phase_basetype: Unsupported type: %s (0x%02x, ptr_level: 0)\n", var->name, rtype);
2732             size = 0;
2733     }
2734
2735     if (phase == PHASE_MARSHAL)
2736         print_file(file, indent, "MIDL_memset(__frame->_StubMsg.Buffer, 0, (0x%x - (long)__frame->_StubMsg.Buffer) & 0x%x);\n", alignment, alignment - 1);
2737     print_file(file, indent, "__frame->_StubMsg.Buffer = (unsigned char *)(((long)__frame->_StubMsg.Buffer + %u) & ~0x%x);\n",
2738                 alignment - 1, alignment - 1);
2739
2740     if (phase == PHASE_MARSHAL)
2741     {
2742         print_file(file, indent, "*(");
2743         write_type_decl(file, is_ptr(type) ? type->ref : type, NULL);
2744         if (is_ptr(type))
2745             fprintf(file, " *)__frame->_StubMsg.Buffer = *");
2746         else
2747             fprintf(file, " *)__frame->_StubMsg.Buffer = ");
2748         fprintf(file, "%s%s", local_var_prefix, varname);
2749         fprintf(file, ";\n");
2750     }
2751     else if (phase == PHASE_UNMARSHAL)
2752     {
2753         print_file(file, indent, "if (__frame->_StubMsg.Buffer + sizeof(");
2754         write_type_decl(file, is_ptr(type) ? type->ref : type, NULL);
2755         fprintf(file, ") > __frame->_StubMsg.BufferEnd)\n");
2756         print_file(file, indent, "{\n");
2757         print_file(file, indent + 1, "RpcRaiseException(RPC_X_BAD_STUB_DATA);\n");
2758         print_file(file, indent, "}\n");
2759         if (pass == PASS_IN || pass == PASS_RETURN)
2760             print_file(file, indent, "");
2761         else
2762             print_file(file, indent, "*");
2763         fprintf(file, "%s%s", local_var_prefix, varname);
2764         if (pass == PASS_IN && is_ptr(type))
2765             fprintf(file, " = (");
2766         else
2767             fprintf(file, " = *(");
2768         write_type_decl(file, is_ptr(type) ? type->ref : type, NULL);
2769         fprintf(file, " *)__frame->_StubMsg.Buffer;\n");
2770     }
2771
2772     print_file(file, indent, "__frame->_StubMsg.Buffer += sizeof(");
2773     write_type_decl(file, var->type, NULL);
2774     fprintf(file, ");\n");
2775 }
2776
2777 /* returns whether the MaxCount, Offset or ActualCount members need to be
2778  * filled in for the specified phase */
2779 static inline int is_conformance_needed_for_phase(enum remoting_phase phase)
2780 {
2781     return (phase != PHASE_UNMARSHAL);
2782 }
2783
2784 expr_t *get_size_is_expr(const type_t *t, const char *name)
2785 {
2786     expr_t *x = NULL;
2787
2788     for ( ; is_ptr(t) || is_array(t); t = t->ref)
2789         if (t->size_is)
2790         {
2791             if (!x)
2792                 x = t->size_is;
2793             else
2794                 error("%s: multidimensional conformant"
2795                       " arrays not supported at the top level\n",
2796                       name);
2797         }
2798
2799     return x;
2800 }
2801
2802 static void write_parameter_conf_or_var_exprs(FILE *file, int indent, const char *local_var_prefix,
2803                                               enum remoting_phase phase, const var_t *var)
2804 {
2805     const type_t *type = var->type;
2806     /* get fundamental type for the argument */
2807     for (;;)
2808     {
2809         if (is_attr(type->attrs, ATTR_WIREMARSHAL))
2810             break;
2811         else if (is_attr(type->attrs, ATTR_CONTEXTHANDLE))
2812             break;
2813         else if (is_array(type) || is_string_type(var->attrs, type))
2814         {
2815             if (is_conformance_needed_for_phase(phase))
2816             {
2817                 if (type->size_is)
2818                 {
2819                     print_file(file, indent, "__frame->_StubMsg.MaxCount = (unsigned long)");
2820                     write_expr(file, type->size_is, 1, 1, NULL, NULL, local_var_prefix);
2821                     fprintf(file, ";\n\n");
2822                 }
2823                 if (type->length_is)
2824                 {
2825                     print_file(file, indent, "__frame->_StubMsg.Offset = (unsigned long)0;\n"); /* FIXME */
2826                     print_file(file, indent, "__frame->_StubMsg.ActualCount = (unsigned long)");
2827                     write_expr(file, type->length_is, 1, 1, NULL, NULL, local_var_prefix);
2828                     fprintf(file, ";\n\n");
2829                 }
2830             }
2831             break;
2832         }
2833         else if (type->type == RPC_FC_NON_ENCAPSULATED_UNION)
2834         {
2835             if (is_conformance_needed_for_phase(phase))
2836             {
2837                 print_file(file, indent, "__frame->_StubMsg.MaxCount = (unsigned long)");
2838                 write_expr(file, get_attrp(var->attrs, ATTR_SWITCHIS), 1, 1, NULL, NULL, local_var_prefix);
2839                 fprintf(file, ";\n\n");
2840             }
2841             break;
2842         }
2843         else if (type->type == RPC_FC_IP)
2844         {
2845             expr_t *iid;
2846
2847             if (is_conformance_needed_for_phase(phase) && (iid = get_attrp( var->attrs, ATTR_IIDIS )))
2848             {
2849                 print_file( file, indent, "__frame->_StubMsg.MaxCount = (unsigned long) " );
2850                 write_expr( file, iid, 1, 1, NULL, NULL, local_var_prefix );
2851                 fprintf( file, ";\n\n" );
2852             }
2853             break;
2854         }
2855         else if (is_ptr(type))
2856             type = type->ref;
2857         else
2858             break;
2859     }
2860 }
2861
2862 static void write_remoting_arg(FILE *file, int indent, const func_t *func, const char *local_var_prefix,
2863                                enum pass pass, enum remoting_phase phase, const var_t *var)
2864 {
2865     int in_attr, out_attr, pointer_type;
2866     const type_t *type = var->type;
2867     unsigned char rtype;
2868     size_t start_offset = type->typestring_offset;
2869
2870     pointer_type = get_attrv(var->attrs, ATTR_POINTERTYPE);
2871     if (!pointer_type)
2872         pointer_type = RPC_FC_RP;
2873
2874     in_attr = is_attr(var->attrs, ATTR_IN);
2875     out_attr = is_attr(var->attrs, ATTR_OUT);
2876     if (!in_attr && !out_attr)
2877         in_attr = 1;
2878
2879     if (phase != PHASE_FREE)
2880         switch (pass)
2881         {
2882         case PASS_IN:
2883             if (!in_attr) return;
2884             break;
2885         case PASS_OUT:
2886             if (!out_attr) return;
2887             break;
2888         case PASS_RETURN:
2889             break;
2890         }
2891
2892     write_parameter_conf_or_var_exprs(file, indent, local_var_prefix, phase, var);
2893     rtype = type->type;
2894
2895     if (is_context_handle(type))
2896     {
2897         if (phase == PHASE_MARSHAL)
2898         {
2899             if (pass == PASS_IN)
2900             {
2901                 /* if the context_handle attribute appears in the chain of types
2902                  * without pointers being followed, then the context handle must
2903                  * be direct, otherwise it is a pointer */
2904                 int is_ch_ptr = is_aliaschain_attr(type, ATTR_CONTEXTHANDLE) ? FALSE : TRUE;
2905                 print_file(file, indent, "NdrClientContextMarshall(\n");
2906                 print_file(file, indent + 1, "&__frame->_StubMsg,\n");
2907                 print_file(file, indent + 1, "(NDR_CCONTEXT)%s%s%s,\n", is_ch_ptr ? "*" : "", local_var_prefix, var->name);
2908                 print_file(file, indent + 1, "%s);\n", in_attr && out_attr ? "1" : "0");
2909             }
2910             else
2911             {
2912                 print_file(file, indent, "NdrServerContextNewMarshall(\n");
2913                 print_file(file, indent + 1, "&__frame->_StubMsg,\n");
2914                 print_file(file, indent + 1, "(NDR_SCONTEXT)%s%s,\n", local_var_prefix, var->name);
2915                 print_file(file, indent + 1, "(NDR_RUNDOWN)%s_rundown,\n", get_context_handle_type_name(var->type));
2916                 print_file(file, indent + 1, "(PFORMAT_STRING)&__MIDL_TypeFormatString.Format[%d]);\n", start_offset);
2917             }
2918         }
2919         else if (phase == PHASE_UNMARSHAL)
2920         {
2921             if (pass == PASS_OUT)
2922             {
2923                 if (!in_attr)
2924                     print_file(file, indent, "*%s%s = 0;\n", local_var_prefix, var->name);
2925                 print_file(file, indent, "NdrClientContextUnmarshall(\n");
2926                 print_file(file, indent + 1, "&__frame->_StubMsg,\n");
2927                 print_file(file, indent + 1, "(NDR_CCONTEXT *)%s%s,\n", local_var_prefix, var->name);
2928                 print_file(file, indent + 1, "_Handle);\n");
2929             }
2930             else
2931             {
2932                 print_file(file, indent, "%s%s = NdrServerContextNewUnmarshall(\n", local_var_prefix, var->name);
2933                 print_file(file, indent + 1, "&__frame->_StubMsg,\n");
2934                 print_file(file, indent + 1, "(PFORMAT_STRING)&__MIDL_TypeFormatString.Format[%d]);\n", start_offset);
2935             }
2936         }
2937     }
2938     else if (is_user_type(var->type))
2939     {
2940         print_phase_function(file, indent, "UserMarshal", local_var_prefix, phase, var, start_offset);
2941     }
2942     else if (is_string_type(var->attrs, var->type))
2943     {
2944         if (is_array(type) && !is_conformant_array(type))
2945             print_phase_function(file, indent, "NonConformantString", local_var_prefix,
2946                                  phase, var, start_offset);
2947         else
2948         {
2949             if (phase == PHASE_FREE || pass == PASS_RETURN || pointer_type == RPC_FC_UP)
2950                 print_phase_function(file, indent, "Pointer", local_var_prefix, phase, var,
2951                                      start_offset - (type->size_is ? 4 : 2));
2952             else
2953                 print_phase_function(file, indent, "ConformantString", local_var_prefix,
2954                                      phase, var, start_offset);
2955         }
2956     }
2957     else if (is_array(type))
2958     {
2959         unsigned char tc = type->type;
2960         const char *array_type = "FixedArray";
2961
2962         /* We already have the size_is expression since it's at the
2963            top level, but do checks for multidimensional conformant
2964            arrays.  When we handle them, we'll need to extend this
2965            function to return a list, and then we'll actually use
2966            the return value.  */
2967         get_size_is_expr(type, var->name);
2968
2969         if (tc == RPC_FC_SMVARRAY || tc == RPC_FC_LGVARRAY)
2970         {
2971             array_type = "VaryingArray";
2972         }
2973         else if (tc == RPC_FC_CARRAY)
2974         {
2975             array_type = "ConformantArray";
2976         }
2977         else if (tc == RPC_FC_CVARRAY || tc == RPC_FC_BOGUS_ARRAY)
2978         {
2979             array_type = (tc == RPC_FC_BOGUS_ARRAY
2980                           ? "ComplexArray"
2981                           : "ConformantVaryingArray");
2982         }
2983
2984         if (pointer_type != RPC_FC_RP) array_type = "Pointer";
2985         print_phase_function(file, indent, array_type, local_var_prefix, phase, var, start_offset);
2986         if (phase == PHASE_FREE && pointer_type == RPC_FC_RP)
2987         {
2988             /* these are all unmarshalled by allocating memory */
2989             if (type->type == RPC_FC_BOGUS_ARRAY ||
2990                 type->type == RPC_FC_CVARRAY ||
2991                 ((type->type == RPC_FC_SMVARRAY || type->type == RPC_FC_LGVARRAY) && in_attr) ||
2992                 (type->type == RPC_FC_CARRAY && !in_attr))
2993             {
2994                 print_file(file, indent, "if (%s%s)\n", local_var_prefix, var->name);
2995                 indent++;
2996                 print_file(file, indent, "__frame->_StubMsg.pfnFree(%s%s);\n", local_var_prefix, var->name);
2997             }
2998         }
2999     }
3000     else if (!is_ptr(var->type) && is_base_type(rtype))
3001     {
3002         if (phase != PHASE_FREE)
3003             print_phase_basetype(file, indent, local_var_prefix, phase, pass, var, var->name);
3004     }
3005     else if (!is_ptr(var->type))
3006     {
3007         switch (rtype)
3008         {
3009         case RPC_FC_STRUCT:
3010         case RPC_FC_PSTRUCT:
3011             print_phase_function(file, indent, "SimpleStruct", local_var_prefix, phase, var, start_offset);
3012             break;
3013         case RPC_FC_CSTRUCT:
3014         case RPC_FC_CPSTRUCT:
3015             print_phase_function(file, indent, "ConformantStruct", local_var_prefix, phase, var, start_offset);
3016             break;
3017         case RPC_FC_CVSTRUCT:
3018             print_phase_function(file, indent, "ConformantVaryingStruct", local_var_prefix, phase, var, start_offset);
3019             break;
3020         case RPC_FC_BOGUS_STRUCT:
3021             print_phase_function(file, indent, "ComplexStruct", local_var_prefix, phase, var, start_offset);
3022             break;
3023         case RPC_FC_RP:
3024             if (is_base_type( var->type->ref->type ))
3025             {
3026                 print_phase_basetype(file, indent, local_var_prefix, phase, pass, var, var->name);
3027             }
3028             else if (var->type->ref->type == RPC_FC_STRUCT)
3029             {
3030                 if (phase != PHASE_BUFFERSIZE && phase != PHASE_FREE)
3031                     print_phase_function(file, indent, local_var_prefix, "SimpleStruct", phase, var, start_offset + 4);
3032             }
3033             else
3034             {
3035                 expr_t *iid;
3036                 if ((iid = get_attrp( var->attrs, ATTR_IIDIS )))
3037                 {
3038                     print_file( file, indent, "__frame->_StubMsg.MaxCount = (unsigned long) " );
3039                     write_expr( file, iid, 1, 1, NULL, NULL, local_var_prefix );
3040                     fprintf( file, ";\n\n" );
3041                 }
3042                 print_phase_function(file, indent, "Pointer", local_var_prefix, phase, var, start_offset);
3043             }
3044             break;
3045         default:
3046             error("write_remoting_arguments: Unsupported type: %s (0x%02x)\n", var->name, rtype);
3047         }
3048     }
3049     else
3050     {
3051         if (last_ptr(var->type) && (pointer_type == RPC_FC_RP) && is_base_type(rtype))
3052         {
3053             if (phase != PHASE_FREE)
3054                 print_phase_basetype(file, indent, local_var_prefix, phase, pass, var, var->name);
3055         }
3056         else if (last_ptr(var->type) && (pointer_type == RPC_FC_RP) && (rtype == RPC_FC_STRUCT))
3057         {
3058             if (phase != PHASE_BUFFERSIZE && phase != PHASE_FREE)
3059                 print_phase_function(file, indent, "SimpleStruct", local_var_prefix, phase, var, start_offset + 4);
3060         }
3061         else
3062         {
3063             if (var->type->ref->type == RPC_FC_IP)
3064                 print_phase_function(file, indent, "InterfacePointer", local_var_prefix, phase, var, start_offset);
3065             else
3066                 print_phase_function(file, indent, "Pointer", local_var_prefix, phase, var, start_offset);
3067         }
3068     }
3069     fprintf(file, "\n");
3070 }
3071
3072 void write_remoting_arguments(FILE *file, int indent, const func_t *func, const char *local_var_prefix,
3073                               enum pass pass, enum remoting_phase phase)
3074 {
3075     if (phase == PHASE_BUFFERSIZE && pass != PASS_RETURN)
3076     {
3077         unsigned int size = get_function_buffer_size( func, pass );
3078         print_file(file, indent, "__frame->_StubMsg.BufferLength = %u;\n", size);
3079     }
3080
3081     if (pass == PASS_RETURN)
3082     {
3083         var_t var;
3084         var = *func->def;
3085         var.type = get_func_return_type(func);
3086         var.name = xstrdup( "_RetVal" );
3087         write_remoting_arg( file, indent, func, local_var_prefix, pass, phase, &var );
3088         free( var.name );
3089     }
3090     else
3091     {
3092         const var_t *var;
3093         if (!func->args)
3094             return;
3095         LIST_FOR_EACH_ENTRY( var, func->args, const var_t, entry )
3096             write_remoting_arg( file, indent, func, local_var_prefix, pass, phase, var );
3097     }
3098 }
3099
3100
3101 size_t get_size_procformatstring_type(const char *name, const type_t *type, const attr_list_t *attrs)
3102 {
3103     return write_procformatstring_type(NULL, 0, name, type, attrs, FALSE);
3104 }
3105
3106
3107 size_t get_size_procformatstring_func(const func_t *func)
3108 {
3109     const var_t *var;
3110     size_t size = 0;
3111
3112     /* argument list size */
3113     if (func->args)
3114         LIST_FOR_EACH_ENTRY( var, func->args, const var_t, entry )
3115             size += get_size_procformatstring_type(var->name, var->type, var->attrs);
3116
3117     /* return value size */
3118     if (is_void(get_func_return_type(func)))
3119         size += 2; /* FC_END and FC_PAD */
3120     else
3121         size += get_size_procformatstring_type("return value", get_func_return_type(func), NULL);
3122
3123     return size;
3124 }
3125
3126 size_t get_size_procformatstring(const statement_list_t *stmts, type_pred_t pred)
3127 {
3128     const statement_t *stmt;
3129     size_t size = 1;
3130     const func_t *func;
3131
3132     if (stmts) LIST_FOR_EACH_ENTRY( stmt, stmts, const statement_t, entry )
3133     {
3134         const type_t *iface;
3135         if (stmt->type == STMT_LIBRARY)
3136         {
3137             size += get_size_procformatstring(stmt->u.lib->stmts, pred) - 1;
3138             continue;
3139         }
3140         else if (stmt->type != STMT_TYPE && stmt->u.type->type != RPC_FC_IP)
3141             continue;
3142
3143         iface = stmt->u.type;
3144         if (!pred(iface))
3145             continue;
3146
3147         if (iface->funcs)
3148             LIST_FOR_EACH_ENTRY( func, iface->funcs, const func_t, entry )
3149                 if (!is_local(func->def->attrs))
3150                     size += get_size_procformatstring_func( func );
3151     }
3152     return size;
3153 }
3154
3155 size_t get_size_typeformatstring(const statement_list_t *stmts, type_pred_t pred)
3156 {
3157     set_all_tfswrite(FALSE);
3158     return process_tfs(NULL, stmts, pred);
3159 }
3160
3161 void declare_stub_args( FILE *file, int indent, const func_t *func )
3162 {
3163     int in_attr, out_attr;
3164     int i = 0;
3165     const var_t *var;
3166
3167     /* declare return value '_RetVal' */
3168     if (!is_void(get_func_return_type(func)))
3169     {
3170         print_file(file, indent, "");
3171         write_type_decl_left(file, get_func_return_type(func));
3172         fprintf(file, " _RetVal;\n");
3173     }
3174
3175     if (!func->args)
3176         return;
3177
3178     LIST_FOR_EACH_ENTRY( var, func->args, const var_t, entry )
3179     {
3180         int is_string = is_attr(var->attrs, ATTR_STRING);
3181
3182         in_attr = is_attr(var->attrs, ATTR_IN);
3183         out_attr = is_attr(var->attrs, ATTR_OUT);
3184         if (!out_attr && !in_attr)
3185             in_attr = 1;
3186
3187         if (is_context_handle(var->type))
3188             print_file(file, indent, "NDR_SCONTEXT %s;\n", var->name);
3189         else
3190         {
3191             if (!in_attr && !var->type->size_is && !is_string)
3192             {
3193                 print_file(file, indent, "");
3194                 write_type_decl(file, var->type->declarray ? var->type : var->type->ref,
3195                                 "_W%u", i++);
3196                 fprintf(file, ";\n");
3197             }
3198
3199             print_file(file, indent, "");
3200             write_type_decl_left(file, var->type);
3201             fprintf(file, " ");
3202             if (var->type->declarray) {
3203                 fprintf(file, "(*%s)", var->name);
3204             } else
3205                 fprintf(file, "%s", var->name);
3206             write_type_right(file, var->type, FALSE);
3207             fprintf(file, ";\n");
3208
3209             if (decl_indirect(var->type))
3210                 print_file(file, indent, "void *_p_%s;\n", var->name);
3211         }
3212     }
3213 }
3214
3215
3216 void assign_stub_out_args( FILE *file, int indent, const func_t *func, const char *local_var_prefix )
3217 {
3218     int in_attr, out_attr;
3219     int i = 0, sep = 0;
3220     const var_t *var;
3221
3222     if (!func->args)
3223         return;
3224
3225     LIST_FOR_EACH_ENTRY( var, func->args, const var_t, entry )
3226     {
3227         int is_string = is_attr(var->attrs, ATTR_STRING);
3228         in_attr = is_attr(var->attrs, ATTR_IN);
3229         out_attr = is_attr(var->attrs, ATTR_OUT);
3230         if (!out_attr && !in_attr)
3231             in_attr = 1;
3232
3233         if (!in_attr)
3234         {
3235             print_file(file, indent, "%s%s", local_var_prefix, var->name);
3236
3237             if (is_context_handle(var->type))
3238             {
3239                 fprintf(file, " = NdrContextHandleInitialize(\n");
3240                 print_file(file, indent + 1, "&__frame->_StubMsg,\n");
3241                 print_file(file, indent + 1, "(PFORMAT_STRING)&__MIDL_TypeFormatString.Format[%d]);\n",
3242                            var->type->typestring_offset);
3243             }
3244             else if (var->type->size_is)
3245             {
3246                 unsigned int size, align = 0;
3247                 type_t *type = var->type;
3248
3249                 fprintf(file, " = NdrAllocate(&__frame->_StubMsg, ");
3250                 for ( ; type->size_is ; type = type->ref)
3251                 {
3252                     write_expr(file, type->size_is, TRUE, TRUE, NULL, NULL, local_var_prefix);
3253                     fprintf(file, " * ");
3254                 }
3255                 size = type_memsize(type, &align);
3256                 fprintf(file, "%u);\n", size);
3257             }
3258             else if (!is_string)
3259             {
3260                 fprintf(file, " = &%s_W%u;\n", local_var_prefix, i);
3261                 if (is_ptr(var->type) && !last_ptr(var->type))
3262                     print_file(file, indent, "%s_W%u = 0;\n", local_var_prefix, i);
3263                 i++;
3264             }
3265
3266             sep = 1;
3267         }
3268     }
3269     if (sep)
3270         fprintf(file, "\n");
3271 }
3272
3273
3274 int write_expr_eval_routines(FILE *file, const char *iface)
3275 {
3276     static const char *var_name = "pS";
3277     static const char *var_name_expr = "pS->";
3278     int result = 0;
3279     struct expr_eval_routine *eval;
3280     unsigned short callback_offset = 0;
3281
3282     LIST_FOR_EACH_ENTRY(eval, &expr_eval_routines, struct expr_eval_routine, entry)
3283     {
3284         const char *name = eval->structure->name;
3285         result = 1;
3286
3287         print_file(file, 0, "static void __RPC_USER %s_%sExprEval_%04u(PMIDL_STUB_MESSAGE pStubMsg)\n",
3288                    iface, name, callback_offset);
3289         print_file(file, 0, "{\n");
3290         print_file (file, 1, "%s *%s = (%s *)(pStubMsg->StackTop - %u);\n",
3291                     name, var_name, name, eval->baseoff);
3292         print_file(file, 1, "pStubMsg->Offset = 0;\n"); /* FIXME */
3293         print_file(file, 1, "pStubMsg->MaxCount = (unsigned long)");
3294         write_expr(file, eval->expr, 1, 1, var_name_expr, eval->structure, "");
3295         fprintf(file, ";\n");
3296         print_file(file, 0, "}\n\n");
3297         callback_offset++;
3298     }
3299     return result;
3300 }
3301
3302 void write_expr_eval_routine_list(FILE *file, const char *iface)
3303 {
3304     struct expr_eval_routine *eval;
3305     struct expr_eval_routine *cursor;
3306     unsigned short callback_offset = 0;
3307
3308     fprintf(file, "static const EXPR_EVAL ExprEvalRoutines[] =\n");
3309     fprintf(file, "{\n");
3310
3311     LIST_FOR_EACH_ENTRY_SAFE(eval, cursor, &expr_eval_routines, struct expr_eval_routine, entry)
3312     {
3313         const char *name = eval->structure->name;
3314         print_file(file, 1, "%s_%sExprEval_%04u,\n", iface, name, callback_offset);
3315         callback_offset++;
3316         list_remove(&eval->entry);
3317         free(eval);
3318     }
3319
3320     fprintf(file, "};\n\n");
3321 }
3322
3323 void write_user_quad_list(FILE *file)
3324 {
3325     user_type_t *ut;
3326
3327     if (list_empty(&user_type_list))
3328         return;
3329
3330     fprintf(file, "static const USER_MARSHAL_ROUTINE_QUADRUPLE UserMarshalRoutines[] =\n");
3331     fprintf(file, "{\n");
3332     LIST_FOR_EACH_ENTRY(ut, &user_type_list, user_type_t, entry)
3333     {
3334         const char *sep = &ut->entry == list_tail(&user_type_list) ? "" : ",";
3335         print_file(file, 1, "{\n");
3336         print_file(file, 2, "(USER_MARSHAL_SIZING_ROUTINE)%s_UserSize,\n", ut->name);
3337         print_file(file, 2, "(USER_MARSHAL_MARSHALLING_ROUTINE)%s_UserMarshal,\n", ut->name);
3338         print_file(file, 2, "(USER_MARSHAL_UNMARSHALLING_ROUTINE)%s_UserUnmarshal,\n", ut->name);
3339         print_file(file, 2, "(USER_MARSHAL_FREEING_ROUTINE)%s_UserFree\n", ut->name);
3340         print_file(file, 1, "}%s\n", sep);
3341     }
3342     fprintf(file, "};\n\n");
3343 }
3344
3345 void write_endpoints( FILE *f, const char *prefix, const str_list_t *list )
3346 {
3347     const struct str_list_entry_t *endpoint;
3348     const char *p;
3349
3350     /* this should be an array of RPC_PROTSEQ_ENDPOINT but we want const strings */
3351     print_file( f, 0, "static const unsigned char * %s__RpcProtseqEndpoint[][2] =\n{\n", prefix );
3352     LIST_FOR_EACH_ENTRY( endpoint, list, const struct str_list_entry_t, entry )
3353     {
3354         print_file( f, 1, "{ (const unsigned char *)\"" );
3355         for (p = endpoint->str; *p && *p != ':'; p++)
3356         {
3357             if (*p == '"' || *p == '\\') fputc( '\\', f );
3358             fputc( *p, f );
3359         }
3360         if (!*p) goto error;
3361         if (p[1] != '[') goto error;
3362
3363         fprintf( f, "\", (const unsigned char *)\"" );
3364         for (p += 2; *p && *p != ']'; p++)
3365         {
3366             if (*p == '"' || *p == '\\') fputc( '\\', f );
3367             fputc( *p, f );
3368         }
3369         if (*p != ']') goto error;
3370         fprintf( f, "\" },\n" );
3371     }
3372     print_file( f, 0, "};\n\n" );
3373     return;
3374
3375 error:
3376     error("Invalid endpoint syntax '%s'\n", endpoint->str);
3377 }
3378
3379 void write_exceptions( FILE *file )
3380 {
3381     fprintf( file, "#ifndef USE_COMPILER_EXCEPTIONS\n");
3382     fprintf( file, "\n");
3383     fprintf( file, "#include \"wine/exception.h\"\n");
3384     fprintf( file, "#undef RpcTryExcept\n");
3385     fprintf( file, "#undef RpcExcept\n");
3386     fprintf( file, "#undef RpcEndExcept\n");
3387     fprintf( file, "#undef RpcTryFinally\n");
3388     fprintf( file, "#undef RpcFinally\n");
3389     fprintf( file, "#undef RpcEndFinally\n");
3390     fprintf( file, "#undef RpcExceptionCode\n");
3391     fprintf( file, "\n");
3392     fprintf( file, "struct __exception_frame;\n");
3393     fprintf( file, "typedef int (*__filter_func)(EXCEPTION_RECORD *, struct __exception_frame *);\n");
3394     fprintf( file, "typedef void (*__finally_func)(struct __exception_frame *);\n");
3395     fprintf( file, "\n");
3396     fprintf( file, "#define __DECL_EXCEPTION_FRAME \\\n");
3397     fprintf( file, "    EXCEPTION_REGISTRATION_RECORD frame; \\\n");
3398     fprintf( file, "    __filter_func                 filter; \\\n");
3399     fprintf( file, "    __finally_func                finally; \\\n");
3400     fprintf( file, "    sigjmp_buf                    jmp; \\\n");
3401     fprintf( file, "    DWORD                         code; \\\n");
3402     fprintf( file, "    unsigned char                 filter_level; \\\n");
3403     fprintf( file, "    unsigned char                 finally_level;\n");
3404     fprintf( file, "\n");
3405     fprintf( file, "struct __exception_frame\n{\n");
3406     fprintf( file, "    __DECL_EXCEPTION_FRAME;\n");
3407     fprintf( file, "};\n");
3408     fprintf( file, "\n");
3409     fprintf( file, "static DWORD __widl_exception_handler( EXCEPTION_RECORD *record,\n");
3410     fprintf( file, "                                       EXCEPTION_REGISTRATION_RECORD *frame,\n");
3411     fprintf( file, "                                       CONTEXT *context,\n");
3412     fprintf( file, "                                       EXCEPTION_REGISTRATION_RECORD **pdispatcher )\n");
3413     fprintf( file, "{\n");
3414     fprintf( file, "    struct __exception_frame *exc_frame = (struct __exception_frame *)frame;\n");
3415     fprintf( file, "\n");
3416     fprintf( file, "    if (record->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND | EH_NESTED_CALL))\n");
3417     fprintf( file, "    {\n" );
3418     fprintf( file, "        if (exc_frame->finally_level && (record->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND)))\n");
3419     fprintf( file, "            exc_frame->finally( exc_frame );\n");
3420     fprintf( file, "        return ExceptionContinueSearch;\n");
3421     fprintf( file, "    }\n" );
3422     fprintf( file, "    exc_frame->code = record->ExceptionCode;\n");
3423     fprintf( file, "    if (exc_frame->filter_level && exc_frame->filter( record, exc_frame ) == EXCEPTION_EXECUTE_HANDLER)\n" );
3424     fprintf( file, "    {\n");
3425     fprintf( file, "        __wine_rtl_unwind( frame, record );\n");
3426     fprintf( file, "        if (exc_frame->finally_level > exc_frame->filter_level)\n" );
3427     fprintf( file, "        {\n");
3428     fprintf( file, "            exc_frame->finally( exc_frame );\n");
3429     fprintf( file, "            __wine_pop_frame( frame );\n");
3430     fprintf( file, "        }\n");
3431     fprintf( file, "        exc_frame->filter_level = 0;\n");
3432     fprintf( file, "        siglongjmp( exc_frame->jmp, 1 );\n");
3433     fprintf( file, "    }\n");
3434     fprintf( file, "    return ExceptionContinueSearch;\n");
3435     fprintf( file, "}\n");
3436     fprintf( file, "\n");
3437     fprintf( file, "#define RpcTryExcept \\\n");
3438     fprintf( file, "    if (!sigsetjmp( __frame->jmp, 0 )) \\\n");
3439     fprintf( file, "    { \\\n");
3440     fprintf( file, "        if (!__frame->finally_level) \\\n" );
3441     fprintf( file, "            __wine_push_frame( &__frame->frame ); \\\n");
3442     fprintf( file, "        __frame->filter_level = __frame->finally_level + 1;\n" );
3443     fprintf( file, "\n");
3444     fprintf( file, "#define RpcExcept(expr) \\\n");
3445     fprintf( file, "        if (!__frame->finally_level) \\\n" );
3446     fprintf( file, "            __wine_pop_frame( &__frame->frame ); \\\n");
3447     fprintf( file, "        __frame->filter_level = 0; \\\n" );
3448     fprintf( file, "    } \\\n");
3449     fprintf( file, "    else \\\n");
3450     fprintf( file, "\n");
3451     fprintf( file, "#define RpcEndExcept\n");
3452     fprintf( file, "\n");
3453     fprintf( file, "#define RpcExceptionCode() (__frame->code)\n");
3454     fprintf( file, "\n");
3455     fprintf( file, "#define RpcTryFinally \\\n");
3456     fprintf( file, "    if (!__frame->filter_level) \\\n");
3457     fprintf( file, "        __wine_push_frame( &__frame->frame ); \\\n");
3458     fprintf( file, "    __frame->finally_level = __frame->filter_level + 1;\n");
3459     fprintf( file, "\n");
3460     fprintf( file, "#define RpcFinally \\\n");
3461     fprintf( file, "    if (!__frame->filter_level) \\\n");
3462     fprintf( file, "        __wine_pop_frame( &__frame->frame ); \\\n");
3463     fprintf( file, "    __frame->finally_level = 0;\n");
3464     fprintf( file, "\n");
3465     fprintf( file, "#define RpcEndFinally\n");
3466     fprintf( file, "\n");
3467     fprintf( file, "#define RpcExceptionInit(filter_func,finally_func) \\\n");
3468     fprintf( file, "    do { \\\n");
3469     fprintf( file, "        __frame->frame.Handler = __widl_exception_handler; \\\n");
3470     fprintf( file, "        __frame->filter = (__filter_func)(filter_func); \\\n" );
3471     fprintf( file, "        __frame->finally = (__finally_func)(finally_func); \\\n");
3472     fprintf( file, "        __frame->filter_level = 0; \\\n");
3473     fprintf( file, "        __frame->finally_level = 0; \\\n");
3474     fprintf( file, "    } while (0)\n");
3475     fprintf( file, "\n");
3476     fprintf( file, "#else /* USE_COMPILER_EXCEPTIONS */\n");
3477     fprintf( file, "\n");
3478     fprintf( file, "#define RpcExceptionInit(filter_func,finally_func) do {} while(0)\n");
3479     fprintf( file, "#define __DECL_EXCEPTION_FRAME\n");
3480     fprintf( file, "\n");
3481     fprintf( file, "#endif /* USE_COMPILER_EXCEPTIONS */\n");
3482 }