1 /****************************************************************************
2 **
3 ** Copyright (C) 2018 Intel Corporation
4 **
5 ** Permission is hereby granted, free of charge, to any person obtaining a copy
6 ** of this software and associated documentation files (the "Software"), to deal
7 ** in the Software without restriction, including without limitation the rights
8 ** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 ** copies of the Software, and to permit persons to whom the Software is
10 ** furnished to do so, subject to the following conditions:
11 **
12 ** The above copyright notice and this permission notice shall be included in
13 ** all copies or substantial portions of the Software.
14 **
15 ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 ** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 ** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 ** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 ** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 ** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 ** THE SOFTWARE.
22 **
23 ****************************************************************************/
24 
25 #ifndef CBORINTERNAL_P_H
26 #define CBORINTERNAL_P_H
27 
28 #include "compilersupport_p.h"
29 
30 #ifndef CBOR_NO_FLOATING_POINT
31 #  include <float.h>
32 #  include <math.h>
33 #else
34 #  ifndef CBOR_NO_HALF_FLOAT_TYPE
35 #    define CBOR_NO_HALF_FLOAT_TYPE     1
36 #  endif
37 #endif
38 
39 #ifndef CBOR_NO_HALF_FLOAT_TYPE
40 #  ifdef __F16C__
41 #    include <immintrin.h>
encode_half(double val)42 static inline unsigned short encode_half(double val)
43 {
44     return _cvtss_sh((float)val, 3);
45 }
decode_half(unsigned short half)46 static inline double decode_half(unsigned short half)
47 {
48     return _cvtsh_ss(half);
49 }
50 #  else
51 /* software implementation of float-to-fp16 conversions */
encode_half(double val)52 static inline unsigned short encode_half(double val)
53 {
54     uint64_t v;
55     int sign, exp, mant;
56     memcpy(&v, &val, sizeof(v));
57     sign = v >> 63 << 15;
58     exp = (v >> 52) & 0x7ff;
59     mant = v << 12 >> 12 >> (53-11);    /* keep only the 11 most significant bits of the mantissa */
60     exp -= 1023;
61     if (exp == 1024) {
62         /* infinity or NaN */
63         exp = 16;
64         mant >>= 1;
65     } else if (exp >= 16) {
66         /* overflow, as largest number */
67         exp = 15;
68         mant = 1023;
69     } else if (exp >= -14) {
70         /* regular normal */
71     } else if (exp >= -24) {
72         /* subnormal */
73         mant |= 1024;
74         mant >>= -(exp + 14);
75         exp = -15;
76     } else {
77         /* underflow, make zero */
78         return 0;
79     }
80 
81     /* safe cast here as bit operations above guarantee not to overflow */
82     return (unsigned short)(sign | ((exp + 15) << 10) | mant);
83 }
84 
85 /* this function was copied & adapted from RFC 7049 Appendix D */
decode_half(unsigned short half)86 static inline double decode_half(unsigned short half)
87 {
88     int exp = (half >> 10) & 0x1f;
89     int mant = half & 0x3ff;
90     double val;
91     if (exp == 0) val = ldexp(mant, -24);
92     else if (exp != 31) val = ldexp(mant + 1024, exp - 25);
93     else val = mant == 0 ? INFINITY : NAN;
94     return half & 0x8000 ? -val : val;
95 }
96 #  endif
97 #endif /* CBOR_NO_HALF_FLOAT_TYPE */
98 
99 #ifndef CBOR_INTERNAL_API
100 #  define CBOR_INTERNAL_API
101 #endif
102 
103 #ifndef CBOR_PARSER_MAX_RECURSIONS
104 #  define CBOR_PARSER_MAX_RECURSIONS 1024
105 #endif
106 
107 #ifndef CBOR_ENCODER_WRITER_CONTROL
108 #  define CBOR_ENCODER_WRITER_CONTROL   0
109 #endif
110 #ifndef CBOR_PARSER_READER_CONTROL
111 #  define CBOR_PARSER_READER_CONTROL    0
112 #endif
113 
114 /*
115  * CBOR Major types
116  * Encoded in the high 3 bits of the descriptor byte
117  * See http://tools.ietf.org/html/rfc7049#section-2.1
118  */
119 typedef enum CborMajorTypes {
120     UnsignedIntegerType = 0U,
121     NegativeIntegerType = 1U,
122     ByteStringType = 2U,
123     TextStringType = 3U,
124     ArrayType = 4U,
125     MapType = 5U,           /* a.k.a. object */
126     TagType = 6U,
127     SimpleTypesType = 7U
128 } CborMajorTypes;
129 
130 /*
131  * CBOR simple and floating point types
132  * Encoded in the low 8 bits of the descriptor byte when the
133  * Major Type is 7.
134  */
135 typedef enum CborSimpleTypes {
136     FalseValue              = 20,
137     TrueValue               = 21,
138     NullValue               = 22,
139     UndefinedValue          = 23,
140     SimpleTypeInNextByte    = 24,   /* not really a simple type */
141     HalfPrecisionFloat      = 25,   /* ditto */
142     SinglePrecisionFloat    = 26,   /* ditto */
143     DoublePrecisionFloat    = 27,   /* ditto */
144     Break                   = 31
145 } CborSimpleTypes;
146 
147 enum {
148     SmallValueBitLength     = 5U,
149     SmallValueMask          = (1U << SmallValueBitLength) - 1,      /* 31 */
150     Value8Bit               = 24U,
151     Value16Bit              = 25U,
152     Value32Bit              = 26U,
153     Value64Bit              = 27U,
154     IndefiniteLength        = 31U,
155 
156     MajorTypeShift          = SmallValueBitLength,
157     MajorTypeMask           = (int) (~0U << MajorTypeShift),
158 
159     BreakByte               = (unsigned)Break | (SimpleTypesType << MajorTypeShift)
160 };
161 
copy_current_position(CborValue * dst,const CborValue * src)162 static inline void copy_current_position(CborValue *dst, const CborValue *src)
163 {
164     /* This "if" is here for pedantry only: the two branches should perform
165      * the same memory operation. */
166     if (src->parser->flags & CborParserFlag_ExternalSource)
167         dst->source.token = src->source.token;
168     else
169         dst->source.ptr = src->source.ptr;
170 }
171 
can_read_bytes(const CborValue * it,size_t n)172 static inline bool can_read_bytes(const CborValue *it, size_t n)
173 {
174     if (CBOR_PARSER_READER_CONTROL >= 0) {
175         if (it->parser->flags & CborParserFlag_ExternalSource || CBOR_PARSER_READER_CONTROL != 0) {
176 #ifdef CBOR_PARSER_CAN_READ_BYTES_FUNCTION
177             return CBOR_PARSER_CAN_READ_BYTES_FUNCTION(it->source.token, n);
178 #else
179             return it->parser->source.ops->can_read_bytes(it->source.token, n);
180 #endif
181         }
182     }
183 
184     /* Convert the pointer subtraction to size_t since end >= ptr
185      * (this prevents issues with (ptrdiff_t)n becoming negative).
186      */
187     return (size_t)(it->parser->source.end - it->source.ptr) >= n;
188 }
189 
advance_bytes(CborValue * it,size_t n)190 static inline void advance_bytes(CborValue *it, size_t n)
191 {
192     if (CBOR_PARSER_READER_CONTROL >= 0) {
193         if (it->parser->flags & CborParserFlag_ExternalSource || CBOR_PARSER_READER_CONTROL != 0) {
194 #ifdef CBOR_PARSER_ADVANCE_BYTES_FUNCTION
195             CBOR_PARSER_ADVANCE_BYTES_FUNCTION(it->source.token, n);
196 #else
197             it->parser->source.ops->advance_bytes(it->source.token, n);
198 #endif
199             return;
200         }
201     }
202 
203     it->source.ptr += n;
204 }
205 
transfer_string(CborValue * it,const void ** ptr,size_t offset,size_t len)206 static inline CborError transfer_string(CborValue *it, const void **ptr, size_t offset, size_t len)
207 {
208     if (CBOR_PARSER_READER_CONTROL >= 0) {
209         if (it->parser->flags & CborParserFlag_ExternalSource || CBOR_PARSER_READER_CONTROL != 0) {
210 #ifdef CBOR_PARSER_TRANSFER_STRING_FUNCTION
211             return CBOR_PARSER_TRANSFER_STRING_FUNCTION(it->source.token, ptr, offset, len);
212 #else
213             return it->parser->source.ops->transfer_string(it->source.token, ptr, offset, len);
214 #endif
215         }
216     }
217 
218     it->source.ptr += offset;
219     if (can_read_bytes(it, len)) {
220         *CONST_CAST(const void **, ptr) = it->source.ptr;
221         it->source.ptr += len;
222         return CborNoError;
223     }
224     return CborErrorUnexpectedEOF;
225 }
226 
read_bytes_unchecked(const CborValue * it,void * dst,size_t offset,size_t n)227 static inline void *read_bytes_unchecked(const CborValue *it, void *dst, size_t offset, size_t n)
228 {
229     if (CBOR_PARSER_READER_CONTROL >= 0) {
230         if (it->parser->flags & CborParserFlag_ExternalSource || CBOR_PARSER_READER_CONTROL != 0) {
231 #ifdef CBOR_PARSER_READ_BYTES_FUNCTION
232             return CBOR_PARSER_READ_BYTES_FUNCTION(it->source.token, dst, offset, n);
233 #else
234             return it->parser->source.ops->read_bytes(it->source.token, dst, offset, n);
235 #endif
236         }
237     }
238 
239     return memcpy(dst, it->source.ptr + offset, n);
240 }
241 
242 #ifdef __GNUC__
243 __attribute__((warn_unused_result))
244 #endif
read_bytes(const CborValue * it,void * dst,size_t offset,size_t n)245 static inline void *read_bytes(const CborValue *it, void *dst, size_t offset, size_t n)
246 {
247     if (can_read_bytes(it, offset + n))
248         return read_bytes_unchecked(it, dst, offset, n);
249     return NULL;
250 }
251 
read_uint8(const CborValue * it,size_t offset)252 static inline uint16_t read_uint8(const CborValue *it, size_t offset)
253 {
254     uint8_t result;
255     read_bytes_unchecked(it, &result, offset, sizeof(result));
256     return result;
257 }
258 
read_uint16(const CborValue * it,size_t offset)259 static inline uint16_t read_uint16(const CborValue *it, size_t offset)
260 {
261     uint16_t result;
262     read_bytes_unchecked(it, &result, offset, sizeof(result));
263     return cbor_ntohs(result);
264 }
265 
read_uint32(const CborValue * it,size_t offset)266 static inline uint32_t read_uint32(const CborValue *it, size_t offset)
267 {
268     uint32_t result;
269     read_bytes_unchecked(it, &result, offset, sizeof(result));
270     return cbor_ntohl(result);
271 }
272 
read_uint64(const CborValue * it,size_t offset)273 static inline uint64_t read_uint64(const CborValue *it, size_t offset)
274 {
275     uint64_t result;
276     read_bytes_unchecked(it, &result, offset, sizeof(result));
277     return cbor_ntohll(result);
278 }
279 
extract_number_checked(const CborValue * it,uint64_t * value,size_t * bytesUsed)280 static inline CborError extract_number_checked(const CborValue *it, uint64_t *value, size_t *bytesUsed)
281 {
282     uint8_t descriptor;
283     size_t bytesNeeded = 0;
284 
285     /* We've already verified that there's at least one byte to be read */
286     read_bytes_unchecked(it, &descriptor, 0, 1);
287     descriptor &= SmallValueMask;
288     if (descriptor < Value8Bit) {
289         *value = descriptor;
290     } else if (unlikely(descriptor > Value64Bit)) {
291         return CborErrorIllegalNumber;
292     } else {
293         bytesNeeded = (size_t)(1 << (descriptor - Value8Bit));
294         if (!can_read_bytes(it, 1 + bytesNeeded))
295             return CborErrorUnexpectedEOF;
296         if (descriptor <= Value16Bit) {
297             if (descriptor == Value16Bit)
298                 *value = read_uint16(it, 1);
299             else
300                 *value = read_uint8(it, 1);
301         } else {
302             if (descriptor == Value32Bit)
303                 *value = read_uint32(it, 1);
304             else
305                 *value = read_uint64(it, 1);
306         }
307     }
308 
309     if (bytesUsed)
310         *bytesUsed = bytesNeeded;
311     return CborNoError;
312 }
313 
314 #endif /* CBORINTERNAL_P_H */
315