blob: 5e93ac8ac5be29c62680fc18ddb7c70d8711cd59 [file] [log] [blame]
Harald Welte92c45f32010-06-12 18:59:38 +02001/*-
Harald Welteec0e2172010-07-20 00:03:44 +02002 * Copyright (c) 2004, 2006 Lev Walkin <vlm@lionet.info>. All rights reserved.
Harald Welte92c45f32010-06-12 18:59:38 +02003 * Redistribution and modifications are permitted subject to BSD license.
4 */
5#if defined(__alpha)
6#define _ISOC99_SOURCE /* For quiet NAN, through bits/nan.h */
7#define _BSD_SOURCE /* To reintroduce finite(3) */
8#include <sys/resource.h> /* For INFINITY */
9#endif
10#include <asn_internal.h>
11#include <stdlib.h> /* for strtod(3) */
12#include <math.h>
13#include <errno.h>
14#include <REAL.h>
Harald Welteec0e2172010-07-20 00:03:44 +020015#include <OCTET_STRING.h>
Harald Welte92c45f32010-06-12 18:59:38 +020016
17#undef INT_MAX
18#define INT_MAX ((int)(((unsigned int)-1) >> 1))
19
20#if !(defined(NAN) || defined(INFINITY))
Harald Welteec0e2172010-07-20 00:03:44 +020021static volatile double real_zero GCC_NOTUSED = 0.0;
Harald Welte92c45f32010-06-12 18:59:38 +020022#endif
23#ifndef NAN
24#define NAN (real_zero/real_zero)
25#endif
26#ifndef INFINITY
27#define INFINITY (1.0/real_zero)
28#endif
29
30/*
31 * REAL basic type description.
32 */
33static ber_tlv_tag_t asn_DEF_REAL_tags[] = {
34 (ASN_TAG_CLASS_UNIVERSAL | (9 << 2))
35};
36asn_TYPE_descriptor_t asn_DEF_REAL = {
37 "REAL",
38 "REAL",
39 ASN__PRIMITIVE_TYPE_free,
40 REAL_print,
41 asn_generic_no_constraint,
42 ber_decode_primitive,
43 der_encode_primitive,
44 REAL_decode_xer,
45 REAL_encode_xer,
Harald Welteec0e2172010-07-20 00:03:44 +020046 REAL_decode_uper,
47 REAL_encode_uper,
Harald Welte92c45f32010-06-12 18:59:38 +020048 0, /* Use generic outmost tag fetcher */
49 asn_DEF_REAL_tags,
50 sizeof(asn_DEF_REAL_tags) / sizeof(asn_DEF_REAL_tags[0]),
51 asn_DEF_REAL_tags, /* Same as above */
52 sizeof(asn_DEF_REAL_tags) / sizeof(asn_DEF_REAL_tags[0]),
53 0, /* No PER visible constraints */
54 0, 0, /* No members */
55 0 /* No specifics */
56};
57
58typedef enum specialRealValue {
59 SRV__NOT_A_NUMBER,
60 SRV__MINUS_INFINITY,
61 SRV__PLUS_INFINITY
62} specialRealValue_e;
63static struct specialRealValue_s {
64 char *string;
65 size_t length;
66 long dv;
67} specialRealValue[] = {
68#define SRV_SET(foo, val) { foo, sizeof(foo) - 1, val }
69 SRV_SET("<NOT-A-NUMBER/>", 0),
70 SRV_SET("<MINUS-INFINITY/>", -1),
71 SRV_SET("<PLUS-INFINITY/>", 1),
72#undef SRV_SET
73};
74
75ssize_t
76REAL__dump(double d, int canonical, asn_app_consume_bytes_f *cb, void *app_key) {
77 char local_buf[64];
78 char *buf = local_buf;
79 ssize_t buflen = sizeof(local_buf);
80 const char *fmt = canonical?"%.15E":"%.15f";
81 ssize_t ret;
82
83 /*
84 * Check whether it is a special value.
85 */
86 /* fpclassify(3) is not portable yet */
87 if(isnan(d)) {
88 buf = specialRealValue[SRV__NOT_A_NUMBER].string;
89 buflen = specialRealValue[SRV__NOT_A_NUMBER].length;
90 return (cb(buf, buflen, app_key) < 0) ? -1 : buflen;
91 } else if(!finite(d)) {
92 if(copysign(1.0, d) < 0.0) {
93 buf = specialRealValue[SRV__MINUS_INFINITY].string;
94 buflen = specialRealValue[SRV__MINUS_INFINITY].length;
95 } else {
96 buf = specialRealValue[SRV__PLUS_INFINITY].string;
97 buflen = specialRealValue[SRV__PLUS_INFINITY].length;
98 }
99 return (cb(buf, buflen, app_key) < 0) ? -1 : buflen;
100 } else if(ilogb(d) <= -INT_MAX) {
101 if(copysign(1.0, d) < 0.0) {
102 buf = "-0";
103 buflen = 2;
104 } else {
105 buf = "0";
106 buflen = 1;
107 }
108 return (cb(buf, buflen, app_key) < 0) ? -1 : buflen;
109 }
110
111 /*
112 * Use the libc's double printing, hopefully they got it right.
113 */
114 do {
115 ret = snprintf(buf, buflen, fmt, d);
116 if(ret < 0) {
117 buflen <<= 1;
118 } else if(ret >= buflen) {
119 buflen = ret + 1;
120 } else {
121 buflen = ret;
122 break;
123 }
124 if(buf != local_buf) FREEMEM(buf);
125 buf = (char *)MALLOC(buflen);
126 if(!buf) return -1;
127 } while(1);
128
129 if(canonical) {
130 /*
131 * Transform the "[-]d.dddE+-dd" output into "[-]d.dddE[-]d"
132 * Check that snprintf() constructed the output correctly.
133 */
134 char *dot, *E;
135 char *end = buf + buflen;
136 char *last_zero;
137
138 dot = (buf[0] == 0x2d /* '-' */) ? (buf + 2) : (buf + 1);
139 if(*dot >= 0x30) {
140 errno = EINVAL;
141 return -1; /* Not a dot, really */
142 }
143 *dot = 0x2e; /* Replace possible comma */
144
145 for(last_zero = dot + 2, E = dot; dot < end; E++) {
146 if(*E == 0x45) {
147 char *expptr = ++E;
148 char *s = expptr;
149 int sign;
150 if(*expptr == 0x2b /* '+' */) {
151 /* Skip the "+" */
152 buflen -= 1;
153 sign = 0;
154 } else {
155 sign = 1;
156 s++;
157 }
158 expptr++;
159 if(expptr > end) {
160 errno = EINVAL;
161 return -1;
162 }
163 if(*expptr == 0x30) {
164 buflen--;
165 expptr++;
166 }
167 if(*last_zero == 0x30) {
168 *last_zero = 0x45; /* E */
169 buflen -= s - (last_zero + 1);
170 s = last_zero + 1;
171 if(sign) {
172 *s++ = 0x2d /* '-' */;
173 buflen++;
174 }
175 }
176 for(; expptr <= end; s++, expptr++)
177 *s = *expptr;
178 break;
179 } else if(*E == 0x30) {
180 if(*last_zero != 0x30)
181 last_zero = E;
182 }
183 }
184 if(E == end) {
185 errno = EINVAL;
186 return -1; /* No promised E */
187 }
188 } else {
189 /*
190 * Remove trailing zeros.
191 */
192 char *end = buf + buflen;
193 char *last_zero = end;
194 int stoplooking = 0;
195 char *z;
196 for(z = end - 1; z > buf; z--) {
197 switch(*z) {
198 case 0x30:
199 if(!stoplooking)
200 last_zero = z;
201 continue;
202 case 0x31: case 0x32: case 0x33: case 0x34:
203 case 0x35: case 0x36: case 0x37: case 0x38: case 0x39:
204 stoplooking = 1;
205 continue;
206 default: /* Catch dot and other separators */
207 /*
208 * Replace possible comma (which may even
209 * be not a comma at all: locale-defined).
210 */
211 *z = 0x2e;
212 if(last_zero == z + 1) { /* leave x.0 */
213 last_zero++;
214 }
215 buflen = last_zero - buf;
216 *last_zero = '\0';
217 break;
218 }
219 break;
220 }
221 }
222
223 ret = cb(buf, buflen, app_key);
224 if(buf != local_buf) FREEMEM(buf);
225 return (ret < 0) ? -1 : buflen;
226}
227
228int
229REAL_print(asn_TYPE_descriptor_t *td, const void *sptr, int ilevel,
230 asn_app_consume_bytes_f *cb, void *app_key) {
231 const REAL_t *st = (const REAL_t *)sptr;
232 ssize_t ret;
233 double d;
234
235 (void)td; /* Unused argument */
236 (void)ilevel; /* Unused argument */
237
238 if(!st || !st->buf)
239 ret = cb("<absent>", 8, app_key);
240 else if(asn_REAL2double(st, &d))
241 ret = cb("<error>", 7, app_key);
242 else
243 ret = REAL__dump(d, 0, cb, app_key);
244
245 return (ret < 0) ? -1 : 0;
246}
247
248asn_enc_rval_t
249REAL_encode_xer(asn_TYPE_descriptor_t *td, void *sptr,
250 int ilevel, enum xer_encoder_flags_e flags,
251 asn_app_consume_bytes_f *cb, void *app_key) {
252 REAL_t *st = (REAL_t *)sptr;
253 asn_enc_rval_t er;
254 double d;
255
256 (void)ilevel;
257
258 if(!st || !st->buf || asn_REAL2double(st, &d))
259 _ASN_ENCODE_FAILED;
260
261 er.encoded = REAL__dump(d, flags & XER_F_CANONICAL, cb, app_key);
262 if(er.encoded < 0) _ASN_ENCODE_FAILED;
263
264 _ASN_ENCODED_OK(er);
265}
266
267
268/*
269 * Decode the chunk of XML text encoding REAL.
270 */
271static enum xer_pbd_rval
272REAL__xer_body_decode(asn_TYPE_descriptor_t *td, void *sptr, const void *chunk_buf, size_t chunk_size) {
273 REAL_t *st = (REAL_t *)sptr;
274 double value;
275 const char *xerdata = (const char *)chunk_buf;
276 char *endptr = 0;
277 char *b;
278
279 (void)td;
280
281 if(!chunk_size) return XPBD_BROKEN_ENCODING;
282
283 /*
284 * Decode an XMLSpecialRealValue: <MINUS-INFINITY>, etc.
285 */
286 if(xerdata[0] == 0x3c /* '<' */) {
287 size_t i;
288 for(i = 0; i < sizeof(specialRealValue)
289 / sizeof(specialRealValue[0]); i++) {
290 struct specialRealValue_s *srv = &specialRealValue[i];
291 double dv;
292
293 if(srv->length != chunk_size
294 || memcmp(srv->string, chunk_buf, chunk_size))
295 continue;
296
297 /*
298 * It could've been done using
299 * (double)srv->dv / real_zero,
300 * but it summons fp exception on some platforms.
301 */
302 switch(srv->dv) {
303 case -1: dv = - INFINITY; break;
304 case 0: dv = NAN; break;
305 case 1: dv = INFINITY; break;
306 default: return XPBD_SYSTEM_FAILURE;
307 }
308
309 if(asn_double2REAL(st, dv))
310 return XPBD_SYSTEM_FAILURE;
311
312 return XPBD_BODY_CONSUMED;
313 }
314 ASN_DEBUG("Unknown XMLSpecialRealValue");
315 return XPBD_BROKEN_ENCODING;
316 }
317
318 /*
319 * Copy chunk into the nul-terminated string, and run strtod.
320 */
321 b = (char *)MALLOC(chunk_size + 1);
322 if(!b) return XPBD_SYSTEM_FAILURE;
323 memcpy(b, chunk_buf, chunk_size);
324 b[chunk_size] = 0; /* nul-terminate */
325
326 value = strtod(b, &endptr);
327 FREEMEM(b);
328 if(endptr == b) return XPBD_BROKEN_ENCODING;
329
330 if(asn_double2REAL(st, value))
331 return XPBD_SYSTEM_FAILURE;
332
333 return XPBD_BODY_CONSUMED;
334}
335
336asn_dec_rval_t
337REAL_decode_xer(asn_codec_ctx_t *opt_codec_ctx,
338 asn_TYPE_descriptor_t *td, void **sptr, const char *opt_mname,
339 const void *buf_ptr, size_t size) {
340
341 return xer_decode_primitive(opt_codec_ctx, td,
342 sptr, sizeof(REAL_t), opt_mname,
343 buf_ptr, size, REAL__xer_body_decode);
344}
345
Harald Welteec0e2172010-07-20 00:03:44 +0200346asn_dec_rval_t
347REAL_decode_uper(asn_codec_ctx_t *opt_codec_ctx,
348 asn_TYPE_descriptor_t *td, asn_per_constraints_t *constraints,
349 void **sptr, asn_per_data_t *pd) {
350 (void)constraints; /* No PER visible constraints */
351 return OCTET_STRING_decode_uper(opt_codec_ctx, td, 0, sptr, pd);
352}
353
354asn_enc_rval_t
355REAL_encode_uper(asn_TYPE_descriptor_t *td,
356 asn_per_constraints_t *constraints, void *sptr, asn_per_outp_t *po) {
357 (void)constraints; /* No PER visible constraints */
358 return OCTET_STRING_encode_uper(td, 0, sptr, po);
359}
Harald Welte92c45f32010-06-12 18:59:38 +0200360
361int
362asn_REAL2double(const REAL_t *st, double *dbl_value) {
363 unsigned int octv;
364
365 if(!st || !st->buf) {
366 errno = EINVAL;
367 return -1;
368 }
369
370 if(st->size == 0) {
371 *dbl_value = 0;
372 return 0;
373 }
374
375 octv = st->buf[0]; /* unsigned byte */
376
377 switch(octv & 0xC0) {
378 case 0x40: /* X.690: 8.5.8 */
379 /* "SpecialRealValue" */
380
381 /* Be liberal in what you accept...
382 if(st->size != 1) ...
383 */
384
385 switch(st->buf[0]) {
386 case 0x40: /* 01000000: PLUS-INFINITY */
387 *dbl_value = INFINITY;
388 return 0;
389 case 0x41: /* 01000001: MINUS-INFINITY */
390 *dbl_value = - INFINITY;
391 return 0;
392 /*
393 * The following cases are defined by
394 * X.690 Amendment 1 (10/03)
395 */
396 case 0x42: /* 01000010: NOT-A-NUMBER */
397 *dbl_value = NAN;
398 return 0;
399 case 0x43: /* 01000011: minus zero */
400 *dbl_value = -0.0;
401 return 0;
402 }
403
404 errno = EINVAL;
405 return -1;
406 case 0x00: { /* X.690: 8.5.6 */
407 /*
408 * Decimal. NR{1,2,3} format.
409 */
410 double d;
411
412 assert(st->buf[st->size - 1] == 0); /* Security, vashu mat' */
413
414 d = strtod((char *)st->buf, 0);
415 if(finite(d)) {
416 *dbl_value = d;
417 return 0;
418 } else {
419 errno = ERANGE;
420 return 0;
421 }
422 }
423 }
424
425 /*
426 * Binary representation.
427 */
428 {
429 double m;
430 int expval; /* exponent value */
431 unsigned int elen; /* exponent value length, in octets */
432 unsigned int scaleF;
433 unsigned int baseF;
434 uint8_t *ptr;
435 uint8_t *end;
436 int sign;
437
438 switch((octv & 0x30) >> 4) {
439 case 0x00: baseF = 1; break; /* base 2 */
440 case 0x01: baseF = 3; break; /* base 8 */
441 case 0x02: baseF = 4; break; /* base 16 */
442 default:
443 /* Reserved field, can't parse now. */
444 errno = EINVAL;
445 return -1;
446 }
447
448 sign = (octv & 0x40); /* bit 7 */
449 scaleF = (octv & 0x0C) >> 2; /* bits 4 to 3 */
450
451 if(st->size <= (int)(1 + (octv & 0x03))) {
452 errno = EINVAL;
453 return -1;
454 }
455
Harald Welteec0e2172010-07-20 00:03:44 +0200456 elen = (octv & 0x03); /* bits 2 to 1; 8.5.6.4 */
457 if(elen == 0x03) { /* bits 2 to 1 = 11; 8.5.6.4, case d) */
Harald Welte92c45f32010-06-12 18:59:38 +0200458 elen = st->buf[1]; /* unsigned binary number */
459 if(elen == 0 || st->size <= (int)(2 + elen)) {
460 errno = EINVAL;
461 return -1;
462 }
Harald Welteec0e2172010-07-20 00:03:44 +0200463 /* FIXME: verify constraints of case d) */
Harald Welte92c45f32010-06-12 18:59:38 +0200464 ptr = &st->buf[2];
465 } else {
Harald Welte92c45f32010-06-12 18:59:38 +0200466 ptr = &st->buf[1];
467 }
468
469 /* Fetch the multibyte exponent */
470 expval = (int)(*(int8_t *)ptr);
471 end = ptr + elen + 1;
472 for(ptr++; ptr < end; ptr++)
473 expval = (expval * 256) + *ptr;
474
475 m = 0.0; /* Initial mantissa value */
476
477 /* Okay, the exponent is here. Now, what about mantissa? */
478 end = st->buf + st->size;
479 if(ptr < end) {
480 for(; ptr < end; ptr++)
481 m = ldexp(m, 8) + *ptr;
482 }
483
484 if(0)
485 ASN_DEBUG("m=%.10f, scF=%d, bF=%d, expval=%d, ldexp()=%f, ldexp()=%f",
486 m, scaleF, baseF, expval,
487 ldexp(m, expval * baseF + scaleF),
488 ldexp(m, scaleF) * pow(pow(2, baseF), expval)
489 );
490
491 /*
492 * (S * N * 2^F) * B^E
493 * Essentially:
494 m = ldexp(m, scaleF) * pow(pow(2, base), expval);
495 */
496 m = ldexp(m, expval * baseF + scaleF);
497 if(finite(m)) {
498 *dbl_value = sign ? -m : m;
499 } else {
500 errno = ERANGE;
501 return -1;
502 }
503
504 } /* if(binary_format) */
505
506 return 0;
507}
508
509/*
510 * Assume IEEE 754 floating point: standard 64 bit double.
511 * [1 bit sign] [11 bits exponent] [52 bits mantissa]
512 */
513int
514asn_double2REAL(REAL_t *st, double dbl_value) {
515#ifdef WORDS_BIGENDIAN /* Known to be big-endian */
516 int littleEndian = 0;
517#else /* need to test: have no explicit information */
518 unsigned int LE = 1;
519 int littleEndian = *(unsigned char *)&LE;
520#endif
521 uint8_t buf[16]; /* More than enough for 8-byte dbl_value */
522 uint8_t dscr[sizeof(dbl_value)]; /* double value scratch pad */
523 /* Assertion guards: won't even compile, if unexpected double size */
Harald Welteec0e2172010-07-20 00:03:44 +0200524 char assertion_buffer1[9 - sizeof(dbl_value)] GCC_NOTUSED;
525 char assertion_buffer2[sizeof(dbl_value) - 7] GCC_NOTUSED;
Harald Welte92c45f32010-06-12 18:59:38 +0200526 uint8_t *ptr = buf;
527 uint8_t *mstop; /* Last byte of mantissa */
528 unsigned int mval; /* Value of the last byte of mantissa */
529 unsigned int bmsign; /* binary mask with sign */
530 unsigned int buflen;
531 unsigned int accum;
532 int expval;
533
534 if(!st) {
535 errno = EINVAL;
536 return -1;
537 }
538
539 /*
540 * ilogb(+-0) returns -INT_MAX or INT_MIN (platform-dependent)
541 * ilogb(+-inf) returns INT_MAX, logb(+-inf) returns +inf
542 * ilogb(NaN) returns INT_MIN or INT_MAX (platform-dependent)
543 */
544 expval = ilogb(dbl_value);
545 if(expval <= -INT_MAX /* Also catches +-0 and maybe isnan() */
546 || expval == INT_MAX /* catches isfin() and maybe isnan() */
547 ) {
548 if(!st->buf || st->size < 2) {
549 ptr = (uint8_t *)MALLOC(2);
550 if(!ptr) return -1;
551 st->buf = ptr;
552 }
553 /* fpclassify(3) is not portable yet */
554 if(isnan(dbl_value)) {
555 st->buf[0] = 0x42; /* NaN */
556 st->buf[1] = 0;
557 st->size = 1;
558 } else if(!finite(dbl_value)) {
559 if(copysign(1.0, dbl_value) < 0.0) {
560 st->buf[0] = 0x41; /* MINUS-INFINITY */
561 } else {
562 st->buf[0] = 0x40; /* PLUS-INFINITY */
563 }
564 st->buf[1] = 0;
565 st->size = 1;
566 } else {
567 if(copysign(1.0, dbl_value) < 0.0) {
568 st->buf[0] = 0x80 | 0x40;
569 st->buf[1] = 0;
570 st->size = 2;
571 } else {
572 /* no content octets: positive zero */
573 st->buf[0] = 0; /* JIC */
574 st->size = 0;
575 }
576 }
577 return 0;
578 }
579
580 if(littleEndian) {
581 uint8_t *s = ((uint8_t *)&dbl_value) + sizeof(dbl_value) - 2;
582 uint8_t *start = ((uint8_t *)&dbl_value);
583 uint8_t *d;
584
585 bmsign = 0x80 | ((s[1] >> 1) & 0x40); /* binary mask & - */
586 for(mstop = d = dscr; s >= start; d++, s--) {
587 *d = *s;
588 if(*d) mstop = d;
589 }
590 } else {
591 uint8_t *s = ((uint8_t *)&dbl_value) + 1;
592 uint8_t *end = ((uint8_t *)&dbl_value) + sizeof(double);
593 uint8_t *d;
594
595 bmsign = 0x80 | ((s[-1] >> 1) & 0x40); /* binary mask & - */
596 for(mstop = d = dscr; s < end; d++, s++) {
597 *d = *s;
598 if(*d) mstop = d;
599 }
600 }
601
602 /* Remove parts of the exponent, leave mantissa and explicit 1. */
603 dscr[0] = 0x10 | (dscr[0] & 0x0f);
604
605 /* Adjust exponent in a very unobvious way */
606 expval -= 8 * ((mstop - dscr) + 1) - 4;
607
608 /* This loop ensures DER conformance by forcing mantissa odd: 11.3.1 */
609 mval = *mstop;
610 if(mval && !(mval & 1)) {
611 unsigned int shift_count = 1;
612 unsigned int ishift;
613 uint8_t *mptr;
614
615 /*
616 * Figure out what needs to be done to make mantissa odd.
617 */
618 if(!(mval & 0x0f)) /* Speed-up a little */
619 shift_count = 4;
620 while(((mval >> shift_count) & 1) == 0)
621 shift_count++;
622
623 ishift = 8 - shift_count;
624 accum = 0;
625
626 /* Go over the buffer, shifting it shift_count bits right. */
627 for(mptr = dscr; mptr <= mstop; mptr++) {
628 mval = *mptr;
629 *mptr = accum | (mval >> shift_count);
630 accum = mval << ishift;
631 }
632
633 /* Adjust mantissa appropriately. */
634 expval += shift_count;
635 }
636
637 if(expval < 0) {
638 if((expval >> 7) == -1) {
639 *ptr++ = bmsign | 0x00;
640 *ptr++ = expval;
641 } else if((expval >> 15) == -1) {
642 *ptr++ = bmsign | 0x01;
643 *ptr++ = expval >> 8;
644 *ptr++ = expval;
645 } else {
646 *ptr++ = bmsign | 0x02;
647 *ptr++ = expval >> 16;
648 *ptr++ = expval >> 8;
649 *ptr++ = expval;
650 }
651 } else if(expval <= 0x7f) {
652 *ptr++ = bmsign | 0x00;
653 *ptr++ = expval;
654 } else if(expval <= 0x7fff) {
655 *ptr++ = bmsign | 0x01;
656 *ptr++ = expval >> 8;
657 *ptr++ = expval;
658 } else {
659 assert(expval <= 0x7fffff);
660 *ptr++ = bmsign | 0x02;
661 *ptr++ = expval >> 16;
662 *ptr++ = expval >> 8;
663 *ptr++ = expval;
664 }
665
666 buflen = (mstop - dscr) + 1;
667 memcpy(ptr, dscr, buflen);
668 ptr += buflen;
669 buflen = ptr - buf;
670
671 ptr = (uint8_t *)MALLOC(buflen + 1);
672 if(!ptr) return -1;
673
674 memcpy(ptr, buf, buflen);
675 buf[buflen] = 0; /* JIC */
676
677 if(st->buf) FREEMEM(st->buf);
678 st->buf = ptr;
679 st->size = buflen;
680
681 return 0;
682}