2 * Copyright (c) 2003-2014 Lev Walkin <vlm@lionet.info>.
4 * Redistribution and modifications are permitted subject to BSD license.
6 #include <asn_internal.h>
8 #include <asn_codecs_prim.h> /* Encoder and decoder of a primitive type */
12 * INTEGER basic type description.
14 static const ber_tlv_tag_t asn_DEF_INTEGER_tags[] = {
15 (ASN_TAG_CLASS_UNIVERSAL | (2 << 2))
17 asn_TYPE_operation_t asn_OP_INTEGER = {
25 #ifdef ASN_DISABLE_OER_SUPPORT
29 INTEGER_decode_oer, /* OER decoder */
30 INTEGER_encode_oer, /* Canonical OER encoder */
31 #endif /* ASN_DISABLE_OER_SUPPORT */
32 #ifdef ASN_DISABLE_PER_SUPPORT
38 INTEGER_decode_uper, /* Unaligned PER decoder */
39 INTEGER_encode_uper, /* Unaligned PER encoder */
40 INTEGER_decode_aper, /* Aligned PER decoder */
41 INTEGER_encode_aper, /* Aligned PER encoder */
42 #endif /* ASN_DISABLE_PER_SUPPORT */
44 0 /* Use generic outmost tag fetcher */
46 asn_TYPE_descriptor_t asn_DEF_INTEGER = {
51 sizeof(asn_DEF_INTEGER_tags) / sizeof(asn_DEF_INTEGER_tags[0]),
52 asn_DEF_INTEGER_tags, /* Same as above */
53 sizeof(asn_DEF_INTEGER_tags) / sizeof(asn_DEF_INTEGER_tags[0]),
54 { 0, 0, asn_generic_no_constraint },
55 0, 0, /* No members */
60 * Encode INTEGER type using DER.
63 INTEGER_encode_der(const asn_TYPE_descriptor_t *td, const void *sptr,
64 int tag_mode, ber_tlv_tag_t tag, asn_app_consume_bytes_f *cb,
66 const INTEGER_t *st = (const INTEGER_t *)sptr;
68 INTEGER_t effective_integer;
70 ASN_DEBUG("%s %s as INTEGER (tm=%d)",
71 cb?"Encoding":"Estimating", td->name, tag_mode);
74 * Canonicalize integer in the buffer.
75 * (Remove too long sign extension, remove some first 0x00 bytes)
78 uint8_t *buf = st->buf;
79 uint8_t *end1 = buf + st->size - 1;
82 /* Compute the number of superfluous leading bytes */
83 for(; buf < end1; buf++) {
85 * If the contents octets of an integer value encoding
86 * consist of more than one octet, then the bits of the
87 * first octet and bit 8 of the second octet:
88 * a) shall not all be ones; and
89 * b) shall not all be zero.
92 case 0x00: if((buf[1] & 0x80) == 0)
95 case 0xff: if((buf[1] & 0x80))
102 /* Remove leading superfluous bytes from the integer */
103 shift = buf - st->buf;
106 const uint8_t *c_buf;
109 unconst.c_buf = st->buf;
110 effective_integer.buf = unconst.nc_buf + shift;
111 effective_integer.size = st->size - shift;
113 st = &effective_integer;
117 rval = der_encode_primitive(td, st, tag_mode, tag, cb, app_key);
118 if(rval.structure_ptr == &effective_integer) {
119 rval.structure_ptr = sptr;
124 static const asn_INTEGER_enum_map_t *INTEGER_map_enum2value(
125 const asn_INTEGER_specifics_t *specs, const char *lstart,
129 * INTEGER specific human-readable output.
132 INTEGER__dump(const asn_TYPE_descriptor_t *td, const INTEGER_t *st, asn_app_consume_bytes_f *cb, void *app_key, int plainOrXER) {
133 const asn_INTEGER_specifics_t *specs =
134 (const asn_INTEGER_specifics_t *)td->specifics;
136 uint8_t *buf = st->buf;
137 uint8_t *buf_end = st->buf + st->size;
143 if(specs && specs->field_unsigned)
144 ret = asn_INTEGER2umax(st, (uintmax_t *)&value);
146 ret = asn_INTEGER2imax(st, &value);
148 /* Simple case: the integer size is small */
150 const asn_INTEGER_enum_map_t *el;
151 el = (value >= 0 || !specs || !specs->field_unsigned)
152 ? INTEGER_map_value2enum(specs, value) : 0;
155 return asn__format_to_callback(cb, app_key,
156 "%" ASN_PRIdMAX " (%s)", value, el->enum_name);
158 return asn__format_to_callback(cb, app_key,
159 "<%s/>", el->enum_name);
160 } else if(plainOrXER && specs && specs->strict_enumeration) {
161 ASN_DEBUG("ASN.1 forbids dealing with "
162 "unknown value of ENUMERATED type");
166 return asn__format_to_callback(cb, app_key,
167 (specs && specs->field_unsigned)
172 } else if(plainOrXER && specs && specs->strict_enumeration) {
174 * Here and earlier, we cannot encode the ENUMERATED values
175 * if there is no corresponding identifier.
177 ASN_DEBUG("ASN.1 forbids dealing with "
178 "unknown value of ENUMERATED type");
183 /* Output in the long xx:yy:zz... format */
184 /* TODO: replace with generic algorithm (Knuth TAOCP Vol 2, 4.3.1) */
185 for(p = scratch; buf < buf_end; buf++) {
186 const char * const h2c = "0123456789ABCDEF";
187 if((p - scratch) >= (ssize_t)(sizeof(scratch) - 4)) {
189 if(cb(scratch, p - scratch, app_key) < 0)
191 wrote += p - scratch;
194 *p++ = h2c[*buf >> 4];
195 *p++ = h2c[*buf & 0x0F];
196 *p++ = 0x3a; /* ":" */
199 p--; /* Remove the last ":" */
201 wrote += p - scratch;
202 return (cb(scratch, p - scratch, app_key) < 0) ? -1 : wrote;
206 * INTEGER specific human-readable output.
209 INTEGER_print(const asn_TYPE_descriptor_t *td, const void *sptr, int ilevel,
210 asn_app_consume_bytes_f *cb, void *app_key) {
211 const INTEGER_t *st = (const INTEGER_t *)sptr;
217 ret = cb("<absent>", 8, app_key);
219 ret = INTEGER__dump(td, st, cb, app_key, 0);
221 return (ret < 0) ? -1 : 0;
227 const asn_INTEGER_enum_map_t *vemap;
228 const unsigned int *evmap;
231 INTEGER__compar_enum2value(const void *kp, const void *am) {
232 const struct e2v_key *key = (const struct e2v_key *)kp;
233 const asn_INTEGER_enum_map_t *el = (const asn_INTEGER_enum_map_t *)am;
234 const char *ptr, *end, *name;
236 /* Remap the element (sort by different criterion) */
237 el = key->vemap + key->evmap[el - key->vemap];
239 /* Compare strings */
240 for(ptr = key->start, end = key->stop, name = el->enum_name;
241 ptr < end; ptr++, name++) {
242 if(*ptr != *name || !*name)
243 return *(const unsigned char *)ptr
244 - *(const unsigned char *)name;
246 return name[0] ? -1 : 0;
249 static const asn_INTEGER_enum_map_t *
250 INTEGER_map_enum2value(const asn_INTEGER_specifics_t *specs, const char *lstart,
252 const asn_INTEGER_enum_map_t *el_found;
253 int count = specs ? specs->map_count : 0;
257 if(!count) return NULL;
259 /* Guaranteed: assert(lstart < lstop); */
260 /* Figure out the tag name */
261 for(lstart++, lp = lstart; lp < lstop; lp++) {
263 case 9: case 10: case 11: case 12: case 13: case 32: /* WSP */
264 case 0x2f: /* '/' */ case 0x3e: /* '>' */
271 if(lp == lstop) return NULL; /* No tag found */
276 key.vemap = specs->value2enum;
277 key.evmap = specs->enum2value;
278 el_found = (asn_INTEGER_enum_map_t *)bsearch(&key,
279 specs->value2enum, count, sizeof(specs->value2enum[0]),
280 INTEGER__compar_enum2value);
282 /* Remap enum2value into value2enum */
283 el_found = key.vemap + key.evmap[el_found - key.vemap];
289 INTEGER__compar_value2enum(const void *kp, const void *am) {
290 long a = *(const long *)kp;
291 const asn_INTEGER_enum_map_t *el = (const asn_INTEGER_enum_map_t *)am;
292 long b = el->nat_value;
294 else if(a == b) return 0;
298 const asn_INTEGER_enum_map_t *
299 INTEGER_map_value2enum(const asn_INTEGER_specifics_t *specs, long value) {
300 int count = specs ? specs->map_count : 0;
302 return (asn_INTEGER_enum_map_t *)bsearch(&value, specs->value2enum,
303 count, sizeof(specs->value2enum[0]),
304 INTEGER__compar_value2enum);
308 INTEGER_st_prealloc(INTEGER_t *st, int min_size) {
309 void *p = MALLOC(min_size + 1);
322 * Decode the chunk of XML text encoding INTEGER.
324 static enum xer_pbd_rval
325 INTEGER__xer_body_decode(const asn_TYPE_descriptor_t *td, void *sptr,
326 const void *chunk_buf, size_t chunk_size) {
327 const asn_INTEGER_specifics_t *specs =
328 (const asn_INTEGER_specifics_t *)td->specifics;
329 INTEGER_t *st = (INTEGER_t *)sptr;
331 intmax_t hex_value = 0;
333 const char *lstart = (const char *)chunk_buf;
334 const char *lstop = lstart + chunk_size;
340 ST_DIGITS_TRAILSPACE,
343 ST_HEXDIGITS_TRAILSPACE,
347 } state = ST_LEADSPACE;
348 const char *dec_value_start = 0; /* INVARIANT: always !0 in ST_DIGITS */
349 const char *dec_value_end = 0;
352 ASN_DEBUG("INTEGER body %ld 0x%2x..0x%2x",
353 (long)chunk_size, *lstart, lstop[-1]);
355 if(INTEGER_st_prealloc(st, (chunk_size/3) + 1))
356 return XPBD_SYSTEM_FAILURE;
359 * We may have received a tag here. It will be processed inline.
360 * Use strtoul()-like code and serialize the result.
362 for(lp = lstart; lp < lstop; lp++) {
365 case 0x09: case 0x0a: case 0x0d: case 0x20:
368 case ST_DIGITS_TRAILSPACE:
369 case ST_HEXDIGITS_TRAILSPACE:
374 state = ST_DIGITS_TRAILSPACE;
377 state = ST_HEXDIGITS_TRAILSPACE;
384 if(state == ST_LEADSPACE) {
386 dec_value_start = lp;
387 state = ST_WAITDIGITS;
392 if(state == ST_LEADSPACE) {
394 dec_value_start = lp;
395 state = ST_WAITDIGITS;
399 case 0x30: case 0x31: case 0x32: case 0x33: case 0x34:
400 case 0x35: case 0x36: case 0x37: case 0x38: case 0x39:
402 case ST_DIGITS: continue;
403 case ST_SKIPSPHEX: /* Fall through */
405 hex_value = (lv - 0x30) << 4;
406 state = ST_HEXDIGIT2;
409 hex_value += (lv - 0x30);
411 st->buf[st->size++] = (uint8_t)hex_value;
414 return XPBD_BROKEN_ENCODING;
417 dec_value_start = lp;
426 case 0x3c: /* '<', start of XML encoded enumeration */
427 if(state == ST_LEADSPACE) {
428 const asn_INTEGER_enum_map_t *el;
429 el = INTEGER_map_enum2value(
430 (const asn_INTEGER_specifics_t *)
431 td->specifics, lstart, lstop);
433 ASN_DEBUG("Found \"%s\" => %ld",
434 el->enum_name, el->nat_value);
435 dec_value = el->nat_value;
440 ASN_DEBUG("Unknown identifier for INTEGER");
442 return XPBD_BROKEN_ENCODING;
444 if(state == ST_HEXCOLON) {
445 /* This colon is expected */
446 state = ST_HEXDIGIT1;
448 } else if(state == ST_DIGITS) {
449 /* The colon here means that we have
450 * decoded the first two hexadecimal
451 * places as a decimal value.
452 * Switch decoding mode. */
453 ASN_DEBUG("INTEGER re-evaluate as hex form");
454 state = ST_SKIPSPHEX;
459 ASN_DEBUG("state %d at %ld", state, (long)(lp - lstart));
463 case 0x41:case 0x42:case 0x43:case 0x44:case 0x45:case 0x46:
464 case 0x61:case 0x62:case 0x63:case 0x64:case 0x65:case 0x66:
467 case ST_LEADSPACE: /* Fall through */
469 hex_value = lv - ((lv < 0x61) ? 0x41 : 0x61);
472 state = ST_HEXDIGIT2;
475 hex_value += lv - ((lv < 0x61) ? 0x41 : 0x61);
477 st->buf[st->size++] = (uint8_t)hex_value;
481 ASN_DEBUG("INTEGER re-evaluate as hex form");
482 state = ST_SKIPSPHEX;
492 /* Found extra non-numeric stuff */
493 ASN_DEBUG("INTEGER :: Found non-numeric 0x%2x at %ld",
494 lv, (long)(lp - lstart));
495 state = ST_UNEXPECTED;
501 /* Got a complete and valid enumeration encoded as a tag. */
504 dec_value_end = lstop;
506 case ST_DIGITS_TRAILSPACE:
507 /* The last symbol encountered was a digit. */
508 switch(asn_strtoimax_lim(dec_value_start, &dec_value_end, &dec_value)) {
510 if(specs && specs->field_unsigned && (uintmax_t) dec_value <= ULONG_MAX) {
512 } else if(dec_value >= LONG_MIN && dec_value <= LONG_MAX) {
516 * We model INTEGER on long for XER,
517 * to avoid rewriting all the tests at once.
519 ASN_DEBUG("INTEGER exceeds long range");
522 case ASN_STRTOX_ERROR_RANGE:
523 ASN_DEBUG("INTEGER decode %s hit range limit", td->name);
524 return XPBD_DECODER_LIMIT;
525 case ASN_STRTOX_ERROR_INVAL:
526 case ASN_STRTOX_EXPECT_MORE:
527 case ASN_STRTOX_EXTRA_DATA:
528 return XPBD_BROKEN_ENCODING;
532 case ST_HEXDIGITS_TRAILSPACE:
533 st->buf[st->size] = 0; /* Just in case termination */
534 return XPBD_BODY_CONSUMED;
538 return XPBD_BROKEN_ENCODING;
540 /* Content not found */
541 return XPBD_NOT_BODY_IGNORE;
544 ASN_DEBUG("INTEGER: No useful digits (state %d)", state);
545 return XPBD_BROKEN_ENCODING; /* No digits */
549 * Convert the result of parsing of enumeration or a straight
550 * decimal value into a BER representation.
552 if(asn_imax2INTEGER(st, dec_value)) {
553 ASN_DEBUG("INTEGER decode %s conversion failed", td->name);
554 return XPBD_SYSTEM_FAILURE;
557 return XPBD_BODY_CONSUMED;
561 INTEGER_decode_xer(const asn_codec_ctx_t *opt_codec_ctx,
562 const asn_TYPE_descriptor_t *td, void **sptr,
563 const char *opt_mname, const void *buf_ptr, size_t size) {
564 return xer_decode_primitive(opt_codec_ctx, td,
565 sptr, sizeof(INTEGER_t), opt_mname,
566 buf_ptr, size, INTEGER__xer_body_decode);
570 INTEGER_encode_xer(const asn_TYPE_descriptor_t *td, const void *sptr,
571 int ilevel, enum xer_encoder_flags_e flags,
572 asn_app_consume_bytes_f *cb, void *app_key) {
573 const INTEGER_t *st = (const INTEGER_t *)sptr;
574 asn_enc_rval_t er = {0,0,0};
582 er.encoded = INTEGER__dump(td, st, cb, app_key, 1);
583 if(er.encoded < 0) ASN__ENCODE_FAILED;
588 #ifndef ASN_DISABLE_PER_SUPPORT
591 INTEGER_decode_uper(const asn_codec_ctx_t *opt_codec_ctx,
592 const asn_TYPE_descriptor_t *td,
593 const asn_per_constraints_t *constraints, void **sptr,
594 asn_per_data_t *pd) {
595 const asn_INTEGER_specifics_t *specs =
596 (const asn_INTEGER_specifics_t *)td->specifics;
597 asn_dec_rval_t rval = { RC_OK, 0 };
598 INTEGER_t *st = (INTEGER_t *)*sptr;
599 const asn_per_constraint_t *ct;
605 st = (INTEGER_t *)(*sptr = CALLOC(1, sizeof(*st)));
606 if(!st) ASN__DECODE_FAILED;
609 if(!constraints) constraints = td->encoding_constraints.per_constraints;
610 ct = constraints ? &constraints->value : 0;
612 if(ct && ct->flags & APC_EXTENSIBLE) {
613 int inext = per_get_few_bits(pd, 1);
614 if(inext < 0) ASN__DECODE_STARVED;
622 if(ct->flags & APC_SEMI_CONSTRAINED) {
623 st->buf = (uint8_t *)CALLOC(1, 2);
624 if(!st->buf) ASN__DECODE_FAILED;
626 } else if(ct->flags & APC_CONSTRAINED && ct->range_bits >= 0) {
627 size_t size = (ct->range_bits + 7) >> 3;
628 st->buf = (uint8_t *)MALLOC(1 + size + 1);
629 if(!st->buf) ASN__DECODE_FAILED;
634 /* X.691-2008/11, #13.2.2, constrained whole number */
635 if(ct && ct->flags != APC_UNCONSTRAINED) {
637 ASN_DEBUG("Integer with range %d bits", ct->range_bits);
638 if(ct->range_bits >= 0) {
639 if((size_t)ct->range_bits > 8 * sizeof(unsigned long))
642 if(specs && specs->field_unsigned) {
643 unsigned long uvalue = 0;
644 if(uper_get_constrained_whole_number(pd,
645 &uvalue, ct->range_bits))
647 ASN_DEBUG("Got value %lu + low %ld",
648 uvalue, ct->lower_bound);
649 uvalue += ct->lower_bound;
650 if(asn_ulong2INTEGER(st, uvalue))
653 unsigned long uvalue = 0;
655 if(uper_get_constrained_whole_number(pd,
656 &uvalue, ct->range_bits))
658 ASN_DEBUG("Got value %lu + low %ld",
659 uvalue, ct->lower_bound);
660 if(per_long_range_unrebase(uvalue, ct->lower_bound,
661 ct->upper_bound, &svalue)
662 || asn_long2INTEGER(st, svalue)) {
669 ASN_DEBUG("Decoding unconstrained integer %s", td->name);
672 /* X.691, #12.2.3, #12.2.4 */
678 /* Get the PER length */
679 len = uper_get_length(pd, -1, 0, &repeat);
680 if(len < 0) ASN__DECODE_STARVED;
682 p = REALLOC(st->buf, st->size + len + 1);
683 if(!p) ASN__DECODE_FAILED;
684 st->buf = (uint8_t *)p;
686 ret = per_get_many_bits(pd, &st->buf[st->size], 0, 8 * len);
687 if(ret < 0) ASN__DECODE_STARVED;
690 st->buf[st->size] = 0; /* JIC */
693 if(ct && ct->lower_bound) {
695 * TODO: replace by in-place arithmetics.
698 if(asn_INTEGER2long(st, &value))
700 if(asn_imax2INTEGER(st, value + ct->lower_bound))
708 INTEGER_encode_uper(const asn_TYPE_descriptor_t *td,
709 const asn_per_constraints_t *constraints, const void *sptr,
710 asn_per_outp_t *po) {
711 const asn_INTEGER_specifics_t *specs =
712 (const asn_INTEGER_specifics_t *)td->specifics;
713 asn_enc_rval_t er = {0,0,0};
714 const INTEGER_t *st = (const INTEGER_t *)sptr;
717 const asn_per_constraint_t *ct;
720 if(!st || st->size == 0) ASN__ENCODE_FAILED;
722 if(!constraints) constraints = td->encoding_constraints.per_constraints;
723 ct = constraints ? &constraints->value : 0;
729 if(specs && specs->field_unsigned) {
731 if(asn_INTEGER2ulong(st, &uval))
733 /* Check proper range */
734 if(ct->flags & APC_SEMI_CONSTRAINED) {
735 if(uval < (unsigned long)ct->lower_bound)
737 } else if(ct->range_bits >= 0) {
738 if(uval < (unsigned long)ct->lower_bound
739 || uval > (unsigned long)ct->upper_bound)
742 ASN_DEBUG("Value %lu (%02x/%" ASN_PRI_SIZE ") lb %lu ub %lu %s",
743 uval, st->buf[0], st->size,
744 ct->lower_bound, ct->upper_bound,
745 inext ? "ext" : "fix");
748 if(asn_INTEGER2long(st, &value))
750 /* Check proper range */
751 if(ct->flags & APC_SEMI_CONSTRAINED) {
752 if(value < ct->lower_bound)
754 } else if(ct->range_bits >= 0) {
755 if(value < ct->lower_bound
756 || value > ct->upper_bound)
759 ASN_DEBUG("Value %ld (%02x/%" ASN_PRI_SIZE ") lb %ld ub %ld %s",
760 value, st->buf[0], st->size,
761 ct->lower_bound, ct->upper_bound,
762 inext ? "ext" : "fix");
764 if(ct->flags & APC_EXTENSIBLE) {
765 if(per_put_few_bits(po, inext, 1))
774 /* X.691-11/2008, #13.2.2, test if constrained whole number */
775 if(ct && ct->range_bits >= 0) {
777 /* #11.5.6 -> #11.3 */
778 ASN_DEBUG("Encoding integer %ld (%lu) with range %d bits",
779 value, value - ct->lower_bound, ct->range_bits);
780 if(specs && specs->field_unsigned) {
781 if ( ((unsigned long)ct->lower_bound > (unsigned long)(ct->upper_bound)
782 || ((unsigned long)value < (unsigned long)ct->lower_bound))
783 || ((unsigned long)value > (unsigned long)ct->upper_bound)
785 ASN_DEBUG("Value %lu to-be-encoded is outside the bounds [%lu, %lu]!",
786 value, ct->lower_bound, ct->upper_bound);
789 v = (unsigned long)value - (unsigned long)ct->lower_bound;
791 if(per_long_range_rebase(value, ct->lower_bound, ct->upper_bound, &v)) {
795 if(uper_put_constrained_whole_number_u(po, v, ct->range_bits))
800 if(ct && ct->lower_bound) {
801 ASN_DEBUG("Adjust lower bound to %ld", ct->lower_bound);
802 /* TODO: adjust lower bound */
806 for(buf = st->buf, end = st->buf + st->size; buf < end;) {
808 ssize_t mayEncode = uper_put_length(po, end - buf, &need_eom);
811 if(per_put_many_bits(po, buf, 8 * mayEncode))
814 if(need_eom && uper_put_length(po, 0, 0)) ASN__ENCODE_FAILED;
821 INTEGER_decode_aper(const asn_codec_ctx_t *opt_codec_ctx,
822 const asn_TYPE_descriptor_t *td,
823 const asn_per_constraints_t *constraints, void **sptr, asn_per_data_t *pd) {
824 const asn_INTEGER_specifics_t *specs = (const asn_INTEGER_specifics_t *)td->specifics;
825 asn_dec_rval_t rval = { RC_OK, 0 };
826 INTEGER_t *st = (INTEGER_t *)*sptr;
827 const asn_per_constraint_t *ct;
833 st = (INTEGER_t *)(*sptr = CALLOC(1, sizeof(*st)));
834 if(!st) ASN__DECODE_FAILED;
837 if(!constraints) constraints = td->encoding_constraints.per_constraints;
838 ct = constraints ? &constraints->value : 0;
840 if(ct && ct->flags & APC_EXTENSIBLE) {
841 int inext = per_get_few_bits(pd, 1);
842 if(inext < 0) ASN__DECODE_STARVED;
850 if(ct->flags & APC_SEMI_CONSTRAINED) {
851 st->buf = (uint8_t *)CALLOC(1, 2);
852 if(!st->buf) ASN__DECODE_FAILED;
854 } else if(ct->flags & APC_CONSTRAINED && ct->range_bits >= 0) {
855 size_t size = (ct->range_bits + 7) >> 3;
856 st->buf = (uint8_t *)MALLOC(1 + size + 1);
857 if(!st->buf) ASN__DECODE_FAILED;
863 if(ct && ct->flags != APC_UNCONSTRAINED) {
865 ASN_DEBUG("Integer with range %d bits", ct->range_bits);
866 if(ct->range_bits >= 0) {
867 if (ct->range_bits > 16) {
868 int max_range_bytes = (ct->range_bits >> 3) +
869 (((ct->range_bits % 8) > 0) ? 1 : 0);
875 if (upper >= max_range_bytes)
878 ASN_DEBUG("Can encode %d (%d bytes) in %d bits", ct->range_bits,
881 if ((length = per_get_few_bits(pd, i)) < 0)
884 /* X.691 #12.2.6 length determinant + lb (1) */
886 ASN_DEBUG("Got length %d", length);
887 if (aper_get_align(pd) != 0)
890 int buf = per_get_few_bits(pd, 8);
893 value += (((long)buf) << (8 * length));
896 value += ct->lower_bound;
897 if((specs && specs->field_unsigned)
898 ? asn_uint642INTEGER(st, (unsigned long)value)
899 : asn_int642INTEGER(st, value))
901 ASN_DEBUG("Got value %ld + low %ld",
902 value, ct->lower_bound);
905 if (ct->range_bits < 8) {
906 value = per_get_few_bits(pd, ct->range_bits);
907 if(value < 0) ASN__DECODE_STARVED;
908 } else if (ct->range_bits == 8) {
909 if (aper_get_align(pd) < 0)
911 value = per_get_few_bits(pd, ct->range_bits);
912 if(value < 0) ASN__DECODE_STARVED;
915 if (aper_get_align(pd) < 0)
917 value = per_get_few_bits(pd, 16);
918 if(value < 0) ASN__DECODE_STARVED;
920 value += ct->lower_bound;
921 if((specs && specs->field_unsigned)
922 ? asn_ulong2INTEGER(st, value)
923 : asn_long2INTEGER(st, value))
925 ASN_DEBUG("Got value %ld + low %ld",
926 value, ct->lower_bound);
933 ASN_DEBUG("Decoding unconstrained integer %s", td->name);
936 /* X.691, #12.2.3, #12.2.4 */
942 /* Get the PER length */
943 len = aper_get_length(pd, -1, -1, &repeat);
944 if(len < 0) ASN__DECODE_STARVED;
946 p = REALLOC(st->buf, st->size + len + 1);
947 if(!p) ASN__DECODE_FAILED;
948 st->buf = (uint8_t *)p;
950 ret = per_get_many_bits(pd, &st->buf[st->size], 0, 8 * len);
951 if(ret < 0) ASN__DECODE_STARVED;
954 st->buf[st->size] = 0; /* JIC */
957 if(ct && ct->lower_bound) {
959 * TODO: replace by in-place arithmetics.
962 if(asn_INTEGER2long(st, &value))
964 if(asn_long2INTEGER(st, value + ct->lower_bound))
972 INTEGER_encode_aper(const asn_TYPE_descriptor_t *td,
973 const asn_per_constraints_t *constraints,
974 const void *sptr, asn_per_outp_t *po) {
975 const asn_INTEGER_specifics_t *specs = (const asn_INTEGER_specifics_t *)td->specifics;
976 asn_enc_rval_t er = {0,0,0};
977 const INTEGER_t *st = (const INTEGER_t *)sptr;
980 const asn_per_constraint_t *ct;
983 if(!st || st->size == 0) ASN__ENCODE_FAILED;
985 if(!constraints) constraints = td->encoding_constraints.per_constraints;
986 ct = constraints ? &constraints->value : 0;
992 if(specs && specs->field_unsigned) {
994 if(asn_INTEGER2ulong(st, &uval))
996 /* Check proper range */
997 if(ct->flags & APC_SEMI_CONSTRAINED) {
998 if(uval < (unsigned long)ct->lower_bound)
1000 } else if(ct->range_bits >= 0) {
1001 if(uval < (unsigned long)ct->lower_bound
1002 || uval > (unsigned long)ct->upper_bound)
1005 ASN_DEBUG("Value %lu (%02x/%lu) lb %ld ub %ld %s",
1006 uval, st->buf[0], st->size,
1007 ct->lower_bound, ct->upper_bound,
1008 inext ? "ext" : "fix");
1011 if(asn_INTEGER2long(st, &value)) ASN__ENCODE_FAILED;
1012 /* Check proper range */
1013 if(ct->flags & APC_SEMI_CONSTRAINED) {
1014 if(value < ct->lower_bound)
1016 } else if(ct->range_bits >= 0) {
1017 if(value < ct->lower_bound
1018 || value > ct->upper_bound)
1021 ASN_DEBUG("Value %lu (%02x/%lu) lb %ld ub %ld %s",
1022 value, st->buf[0], st->size,
1023 ct->lower_bound, ct->upper_bound,
1024 inext ? "ext" : "fix");
1026 if(ct->flags & APC_EXTENSIBLE) {
1027 if(per_put_few_bits(po, inext, 1))
1035 /* X.691, #12.2.2 */
1036 if(ct && ct->range_bits >= 0) {
1040 ASN_DEBUG("Encoding integer %ld (%lu) with range %d bits",
1041 value, value - ct->lower_bound, ct->range_bits);
1043 v = value - ct->lower_bound;
1045 /* #12 <= 8 -> alignment ? */
1046 if (ct->range_bits < 8) {
1047 if(per_put_few_bits(po, 0x00 | v, ct->range_bits))
1049 } else if (ct->range_bits == 8) {
1050 if(aper_put_align(po) < 0)
1052 if(per_put_few_bits(po, 0x00 | v, ct->range_bits))
1054 } else if (ct->range_bits <= 16) {
1055 /* Consume the bytes to align on octet */
1056 if(aper_put_align(po) < 0)
1058 if(per_put_few_bits(po, 0x0000 | v,
1062 /* TODO: extend to >64 bits */
1065 int max_range_bytes = (ct->range_bits >> 3) +
1066 (((ct->range_bits % 8) > 0) ? 1 : 0);
1068 for (i = 1; ; i++) {
1070 if (upper >= max_range_bytes)
1074 for (j = sizeof(int64_t) -1; j != 0; j--) {
1076 val = v64 >> (j * 8);
1081 /* Putting length in the minimum number of bits ex: 5 = 3bits */
1082 if (per_put_few_bits(po, j, i))
1085 /* Consume the bits to align on octet */
1086 if (aper_put_align(po) < 0)
1089 for (i = 0; i <= j; i++) {
1090 if(per_put_few_bits(po, (v64 >> (8 * (j - i))) & 0xff, 8))
1094 ASN__ENCODED_OK(er);
1097 if(ct && ct->lower_bound) {
1098 ASN_DEBUG("Adjust lower bound to %ld", ct->lower_bound);
1099 /* TODO: adjust lower bound */
1103 for(buf = st->buf, end = st->buf + st->size; buf < end;) {
1104 ssize_t mayEncode = aper_put_length(po, -1, end - buf);
1107 if(per_put_many_bits(po, buf, 8 * mayEncode))
1112 ASN__ENCODED_OK(er);
1115 #endif /* ASN_DISABLE_PER_SUPPORT */
1118 asn__integer_convert(const uint8_t *b, const uint8_t *end) {
1121 /* Perform the sign initialization */
1122 /* Actually value = -(*b >> 7); gains nothing, yet unreadable! */
1124 value = (uintmax_t)(-1);
1129 /* Conversion engine */
1130 for(; b < end; b++) {
1131 value = (value << 8) | *b;
1138 asn_INTEGER2imax(const INTEGER_t *iptr, intmax_t *lptr) {
1142 /* Sanity checking */
1143 if(!iptr || !iptr->buf || !lptr) {
1148 /* Cache the begin/end of the buffer */
1149 b = iptr->buf; /* Start of the INTEGER buffer */
1151 end = b + size; /* Where to stop */
1153 if(size > sizeof(intmax_t)) {
1154 uint8_t *end1 = end - 1;
1156 * Slightly more advanced processing,
1157 * able to process INTEGERs with >sizeof(intmax_t) bytes
1158 * when the actual value is small, e.g. for intmax_t == int32_t
1159 * (0x0000000000abcdef INTEGER would yield a fine 0x00abcdef int32_t)
1161 /* Skip out the insignificant leading bytes */
1162 for(; b < end1; b++) {
1164 case 0x00: if((b[1] & 0x80) == 0) continue; break;
1165 case 0xff: if((b[1] & 0x80) != 0) continue; break;
1171 if(size > sizeof(intmax_t)) {
1172 /* Still cannot fit the sizeof(intmax_t) */
1178 /* Shortcut processing of a corner case */
1184 *lptr = asn__integer_convert(b, end);
1188 /* FIXME: negative INTEGER values are silently interpreted as large unsigned ones. */
1190 asn_INTEGER2umax(const INTEGER_t *iptr, uintmax_t *lptr) {
1195 if(!iptr || !iptr->buf || !lptr) {
1204 /* If all extra leading bytes are zeroes, ignore them */
1205 for(; size > sizeof(value); b++, size--) {
1207 /* Value won't fit into uintmax_t */
1213 /* Conversion engine */
1214 for(value = 0; b < end; b++)
1215 value = (value << 8) | *b;
1222 asn_umax2INTEGER(INTEGER_t *st, uintmax_t value) {
1228 if(value <= ((~(uintmax_t)0) >> 1)) {
1229 return asn_imax2INTEGER(st, value);
1232 buf = (uint8_t *)MALLOC(1 + sizeof(value));
1235 end = buf + (sizeof(value) + 1);
1236 buf[0] = 0; /* INTEGERs are signed. 0-byte indicates positive. */
1237 for(b = buf + 1, shr = (sizeof(value) - 1) * 8; b < end; shr -= 8, b++)
1238 *b = (uint8_t)(value >> shr);
1240 if(st->buf) FREEMEM(st->buf);
1242 st->size = 1 + sizeof(value);
1248 asn_imax2INTEGER(INTEGER_t *st, intmax_t value) {
1253 int littleEndian = 1; /* Run-time detection */
1261 buf = (uint8_t *)(long *)MALLOC(sizeof(value));
1264 if(*(char *)&littleEndian) {
1265 pstart = (uint8_t *)&value + sizeof(value) - 1;
1266 pend1 = (uint8_t *)&value;
1269 pstart = (uint8_t *)&value;
1270 pend1 = pstart + sizeof(value) - 1;
1275 * If the contents octet consists of more than one octet,
1276 * then bits of the first octet and bit 8 of the second octet:
1277 * a) shall not all be ones; and
1278 * b) shall not all be zero.
1280 for(p = pstart; p != pend1; p += add) {
1282 case 0x00: if((*(p+add) & 0x80) == 0)
1285 case 0xff: if((*(p+add) & 0x80))
1291 /* Copy the integer body */
1292 for(bp = buf, pend1 += add; p != pend1; p += add)
1295 if(st->buf) FREEMEM(st->buf);
1297 st->size = bp - buf;
1303 asn_INTEGER2long(const INTEGER_t *iptr, long *l) {
1305 if(asn_INTEGER2imax(iptr, &v) == 0) {
1306 if(v < LONG_MIN || v > LONG_MAX) {
1318 asn_INTEGER2ulong(const INTEGER_t *iptr, unsigned long *l) {
1320 if(asn_INTEGER2umax(iptr, &v) == 0) {
1333 asn_long2INTEGER(INTEGER_t *st, long value) {
1334 return asn_imax2INTEGER(st, value);
1338 asn_ulong2INTEGER(INTEGER_t *st, unsigned long value) {
1339 return asn_imax2INTEGER(st, value);
1344 asn_uint642INTEGER(INTEGER_t *st, uint64_t value) {
1350 if(value <= INT64_MAX)
1351 return asn_int642INTEGER(st, value);
1353 buf = (uint8_t *)MALLOC(1 + sizeof(value));
1356 end = buf + (sizeof(value) + 1);
1358 for(b = buf + 1, shr = (sizeof(value)-1)*8; b < end; shr -= 8, b++)
1359 *b = (uint8_t)(value >> shr);
1361 if(st->buf) FREEMEM(st->buf);
1363 st->size = 1 + sizeof(value);
1369 asn_int642INTEGER(INTEGER_t *st, int64_t value) {
1374 int littleEndian = 1; /* Run-time detection */
1382 buf = (uint8_t *)MALLOC(sizeof(value));
1385 if(*(char *)&littleEndian) {
1386 pstart = (uint8_t *)&value + sizeof(value) - 1;
1387 pend1 = (uint8_t *)&value;
1390 pstart = (uint8_t *)&value;
1391 pend1 = pstart + sizeof(value) - 1;
1396 * If the contents octet consists of more than one octet,
1397 * then bits of the first octet and bit 8 of the second octet:
1398 * a) shall not all be ones; and
1399 * b) shall not all be zero.
1401 for(p = pstart; p != pend1; p += add) {
1403 case 0x00: if((*(p+add) & 0x80) == 0)
1406 case 0xff: if((*(p+add) & 0x80))
1412 /* Copy the integer body */
1413 for(pstart = p, bp = buf, pend1 += add; p != pend1; p += add)
1416 if(st->buf) FREEMEM(st->buf);
1418 st->size = bp - buf;
1424 * Parse the number in the given string until the given *end position,
1425 * returning the position after the last parsed character back using the
1426 * same (*end) pointer.
1427 * WARNING: This behavior is different from the standard strtol/strtoimax(3).
1429 enum asn_strtox_result_e
1430 asn_strtoimax_lim(const char *str, const char **end, intmax_t *intp) {
1434 #define ASN1_INTMAX_MAX ((~(uintmax_t)0) >> 1)
1435 const intmax_t upper_boundary = ASN1_INTMAX_MAX / 10;
1436 intmax_t last_digit_max = ASN1_INTMAX_MAX % 10;
1437 #undef ASN1_INTMAX_MAX
1439 if(str >= *end) return ASN_STRTOX_ERROR_INVAL;
1450 return ASN_STRTOX_EXPECT_MORE;
1454 for(value = 0; str < (*end); str++) {
1456 case 0x30: case 0x31: case 0x32: case 0x33: case 0x34:
1457 case 0x35: case 0x36: case 0x37: case 0x38: case 0x39: {
1459 if(value < upper_boundary) {
1460 value = value * 10 + d;
1461 } else if(value == upper_boundary) {
1462 if(d <= last_digit_max) {
1464 value = value * 10 + d;
1467 value = -value * 10 - d;
1471 return ASN_STRTOX_ERROR_RANGE;
1475 return ASN_STRTOX_ERROR_RANGE;
1481 *intp = sign * value;
1482 return ASN_STRTOX_EXTRA_DATA;
1487 *intp = sign * value;
1488 return ASN_STRTOX_OK;
1492 * Parse the number in the given string until the given *end position,
1493 * returning the position after the last parsed character back using the
1494 * same (*end) pointer.
1495 * WARNING: This behavior is different from the standard strtoul/strtoumax(3).
1497 enum asn_strtox_result_e
1498 asn_strtoumax_lim(const char *str, const char **end, uintmax_t *uintp) {
1501 #define ASN1_UINTMAX_MAX ((~(uintmax_t)0))
1502 const uintmax_t upper_boundary = ASN1_UINTMAX_MAX / 10;
1503 uintmax_t last_digit_max = ASN1_UINTMAX_MAX % 10;
1504 #undef ASN1_UINTMAX_MAX
1506 if(str >= *end) return ASN_STRTOX_ERROR_INVAL;
1510 return ASN_STRTOX_ERROR_INVAL;
1515 return ASN_STRTOX_EXPECT_MORE;
1519 for(value = 0; str < (*end); str++) {
1521 case 0x30: case 0x31: case 0x32: case 0x33: case 0x34:
1522 case 0x35: case 0x36: case 0x37: case 0x38: case 0x39: {
1523 unsigned int d = *str - '0';
1524 if(value < upper_boundary) {
1525 value = value * 10 + d;
1526 } else if(value == upper_boundary) {
1527 if(d <= last_digit_max) {
1528 value = value * 10 + d;
1531 return ASN_STRTOX_ERROR_RANGE;
1535 return ASN_STRTOX_ERROR_RANGE;
1542 return ASN_STRTOX_EXTRA_DATA;
1548 return ASN_STRTOX_OK;
1551 enum asn_strtox_result_e
1552 asn_strtol_lim(const char *str, const char **end, long *lp) {
1554 switch(asn_strtoimax_lim(str, end, &value)) {
1555 case ASN_STRTOX_ERROR_RANGE:
1556 return ASN_STRTOX_ERROR_RANGE;
1557 case ASN_STRTOX_ERROR_INVAL:
1558 return ASN_STRTOX_ERROR_INVAL;
1559 case ASN_STRTOX_EXPECT_MORE:
1560 return ASN_STRTOX_EXPECT_MORE;
1562 if(value >= LONG_MIN && value <= LONG_MAX) {
1564 return ASN_STRTOX_OK;
1566 return ASN_STRTOX_ERROR_RANGE;
1568 case ASN_STRTOX_EXTRA_DATA:
1569 if(value >= LONG_MIN && value <= LONG_MAX) {
1571 return ASN_STRTOX_EXTRA_DATA;
1573 return ASN_STRTOX_ERROR_RANGE;
1577 assert(!"Unreachable");
1578 return ASN_STRTOX_ERROR_INVAL;
1581 enum asn_strtox_result_e
1582 asn_strtoul_lim(const char *str, const char **end, unsigned long *ulp) {
1584 switch(asn_strtoumax_lim(str, end, &value)) {
1585 case ASN_STRTOX_ERROR_RANGE:
1586 return ASN_STRTOX_ERROR_RANGE;
1587 case ASN_STRTOX_ERROR_INVAL:
1588 return ASN_STRTOX_ERROR_INVAL;
1589 case ASN_STRTOX_EXPECT_MORE:
1590 return ASN_STRTOX_EXPECT_MORE;
1592 if(value <= ULONG_MAX) {
1594 return ASN_STRTOX_OK;
1596 return ASN_STRTOX_ERROR_RANGE;
1598 case ASN_STRTOX_EXTRA_DATA:
1599 if(value <= ULONG_MAX) {
1601 return ASN_STRTOX_EXTRA_DATA;
1603 return ASN_STRTOX_ERROR_RANGE;
1607 assert(!"Unreachable");
1608 return ASN_STRTOX_ERROR_INVAL;
1612 INTEGER_compare(const asn_TYPE_descriptor_t *td, const void *aptr,
1614 const INTEGER_t *a = aptr;
1615 const INTEGER_t *b = bptr;
1620 if(a->size && b->size) {
1621 int sign_a = (a->buf[0] & 0x80) ? -1 : 1;
1622 int sign_b = (b->buf[0] & 0x80) ? -1 : 1;
1624 if(sign_a < sign_b) return -1;
1625 if(sign_a > sign_b) return 1;
1627 /* The shortest integer wins, unless comparing negatives */
1628 if(a->size < b->size) {
1630 } else if(a->size > b->size) {
1634 return sign_a * memcmp(a->buf, b->buf, a->size);
1635 } else if(a->size) {
1636 int sign = (a->buf[0] & 0x80) ? -1 : 1;
1638 } else if(b->size) {
1639 int sign = (a->buf[0] & 0x80) ? -1 : 1;
1644 } else if(!a && !b) {
1654 asn_random_fill_result_t
1655 INTEGER_random_fill(const asn_TYPE_descriptor_t *td, void **sptr,
1656 const asn_encoding_constraints_t *constraints,
1657 size_t max_length) {
1658 const asn_INTEGER_specifics_t *specs =
1659 (const asn_INTEGER_specifics_t *)td->specifics;
1660 asn_random_fill_result_t result_ok = {ARFILL_OK, 1};
1661 asn_random_fill_result_t result_failed = {ARFILL_FAILED, 0};
1662 asn_random_fill_result_t result_skipped = {ARFILL_SKIPPED, 0};
1663 INTEGER_t *st = *sptr;
1664 const asn_INTEGER_enum_map_t *emap;
1667 int find_inside_map;
1669 if(max_length == 0) return result_skipped;
1672 st = (INTEGER_t *)CALLOC(1, sizeof(*st));
1674 return result_failed;
1679 emap = specs->value2enum;
1680 emap_len = specs->map_count;
1681 if(specs->strict_enumeration) {
1682 find_inside_map = emap_len > 0;
1684 find_inside_map = emap_len ? asn_random_between(0, 1) : 0;
1689 find_inside_map = 0;
1692 if(find_inside_map) {
1693 assert(emap_len > 0);
1694 value = emap[asn_random_between(0, emap_len - 1)].nat_value;
1696 const asn_per_constraints_t *ct;
1698 static const long variants[] = {
1699 -65536, -65535, -65534, -32769, -32768, -32767, -16385, -16384,
1700 -16383, -257, -256, -255, -254, -129, -128, -127,
1701 -126, -1, 0, 1, 126, 127, 128, 129,
1702 254, 255, 256, 257, 16383, 16384, 16385, 32767,
1703 32768, 32769, 65534, 65535, 65536, 65537};
1704 if(specs && specs->field_unsigned) {
1705 assert(variants[18] == 0);
1706 value = variants[asn_random_between(
1707 18, sizeof(variants) / sizeof(variants[0]) - 1)];
1709 value = variants[asn_random_between(
1710 0, sizeof(variants) / sizeof(variants[0]) - 1)];
1713 if(!constraints) constraints = &td->encoding_constraints;
1714 ct = constraints ? constraints->per_constraints : 0;
1715 if(ct && (ct->value.flags & APC_CONSTRAINED)) {
1716 if(value < ct->value.lower_bound || value > ct->value.upper_bound) {
1717 value = asn_random_between(ct->value.lower_bound,
1718 ct->value.upper_bound);
1723 if(asn_imax2INTEGER(st, value)) {
1725 ASN_STRUCT_RESET(*td, st);
1727 ASN_STRUCT_FREE(*td, st);
1729 return result_failed;
1732 result_ok.length = st->size;