2 * Copyright (c) 2003, 2004, 2005, 2006 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 ber_tlv_tag_t asn_DEF_INTEGER_tags[] = {
15 (ASN_TAG_CLASS_UNIVERSAL | (2 << 2))
17 asn_TYPE_descriptor_t asn_DEF_INTEGER = {
20 ASN__PRIMITIVE_TYPE_free,
22 asn_generic_no_constraint,
27 INTEGER_decode_uper, /* Unaligned PER decoder */
28 INTEGER_encode_uper, /* Unaligned PER encoder */
29 0, /* Use generic outmost tag fetcher */
31 sizeof(asn_DEF_INTEGER_tags) / sizeof(asn_DEF_INTEGER_tags[0]),
32 asn_DEF_INTEGER_tags, /* Same as above */
33 sizeof(asn_DEF_INTEGER_tags) / sizeof(asn_DEF_INTEGER_tags[0]),
34 0, /* No PER visible constraints */
35 0, 0, /* No members */
40 * Encode INTEGER type using DER.
43 INTEGER_encode_der(asn_TYPE_descriptor_t *td, void *sptr,
44 int tag_mode, ber_tlv_tag_t tag,
45 asn_app_consume_bytes_f *cb, void *app_key) {
46 INTEGER_t *st = (INTEGER_t *)sptr;
48 ASN_DEBUG("%s %s as INTEGER (tm=%d)",
49 cb?"Encoding":"Estimating", td->name, tag_mode);
52 * Canonicalize integer in the buffer.
53 * (Remove too long sign extension, remove some first 0x00 bytes)
56 uint8_t *buf = st->buf;
57 uint8_t *end1 = buf + st->size - 1;
60 /* Compute the number of superfluous leading bytes */
61 for(; buf < end1; buf++) {
63 * If the contents octets of an integer value encoding
64 * consist of more than one octet, then the bits of the
65 * first octet and bit 8 of the second octet:
66 * a) shall not all be ones; and
67 * b) shall not all be zero.
70 case 0x00: if((buf[1] & 0x80) == 0)
73 case 0xff: if((buf[1] & 0x80))
80 /* Remove leading superfluous bytes from the integer */
81 shift = buf - st->buf;
83 uint8_t *nb = st->buf;
86 st->size -= shift; /* New size, minus bad bytes */
89 for(; nb < end; nb++, buf++)
95 return der_encode_primitive(td, sptr, tag_mode, tag, cb, app_key);
98 static const asn_INTEGER_enum_map_t *INTEGER_map_enum2value(asn_INTEGER_specifics_t *specs, const char *lstart, const char *lstop);
101 * INTEGER specific human-readable output.
104 INTEGER__dump(asn_TYPE_descriptor_t *td, const INTEGER_t *st, asn_app_consume_bytes_f *cb, void *app_key, int plainOrXER) {
105 asn_INTEGER_specifics_t *specs=(asn_INTEGER_specifics_t *)td->specifics;
106 char scratch[32]; /* Enough for 64-bit integer */
107 uint8_t *buf = st->buf;
108 uint8_t *buf_end = st->buf + st->size;
114 * Advance buf pointer until the start of the value's body.
115 * This will make us able to process large integers using simple case,
116 * when the actual value is small
117 * (0x0000000000abcdef would yield a fine 0x00abcdef)
119 /* Skip the insignificant leading bytes */
120 for(; buf < buf_end-1; buf++) {
122 case 0x00: if((buf[1] & 0x80) == 0) continue; break;
123 case 0xff: if((buf[1] & 0x80) != 0) continue; break;
128 /* Simple case: the integer size is small */
129 if((size_t)(buf_end - buf) <= sizeof(accum)) {
130 const asn_INTEGER_enum_map_t *el;
138 accum = (*buf & 0x80) ? -1 : 0;
139 for(; buf < buf_end; buf++)
140 accum = (accum << 8) | *buf;
143 el = INTEGER_map_value2enum(specs, accum);
145 scrsize = el->enum_len + 32;
146 scr = (char *)alloca(scrsize);
148 ret = snprintf(scr, scrsize,
149 "%ld (%s)", accum, el->enum_name);
151 ret = snprintf(scr, scrsize,
152 "<%s/>", el->enum_name);
153 } else if(plainOrXER && specs && specs->strict_enumeration) {
154 ASN_DEBUG("ASN.1 forbids dealing with "
155 "unknown value of ENUMERATED type");
159 scrsize = sizeof(scratch);
161 ret = snprintf(scr, scrsize, "%ld", accum);
163 assert(ret > 0 && (size_t)ret < scrsize);
164 return (cb(scr, ret, app_key) < 0) ? -1 : ret;
165 } else if(plainOrXER && specs && specs->strict_enumeration) {
167 * Here and earlier, we cannot encode the ENUMERATED values
168 * if there is no corresponding identifier.
170 ASN_DEBUG("ASN.1 forbids dealing with "
171 "unknown value of ENUMERATED type");
176 /* Output in the long xx:yy:zz... format */
177 /* TODO: replace with generic algorithm (Knuth TAOCP Vol 2, 4.3.1) */
178 for(p = scratch; buf < buf_end; buf++) {
179 static const char *h2c = "0123456789ABCDEF";
180 if((p - scratch) >= (ssize_t)(sizeof(scratch) - 4)) {
182 if(cb(scratch, p - scratch, app_key) < 0)
184 wrote += p - scratch;
187 *p++ = h2c[*buf >> 4];
188 *p++ = h2c[*buf & 0x0F];
189 *p++ = 0x3a; /* ":" */
192 p--; /* Remove the last ":" */
194 wrote += p - scratch;
195 return (cb(scratch, p - scratch, app_key) < 0) ? -1 : wrote;
199 * INTEGER specific human-readable output.
202 INTEGER_print(asn_TYPE_descriptor_t *td, const void *sptr, int ilevel,
203 asn_app_consume_bytes_f *cb, void *app_key) {
204 const INTEGER_t *st = (const INTEGER_t *)sptr;
211 ret = cb("<absent>", 8, app_key);
213 ret = INTEGER__dump(td, st, cb, app_key, 0);
215 return (ret < 0) ? -1 : 0;
221 asn_INTEGER_enum_map_t *vemap;
225 INTEGER__compar_enum2value(const void *kp, const void *am) {
226 const struct e2v_key *key = (const struct e2v_key *)kp;
227 const asn_INTEGER_enum_map_t *el = (const asn_INTEGER_enum_map_t *)am;
228 const char *ptr, *end, *name;
230 /* Remap the element (sort by different criterion) */
231 el = key->vemap + key->evmap[el - key->vemap];
233 /* Compare strings */
234 for(ptr = key->start, end = key->stop, name = el->enum_name;
235 ptr < end; ptr++, name++) {
237 return *(const unsigned char *)ptr
238 - *(const unsigned char *)name;
240 return name[0] ? -1 : 0;
243 static const asn_INTEGER_enum_map_t *
244 INTEGER_map_enum2value(asn_INTEGER_specifics_t *specs, const char *lstart, const char *lstop) {
245 asn_INTEGER_enum_map_t *el_found;
246 int count = specs ? specs->map_count : 0;
250 if(!count) return NULL;
252 /* Guaranteed: assert(lstart < lstop); */
253 /* Figure out the tag name */
254 for(lstart++, lp = lstart; lp < lstop; lp++) {
256 case 9: case 10: case 11: case 12: case 13: case 32: /* WSP */
257 case 0x2f: /* '/' */ case 0x3e: /* '>' */
264 if(lp == lstop) return NULL; /* No tag found */
269 key.vemap = specs->value2enum;
270 key.evmap = specs->enum2value;
271 el_found = (asn_INTEGER_enum_map_t *)bsearch(&key,
272 specs->value2enum, count, sizeof(specs->value2enum[0]),
273 INTEGER__compar_enum2value);
275 /* Remap enum2value into value2enum */
276 el_found = key.vemap + key.evmap[el_found - key.vemap];
282 INTEGER__compar_value2enum(const void *kp, const void *am) {
283 long a = *(const long *)kp;
284 const asn_INTEGER_enum_map_t *el = (const asn_INTEGER_enum_map_t *)am;
285 long b = el->nat_value;
287 else if(a == b) return 0;
291 const asn_INTEGER_enum_map_t *
292 INTEGER_map_value2enum(asn_INTEGER_specifics_t *specs, long value) {
293 int count = specs ? specs->map_count : 0;
295 return (asn_INTEGER_enum_map_t *)bsearch(&value, specs->value2enum,
296 count, sizeof(specs->value2enum[0]),
297 INTEGER__compar_value2enum);
301 INTEGER_st_prealloc(INTEGER_t *st, int min_size) {
302 void *p = MALLOC(min_size + 1);
315 * Decode the chunk of XML text encoding INTEGER.
317 static enum xer_pbd_rval
318 INTEGER__xer_body_decode(asn_TYPE_descriptor_t *td, void *sptr, const void *chunk_buf, size_t chunk_size) {
319 INTEGER_t *st = (INTEGER_t *)sptr;
323 const char *lstart = (const char *)chunk_buf;
324 const char *lstop = lstart + chunk_size;
334 } state = ST_SKIPSPACE;
337 ASN_DEBUG("INTEGER body %d 0x%2x..0x%2x",
338 chunk_size, *lstart, lstop[-1]);
341 * We may have received a tag here. It will be processed inline.
342 * Use strtoul()-like code and serialize the result.
344 for(value = 0, lp = lstart; lp < lstop; lp++) {
347 case 0x09: case 0x0a: case 0x0d: case 0x20:
353 if(xer_is_whitespace(lp, lstop - lp)) {
363 if(state == ST_SKIPSPACE) {
365 state = ST_WAITDIGITS;
370 if(state == ST_SKIPSPACE) {
371 state = ST_WAITDIGITS;
375 case 0x30: case 0x31: case 0x32: case 0x33: case 0x34:
376 case 0x35: case 0x36: case 0x37: case 0x38: case 0x39:
378 case ST_DIGITS: break;
379 case ST_SKIPSPHEX: /* Fall through */
381 value = (lv - 0x30) << 4;
382 state = ST_HEXDIGIT2;
385 value += (lv - 0x30);
387 st->buf[st->size++] = value;
390 return XPBD_BROKEN_ENCODING;
397 long new_value = value * 10;
399 if(new_value / 10 != value)
401 return XPBD_DECODER_LIMIT;
403 value = new_value + (lv - 0x30);
404 /* Check for two's complement overflow */
406 /* Check whether it is a LONG_MIN */
408 && (unsigned long)value
409 == ~((unsigned long)-1 >> 1)) {
413 return XPBD_DECODER_LIMIT;
419 if(state == ST_SKIPSPACE) {
420 const asn_INTEGER_enum_map_t *el;
421 el = INTEGER_map_enum2value(
422 (asn_INTEGER_specifics_t *)
423 td->specifics, lstart, lstop);
425 ASN_DEBUG("Found \"%s\" => %ld",
426 el->enum_name, el->nat_value);
428 value = el->nat_value;
432 ASN_DEBUG("Unknown identifier for INTEGER");
434 return XPBD_BROKEN_ENCODING;
436 if(state == ST_HEXCOLON) {
437 /* This colon is expected */
438 state = ST_HEXDIGIT1;
440 } else if(state == ST_DIGITS) {
441 /* The colon here means that we have
442 * decoded the first two hexadecimal
443 * places as a decimal value.
444 * Switch decoding mode. */
445 ASN_DEBUG("INTEGER re-evaluate as hex form");
446 if(INTEGER_st_prealloc(st, (chunk_size/3) + 1))
447 return XPBD_SYSTEM_FAILURE;
448 state = ST_SKIPSPHEX;
452 ASN_DEBUG("state %d at %d", state, lp - lstart);
456 case 0x41:case 0x42:case 0x43:case 0x44:case 0x45:case 0x46:
457 case 0x61:case 0x62:case 0x63:case 0x64:case 0x65:case 0x66:
460 case ST_SKIPSPACE: /* Fall through */
462 value = lv - ((lv < 0x61) ? 0x41 : 0x61);
465 state = ST_HEXDIGIT2;
468 value += lv - ((lv < 0x61) ? 0x41 : 0x61);
470 st->buf[st->size++] = value;
474 ASN_DEBUG("INTEGER re-evaluate as hex form");
475 if(INTEGER_st_prealloc(st, (chunk_size/3) + 1))
476 return XPBD_SYSTEM_FAILURE;
477 state = ST_SKIPSPHEX;
486 /* Found extra non-numeric stuff */
487 ASN_DEBUG("Found non-numeric 0x%2x at %d",
489 state = ST_EXTRASTUFF;
495 /* Everything is cool */
498 st->buf[st->size] = 0; /* Just in case termination */
499 return XPBD_BODY_CONSUMED;
503 return XPBD_BROKEN_ENCODING;
505 if(xer_is_whitespace(lp, lstop - lp)) {
506 if(state != ST_EXTRASTUFF)
507 return XPBD_NOT_BODY_IGNORE;
510 ASN_DEBUG("INTEGER: No useful digits (state %d)",
512 return XPBD_BROKEN_ENCODING; /* No digits */
517 value *= sign; /* Change sign, if needed */
519 if(asn_long2INTEGER(st, value))
520 return XPBD_SYSTEM_FAILURE;
522 return XPBD_BODY_CONSUMED;
526 INTEGER_decode_xer(asn_codec_ctx_t *opt_codec_ctx,
527 asn_TYPE_descriptor_t *td, void **sptr, const char *opt_mname,
528 const void *buf_ptr, size_t size) {
530 return xer_decode_primitive(opt_codec_ctx, td,
531 sptr, sizeof(INTEGER_t), opt_mname,
532 buf_ptr, size, INTEGER__xer_body_decode);
536 INTEGER_encode_xer(asn_TYPE_descriptor_t *td, void *sptr,
537 int ilevel, enum xer_encoder_flags_e flags,
538 asn_app_consume_bytes_f *cb, void *app_key) {
539 const INTEGER_t *st = (const INTEGER_t *)sptr;
548 er.encoded = INTEGER__dump(td, st, cb, app_key, 1);
549 if(er.encoded < 0) _ASN_ENCODE_FAILED;
555 INTEGER_decode_uper(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td,
556 asn_per_constraints_t *constraints, void **sptr, asn_per_data_t *pd) {
557 asn_dec_rval_t rval = { RC_OK, 0 };
558 INTEGER_t *st = (INTEGER_t *)*sptr;
559 asn_per_constraint_t *ct;
565 st = (INTEGER_t *)(*sptr = CALLOC(1, sizeof(*st)));
566 if(!st) _ASN_DECODE_FAILED;
569 if(!constraints) constraints = td->per_constraints;
570 ct = constraints ? &constraints->value : 0;
572 if(ct && ct->flags & APC_EXTENSIBLE) {
573 int inext = per_get_few_bits(pd, 1);
574 if(inext < 0) _ASN_DECODE_STARVED;
580 if(ct->flags & APC_SEMI_CONSTRAINED) {
581 st->buf = (uint8_t *)CALLOC(1, 2);
582 if(!st->buf) _ASN_DECODE_FAILED;
584 } else if(ct->flags & APC_CONSTRAINED && ct->range_bits >= 0) {
585 size_t size = (ct->range_bits + 7) >> 3;
586 st->buf = (uint8_t *)MALLOC(1 + size + 1);
587 if(!st->buf) _ASN_DECODE_FAILED;
597 if(ct && ct->flags != APC_UNCONSTRAINED) {
599 ASN_DEBUG("Integer with range %d bits", ct->range_bits);
600 if(ct->range_bits >= 0) {
601 long value = per_get_few_bits(pd, ct->range_bits);
602 if(value < 0) _ASN_DECODE_STARVED;
603 ASN_DEBUG("Got value %ld + low %ld",
604 value, ct->lower_bound);
605 value += ct->lower_bound;
606 if(asn_long2INTEGER(st, value))
611 ASN_DEBUG("Decoding unconstrained integer %s", td->name);
614 /* X.691, #12.2.3, #12.2.4 */
620 /* Get the PER length */
621 len = uper_get_length(pd, -1, &repeat);
622 if(len < 0) _ASN_DECODE_STARVED;
624 p = REALLOC(st->buf, st->size + len + 1);
625 if(!p) _ASN_DECODE_FAILED;
626 st->buf = (uint8_t *)p;
628 ret = per_get_many_bits(pd, &st->buf[st->size], 0, 8 * len);
629 if(ret < 0) _ASN_DECODE_STARVED;
632 st->buf[st->size] = 0; /* JIC */
635 if(ct && ct->lower_bound) {
637 * TODO: replace by in-place arithmetics.
640 if(asn_INTEGER2long(st, &value))
642 if(asn_long2INTEGER(st, value + ct->lower_bound))
650 INTEGER_encode_uper(asn_TYPE_descriptor_t *td,
651 asn_per_constraints_t *constraints, void *sptr, asn_per_outp_t *po) {
653 INTEGER_t *st = (INTEGER_t *)sptr;
656 asn_per_constraint_t *ct;
659 if(!st || st->size == 0) _ASN_ENCODE_FAILED;
661 if(!constraints) constraints = td->per_constraints;
662 ct = constraints ? &constraints->value : 0;
668 if(asn_INTEGER2long(st, &value))
670 /* Check proper range */
671 if(ct->flags & APC_SEMI_CONSTRAINED) {
672 if(value < ct->lower_bound)
674 } else if(ct->range_bits >= 0) {
675 if(value < ct->lower_bound
676 || value > ct->upper_bound)
679 ASN_DEBUG("Value %ld (%02x/%d) lb %ld ub %ld %s",
680 value, st->buf[0], st->size,
681 ct->lower_bound, ct->upper_bound,
682 inext ? "ext" : "fix");
683 if(ct->flags & APC_EXTENSIBLE) {
684 if(per_put_few_bits(po, inext, 1))
694 if(ct && ct->range_bits >= 0) {
696 ASN_DEBUG("Encoding integer with range %d bits",
698 if(per_put_few_bits(po, value - ct->lower_bound,
704 if(ct && ct->lower_bound) {
705 ASN_DEBUG("Adjust lower bound to %ld", ct->lower_bound);
706 /* TODO: adjust lower bound */
710 for(buf = st->buf, end = st->buf + st->size; buf < end;) {
711 ssize_t mayEncode = uper_put_length(po, end - buf);
714 if(per_put_many_bits(po, buf, 8 * mayEncode))
723 asn_INTEGER2long(const INTEGER_t *iptr, long *lptr) {
728 /* Sanity checking */
729 if(!iptr || !iptr->buf || !lptr) {
734 /* Cache the begin/end of the buffer */
735 b = iptr->buf; /* Start of the INTEGER buffer */
737 end = b + size; /* Where to stop */
739 if(size > sizeof(long)) {
740 uint8_t *end1 = end - 1;
742 * Slightly more advanced processing,
743 * able to >sizeof(long) bytes,
744 * when the actual value is small
745 * (0x0000000000abcdef would yield a fine 0x00abcdef)
747 /* Skip out the insignificant leading bytes */
748 for(; b < end1; b++) {
750 case 0x00: if((b[1] & 0x80) == 0) continue; break;
751 case 0xff: if((b[1] & 0x80) != 0) continue; break;
757 if(size > sizeof(long)) {
758 /* Still cannot fit the long */
764 /* Shortcut processing of a corner case */
770 /* Perform the sign initialization */
771 /* Actually l = -(*b >> 7); gains nothing, yet unreadable! */
772 if((*b >> 7)) l = -1; else l = 0;
774 /* Conversion engine */
783 asn_long2INTEGER(INTEGER_t *st, long value) {
788 int littleEndian = 1; /* Run-time detection */
796 buf = (uint8_t *)MALLOC(sizeof(value));
799 if(*(char *)&littleEndian) {
800 pstart = (uint8_t *)&value + sizeof(value) - 1;
801 pend1 = (uint8_t *)&value;
804 pstart = (uint8_t *)&value;
805 pend1 = pstart + sizeof(value) - 1;
810 * If the contents octet consists of more than one octet,
811 * then bits of the first octet and bit 8 of the second octet:
812 * a) shall not all be ones; and
813 * b) shall not all be zero.
815 for(p = pstart; p != pend1; p += add) {
817 case 0x00: if((*(p+add) & 0x80) == 0)
820 case 0xff: if((*(p+add) & 0x80))
826 /* Copy the integer body */
827 for(pstart = p, bp = buf, pend1 += add; p != pend1; p += add)
830 if(st->buf) FREEMEM(st->buf);