Moving in e2sim originally from it/test/simulators
[sim/e2-interface.git] / e2sim / ASN1c / NativeInteger.c
1 /*****************************************************************************
2 #                                                                            *
3 # Copyright 2019 AT&T Intellectual Property                                  *
4 #                                                                            *
5 # Licensed under the Apache License, Version 2.0 (the "License");            *
6 # you may not use this file except in compliance with the License.           *
7 # You may obtain a copy of the License at                                    *
8 #                                                                            *
9 #      http://www.apache.org/licenses/LICENSE-2.0                            *
10 #                                                                            *
11 # Unless required by applicable law or agreed to in writing, software        *
12 # distributed under the License is distributed on an "AS IS" BASIS,          *
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   *
14 # See the License for the specific language governing permissions and        *
15 # limitations under the License.                                             *
16 #                                                                            *
17 ******************************************************************************/
18
19 /*-
20  * Copyright (c) 2004, 2005, 2006 Lev Walkin <vlm@lionet.info>.
21  * All rights reserved.
22  * Redistribution and modifications are permitted subject to BSD license.
23  */
24 /*
25  * Read the NativeInteger.h for the explanation wrt. differences between
26  * INTEGER and NativeInteger.
27  * Basically, both are decoders and encoders of ASN.1 INTEGER type, but this
28  * implementation deals with the standard (machine-specific) representation
29  * of them instead of using the platform-independent buffer.
30  */
31 #include <asn_internal.h>
32 #include <NativeInteger.h>
33
34 /*
35  * NativeInteger basic type description.
36  */
37 static const ber_tlv_tag_t asn_DEF_NativeInteger_tags[] = {
38         (ASN_TAG_CLASS_UNIVERSAL | (2 << 2))
39 };
40 asn_TYPE_operation_t asn_OP_NativeInteger = {
41         NativeInteger_free,
42         NativeInteger_print,
43         NativeInteger_compare,
44         NativeInteger_decode_ber,
45         NativeInteger_encode_der,
46         NativeInteger_decode_xer,
47         NativeInteger_encode_xer,
48 #ifdef  ASN_DISABLE_OER_SUPPORT
49         0,
50         0,
51 #else
52         NativeInteger_decode_oer,       /* OER decoder */
53         NativeInteger_encode_oer,       /* Canonical OER encoder */
54 #endif  /* ASN_DISABLE_OER_SUPPORT */
55 #ifdef  ASN_DISABLE_PER_SUPPORT
56         0,
57         0,
58         0,
59         0,
60 #else
61         NativeInteger_decode_uper,      /* Unaligned PER decoder */
62         NativeInteger_encode_uper,      /* Unaligned PER encoder */
63         NativeInteger_decode_aper,      /* Aligned PER decoder */
64         NativeInteger_encode_aper,      /* Aligned PER encoder */
65 #endif  /* ASN_DISABLE_PER_SUPPORT */
66         NativeInteger_random_fill,
67         0       /* Use generic outmost tag fetcher */
68 };
69 asn_TYPE_descriptor_t asn_DEF_NativeInteger = {
70         "INTEGER",                      /* The ASN.1 type is still INTEGER */
71         "INTEGER",
72         &asn_OP_NativeInteger,
73         asn_DEF_NativeInteger_tags,
74         sizeof(asn_DEF_NativeInteger_tags) / sizeof(asn_DEF_NativeInteger_tags[0]),
75         asn_DEF_NativeInteger_tags,     /* Same as above */
76         sizeof(asn_DEF_NativeInteger_tags) / sizeof(asn_DEF_NativeInteger_tags[0]),
77         { 0, 0, asn_generic_no_constraint },
78         0, 0,   /* No members */
79         0       /* No specifics */
80 };
81
82 /*
83  * Decode INTEGER type.
84  */
85 asn_dec_rval_t
86 NativeInteger_decode_ber(const asn_codec_ctx_t *opt_codec_ctx,
87                          const asn_TYPE_descriptor_t *td, void **nint_ptr,
88                          const void *buf_ptr, size_t size, int tag_mode) {
89     const asn_INTEGER_specifics_t *specs =
90         (const asn_INTEGER_specifics_t *)td->specifics;
91     long *native = (long *)*nint_ptr;
92         asn_dec_rval_t rval;
93         ber_tlv_len_t length;
94
95         /*
96          * If the structure is not there, allocate it.
97          */
98         if(native == NULL) {
99                 native = (long *)(*nint_ptr = CALLOC(1, sizeof(*native)));
100                 if(native == NULL) {
101                         rval.code = RC_FAIL;
102                         rval.consumed = 0;
103                         return rval;
104                 }
105         }
106
107         ASN_DEBUG("Decoding %s as INTEGER (tm=%d)",
108                 td->name, tag_mode);
109
110         /*
111          * Check tags.
112          */
113         rval = ber_check_tags(opt_codec_ctx, td, 0, buf_ptr, size,
114                         tag_mode, 0, &length, 0);
115         if(rval.code != RC_OK)
116                 return rval;
117
118         ASN_DEBUG("%s length is %d bytes", td->name, (int)length);
119
120         /*
121          * Make sure we have this length.
122          */
123         buf_ptr = ((const char *)buf_ptr) + rval.consumed;
124         size -= rval.consumed;
125         if(length > (ber_tlv_len_t)size) {
126                 rval.code = RC_WMORE;
127                 rval.consumed = 0;
128                 return rval;
129         }
130
131         /*
132          * ASN.1 encoded INTEGER: buf_ptr, length
133          * Fill the native, at the same time checking for overflow.
134          * If overflow occured, return with RC_FAIL.
135          */
136         {
137                 INTEGER_t tmp;
138                 union {
139                         const void *constbuf;
140                         void *nonconstbuf;
141                 } unconst_buf;
142                 long l;
143
144                 unconst_buf.constbuf = buf_ptr;
145                 tmp.buf = (uint8_t *)unconst_buf.nonconstbuf;
146                 tmp.size = length;
147
148                 if((specs&&specs->field_unsigned)
149                         ? asn_INTEGER2ulong(&tmp, (unsigned long *)&l) /* sic */
150                         : asn_INTEGER2long(&tmp, &l)) {
151                         rval.code = RC_FAIL;
152                         rval.consumed = 0;
153                         return rval;
154                 }
155
156                 *native = l;
157         }
158
159         rval.code = RC_OK;
160         rval.consumed += length;
161
162         ASN_DEBUG("Took %ld/%ld bytes to encode %s (%ld)",
163                 (long)rval.consumed, (long)length, td->name, (long)*native);
164
165         return rval;
166 }
167
168 /*
169  * Encode the NativeInteger using the standard INTEGER type DER encoder.
170  */
171 asn_enc_rval_t
172 NativeInteger_encode_der(const asn_TYPE_descriptor_t *sd, const void *ptr,
173                          int tag_mode, ber_tlv_tag_t tag,
174                          asn_app_consume_bytes_f *cb, void *app_key) {
175         unsigned long native = *(const unsigned long *)ptr; /* Disable sign ext. */
176         asn_enc_rval_t erval = {0,0,0};
177         INTEGER_t tmp;
178
179 #ifdef  WORDS_BIGENDIAN         /* Opportunistic optimization */
180
181         tmp.buf = (uint8_t *)&native;
182         tmp.size = sizeof(native);
183
184 #else   /* Works even if WORDS_BIGENDIAN is not set where should've been */
185         uint8_t buf[sizeof(native)];
186         uint8_t *p;
187
188         /* Prepare a fake INTEGER */
189         for(p = buf + sizeof(buf) - 1; p >= buf; p--, native >>= 8)
190                 *p = (uint8_t)native;
191
192         tmp.buf = buf;
193         tmp.size = sizeof(buf);
194 #endif  /* WORDS_BIGENDIAN */
195         
196         /* Encode fake INTEGER */
197         erval = INTEGER_encode_der(sd, &tmp, tag_mode, tag, cb, app_key);
198     if(erval.structure_ptr == &tmp) {
199         erval.structure_ptr = ptr;
200     }
201         return erval;
202 }
203
204 /*
205  * Decode the chunk of XML text encoding INTEGER.
206  */
207 asn_dec_rval_t
208 NativeInteger_decode_xer(const asn_codec_ctx_t *opt_codec_ctx,
209                          const asn_TYPE_descriptor_t *td, void **sptr,
210                          const char *opt_mname, const void *buf_ptr,
211                          size_t size) {
212     const asn_INTEGER_specifics_t *specs =
213         (const asn_INTEGER_specifics_t *)td->specifics;
214     asn_dec_rval_t rval;
215         INTEGER_t st;
216         void *st_ptr = (void *)&st;
217         long *native = (long *)*sptr;
218
219         if(!native) {
220                 native = (long *)(*sptr = CALLOC(1, sizeof(*native)));
221                 if(!native) ASN__DECODE_FAILED;
222         }
223
224         memset(&st, 0, sizeof(st));
225         rval = INTEGER_decode_xer(opt_codec_ctx, td, &st_ptr, 
226                 opt_mname, buf_ptr, size);
227         if(rval.code == RC_OK) {
228                 long l;
229                 if((specs&&specs->field_unsigned)
230                         ? asn_INTEGER2ulong(&st, (unsigned long *)&l) /* sic */
231                         : asn_INTEGER2long(&st, &l)) {
232                         rval.code = RC_FAIL;
233                         rval.consumed = 0;
234                 } else {
235                         *native = l;
236                 }
237         } else {
238                 /*
239                  * Cannot restart from the middle;
240                  * there is no place to save state in the native type.
241                  * Request a continuation from the very beginning.
242                  */
243                 rval.consumed = 0;
244         }
245         ASN_STRUCT_FREE_CONTENTS_ONLY(asn_DEF_INTEGER, &st);
246         return rval;
247 }
248
249
250 asn_enc_rval_t
251 NativeInteger_encode_xer(const asn_TYPE_descriptor_t *td, const void *sptr,
252                          int ilevel, enum xer_encoder_flags_e flags,
253                          asn_app_consume_bytes_f *cb, void *app_key) {
254     const asn_INTEGER_specifics_t *specs =
255         (const asn_INTEGER_specifics_t *)td->specifics;
256     char scratch[32];   /* Enough for 64-bit int */
257         asn_enc_rval_t er = {0,0,0};
258         const long *native = (const long *)sptr;
259
260         (void)ilevel;
261         (void)flags;
262
263         if(!native) ASN__ENCODE_FAILED;
264
265         er.encoded = snprintf(scratch, sizeof(scratch),
266                         (specs && specs->field_unsigned)
267                         ? "%lu" : "%ld", *native);
268         if(er.encoded <= 0 || (size_t)er.encoded >= sizeof(scratch)
269                 || cb(scratch, er.encoded, app_key) < 0)
270                 ASN__ENCODE_FAILED;
271
272         ASN__ENCODED_OK(er);
273 }
274
275 #ifndef  ASN_DISABLE_PER_SUPPORT
276
277 asn_dec_rval_t
278 NativeInteger_decode_uper(const asn_codec_ctx_t *opt_codec_ctx,
279                           const asn_TYPE_descriptor_t *td,
280                           const asn_per_constraints_t *constraints, void **sptr,
281                           asn_per_data_t *pd) {
282     const asn_INTEGER_specifics_t *specs =
283         (const asn_INTEGER_specifics_t *)td->specifics;
284     asn_dec_rval_t rval;
285         long *native = (long *)*sptr;
286         INTEGER_t tmpint;
287         void *tmpintptr = &tmpint;
288
289         (void)opt_codec_ctx;
290         ASN_DEBUG("Decoding NativeInteger %s (UPER)", td->name);
291
292         if(!native) {
293                 native = (long *)(*sptr = CALLOC(1, sizeof(*native)));
294                 if(!native) ASN__DECODE_FAILED;
295         }
296
297         memset(&tmpint, 0, sizeof tmpint);
298         rval = INTEGER_decode_uper(opt_codec_ctx, td, constraints,
299                                    &tmpintptr, pd);
300         if(rval.code == RC_OK) {
301                 if((specs&&specs->field_unsigned)
302                         ? asn_INTEGER2ulong(&tmpint, (unsigned long *)native)
303                         : asn_INTEGER2long(&tmpint, native))
304                         rval.code = RC_FAIL;
305                 else
306                         ASN_DEBUG("NativeInteger %s got value %ld",
307                                 td->name, *native);
308         }
309         ASN_STRUCT_FREE_CONTENTS_ONLY(asn_DEF_INTEGER, &tmpint);
310
311         return rval;
312 }
313
314 asn_enc_rval_t
315 NativeInteger_encode_uper(const asn_TYPE_descriptor_t *td,
316                           const asn_per_constraints_t *constraints,
317                           const void *sptr, asn_per_outp_t *po) {
318     const asn_INTEGER_specifics_t *specs =
319         (const asn_INTEGER_specifics_t *)td->specifics;
320     asn_enc_rval_t er = {0,0,0};
321         long native;
322         INTEGER_t tmpint;
323
324         if(!sptr) ASN__ENCODE_FAILED;
325
326     native = *(const long *)sptr;
327
328     ASN_DEBUG("Encoding NativeInteger %s %ld (UPER)", td->name, native);
329
330         memset(&tmpint, 0, sizeof(tmpint));
331         if((specs&&specs->field_unsigned)
332                 ? asn_ulong2INTEGER(&tmpint, native)
333                 : asn_long2INTEGER(&tmpint, native))
334                 ASN__ENCODE_FAILED;
335         er = INTEGER_encode_uper(td, constraints, &tmpint, po);
336         ASN_STRUCT_FREE_CONTENTS_ONLY(asn_DEF_INTEGER, &tmpint);
337         return er;
338 }
339
340 asn_dec_rval_t
341 NativeInteger_decode_aper(const asn_codec_ctx_t *opt_codec_ctx,
342                           const asn_TYPE_descriptor_t *td,
343                           const asn_per_constraints_t *constraints, void **sptr, asn_per_data_t *pd) {
344
345         const asn_INTEGER_specifics_t *specs = (const asn_INTEGER_specifics_t *)td->specifics;
346         asn_dec_rval_t rval;
347         long *native = (long *)*sptr;
348         INTEGER_t tmpint;
349         void *tmpintptr = &tmpint;
350
351         (void)opt_codec_ctx;
352         ASN_DEBUG("Decoding NativeInteger %s (APER)", td->name);
353
354         if(!native) {
355                 native = (long *)(*sptr = CALLOC(1, sizeof(*native)));
356                 if(!native) ASN__DECODE_FAILED;
357         }
358
359         memset(&tmpint, 0, sizeof tmpint);
360         rval = INTEGER_decode_aper(opt_codec_ctx, td, constraints,
361                                    &tmpintptr, pd);
362         if(rval.code == RC_OK) {
363                 if((specs&&specs->field_unsigned)
364                         ? asn_INTEGER2ulong(&tmpint, (unsigned long *)native)
365                         : asn_INTEGER2long(&tmpint, native))
366                         rval.code = RC_FAIL;
367                 else
368                         ASN_DEBUG("NativeInteger %s got value %ld",
369                                   td->name, *native);
370         }
371         ASN_STRUCT_FREE_CONTENTS_ONLY(asn_DEF_INTEGER, &tmpint);
372
373         return rval;
374 }
375
376 asn_enc_rval_t
377 NativeInteger_encode_aper(const asn_TYPE_descriptor_t *td,
378                           const asn_per_constraints_t *constraints,
379                           const void *sptr, asn_per_outp_t *po) {
380
381         const asn_INTEGER_specifics_t *specs = (const asn_INTEGER_specifics_t *)td->specifics;
382         asn_enc_rval_t er = {0,0,0};
383         long native;
384         INTEGER_t tmpint;
385
386         if(!sptr) ASN__ENCODE_FAILED;
387
388         native = *(const long *)sptr;
389
390         ASN_DEBUG("Encoding NativeInteger %s %ld (APER)", td->name, native);
391
392         memset(&tmpint, 0, sizeof(tmpint));
393         if((specs&&specs->field_unsigned)
394                 ? asn_ulong2INTEGER(&tmpint, (unsigned long)native)
395                 : asn_long2INTEGER(&tmpint, native))
396                 ASN__ENCODE_FAILED;
397         er = INTEGER_encode_aper(td, constraints, &tmpint, po);
398         ASN_STRUCT_FREE_CONTENTS_ONLY(asn_DEF_INTEGER, &tmpint);
399         return er;
400 }
401
402 #endif  /* ASN_DISABLE_PER_SUPPORT */
403
404 /*
405  * INTEGER specific human-readable output.
406  */
407 int
408 NativeInteger_print(const asn_TYPE_descriptor_t *td, const void *sptr,
409                     int ilevel, asn_app_consume_bytes_f *cb, void *app_key) {
410     const asn_INTEGER_specifics_t *specs =
411         (const asn_INTEGER_specifics_t *)td->specifics;
412     const long *native = (const long *)sptr;
413     char scratch[32]; /* Enough for 64-bit int */
414     int ret;
415
416     (void)td;       /* Unused argument */
417     (void)ilevel;   /* Unused argument */
418
419     if(native) {
420         long value = *native;
421         ret = snprintf(scratch, sizeof(scratch),
422                        (specs && specs->field_unsigned) ? "%lu" : "%ld", value);
423         assert(ret > 0 && (size_t)ret < sizeof(scratch));
424         if(cb(scratch, ret, app_key) < 0) return -1;
425         if(specs && (value >= 0 || !specs->field_unsigned)) {
426             const asn_INTEGER_enum_map_t *el =
427                 INTEGER_map_value2enum(specs, value);
428             if(el) {
429                 if(cb(" (", 2, app_key) < 0) return -1;
430                 if(cb(el->enum_name, el->enum_len, app_key) < 0) return -1;
431                 if(cb(")", 1, app_key) < 0) return -1;
432             }
433         }
434         return 0;
435         } else {
436                 return (cb("<absent>", 8, app_key) < 0) ? -1 : 0;
437         }
438 }
439
440 void
441 NativeInteger_free(const asn_TYPE_descriptor_t *td, void *ptr,
442                    enum asn_struct_free_method method) {
443     if(!td || !ptr)
444                 return;
445
446         ASN_DEBUG("Freeing %s as INTEGER (%d, %p, Native)",
447                 td->name, method, ptr);
448
449     switch(method) {
450     case ASFM_FREE_EVERYTHING:
451         FREEMEM(ptr);
452         break;
453     case ASFM_FREE_UNDERLYING:
454         break;
455     case ASFM_FREE_UNDERLYING_AND_RESET:
456         memset(ptr, 0, sizeof(long));
457         break;
458     }
459 }
460
461 int
462 NativeInteger_compare(const asn_TYPE_descriptor_t *td, const void *aptr, const void *bptr) {
463     (void)td;
464
465     if(aptr && bptr) {
466         const asn_INTEGER_specifics_t *specs =
467             (const asn_INTEGER_specifics_t *)td->specifics;
468         if(specs && specs->field_unsigned) {
469             const unsigned long *a = aptr;
470             const unsigned long *b = bptr;
471             if(*a < *b) {
472                 return -1;
473             } else if(*a > *b) {
474                 return 1;
475             } else {
476                 return 0;
477             }
478         } else {
479             const long *a = aptr;
480             const long *b = bptr;
481             if(*a < *b) {
482                 return -1;
483             } else if(*a > *b) {
484                 return 1;
485             } else {
486                 return 0;
487             }
488         }
489     } else if(!aptr) {
490         return -1;
491     } else {
492         return 1;
493     }
494 }
495
496 asn_random_fill_result_t
497 NativeInteger_random_fill(const asn_TYPE_descriptor_t *td, void **sptr,
498                           const asn_encoding_constraints_t *constraints,
499                           size_t max_length) {
500     const asn_INTEGER_specifics_t *specs =
501         (const asn_INTEGER_specifics_t *)td->specifics;
502     asn_random_fill_result_t result_ok = {ARFILL_OK, 1};
503     asn_random_fill_result_t result_failed = {ARFILL_FAILED, 0};
504     asn_random_fill_result_t result_skipped = {ARFILL_SKIPPED, 0};
505     long *st = *sptr;
506     const asn_INTEGER_enum_map_t *emap;
507     size_t emap_len;
508     intmax_t value;
509     int find_inside_map;
510
511     if(max_length == 0) return result_skipped;
512
513     if(st == NULL) {
514         st = (long *)CALLOC(1, sizeof(*st));
515         if(st == NULL) {
516             return result_failed;
517         }
518     }
519
520     if(specs) {
521         emap = specs->value2enum;
522         emap_len = specs->map_count;
523         if(specs->strict_enumeration) {
524             find_inside_map = emap_len > 0;
525         } else {
526             find_inside_map = emap_len ? asn_random_between(0, 1) : 0;
527         }
528     } else {
529         emap = 0;
530         emap_len = 0;
531         find_inside_map = 0;
532     }
533
534     if(find_inside_map) {
535         assert(emap_len > 0);
536         value = emap[asn_random_between(0, emap_len - 1)].nat_value;
537     } else {
538         const asn_per_constraints_t *ct;
539
540         static const long variants[] = {
541             -65536, -65535, -65534, -32769, -32768, -32767, -16385, -16384,
542             -16383, -257,   -256,   -255,   -254,   -129,   -128,   -127,
543             -126,   -1,     0,      1,      126,    127,    128,    129,
544             254,    255,    256,    257,    16383,  16384,  16385,  32767,
545             32768,  32769,  65534,  65535,  65536,  65537};
546         if(specs && specs->field_unsigned) {
547             assert(variants[18] == 0);
548             value = variants[asn_random_between(
549                 18, sizeof(variants) / sizeof(variants[0]) - 1)];
550         } else {
551             value = variants[asn_random_between(
552                 0, sizeof(variants) / sizeof(variants[0]) - 1)];
553         }
554
555         if(!constraints) constraints = &td->encoding_constraints;
556         ct = constraints ? constraints->per_constraints : 0;
557         if(ct && (ct->value.flags & APC_CONSTRAINED)) {
558             if(value < ct->value.lower_bound || value > ct->value.upper_bound) {
559                 value = asn_random_between(ct->value.lower_bound,
560                                            ct->value.upper_bound);
561             }
562         }
563     }
564
565     *sptr = st;
566     *st = value;
567     return result_ok;
568 }