Merge "Moving in e2sim originally from it/test/simulators"
[sim/e2-interface.git] / e2sim / ASN1c / constr_CHOICE.c
1 /*****************************************************************************
2 #                                                                            *
3 # Copyright 2019 AT&T Intellectual Property                                  *
4 #                                                                            *
5 # Licensed under the Apache License, Version 2.0 (the "License");            *
6 # you may not use this file except in compliance with the License.           *
7 # You may obtain a copy of the License at                                    *
8 #                                                                            *
9 #      http://www.apache.org/licenses/LICENSE-2.0                            *
10 #                                                                            *
11 # Unless required by applicable law or agreed to in writing, software        *
12 # distributed under the License is distributed on an "AS IS" BASIS,          *
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   *
14 # See the License for the specific language governing permissions and        *
15 # limitations under the License.                                             *
16 #                                                                            *
17 ******************************************************************************/
18
19 /*
20  * Copyright (c) 2003-2017 Lev Walkin <vlm@lionet.info>. All rights reserved.
21  * Redistribution and modifications are permitted subject to BSD license.
22  */
23 #include <asn_internal.h>
24 #include <constr_CHOICE.h>
25 #include <per_opentype.h>
26
27 /*
28  * Number of bytes left for this structure.
29  * (ctx->left) indicates the number of bytes _transferred_ for the structure.
30  * (size) contains the number of bytes in the buffer passed.
31  */
32 #define LEFT    ((size<(size_t)ctx->left)?size:(size_t)ctx->left)
33
34 /*
35  * If the subprocessor function returns with an indication that it wants
36  * more data, it may well be a fatal decoding problem, because the
37  * size is constrained by the <TLV>'s L, even if the buffer size allows
38  * reading more data.
39  * For example, consider the buffer containing the following TLVs:
40  * <T:5><L:1><V> <T:6>...
41  * The TLV length clearly indicates that one byte is expected in V, but
42  * if the V processor returns with "want more data" even if the buffer
43  * contains way more data than the V processor have seen.
44  */
45 #define SIZE_VIOLATION  (ctx->left >= 0 && (size_t)ctx->left <= size)
46
47 /*
48  * This macro "eats" the part of the buffer which is definitely "consumed",
49  * i.e. was correctly converted into local representation or rightfully skipped.
50  */
51 #undef  ADVANCE
52 #define ADVANCE(num_bytes)      do {            \
53                 size_t num = num_bytes;         \
54                 ptr = ((const char *)ptr) + num;\
55                 size -= num;                    \
56                 if(ctx->left >= 0)              \
57                         ctx->left -= num;       \
58                 consumed_myself += num;         \
59         } while(0)
60
61 /*
62  * Switch to the next phase of parsing.
63  */
64 #undef  NEXT_PHASE
65 #define NEXT_PHASE(ctx) do {                    \
66                 ctx->phase++;                   \
67                 ctx->step = 0;                  \
68         } while(0)
69
70 /*
71  * Return a standardized complex structure.
72  */
73 #undef  RETURN
74 #define RETURN(_code)   do {                    \
75                 rval.code = _code;              \
76                 rval.consumed = consumed_myself;\
77                 return rval;                    \
78         } while(0)
79
80 /*
81  * See the definitions.
82  */
83 static unsigned _fetch_present_idx(const void *struct_ptr, unsigned off,
84                                    unsigned size);
85 static void _set_present_idx(void *sptr, unsigned offset, unsigned size,
86                              unsigned pres);
87 static const void *_get_member_ptr(const asn_TYPE_descriptor_t *,
88                                    const void *sptr, asn_TYPE_member_t **elm,
89                                    unsigned *present);
90
91 /*
92  * Tags are canonically sorted in the tag to member table.
93  */
94 static int
95 _search4tag(const void *ap, const void *bp) {
96         const asn_TYPE_tag2member_t *a = (const asn_TYPE_tag2member_t *)ap;
97         const asn_TYPE_tag2member_t *b = (const asn_TYPE_tag2member_t *)bp;
98
99         int a_class = BER_TAG_CLASS(a->el_tag);
100         int b_class = BER_TAG_CLASS(b->el_tag);
101
102         if(a_class == b_class) {
103                 ber_tlv_tag_t a_value = BER_TAG_VALUE(a->el_tag);
104                 ber_tlv_tag_t b_value = BER_TAG_VALUE(b->el_tag);
105
106                 if(a_value == b_value)
107                         return 0;
108                 else if(a_value < b_value)
109                         return -1;
110                 else
111                         return 1;
112         } else if(a_class < b_class) {
113                 return -1;
114         } else {
115                 return 1;
116         }
117 }
118
119 /*
120  * The decoder of the CHOICE type.
121  */
122 asn_dec_rval_t
123 CHOICE_decode_ber(const asn_codec_ctx_t *opt_codec_ctx,
124                   const asn_TYPE_descriptor_t *td, void **struct_ptr,
125                   const void *ptr, size_t size, int tag_mode) {
126     /*
127          * Bring closer parts of structure description.
128          */
129         const asn_CHOICE_specifics_t *specs =
130                 (const asn_CHOICE_specifics_t *)td->specifics;
131         asn_TYPE_member_t *elements = td->elements;
132
133         /*
134          * Parts of the structure being constructed.
135          */
136         void *st = *struct_ptr; /* Target structure. */
137         asn_struct_ctx_t *ctx;  /* Decoder context */
138
139         ber_tlv_tag_t tlv_tag;  /* T from TLV */
140         ssize_t tag_len;        /* Length of TLV's T */
141         asn_dec_rval_t rval;    /* Return code from subparsers */
142
143         ssize_t consumed_myself = 0;    /* Consumed bytes from ptr */
144
145         ASN_DEBUG("Decoding %s as CHOICE", td->name);
146
147         /*
148          * Create the target structure if it is not present already.
149          */
150         if(st == 0) {
151                 st = *struct_ptr = CALLOC(1, specs->struct_size);
152                 if(st == 0) {
153                         RETURN(RC_FAIL);
154                 }
155         }
156
157         /*
158          * Restore parsing context.
159          */
160         ctx = (asn_struct_ctx_t *)((char *)st + specs->ctx_offset);
161         
162         /*
163          * Start to parse where left previously
164          */
165         switch(ctx->phase) {
166         case 0:
167                 /*
168                  * PHASE 0.
169                  * Check that the set of tags associated with given structure
170                  * perfectly fits our expectations.
171                  */
172
173                 if(tag_mode || td->tags_count) {
174                         rval = ber_check_tags(opt_codec_ctx, td, ctx, ptr, size,
175                                 tag_mode, -1, &ctx->left, 0);
176                         if(rval.code != RC_OK) {
177                                 ASN_DEBUG("%s tagging check failed: %d",
178                                         td->name, rval.code);
179                                 return rval;
180                         }
181
182                         if(ctx->left >= 0) {
183                                 /* ?Substracted below! */
184                                 ctx->left += rval.consumed;
185                         }
186                         ADVANCE(rval.consumed);
187                 } else {
188                         ctx->left = -1;
189                 }
190
191                 NEXT_PHASE(ctx);
192
193                 ASN_DEBUG("Structure consumes %ld bytes, buffer %ld",
194                         (long)ctx->left, (long)size);
195
196                 /* Fall through */
197         case 1:
198                 /*
199                  * Fetch the T from TLV.
200                  */
201                 tag_len = ber_fetch_tag(ptr, LEFT, &tlv_tag);
202                 ASN_DEBUG("In %s CHOICE tag length %d", td->name, (int)tag_len);
203                 switch(tag_len) {
204                 case 0: if(!SIZE_VIOLATION) RETURN(RC_WMORE);
205                         /* Fall through */
206                 case -1: RETURN(RC_FAIL);
207                 }
208
209                 do {
210                         const asn_TYPE_tag2member_t *t2m;
211                         asn_TYPE_tag2member_t key;
212
213                         key.el_tag = tlv_tag;
214                         t2m = (const asn_TYPE_tag2member_t *)bsearch(&key,
215                                         specs->tag2el, specs->tag2el_count,
216                                         sizeof(specs->tag2el[0]), _search4tag);
217                         if(t2m) {
218                                 /*
219                                  * Found the element corresponding to the tag.
220                                  */
221                                 NEXT_PHASE(ctx);
222                                 ctx->step = t2m->el_no;
223                                 break;
224                         } else if(specs->ext_start == -1) {
225                                 ASN_DEBUG("Unexpected tag %s "
226                                         "in non-extensible CHOICE %s",
227                                         ber_tlv_tag_string(tlv_tag), td->name);
228                                 RETURN(RC_FAIL);
229                         } else {
230                                 /* Skip this tag */
231                                 ssize_t skip;
232
233                                 ASN_DEBUG("Skipping unknown tag %s",
234                                         ber_tlv_tag_string(tlv_tag));
235
236                                 skip = ber_skip_length(opt_codec_ctx,
237                                         BER_TLV_CONSTRUCTED(ptr),
238                                         (const char *)ptr + tag_len,
239                                         LEFT - tag_len);
240
241                                 switch(skip) {
242                                 case 0: if(!SIZE_VIOLATION) RETURN(RC_WMORE);
243                                         /* Fall through */
244                                 case -1: RETURN(RC_FAIL);
245                                 }
246
247                                 ADVANCE(skip + tag_len);
248                                 RETURN(RC_OK);
249                         }
250                 } while(0);
251
252         case 2:
253                 /*
254                  * PHASE 2.
255                  * Read in the element.
256                  */
257             do {
258                 asn_TYPE_member_t *elm;/* CHOICE's element */
259                 void *memb_ptr;         /* Pointer to the member */
260                 void **memb_ptr2;       /* Pointer to that pointer */
261
262                 elm = &elements[ctx->step];
263
264                 /*
265                  * Compute the position of the member inside a structure,
266                  * and also a type of containment (it may be contained
267                  * as pointer or using inline inclusion).
268                  */
269                 if(elm->flags & ATF_POINTER) {
270                         /* Member is a pointer to another structure */
271                         memb_ptr2 = (void **)((char *)st + elm->memb_offset);
272                 } else {
273                         /*
274                          * A pointer to a pointer
275                          * holding the start of the structure
276                          */
277                         memb_ptr = (char *)st + elm->memb_offset;
278                         memb_ptr2 = &memb_ptr;
279                 }
280                 /* Set presence to be able to free it properly at any time */
281                 _set_present_idx(st, specs->pres_offset,
282                                 specs->pres_size, ctx->step + 1);
283                 /*
284                  * Invoke the member fetch routine according to member's type
285                  */
286                 rval = elm->type->op->ber_decoder(opt_codec_ctx, elm->type,
287                                 memb_ptr2, ptr, LEFT, elm->tag_mode);
288                 switch(rval.code) {
289                 case RC_OK:
290                         break;
291                 case RC_WMORE: /* More data expected */
292                         if(!SIZE_VIOLATION) {
293                                 ADVANCE(rval.consumed);
294                                 RETURN(RC_WMORE);
295                         }
296                         RETURN(RC_FAIL);
297                 case RC_FAIL: /* Fatal error */
298                         RETURN(rval.code);
299                 } /* switch(rval) */
300                 
301                 ADVANCE(rval.consumed);
302           } while(0);
303
304                 NEXT_PHASE(ctx);
305
306                 /* Fall through */
307         case 3:
308                 ASN_DEBUG("CHOICE %s Leftover: %ld, size = %ld, tm=%d, tc=%d",
309                         td->name, (long)ctx->left, (long)size,
310                         tag_mode, td->tags_count);
311
312                 if(ctx->left > 0) {
313                         /*
314                          * The type must be fully decoded
315                          * by the CHOICE member-specific decoder.
316                          */
317                         RETURN(RC_FAIL);
318                 }
319
320                 if(ctx->left == -1
321                 && !(tag_mode || td->tags_count)) {
322                         /*
323                          * This is an untagged CHOICE.
324                          * It doesn't contain nothing
325                          * except for the member itself, including all its tags.
326                          * The decoding is completed.
327                          */
328                         NEXT_PHASE(ctx);
329                         break;
330                 }
331
332                 /*
333                  * Read in the "end of data chunks"'s.
334                  */
335                 while(ctx->left < 0) {
336                         ssize_t tl;
337
338                         tl = ber_fetch_tag(ptr, LEFT, &tlv_tag);
339                         switch(tl) {
340                         case 0: if(!SIZE_VIOLATION) RETURN(RC_WMORE);
341                                 /* Fall through */
342                         case -1: RETURN(RC_FAIL);
343                         }
344
345                         /*
346                          * Expected <0><0>...
347                          */
348                         if(((const uint8_t *)ptr)[0] == 0) {
349                                 if(LEFT < 2) {
350                                         if(SIZE_VIOLATION)
351                                                 RETURN(RC_FAIL);
352                                         else
353                                                 RETURN(RC_WMORE);
354                                 } else if(((const uint8_t *)ptr)[1] == 0) {
355                                         /*
356                                          * Correctly finished with <0><0>.
357                                          */
358                                         ADVANCE(2);
359                                         ctx->left++;
360                                         continue;
361                                 }
362                         } else {
363                                 ASN_DEBUG("Unexpected continuation in %s",
364                                         td->name);
365                                 RETURN(RC_FAIL);
366                         }
367
368                         /* UNREACHABLE */
369                 }
370
371                 NEXT_PHASE(ctx);
372         case 4:
373                 /* No meaningful work here */
374                 break;
375         }
376         
377         RETURN(RC_OK);
378 }
379
380 asn_enc_rval_t
381 CHOICE_encode_der(const asn_TYPE_descriptor_t *td, const void *sptr,
382                   int tag_mode, ber_tlv_tag_t tag, asn_app_consume_bytes_f *cb,
383                   void *app_key) {
384     const asn_CHOICE_specifics_t *specs = (const asn_CHOICE_specifics_t *)td->specifics;
385         asn_TYPE_member_t *elm; /* CHOICE element */
386         asn_enc_rval_t erval = {0,0,0};
387         const void *memb_ptr;
388         size_t computed_size = 0;
389         unsigned present;
390
391         if(!sptr) ASN__ENCODE_FAILED;
392
393         ASN_DEBUG("%s %s as CHOICE",
394                 cb?"Encoding":"Estimating", td->name);
395
396         present = _fetch_present_idx(sptr,
397                 specs->pres_offset, specs->pres_size);
398
399         /*
400          * If the structure was not initialized, it cannot be encoded:
401          * can't deduce what to encode in the choice type.
402          */
403         if(present == 0 || present > td->elements_count) {
404                 if(present == 0 && td->elements_count == 0) {
405                         /* The CHOICE is empty?! */
406                         erval.encoded = 0;
407                         ASN__ENCODED_OK(erval);
408                 }
409                 ASN__ENCODE_FAILED;
410         }
411
412         /*
413          * Seek over the present member of the structure.
414          */
415         elm = &td->elements[present-1];
416         if(elm->flags & ATF_POINTER) {
417         memb_ptr =
418             *(const void *const *)((const char *)sptr + elm->memb_offset);
419         if(memb_ptr == 0) {
420                         if(elm->optional) {
421                                 erval.encoded = 0;
422                                 ASN__ENCODED_OK(erval);
423                         }
424                         /* Mandatory element absent */
425                         ASN__ENCODE_FAILED;
426                 }
427         } else {
428         memb_ptr = (const void *)((const char *)sptr + elm->memb_offset);
429     }
430
431         /*
432          * If the CHOICE itself is tagged EXPLICIT:
433          * T ::= [2] EXPLICIT CHOICE { ... }
434          * Then emit the appropriate tags.
435          */
436         if(tag_mode == 1 || td->tags_count) {
437                 /*
438                  * For this, we need to pre-compute the member.
439                  */
440                 ssize_t ret;
441
442                 /* Encode member with its tag */
443                 erval = elm->type->op->der_encoder(elm->type, memb_ptr,
444                         elm->tag_mode, elm->tag, 0, 0);
445                 if(erval.encoded == -1)
446                         return erval;
447
448                 /* Encode CHOICE with parent or my own tag */
449                 ret = der_write_tags(td, erval.encoded, tag_mode, 1, tag,
450                         cb, app_key);
451                 if(ret == -1)
452                         ASN__ENCODE_FAILED;
453                 computed_size += ret;
454         }
455
456         /*
457          * Encode the single underlying member.
458          */
459         erval = elm->type->op->der_encoder(elm->type, memb_ptr,
460                 elm->tag_mode, elm->tag, cb, app_key);
461         if(erval.encoded == -1)
462                 return erval;
463
464         ASN_DEBUG("Encoded CHOICE member in %ld bytes (+%ld)",
465                 (long)erval.encoded, (long)computed_size);
466
467         erval.encoded += computed_size;
468
469         return erval;
470 }
471
472 ber_tlv_tag_t
473 CHOICE_outmost_tag(const asn_TYPE_descriptor_t *td, const void *ptr, int tag_mode, ber_tlv_tag_t tag) {
474         const asn_CHOICE_specifics_t *specs = (const asn_CHOICE_specifics_t *)td->specifics;
475         unsigned present;
476
477         assert(tag_mode == 0); (void)tag_mode;
478         assert(tag == 0); (void)tag;
479
480         /*
481          * Figure out which CHOICE element is encoded.
482          */
483         present = _fetch_present_idx(ptr, specs->pres_offset, specs->pres_size);
484
485         if(present > 0 && present <= td->elements_count) {
486                 const asn_TYPE_member_t *elm = &td->elements[present-1];
487                 const void *memb_ptr;
488
489                 if(elm->flags & ATF_POINTER) {
490                         memb_ptr = *(const void * const *)
491                                         ((const char *)ptr + elm->memb_offset);
492                 } else {
493                         memb_ptr = (const void *)
494                                         ((const char *)ptr + elm->memb_offset);
495                 }
496
497                 return asn_TYPE_outmost_tag(elm->type, memb_ptr,
498                         elm->tag_mode, elm->tag);
499         } else {
500                 return (ber_tlv_tag_t)-1;
501         }
502 }
503
504 int
505 CHOICE_constraint(const asn_TYPE_descriptor_t *td, const void *sptr,
506                   asn_app_constraint_failed_f *ctfailcb, void *app_key) {
507     const asn_CHOICE_specifics_t *specs =
508         (const asn_CHOICE_specifics_t *)td->specifics;
509     unsigned present;
510
511         if(!sptr) {
512                 ASN__CTFAIL(app_key, td, sptr,
513                         "%s: value not given (%s:%d)",
514                         td->name, __FILE__, __LINE__);
515                 return -1;
516         }
517
518         /*
519          * Figure out which CHOICE element is encoded.
520          */
521         present = _fetch_present_idx(sptr, specs->pres_offset,specs->pres_size);
522         if(present > 0 && present <= td->elements_count) {
523                 asn_TYPE_member_t *elm = &td->elements[present-1];
524                 const void *memb_ptr;
525
526                 if(elm->flags & ATF_POINTER) {
527                         memb_ptr = *(const void * const *)((const char *)sptr + elm->memb_offset);
528                         if(!memb_ptr) {
529                                 if(elm->optional)
530                                         return 0;
531                                 ASN__CTFAIL(app_key, td, sptr,
532                                         "%s: mandatory CHOICE element %s absent (%s:%d)",
533                                         td->name, elm->name, __FILE__, __LINE__);
534                                 return -1;
535                         }
536                 } else {
537                         memb_ptr = (const void *)((const char *)sptr + elm->memb_offset);
538                 }
539
540                 if(elm->encoding_constraints.general_constraints) {
541                         return elm->encoding_constraints.general_constraints(elm->type, memb_ptr,
542                                 ctfailcb, app_key);
543                 } else {
544                         return elm->type->encoding_constraints.general_constraints(elm->type,
545                                         memb_ptr, ctfailcb, app_key);
546                 }
547         } else {
548                 ASN__CTFAIL(app_key, td, sptr,
549                         "%s: no CHOICE element given (%s:%d)",
550                         td->name, __FILE__, __LINE__);
551                 return -1;
552         }
553 }
554
555 #undef  XER_ADVANCE
556 #define XER_ADVANCE(num_bytes)  do {                    \
557                 size_t num = num_bytes;                 \
558                 buf_ptr = (const void *)(((const char *)buf_ptr) + num); \
559                 size -= num;                            \
560                 consumed_myself += num;                 \
561         } while(0)
562
563 /*
564  * Decode the XER (XML) data.
565  */
566 asn_dec_rval_t
567 CHOICE_decode_xer(const asn_codec_ctx_t *opt_codec_ctx,
568                   const asn_TYPE_descriptor_t *td, void **struct_ptr,
569                   const char *opt_mname, const void *buf_ptr, size_t size) {
570     /*
571          * Bring closer parts of structure description.
572          */
573         const asn_CHOICE_specifics_t *specs = (const asn_CHOICE_specifics_t *)td->specifics;
574         const char *xml_tag = opt_mname ? opt_mname : td->xml_tag;
575
576         /*
577          * Parts of the structure being constructed.
578          */
579         void *st = *struct_ptr; /* Target structure. */
580         asn_struct_ctx_t *ctx;  /* Decoder context */
581
582         asn_dec_rval_t rval;            /* Return value of a decoder */
583         ssize_t consumed_myself = 0;    /* Consumed bytes from ptr */
584         size_t edx;                     /* Element index */
585
586         /*
587          * Create the target structure if it is not present already.
588          */
589         if(st == 0) {
590                 st = *struct_ptr = CALLOC(1, specs->struct_size);
591                 if(st == 0) RETURN(RC_FAIL);
592         }
593
594         /*
595          * Restore parsing context.
596          */
597         ctx = (asn_struct_ctx_t *)((char *)st + specs->ctx_offset);
598         if(ctx->phase == 0 && !*xml_tag)
599                 ctx->phase = 1; /* Skip the outer tag checking phase */
600
601         /*
602          * Phases of XER/XML processing:
603          * Phase 0: Check that the opening tag matches our expectations.
604          * Phase 1: Processing body and reacting on closing tag.
605          * Phase 2: Processing inner type.
606          * Phase 3: Only waiting for closing tag.
607          * Phase 4: Skipping unknown extensions.
608          * Phase 5: PHASED OUT
609          */
610         for(edx = ctx->step; ctx->phase <= 4;) {
611                 pxer_chunk_type_e ch_type;      /* XER chunk type */
612                 ssize_t ch_size;                /* Chunk size */
613                 xer_check_tag_e tcv;            /* Tag check value */
614                 asn_TYPE_member_t *elm;
615
616                 /*
617                  * Go inside the member.
618                  */
619                 if(ctx->phase == 2) {
620                         asn_dec_rval_t tmprval;
621                         void *memb_ptr;         /* Pointer to the member */
622                         void **memb_ptr2;       /* Pointer to that pointer */
623                         unsigned old_present;
624
625                         elm = &td->elements[edx];
626
627                         if(elm->flags & ATF_POINTER) {
628                                 /* Member is a pointer to another structure */
629                                 memb_ptr2 = (void **)((char *)st
630                                         + elm->memb_offset);
631                         } else {
632                                 memb_ptr = (char *)st + elm->memb_offset;
633                                 memb_ptr2 = &memb_ptr;
634                         }
635
636                         /* Start/Continue decoding the inner member */
637                         tmprval = elm->type->op->xer_decoder(opt_codec_ctx,
638                                         elm->type, memb_ptr2, elm->name,
639                                         buf_ptr, size);
640                         XER_ADVANCE(tmprval.consumed);
641                         ASN_DEBUG("XER/CHOICE: itdf: [%s] code=%d",
642                                 elm->type->name, tmprval.code);
643                         old_present = _fetch_present_idx(st,
644                                 specs->pres_offset, specs->pres_size);
645                         assert(old_present == 0 || old_present == edx + 1);
646                         /* Record what we've got */
647                         _set_present_idx(st,
648                                 specs->pres_offset, specs->pres_size, edx + 1);
649                         if(tmprval.code != RC_OK)
650                                 RETURN(tmprval.code);
651                         ctx->phase = 3;
652                         /* Fall through */
653                 }
654
655                 /* No need to wait for closing tag; special mode. */
656                 if(ctx->phase == 3 && !*xml_tag) {
657                         ctx->phase = 5; /* Phase out */
658                         RETURN(RC_OK);
659                 }
660
661                 /*
662                  * Get the next part of the XML stream.
663                  */
664                 ch_size = xer_next_token(&ctx->context, buf_ptr, size, &ch_type);
665                 if(ch_size == -1) {
666             RETURN(RC_FAIL);
667         } else {
668                         switch(ch_type) {
669                         case PXER_WMORE:
670                 RETURN(RC_WMORE);
671                         case PXER_COMMENT:      /* Got XML comment */
672                         case PXER_TEXT:         /* Ignore free-standing text */
673                                 XER_ADVANCE(ch_size);   /* Skip silently */
674                                 continue;
675                         case PXER_TAG:
676                                 break;  /* Check the rest down there */
677                         }
678                 }
679
680                 tcv = xer_check_tag(buf_ptr, ch_size, xml_tag);
681                 ASN_DEBUG("XER/CHOICE checked [%c%c%c%c] vs [%s], tcv=%d",
682                         ch_size>0?((const uint8_t *)buf_ptr)[0]:'?',
683                         ch_size>1?((const uint8_t *)buf_ptr)[1]:'?',
684                         ch_size>2?((const uint8_t *)buf_ptr)[2]:'?',
685                         ch_size>3?((const uint8_t *)buf_ptr)[3]:'?',
686                 xml_tag, tcv);
687
688                 /* Skip the extensions section */
689                 if(ctx->phase == 4) {
690                         ASN_DEBUG("skip_unknown(%d, %ld)",
691                                 tcv, (long)ctx->left);
692                         switch(xer_skip_unknown(tcv, &ctx->left)) {
693                         case -1:
694                                 ctx->phase = 5;
695                                 RETURN(RC_FAIL);
696                         case 1:
697                                 ctx->phase = 3;
698                                 /* Fall through */
699                         case 0:
700                                 XER_ADVANCE(ch_size);
701                                 continue;
702                         case 2:
703                                 ctx->phase = 3;
704                                 break;
705                         }
706                 }
707
708                 switch(tcv) {
709                 case XCT_BOTH:
710                         break;  /* No CHOICE? */
711                 case XCT_CLOSING:
712                         if(ctx->phase != 3)
713                                 break;
714                         XER_ADVANCE(ch_size);
715                         ctx->phase = 5; /* Phase out */
716                         RETURN(RC_OK);
717                 case XCT_OPENING:
718                         if(ctx->phase == 0) {
719                                 XER_ADVANCE(ch_size);
720                                 ctx->phase = 1; /* Processing body phase */
721                                 continue;
722                         }
723                         /* Fall through */
724                 case XCT_UNKNOWN_OP:
725                 case XCT_UNKNOWN_BO:
726
727                         if(ctx->phase != 1)
728                                 break;  /* Really unexpected */
729
730                         /*
731                          * Search which inner member corresponds to this tag.
732                          */
733                         for(edx = 0; edx < td->elements_count; edx++) {
734                                 elm = &td->elements[edx];
735                                 tcv = xer_check_tag(buf_ptr,ch_size,elm->name);
736                                 switch(tcv) {
737                                 case XCT_BOTH:
738                                 case XCT_OPENING:
739                                         /*
740                                          * Process this member.
741                                          */
742                                         ctx->step = edx;
743                                         ctx->phase = 2;
744                                         break;
745                                 case XCT_UNKNOWN_OP:
746                                 case XCT_UNKNOWN_BO:
747                                         continue;
748                                 default:
749                                         edx = td->elements_count;
750                                         break;  /* Phase out */
751                                 }
752                                 break;
753                         }
754                         if(edx != td->elements_count)
755                                 continue;
756
757                         /* It is expected extension */
758                         if(specs->ext_start != -1) {
759                                 ASN_DEBUG("Got anticipated extension");
760                                 /*
761                                  * Check for (XCT_BOTH or XCT_UNKNOWN_BO)
762                                  * By using a mask. Only record a pure
763                                  * <opening> tags.
764                                  */
765                                 if(tcv & XCT_CLOSING) {
766                                         /* Found </extension> without body */
767                                         ctx->phase = 3; /* Terminating */
768                                 } else {
769                                         ctx->left = 1;
770                                         ctx->phase = 4; /* Skip ...'s */
771                                 }
772                                 XER_ADVANCE(ch_size);
773                                 continue;
774                         }
775
776                         /* Fall through */
777                 default:
778                         break;
779                 }
780
781                 ASN_DEBUG("Unexpected XML tag [%c%c%c%c] in CHOICE [%s]"
782                         " (ph=%d, tag=%s)",
783                         ch_size>0?((const uint8_t *)buf_ptr)[0]:'?',
784                         ch_size>1?((const uint8_t *)buf_ptr)[1]:'?',
785                         ch_size>2?((const uint8_t *)buf_ptr)[2]:'?',
786                         ch_size>3?((const uint8_t *)buf_ptr)[3]:'?',
787                         td->name, ctx->phase, xml_tag);
788                 break;
789         }
790
791         ctx->phase = 5; /* Phase out, just in case */
792         RETURN(RC_FAIL);
793 }
794
795
796 asn_enc_rval_t
797 CHOICE_encode_xer(const asn_TYPE_descriptor_t *td, const void *sptr, int ilevel,
798                   enum xer_encoder_flags_e flags, asn_app_consume_bytes_f *cb,
799                   void *app_key) {
800         const asn_CHOICE_specifics_t *specs =
801                 (const asn_CHOICE_specifics_t *)td->specifics;
802         asn_enc_rval_t er = {0,0,0};
803         unsigned present = 0;
804
805         if(!sptr)
806                 ASN__ENCODE_FAILED;
807
808         /*
809          * Figure out which CHOICE element is encoded.
810          */
811         present = _fetch_present_idx(sptr, specs->pres_offset,specs->pres_size);
812
813         if(present == 0 || present > td->elements_count) {
814                 ASN__ENCODE_FAILED;
815         }  else {
816                 asn_enc_rval_t tmper = {0,0,0};
817                 asn_TYPE_member_t *elm = &td->elements[present-1];
818                 const void *memb_ptr = NULL;
819                 const char *mname = elm->name;
820                 unsigned int mlen = strlen(mname);
821
822                 if(elm->flags & ATF_POINTER) {
823             memb_ptr =
824                 *(const void *const *)((const char *)sptr + elm->memb_offset);
825             if(!memb_ptr) ASN__ENCODE_FAILED;
826                 } else {
827             memb_ptr = (const void *)((const char *)sptr + elm->memb_offset);
828         }
829
830         er.encoded = 0;
831
832                 if(!(flags & XER_F_CANONICAL)) ASN__TEXT_INDENT(1, ilevel);
833                 ASN__CALLBACK3("<", 1, mname, mlen, ">", 1);
834
835                 tmper = elm->type->op->xer_encoder(elm->type, memb_ptr,
836                                 ilevel + 1, flags, cb, app_key);
837                 if(tmper.encoded == -1) return tmper;
838                 er.encoded += tmper.encoded;
839
840                 ASN__CALLBACK3("</", 2, mname, mlen, ">", 1);
841         }
842
843         if(!(flags & XER_F_CANONICAL)) ASN__TEXT_INDENT(1, ilevel - 1);
844
845         ASN__ENCODED_OK(er);
846 cb_failed:
847         ASN__ENCODE_FAILED;
848 }
849
850 asn_dec_rval_t
851 CHOICE_decode_uper(const asn_codec_ctx_t *opt_codec_ctx,
852                    const asn_TYPE_descriptor_t *td,
853                    const asn_per_constraints_t *constraints, void **sptr,
854                    asn_per_data_t *pd) {
855     const asn_CHOICE_specifics_t *specs =
856         (const asn_CHOICE_specifics_t *)td->specifics;
857     asn_dec_rval_t rv;
858         const asn_per_constraint_t *ct;
859         asn_TYPE_member_t *elm; /* CHOICE's element */
860         void *memb_ptr;
861         void **memb_ptr2;
862         void *st = *sptr;
863         int value;
864
865         if(ASN__STACK_OVERFLOW_CHECK(opt_codec_ctx))
866                 ASN__DECODE_FAILED;
867
868         /*
869          * Create the target structure if it is not present already.
870          */
871         if(!st) {
872                 st = *sptr = CALLOC(1, specs->struct_size);
873                 if(!st) ASN__DECODE_FAILED;
874         }
875
876         if(constraints) ct = &constraints->value;
877         else if(td->encoding_constraints.per_constraints) ct = &td->encoding_constraints.per_constraints->value;
878         else ct = 0;
879
880         if(ct && ct->flags & APC_EXTENSIBLE) {
881                 value = per_get_few_bits(pd, 1);
882                 if(value < 0) ASN__DECODE_STARVED;
883                 if(value) ct = 0;       /* Not restricted */
884         }
885
886         if(ct && ct->range_bits >= 0) {
887                 value = per_get_few_bits(pd, ct->range_bits);
888                 if(value < 0) ASN__DECODE_STARVED;
889                 ASN_DEBUG("CHOICE %s got index %d in range %d",
890                         td->name, value, ct->range_bits);
891                 if(value > ct->upper_bound)
892                         ASN__DECODE_FAILED;
893         } else {
894                 if(specs->ext_start == -1)
895                         ASN__DECODE_FAILED;
896                 value = uper_get_nsnnwn(pd);
897                 if(value < 0) ASN__DECODE_STARVED;
898                 value += specs->ext_start;
899                 if((unsigned)value >= td->elements_count)
900                         ASN__DECODE_FAILED;
901         }
902
903         /* Adjust if canonical order is different from natural order */
904         if(specs->from_canonical_order) {
905         ASN_DEBUG("CHOICE presence from wire %d", value);
906                 value = specs->from_canonical_order[value];
907         ASN_DEBUG("CHOICE presence index effective %d", value);
908     }
909
910         /* Set presence to be able to free it later */
911         _set_present_idx(st, specs->pres_offset, specs->pres_size, value + 1);
912
913         elm = &td->elements[value];
914         if(elm->flags & ATF_POINTER) {
915                 /* Member is a pointer to another structure */
916                 memb_ptr2 = (void **)((char *)st + elm->memb_offset);
917         } else {
918                 memb_ptr = (char *)st + elm->memb_offset;
919                 memb_ptr2 = &memb_ptr;
920         }
921         ASN_DEBUG("Discovered CHOICE %s encodes %s", td->name, elm->name);
922
923         if(ct && ct->range_bits >= 0) {
924                 rv = elm->type->op->uper_decoder(opt_codec_ctx, elm->type,
925                         elm->encoding_constraints.per_constraints, memb_ptr2, pd);
926         } else {
927                 rv = uper_open_type_get(opt_codec_ctx, elm->type,
928                         elm->encoding_constraints.per_constraints, memb_ptr2, pd);
929         }
930
931         if(rv.code != RC_OK)
932                 ASN_DEBUG("Failed to decode %s in %s (CHOICE) %d",
933                         elm->name, td->name, rv.code);
934         return rv;
935 }
936
937 asn_enc_rval_t
938 CHOICE_encode_uper(const asn_TYPE_descriptor_t *td,
939                    const asn_per_constraints_t *constraints, const void *sptr,
940                    asn_per_outp_t *po) {
941         const asn_CHOICE_specifics_t *specs = (const asn_CHOICE_specifics_t *)td->specifics;
942         asn_TYPE_member_t *elm; /* CHOICE's element */
943         const asn_per_constraint_t *ct;
944         const void *memb_ptr;
945         unsigned present;
946         int present_enc;
947
948         if(!sptr) ASN__ENCODE_FAILED;
949
950         ASN_DEBUG("Encoding %s as CHOICE", td->name);
951
952         if(constraints) ct = &constraints->value;
953         else if(td->encoding_constraints.per_constraints)
954                 ct = &td->encoding_constraints.per_constraints->value;
955         else ct = 0;
956
957         present = _fetch_present_idx(sptr, specs->pres_offset, specs->pres_size);
958
959         /*
960          * If the structure was not initialized properly, it cannot be encoded:
961          * can't deduce what to encode in the choice type.
962          */
963         if(present == 0 || present > td->elements_count)
964                 ASN__ENCODE_FAILED;
965         else
966                 present--;
967
968         ASN_DEBUG("Encoding %s CHOICE element %d", td->name, present);
969
970     /* Adjust if canonical order is different from natural order */
971     if(specs->to_canonical_order)
972         present_enc = specs->to_canonical_order[present];
973     else
974         present_enc = present;
975
976     if(ct && ct->range_bits >= 0) {
977                 if(present_enc < ct->lower_bound
978                 || present_enc > ct->upper_bound) {
979                         if(ct->flags & APC_EXTENSIBLE) {
980                 ASN_DEBUG(
981                     "CHOICE member %d (enc %d) is an extension (%ld..%ld)",
982                     present, present_enc, ct->lower_bound, ct->upper_bound);
983                 if(per_put_few_bits(po, 1, 1))
984                                         ASN__ENCODE_FAILED;
985                         } else {
986                                 ASN__ENCODE_FAILED;
987                         }
988                         ct = 0;
989                 }
990         }
991         if(ct && ct->flags & APC_EXTENSIBLE) {
992         ASN_DEBUG("CHOICE member %d (enc %d) is not an extension (%ld..%ld)",
993                   present, present_enc, ct->lower_bound, ct->upper_bound);
994         if(per_put_few_bits(po, 0, 1))
995                         ASN__ENCODE_FAILED;
996     }
997
998
999         elm = &td->elements[present];
1000     ASN_DEBUG("CHOICE member \"%s\" %d (as %d)", elm->name, present,
1001               present_enc);
1002     if(elm->flags & ATF_POINTER) {
1003                 /* Member is a pointer to another structure */
1004         memb_ptr =
1005             *(const void *const *)((const char *)sptr + elm->memb_offset);
1006         if(!memb_ptr) ASN__ENCODE_FAILED;
1007         } else {
1008         memb_ptr = (const char *)sptr + elm->memb_offset;
1009     }
1010
1011     if(ct && ct->range_bits >= 0) {
1012         if(per_put_few_bits(po, present_enc, ct->range_bits))
1013             ASN__ENCODE_FAILED;
1014
1015         return elm->type->op->uper_encoder(
1016             elm->type, elm->encoding_constraints.per_constraints, memb_ptr, po);
1017     } else {
1018         asn_enc_rval_t rval = {0,0,0};
1019         if(specs->ext_start == -1) ASN__ENCODE_FAILED;
1020         if(uper_put_nsnnwn(po, present_enc - specs->ext_start))
1021             ASN__ENCODE_FAILED;
1022         if(uper_open_type_put(elm->type,
1023                               elm->encoding_constraints.per_constraints,
1024                               memb_ptr, po))
1025             ASN__ENCODE_FAILED;
1026         rval.encoded = 0;
1027         ASN__ENCODED_OK(rval);
1028     }
1029 }
1030
1031 asn_dec_rval_t
1032 CHOICE_decode_aper(const asn_codec_ctx_t *opt_codec_ctx,
1033                    const asn_TYPE_descriptor_t *td,
1034                    const asn_per_constraints_t *constraints, void **sptr, asn_per_data_t *pd) {
1035         const asn_CHOICE_specifics_t *specs = (const asn_CHOICE_specifics_t *)td->specifics;
1036         asn_dec_rval_t rv;
1037         const asn_per_constraint_t *ct;
1038         const asn_per_constraint_t *ext_ct = NULL;
1039         asn_TYPE_member_t *elm; /* CHOICE's element */
1040         void *memb_ptr;
1041         void **memb_ptr2;
1042         void *st = *sptr;
1043         int value;
1044
1045         if(ASN__STACK_OVERFLOW_CHECK(opt_codec_ctx))
1046                 ASN__DECODE_FAILED;
1047
1048         /*
1049          * Create the target structure if it is not present already.
1050          */
1051         if(!st) {
1052                 st = *sptr = CALLOC(1, specs->struct_size);
1053                 if(!st) ASN__DECODE_FAILED;
1054         }
1055
1056         if(constraints) ct = &constraints->value;
1057         else if(td->encoding_constraints.per_constraints)
1058                 ct = &td->encoding_constraints.per_constraints->value;
1059         else ct = 0;
1060
1061         if(ct && ct->flags & APC_EXTENSIBLE) {
1062                 value = per_get_few_bits(pd, 1);
1063                 if(value < 0) ASN__DECODE_STARVED;
1064                 if(value) {
1065                   ext_ct = ct;
1066                   ct = 0;       /* Not restricted */
1067                 }
1068         }
1069
1070
1071         if(ct && ct->range_bits >= 0) {
1072                 value = per_get_few_bits(pd, ct->range_bits);
1073                 if(value < 0) ASN__DECODE_STARVED;
1074                 ASN_DEBUG("CHOICE %s got index %d in range %d",
1075                           td->name, value, ct->range_bits);
1076                 if(value > ct->upper_bound)
1077                         ASN__DECODE_FAILED;
1078         } else {
1079                 if(specs->ext_start == -1)
1080                         ASN__DECODE_FAILED;
1081                 value = aper_get_nsnnwn(pd, ext_ct->range_bits);
1082                 if(value < 0) ASN__DECODE_STARVED;
1083                 value += specs->ext_start;
1084                 if((unsigned)value >= td->elements_count)
1085                         ASN__DECODE_FAILED;
1086         }
1087
1088         /* Adjust if canonical order is different from natural order */
1089         if(specs->from_canonical_order)
1090                 value = specs->from_canonical_order[value];
1091
1092         /* Set presence to be able to free it later */
1093         _set_present_idx(st, specs->pres_offset, specs->pres_size, value + 1);
1094
1095         elm = &td->elements[value];
1096         if(elm->flags & ATF_POINTER) {
1097                 /* Member is a pointer to another structure */
1098                 memb_ptr2 = (void **)((char *)st + elm->memb_offset);
1099         } else {
1100                 memb_ptr = (char *)st + elm->memb_offset;
1101                 memb_ptr2 = &memb_ptr;
1102         }
1103         ASN_DEBUG("Discovered CHOICE %s encodes %s", td->name, elm->name);
1104
1105         if(ct && ct->range_bits >= 0) {
1106                 rv = elm->type->op->aper_decoder(opt_codec_ctx, elm->type,
1107                                                  elm->encoding_constraints.per_constraints, memb_ptr2, pd);
1108         } else {
1109                 rv = aper_open_type_get(opt_codec_ctx, elm->type,
1110                                         elm->encoding_constraints.per_constraints, memb_ptr2, pd);
1111         }
1112
1113         if(rv.code != RC_OK)
1114                 ASN_DEBUG("Failed to decode %s in %s (CHOICE) %d",
1115                           elm->name, td->name, rv.code);
1116         return rv;
1117 }
1118
1119 asn_enc_rval_t
1120 CHOICE_encode_aper(const asn_TYPE_descriptor_t *td,
1121                    const asn_per_constraints_t *constraints,
1122                    const void *sptr, asn_per_outp_t *po) {
1123         const asn_CHOICE_specifics_t *specs = (const asn_CHOICE_specifics_t *)td->specifics;
1124         const asn_TYPE_member_t *elm; /* CHOICE's element */
1125         const asn_per_constraint_t *ct = NULL;
1126         const asn_per_constraint_t *ext_ct = NULL;
1127         const void *memb_ptr;
1128         unsigned present;
1129         int present_enc;
1130         
1131         if(!sptr) ASN__ENCODE_FAILED;
1132
1133         ASN_DEBUG("Encoding %s as CHOICE using ALIGNED PER", td->name);
1134
1135         if(constraints) ct = &constraints->value;
1136         else if(td->encoding_constraints.per_constraints)
1137                 ct = &td->encoding_constraints.per_constraints->value;
1138         else ct = NULL;
1139
1140         present = _fetch_present_idx(sptr,
1141                                      specs->pres_offset, specs->pres_size);
1142
1143         /*
1144          * If the structure was not initialized properly, it cannot be encoded:
1145          * can't deduce what to encode in the choice type.
1146          */
1147         if(present <= 0 || (unsigned)present > td->elements_count)
1148                 ASN__ENCODE_FAILED;
1149         else
1150                 present--;
1151
1152         /* Adjust if canonical order is different from natural order */
1153         if(specs->to_canonical_order)
1154                 present_enc = specs->to_canonical_order[present];
1155         else
1156                 present_enc = present;
1157         
1158         ASN_DEBUG("Encoding %s CHOICE element %d", td->name, present);
1159
1160         if(ct && (ct->range_bits >= 0)) {
1161           // Value is not within the range of the primary values ?
1162           if(present < ct->lower_bound || present > ct->upper_bound) {
1163             if(ct->flags & APC_EXTENSIBLE) {
1164               ASN_DEBUG("CHOICE member %d (enc %d) is an extension (%ld..%ld)",
1165                         present, present_enc, ct->lower_bound, ct->upper_bound);
1166               // X691/23.5 Extension marker = 1 
1167               if(per_put_few_bits(po, 1, 1)) {
1168                 ASN__ENCODE_FAILED;
1169               }
1170             } else {
1171               ASN__ENCODE_FAILED;
1172             }
1173             // no more need of constraint.
1174             ext_ct = ct;
1175             ct = NULL;
1176           }
1177         }
1178         
1179         if(ct && (ct->flags & APC_EXTENSIBLE)) {
1180           ASN_DEBUG("CHOICE member %d (enc %d) is not an extension (%ld..%ld)",
1181                     present, present, ct->lower_bound, ct->upper_bound);
1182           // X691.23.5 Extension marker = 0
1183           if(per_put_few_bits(po, 0, 1)) {
1184             ASN__ENCODE_FAILED;
1185           }
1186         }
1187
1188         elm = &td->elements[present];
1189         if(elm->flags & ATF_POINTER) {
1190                 /* Member is a pointer to another structure */
1191                 memb_ptr = *(const void *const *)((const char *)sptr + elm->memb_offset);
1192                 if(!memb_ptr) ASN__ENCODE_FAILED;
1193         } else {
1194                 memb_ptr = (const char *)sptr + elm->memb_offset;
1195         }
1196
1197         if(ct && (ct->range_bits >= 0)) {
1198                 // By construction (ct != 0), the alternative value is a non extended one.
1199                 // X691/23.7 X691/23.6 alternative value encoded as a range_bits bits value.
1200                 if(per_put_few_bits(po, present_enc, ct->range_bits))
1201                         ASN__ENCODE_FAILED;
1202
1203                 return elm->type->op->aper_encoder(elm->type, elm->encoding_constraints.per_constraints,
1204                                                    memb_ptr, po);
1205         } else {
1206                 asn_enc_rval_t rval = {0,0,0};
1207                 if(specs->ext_start == -1)
1208                         ASN__ENCODE_FAILED;
1209                 // X691/23.8 normally encoded as a small non negative whole number
1210                 
1211                 if(ext_ct && aper_put_nsnnwn(po, ext_ct->range_bits, present_enc - specs->ext_start))
1212                         ASN__ENCODE_FAILED;
1213                 if(aper_open_type_put(elm->type, elm->encoding_constraints.per_constraints,
1214                                       memb_ptr, po))
1215                         ASN__ENCODE_FAILED;
1216                 rval.encoded = 0;
1217                 ASN__ENCODED_OK(rval);
1218         }
1219 }
1220
1221 int
1222 CHOICE_print(const asn_TYPE_descriptor_t *td, const void *sptr, int ilevel,
1223              asn_app_consume_bytes_f *cb, void *app_key) {
1224     const asn_CHOICE_specifics_t *specs = (const asn_CHOICE_specifics_t *)td->specifics;
1225         unsigned present;
1226
1227         if(!sptr) return (cb("<absent>", 8, app_key) < 0) ? -1 : 0;
1228
1229         /*
1230          * Figure out which CHOICE element is encoded.
1231          */
1232         present = _fetch_present_idx(sptr, specs->pres_offset,specs->pres_size);
1233
1234         /*
1235          * Print that element.
1236          */
1237         if(present > 0 && present <= td->elements_count) {
1238                 asn_TYPE_member_t *elm = &td->elements[present-1];
1239                 const void *memb_ptr;
1240
1241                 if(elm->flags & ATF_POINTER) {
1242                         memb_ptr = *(const void * const *)((const char *)sptr + elm->memb_offset);
1243                         if(!memb_ptr) return (cb("<absent>", 8, app_key) < 0) ? -1 : 0;
1244                 } else {
1245                         memb_ptr = (const void *)((const char *)sptr + elm->memb_offset);
1246                 }
1247
1248                 /* Print member's name and stuff */
1249                 if(0) {
1250                         if(cb(elm->name, strlen(elm->name), app_key) < 0
1251                         || cb(": ", 2, app_key) < 0)
1252                                 return -1;
1253                 }
1254
1255                 return elm->type->op->print_struct(elm->type, memb_ptr, ilevel,
1256                         cb, app_key);
1257         } else {
1258                 return (cb("<absent>", 8, app_key) < 0) ? -1 : 0;
1259         }
1260 }
1261
1262 void
1263 CHOICE_free(const asn_TYPE_descriptor_t *td, void *ptr,
1264             enum asn_struct_free_method method) {
1265     const asn_CHOICE_specifics_t *specs =
1266         (const asn_CHOICE_specifics_t *)td->specifics;
1267     unsigned present;
1268
1269         if(!td || !ptr)
1270                 return;
1271
1272         ASN_DEBUG("Freeing %s as CHOICE", td->name);
1273
1274         /*
1275          * Figure out which CHOICE element is encoded.
1276          */
1277         present = _fetch_present_idx(ptr, specs->pres_offset, specs->pres_size);
1278
1279         /*
1280          * Free that element.
1281          */
1282         if(present > 0 && present <= td->elements_count) {
1283                 asn_TYPE_member_t *elm = &td->elements[present-1];
1284                 void *memb_ptr;
1285
1286                 if(elm->flags & ATF_POINTER) {
1287                         memb_ptr = *(void **)((char *)ptr + elm->memb_offset);
1288                         if(memb_ptr)
1289                                 ASN_STRUCT_FREE(*elm->type, memb_ptr);
1290                 } else {
1291                         memb_ptr = (void *)((char *)ptr + elm->memb_offset);
1292                         ASN_STRUCT_FREE_CONTENTS_ONLY(*elm->type, memb_ptr);
1293                 }
1294         }
1295
1296     switch(method) {
1297     case ASFM_FREE_EVERYTHING:
1298         FREEMEM(ptr);
1299         break;
1300     case ASFM_FREE_UNDERLYING:
1301         break;
1302     case ASFM_FREE_UNDERLYING_AND_RESET:
1303         memset(ptr, 0, specs->struct_size);
1304         break;
1305     }
1306 }
1307
1308
1309 /*
1310  * The following functions functions offer protection against -fshort-enums,
1311  * compatible with little- and big-endian machines.
1312  * If assertion is triggered, either disable -fshort-enums, or add an entry
1313  * here with the ->pres_size of your target stracture.
1314  * Unless the target structure is packed, the ".present" member
1315  * is guaranteed to be aligned properly. ASN.1 compiler itself does not
1316  * produce packed code.
1317  */
1318 static unsigned
1319 _fetch_present_idx(const void *struct_ptr, unsigned pres_offset,
1320                    unsigned pres_size) {
1321     const void *present_ptr;
1322         unsigned present;
1323
1324         present_ptr = ((const char *)struct_ptr) + pres_offset;
1325
1326         switch(pres_size) {
1327         case sizeof(int):       present = *(const unsigned int *)present_ptr; break;
1328         case sizeof(short):     present = *(const unsigned short *)present_ptr; break;
1329         case sizeof(char):      present = *(const unsigned char *)present_ptr; break;
1330         default:
1331                 /* ANSI C mandates enum to be equivalent to integer */
1332                 assert(pres_size != sizeof(int));
1333                 return 0;       /* If not aborted, pass back safe value */
1334         }
1335
1336         return present;
1337 }
1338
1339 static void
1340 _set_present_idx(void *struct_ptr, unsigned pres_offset, unsigned pres_size,
1341                  unsigned present) {
1342     void *present_ptr;
1343         present_ptr = ((char *)struct_ptr) + pres_offset;
1344
1345         switch(pres_size) {
1346         case sizeof(int):       *(unsigned int *)present_ptr   = present; break;
1347         case sizeof(short):     *(unsigned short *)present_ptr = present; break;
1348         case sizeof(char):      *(unsigned char *)present_ptr  = present; break;
1349         default:
1350                 /* ANSI C mandates enum to be equivalent to integer */
1351                 assert(pres_size != sizeof(int));
1352         }
1353 }
1354
1355 static const void *
1356 _get_member_ptr(const asn_TYPE_descriptor_t *td, const void *sptr,
1357                 asn_TYPE_member_t **elm_ptr, unsigned *present_out) {
1358     const asn_CHOICE_specifics_t *specs =
1359         (const asn_CHOICE_specifics_t *)td->specifics;
1360     unsigned present;
1361
1362     if(!sptr) {
1363         *elm_ptr = NULL;
1364         *present_out = 0;
1365         return NULL;
1366     }
1367
1368     /*
1369          * Figure out which CHOICE element is encoded.
1370          */
1371         present = _fetch_present_idx(sptr, specs->pres_offset, specs->pres_size);
1372     *present_out = present;
1373
1374     /*
1375      * The presence index is intentionally 1-based to avoid
1376      * treating zeroed structure as a valid one.
1377      */
1378         if(present > 0 && present <= td->elements_count) {
1379         asn_TYPE_member_t *const elm = &td->elements[present - 1];
1380         const void *memb_ptr;
1381
1382                 if(elm->flags & ATF_POINTER) {
1383             memb_ptr =
1384                 *(const void *const *)((const char *)sptr + elm->memb_offset);
1385         } else {
1386             memb_ptr = (const void *)((const char *)sptr + elm->memb_offset);
1387         }
1388         *elm_ptr = elm;
1389         return memb_ptr;
1390     } else {
1391         *elm_ptr = NULL;
1392         return NULL;
1393     }
1394
1395 }
1396
1397 int
1398 CHOICE_compare(const asn_TYPE_descriptor_t *td, const void *aptr, const void *bptr) {
1399     asn_TYPE_member_t *aelm;
1400     asn_TYPE_member_t *belm;
1401     unsigned apresent = 0;
1402     unsigned bpresent = 0;
1403     const void *amember = _get_member_ptr(td, aptr, &aelm, &apresent);
1404     const void *bmember = _get_member_ptr(td, bptr, &belm, &bpresent);
1405
1406     if(amember && bmember) {
1407         if(apresent == bpresent) {
1408             assert(aelm == belm);
1409             return aelm->type->op->compare_struct(aelm->type, amember, bmember);
1410         } else if(apresent < bpresent) {
1411             return -1;
1412         } else {
1413             return 1;
1414         }
1415     } else if(!amember) {
1416         return -1;
1417     } else {
1418         return 1;
1419     }
1420 }
1421
1422 /*
1423  * Return the 1-based choice variant presence index.
1424  * Returns 0 in case of error.
1425  */
1426 unsigned
1427 CHOICE_variant_get_presence(const asn_TYPE_descriptor_t *td, const void *sptr) {
1428     const asn_CHOICE_specifics_t *specs =
1429         (const asn_CHOICE_specifics_t *)td->specifics;
1430     return _fetch_present_idx(sptr, specs->pres_offset, specs->pres_size);
1431 }
1432
1433 /*
1434  * Sets or resets the 1-based choice variant presence index.
1435  * In case a previous index is not zero, the currently selected structure
1436  * member is freed and zeroed-out first.
1437  * Returns 0 on success and -1 on error.
1438  */
1439 int
1440 CHOICE_variant_set_presence(const asn_TYPE_descriptor_t *td, void *sptr,
1441                             unsigned present) {
1442     const asn_CHOICE_specifics_t *specs =
1443         (const asn_CHOICE_specifics_t *)td->specifics;
1444     unsigned old_present;
1445
1446     if(!sptr) {
1447         return -1;
1448     }
1449
1450     if(present > td->elements_count)
1451         return -1;
1452
1453     old_present =
1454         _fetch_present_idx(sptr, specs->pres_offset, specs->pres_size);
1455     if(present == old_present)
1456         return 0;
1457
1458     if(old_present != 0) {
1459         assert(old_present <= td->elements_count);
1460         ASN_STRUCT_RESET(*td, sptr);
1461     }
1462
1463     _set_present_idx(sptr, specs->pres_offset, specs->pres_size, present);
1464
1465     return 0;
1466 }
1467
1468
1469 asn_random_fill_result_t
1470 CHOICE_random_fill(const asn_TYPE_descriptor_t *td, void **sptr,
1471                    const asn_encoding_constraints_t *constr,
1472                    size_t max_length) {
1473     const asn_CHOICE_specifics_t *specs =
1474         (const asn_CHOICE_specifics_t *)td->specifics;
1475     asn_random_fill_result_t res;
1476     asn_random_fill_result_t result_failed = {ARFILL_FAILED, 0};
1477     asn_random_fill_result_t result_skipped = {ARFILL_SKIPPED, 0};
1478     const asn_TYPE_member_t *elm;
1479     unsigned present;
1480     void *memb_ptr;   /* Pointer to the member */
1481     void **memb_ptr2; /* Pointer to that pointer */
1482     void *st = *sptr;
1483
1484     if(max_length == 0) return result_skipped;
1485
1486     (void)constr;
1487
1488     if(st == NULL) {
1489         st = CALLOC(1, specs->struct_size);
1490         if(st == NULL) {
1491             return result_failed;
1492         }
1493     }
1494
1495     present = asn_random_between(1, td->elements_count);
1496     elm = &td->elements[present - 1];
1497
1498         if(elm->flags & ATF_POINTER) {
1499                 /* Member is a pointer to another structure */
1500                 memb_ptr2 = (void **)((char *)st + elm->memb_offset);
1501         } else {
1502                 memb_ptr = (char *)st + elm->memb_offset;
1503                 memb_ptr2 = &memb_ptr;
1504         }
1505
1506     res = elm->type->op->random_fill(elm->type, memb_ptr2,
1507                                     &elm->encoding_constraints, max_length);
1508     _set_present_idx(st, specs->pres_offset, specs->pres_size, present);
1509     if(res.code == ARFILL_OK) {
1510         *sptr = st;
1511     } else {
1512         if(st == *sptr) {
1513             ASN_STRUCT_RESET(*td, st);
1514         } else {
1515             ASN_STRUCT_FREE(*td, st);
1516         }
1517     }
1518
1519     return res;
1520 }
1521
1522
1523 asn_TYPE_operation_t asn_OP_CHOICE = {
1524         CHOICE_free,
1525         CHOICE_print,
1526         CHOICE_compare,
1527         CHOICE_decode_ber,
1528         CHOICE_encode_der,
1529         CHOICE_decode_xer,
1530         CHOICE_encode_xer,
1531 #ifdef  ASN_DISABLE_OER_SUPPORT
1532         0,
1533         0,
1534 #else
1535         CHOICE_decode_oer,
1536         CHOICE_encode_oer,
1537 #endif  /* ASN_DISABLE_OER_SUPPORT */
1538 #ifdef ASN_DISABLE_PER_SUPPORT
1539         0,
1540         0,
1541         0,
1542         0,
1543 #else
1544         CHOICE_decode_uper,
1545         CHOICE_encode_uper,
1546         CHOICE_decode_aper,
1547         CHOICE_encode_aper,
1548 #endif  /* ASN_DISABLE_PER_SUPPORT */
1549         CHOICE_random_fill,
1550         CHOICE_outmost_tag
1551 };