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