2a2f4d720a32b7d2dbe7454445c65cb9bf7f06a8
[sim/e2-interface.git] / e2sim / previous / e2apv1sim / ASN1c / INTEGER.c
1 /*-
2  * Copyright (c) 2003-2014 Lev Walkin <vlm@lionet.info>.
3  * All rights reserved.
4  * Redistribution and modifications are permitted subject to BSD license.
5  */
6 #include <asn_internal.h>
7 #include <INTEGER.h>
8 #include <asn_codecs_prim.h>    /* Encoder and decoder of a primitive type */
9 #include <errno.h>
10
11 /*
12  * INTEGER basic type description.
13  */
14 static const ber_tlv_tag_t asn_DEF_INTEGER_tags[] = {
15         (ASN_TAG_CLASS_UNIVERSAL | (2 << 2))
16 };
17 asn_TYPE_operation_t asn_OP_INTEGER = {
18         INTEGER_free,
19         INTEGER_print,
20         INTEGER_compare,
21         ber_decode_primitive,
22         INTEGER_encode_der,
23         INTEGER_decode_xer,
24         INTEGER_encode_xer,
25 #ifdef  ASN_DISABLE_OER_SUPPORT
26         0,
27         0,
28 #else
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
33         0,
34         0,
35         0,
36         0,
37 #else
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 */
43         INTEGER_random_fill,
44         0       /* Use generic outmost tag fetcher */
45 };
46 asn_TYPE_descriptor_t asn_DEF_INTEGER = {
47         "INTEGER",
48         "INTEGER",
49         &asn_OP_INTEGER,
50         asn_DEF_INTEGER_tags,
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 */
56         0       /* No specifics */
57 };
58
59 /*
60  * Encode INTEGER type using DER.
61  */
62 asn_enc_rval_t
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,
65                    void *app_key) {
66     const INTEGER_t *st = (const INTEGER_t *)sptr;
67     asn_enc_rval_t rval;
68     INTEGER_t effective_integer;
69
70         ASN_DEBUG("%s %s as INTEGER (tm=%d)",
71                 cb?"Encoding":"Estimating", td->name, tag_mode);
72
73         /*
74          * Canonicalize integer in the buffer.
75          * (Remove too long sign extension, remove some first 0x00 bytes)
76          */
77         if(st->buf) {
78                 uint8_t *buf = st->buf;
79                 uint8_t *end1 = buf + st->size - 1;
80                 int shift;
81
82                 /* Compute the number of superfluous leading bytes */
83                 for(; buf < end1; buf++) {
84                         /*
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.
90                          */
91                         switch(*buf) {
92                         case 0x00: if((buf[1] & 0x80) == 0)
93                                         continue;
94                                 break;
95                         case 0xff: if((buf[1] & 0x80))
96                                         continue;
97                                 break;
98                         }
99                         break;
100                 }
101
102                 /* Remove leading superfluous bytes from the integer */
103                 shift = buf - st->buf;
104                 if(shift) {
105             union {
106                 const uint8_t *c_buf;
107                 uint8_t *nc_buf;
108             } unconst;
109             unconst.c_buf = st->buf;
110             effective_integer.buf = unconst.nc_buf + shift;
111             effective_integer.size = st->size - shift;
112
113             st = &effective_integer;
114         }
115     }
116
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;
120     }
121     return rval;
122 }
123
124 static const asn_INTEGER_enum_map_t *INTEGER_map_enum2value(
125     const asn_INTEGER_specifics_t *specs, const char *lstart,
126     const char *lstop);
127
128 /*
129  * INTEGER specific human-readable output.
130  */
131 static ssize_t
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;
135         char scratch[32];
136         uint8_t *buf = st->buf;
137         uint8_t *buf_end = st->buf + st->size;
138         intmax_t value;
139         ssize_t wrote = 0;
140         char *p;
141         int ret;
142
143         if(specs && specs->field_unsigned)
144                 ret = asn_INTEGER2umax(st, (uintmax_t *)&value);
145         else
146                 ret = asn_INTEGER2imax(st, &value);
147
148         /* Simple case: the integer size is small */
149         if(ret == 0) {
150                 const asn_INTEGER_enum_map_t *el;
151                 el = (value >= 0 || !specs || !specs->field_unsigned)
152                         ? INTEGER_map_value2enum(specs, value) : 0;
153                 if(el) {
154                         if(plainOrXER == 0)
155                                 return asn__format_to_callback(cb, app_key,
156                                         "%" ASN_PRIdMAX " (%s)", value, el->enum_name);
157                         else
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");
163                         errno = EPERM;
164                         return -1;
165                 } else {
166             return asn__format_to_callback(cb, app_key,
167                                            (specs && specs->field_unsigned)
168                                                ? "%" ASN_PRIuMAX
169                                                : "%" ASN_PRIdMAX,
170                                            value);
171         }
172         } else if(plainOrXER && specs && specs->strict_enumeration) {
173                 /*
174                  * Here and earlier, we cannot encode the ENUMERATED values
175                  * if there is no corresponding identifier.
176                  */
177                 ASN_DEBUG("ASN.1 forbids dealing with "
178                         "unknown value of ENUMERATED type");
179                 errno = EPERM;
180                 return -1;
181         }
182
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)) {
188                         /* Flush buffer */
189                         if(cb(scratch, p - scratch, app_key) < 0)
190                                 return -1;
191                         wrote += p - scratch;
192                         p = scratch;
193                 }
194                 *p++ = h2c[*buf >> 4];
195                 *p++ = h2c[*buf & 0x0F];
196                 *p++ = 0x3a;    /* ":" */
197         }
198         if(p != scratch)
199                 p--;    /* Remove the last ":" */
200
201         wrote += p - scratch;
202         return (cb(scratch, p - scratch, app_key) < 0) ? -1 : wrote;
203 }
204
205 /*
206  * INTEGER specific human-readable output.
207  */
208 int
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;
212         ssize_t ret;
213
214         (void)ilevel;
215
216         if(!st || !st->buf)
217                 ret = cb("<absent>", 8, app_key);
218         else
219                 ret = INTEGER__dump(td, st, cb, app_key, 0);
220
221         return (ret < 0) ? -1 : 0;
222 }
223
224 struct e2v_key {
225         const char *start;
226         const char *stop;
227         const asn_INTEGER_enum_map_t *vemap;
228         const unsigned int *evmap;
229 };
230 static int
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;
235
236         /* Remap the element (sort by different criterion) */
237         el = key->vemap + key->evmap[el - key->vemap];
238
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;
245         }
246         return name[0] ? -1 : 0;
247 }
248
249 static const asn_INTEGER_enum_map_t *
250 INTEGER_map_enum2value(const asn_INTEGER_specifics_t *specs, const char *lstart,
251                        const char *lstop) {
252     const asn_INTEGER_enum_map_t *el_found;
253         int count = specs ? specs->map_count : 0;
254         struct e2v_key key;
255         const char *lp;
256
257         if(!count) return NULL;
258
259         /* Guaranteed: assert(lstart < lstop); */
260         /* Figure out the tag name */
261         for(lstart++, lp = lstart; lp < lstop; lp++) {
262                 switch(*lp) {
263                 case 9: case 10: case 11: case 12: case 13: case 32: /* WSP */
264                 case 0x2f: /* '/' */ case 0x3e: /* '>' */
265                         break;
266                 default:
267                         continue;
268                 }
269                 break;
270         }
271         if(lp == lstop) return NULL;    /* No tag found */
272         lstop = lp;
273
274         key.start = lstart;
275         key.stop = lstop;
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);
281         if(el_found) {
282                 /* Remap enum2value into value2enum */
283                 el_found = key.vemap + key.evmap[el_found - key.vemap];
284         }
285         return el_found;
286 }
287
288 static int
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;
293         if(a < b) return -1;
294         else if(a == b) return 0;
295         else return 1;
296 }
297
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;
301         if(!count) return 0;
302         return (asn_INTEGER_enum_map_t *)bsearch(&value, specs->value2enum,
303                 count, sizeof(specs->value2enum[0]),
304                 INTEGER__compar_value2enum);
305 }
306
307 static int
308 INTEGER_st_prealloc(INTEGER_t *st, int min_size) {
309         void *p = MALLOC(min_size + 1);
310         if(p) {
311                 void *b = st->buf;
312                 st->size = 0;
313                 st->buf = p;
314                 FREEMEM(b);
315                 return 0;
316         } else {
317                 return -1;
318         }
319 }
320
321 /*
322  * Decode the chunk of XML text encoding INTEGER.
323  */
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;
330         intmax_t dec_value;
331         intmax_t hex_value = 0;
332         const char *lp;
333         const char *lstart = (const char *)chunk_buf;
334         const char *lstop = lstart + chunk_size;
335         enum {
336                 ST_LEADSPACE,
337                 ST_SKIPSPHEX,
338                 ST_WAITDIGITS,
339                 ST_DIGITS,
340                 ST_DIGITS_TRAILSPACE,
341                 ST_HEXDIGIT1,
342                 ST_HEXDIGIT2,
343                 ST_HEXDIGITS_TRAILSPACE,
344                 ST_HEXCOLON,
345                 ST_END_ENUM,
346                 ST_UNEXPECTED
347         } state = ST_LEADSPACE;
348         const char *dec_value_start = 0; /* INVARIANT: always !0 in ST_DIGITS */
349         const char *dec_value_end = 0;
350
351         if(chunk_size)
352                 ASN_DEBUG("INTEGER body %ld 0x%2x..0x%2x",
353                         (long)chunk_size, *lstart, lstop[-1]);
354
355         if(INTEGER_st_prealloc(st, (chunk_size/3) + 1))
356                 return XPBD_SYSTEM_FAILURE;
357
358         /*
359          * We may have received a tag here. It will be processed inline.
360          * Use strtoul()-like code and serialize the result.
361          */
362         for(lp = lstart; lp < lstop; lp++) {
363                 int lv = *lp;
364                 switch(lv) {
365                 case 0x09: case 0x0a: case 0x0d: case 0x20:
366                         switch(state) {
367                         case ST_LEADSPACE:
368                         case ST_DIGITS_TRAILSPACE:
369                         case ST_HEXDIGITS_TRAILSPACE:
370                         case ST_SKIPSPHEX:
371                                 continue;
372                         case ST_DIGITS:
373                                 dec_value_end = lp;
374                                 state = ST_DIGITS_TRAILSPACE;
375                                 continue;
376                         case ST_HEXCOLON:
377                                 state = ST_HEXDIGITS_TRAILSPACE;
378                                 continue;
379                         default:
380                                 break;
381                         }
382                         break;
383                 case 0x2d:      /* '-' */
384                         if(state == ST_LEADSPACE) {
385                                 dec_value = 0;
386                                 dec_value_start = lp;
387                                 state = ST_WAITDIGITS;
388                                 continue;
389                         }
390                         break;
391                 case 0x2b:      /* '+' */
392                         if(state == ST_LEADSPACE) {
393                                 dec_value = 0;
394                                 dec_value_start = lp;
395                                 state = ST_WAITDIGITS;
396                                 continue;
397                         }
398                         break;
399                 case 0x30: case 0x31: case 0x32: case 0x33: case 0x34:
400                 case 0x35: case 0x36: case 0x37: case 0x38: case 0x39:
401                         switch(state) {
402                         case ST_DIGITS: continue;
403                         case ST_SKIPSPHEX:      /* Fall through */
404                         case ST_HEXDIGIT1:
405                                 hex_value = (lv - 0x30) << 4;
406                                 state = ST_HEXDIGIT2;
407                                 continue;
408                         case ST_HEXDIGIT2:
409                                 hex_value += (lv - 0x30);
410                                 state = ST_HEXCOLON;
411                                 st->buf[st->size++] = (uint8_t)hex_value;
412                                 continue;
413                         case ST_HEXCOLON:
414                                 return XPBD_BROKEN_ENCODING;
415                         case ST_LEADSPACE:
416                                 dec_value = 0;
417                                 dec_value_start = lp;
418                                 /* FALL THROUGH */
419                         case ST_WAITDIGITS:
420                                 state = ST_DIGITS;
421                                 continue;
422                         default:
423                                 break;
424                         }
425                         break;
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);
432                                 if(el) {
433                                         ASN_DEBUG("Found \"%s\" => %ld",
434                                                 el->enum_name, el->nat_value);
435                                         dec_value = el->nat_value;
436                                         state = ST_END_ENUM;
437                                         lp = lstop - 1;
438                                         continue;
439                                 }
440                                 ASN_DEBUG("Unknown identifier for INTEGER");
441                         }
442                         return XPBD_BROKEN_ENCODING;
443                 case 0x3a:      /* ':' */
444                         if(state == ST_HEXCOLON) {
445                                 /* This colon is expected */
446                                 state = ST_HEXDIGIT1;
447                                 continue;
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;
455                                 dec_value_start = 0;
456                                 lp = lstart - 1;
457                                 continue;
458                         } else {
459                                 ASN_DEBUG("state %d at %ld", state, (long)(lp - lstart));
460                                 break;
461                         }
462                 /* [A-Fa-f] */
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:
465                         switch(state) {
466                         case ST_SKIPSPHEX:
467                         case ST_LEADSPACE: /* Fall through */
468                         case ST_HEXDIGIT1:
469                                 hex_value = lv - ((lv < 0x61) ? 0x41 : 0x61);
470                                 hex_value += 10;
471                                 hex_value <<= 4;
472                                 state = ST_HEXDIGIT2;
473                                 continue;
474                         case ST_HEXDIGIT2:
475                                 hex_value += lv - ((lv < 0x61) ? 0x41 : 0x61);
476                                 hex_value += 10;
477                                 st->buf[st->size++] = (uint8_t)hex_value;
478                                 state = ST_HEXCOLON;
479                                 continue;
480                         case ST_DIGITS:
481                                 ASN_DEBUG("INTEGER re-evaluate as hex form");
482                                 state = ST_SKIPSPHEX;
483                                 dec_value_start = 0;
484                                 lp = lstart - 1;
485                                 continue;
486                         default:
487                                 break;
488                         }
489                         break;
490                 }
491
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;
496                 break;
497         }
498
499         switch(state) {
500         case ST_END_ENUM:
501                 /* Got a complete and valid enumeration encoded as a tag. */
502                 break;
503         case ST_DIGITS:
504                 dec_value_end = lstop;
505                 /* FALL THROUGH */
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)) {
509         case ASN_STRTOX_OK:
510             if(specs && specs->field_unsigned && (uintmax_t) dec_value <= ULONG_MAX) {
511                 break;
512             } else if(dec_value >= LONG_MIN && dec_value <= LONG_MAX) {
513                 break;
514             } else {
515                 /*
516                  * We model INTEGER on long for XER,
517                  * to avoid rewriting all the tests at once.
518                  */
519                 ASN_DEBUG("INTEGER exceeds long range");
520             }
521             /* Fall through */
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;
529                 }
530                 break;
531         case ST_HEXCOLON:
532         case ST_HEXDIGITS_TRAILSPACE:
533                 st->buf[st->size] = 0;  /* Just in case termination */
534                 return XPBD_BODY_CONSUMED;
535         case ST_HEXDIGIT1:
536         case ST_HEXDIGIT2:
537         case ST_SKIPSPHEX:
538                 return XPBD_BROKEN_ENCODING;
539         case ST_LEADSPACE:
540                 /* Content not found */
541                 return XPBD_NOT_BODY_IGNORE;
542         case ST_WAITDIGITS:
543         case ST_UNEXPECTED:
544                 ASN_DEBUG("INTEGER: No useful digits (state %d)", state);
545                 return XPBD_BROKEN_ENCODING;    /* No digits */
546         }
547
548         /*
549          * Convert the result of parsing of enumeration or a straight
550          * decimal value into a BER representation.
551          */
552         if(asn_imax2INTEGER(st, dec_value)) {
553                 ASN_DEBUG("INTEGER decode %s conversion failed", td->name);
554                 return XPBD_SYSTEM_FAILURE;
555         }
556
557         return XPBD_BODY_CONSUMED;
558 }
559
560 asn_dec_rval_t
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);
567 }
568
569 asn_enc_rval_t
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};
575
576         (void)ilevel;
577         (void)flags;
578         
579         if(!st || !st->buf)
580                 ASN__ENCODE_FAILED;
581
582         er.encoded = INTEGER__dump(td, st, cb, app_key, 1);
583         if(er.encoded < 0) ASN__ENCODE_FAILED;
584
585         ASN__ENCODED_OK(er);
586 }
587
588 #ifndef ASN_DISABLE_PER_SUPPORT
589
590 asn_dec_rval_t
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;
600         int repeat;
601
602         (void)opt_codec_ctx;
603
604         if(!st) {
605                 st = (INTEGER_t *)(*sptr = CALLOC(1, sizeof(*st)));
606                 if(!st) ASN__DECODE_FAILED;
607         }
608
609         if(!constraints) constraints = td->encoding_constraints.per_constraints;
610         ct = constraints ? &constraints->value : 0;
611
612         if(ct && ct->flags & APC_EXTENSIBLE) {
613                 int inext = per_get_few_bits(pd, 1);
614                 if(inext < 0) ASN__DECODE_STARVED;
615                 if(inext) ct = 0;
616         }
617
618         FREEMEM(st->buf);
619         st->buf = 0;
620         st->size = 0;
621         if(ct) {
622                 if(ct->flags & APC_SEMI_CONSTRAINED) {
623                         st->buf = (uint8_t *)CALLOC(1, 2);
624                         if(!st->buf) ASN__DECODE_FAILED;
625                         st->size = 1;
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;
630                         st->size = size;
631                 }
632         }
633
634         /* X.691-2008/11, #13.2.2, constrained whole number */
635         if(ct && ct->flags != APC_UNCONSTRAINED) {
636                 /* #11.5.6 */
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))
640                                 ASN__DECODE_FAILED;
641
642                         if(specs && specs->field_unsigned) {
643                                 unsigned long uvalue = 0;
644                                 if(uper_get_constrained_whole_number(pd,
645                                         &uvalue, ct->range_bits))
646                                         ASN__DECODE_STARVED;
647                                 ASN_DEBUG("Got value %lu + low %ld",
648                                         uvalue, ct->lower_bound);
649                                 uvalue += ct->lower_bound;
650                                 if(asn_ulong2INTEGER(st, uvalue))
651                                         ASN__DECODE_FAILED;
652                         } else {
653                                 unsigned long uvalue = 0;
654                                 long svalue;
655                                 if(uper_get_constrained_whole_number(pd,
656                                         &uvalue, ct->range_bits))
657                                         ASN__DECODE_STARVED;
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)) {
663                     ASN__DECODE_FAILED;
664                 }
665                         }
666                         return rval;
667                 }
668         } else {
669                 ASN_DEBUG("Decoding unconstrained integer %s", td->name);
670         }
671
672         /* X.691, #12.2.3, #12.2.4 */
673         do {
674                 ssize_t len = 0;
675                 void *p = NULL;
676                 int ret = 0;
677
678                 /* Get the PER length */
679                 len = uper_get_length(pd, -1, 0, &repeat);
680                 if(len < 0) ASN__DECODE_STARVED;
681
682                 p = REALLOC(st->buf, st->size + len + 1);
683                 if(!p) ASN__DECODE_FAILED;
684                 st->buf = (uint8_t *)p;
685
686                 ret = per_get_many_bits(pd, &st->buf[st->size], 0, 8 * len);
687                 if(ret < 0) ASN__DECODE_STARVED;
688                 st->size += len;
689         } while(repeat);
690         st->buf[st->size] = 0;  /* JIC */
691
692         /* #12.2.3 */
693         if(ct && ct->lower_bound) {
694                 /*
695                  * TODO: replace by in-place arithmetics.
696                  */
697                 long value = 0;
698                 if(asn_INTEGER2long(st, &value))
699                         ASN__DECODE_FAILED;
700                 if(asn_imax2INTEGER(st, value + ct->lower_bound))
701                         ASN__DECODE_FAILED;
702         }
703
704         return rval;
705 }
706
707 asn_enc_rval_t
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;
715         const uint8_t *buf;
716         const uint8_t *end;
717         const asn_per_constraint_t *ct;
718         long value = 0;
719
720         if(!st || st->size == 0) ASN__ENCODE_FAILED;
721
722         if(!constraints) constraints = td->encoding_constraints.per_constraints;
723         ct = constraints ? &constraints->value : 0;
724
725         er.encoded = 0;
726
727         if(ct) {
728                 int inext = 0;
729                 if(specs && specs->field_unsigned) {
730                         unsigned long uval;
731                         if(asn_INTEGER2ulong(st, &uval))
732                                 ASN__ENCODE_FAILED;
733                         /* Check proper range */
734                         if(ct->flags & APC_SEMI_CONSTRAINED) {
735                                 if(uval < (unsigned long)ct->lower_bound)
736                                         inext = 1;
737                         } else if(ct->range_bits >= 0) {
738                                 if(uval < (unsigned long)ct->lower_bound
739                                 || uval > (unsigned long)ct->upper_bound)
740                                         inext = 1;
741                         }
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");
746                         value = uval;
747                 } else {
748                         if(asn_INTEGER2long(st, &value))
749                                 ASN__ENCODE_FAILED;
750                         /* Check proper range */
751                         if(ct->flags & APC_SEMI_CONSTRAINED) {
752                                 if(value < ct->lower_bound)
753                                         inext = 1;
754                         } else if(ct->range_bits >= 0) {
755                                 if(value < ct->lower_bound
756                                 || value > ct->upper_bound)
757                                         inext = 1;
758                         }
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");
763                 }
764                 if(ct->flags & APC_EXTENSIBLE) {
765                         if(per_put_few_bits(po, inext, 1))
766                                 ASN__ENCODE_FAILED;
767                         if(inext) ct = 0;
768                 } else if(inext) {
769                         ASN__ENCODE_FAILED;
770                 }
771         }
772
773
774         /* X.691-11/2008, #13.2.2, test if constrained whole number */
775         if(ct && ct->range_bits >= 0) {
776         unsigned long v;
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)
784                 ) {
785                         ASN_DEBUG("Value %lu to-be-encoded is outside the bounds [%lu, %lu]!",
786                                 value, ct->lower_bound, ct->upper_bound);
787                         ASN__ENCODE_FAILED;
788                 }
789                 v = (unsigned long)value - (unsigned long)ct->lower_bound;
790         } else {
791                 if(per_long_range_rebase(value, ct->lower_bound, ct->upper_bound, &v)) {
792                         ASN__ENCODE_FAILED;
793                 }
794         }
795         if(uper_put_constrained_whole_number_u(po, v, ct->range_bits))
796                 ASN__ENCODE_FAILED;
797         ASN__ENCODED_OK(er);
798         }
799
800         if(ct && ct->lower_bound) {
801                 ASN_DEBUG("Adjust lower bound to %ld", ct->lower_bound);
802                 /* TODO: adjust lower bound */
803                 ASN__ENCODE_FAILED;
804         }
805
806         for(buf = st->buf, end = st->buf + st->size; buf < end;) {
807         int need_eom = 0;
808         ssize_t mayEncode = uper_put_length(po, end - buf, &need_eom);
809         if(mayEncode < 0)
810                         ASN__ENCODE_FAILED;
811                 if(per_put_many_bits(po, buf, 8 * mayEncode))
812                         ASN__ENCODE_FAILED;
813                 buf += mayEncode;
814         if(need_eom && uper_put_length(po, 0, 0)) ASN__ENCODE_FAILED;
815     }
816
817         ASN__ENCODED_OK(er);
818 }
819
820 asn_dec_rval_t
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;
828         int repeat;
829
830         (void)opt_codec_ctx;
831
832         if(!st) {
833                 st = (INTEGER_t *)(*sptr = CALLOC(1, sizeof(*st)));
834                 if(!st) ASN__DECODE_FAILED;
835         }
836
837         if(!constraints) constraints = td->encoding_constraints.per_constraints;
838         ct = constraints ? &constraints->value : 0;
839
840         if(ct && ct->flags & APC_EXTENSIBLE) {
841                 int inext = per_get_few_bits(pd, 1);
842                 if(inext < 0) ASN__DECODE_STARVED;
843                 if(inext) ct = 0;
844         }
845
846         FREEMEM(st->buf);
847         st->buf = 0;
848         st->size = 0;
849         if(ct) {
850                 if(ct->flags & APC_SEMI_CONSTRAINED) {
851                         st->buf = (uint8_t *)CALLOC(1, 2);
852                         if(!st->buf) ASN__DECODE_FAILED;
853                         st->size = 1;
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;
858                         st->size = size;
859                 }
860         }
861
862         /* X.691, #12.2.2 */
863         if(ct && ct->flags != APC_UNCONSTRAINED) {
864                 /* #10.5.6 */
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);
870                                 int length = 0, i;
871                                 long value = 0;
872
873                                 for (i = 1; ; i++) {
874                                         int upper = 1 << i;
875                                         if (upper >= max_range_bytes)
876                                                 break;
877                                 }
878                                 ASN_DEBUG("Can encode %d (%d bytes) in %d bits", ct->range_bits,
879                                           max_range_bytes, i);
880
881                                 if ((length = per_get_few_bits(pd, i)) < 0)
882                                         ASN__DECODE_FAILED;
883
884                                 /* X.691 #12.2.6 length determinant + lb (1) */
885                                 length += 1;
886                                 ASN_DEBUG("Got length %d", length);
887                                 if (aper_get_align(pd) != 0)
888                                         ASN__DECODE_FAILED;
889                                 while (length--) {
890                                         int buf = per_get_few_bits(pd, 8);
891                                         if (buf < 0)
892                                                 ASN__DECODE_FAILED;
893                                         value += (((long)buf) << (8 * length));
894                                 }
895
896                                 value += ct->lower_bound;
897                                 if((specs && specs->field_unsigned)
898                                         ? asn_uint642INTEGER(st, (unsigned long)value)
899                                         : asn_int642INTEGER(st, value))
900                                         ASN__DECODE_FAILED;
901                                 ASN_DEBUG("Got value %ld + low %ld",
902                                           value, ct->lower_bound);
903                         } else {
904                                 long value = 0;
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)
910                                                 ASN__DECODE_FAILED;
911                                         value = per_get_few_bits(pd, ct->range_bits);
912                                         if(value < 0) ASN__DECODE_STARVED;
913                                 } else {
914                                         /* Align */
915                                         if (aper_get_align(pd) < 0)
916                                                 ASN__DECODE_FAILED;
917                                         value = per_get_few_bits(pd, 16);
918                                         if(value < 0) ASN__DECODE_STARVED;
919                                 }
920                                 value += ct->lower_bound;
921                                 if((specs && specs->field_unsigned)
922                                         ? asn_ulong2INTEGER(st, value)
923                                         : asn_long2INTEGER(st, value))
924                                         ASN__DECODE_FAILED;
925                                 ASN_DEBUG("Got value %ld + low %ld",
926                                           value, ct->lower_bound);
927                         }
928                         return rval;
929                 } else {
930                         ASN__DECODE_FAILED;
931                 }
932         } else {
933                 ASN_DEBUG("Decoding unconstrained integer %s", td->name);
934         }
935
936         /* X.691, #12.2.3, #12.2.4 */
937         do {
938                 ssize_t len;
939                 void *p;
940                 int ret;
941
942                 /* Get the PER length */
943                 len = aper_get_length(pd, -1, -1, &repeat);
944                 if(len < 0) ASN__DECODE_STARVED;
945
946                 p = REALLOC(st->buf, st->size + len + 1);
947                 if(!p) ASN__DECODE_FAILED;
948                 st->buf = (uint8_t *)p;
949
950                 ret = per_get_many_bits(pd, &st->buf[st->size], 0, 8 * len);
951                 if(ret < 0) ASN__DECODE_STARVED;
952                 st->size += len;
953         } while(repeat);
954         st->buf[st->size] = 0;  /* JIC */
955
956         /* #12.2.3 */
957         if(ct && ct->lower_bound) {
958                 /*
959                  * TODO: replace by in-place arithmetics.
960                  */
961                 long value;
962                 if(asn_INTEGER2long(st, &value))
963                         ASN__DECODE_FAILED;
964                 if(asn_long2INTEGER(st, value + ct->lower_bound))
965                         ASN__DECODE_FAILED;
966         }
967
968         return rval;
969 }
970
971 asn_enc_rval_t
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;
978         const uint8_t *buf;
979         const uint8_t *end;
980         const asn_per_constraint_t *ct;
981         long value = 0;
982
983         if(!st || st->size == 0) ASN__ENCODE_FAILED;
984
985         if(!constraints) constraints = td->encoding_constraints.per_constraints;
986         ct = constraints ? &constraints->value : 0;
987
988         er.encoded = 0;
989
990         if(ct) {
991                 int inext = 0;
992                 if(specs && specs->field_unsigned) {
993                         unsigned long uval;
994                         if(asn_INTEGER2ulong(st, &uval))
995                                 ASN__ENCODE_FAILED;
996                         /* Check proper range */
997                         if(ct->flags & APC_SEMI_CONSTRAINED) {
998                                 if(uval < (unsigned long)ct->lower_bound)
999                                         inext = 1;
1000                         } else if(ct->range_bits >= 0) {
1001                                 if(uval < (unsigned long)ct->lower_bound
1002                                         || uval > (unsigned long)ct->upper_bound)
1003                                         inext = 1;
1004                         }
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");
1009                         value = uval;
1010                 } else {
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)
1015                                         inext = 1;
1016                         } else if(ct->range_bits >= 0) {
1017                                 if(value < ct->lower_bound
1018                                         || value > ct->upper_bound)
1019                                         inext = 1;
1020                         }
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");
1025                 }
1026                 if(ct->flags & APC_EXTENSIBLE) {
1027                         if(per_put_few_bits(po, inext, 1))
1028                                 ASN__ENCODE_FAILED;
1029                         if(inext) ct = 0;
1030                 } else if(inext) {
1031                         ASN__ENCODE_FAILED;
1032                 }
1033         }
1034
1035         /* X.691, #12.2.2 */
1036         if(ct && ct->range_bits >= 0) {
1037                 unsigned long v;
1038
1039                 /* #10.5.6 */
1040                 ASN_DEBUG("Encoding integer %ld (%lu) with range %d bits",
1041                           value, value - ct->lower_bound, ct->range_bits);
1042
1043                 v = value - ct->lower_bound;
1044
1045                 /* #12 <= 8 -> alignment ? */
1046                 if (ct->range_bits < 8) {
1047                         if(per_put_few_bits(po, 0x00 | v, ct->range_bits))
1048                                 ASN__ENCODE_FAILED;
1049                 } else if (ct->range_bits == 8) {
1050                         if(aper_put_align(po) < 0)
1051                                 ASN__ENCODE_FAILED;
1052                         if(per_put_few_bits(po, 0x00 | v, ct->range_bits))
1053                                 ASN__ENCODE_FAILED;
1054                 } else if (ct->range_bits <= 16) {
1055                         /* Consume the bytes to align on octet */
1056                         if(aper_put_align(po) < 0)
1057                                 ASN__ENCODE_FAILED;
1058                         if(per_put_few_bits(po, 0x0000 | v,
1059                                             16))
1060                                 ASN__ENCODE_FAILED;
1061                 } else {
1062                         /* TODO: extend to >64 bits */
1063                         int64_t v64 = v;
1064                         int i, j;
1065                         int max_range_bytes = (ct->range_bits >> 3) +
1066                                               (((ct->range_bits % 8) > 0) ? 1 : 0);
1067
1068                         for (i = 1; ; i++) {
1069                                 int upper = 1 << i;
1070                                 if (upper >= max_range_bytes)
1071                                         break;
1072                         }
1073
1074                         for (j = sizeof(int64_t) -1; j != 0; j--) {
1075                                 int64_t val;
1076                                 val = v64 >> (j * 8);
1077                                 if (val != 0)
1078                                         break;
1079                         }
1080
1081                         /* Putting length in the minimum number of bits ex: 5 = 3bits */
1082                         if (per_put_few_bits(po, j, i))
1083                                 ASN__ENCODE_FAILED;
1084
1085                         /* Consume the bits to align on octet */
1086                         if (aper_put_align(po) < 0)
1087                                 ASN__ENCODE_FAILED;
1088                         /* Put the value */
1089                         for (i = 0; i <= j; i++) {
1090                                 if(per_put_few_bits(po, (v64 >> (8 * (j - i))) & 0xff, 8))
1091                                         ASN__ENCODE_FAILED;
1092                         }
1093                 }
1094                 ASN__ENCODED_OK(er);
1095         }
1096
1097         if(ct && ct->lower_bound) {
1098                 ASN_DEBUG("Adjust lower bound to %ld", ct->lower_bound);
1099                 /* TODO: adjust lower bound */
1100                 ASN__ENCODE_FAILED;
1101         }
1102
1103         for(buf = st->buf, end = st->buf + st->size; buf < end;) {
1104                 ssize_t mayEncode = aper_put_length(po, -1, end - buf);
1105                 if(mayEncode < 0)
1106                         ASN__ENCODE_FAILED;
1107                 if(per_put_many_bits(po, buf, 8 * mayEncode))
1108                         ASN__ENCODE_FAILED;
1109                 buf += mayEncode;
1110         }
1111
1112         ASN__ENCODED_OK(er);
1113 }
1114
1115 #endif  /* ASN_DISABLE_PER_SUPPORT */
1116
1117 static intmax_t
1118 asn__integer_convert(const uint8_t *b, const uint8_t *end) {
1119     uintmax_t value;
1120
1121     /* Perform the sign initialization */
1122     /* Actually value = -(*b >> 7); gains nothing, yet unreadable! */
1123     if((*b >> 7)) {
1124         value = (uintmax_t)(-1);
1125     } else {
1126         value = 0;
1127     }
1128
1129     /* Conversion engine */
1130     for(; b < end; b++) {
1131         value = (value << 8) | *b;
1132     }
1133
1134     return value;
1135 }
1136
1137 int
1138 asn_INTEGER2imax(const INTEGER_t *iptr, intmax_t *lptr) {
1139         uint8_t *b, *end;
1140         size_t size;
1141
1142         /* Sanity checking */
1143         if(!iptr || !iptr->buf || !lptr) {
1144                 errno = EINVAL;
1145                 return -1;
1146         }
1147
1148         /* Cache the begin/end of the buffer */
1149         b = iptr->buf;  /* Start of the INTEGER buffer */
1150         size = iptr->size;
1151         end = b + size; /* Where to stop */
1152
1153         if(size > sizeof(intmax_t)) {
1154                 uint8_t *end1 = end - 1;
1155                 /*
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)
1160                  */
1161                 /* Skip out the insignificant leading bytes */
1162                 for(; b < end1; b++) {
1163                         switch(*b) {
1164                                 case 0x00: if((b[1] & 0x80) == 0) continue; break;
1165                                 case 0xff: if((b[1] & 0x80) != 0) continue; break;
1166                         }
1167                         break;
1168                 }
1169
1170                 size = end - b;
1171                 if(size > sizeof(intmax_t)) {
1172                         /* Still cannot fit the sizeof(intmax_t) */
1173                         errno = ERANGE;
1174                         return -1;
1175                 }
1176         }
1177
1178         /* Shortcut processing of a corner case */
1179         if(end == b) {
1180                 *lptr = 0;
1181                 return 0;
1182         }
1183
1184         *lptr = asn__integer_convert(b, end);
1185         return 0;
1186 }
1187
1188 /* FIXME: negative INTEGER values are silently interpreted as large unsigned ones. */
1189 int
1190 asn_INTEGER2umax(const INTEGER_t *iptr, uintmax_t *lptr) {
1191         uint8_t *b, *end;
1192         uintmax_t value;
1193         size_t size;
1194
1195         if(!iptr || !iptr->buf || !lptr) {
1196                 errno = EINVAL;
1197                 return -1;
1198         }
1199
1200         b = iptr->buf;
1201         size = iptr->size;
1202         end = b + size;
1203
1204         /* If all extra leading bytes are zeroes, ignore them */
1205         for(; size > sizeof(value); b++, size--) {
1206                 if(*b) {
1207                         /* Value won't fit into uintmax_t */
1208                         errno = ERANGE;
1209                         return -1;
1210                 }
1211         }
1212
1213         /* Conversion engine */
1214         for(value = 0; b < end; b++)
1215                 value = (value << 8) | *b;
1216
1217         *lptr = value;
1218         return 0;
1219 }
1220
1221 int
1222 asn_umax2INTEGER(INTEGER_t *st, uintmax_t value) {
1223     uint8_t *buf;
1224     uint8_t *end;
1225     uint8_t *b;
1226     int shr;
1227
1228     if(value <= ((~(uintmax_t)0) >> 1)) {
1229         return asn_imax2INTEGER(st, value);
1230     }
1231
1232     buf = (uint8_t *)MALLOC(1 + sizeof(value));
1233     if(!buf) return -1;
1234
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);
1239
1240     if(st->buf) FREEMEM(st->buf);
1241     st->buf = buf;
1242     st->size = 1 + sizeof(value);
1243
1244         return 0;
1245 }
1246
1247 int
1248 asn_imax2INTEGER(INTEGER_t *st, intmax_t value) {
1249         uint8_t *buf, *bp;
1250         uint8_t *p;
1251         uint8_t *pstart;
1252         uint8_t *pend1;
1253         int littleEndian = 1;   /* Run-time detection */
1254         int add;
1255
1256         if(!st) {
1257                 errno = EINVAL;
1258                 return -1;
1259         }
1260
1261         buf = (uint8_t *)(long *)MALLOC(sizeof(value));
1262         if(!buf) return -1;
1263
1264         if(*(char *)&littleEndian) {
1265                 pstart = (uint8_t *)&value + sizeof(value) - 1;
1266                 pend1 = (uint8_t *)&value;
1267                 add = -1;
1268         } else {
1269                 pstart = (uint8_t *)&value;
1270                 pend1 = pstart + sizeof(value) - 1;
1271                 add = 1;
1272         }
1273
1274         /*
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.
1279          */
1280         for(p = pstart; p != pend1; p += add) {
1281                 switch(*p) {
1282                 case 0x00: if((*(p+add) & 0x80) == 0)
1283                                 continue;
1284                         break;
1285                 case 0xff: if((*(p+add) & 0x80))
1286                                 continue;
1287                         break;
1288                 }
1289                 break;
1290         }
1291         /* Copy the integer body */
1292         for(bp = buf, pend1 += add; p != pend1; p += add)
1293                 *bp++ = *p;
1294
1295         if(st->buf) FREEMEM(st->buf);
1296         st->buf = buf;
1297         st->size = bp - buf;
1298
1299         return 0;
1300 }
1301
1302 int
1303 asn_INTEGER2long(const INTEGER_t *iptr, long *l) {
1304     intmax_t v;
1305     if(asn_INTEGER2imax(iptr, &v) == 0) {
1306         if(v < LONG_MIN || v > LONG_MAX) {
1307             errno = ERANGE;
1308             return -1;
1309         }
1310         *l = v;
1311         return 0;
1312     } else {
1313         return -1;
1314     }
1315 }
1316
1317 int
1318 asn_INTEGER2ulong(const INTEGER_t *iptr, unsigned long *l) {
1319     uintmax_t v;
1320     if(asn_INTEGER2umax(iptr, &v) == 0) {
1321         if(v > ULONG_MAX) {
1322             errno = ERANGE;
1323             return -1;
1324         }
1325         *l = v;
1326         return 0;
1327     } else {
1328         return -1;
1329     }
1330 }
1331
1332 int
1333 asn_long2INTEGER(INTEGER_t *st, long value) {
1334     return asn_imax2INTEGER(st, value);
1335 }
1336
1337 int
1338 asn_ulong2INTEGER(INTEGER_t *st, unsigned long value) {
1339     return asn_imax2INTEGER(st, value);
1340 }
1341
1342
1343 int
1344 asn_uint642INTEGER(INTEGER_t *st, uint64_t value) {
1345         uint8_t *buf;
1346         uint8_t *end;
1347         uint8_t *b;
1348         int shr;
1349
1350         if(value <= INT64_MAX)
1351                 return asn_int642INTEGER(st, value);
1352
1353         buf = (uint8_t *)MALLOC(1 + sizeof(value));
1354         if(!buf) return -1;
1355
1356         end = buf + (sizeof(value) + 1);
1357         buf[0] = 0;
1358         for(b = buf + 1, shr = (sizeof(value)-1)*8; b < end; shr -= 8, b++)
1359                 *b = (uint8_t)(value >> shr);
1360
1361         if(st->buf) FREEMEM(st->buf);
1362         st->buf = buf;
1363         st->size = 1 + sizeof(value);
1364
1365         return 0;
1366 }
1367
1368 int
1369 asn_int642INTEGER(INTEGER_t *st, int64_t value) {
1370         uint8_t *buf, *bp;
1371         uint8_t *p;
1372         uint8_t *pstart;
1373         uint8_t *pend1;
1374         int littleEndian = 1;   /* Run-time detection */
1375         int add;
1376
1377         if(!st) {
1378                 errno = EINVAL;
1379                 return -1;
1380         }
1381
1382         buf = (uint8_t *)MALLOC(sizeof(value));
1383         if(!buf) return -1;
1384
1385         if(*(char *)&littleEndian) {
1386                 pstart = (uint8_t *)&value + sizeof(value) - 1;
1387                 pend1 = (uint8_t *)&value;
1388                 add = -1;
1389         } else {
1390                 pstart = (uint8_t *)&value;
1391                 pend1 = pstart + sizeof(value) - 1;
1392                 add = 1;
1393         }
1394
1395         /*
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.
1400          */
1401         for(p = pstart; p != pend1; p += add) {
1402                 switch(*p) {
1403                 case 0x00: if((*(p+add) & 0x80) == 0)
1404                                 continue;
1405                         break;
1406                 case 0xff: if((*(p+add) & 0x80))
1407                                 continue;
1408                         break;
1409                 }
1410                 break;
1411         }
1412         /* Copy the integer body */
1413         for(pstart = p, bp = buf, pend1 += add; p != pend1; p += add)
1414                 *bp++ = *p;
1415
1416         if(st->buf) FREEMEM(st->buf);
1417         st->buf = buf;
1418         st->size = bp - buf;
1419
1420         return 0;
1421 }
1422
1423 /*
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).
1428  */
1429 enum asn_strtox_result_e
1430 asn_strtoimax_lim(const char *str, const char **end, intmax_t *intp) {
1431         int sign = 1;
1432         intmax_t value;
1433
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
1438
1439         if(str >= *end) return ASN_STRTOX_ERROR_INVAL;
1440
1441         switch(*str) {
1442         case '-':
1443                 last_digit_max++;
1444                 sign = -1;
1445                 /* FALL THROUGH */
1446         case '+':
1447                 str++;
1448                 if(str >= *end) {
1449                         *end = str;
1450                         return ASN_STRTOX_EXPECT_MORE;
1451                 }
1452         }
1453
1454         for(value = 0; str < (*end); str++) {
1455                 switch(*str) {
1456                 case 0x30: case 0x31: case 0x32: case 0x33: case 0x34:
1457                 case 0x35: case 0x36: case 0x37: case 0x38: case 0x39: {
1458                         int d = *str - '0';
1459                         if(value < upper_boundary) {
1460                                 value = value * 10 + d;
1461                         } else if(value == upper_boundary) {
1462                                 if(d <= last_digit_max) {
1463                                         if(sign > 0) {
1464                                                 value = value * 10 + d;
1465                                         } else {
1466                                                 sign = 1;
1467                                                 value = -value * 10 - d;
1468                                         }
1469                                 } else {
1470                                         *end = str;
1471                                         return ASN_STRTOX_ERROR_RANGE;
1472                                 }
1473                         } else {
1474                                 *end = str;
1475                                 return ASN_STRTOX_ERROR_RANGE;
1476                         }
1477                     }
1478                     continue;
1479                 default:
1480                     *end = str;
1481                     *intp = sign * value;
1482                     return ASN_STRTOX_EXTRA_DATA;
1483                 }
1484         }
1485
1486         *end = str;
1487         *intp = sign * value;
1488         return ASN_STRTOX_OK;
1489 }
1490
1491 /*
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).
1496  */
1497 enum asn_strtox_result_e
1498 asn_strtoumax_lim(const char *str, const char **end, uintmax_t *uintp) {
1499         uintmax_t value;
1500
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
1505
1506     if(str >= *end) return ASN_STRTOX_ERROR_INVAL;
1507
1508         switch(*str) {
1509         case '-':
1510         return ASN_STRTOX_ERROR_INVAL;
1511         case '+':
1512                 str++;
1513                 if(str >= *end) {
1514                         *end = str;
1515                         return ASN_STRTOX_EXPECT_MORE;
1516                 }
1517         }
1518
1519         for(value = 0; str < (*end); str++) {
1520                 switch(*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;
1529                 } else {
1530                                         *end = str;
1531                                         return ASN_STRTOX_ERROR_RANGE;
1532                                 }
1533                         } else {
1534                                 *end = str;
1535                                 return ASN_STRTOX_ERROR_RANGE;
1536                         }
1537                     }
1538                     continue;
1539                 default:
1540                     *end = str;
1541                     *uintp = value;
1542                     return ASN_STRTOX_EXTRA_DATA;
1543                 }
1544         }
1545
1546         *end = str;
1547         *uintp = value;
1548         return ASN_STRTOX_OK;
1549 }
1550
1551 enum asn_strtox_result_e
1552 asn_strtol_lim(const char *str, const char **end, long *lp) {
1553     intmax_t value;
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;
1561     case ASN_STRTOX_OK:
1562         if(value >= LONG_MIN && value <= LONG_MAX) {
1563             *lp = value;
1564             return ASN_STRTOX_OK;
1565         } else {
1566             return ASN_STRTOX_ERROR_RANGE;
1567         }
1568     case ASN_STRTOX_EXTRA_DATA:
1569         if(value >= LONG_MIN && value <= LONG_MAX) {
1570             *lp = value;
1571             return ASN_STRTOX_EXTRA_DATA;
1572         } else {
1573             return ASN_STRTOX_ERROR_RANGE;
1574         }
1575     }
1576
1577     assert(!"Unreachable");
1578     return ASN_STRTOX_ERROR_INVAL;
1579 }
1580
1581 enum asn_strtox_result_e
1582 asn_strtoul_lim(const char *str, const char **end, unsigned long *ulp) {
1583     uintmax_t value;
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;
1591     case ASN_STRTOX_OK:
1592         if(value <= ULONG_MAX) {
1593             *ulp = value;
1594             return ASN_STRTOX_OK;
1595         } else {
1596             return ASN_STRTOX_ERROR_RANGE;
1597         }
1598     case ASN_STRTOX_EXTRA_DATA:
1599         if(value <= ULONG_MAX) {
1600             *ulp = value;
1601             return ASN_STRTOX_EXTRA_DATA;
1602         } else {
1603             return ASN_STRTOX_ERROR_RANGE;
1604         }
1605     }
1606
1607     assert(!"Unreachable");
1608     return ASN_STRTOX_ERROR_INVAL;
1609 }
1610
1611 int
1612 INTEGER_compare(const asn_TYPE_descriptor_t *td, const void *aptr,
1613                      const void *bptr) {
1614     const INTEGER_t *a = aptr;
1615     const INTEGER_t *b = bptr;
1616
1617     (void)td;
1618
1619     if(a && b) {
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;
1623
1624             if(sign_a < sign_b) return -1;
1625             if(sign_a > sign_b) return 1;
1626
1627             /* The shortest integer wins, unless comparing negatives */
1628             if(a->size < b->size) {
1629                 return -1 * sign_a;
1630             } else if(a->size > b->size) {
1631                 return 1 * sign_b;
1632             }
1633
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;
1637             return (1) * sign;
1638         } else if(b->size) {
1639             int sign = (a->buf[0] & 0x80) ? -1 : 1;
1640             return (-1) * sign;
1641         } else {
1642             return 0;
1643         }
1644     } else if(!a && !b) {
1645         return 0;
1646     } else if(!a) {
1647         return -1;
1648     } else {
1649         return 1;
1650     }
1651
1652 }
1653
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;
1665     size_t emap_len;
1666     intmax_t value;
1667     int find_inside_map;
1668
1669     if(max_length == 0) return result_skipped;
1670
1671     if(st == NULL) {
1672         st = (INTEGER_t *)CALLOC(1, sizeof(*st));
1673         if(st == NULL) {
1674             return result_failed;
1675         }
1676     }
1677
1678     if(specs) {
1679         emap = specs->value2enum;
1680         emap_len = specs->map_count;
1681         if(specs->strict_enumeration) {
1682             find_inside_map = emap_len > 0;
1683         } else {
1684             find_inside_map = emap_len ? asn_random_between(0, 1) : 0;
1685         }
1686     } else {
1687         emap = 0;
1688         emap_len = 0;
1689         find_inside_map = 0;
1690     }
1691
1692     if(find_inside_map) {
1693         assert(emap_len > 0);
1694         value = emap[asn_random_between(0, emap_len - 1)].nat_value;
1695     } else {
1696         const asn_per_constraints_t *ct;
1697
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)];
1708         } else {
1709             value = variants[asn_random_between(
1710                 0, sizeof(variants) / sizeof(variants[0]) - 1)];
1711         }
1712
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);
1719             }
1720         }
1721     }
1722
1723     if(asn_imax2INTEGER(st, value)) {
1724         if(st == *sptr) {
1725             ASN_STRUCT_RESET(*td, st);
1726         } else {
1727             ASN_STRUCT_FREE(*td, st);
1728         }
1729         return result_failed;
1730     } else {
1731         *sptr = st;
1732         result_ok.length = st->size;
1733         return result_ok;
1734     }
1735 }