a1185e22acdbafc7e93a1cdf26443a97f8996581
[o-du/l2.git] / src / codec_utils / common / BIT_STRING.c
1 /*-
2  * Copyright (c) 2003, 2004 Lev Walkin <vlm@lionet.info>. All rights reserved.
3  * Redistribution and modifications are permitted subject to BSD license.
4  */
5 #include <asn_internal.h>
6 #include <BIT_STRING.h>
7 #include <asn_internal.h>
8
9 /*
10  * BIT STRING basic type description.
11  */
12 static const ber_tlv_tag_t asn_DEF_BIT_STRING_tags[] = {
13         (ASN_TAG_CLASS_UNIVERSAL | (3 << 2))
14 };
15 asn_OCTET_STRING_specifics_t asn_SPC_BIT_STRING_specs = {
16         sizeof(BIT_STRING_t),
17         offsetof(BIT_STRING_t, _asn_ctx),
18         ASN_OSUBV_BIT
19 };
20 asn_TYPE_operation_t asn_OP_BIT_STRING = {
21         OCTET_STRING_free,         /* Implemented in terms of OCTET STRING */
22         BIT_STRING_print,
23         BIT_STRING_compare,
24         OCTET_STRING_decode_ber,   /* Implemented in terms of OCTET STRING */
25         OCTET_STRING_encode_der,   /* Implemented in terms of OCTET STRING */
26         OCTET_STRING_decode_xer_binary,
27         BIT_STRING_encode_xer,
28 #ifdef  ASN_DISABLE_OER_SUPPORT
29         0,
30         0,
31 #else
32         BIT_STRING_decode_oer,
33         BIT_STRING_encode_oer,
34 #endif  /* ASN_DISABLE_OER_SUPPORT */
35 #ifdef  ASN_DISABLE_PER_SUPPORT
36         0,
37         0,
38         0,
39         0,
40 #else
41         BIT_STRING_decode_uper, /* Unaligned PER decoder */
42         BIT_STRING_encode_uper, /* Unaligned PER encoder */
43         OCTET_STRING_decode_aper,       /* Aligned PER decoder */
44         OCTET_STRING_encode_aper,       /* Aligned PER encoder */
45 #endif  /* ASN_DISABLE_PER_SUPPORT */
46         BIT_STRING_random_fill,
47         0       /* Use generic outmost tag fetcher */
48 };
49 asn_TYPE_descriptor_t asn_DEF_BIT_STRING = {
50         "BIT STRING",
51         "BIT_STRING",
52         &asn_OP_BIT_STRING,
53         asn_DEF_BIT_STRING_tags,
54         sizeof(asn_DEF_BIT_STRING_tags)
55           / sizeof(asn_DEF_BIT_STRING_tags[0]),
56         asn_DEF_BIT_STRING_tags,        /* Same as above */
57         sizeof(asn_DEF_BIT_STRING_tags)
58           / sizeof(asn_DEF_BIT_STRING_tags[0]),
59         { 0, 0, BIT_STRING_constraint },
60         0, 0,   /* No members */
61         &asn_SPC_BIT_STRING_specs
62 };
63
64 /*
65  * BIT STRING generic constraint.
66  */
67 int
68 BIT_STRING_constraint(const asn_TYPE_descriptor_t *td, const void *sptr,
69                       asn_app_constraint_failed_f *ctfailcb, void *app_key) {
70     const BIT_STRING_t *st = (const BIT_STRING_t *)sptr;
71        printf("Inside %s:%d\n", __FILE__,__LINE__);
72
73         if(st && st->buf) {
74                 if((st->size == 0 && st->bits_unused)
75                 || st->bits_unused < 0 || st->bits_unused > 7) {
76                         ASN__CTFAIL(app_key, td, sptr,
77                                 "%s: invalid padding byte (%s:%d)",
78                                 td->name, __FILE__, __LINE__);
79                         return -1;
80                 }
81         } else {
82                 ASN__CTFAIL(app_key, td, sptr,
83                         "%s: value not given (%s:%d)",
84                         td->name, __FILE__, __LINE__);
85                 return -1;
86         }
87
88         return 0;
89 }
90
91 static const char *_bit_pattern[16] = {
92         "0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111",
93         "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"
94 };
95
96 asn_enc_rval_t
97 BIT_STRING_encode_xer(const asn_TYPE_descriptor_t *td, const void *sptr,
98                       int ilevel, enum xer_encoder_flags_e flags,
99                       asn_app_consume_bytes_f *cb, void *app_key) {
100         asn_enc_rval_t er = {0, 0, 0};
101         char scratch[128];
102         char *p = scratch;
103         char *scend = scratch + (sizeof(scratch) - 10);
104         const BIT_STRING_t *st = (const BIT_STRING_t *)sptr;
105         int xcan = (flags & XER_F_CANONICAL);
106         uint8_t *buf;
107         uint8_t *end;
108
109         if(!st || !st->buf)
110                 ASN__ENCODE_FAILED;
111
112         er.encoded = 0;
113
114         buf = st->buf;
115         end = buf + st->size - 1;       /* Last byte is special */
116
117         /*
118          * Binary dump
119          */
120         for(; buf < end; buf++) {
121                 int v = *buf;
122                 int nline = xcan?0:(((buf - st->buf) % 8) == 0);
123                 if(p >= scend || nline) {
124                         ASN__CALLBACK(scratch, p - scratch);
125                         p = scratch;
126                         if(nline) ASN__TEXT_INDENT(1, ilevel);
127                 }
128                 memcpy(p + 0, _bit_pattern[v >> 4], 4);
129                 memcpy(p + 4, _bit_pattern[v & 0x0f], 4);
130                 p += 8;
131         }
132
133         if(!xcan && ((buf - st->buf) % 8) == 0)
134                 ASN__TEXT_INDENT(1, ilevel);
135         ASN__CALLBACK(scratch, p - scratch);
136         p = scratch;
137
138         if(buf == end) {
139                 int v = *buf;
140                 int ubits = st->bits_unused;
141                 int i;
142                 for(i = 7; i >= ubits; i--)
143                         *p++ = (v & (1 << i)) ? 0x31 : 0x30;
144                 ASN__CALLBACK(scratch, p - scratch);
145         }
146
147         if(!xcan) ASN__TEXT_INDENT(1, ilevel - 1);
148
149         ASN__ENCODED_OK(er);
150 cb_failed:
151         ASN__ENCODE_FAILED;
152 }
153
154
155 /*
156  * BIT STRING specific contents printer.
157  */
158 int
159 BIT_STRING_print(const asn_TYPE_descriptor_t *td, const void *sptr, int ilevel,
160                  asn_app_consume_bytes_f *cb, void *app_key) {
161     const char * const h2c = "0123456789ABCDEF";
162         char scratch[64];
163         const BIT_STRING_t *st = (const BIT_STRING_t *)sptr;
164         uint8_t *buf;
165         uint8_t *end;
166         char *p = scratch;
167
168         (void)td;       /* Unused argument */
169
170         if(!st || !st->buf)
171                 return (cb("<absent>", 8, app_key) < 0) ? -1 : 0;
172
173         ilevel++;
174         buf = st->buf;
175         end = buf + st->size;
176
177         /*
178          * Hexadecimal dump.
179          */
180         for(; buf < end; buf++) {
181                 if((buf - st->buf) % 16 == 0 && (st->size > 16)
182                                 && buf != st->buf) {
183                         _i_INDENT(1);
184                         /* Dump the string */
185                         if(cb(scratch, p - scratch, app_key) < 0) return -1;
186                         p = scratch;
187                 }
188                 *p++ = h2c[*buf >> 4];
189                 *p++ = h2c[*buf & 0x0F];
190                 *p++ = 0x20;
191         }
192
193         if(p > scratch) {
194                 p--;    /* Eat the tailing space */
195
196                 if((st->size > 16)) {
197                         _i_INDENT(1);
198                 }
199
200                 /* Dump the incomplete 16-bytes row */
201                 if(cb(scratch, p - scratch, app_key) < 0)
202                         return -1;
203         }
204
205     if(st->bits_unused) {
206         int ret = snprintf(scratch, sizeof(scratch), " (%d bit%s unused)",
207                            st->bits_unused, st->bits_unused == 1 ? "" : "s");
208         assert(ret > 0 && ret < (ssize_t)sizeof(scratch));
209         if(ret > 0 && ret < (ssize_t)sizeof(scratch)
210            && cb(scratch, ret, app_key) < 0)
211             return -1;
212     }
213
214         return 0;
215 }
216
217 /*
218  * Non-destructively remove the trailing 0-bits from the given bit string.
219  */
220 static const BIT_STRING_t *
221 BIT_STRING__compactify(const BIT_STRING_t *st, BIT_STRING_t *tmp) {
222     const uint8_t *b;
223     union {
224         const uint8_t *c_buf;
225         uint8_t *nc_buf;
226     } unconst;
227
228     if(st->size == 0) {
229         assert(st->bits_unused == 0);
230         return st;
231     } else {
232         for(b = &st->buf[st->size - 1]; b > st->buf && *b == 0; b--) {
233             ;
234         }
235         /* b points to the last byte which may contain data */
236         if(*b) {
237             int unused = 7;
238             uint8_t v = *b;
239             v &= -(int8_t)v;
240             if(v & 0x0F) unused -= 4;
241             if(v & 0x33) unused -= 2;
242             if(v & 0x55) unused -= 1;
243             tmp->size = b-st->buf + 1;
244             tmp->bits_unused = unused;
245         } else {
246             tmp->size = b-st->buf;
247             tmp->bits_unused = 0;
248         }
249
250         assert(b >= st->buf);
251     }
252
253     unconst.c_buf = st->buf;
254     tmp->buf = unconst.nc_buf;
255     return tmp;
256 }
257
258 /*
259  * Lexicographically compare the common prefix of both strings,
260  * and if it is the same return -1 for the smallest string.
261  */
262 int
263 BIT_STRING_compare(const asn_TYPE_descriptor_t *td, const void *aptr,
264                    const void *bptr) {
265     /*
266      * Remove information about trailing bits, since
267      * X.680 (08/2015) #22.7 "ensure that different semantics are not"
268      * "associated with [values that differ only in] the trailing 0 bits."
269      */
270     BIT_STRING_t compact_a, compact_b;
271     const BIT_STRING_t *a = BIT_STRING__compactify(aptr, &compact_a);
272     const BIT_STRING_t *b = BIT_STRING__compactify(bptr, &compact_b);
273     const asn_OCTET_STRING_specifics_t *specs = td->specifics;
274
275     assert(specs && specs->subvariant == ASN_OSUBV_BIT);
276
277     if(a && b) {
278         size_t common_prefix_size = a->size <= b->size ? a->size : b->size;
279         int ret = memcmp(a->buf, b->buf, common_prefix_size);
280         if(ret == 0) {
281             /* Figure out which string with equal prefixes is longer. */
282             if(a->size < b->size) {
283                 return -1;
284             } else if(a->size > b->size) {
285                 return 1;
286             } else {
287                 /* Figure out how many unused bits */
288                 if(a->bits_unused > b->bits_unused) {
289                     return -1;
290                 } else if(a->bits_unused < b->bits_unused) {
291                     return 1;
292                 } else {
293                     return 0;
294                 }
295             }
296         } else {
297             return ret;
298         }
299     } else if(!a && !b) {
300         return 0;
301     } else if(!a) {
302         return -1;
303     } else {
304         return 1;
305     }
306 }
307
308 #ifndef  ASN_DISABLE_PER_SUPPORT
309
310 #undef  RETURN
311 #define RETURN(_code)                       \
312     do {                                    \
313         asn_dec_rval_t tmprval;             \
314         tmprval.code = _code;               \
315         tmprval.consumed = consumed_myself; \
316         return tmprval;                     \
317     } while(0)
318
319 static asn_per_constraint_t asn_DEF_BIT_STRING_constraint_size = {
320     APC_SEMI_CONSTRAINED, -1, -1, 0, 0};
321
322 asn_dec_rval_t
323 BIT_STRING_decode_uper(const asn_codec_ctx_t *opt_codec_ctx,
324                        const asn_TYPE_descriptor_t *td,
325                        const asn_per_constraints_t *constraints, void **sptr,
326                        asn_per_data_t *pd) {
327     const asn_OCTET_STRING_specifics_t *specs = td->specifics
328                 ? (const asn_OCTET_STRING_specifics_t *)td->specifics
329                 : &asn_SPC_BIT_STRING_specs;
330     const asn_per_constraints_t *pc =
331         constraints ? constraints : td->encoding_constraints.per_constraints;
332         const asn_per_constraint_t *csiz;
333         asn_dec_rval_t rval = { RC_OK, 0 };
334         BIT_STRING_t *st = (BIT_STRING_t *)*sptr;
335         ssize_t consumed_myself = 0;
336         int repeat;
337
338         (void)opt_codec_ctx;
339
340         if(pc) {
341                 csiz = &pc->size;
342         } else {
343                 csiz = &asn_DEF_BIT_STRING_constraint_size;
344         }
345
346         if(specs->subvariant != ASN_OSUBV_BIT) {
347                 ASN_DEBUG("Subvariant %d is not BIT OSUBV_BIT", specs->subvariant);
348                 RETURN(RC_FAIL);
349     }
350
351         /*
352          * Allocate the string.
353          */
354         if(!st) {
355                 st = (BIT_STRING_t *)(*sptr = CALLOC(1, specs->struct_size));
356                 if(!st) RETURN(RC_FAIL);
357         }
358
359         ASN_DEBUG("PER Decoding %s size %ld .. %ld bits %d",
360                 csiz->flags & APC_EXTENSIBLE ? "extensible" : "non-extensible",
361                 csiz->lower_bound, csiz->upper_bound, csiz->effective_bits);
362
363         if(csiz->flags & APC_EXTENSIBLE) {
364                 int inext = per_get_few_bits(pd, 1);
365                 if(inext < 0) RETURN(RC_WMORE);
366                 if(inext) {
367                         csiz = &asn_DEF_BIT_STRING_constraint_size;
368                 }
369         }
370
371         if(csiz->effective_bits >= 0) {
372                 FREEMEM(st->buf);
373         st->size = (csiz->upper_bound + 7) >> 3;
374         st->buf = (uint8_t *)MALLOC(st->size + 1);
375                 if(!st->buf) { st->size = 0; RETURN(RC_FAIL); }
376         }
377
378         /* X.691, #16.5: zero-length encoding */
379         /* X.691, #16.6: short fixed length encoding (up to 2 octets) */
380         /* X.691, #16.7: long fixed length encoding (up to 64K octets) */
381         if(csiz->effective_bits == 0) {
382                 int ret;
383         ASN_DEBUG("Encoding BIT STRING size %ld", csiz->upper_bound);
384         ret = per_get_many_bits(pd, st->buf, 0, csiz->upper_bound);
385                 if(ret < 0) RETURN(RC_WMORE);
386                 consumed_myself += csiz->upper_bound;
387                 st->buf[st->size] = 0;
388         st->bits_unused = (8 - (csiz->upper_bound & 0x7)) & 0x7;
389         RETURN(RC_OK);
390         }
391
392         st->size = 0;
393         do {
394                 ssize_t raw_len;
395                 ssize_t len_bytes;
396                 ssize_t len_bits;
397                 void *p;
398                 int ret;
399
400                 /* Get the PER length */
401                 raw_len = uper_get_length(pd, csiz->effective_bits, csiz->lower_bound,
402                                           &repeat);
403                 if(raw_len < 0) RETURN(RC_WMORE);
404         if(raw_len == 0 && st->buf) break;
405
406                 ASN_DEBUG("Got PER length eb %ld, len %ld, %s (%s)",
407                         (long)csiz->effective_bits, (long)raw_len,
408                         repeat ? "repeat" : "once", td->name);
409         len_bits = raw_len;
410         len_bytes = (len_bits + 7) >> 3;
411         if(len_bits & 0x7) st->bits_unused = 8 - (len_bits & 0x7);
412         /* len_bits be multiple of 16K if repeat is set */
413         p = REALLOC(st->buf, st->size + len_bytes + 1);
414                 if(!p) RETURN(RC_FAIL);
415                 st->buf = (uint8_t *)p;
416
417         ret = per_get_many_bits(pd, &st->buf[st->size], 0, len_bits);
418         if(ret < 0) RETURN(RC_WMORE);
419                 st->size += len_bytes;
420         } while(repeat);
421         st->buf[st->size] = 0;  /* nul-terminate */
422
423         return rval;
424 }
425
426 asn_enc_rval_t
427 BIT_STRING_encode_uper(const asn_TYPE_descriptor_t *td,
428                        const asn_per_constraints_t *constraints,
429                        const void *sptr, asn_per_outp_t *po) {
430     const asn_OCTET_STRING_specifics_t *specs =
431         td->specifics ? (const asn_OCTET_STRING_specifics_t *)td->specifics
432                       : &asn_SPC_BIT_STRING_specs;
433     const asn_per_constraints_t *pc =
434         constraints ? constraints : td->encoding_constraints.per_constraints;
435         const asn_per_constraint_t *csiz;
436         const BIT_STRING_t *st = (const BIT_STRING_t *)sptr;
437         BIT_STRING_t compact_bstr;  /* Do not modify this directly! */
438         asn_enc_rval_t er = { 0, 0, 0 };
439         int inext = 0;          /* Lies not within extension root */
440         size_t size_in_bits;
441         const uint8_t *buf;
442         int ret;
443         int ct_extensible;
444
445         if(!st || (!st->buf && st->size))
446                 ASN__ENCODE_FAILED;
447
448         if(specs->subvariant == ASN_OSUBV_BIT) {
449         if((st->size == 0 && st->bits_unused) || (st->bits_unused & ~7))
450 {
451             ASN__ENCODE_FAILED;
452 }
453     } else {
454                 ASN__ENCODE_FAILED;
455     }
456
457         if(pc) {
458         csiz = &pc->size;
459     } else {
460                 csiz = &asn_DEF_BIT_STRING_constraint_size;
461         }
462         ct_extensible = csiz->flags & APC_EXTENSIBLE;
463
464     /* Figure out the size without the trailing bits */
465     st = BIT_STRING__compactify(st, &compact_bstr);
466     size_in_bits = 8 * st->size - st->bits_unused;
467
468     ASN_DEBUG(
469         "Encoding %s into %" ASN_PRI_SIZE " bits"
470         " (%ld..%ld, effective %d)%s",
471         td->name, size_in_bits, csiz->lower_bound, csiz->upper_bound,
472         csiz->effective_bits, ct_extensible ? " EXT" : "");
473
474     /* Figure out whether size lies within PER visible constraint */
475
476     if(csiz->effective_bits >= 0) {
477         if((ssize_t)size_in_bits > csiz->upper_bound) {
478             if(ct_extensible) {
479                 csiz = &asn_DEF_BIT_STRING_constraint_size;
480                 inext = 1;
481             } else {
482         printf("Inside bit string endocde %s:%d\n", __FILE__, __LINE__);
483                 ASN__ENCODE_FAILED;
484             }
485         }
486     } else {
487         inext = 0;
488     }
489
490     if(ct_extensible) {
491                 /* Declare whether length is [not] within extension root */
492                 if(per_put_few_bits(po, inext, 1))
493 {
494         printf("Inside bit string endocde %s:%d\n", __FILE__, __LINE__);
495                         ASN__ENCODE_FAILED;
496 }
497         }
498
499     if(csiz->effective_bits >= 0 && !inext) {
500         int add_trailer = (ssize_t)size_in_bits < csiz->lower_bound;
501         ASN_DEBUG(
502             "Encoding %" ASN_PRI_SIZE " bytes (%ld), length (in %d bits) trailer %d; actual "
503             "value %" ASN_PRI_SSIZE "",
504             st->size, size_in_bits - csiz->lower_bound, csiz->effective_bits,
505             add_trailer,
506             add_trailer ? 0 : (ssize_t)size_in_bits - csiz->lower_bound);
507         ret = per_put_few_bits(
508             po, add_trailer ? 0 : (ssize_t)size_in_bits - csiz->lower_bound,
509             csiz->effective_bits);
510         if(ret) 
511 {
512         printf("Inside bit string endocde %s:%d\n", __FILE__, __LINE__);
513 ASN__ENCODE_FAILED;
514 }
515         ret = per_put_many_bits(po, st->buf, size_in_bits);
516         if(ret) 
517 {
518         printf("Inside bit string endocde %s:%d\n", __FILE__, __LINE__);
519 ASN__ENCODE_FAILED;
520 }
521         if(add_trailer) {
522             static const uint8_t zeros[16];
523             size_t trailing_zero_bits = csiz->lower_bound - size_in_bits;
524             while(trailing_zero_bits > 0) {
525                 if(trailing_zero_bits > 8 * sizeof(zeros)) {
526                     ret = per_put_many_bits(po, zeros, 8 * sizeof(zeros));
527                     trailing_zero_bits -= 8 * sizeof(zeros);
528                 } else {
529                     ret = per_put_many_bits(po, zeros, trailing_zero_bits);
530                     trailing_zero_bits = 0;
531                 }
532         if(ret) 
533 {
534         printf("Inside bit string endocde %s:%d\n", __FILE__, __LINE__);
535 ASN__ENCODE_FAILED;
536 }
537             }
538         }
539         ASN__ENCODED_OK(er);
540     }
541
542     ASN_DEBUG("Encoding %" ASN_PRI_SIZE " bytes", st->size);
543
544     buf = st->buf;
545     do {
546         int need_eom = 0;
547         ssize_t maySave = uper_put_length(po, size_in_bits, &need_eom);
548         if(maySave < 0) 
549 {
550         printf("Inside bit string endocde %s:%d\n", __FILE__, __LINE__);
551 ASN__ENCODE_FAILED;
552 }
553
554         ASN_DEBUG("Encoding %" ASN_PRI_SSIZE " of %" ASN_PRI_SIZE "", maySave, size_in_bits);
555
556         ret = per_put_many_bits(po, buf, maySave);
557         if(ret) 
558 {
559         printf("Inside bit string endocde %s:%d\n", __FILE__, __LINE__);
560 ASN__ENCODE_FAILED;
561 }
562
563         buf += maySave >> 3;
564         size_in_bits -= maySave;
565         assert(!(maySave & 0x07) || !size_in_bits);
566         if(need_eom && uper_put_length(po, 0, 0))
567 {
568         printf("Inside bit string endocde %s:%d\n", __FILE__, __LINE__);
569             ASN__ENCODE_FAILED; /* End of Message length */
570 }
571     } while(size_in_bits);
572
573     ASN__ENCODED_OK(er);
574 }
575
576 #endif  /* ASN_DISABLE_PER_SUPPORT */
577
578 asn_random_fill_result_t
579 BIT_STRING_random_fill(const asn_TYPE_descriptor_t *td, void **sptr,
580                        const asn_encoding_constraints_t *constraints,
581                        size_t max_length) {
582     const asn_OCTET_STRING_specifics_t *specs =
583         td->specifics ? (const asn_OCTET_STRING_specifics_t *)td->specifics
584                       : &asn_SPC_BIT_STRING_specs;
585     asn_random_fill_result_t result_ok = {ARFILL_OK, 1};
586     asn_random_fill_result_t result_failed = {ARFILL_FAILED, 0};
587     asn_random_fill_result_t result_skipped = {ARFILL_SKIPPED, 0};
588     static unsigned lengths[] = {0,     1,     2,     3,     4,     8,
589                                  126,   127,   128,   16383, 16384, 16385,
590                                  65534, 65535, 65536, 65537};
591     uint8_t *buf;
592     uint8_t *bend;
593     uint8_t *b;
594     size_t rnd_bits, rnd_len;
595     BIT_STRING_t *st;
596
597     if(max_length == 0) return result_skipped;
598
599     switch(specs->subvariant) {
600     case ASN_OSUBV_ANY:
601         return result_failed;
602     case ASN_OSUBV_BIT:
603         break;
604     default:
605         break;
606     }
607
608     /* Figure out how far we should go */
609     rnd_bits = lengths[asn_random_between(
610         0, sizeof(lengths) / sizeof(lengths[0]) - 1)];
611     if(!constraints || !constraints->per_constraints)
612         constraints = &td->encoding_constraints;
613     if(constraints->per_constraints) {
614         const asn_per_constraint_t *pc = &constraints->per_constraints->size;
615         if(pc->flags & APC_CONSTRAINED) {
616             long suggested_upper_bound = pc->upper_bound < (ssize_t)max_length
617                                              ? pc->upper_bound
618                                              : (ssize_t)max_length;
619             if(max_length < (size_t)pc->lower_bound) {
620                 return result_skipped;
621             }
622             if(pc->flags & APC_EXTENSIBLE) {
623                 switch(asn_random_between(0, 5)) {
624                 case 0:
625                     if(pc->lower_bound > 0) {
626                         rnd_bits = pc->lower_bound - 1;
627                         break;
628                     }
629                     /* Fall through */
630                 case 1:
631                     rnd_bits = pc->upper_bound + 1;
632                     break;
633                 case 2:
634                     /* Keep rnd_bits from the table */
635                     if(rnd_bits < max_length) {
636                         break;
637                     }
638                     /* Fall through */
639                 default:
640                     rnd_bits = asn_random_between(pc->lower_bound,
641                                                   suggested_upper_bound);
642                 }
643             } else {
644                 rnd_bits =
645                     asn_random_between(pc->lower_bound, suggested_upper_bound);
646             }
647         } else {
648             rnd_bits = asn_random_between(0, max_length - 1);
649         }
650     } else if(rnd_bits >= max_length) {
651         rnd_bits = asn_random_between(0, max_length - 1);
652     }
653
654     rnd_len = (rnd_bits + 7) / 8;
655     buf = CALLOC(1, rnd_len + 1);
656     if(!buf) return result_failed;
657
658     bend = &buf[rnd_len];
659
660     for(b = buf; b < bend; b++) {
661         *(uint8_t *)b = asn_random_between(0, 255);
662     }
663     *b = 0; /* Zero-terminate just in case. */
664
665     if(*sptr) {
666         st = *sptr;
667         FREEMEM(st->buf);
668     } else {
669         st = (BIT_STRING_t *)(*sptr = CALLOC(1, specs->struct_size));
670         if(!st) {
671             FREEMEM(buf);
672             return result_failed;
673         }
674     }
675
676     st->buf = buf;
677     st->size = rnd_len;
678     st->bits_unused = (8 - (rnd_bits & 0x7)) & 0x7;
679     if(st->bits_unused) {
680         assert(st->size > 0);
681         st->buf[st->size-1] &= 0xff << st->bits_unused;
682     }
683
684     result_ok.length = st->size;
685     return result_ok;
686 }