s4:torture: Adapt KDC canon test to Heimdal upstream changes
[samba.git] / third_party / heimdal / lib / asn1 / gen_template.c
1 /*
2  * Copyright (c) 1997 - 2005 Kungliga Tekniska Högskolan
3  * (Royal Institute of Technology, Stockholm, Sweden).
4  * All rights reserved.
5  *
6  * Portions Copyright (c) 2009 - 2010 Apple Inc. All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * 3. Neither the name of the Institute nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35
36 /*
37  * Currently we generate C source code defining constant arrays of structures
38  * containing a sort of a "byte-coded" template of an ASN.1 compiler to be
39  * interpreted at run-time.
40  */
41
42 #include "gen_locl.h"
43 #include <vis.h>
44 #include <vis-extras.h>
45
46 static const char *symbol_name(const char *, const Type *);
47 static void generate_template_type(const char *, const char **, const char *, const char *, const char *,
48                                    Type *, int, int, int);
49
50 static const char *
51 ttype_symbol(const char *basename, const Type *t)
52 {
53     return t->symbol->gen_name;
54 }
55
56 static const char *
57 integer_symbol(const char *basename, const Type *t)
58 {
59     if (t->members)
60         /*
61          * XXX enum foo -- compute the size either from inspecting the members
62          * and applying the ABI's rules for enum size, OR infer the field
63          * size from a template by using the offsetof field.  The latter is
64          * hard to do though.
65          */
66         return "int";
67     else if (t->range == NULL)
68         return "heim_integer";
69     else if (t->range->min < 0 &&
70              (t->range->min < INT_MIN || t->range->max > INT_MAX))
71         return "int64_t";
72     else if (t->range->min < 0)
73         return "int";
74     else if (t->range->max > UINT_MAX)
75         return "uint64_t";
76     else
77         return "unsigned";
78 }
79
80 static const char *
81 boolean_symbol(const char *basename, const Type *t)
82 {
83     return "int";
84 }
85
86
87 static const char *
88 octetstring_symbol(const char *basename, const Type *t)
89 {
90     return "heim_octet_string";
91 }
92
93 static const char *
94 sequence_symbol(const char *basename, const Type *t)
95 {
96     return basename;
97 }
98
99 static const char *
100 time_symbol(const char *basename, const Type *t)
101 {
102     return "time_t";
103 }
104
105 static const char *
106 tag_symbol(const char *basename, const Type *t)
107 {
108     return symbol_name(basename, t->subtype);
109 }
110
111 static const char *
112 generalstring_symbol(const char *basename, const Type *t)
113 {
114     return "heim_general_string";
115 }
116
117 static const char *
118 printablestring_symbol(const char *basename, const Type *t)
119 {
120     return "heim_printable_string";
121 }
122
123 static const char *
124 ia5string_symbol(const char *basename, const Type *t)
125 {
126     return "heim_ia5_string";
127 }
128
129 static const char *
130 teletexstring_symbol(const char *basename, const Type *t)
131 {
132     return "heim_general_string";
133 }
134
135 static const char *
136 visiblestring_symbol(const char *basename, const Type *t)
137 {
138     return "heim_visible_string";
139 }
140
141 static const char *
142 utf8string_symbol(const char *basename, const Type *t)
143 {
144     return "heim_utf8_string";
145 }
146
147 static const char *
148 bmpstring_symbol(const char *basename, const Type *t)
149 {
150     return "heim_bmp_string";
151 }
152
153 static const char *
154 universalstring_symbol(const char *basename, const Type *t)
155 {
156     return "heim_universal_string";
157 }
158
159 static const char *
160 oid_symbol(const char *basename, const Type *t)
161 {
162     return "heim_oid";
163 }
164
165 static const char *
166 bitstring_symbol(const char *basename, const Type *t)
167 {
168     if (t->members)
169         return basename;
170     return "heim_bit_string";
171 }
172
173
174
175 /* Keep this sorted by `type' so we can just index this by type */
176 const struct {
177     enum typetype type;
178     const char *(*symbol_name)(const char *, const Type *);
179     int is_struct;
180 } types[] =  {
181     { TBitString, bitstring_symbol, 0 },
182     { TBoolean, boolean_symbol, 0 },
183     { TChoice, sequence_symbol, 1 },
184     { TEnumerated, integer_symbol, 0 },
185     { TGeneralString, generalstring_symbol, 0 },
186     { TTeletexString, teletexstring_symbol, 0 },
187     { TGeneralizedTime, time_symbol, 0 },
188     { TIA5String, ia5string_symbol, 0 },
189     { TInteger, integer_symbol, 0 },
190     { TNull, integer_symbol, 1 },
191     { TOID, oid_symbol, 0 },
192     { TOctetString, octetstring_symbol, 0 },
193     { TPrintableString, printablestring_symbol, 0 },
194     { TSequence, sequence_symbol, 1 },
195     { TSequenceOf, tag_symbol, 1 },
196     { TSet, sequence_symbol, 1 },
197     { TSetOf, tag_symbol, 1 },
198     { TTag, tag_symbol, 1 },
199     { TType, ttype_symbol, 1 },
200     { TUTCTime, time_symbol, 0 },
201     { TUTF8String, utf8string_symbol, 0 },
202     { TBMPString, bmpstring_symbol, 0 },
203     { TUniversalString, universalstring_symbol, 0 },
204     { TVisibleString, visiblestring_symbol, 0 },
205 };
206
207 static FILE *
208 get_code_file(void)
209 {
210     if (!one_code_file)
211         return templatefile;
212     return codefile;
213 }
214
215
216 static int
217 is_supported_type_p(const Type *t)
218 {
219     return t->type >= 0 && t->type <= TVisibleString &&
220         types[t->type].type == t->type;
221 }
222
223 int
224 is_template_compat (const Symbol *s)
225 {
226     return is_supported_type_p(s->type);
227 }
228
229 static const char *
230 symbol_name(const char *basename, const Type *t)
231 {
232     if (t->type >= 0 && t->type <= TVisibleString &&
233         types[t->type].type == t->type)
234         return (types[t->type].symbol_name)(basename, t);
235     if (t->type >= 0 && t->type <= TVisibleString)
236         errx(1, "types[] is not sorted");
237     errx(1, "unknown der type: %d\n", t->type);
238     return NULL;
239 }
240
241
242 static char *
243 partial_offset(const char *basetype, const char *name, int need_offset, int isstruct)
244 {
245     char *str;
246     if (name == NULL || need_offset == 0)
247         return strdup("0");
248     if (asprintf(&str, "offsetof(%s%s, %s)", isstruct ? "struct " : "", basetype, name) < 0 || str == NULL)
249         errx(1, "malloc");
250     return str;
251 }
252
253 struct template {
254     char *line;
255     char *tt;
256     char *offset;
257     char *ptr;
258     HEIM_TAILQ_ENTRY(template) members;
259 };
260
261 HEIM_TAILQ_HEAD(templatehead, template);
262
263 struct tlist {
264     char *name;
265     char *header;
266     struct templatehead template;
267     HEIM_TAILQ_ENTRY(tlist) tmembers;
268 };
269
270 HEIM_TAILQ_HEAD(tlisthead, tlist);
271
272 static void tlist_header(struct tlist *, const char *, ...) __attribute__ ((__format__ (__printf__, 2, 3)));
273 static struct template *
274     add_line(struct templatehead *, const char *, ...) __attribute__ ((__format__ (__printf__, 2, 3)));
275 static int tlist_cmp(const struct tlist *, const struct tlist *);
276
277 static void add_line_pointer(struct templatehead *, const char *, const char *, const char *, ...)
278     __attribute__ ((__format__ (__printf__, 4, 5)));
279 static void add_line_string(struct templatehead *, const char *, const char *, const char *, ...)
280     __attribute__ ((__format__ (__printf__, 4, 5)));
281 static void add_line_pointer_reference(struct templatehead *, const char *, const char *, const char *, ...)
282     __attribute__ ((__format__ (__printf__, 4, 5)));
283
284
285 static struct tlisthead tlistmaster = HEIM_TAILQ_HEAD_INITIALIZER(tlistmaster);
286 static unsigned long numdups = 0;
287
288 static struct tlist *
289 tlist_new(const char *name)
290 {
291     struct tlist *tl = calloc(1, sizeof(*tl));
292     tl->name = strdup(name);
293     HEIM_TAILQ_INIT(&tl->template);
294     return tl;
295 }
296
297 static void
298 tlist_header(struct tlist *t, const char *fmt, ...)
299 {
300     va_list ap;
301     va_start(ap, fmt);
302     if (vasprintf(&t->header, fmt, ap) < 0 || t->header == NULL)
303         errx(1, "malloc");
304     va_end(ap);
305 }
306
307 static unsigned long
308 tlist_count(struct tlist *tl)
309 {
310     unsigned int count = 0;
311     struct template *q;
312
313     HEIM_TAILQ_FOREACH(q, &tl->template, members) {
314         count++;
315     }
316     return count;
317 }
318
319 static void
320 tlist_add(struct tlist *tl)
321 {
322     HEIM_TAILQ_INSERT_TAIL(&tlistmaster, tl, tmembers);
323 }
324
325 static void
326 tlist_print(struct tlist *tl)
327 {
328     struct template *q;
329     unsigned int i = 1;
330     FILE *f = get_code_file();
331
332     fprintf(f, "const struct asn1_template asn1_%s[] = {\n", tl->name);
333     fprintf(f, "/* 0 */ %s,\n", tl->header);
334     HEIM_TAILQ_FOREACH(q, &tl->template, members) {
335         int last = (HEIM_TAILQ_LAST(&tl->template, templatehead) == q);
336         fprintf(f, "/* %lu */ %s%s\n", (unsigned long)i++, q->line, last ? "" : ",");
337     }
338     fprintf(f, "};\n");
339 }
340
341 static struct tlist *
342 tlist_find_by_name(const char *name)
343 {
344     struct tlist *ql;
345     HEIM_TAILQ_FOREACH(ql, &tlistmaster, tmembers) {
346         if (strcmp(ql->name, name) == 0)
347             return ql;
348     }
349     return NULL;
350 }
351
352 static int
353 tlist_cmp_name(const char *tname, const char *qname)
354 {
355     struct tlist *tl = tlist_find_by_name(tname);
356     struct tlist *ql = tlist_find_by_name(qname);
357     if (tl == NULL)
358         return 1;
359     if (ql == NULL)
360         return -1;
361     return tlist_cmp(tl, ql);
362 }
363
364 static int
365 tlist_cmp(const struct tlist *tl, const struct tlist *ql)
366 {
367     int ret;
368     struct template *t, *q;
369
370     if (tl == ql)
371         return 0;
372     ret = strcmp(tl->header, ql->header);
373     if (ret != 0) return ret;
374
375     q = HEIM_TAILQ_FIRST(&ql->template);
376     HEIM_TAILQ_FOREACH(t, &tl->template, members) {
377         if (q == NULL) return 1;
378
379         if (t->ptr == NULL || q->ptr == NULL) {
380             ret = strcmp(t->line, q->line);
381             if (ret != 0) return ret;
382         } else {
383             ret = strcmp(t->tt, q->tt);
384             if (ret != 0) return ret;
385
386             ret = strcmp(t->offset, q->offset);
387             if (ret != 0) return ret;
388
389             if ((ret = strcmp(t->ptr, q->ptr)) != 0 ||
390                 (ret = tlist_cmp_name(t->ptr, q->ptr)) != 0)
391                 return ret;
392         }
393         q = HEIM_TAILQ_NEXT(q, members);
394     }
395     if (q != NULL) return -1;
396     return 0;
397 }
398
399
400 static const char *
401 tlist_find_dup(const struct tlist *tl)
402 {
403     struct tlist *ql;
404
405     HEIM_TAILQ_FOREACH(ql, &tlistmaster, tmembers) {
406         if (tlist_cmp(ql, tl) == 0) {
407             numdups++;
408             return ql->name;
409         }
410     }
411     return NULL;
412 }
413
414
415 /*
416  * Add an entry to a template.
417  */
418
419 static struct template *
420 add_line(struct templatehead *t, const char *fmt, ...)
421 {
422     struct template *q = calloc(1, sizeof(*q));
423     va_list ap;
424     va_start(ap, fmt);
425     if (vasprintf(&q->line, fmt, ap) < 0 || q->line == NULL)
426         errx(1, "malloc");
427     va_end(ap);
428     HEIM_TAILQ_INSERT_TAIL(t, q, members);
429     return q;
430 }
431
432 /*
433  * Add an entry to a template, with the pointer field being a symbol name of a
434  * template (i.e., an array, which decays to a pointer as usual in C).
435  */
436 static void
437 add_line_pointer(struct templatehead *t,
438                  const char *ptr,
439                  const char *offset,
440                  const char *ttfmt,
441                  ...)
442 {
443     struct template *q;
444     va_list ap;
445     char *tt = NULL;
446
447     va_start(ap, ttfmt);
448     if (vasprintf(&tt, ttfmt, ap) < 0 || tt == NULL)
449         errx(1, "malloc");
450     va_end(ap);
451
452     q = add_line(t, "{ %s, %s, asn1_%s }", tt, offset, ptr);
453     q->tt = tt;
454     q->offset = strdup(offset);
455     q->ptr = strdup(ptr);
456 }
457
458 /*
459  * Add an entry to a template where the pointer firled is a string literal.
460  */
461 static void
462 add_line_string(struct templatehead *t,
463                 const char *str,
464                 const char *offset,
465                 const char *ttfmt,
466                 ...)
467 {
468     struct template *q;
469     va_list ap;
470     char *tt = NULL;
471
472     va_start(ap, ttfmt);
473     if (vasprintf(&tt, ttfmt, ap) < 0 || tt == NULL)
474         errx(1, "malloc");
475     va_end(ap);
476
477     q = add_line(t, "{ %s, %s, \"%s\" }", tt, offset, str);
478     q->tt = tt;
479     q->offset = strdup(offset);
480     q->ptr = strdup(str);
481 }
482
483 /*
484  * Add an entry to a template, with the pointer field being a reference to
485  * named object of a type other than a template or other array type.
486  */
487 static void
488 add_line_pointer_reference(struct templatehead *t,
489                            const char *ptr,
490                            const char *offset,
491                            const char *ttfmt,
492                            ...)
493 {
494     struct template *q;
495     va_list ap;
496     char *tt = NULL;
497
498     va_start(ap, ttfmt);
499     if (vasprintf(&tt, ttfmt, ap) < 0 || tt == NULL)
500         errx(1, "malloc");
501     va_end(ap);
502
503     q = add_line(t, "{ %s, %s, (const void *)&asn1_%s }", tt, offset, ptr);
504     q->tt = tt;
505     q->offset = strdup(offset);
506     q->ptr = strdup(ptr);
507 }
508
509 static int
510 use_extern(const Symbol *s)
511 {
512     if (s->type == NULL)
513         return 1;
514     return 0;
515 }
516
517 static int
518 is_struct(const Type *t, int isstruct)
519 {
520     if (t->type == TType)
521         return 0;
522     if (t->type == TSequence || t->type == TSet || t->type == TChoice)
523         return 1;
524     if (t->type == TTag)
525         return is_struct(t->subtype, isstruct);
526
527     if (t->type >= 0 && t->type <= TVisibleString &&
528         types[t->type].type == t->type) {
529         if (types[t->type].is_struct == 0)
530             return 0;
531         return isstruct;
532     }
533     if (t->type >= 0 && t->type <= TVisibleString)
534         errx(1, "types[] is not sorted");
535     errx(1, "unknown der type: %d\n", t->type);
536     return isstruct;
537 }
538
539 static const Type *
540 compact_tag(const Type *t)
541 {
542     while (t->type == TTag)
543         t = t->subtype;
544     return t;
545 }
546
547 static void
548 defval(struct templatehead *temp, Member *m)
549 {
550     switch (m->defval->type) {
551     case booleanvalue:
552         add_line(temp, "{ A1_OP_DEFVAL|A1_DV_BOOLEAN, ~0, (void *)%u }",
553                  m->defval->u.booleanvalue);
554         break;
555     case nullvalue:
556         add_line(temp, "{ A1_OP_DEFVAL|A1_DV_NULL, ~0, (void *)0 }");
557         break;
558     case integervalue: {
559         const char *dv = "A1_DV_INTEGER";
560         Type *t = m->type;
561
562         for (;;) {
563             if (t->range)
564                 break;
565             if (t->type == TInteger && t->members)
566                 break;
567             if (t->type == TEnumerated)
568                 break;
569             if (t->subtype)
570                 t = t->subtype;
571             else if (t->symbol && t->symbol->type)
572                 t = t->symbol->type;
573             else
574                 errx(1, "DEFAULT values for unconstrained INTEGER members not supported");
575         }
576
577         if (t->members)
578             dv = "A1_DV_INTEGER32"; /* XXX Enum size assumptions!  No good! */
579         else if (t->range->min < 0 &&
580                  (t->range->min < INT_MIN || t->range->max > INT_MAX))
581             dv = "A1_DV_INTEGER64";
582         else if (t->range->min < 0)
583             dv = "A1_DV_INTEGER32";
584         else if (t->range->max > UINT_MAX)
585             dv = "A1_DV_INTEGER64";
586         else
587             dv = "A1_DV_INTEGER32";
588         add_line(temp, "{ A1_OP_DEFVAL|%s, ~0, (void *)%llu }",
589                  dv, (long long)m->defval->u.integervalue);
590         break;
591     }
592     case stringvalue: {
593         char *quoted;
594
595         if (rk_strasvis(&quoted, m->defval->u.stringvalue,
596                         VIS_CSTYLE | VIS_NL, "\"") < 0)
597             err(1, "Could not quote a string");
598         add_line(temp, "{ A1_OP_DEFVAL|A1_DV_UTF8STRING, ~0, (void *)\"%s\" }",
599                  quoted);
600         free(quoted);
601         break;
602     }
603     case objectidentifiervalue: {
604         struct objid *o;
605         size_t sz = sizeof("{ }");
606         char *s, *p;
607         int len;
608
609         for (o = m->defval->u.objectidentifiervalue; o != NULL; o = o->next) {
610             if ((len = snprintf(0, 0, " %d", o->value)) < 0)
611                 err(1, "Could not format integer");
612             sz += len;
613         }
614
615         if ((p = s = malloc(sz)) == NULL)
616                 err(1, "Could not allocate string");
617
618         len = snprintf(p, sz, "{");
619         sz -= len;
620         p += len;
621         for (o = m->defval->u.objectidentifiervalue; o != NULL; o = o->next) {
622             if ((len = snprintf(p, sz, " %d", o->value)) < 0 || len > sz - 1)
623                 err(1, "Could not format integer");
624             sz -= len;
625             p += len;
626         }
627         len = snprintf(p, sz, " }");
628         sz -= len;
629         p += len;
630
631         add_line(temp, "{ A1_OP_DEFVAL|A1_DV_INTEGER, ~0, (void *)\"%s\" }", s);
632         free(s);
633         break;
634     }
635     default: abort();
636     }
637 }
638
639 int
640 objid_cmp(struct objid *oida, struct objid *oidb)
641 {
642     struct objid *p;
643     size_t ai, bi, alen, blen;
644     int avals[20];
645     int bvals[20];
646     int c;
647
648     /*
649      * Our OID values are backwards here.  Comparing them is hard.
650      */
651
652     for (p = oida, alen = 0;
653          p && alen < sizeof(avals)/sizeof(avals[0]);
654          p = p->next)
655         avals[alen++] = p->value;
656     for (p = oidb, blen = 0;
657          p && blen < sizeof(bvals)/sizeof(bvals[0]);
658          p = p->next)
659         bvals[blen++] = p->value;
660     if (alen >= sizeof(avals)/sizeof(avals[0]) ||
661         blen >= sizeof(bvals)/sizeof(bvals[0]))
662         err(1, "OIDs with more components than %llu not supported",
663             (unsigned long long)sizeof(avals)/sizeof(avals[0]));
664
665     for (ai = 0, bi = 0; ai < alen && bi < blen;)
666         if ((c = avals[(alen-1)-(ai++)] - bvals[(blen-1)-(bi++)]))
667             return c;
668
669     if (ai == alen && bi == blen)
670         return 0;
671     if (ai == alen)
672         return 1;
673     return -1;
674 }
675
676 int
677 object_cmp(const void *va, const void *vb)
678 {
679     const IOSObject *oa = *(const IOSObject * const *)va;
680     const IOSObject *ob = *(const IOSObject * const *)vb;
681
682     switch (oa->typeidf->value->type) {
683     case booleanvalue:
684         return oa->typeidf->value->u.booleanvalue -
685             ob->typeidf->value->u.booleanvalue;
686     case nullvalue:
687         return 0;
688     case integervalue:
689         return oa->typeidf->value->u.integervalue -
690             ob->typeidf->value->u.integervalue;
691     case stringvalue:
692         return strcmp(oa->typeidf->value->u.stringvalue,
693             ob->typeidf->value->u.stringvalue);
694     case objectidentifiervalue: {
695         return objid_cmp(oa->typeidf->value->u.objectidentifiervalue,
696             ob->typeidf->value->u.objectidentifiervalue);
697     }
698     default:
699             abort();
700             return -1;
701     }
702 }
703
704 void
705 sort_object_set(IOSObjectSet *os,       /* Object set to sort fields of */
706                 Field *typeidfield,     /* Field to sort by */
707                 IOSObject ***objectsp,  /* Output: array of objects */
708                 size_t *nobjsp)         /* Output: count of objects */
709 {
710     IOSObject **objects;
711     IOSObject *o;
712     size_t i, nobjs = 0;
713
714     HEIM_TAILQ_FOREACH(o, os->objects, objects) {
715         ObjectField *typeidobjf = NULL;
716         ObjectField *of;
717
718         HEIM_TAILQ_FOREACH(of, o->objfields, objfields) {
719             if (strcmp(of->name, typeidfield->name) == 0)
720                 typeidobjf = of;
721         }
722         if (!typeidobjf) {
723             warnx("Ignoring incomplete object specification of %s "
724                   "(missing type ID field)",
725                   o->symbol ? o->symbol->name : "<unknown>");
726             continue;
727         }
728         o->typeidf = typeidobjf;
729         nobjs++;
730     }
731     *nobjsp = nobjs;
732
733     if ((objects = calloc(nobjs, sizeof(*objects))) == NULL)
734         err(1, "Out of memory");
735     *objectsp = objects;
736
737     i = 0;
738     HEIM_TAILQ_FOREACH(o, os->objects, objects) {
739         ObjectField *typeidobjf = NULL;
740         ObjectField *of;
741
742         HEIM_TAILQ_FOREACH(of, o->objfields, objfields) {
743             if (strcmp(of->name, typeidfield->name) == 0)
744                 typeidobjf = of;
745         }
746         if (typeidobjf)
747             objects[i++] = o;
748     }
749     qsort(objects, nobjs, sizeof(*objects), object_cmp);
750 }
751
752 static void
753 template_object_set(IOSObjectSet *os, Field *typeidfield, Field *opentypefield)
754 {
755     IOSObject **objects;
756     IOSObject *o;
757     struct tlist *tl;
758     size_t nobjs, i;
759
760     if (os->symbol->emitted_template)
761         return;
762
763     sort_object_set(os, typeidfield, &objects, &nobjs);
764
765     tl = tlist_new(os->symbol->name);
766     add_line(&tl->template, "{ A1_OP_NAME, 0, \"%s\" }", os->symbol->name);
767     for (i = 0; i < nobjs; i++) {
768         ObjectField *typeidobjf = NULL, *opentypeobjf = NULL;
769         ObjectField *of;
770         char *s = NULL;
771
772         o = objects[i];
773
774         HEIM_TAILQ_FOREACH(of, o->objfields, objfields) {
775             if (strcmp(of->name, typeidfield->name) == 0)
776                 typeidobjf = of;
777             else if (strcmp(of->name, opentypefield->name) == 0)
778                 opentypeobjf = of;
779         }
780         if (!typeidobjf)
781             continue; /* We've warned about this one already when sorting */
782         if (!opentypeobjf) {
783             warnx("Ignoring incomplete object specification of %s "
784                   "(missing open type field)",
785                   o->symbol ? o->symbol->name : "<unknown>");
786             continue;
787         }
788
789         add_line(&tl->template, "{ A1_OP_NAME, 0, \"%s\" }", o->symbol->name);
790         /*
791          * Some of this logic could stand to move into sanity checks of object
792          * definitions in asn1parse.y.
793          */
794         switch (typeidobjf->value->type) {
795         case integervalue:
796             add_line(&tl->template,
797                      "{ A1_OP_OPENTYPE_ID | A1_OTI_IS_INTEGER, 0, (void *)%lld }",
798                      (long long)typeidobjf->value->u.integervalue);
799             break;
800         case objectidentifiervalue:
801             if (asprintf(&s, "oid_%s",
802                          typeidobjf->value->s->gen_name) == -1 || !s)
803                 err(1, "Out of memory");
804             add_line_pointer_reference(&tl->template, s, "0", "A1_OP_OPENTYPE_ID");
805             free(s);
806             s = NULL;
807             break;
808         default:
809             errx(1, "Only integer and OID types supported "
810                  "for open type type-ID fields");
811         }
812
813         if (asprintf(&s, "sizeof(%s)",
814                      opentypeobjf->type->symbol->gen_name) == -1 || !s)
815             err(1, "Out of memory");
816         add_line_pointer_reference(&tl->template,
817                                    opentypeobjf->type->symbol->gen_name, s,
818                                    "A1_OP_OPENTYPE");
819         free(s);
820     }
821     free(objects);
822
823     tlist_header(tl, "{ 0, 0, ((void *)%lu) }", nobjs);
824     tlist_print(tl);
825     tlist_add(tl);
826     os->symbol->emitted_template = 1;
827 }
828
829 static void
830 template_open_type(struct templatehead *temp,
831                    const char *basetype,
832                    const Type *t,
833                    size_t typeididx,
834                    size_t opentypeidx,
835                    Field *typeidfield,
836                    Field *opentypefield,
837                    Member *m,
838                    int is_array_of_open_type)
839 {
840     char *s = NULL;
841
842     if (typeididx >= 1<<10 || opentypeidx >= 1<<10)
843         errx(1, "SET/SEQUENCE with too many members (%s)", basetype);
844
845     if (asprintf(&s, "offsetof(%s, _ioschoice_%s)",
846                  basetype, m->gen_name) == -1 || !s)
847         err(1, "Out of memory");
848
849     template_object_set(t->actual_parameter, typeidfield, opentypefield);
850     add_line_pointer(temp, t->actual_parameter->symbol->gen_name, s,
851                      /*
852                       * We always sort object sets for now as we can't import
853                       * values yet, so they must all be known.
854                       */
855                      "A1_OP_OPENTYPE_OBJSET | A1_OS_IS_SORTED |%s | (%llu << 10) | %llu",
856                      is_array_of_open_type ? "A1_OS_OT_IS_ARRAY" : "0",
857                      (unsigned long long)opentypeidx,
858                      (unsigned long long)typeididx);
859     free(s);
860 }
861
862 static void
863 template_names(struct templatehead *temp, const char *basetype, const Type *t)
864 {
865     Member *m;
866
867     add_line_string(temp, basetype, "0", "A1_OP_NAME");
868     HEIM_TAILQ_FOREACH(m, t->members, members) {
869         add_line_string(temp, m->name, "0", "A1_OP_NAME");
870     }
871 }
872
873 static void
874 template_members(struct templatehead *temp,
875                  const char *basetype,
876                  const char *name,
877                  const Type *t,
878                  int optional,
879                  int defaulted,
880                  int implicit,
881                  int isstruct,
882                  int need_offset)
883 {
884     char *poffset = NULL;
885
886     if (optional && t->type != TTag && t->type != TType)
887         errx(1, "%s...%s is optional and not a (TTag or TType)", basetype, name);
888
889     poffset = partial_offset(basetype, name, need_offset, isstruct);
890
891     switch (t->type) {
892     case TType:
893         if (use_extern(t->symbol)) {
894             add_line(temp, "{ A1_OP_TYPE_EXTERN %s%s%s, %s, &asn1_extern_%s}",
895                      optional  ? "|A1_FLAG_OPTIONAL" : "",
896                      defaulted ? "|A1_FLAG_DEFAULT" : "",
897                      implicit  ? "|A1_FLAG_IMPLICIT" : "",
898                      poffset, t->symbol->gen_name);
899         } else {
900             add_line_pointer(temp, t->symbol->gen_name, poffset,
901                              "A1_OP_TYPE %s%s%s",
902                              optional  ? "|A1_FLAG_OPTIONAL" : "",
903                              defaulted ? "|A1_FLAG_DEFAULT" : "",
904                              implicit  ? "|A1_FLAG_IMPLICIT" : "");
905
906         }
907         break;
908     case TEnumerated:
909     case TInteger: {
910         char *varname = NULL;
911         char *itype = NULL;
912
913         if (t->members)
914             itype = "IMEMBER";
915         else if (t->range == NULL)
916             itype = "HEIM_INTEGER";
917         else if (t->range->min < 0 &&
918                  (t->range->min < INT_MIN || t->range->max > INT_MAX))
919             itype = "INTEGER64";
920         else if (t->range->min < 0)
921             itype = "INTEGER";
922         else if (t->range->max > UINT_MAX)
923             itype = "UNSIGNED64";
924         else
925             itype = "UNSIGNED";
926
927         /*
928          * If `t->members' then we should generate a template for those
929          * members.
930          *
931          * We don't know the name of this field, and the type may not have a
932          * name.  If it has no name, we should generate a name for it, and if
933          * it does have a name, use it, to name a template for its members.
934          *
935          * Then we could use that in _asn1_print() to pretty-print values of
936          * enumerations.
937          */
938         if (t->members && t->symbol) {
939             struct tlist *tl;
940             Member *m;
941             size_t nmemb = 0;
942
943             if (asprintf(&varname, "%s_enum_names", t->symbol->gen_name) == -1 ||
944                 varname == NULL)
945                 err(1, "Out of memory");
946
947             tl = tlist_new(varname);
948             /*
949              * XXX We're going to assume that t->members is sorted in
950              * numerically ascending order in the module source.  We should
951              * really sort it here.
952              */
953             HEIM_TAILQ_FOREACH(m, t->members, members) {
954                 if (m->val > UINT32_MAX)
955                     continue; /* Wouldn't fit in the offset field */
956                 add_line(&tl->template,
957                          "{ A1_OP_NAME, %d, \"%s\" }", m->val, m->name);
958                 nmemb++;
959             }
960             tlist_header(tl, "{ 0, 0, ((void *)%lu) }", nmemb);
961             /* XXX Accidentally O(N^2)? */
962             if (!tlist_find_dup(tl)) {
963                 tlist_print(tl);
964                 tlist_add(tl);
965             }
966             add_line(temp, "{ A1_PARSE_T(A1T_%s), %s, asn1_%s }", itype, poffset, varname);
967         } else {
968             add_line(temp, "{ A1_PARSE_T(A1T_%s), %s, NULL }", itype, poffset);
969         }
970         break;
971     }
972     case TGeneralString:
973         add_line(temp, "{ A1_PARSE_T(A1T_GENERAL_STRING), %s, NULL }", poffset);
974         break;
975     case TTeletexString:
976         add_line(temp, "{ A1_PARSE_T(A1T_TELETEX_STRING), %s, NULL }", poffset);
977         break;
978     case TPrintableString:
979         add_line(temp, "{ A1_PARSE_T(A1T_PRINTABLE_STRING), %s, NULL }", poffset);
980         break;
981     case TOctetString:
982         add_line(temp, "{ A1_PARSE_T(A1T_OCTET_STRING), %s, NULL }", poffset);
983         break;
984     case TIA5String:
985         add_line(temp, "{ A1_PARSE_T(A1T_IA5_STRING), %s, NULL }", poffset);
986         break;
987     case TBMPString:
988         add_line(temp, "{ A1_PARSE_T(A1T_BMP_STRING), %s, NULL }", poffset);
989         break;
990     case TUniversalString:
991         add_line(temp, "{ A1_PARSE_T(A1T_UNIVERSAL_STRING), %s, NULL }", poffset);
992         break;
993     case TVisibleString:
994         add_line(temp, "{ A1_PARSE_T(A1T_VISIBLE_STRING), %s, NULL }", poffset);
995         break;
996     case TUTF8String:
997         add_line(temp, "{ A1_PARSE_T(A1T_UTF8_STRING), %s, NULL }", poffset);
998         break;
999     case TGeneralizedTime:
1000         add_line(temp, "{ A1_PARSE_T(A1T_GENERALIZED_TIME), %s, NULL }", poffset);
1001         break;
1002     case TUTCTime:
1003         add_line(temp, "{ A1_PARSE_T(A1T_UTC_TIME), %s, NULL }", poffset);
1004         break;
1005     case TBoolean:
1006         add_line(temp, "{ A1_PARSE_T(A1T_BOOLEAN), %s, NULL }", poffset);
1007         break;
1008     case TOID:
1009         add_line(temp, "{ A1_PARSE_T(A1T_OID), %s, NULL }", poffset);
1010         break;
1011     case TNull:
1012         break;
1013     case TBitString: {
1014         struct templatehead template;
1015         struct template *q;
1016         Member *m;
1017         size_t count = 0, i;
1018         char *bname = NULL;
1019         FILE *f = get_code_file();
1020         static unsigned long bmember_counter = 0;
1021
1022         HEIM_TAILQ_INIT(&template);
1023
1024         if (HEIM_TAILQ_EMPTY(t->members)) {
1025             add_line(temp, "{ A1_PARSE_T(A1T_HEIM_BIT_STRING), %s, NULL }", poffset);
1026             break;
1027         }
1028
1029         if (asprintf(&bname, "bmember_%s_%lu", name ? name : "", bmember_counter++) < 0 || bname == NULL)
1030             errx(1, "malloc");
1031         output_name(bname);
1032
1033         HEIM_TAILQ_FOREACH(m, t->members, members) {
1034             add_line(&template, "{ 0, %d, \"%s\" }", m->val, m->gen_name);
1035         }
1036
1037         HEIM_TAILQ_FOREACH(q, &template, members) {
1038             count++;
1039         }
1040
1041         fprintf(f, "static const struct asn1_template asn1_%s_%s[] = {\n", basetype, bname);
1042         fprintf(f, "/* 0 */ { 0%s, sizeof(%s), ((void *)%lu) },\n",
1043                 rfc1510_bitstring ? "|A1_HBF_RFC1510" : "",
1044                 basetype, (unsigned long)count);
1045         i = 1;
1046         HEIM_TAILQ_FOREACH(q, &template, members) {
1047             int last = (HEIM_TAILQ_LAST(&template, templatehead) == q);
1048             fprintf(f, "/* %lu */ %s%s\n", (unsigned long)i++, q->line, last ? "" : ",");
1049         }
1050         fprintf(f, "};\n");
1051
1052         add_line(temp, "{ A1_OP_BMEMBER, %s, asn1_%s_%s }", poffset, basetype, bname);
1053
1054         free(bname);
1055
1056         break;
1057     }
1058     case TSet: {
1059         Member *opentypemember = NULL;
1060         Member *typeidmember = NULL;
1061         Field *opentypefield = NULL;
1062         Field *typeidfield = NULL;
1063         Member *m;
1064         size_t i = 0, typeididx = 0, opentypeidx = 0;
1065         int is_array_of_open_type = 0;
1066         int deco_opt;
1067         char *ft, *fn;
1068
1069         if (isstruct && t->actual_parameter)
1070             get_open_type_defn_fields(t, &typeidmember, &opentypemember,
1071                                       &typeidfield, &opentypefield,
1072                                       &is_array_of_open_type);
1073
1074         fprintf(get_code_file(), "/* tset: members isstruct: %d */\n", isstruct);
1075
1076         HEIM_TAILQ_FOREACH(m, t->members, members) {
1077             char *newbasename = NULL;
1078
1079             if (m->ellipsis)
1080                 continue;
1081
1082             if (typeidmember == m) typeididx = i;
1083             if (opentypemember == m) opentypeidx = i;
1084
1085             if (name) {
1086                 if (asprintf(&newbasename, "%s_%s", basetype, name) < 0)
1087                     errx(1, "malloc");
1088             } else
1089                 newbasename = strdup(basetype);
1090             if (newbasename == NULL)
1091                 errx(1, "malloc");
1092
1093             if (m->defval)
1094                 defval(temp, m);
1095
1096             template_members(temp, newbasename, m->gen_name, m->type, m->optional, m->defval ? 1 : 0, 0, isstruct, 1);
1097
1098             free(newbasename);
1099             i++;
1100         }
1101
1102         if (isstruct && t->actual_parameter)
1103             template_open_type(temp, basetype, t, typeididx, opentypeidx,
1104                                typeidfield, opentypefield, opentypemember,
1105                                is_array_of_open_type);
1106
1107         if (decorate_type(basetype, &ft, &fn, &deco_opt)) {
1108             char *poffset2;
1109
1110             poffset2 = partial_offset(basetype, fn, 1, isstruct);
1111             add_line_pointer(temp, ft, poffset2, "A1_OP_TYPE_DECORATE %s",
1112                              deco_opt ? "|A1_FLAG_OPTIONAL" : "");
1113             free(poffset2);
1114             free(ft);
1115             free(fn);
1116         }
1117
1118         if (isstruct)
1119             template_names(temp, basetype, t);
1120         break;
1121     }
1122     case TSequence: {
1123         Member *opentypemember = NULL;
1124         Member *typeidmember = NULL;
1125         Field *opentypefield = NULL;
1126         Field *typeidfield = NULL;
1127         Member *m;
1128         size_t i = 0, typeididx = 0, opentypeidx = 0;
1129         int is_array_of_open_type = 0;
1130         int deco_opt;
1131         char *ft, *fn;
1132
1133         if (isstruct && t->actual_parameter)
1134             get_open_type_defn_fields(t, &typeidmember, &opentypemember,
1135                                       &typeidfield, &opentypefield,
1136                                       &is_array_of_open_type);
1137
1138         fprintf(get_code_file(), "/* tsequence: members isstruct: %d */\n", isstruct);
1139
1140         HEIM_TAILQ_FOREACH(m, t->members, members) {
1141             char *newbasename = NULL;
1142
1143             if (m->ellipsis)
1144                 continue;
1145
1146             if (typeidmember == m) typeididx = i;
1147             if (opentypemember == m) opentypeidx = i;
1148
1149             if (name) {
1150                 if (asprintf(&newbasename, "%s_%s", basetype, name) < 0)
1151                     errx(1, "malloc");
1152             } else
1153                 newbasename = strdup(basetype);
1154             if (newbasename == NULL)
1155                 errx(1, "malloc");
1156
1157             if (m->defval)
1158                 defval(temp, m);
1159             
1160             template_members(temp, newbasename, m->gen_name, m->type, m->optional, m->defval ? 1 : 0, 0, isstruct, 1);
1161
1162             free(newbasename);
1163             i++;
1164         }
1165
1166         if (isstruct && t->actual_parameter)
1167             template_open_type(temp, basetype, t, typeididx, opentypeidx,
1168                                typeidfield, opentypefield, opentypemember,
1169                                is_array_of_open_type);
1170
1171         if (decorate_type(basetype, &ft, &fn, &deco_opt)) {
1172             char *poffset2;
1173
1174             poffset2 = partial_offset(basetype, fn, 1, isstruct);
1175             add_line_pointer(temp, ft, poffset2, "A1_OP_TYPE_DECORATE %s",
1176                              deco_opt ? "|A1_FLAG_OPTIONAL" : "");
1177             free(poffset2);
1178             free(ft);
1179             free(fn);
1180         }
1181
1182         if (isstruct)
1183             template_names(temp, basetype, t);
1184         break;
1185     }
1186     case TTag: {
1187         char *tname = NULL, *elname = NULL;
1188         const char *sename, *dupname;
1189         int subtype_is_struct = is_struct(t->subtype, isstruct);
1190         static unsigned long tag_counter = 0;
1191         int tagimplicit = 0;
1192         int prim = !(t->tag.tagclass != ASN1_C_UNIV &&
1193                      t->tag.tagenv == TE_EXPLICIT) &&
1194             is_primitive_type(t->subtype);
1195
1196         if (t->tag.tagenv == TE_IMPLICIT) {
1197             Type *t2 = t->subtype ? t->subtype : t->symbol->type;
1198
1199             while (t2->type == TType && (t2->subtype || t2->symbol->type))
1200                 t2 = t2->subtype ? t2->subtype : t2->symbol->type;
1201             if (t2->type != TChoice)
1202                 tagimplicit = 1;
1203         }
1204
1205         fprintf(get_code_file(), "/* template_members: %s %s %s */\n", basetype, implicit ? "imp" : "exp", tagimplicit ? "imp" : "exp");
1206
1207         if (subtype_is_struct)
1208             sename = basetype;
1209         else
1210             sename = symbol_name(basetype, t->subtype);
1211
1212         if (asprintf(&tname, "tag_%s_%lu", name ? name : "", tag_counter++) < 0 || tname == NULL)
1213             errx(1, "malloc");
1214         output_name(tname);
1215
1216         if (asprintf(&elname, "%s_%s", basetype, tname) < 0 || elname == NULL)
1217             errx(1, "malloc");
1218
1219         generate_template_type(elname, &dupname, NULL, sename, name,
1220                                t->subtype, 0, subtype_is_struct, 0);
1221
1222         add_line_pointer(temp, dupname, poffset,
1223                          "A1_TAG_T(%s,%s,%s)%s%s%s",
1224                          classname(t->tag.tagclass),
1225                          prim  ? "PRIM" : "CONS",
1226                          valuename(t->tag.tagclass, t->tag.tagvalue),
1227                          optional    ? "|A1_FLAG_OPTIONAL" : "",
1228                          defaulted   ? "|A1_FLAG_DEFAULT" : "",
1229                          tagimplicit ? "|A1_FLAG_IMPLICIT" : "");
1230
1231         free(tname);
1232         free(elname);
1233
1234         break;
1235     }
1236     case TSetOf:
1237     case TSequenceOf: {
1238         const char *type = NULL, *tname, *dupname;
1239         char *sename = NULL, *elname = NULL;
1240         int subtype_is_struct = is_struct(t->subtype, 0);
1241         static unsigned long seof_counter = 0;
1242
1243         if (name && subtype_is_struct) {
1244             tname = "seofTstruct";
1245             if (asprintf(&sename, "%s_%s_val", basetype, name) < 0)
1246                 errx(1, "malloc");
1247         } else if (subtype_is_struct) {
1248             tname = "seofTstruct";
1249             if (asprintf(&sename, "%s_val", symbol_name(basetype, t->subtype)) < 0)
1250                 errx(1, "malloc");
1251         } else {
1252             if (name)
1253                 tname = name;
1254             else
1255                 tname = "seofTstruct";
1256             sename = strdup(symbol_name(basetype, t->subtype));
1257         }
1258         if (sename == NULL)
1259             errx(1, "malloc");
1260
1261         if (t->type == TSetOf) type = "A1_OP_SETOF";
1262         else if (t->type == TSequenceOf) type = "A1_OP_SEQOF";
1263         else abort();
1264
1265         if (asprintf(&elname, "%s_%s_%lu", basetype, tname, seof_counter++) < 0 || elname == NULL)
1266             errx(1, "malloc");
1267
1268         generate_template_type(elname, &dupname, NULL, sename, NULL, t->subtype,
1269                                0, subtype_is_struct, need_offset);
1270
1271         add_line(temp, "{ %s, %s, asn1_%s }", type, poffset, dupname);
1272         free(sename);
1273         break;
1274     }
1275     case TChoice: {
1276         struct templatehead template;
1277         struct template *q;
1278         size_t count = 0, i;
1279         char *tname = NULL;
1280         FILE *f = get_code_file();
1281         Member *m;
1282         int ellipsis = 0;
1283         char *e;
1284         static unsigned long choice_counter = 0;
1285
1286         HEIM_TAILQ_INIT(&template);
1287
1288         if (asprintf(&tname, "asn1_choice_%s_%s%lu",
1289                      basetype, name ? name : "", choice_counter++) < 0 || tname == NULL)
1290             errx(1, "malloc");
1291
1292         HEIM_TAILQ_FOREACH(m, t->members, members) {
1293             const char *dupname;
1294             char *elname = NULL;
1295             char *newbasename = NULL;
1296             int subtype_is_struct;
1297
1298             if (m->ellipsis) {
1299                 ellipsis = 1;
1300                 continue;
1301             }
1302
1303             subtype_is_struct = is_struct(m->type, 0);
1304
1305             if (asprintf(&elname, "%s_choice_%s", basetype, m->gen_name) < 0 || elname == NULL)
1306                 errx(1, "malloc");
1307
1308             if (subtype_is_struct) {
1309                 if (asprintf(&newbasename, "%s_%s", basetype, m->gen_name) < 0)
1310                     errx(1, "malloc");
1311             } else
1312                 newbasename = strdup(basetype);
1313
1314             if (newbasename == NULL)
1315                 errx(1, "malloc");
1316
1317
1318             generate_template_type(elname, &dupname, NULL,
1319                                    symbol_name(newbasename, m->type),
1320                                    NULL, m->type, 0, subtype_is_struct, 1);
1321
1322             add_line(&template, "{ %s, offsetof(%s%s, u.%s), asn1_%s }",
1323                      m->label, isstruct ? "struct " : "",
1324                      basetype, m->gen_name,
1325                      dupname);
1326
1327             free(elname);
1328             free(newbasename);
1329         }
1330
1331         HEIM_TAILQ_FOREACH(m, t->members, members) {
1332             add_line(&template, "{ 0, 0, \"%s\" }", m->name);
1333         }
1334
1335         e = NULL;
1336         if (ellipsis) {
1337             if (asprintf(&e, "offsetof(%s%s, u.asn1_ellipsis)", isstruct ? "struct " : "", basetype) < 0 || e == NULL)
1338                 errx(1, "malloc");
1339         }
1340
1341         HEIM_TAILQ_FOREACH(q, &template, members) {
1342             count++;
1343         }
1344
1345         fprintf(f, "static const struct asn1_template %s[] = {\n", tname);
1346         fprintf(f, "/* 0 */ { %s, offsetof(%s%s, element), ((void *)%lu) },\n",
1347                 e ? e : "0", isstruct ? "struct " : "", basetype, (unsigned long)count);
1348         i = 1;
1349         HEIM_TAILQ_FOREACH(q, &template, members) {
1350             int last = (HEIM_TAILQ_LAST(&template, templatehead) == q);
1351             fprintf(f, "/* %lu */ %s%s\n", (unsigned long)i++, q->line, last ? "" : ",");
1352         }
1353         fprintf(f, "};\n");
1354
1355         add_line(temp, "{ A1_OP_CHOICE, %s, %s }", poffset, tname);
1356
1357         free(e);
1358         free(tname);
1359         break;
1360     }
1361     default:
1362         abort ();
1363     }
1364     if (poffset)
1365         free(poffset);
1366 }
1367
1368 static void
1369 gen_extern_stubs(FILE *f, const char *name)
1370 {
1371     fprintf(f,
1372             "static const struct asn1_type_func asn1_extern_%s = {\n"
1373             "\t(asn1_type_encode)encode_%s,\n"
1374             "\t(asn1_type_decode)decode_%s,\n"
1375             "\t(asn1_type_length)length_%s,\n"
1376             "\t(asn1_type_copy)copy_%s,\n"
1377             "\t(asn1_type_release)free_%s,\n"
1378             "\t(asn1_type_print)print_%s,\n"
1379             "\tsizeof(%s)\n"
1380             "};\n",
1381             name, name, name, name,
1382             name, name, name, name);
1383 }
1384
1385 void
1386 gen_template_import(const Symbol *s)
1387 {
1388     FILE *f = get_code_file();
1389
1390     if (template_flag == 0)
1391         return;
1392
1393     gen_extern_stubs(f, s->gen_name);
1394 }
1395
1396 void
1397 generate_template_type_forward(const char *name)
1398 {
1399     fprintf(get_code_file(), "extern const struct asn1_template asn1_%s[];\n", name);
1400 }
1401
1402 void
1403 generate_template_objectset_forwards(const Symbol *s)
1404 {
1405     if (!template_flag)
1406         return;
1407     fprintf(get_code_file(), "extern const struct asn1_template asn1_%s[];\n",
1408             s->gen_name);
1409 }
1410
1411 static void
1412 generate_template_type(const char *varname,
1413                        const char **dupname,
1414                        const char *symname,
1415                        const char *basetype,
1416                        const char *name,
1417                        Type *type,
1418                        int optional,
1419                        int isstruct,
1420                        int need_offset)
1421 {
1422     struct tlist *tl;
1423     const char *d;
1424     char *szt = NULL;
1425     int have_ellipsis = 0;
1426     int implicit = 0;
1427     int n;
1428
1429     tl = tlist_new(varname);
1430
1431     if (type->type == TTag && type->tag.tagenv == TE_IMPLICIT) {
1432         Type *t = type->subtype ? type->subtype : type->symbol->type;
1433
1434         while (t->type == TType && (t->subtype || t->symbol->type))
1435             t = t->subtype ? t->subtype : t->symbol->type;
1436         if (t->type != TChoice)
1437             implicit = (type->tag.tagenv == TE_IMPLICIT);
1438     }
1439
1440     template_members(&tl->template, basetype, name, type, optional, 0,
1441                      implicit, isstruct, need_offset);
1442
1443     /* if its a sequence or set type, check if there is a ellipsis */
1444     if (type->type == TSequence || type->type == TSet) {
1445         Member *m;
1446         HEIM_TAILQ_FOREACH(m, type->members, members) {
1447             if (m->ellipsis)
1448                 have_ellipsis = 1;
1449         }
1450     }
1451
1452     if (isstruct)
1453         if (name)
1454             n = asprintf(&szt, "struct %s_%s", basetype, name);
1455         else
1456             n = asprintf(&szt, "struct %s", basetype);
1457     else
1458         n = asprintf(&szt, "%s", basetype);
1459     if (n < 0 || szt == NULL)
1460         errx(1, "malloc");
1461
1462     if (HEIM_TAILQ_EMPTY(&tl->template) && compact_tag(type)->type != TNull)
1463         errx(1, "Tag %s...%s with no content ?", basetype, name ? name : "");
1464
1465     fprintf(get_code_file(), "/* generate_template_type: %s */\n", tl->name);
1466
1467     tlist_header(tl, "{ 0%s%s, sizeof(%s), ((void *)%lu) }",
1468                  (symname && preserve_type(symname)) ? "|A1_HF_PRESERVE" : "",
1469                  have_ellipsis ? "|A1_HF_ELLIPSIS" : "", szt, tlist_count(tl));
1470
1471     free(szt);
1472
1473     /* XXX Accidentally O(N^2)? */
1474     d = tlist_find_dup(tl);
1475     if (d) {
1476 #if 0
1477         if (strcmp(d, tl->name) == 0)
1478             errx(1, "found dup of ourself: %s", d);
1479 #endif
1480         *dupname = d;
1481     } else {
1482         *dupname = tl->name;
1483         tlist_print(tl);
1484         tlist_add(tl);
1485     }
1486 }
1487
1488
1489 void
1490 generate_template(const Symbol *s)
1491 {
1492     FILE *f = get_code_file();
1493     const char *dupname;
1494
1495     if (use_extern(s)) {
1496         gen_extern_stubs(f, s->gen_name);
1497         return;
1498     }
1499
1500     generate_template_type(s->gen_name, &dupname, s->name, s->gen_name, NULL, s->type, 0, 0, 1);
1501
1502     fprintf(f,
1503             "\n"
1504             "int ASN1CALL\n"
1505             "decode_%s(const unsigned char *p, size_t len, %s *data, size_t *size)\n"
1506             "{\n"
1507             "    return _asn1_decode_top(asn1_%s, 0|%s, p, len, data, size);\n"
1508             "}\n"
1509             "\n",
1510             s->gen_name,
1511             s->gen_name,
1512             dupname,
1513             support_ber ? "A1_PF_ALLOW_BER" : "0");
1514
1515     fprintf(f,
1516             "\n"
1517             "int ASN1CALL\n"
1518             "encode_%s(unsigned char *p, size_t len, const %s *data, size_t *size)\n"
1519             "{\n"
1520             "    return _asn1_encode%s(asn1_%s, p, len, data, size);\n"
1521             "}\n"
1522             "\n",
1523             s->gen_name,
1524             s->gen_name,
1525             fuzzer_string,
1526             dupname);
1527
1528     fprintf(f,
1529             "\n"
1530             "size_t ASN1CALL\n"
1531             "length_%s(const %s *data)\n"
1532             "{\n"
1533             "    return _asn1_length%s(asn1_%s, data);\n"
1534             "}\n"
1535             "\n",
1536             s->gen_name,
1537             s->gen_name,
1538             fuzzer_string,
1539             dupname);
1540
1541
1542     fprintf(f,
1543             "\n"
1544             "void ASN1CALL\n"
1545             "free_%s(%s *data)\n"
1546             "{\n"
1547             "    _asn1_free_top(asn1_%s, data);\n"
1548             "}\n"
1549             "\n",
1550             s->gen_name,
1551             s->gen_name,
1552             dupname);
1553
1554     fprintf(f,
1555             "\n"
1556             "int ASN1CALL\n"
1557             "copy_%s(const %s *from, %s *to)\n"
1558             "{\n"
1559             "    return _asn1_copy_top(asn1_%s, from, to);\n"
1560             "}\n"
1561             "\n",
1562             s->gen_name,
1563             s->gen_name,
1564             s->gen_name,
1565             dupname);
1566
1567     fprintf(f,
1568             "\n"
1569             "char * ASN1CALL\n"
1570             "print_%s(const %s *data, int flags)\n"
1571             "{\n"
1572             "    return _asn1_print_top(asn1_%s, flags, data);\n"
1573             "}\n"
1574             "\n",
1575             s->gen_name,
1576             s->gen_name,
1577             dupname);
1578 }