blob: 8eaeb434c6a82d688d0d30f6821f265f2009e8cc [file] [log] [blame]
Laurence Lundbladeb69cad72018-09-13 11:09:01 -07001/*==============================================================================
Laurence Lundbladed92a6162018-11-01 11:38:35 +07002 Copyright (c) 2016-2018, The Linux Foundation.
3 Copyright (c) 2018, Laurence Lundblade.
4 All rights reserved.
Laurence Lundblade624405d2018-09-18 20:10:47 -07005
Laurence Lundblade0dbc9172018-11-01 14:17:21 +07006Redistribution and use in source and binary forms, with or without
7modification, are permitted provided that the following conditions are
8met:
9 * Redistributions of source code must retain the above copyright
10 notice, this list of conditions and the following disclaimer.
11 * Redistributions in binary form must reproduce the above
12 copyright notice, this list of conditions and the following
13 disclaimer in the documentation and/or other materials provided
14 with the distribution.
15 * Neither the name of The Linux Foundation nor the names of its
16 contributors, nor the name "Laurence Lundblade" may be used to
17 endorse or promote products derived from this software without
18 specific prior written permission.
Laurence Lundblade624405d2018-09-18 20:10:47 -070019
Laurence Lundblade0dbc9172018-11-01 14:17:21 +070020THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
21WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
22MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
23ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
24BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
27BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
28WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
29OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
30IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Laurence Lundblade624405d2018-09-18 20:10:47 -070031 ==============================================================================*/
32
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070033/*===================================================================================
34 FILE: qcbor_decode.c
35
36 DESCRIPTION: This file contains the implementation of QCBOR.
37
38 EDIT HISTORY FOR FILE:
39
40 This section contains comments describing changes made to the module.
41 Notice that changes are listed in reverse chronological order.
42
43 when who what, where, why
44 -------- ---- ---------------------------------------------------
Laurence Lundblade8b06e2e2018-12-04 12:26:51 +090045 11/9/18 llundblade Error codes are now enums.
46 11/2/18 llundblade Simplify float decoding and align with preferred
47 float encoding
48 10/31/18 llundblade Switch to one license that is almost BSD-3.
49 10/28/18 llundblade Reworked tag decoding
50 10/15/18 llundblade Indefinite length maps and arrays supported
51 10/8/18 llundblade Indefinite length strings supported
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070052 02/04/17 llundbla Work on CPUs that don's require pointer alignment
53 by making use of changes in UsefulBuf
54 03/01/17 llundbla More data types; decoding improvements and fixes
55 11/13/16 llundbla Integrate most TZ changes back into github version.
56 09/30/16 gkanike Porting to TZ.
57 03/15/16 llundbla Initial Version.
58
59 =====================================================================================*/
60
61#include "qcbor.h"
Laurence Lundblade12d32c52018-09-19 11:25:27 -070062#include "ieee754.h"
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070063
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070064
Laurence Lundblade7e0d13b2018-10-16 19:54:13 +053065/*
66 This casts away the const-ness of a pointer, usually so it can be
67 freed or realloced.
68 */
69#define UNCONST_POINTER(ptr) ((void *)(ptr))
70
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070071
72/*
Laurence Lundblade3a760b02018-10-08 13:46:03 +080073 Collection of functions to track the map/array nesting for decoding
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070074 */
75
76inline static int IsMapOrArray(uint8_t uDataType)
77{
78 return uDataType == QCBOR_TYPE_MAP || uDataType == QCBOR_TYPE_ARRAY;
79}
80
81inline static int DecodeNesting_IsNested(const QCBORDecodeNesting *pNesting)
82{
83 return pNesting->pCurrent != &(pNesting->pMapsAndArrays[0]);
84}
85
Laurence Lundblade041ffa52018-10-07 11:43:51 +070086inline static int DecodeNesting_IsIndefiniteLength(const QCBORDecodeNesting *pNesting)
Laurence Lundblade0f99d692018-09-26 14:39:28 -070087{
Laurence Lundblade0f99d692018-09-26 14:39:28 -070088 return pNesting->pCurrent->uCount == UINT16_MAX;
89}
90
Laurence Lundblade3a760b02018-10-08 13:46:03 +080091inline static uint8_t DecodeNesting_GetLevel(QCBORDecodeNesting *pNesting)
92{
93 return pNesting->pCurrent - &(pNesting->pMapsAndArrays[0]);
94}
95
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070096inline static int DecodeNesting_TypeIsMap(const QCBORDecodeNesting *pNesting)
97{
Laurence Lundblade0f99d692018-09-26 14:39:28 -070098 if(!DecodeNesting_IsNested(pNesting)) {
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070099 return 0;
Laurence Lundblade0f99d692018-09-26 14:39:28 -0700100 }
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700101
102 return CBOR_MAJOR_TYPE_MAP == pNesting->pCurrent->uMajorType;
103}
104
Laurence Lundblade3a760b02018-10-08 13:46:03 +0800105// Process a break. This will either ascend the nesting or error out
Laurence Lundblade30816f22018-11-10 13:40:22 +0700106inline static QCBORError DecodeNesting_BreakAscend(QCBORDecodeNesting *pNesting)
Laurence Lundblade041ffa52018-10-07 11:43:51 +0700107{
Laurence Lundblade3a760b02018-10-08 13:46:03 +0800108 // breaks must always occur when there is nesting
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700109 if(!DecodeNesting_IsNested(pNesting)) {
Laurence Lundblade3a760b02018-10-08 13:46:03 +0800110 return QCBOR_ERR_BAD_BREAK;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700111 }
112
Laurence Lundblade3a760b02018-10-08 13:46:03 +0800113 // breaks can only occur when the map/array is indefinite length
114 if(!DecodeNesting_IsIndefiniteLength(pNesting)) {
115 return QCBOR_ERR_BAD_BREAK;
116 }
117
118 // if all OK, the break reduces the level of nesting
119 pNesting->pCurrent--;
120
121 return QCBOR_SUCCESS;
122}
123
124// Called on every single item except breaks including the opening of a map/array
125inline static void DecodeNesting_DecrementCount(QCBORDecodeNesting *pNesting)
126{
127 if(!DecodeNesting_IsNested(pNesting)) {
128 // at top level where there is no tracking
129 return;
130 }
131
132 if(DecodeNesting_IsIndefiniteLength(pNesting)) {
133 // There is no count for indefinite length arrays/maps
134 return;
135 }
136
137 // Decrement the count of items in this array/map
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700138 pNesting->pCurrent->uCount--;
Laurence Lundblade0f99d692018-09-26 14:39:28 -0700139
Laurence Lundblade3a760b02018-10-08 13:46:03 +0800140 // Pop up nesting levels if the counts at the levels are zero
141 while(DecodeNesting_IsNested(pNesting) && 0 == pNesting->pCurrent->uCount) {
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700142 pNesting->pCurrent--;
Laurence Lundblade9e3651c2018-10-10 11:49:55 +0800143 if(!DecodeNesting_IsIndefiniteLength(pNesting)) {
144 pNesting->pCurrent->uCount--;
145 }
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700146 }
147}
148
Laurence Lundblade3a760b02018-10-08 13:46:03 +0800149// Called on every map/array
Laurence Lundblade30816f22018-11-10 13:40:22 +0700150inline static QCBORError DecodeNesting_Descend(QCBORDecodeNesting *pNesting, QCBORItem *pItem)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700151{
Laurence Lundblade30816f22018-11-10 13:40:22 +0700152 QCBORError nReturn = QCBOR_SUCCESS;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700153
Laurence Lundblade3a760b02018-10-08 13:46:03 +0800154 if(pItem->val.uCount == 0) {
155 // Nothing to do for empty definite lenth arrays. They are just are
156 // effectively the same as an item that is not a map or array
157 goto Done;
Laurence Lundbladea44d5062018-10-17 18:45:12 +0530158 // Empty indefinite length maps and arrays are handled elsewhere
Laurence Lundblade3a760b02018-10-08 13:46:03 +0800159 }
160
161 // Error out if arrays is too long to handle
162 if(pItem->val.uCount != UINT16_MAX && pItem->val.uCount > QCBOR_MAX_ITEMS_IN_ARRAY) {
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700163 nReturn = QCBOR_ERR_ARRAY_TOO_LONG;
164 goto Done;
165 }
166
Laurence Lundblade3a760b02018-10-08 13:46:03 +0800167 // Error out if nesting is too deep
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700168 if(pNesting->pCurrent >= &(pNesting->pMapsAndArrays[QCBOR_MAX_ARRAY_NESTING])) {
169 nReturn = QCBOR_ERR_ARRAY_NESTING_TOO_DEEP;
170 goto Done;
171 }
172
Laurence Lundblade3a760b02018-10-08 13:46:03 +0800173 // The actual descend
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700174 pNesting->pCurrent++;
175
Laurence Lundblade3a760b02018-10-08 13:46:03 +0800176 // Record a few details for this nesting level
177 pNesting->pCurrent->uMajorType = pItem->uDataType;
178 pNesting->pCurrent->uCount = pItem->val.uCount;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700179
180Done:
181 return nReturn;;
182}
183
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700184inline static void DecodeNesting_Init(QCBORDecodeNesting *pNesting)
185{
186 pNesting->pCurrent = &(pNesting->pMapsAndArrays[0]);
187}
188
189
190
Laurence Lundbladedbe6f212018-10-28 11:37:53 +0700191/*
192 This list of built-in tags. Only add tags here that are
193 clearly established and useful. Once a tag is added here
194 it can't be taken out as that would break backwards compatibility.
195 There are only 48 slots available forever.
196 */
197static const uint16_t spBuiltInTagMap[] = {
198 CBOR_TAG_DATE_STRING, // See TAG_MAPPER_FIRST_FOUR
199 CBOR_TAG_DATE_EPOCH, // See TAG_MAPPER_FIRST_FOUR
200 CBOR_TAG_POS_BIGNUM, // See TAG_MAPPER_FIRST_FOUR
201 CBOR_TAG_NEG_BIGNUM, // See TAG_MAPPER_FIRST_FOUR
202 CBOR_TAG_FRACTION,
203 CBOR_TAG_BIGFLOAT,
204 CBOR_TAG_COSE_ENCRYPTO,
205 CBOR_TAG_COSE_MAC0,
206 CBOR_TAG_COSE_SIGN1,
207 CBOR_TAG_ENC_AS_B64URL,
208 CBOR_TAG_ENC_AS_B64,
209 CBOR_TAG_ENC_AS_B16,
210 CBOR_TAG_CBOR,
211 CBOR_TAG_URI,
212 CBOR_TAG_B64URL,
213 CBOR_TAG_B64,
214 CBOR_TAG_REGEX,
215 CBOR_TAG_MIME,
216 CBOR_TAG_BIN_UUID,
217 CBOR_TAG_CWT,
218 CBOR_TAG_ENCRYPT,
219 CBOR_TAG_MAC,
220 CBOR_TAG_SIGN,
221 CBOR_TAG_GEO_COORD,
222 CBOR_TAG_CBOR_MAGIC
223};
224
225// This is used in a bit of cleverness in GetNext_TaggedItem() to
226// keep code size down and switch for the internal processing of
227// these types. This will break if the first four items in
228// spBuiltInTagMap don't have values 0,1,2,3. That is the
229// mapping is 0 to 0, 1 to 1, 2 to 2 and 3 to 3.
230#define QCBOR_TAGFLAG_DATE_STRING (0x01LL << CBOR_TAG_DATE_STRING)
231#define QCBOR_TAGFLAG_DATE_EPOCH (0x01LL << CBOR_TAG_DATE_EPOCH)
232#define QCBOR_TAGFLAG_POS_BIGNUM (0x01LL << CBOR_TAG_POS_BIGNUM)
233#define QCBOR_TAGFLAG_NEG_BIGNUM (0x01LL << CBOR_TAG_NEG_BIGNUM)
234
235#define TAG_MAPPER_FIRST_FOUR (QCBOR_TAGFLAG_DATE_STRING |\
236 QCBOR_TAGFLAG_DATE_EPOCH |\
237 QCBOR_TAGFLAG_POS_BIGNUM |\
238 QCBOR_TAGFLAG_NEG_BIGNUM)
239
240#define TAG_MAPPER_TOTAL_TAG_BITS 64 // Number of bits in a uint64_t
241#define TAG_MAPPER_CUSTOM_TAGS_BASE_INDEX (TAG_MAPPER_TOTAL_TAG_BITS - QCBOR_MAX_CUSTOM_TAGS) // 48
242#define TAG_MAPPER_MAX_SIZE_BUILT_IN_TAGS (TAG_MAPPER_TOTAL_TAG_BITS - QCBOR_MAX_CUSTOM_TAGS ) // 48
243
244static inline int TagMapper_LookupBuiltIn(uint64_t uTag)
245{
246 if(sizeof(spBuiltInTagMap)/sizeof(uint16_t) > TAG_MAPPER_MAX_SIZE_BUILT_IN_TAGS) {
247 // This is a cross-check to make sure the above array doesn't
248 // accidentally get made too big.
249 // In normal conditions the above test should optimize out
250 // as all the values are known at compile time.
251 return -1;
252 }
253
254 if(uTag > UINT16_MAX) {
255 // This tag map works only on 16-bit tags
256 return -1;
257 }
258
259 for(int nTagBitIndex = 0; nTagBitIndex < (int)(sizeof(spBuiltInTagMap)/sizeof(uint16_t)); nTagBitIndex++) {
260 if(spBuiltInTagMap[nTagBitIndex] == uTag) {
261 return nTagBitIndex;
262 }
263 }
264 return -1; // Indicates no match
265}
266
267static inline int TagMapper_LookupCallerConfigured(const QCBORTagListIn *pCallerConfiguredTagMap, uint64_t uTag)
268{
269 for(int nTagBitIndex = 0; nTagBitIndex < pCallerConfiguredTagMap->uNumTags; nTagBitIndex++) {
270 if(pCallerConfiguredTagMap->puTags[nTagBitIndex] == uTag) {
271 return nTagBitIndex + TAG_MAPPER_CUSTOM_TAGS_BASE_INDEX;
272 }
273 }
274
275 return -1; // Indicates no match
276}
277
278/*
279 Find the tag bit index for a given tag value, or error out
280
281 This and the above functions could probably be optimized and made
282 clearer and neater.
283 */
Laurence Lundblade30816f22018-11-10 13:40:22 +0700284static QCBORError TagMapper_Lookup(const QCBORTagListIn *pCallerConfiguredTagMap, uint64_t uTag, uint8_t *puTagBitIndex)
Laurence Lundbladedbe6f212018-10-28 11:37:53 +0700285{
286 int nTagBitIndex = TagMapper_LookupBuiltIn(uTag);
287 if(nTagBitIndex >= 0) {
288 // Cast is safe because TagMapper_LookupBuiltIn never returns > 47
289 *puTagBitIndex = (uint8_t)nTagBitIndex;
290 return QCBOR_SUCCESS;
291 }
292
293 if(pCallerConfiguredTagMap) {
294 if(pCallerConfiguredTagMap->uNumTags > QCBOR_MAX_CUSTOM_TAGS) {
295 return QCBOR_ERR_TOO_MANY_TAGS;
296 }
297 nTagBitIndex = TagMapper_LookupCallerConfigured(pCallerConfiguredTagMap, uTag);
298 if(nTagBitIndex >= 0) {
299 // Cast is safe because TagMapper_LookupBuiltIn never returns > 63
300
301 *puTagBitIndex = (uint8_t)nTagBitIndex;
302 return QCBOR_SUCCESS;
303 }
304 }
305
306 return QCBOR_ERR_BAD_OPT_TAG;
307}
308
309
310
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700311
312/*
313 Public function, see header file
314 */
315void QCBORDecode_Init(QCBORDecodeContext *me, UsefulBufC EncodedCBOR, int8_t nDecodeMode)
316{
317 memset(me, 0, sizeof(QCBORDecodeContext));
318 UsefulInputBuf_Init(&(me->InBuf), EncodedCBOR);
319 // Don't bother with error check on decode mode. If a bad value is passed it will just act as
320 // if the default normal mode of 0 was set.
321 me->uDecodeMode = nDecodeMode;
322 DecodeNesting_Init(&(me->nesting));
323}
324
325
326/*
Laurence Lundblade0f99d692018-09-26 14:39:28 -0700327 Public function, see header file
328 */
Laurence Lundblade471a3fd2018-10-18 21:27:45 +0530329void QCBORDecode_SetUpAllocator(QCBORDecodeContext *pCtx, const QCBORStringAllocator *pAllocator, bool bAllocAll)
Laurence Lundblade0f99d692018-09-26 14:39:28 -0700330{
Laurence Lundbladedbe6f212018-10-28 11:37:53 +0700331 pCtx->pStringAllocator = (void *)pAllocator;
Laurence Lundblade471a3fd2018-10-18 21:27:45 +0530332 pCtx->bStringAllocateAll = bAllocAll;
Laurence Lundblade0f99d692018-09-26 14:39:28 -0700333}
334
Laurence Lundbladedbe6f212018-10-28 11:37:53 +0700335void QCBORDecode_SetCallerConfiguredTagList(QCBORDecodeContext *me, const QCBORTagListIn *pTagList)
336{
337 me->pCallerConfiguredTagList = pTagList;
338}
339
Laurence Lundblade0f99d692018-09-26 14:39:28 -0700340
341/*
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700342 This decodes the fundamental part of a CBOR data item, the type and number
343
344 This is the Counterpart to InsertEncodedTypeAndNumber().
345
346 This does the network->host byte order conversion. The conversion here
347 also results in the conversion for floats in addition to that for
348 lengths, tags and integer values.
349
Laurence Lundblade041ffa52018-10-07 11:43:51 +0700350 This returns:
351 pnMajorType -- the major type for the item
352 puNumber -- the "number" which is used a the value for integers, tags and floats and length for strings and arrays
353 puAdditionalInfo -- Pass this along to know what kind of float or if length is indefinite
354
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700355 */
Laurence Lundblade30816f22018-11-10 13:40:22 +0700356inline static QCBORError DecodeTypeAndNumber(UsefulInputBuf *pUInBuf, int *pnMajorType, uint64_t *puNumber, uint8_t *puAdditionalInfo)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700357{
Laurence Lundbladedbe6f212018-10-28 11:37:53 +0700358 // Stack usage: int/ptr 5 -- 40
Laurence Lundblade30816f22018-11-10 13:40:22 +0700359 QCBORError nReturn;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700360
361 // Get the initial byte that every CBOR data item has
362 const uint8_t InitialByte = UsefulInputBuf_GetByte(pUInBuf);
363
364 // Break down the initial byte
365 const uint8_t uTmpMajorType = InitialByte >> 5;
366 const uint8_t uAdditionalInfo = InitialByte & 0x1f;
367
368 // Get the integer that follows the major type. Do not know if this is a length, value, float or tag at this point
Laurence Lundblade041ffa52018-10-07 11:43:51 +0700369 // Also convert from network byte order.
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700370 uint64_t uTmpValue;
371 switch(uAdditionalInfo) {
372
373 case LEN_IS_ONE_BYTE:
374 uTmpValue = UsefulInputBuf_GetByte(pUInBuf);
375 break;
376
377 case LEN_IS_TWO_BYTES:
378 uTmpValue = UsefulInputBuf_GetUint16(pUInBuf);
379 break;
380
381 case LEN_IS_FOUR_BYTES:
382 uTmpValue = UsefulInputBuf_GetUint32(pUInBuf);
383 break;
384
385 case LEN_IS_EIGHT_BYTES:
386 uTmpValue = UsefulInputBuf_GetUint64(pUInBuf);
387 break;
388
389 case ADDINFO_RESERVED1: // reserved by CBOR spec
390 case ADDINFO_RESERVED2: // reserved by CBOR spec
391 case ADDINFO_RESERVED3: // reserved by CBOR spec
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700392 nReturn = QCBOR_ERR_UNSUPPORTED;
393 goto Done;
Laurence Lundblade0f99d692018-09-26 14:39:28 -0700394
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700395 default:
Laurence Lundblade041ffa52018-10-07 11:43:51 +0700396 // This is when the "number" is in the additional info
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700397 uTmpValue = uAdditionalInfo;
398 break;
399 }
400
401 // If any of the UsefulInputBuf_Get calls fail we will get here with uTmpValue as 0.
402 // There is no harm in this. This following check takes care of catching all of
403 // these errors.
404
405 if(UsefulInputBuf_GetError(pUInBuf)) {
406 nReturn = QCBOR_ERR_HIT_END;
407 goto Done;
408 }
409
410 // All successful if we got here.
411 nReturn = QCBOR_SUCCESS;
412 *pnMajorType = uTmpMajorType;
413 *puNumber = uTmpValue;
414 *puAdditionalInfo = uAdditionalInfo;
415
416Done:
417 return nReturn;
418}
419
420
421/*
422 CBOR doesn't explicitly specify two's compliment for integers but all CPUs
423 use it these days and the test vectors in the RFC are so. All integers in the CBOR
424 structure are positive and the major type indicates positive or negative.
425 CBOR can express positive integers up to 2^x - 1 where x is the number of bits
426 and negative integers down to 2^x. Note that negative numbers can be one
427 more away from zero than positive.
428 Stdint, as far as I can tell, uses two's compliment to represent
429 negative integers.
430
431 See http://www.unix.org/whitepapers/64bit.html for reasons int isn't
432 used here in any way including in the interface
433 */
Laurence Lundblade30816f22018-11-10 13:40:22 +0700434inline static QCBORError DecodeInteger(int nMajorType, uint64_t uNumber, QCBORItem *pDecodedItem)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700435{
Laurence Lundbladedbe6f212018-10-28 11:37:53 +0700436 // Stack usage: int/ptr 1 -- 8
Laurence Lundblade30816f22018-11-10 13:40:22 +0700437 QCBORError nReturn = QCBOR_SUCCESS;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700438
439 if(nMajorType == CBOR_MAJOR_TYPE_POSITIVE_INT) {
440 if (uNumber <= INT64_MAX) {
441 pDecodedItem->val.int64 = (int64_t)uNumber;
442 pDecodedItem->uDataType = QCBOR_TYPE_INT64;
443
444 } else {
445 pDecodedItem->val.uint64 = uNumber;
446 pDecodedItem->uDataType = QCBOR_TYPE_UINT64;
447
448 }
449 } else {
450 if(uNumber <= INT64_MAX) {
451 pDecodedItem->val.int64 = -uNumber-1;
452 pDecodedItem->uDataType = QCBOR_TYPE_INT64;
453
454 } else {
455 // C can't represent a negative integer in this range
456 // so it is an error. todo -- test this condition
457 nReturn = QCBOR_ERR_INT_OVERFLOW;
458 }
459 }
460
461 return nReturn;
462}
463
464// Make sure #define value line up as DecodeSimple counts on this.
465#if QCBOR_TYPE_FALSE != CBOR_SIMPLEV_FALSE
466#error QCBOR_TYPE_FALSE macro value wrong
467#endif
468
469#if QCBOR_TYPE_TRUE != CBOR_SIMPLEV_TRUE
470#error QCBOR_TYPE_TRUE macro value wrong
471#endif
472
473#if QCBOR_TYPE_NULL != CBOR_SIMPLEV_NULL
474#error QCBOR_TYPE_NULL macro value wrong
475#endif
476
477#if QCBOR_TYPE_UNDEF != CBOR_SIMPLEV_UNDEF
478#error QCBOR_TYPE_UNDEF macro value wrong
479#endif
480
Laurence Lundblade0f99d692018-09-26 14:39:28 -0700481#if QCBOR_TYPE_BREAK != CBOR_SIMPLE_BREAK
482#error QCBOR_TYPE_BREAK macro value wrong
483#endif
484
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700485#if QCBOR_TYPE_DOUBLE != DOUBLE_PREC_FLOAT
486#error QCBOR_TYPE_DOUBLE macro value wrong
487#endif
488
489#if QCBOR_TYPE_FLOAT != SINGLE_PREC_FLOAT
490#error QCBOR_TYPE_FLOAT macro value wrong
491#endif
492
493/*
494 Decode true, false, floats, break...
495 */
496
Laurence Lundblade30816f22018-11-10 13:40:22 +0700497inline static QCBORError DecodeSimple(uint8_t uAdditionalInfo, uint64_t uNumber, QCBORItem *pDecodedItem)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700498{
Laurence Lundbladedbe6f212018-10-28 11:37:53 +0700499 // Stack usage: 0
Laurence Lundblade30816f22018-11-10 13:40:22 +0700500 QCBORError nReturn = QCBOR_SUCCESS;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700501
502 // uAdditionalInfo is 5 bits from the initial byte
503 // compile time checks above make sure uAdditionalInfo values line up with uDataType values
504 pDecodedItem->uDataType = uAdditionalInfo;
505
506 switch(uAdditionalInfo) {
507 case ADDINFO_RESERVED1: // 28
508 case ADDINFO_RESERVED2: // 29
509 case ADDINFO_RESERVED3: // 30
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700510 nReturn = QCBOR_ERR_UNSUPPORTED;
511 break;
Laurence Lundblade12d32c52018-09-19 11:25:27 -0700512
Laurence Lundbladecc2ed342018-09-22 17:29:55 -0700513 case HALF_PREC_FLOAT:
Laurence Lundblade67bd5512018-11-02 21:44:06 +0700514 pDecodedItem->val.dfnum = IEEE754_HalfToDouble((uint16_t)uNumber);
515 pDecodedItem->uDataType = QCBOR_TYPE_DOUBLE;
Laurence Lundblade12d32c52018-09-19 11:25:27 -0700516 break;
Laurence Lundbladecc2ed342018-09-22 17:29:55 -0700517 case SINGLE_PREC_FLOAT:
Laurence Lundblade67bd5512018-11-02 21:44:06 +0700518 pDecodedItem->val.dfnum = (double)UsefulBufUtil_CopyUint32ToFloat((uint32_t)uNumber);
519 pDecodedItem->uDataType = QCBOR_TYPE_DOUBLE;
Laurence Lundblade12d32c52018-09-19 11:25:27 -0700520 break;
521 case DOUBLE_PREC_FLOAT:
522 pDecodedItem->val.dfnum = UsefulBufUtil_CopyUint64ToDouble(uNumber);
Laurence Lundblade67bd5512018-11-02 21:44:06 +0700523 pDecodedItem->uDataType = QCBOR_TYPE_DOUBLE;
Laurence Lundblade12d32c52018-09-19 11:25:27 -0700524 break;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700525
526 case CBOR_SIMPLEV_FALSE: // 20
527 case CBOR_SIMPLEV_TRUE: // 21
528 case CBOR_SIMPLEV_NULL: // 22
529 case CBOR_SIMPLEV_UNDEF: // 23
Laurence Lundblade0f99d692018-09-26 14:39:28 -0700530 case CBOR_SIMPLE_BREAK: // 31
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700531 break; // nothing to do
532
533 case CBOR_SIMPLEV_ONEBYTE: // 24
534 if(uNumber <= CBOR_SIMPLE_BREAK) {
535 // This takes out f8 00 ... f8 1f which should be encoded as e0 … f7
536 nReturn = QCBOR_ERR_INVALID_CBOR;
537 goto Done;
538 }
539 // fall through intentionally
540
541 default: // 0-19
542 pDecodedItem->uDataType = QCBOR_TYPE_UKNOWN_SIMPLE;
543 // DecodeTypeAndNumber will make uNumber equal to uAdditionalInfo when uAdditionalInfo is < 24
544 // This cast is safe because the 2, 4 and 8 byte lengths of uNumber are in the double/float cases above
545 pDecodedItem->val.uSimple = (uint8_t)uNumber;
546 break;
547 }
548
549Done:
550 return nReturn;
551}
552
553
554
555/*
Laurence Lundblade471a3fd2018-10-18 21:27:45 +0530556 Decode text and byte strings. Call the string allocator if asked to.
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700557 */
Laurence Lundblade30816f22018-11-10 13:40:22 +0700558inline static QCBORError DecodeBytes(const QCBORStringAllocator *pAlloc, int nMajorType, uint64_t uStrLen, UsefulInputBuf *pUInBuf, QCBORItem *pDecodedItem)
Laurence Lundblade041ffa52018-10-07 11:43:51 +0700559{
Laurence Lundbladedbe6f212018-10-28 11:37:53 +0700560 // Stack usage: UsefulBuf 2, int/ptr 1 40
Laurence Lundblade30816f22018-11-10 13:40:22 +0700561 QCBORError nReturn = QCBOR_SUCCESS;
Laurence Lundblade041ffa52018-10-07 11:43:51 +0700562
Laurence Lundblade471a3fd2018-10-18 21:27:45 +0530563 UsefulBufC Bytes = UsefulInputBuf_GetUsefulBuf(pUInBuf, uStrLen);
564 if(UsefulBuf_IsNULLC(Bytes)) {
565 // Failed to get the bytes for this string item
566 nReturn = QCBOR_ERR_HIT_END;
567 goto Done;
Laurence Lundblade041ffa52018-10-07 11:43:51 +0700568 }
Laurence Lundblade471a3fd2018-10-18 21:27:45 +0530569
570 if(pAlloc) {
571 // We are asked to use string allocator to make a copy
572 UsefulBuf NewMem = pAlloc->fAllocate(pAlloc->pAllocaterContext, NULL, uStrLen);
573 if(UsefulBuf_IsNULL(NewMem)) {
Laurence Lundblade30816f22018-11-10 13:40:22 +0700574 nReturn = QCBOR_ERR_STRING_ALLOCATE;
Laurence Lundblade471a3fd2018-10-18 21:27:45 +0530575 goto Done;
576 }
577 pDecodedItem->val.string = UsefulBuf_Copy(NewMem, Bytes);
578 } else {
579 // Normal case with no string allocator
580 pDecodedItem->val.string = Bytes;
581 }
582 pDecodedItem->uDataType = (nMajorType == CBOR_MAJOR_TYPE_BYTE_STRING) ? QCBOR_TYPE_BYTE_STRING : QCBOR_TYPE_TEXT_STRING;
Laurence Lundblade041ffa52018-10-07 11:43:51 +0700583
Laurence Lundblade471a3fd2018-10-18 21:27:45 +0530584Done:
Laurence Lundblade041ffa52018-10-07 11:43:51 +0700585 return nReturn;
586}
587
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700588
589/*
590 Mostly just assign the right data type for the date string.
591 */
Laurence Lundblade30816f22018-11-10 13:40:22 +0700592inline static QCBORError DecodeDateString(QCBORItem *pDecodedItem)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700593{
Laurence Lundbladedbe6f212018-10-28 11:37:53 +0700594 // Stack Use: UsefulBuf 1 16
595 if(pDecodedItem->uDataType != QCBOR_TYPE_TEXT_STRING) {
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700596 return QCBOR_ERR_BAD_OPT_TAG;
597 }
Laurence Lundbladedbe6f212018-10-28 11:37:53 +0700598
599 UsefulBufC Temp = pDecodedItem->val.string;
600 pDecodedItem->val.dateString = Temp;
601 pDecodedItem->uDataType = QCBOR_TYPE_DATE_STRING;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700602 return QCBOR_SUCCESS;
603}
604
605
606/*
607 Mostly just assign the right data type for the bignum.
608 */
Laurence Lundblade30816f22018-11-10 13:40:22 +0700609inline static QCBORError DecodeBigNum(QCBORItem *pDecodedItem)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700610{
Laurence Lundbladedbe6f212018-10-28 11:37:53 +0700611 // Stack Use: UsefulBuf 1 -- 16
612 if(pDecodedItem->uDataType != QCBOR_TYPE_BYTE_STRING) {
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700613 return QCBOR_ERR_BAD_OPT_TAG;
614 }
Laurence Lundbladedbe6f212018-10-28 11:37:53 +0700615 UsefulBufC Temp = pDecodedItem->val.string;
616 pDecodedItem->val.bigNum = Temp;
Laurence Lundblade67bd5512018-11-02 21:44:06 +0700617 pDecodedItem->uDataType = pDecodedItem->uTagBits & QCBOR_TAGFLAG_POS_BIGNUM ? QCBOR_TYPE_POSBIGNUM : QCBOR_TYPE_NEGBIGNUM;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700618 return QCBOR_SUCCESS;
619}
620
621
622/*
623 The epoch formatted date. Turns lots of different forms of encoding date into uniform one
624 */
Laurence Lundbladedbe6f212018-10-28 11:37:53 +0700625static int DecodeDateEpoch(QCBORItem *pDecodedItem)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700626{
Laurence Lundbladedbe6f212018-10-28 11:37:53 +0700627 // Stack usage: 1
Laurence Lundblade30816f22018-11-10 13:40:22 +0700628 QCBORError nReturn = QCBOR_SUCCESS;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700629
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700630 pDecodedItem->val.epochDate.fSecondsFraction = 0;
631
Laurence Lundbladedbe6f212018-10-28 11:37:53 +0700632 switch (pDecodedItem->uDataType) {
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700633
634 case QCBOR_TYPE_INT64:
Laurence Lundbladedbe6f212018-10-28 11:37:53 +0700635 pDecodedItem->val.epochDate.nSeconds = pDecodedItem->val.int64;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700636 break;
637
638 case QCBOR_TYPE_UINT64:
Laurence Lundbladedbe6f212018-10-28 11:37:53 +0700639 if(pDecodedItem->val.uint64 > INT64_MAX) {
640 nReturn = QCBOR_ERR_DATE_OVERFLOW;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700641 goto Done;
642 }
Laurence Lundbladedbe6f212018-10-28 11:37:53 +0700643 pDecodedItem->val.epochDate.nSeconds = pDecodedItem->val.uint64;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700644 break;
645
Laurence Lundblade9e3651c2018-10-10 11:49:55 +0800646 case QCBOR_TYPE_DOUBLE:
Laurence Lundblade67bd5512018-11-02 21:44:06 +0700647 {
648 const double d = pDecodedItem->val.dfnum;
649 if(d > INT64_MAX) {
650 nReturn = QCBOR_ERR_DATE_OVERFLOW;
651 goto Done;
652 }
653 pDecodedItem->val.epochDate.nSeconds = d; // Float to integer conversion happening here.
654 pDecodedItem->val.epochDate.fSecondsFraction = d - pDecodedItem->val.epochDate.nSeconds;
Laurence Lundblade9e3651c2018-10-10 11:49:55 +0800655 }
Laurence Lundblade9e3651c2018-10-10 11:49:55 +0800656 break;
657
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700658 default:
659 nReturn = QCBOR_ERR_BAD_OPT_TAG;
Laurence Lundbladedbe6f212018-10-28 11:37:53 +0700660 goto Done;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700661 }
Laurence Lundbladedbe6f212018-10-28 11:37:53 +0700662 pDecodedItem->uDataType = QCBOR_TYPE_DATE_EPOCH;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700663
664Done:
665 return nReturn;
666}
667
668
Laurence Lundblade041ffa52018-10-07 11:43:51 +0700669
670
671// Make sure the constants align as this is assumed by the GetAnItem() implementation
672#if QCBOR_TYPE_ARRAY != CBOR_MAJOR_TYPE_ARRAY
673#error QCBOR_TYPE_ARRAY value not lined up with major type
674#endif
675#if QCBOR_TYPE_MAP != CBOR_MAJOR_TYPE_MAP
676#error QCBOR_TYPE_MAP value not lined up with major type
677#endif
678
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700679/*
Laurence Lundblade041ffa52018-10-07 11:43:51 +0700680 This gets a single data item and decodes it including preceding optional tagging. This does not
681 deal with arrays and maps and nesting except to decode the data item introducing them. Arrays and
682 maps are handled at the next level up in GetNext().
683
684 Errors detected here include: an array that is too long to decode, hit end of buffer unexpectedly,
685 a few forms of invalid encoded CBOR
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700686 */
Laurence Lundblade30816f22018-11-10 13:40:22 +0700687static QCBORError GetNext_Item(UsefulInputBuf *pUInBuf, QCBORItem *pDecodedItem, const QCBORStringAllocator *pAlloc)
Laurence Lundblade041ffa52018-10-07 11:43:51 +0700688{
Laurence Lundbladedbe6f212018-10-28 11:37:53 +0700689 // Stack usage: int/ptr 3 -- 24
Laurence Lundblade30816f22018-11-10 13:40:22 +0700690 QCBORError nReturn;
Laurence Lundblade041ffa52018-10-07 11:43:51 +0700691
692 // Get the major type and the number. Number could be length of more bytes or the value depending on the major type
693 // nAdditionalInfo is an encoding of the length of the uNumber and is needed to decode floats and doubles
694 int uMajorType;
695 uint64_t uNumber;
696 uint8_t uAdditionalInfo;
697
698 nReturn = DecodeTypeAndNumber(pUInBuf, &uMajorType, &uNumber, &uAdditionalInfo);
699
700 // Error out here if we got into trouble on the type and number.
701 // The code after this will not work if the type and number is not good.
702 if(nReturn)
703 goto Done;
704
Laurence Lundbladefab1b522018-10-19 13:40:52 +0530705 memset(pDecodedItem, 0, sizeof(QCBORItem));
Laurence Lundblade041ffa52018-10-07 11:43:51 +0700706
707 // At this point the major type and the value are valid. We've got the type and the number that
708 // starts every CBOR data item.
709 switch (uMajorType) {
710 case CBOR_MAJOR_TYPE_POSITIVE_INT: // Major type 0
711 case CBOR_MAJOR_TYPE_NEGATIVE_INT: // Major type 1
712 nReturn = DecodeInteger(uMajorType, uNumber, pDecodedItem);
713 break;
714
715 case CBOR_MAJOR_TYPE_BYTE_STRING: // Major type 2
716 case CBOR_MAJOR_TYPE_TEXT_STRING: // Major type 3
717 if(uAdditionalInfo == LEN_IS_INDEFINITE) {
718 pDecodedItem->uDataType = (uMajorType == CBOR_MAJOR_TYPE_BYTE_STRING) ? QCBOR_TYPE_BYTE_STRING : QCBOR_TYPE_TEXT_STRING;
Laurence Lundbladea44d5062018-10-17 18:45:12 +0530719 pDecodedItem->val.string = (UsefulBufC){NULL, SIZE_MAX};
Laurence Lundblade041ffa52018-10-07 11:43:51 +0700720 } else {
721 nReturn = DecodeBytes(pAlloc, uMajorType, uNumber, pUInBuf, pDecodedItem);
722 }
723 break;
724
725 case CBOR_MAJOR_TYPE_ARRAY: // Major type 4
726 case CBOR_MAJOR_TYPE_MAP: // Major type 5
727 // Record the number of items in the array or map
728 if(uNumber > QCBOR_MAX_ITEMS_IN_ARRAY) {
729 nReturn = QCBOR_ERR_ARRAY_TOO_LONG;
730 goto Done;
731 }
732 if(uAdditionalInfo == LEN_IS_INDEFINITE) {
Laurence Lundbladea44d5062018-10-17 18:45:12 +0530733 pDecodedItem->val.uCount = UINT16_MAX; // Indicate indefinite length
Laurence Lundblade041ffa52018-10-07 11:43:51 +0700734 } else {
735 pDecodedItem->val.uCount = (uint16_t)uNumber; // type conversion OK because of check above
736 }
737 pDecodedItem->uDataType = uMajorType; // C preproc #if above makes sure constants align
738 break;
739
740 case CBOR_MAJOR_TYPE_OPTIONAL: // Major type 6, optional prepended tags
Laurence Lundbladedbe6f212018-10-28 11:37:53 +0700741 pDecodedItem->val.uTagV = uNumber;
Laurence Lundblade041ffa52018-10-07 11:43:51 +0700742 pDecodedItem->uDataType = QCBOR_TYPE_OPTTAG;
743 break;
744
745 case CBOR_MAJOR_TYPE_SIMPLE: // Major type 7, float, double, true, false, null...
746 nReturn = DecodeSimple(uAdditionalInfo, uNumber, pDecodedItem);
747 break;
748
749 default: // Should never happen because DecodeTypeAndNumber() should never return > 7
750 nReturn = QCBOR_ERR_UNSUPPORTED;
751 break;
752 }
753
754Done:
755 return nReturn;
756}
757
758
759
760/*
Laurence Lundblade20b533d2018-10-08 20:44:53 +0800761 This layer deals with indefinite length strings. It pulls all the
Laurence Lundblade2a6850e2018-10-28 20:13:44 +0700762 individual chunk items together into one QCBORItem using the
Laurence Lundblade471a3fd2018-10-18 21:27:45 +0530763 string allocator.
Laurence Lundblade7e0d13b2018-10-16 19:54:13 +0530764
765 Code Reviewers: THIS FUNCTION DOES A LITTLE POINTER MATH
Laurence Lundblade041ffa52018-10-07 11:43:51 +0700766 */
Laurence Lundblade30816f22018-11-10 13:40:22 +0700767static inline QCBORError GetNext_FullItem(QCBORDecodeContext *me, QCBORItem *pDecodedItem)
Laurence Lundblade041ffa52018-10-07 11:43:51 +0700768{
Laurence Lundbladedbe6f212018-10-28 11:37:53 +0700769 // Stack usage; int/ptr 2 UsefulBuf 2 QCBORItem -- 96
Laurence Lundblade30816f22018-11-10 13:40:22 +0700770 QCBORError nReturn;
Laurence Lundblade5b8c5852018-10-14 21:11:42 +0530771 QCBORStringAllocator *pAlloc = (QCBORStringAllocator *)me->pStringAllocator;
Laurence Lundblade471a3fd2018-10-18 21:27:45 +0530772 UsefulBufC FullString = NULLUsefulBufC;
Laurence Lundblade041ffa52018-10-07 11:43:51 +0700773
774 nReturn = GetNext_Item(&(me->InBuf), pDecodedItem, me->bStringAllocateAll ? pAlloc: NULL);
775 if(nReturn) {
776 goto Done;
777 }
778
779 // To reduce code size by removing support for indefinite length strings, the
Laurence Lundblade7e0d13b2018-10-16 19:54:13 +0530780 // code in this function from here down can be eliminated. Run tests, except
781 // indefinite length string tests, to be sure all is OK if this is removed.
Laurence Lundblade041ffa52018-10-07 11:43:51 +0700782
Laurence Lundblade20b533d2018-10-08 20:44:53 +0800783 // Only do indefinite length processing on strings
Laurence Lundblade041ffa52018-10-07 11:43:51 +0700784 if(pDecodedItem->uDataType != QCBOR_TYPE_BYTE_STRING && pDecodedItem->uDataType != QCBOR_TYPE_TEXT_STRING) {
785 goto Done; // no need to do any work here on non-string types
786 }
787
Laurence Lundblade20b533d2018-10-08 20:44:53 +0800788 // Is this a string with an indefinite length?
Laurence Lundblade7e0d13b2018-10-16 19:54:13 +0530789 if(pDecodedItem->val.string.len != SIZE_MAX) {
Laurence Lundblade20b533d2018-10-08 20:44:53 +0800790 goto Done; // length is not indefinite, so no work to do here
Laurence Lundblade041ffa52018-10-07 11:43:51 +0700791 }
792
Laurence Lundblade7e0d13b2018-10-16 19:54:13 +0530793 // Can't do indefinite length strings without a string allocator
Laurence Lundblade041ffa52018-10-07 11:43:51 +0700794 if(pAlloc == NULL) {
Laurence Lundblade041ffa52018-10-07 11:43:51 +0700795 nReturn = QCBOR_ERR_NO_STRING_ALLOCATOR;
796 goto Done;
797 }
798
799 // There is an indefinite length string to work on...
Laurence Lundblade20b533d2018-10-08 20:44:53 +0800800 // Track which type of string it is
Laurence Lundblade041ffa52018-10-07 11:43:51 +0700801 const uint8_t uStringType = pDecodedItem->uDataType;
802
Laurence Lundblade2a6850e2018-10-28 20:13:44 +0700803 // Loop getting chunk of indefinite string
Laurence Lundblade041ffa52018-10-07 11:43:51 +0700804 for(;;) {
Laurence Lundblade2a6850e2018-10-28 20:13:44 +0700805 // Get item for next chunk
806 QCBORItem StringChunkItem;
807 // NULL passed to never string alloc chunk of indefinite length strings
808 nReturn = GetNext_Item(&(me->InBuf), &StringChunkItem, NULL);
Laurence Lundblade041ffa52018-10-07 11:43:51 +0700809 if(nReturn) {
Laurence Lundblade2a6850e2018-10-28 20:13:44 +0700810 break; // Error getting the next chunk
Laurence Lundblade041ffa52018-10-07 11:43:51 +0700811 }
812
Laurence Lundblade7e0d13b2018-10-16 19:54:13 +0530813 // See if it is a marker at end of indefinite length string
Laurence Lundblade2a6850e2018-10-28 20:13:44 +0700814 if(StringChunkItem.uDataType == QCBOR_TYPE_BREAK) {
Laurence Lundblade20b533d2018-10-08 20:44:53 +0800815 // String is complete
Laurence Lundblade041ffa52018-10-07 11:43:51 +0700816 pDecodedItem->val.string = FullString;
Laurence Lundblade57dd1442018-10-15 20:26:28 +0530817 pDecodedItem->uDataAlloc = 1;
Laurence Lundblade041ffa52018-10-07 11:43:51 +0700818 break;
819 }
820
Laurence Lundblade2a6850e2018-10-28 20:13:44 +0700821 // Match data type of chunk to type at beginning.
Laurence Lundblade7e0d13b2018-10-16 19:54:13 +0530822 // Also catches error of other non-string types that don't belong.
Laurence Lundblade2a6850e2018-10-28 20:13:44 +0700823 if(StringChunkItem.uDataType != uStringType) {
Laurence Lundblade30816f22018-11-10 13:40:22 +0700824 nReturn = QCBOR_ERR_INDEFINITE_STRING_CHUNK;
Laurence Lundblade041ffa52018-10-07 11:43:51 +0700825 break;
826 }
827
Laurence Lundblade471a3fd2018-10-18 21:27:45 +0530828 // Alloc new buffer or expand previously allocated buffer so it can fit
Laurence Lundblade7e0d13b2018-10-16 19:54:13 +0530829 UsefulBuf NewMem = (*pAlloc->fAllocate)(pAlloc->pAllocaterContext,
830 UNCONST_POINTER(FullString.ptr),
Laurence Lundblade2a6850e2018-10-28 20:13:44 +0700831 FullString.len + StringChunkItem.val.string.len);
Laurence Lundblade041ffa52018-10-07 11:43:51 +0700832 if(UsefulBuf_IsNULL(NewMem)) {
Laurence Lundblade7e0d13b2018-10-16 19:54:13 +0530833 // Allocation of memory for the string failed
Laurence Lundblade30816f22018-11-10 13:40:22 +0700834 nReturn = QCBOR_ERR_STRING_ALLOCATE;
Laurence Lundblade041ffa52018-10-07 11:43:51 +0700835 break;
836 }
837
Laurence Lundblade2a6850e2018-10-28 20:13:44 +0700838 // Copy new string chunk at the end of string so far.
839 FullString = UsefulBuf_CopyOffset(NewMem, FullString.len, StringChunkItem.val.string);
Laurence Lundblade041ffa52018-10-07 11:43:51 +0700840 }
841
842Done:
Laurence Lundblade471a3fd2018-10-18 21:27:45 +0530843 if(pAlloc && nReturn && !UsefulBuf_IsNULLC(FullString)) {
Laurence Lundblade041ffa52018-10-07 11:43:51 +0700844 // Getting item failed, clean up the allocated memory
Laurence Lundblade7e0d13b2018-10-16 19:54:13 +0530845 (pAlloc->fFree)(pAlloc->pAllocaterContext, UNCONST_POINTER(FullString.ptr));
Laurence Lundblade041ffa52018-10-07 11:43:51 +0700846 }
847
848 return nReturn;
849}
850
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700851
852/*
853 Returns an error if there was something wrong with the optional item or it couldn't
854 be handled.
855 */
Laurence Lundblade30816f22018-11-10 13:40:22 +0700856static QCBORError GetNext_TaggedItem(QCBORDecodeContext *me, QCBORItem *pDecodedItem, QCBORTagListOut *pTags)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700857{
Laurence Lundbladedbe6f212018-10-28 11:37:53 +0700858 // Stack usage: int/ptr: 3 -- 24
Laurence Lundblade30816f22018-11-10 13:40:22 +0700859 QCBORError nReturn;
Laurence Lundbladedbe6f212018-10-28 11:37:53 +0700860 uint64_t uTagBits = 0;
861 if(pTags) {
862 pTags->uNumUsed = 0;
Laurence Lundblade041ffa52018-10-07 11:43:51 +0700863 }
Laurence Lundbladedbe6f212018-10-28 11:37:53 +0700864
865 for(;;) {
866 nReturn = GetNext_FullItem(me, pDecodedItem);
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700867 if(nReturn) {
Laurence Lundbladedbe6f212018-10-28 11:37:53 +0700868 goto Done; // Error out of the loop
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700869 }
870
Laurence Lundbladedbe6f212018-10-28 11:37:53 +0700871 if(pDecodedItem->uDataType != QCBOR_TYPE_OPTTAG) {
872 // Successful exit from loop; maybe got some tags, maybe not
873 pDecodedItem->uTagBits = uTagBits;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700874 break;
875 }
Laurence Lundbladedbe6f212018-10-28 11:37:53 +0700876
877 uint8_t uTagBitIndex;
878 // Tag was mapped, tag was not mapped, error with tag list
879 switch(TagMapper_Lookup(me->pCallerConfiguredTagList, pDecodedItem->val.uTagV, &uTagBitIndex)) {
880
881 case QCBOR_SUCCESS:
882 // Successfully mapped the tag
883 uTagBits |= 0x01ULL << uTagBitIndex;
884 break;
885
886 case QCBOR_ERR_BAD_OPT_TAG:
887 // Tag is not recognized. Do nothing
888 break;
889
890 default:
891 // Error Condition
892 goto Done;
893 }
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700894
Laurence Lundbladedbe6f212018-10-28 11:37:53 +0700895 if(pTags) {
896 // Caller wants all tags recorded in the provided buffer
897 if(pTags->uNumUsed >= pTags->uNumAllocated) {
898 nReturn = QCBOR_ERR_TOO_MANY_TAGS;
899 goto Done;
900 }
901 pTags->puTags[pTags->uNumUsed] = pDecodedItem->val.uTagV;
902 pTags->uNumUsed++;
903 }
904 }
Laurence Lundblade041ffa52018-10-07 11:43:51 +0700905
Laurence Lundbladedbe6f212018-10-28 11:37:53 +0700906 switch(pDecodedItem->uTagBits & TAG_MAPPER_FIRST_FOUR) {
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700907 case 0:
Laurence Lundbladedbe6f212018-10-28 11:37:53 +0700908 // No tags at all or none we know about. Nothing to do.
909 // This is part of the pass-through path of this function
910 // that will mostly be taken when decoding any item.
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700911 break;
912
913 case QCBOR_TAGFLAG_DATE_STRING:
Laurence Lundbladedbe6f212018-10-28 11:37:53 +0700914 nReturn = DecodeDateString(pDecodedItem);
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700915 break;
916
917 case QCBOR_TAGFLAG_DATE_EPOCH:
Laurence Lundbladedbe6f212018-10-28 11:37:53 +0700918 nReturn = DecodeDateEpoch(pDecodedItem);
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700919 break;
920
921 case QCBOR_TAGFLAG_POS_BIGNUM:
922 case QCBOR_TAGFLAG_NEG_BIGNUM:
Laurence Lundbladedbe6f212018-10-28 11:37:53 +0700923 nReturn = DecodeBigNum(pDecodedItem);
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700924 break;
925
926 default:
927 // Encountering some mixed up CBOR like something that
928 // is tagged as both a string and integer date.
Laurence Lundblade30816f22018-11-10 13:40:22 +0700929 nReturn = QCBOR_ERR_BAD_OPT_TAG;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700930 }
931
932Done:
933 return nReturn;
934}
935
936
937/*
Laurence Lundblade20b533d2018-10-08 20:44:53 +0800938 This layer takes care of map entries. It combines the label and data items into one QCBORItem.
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700939 */
Laurence Lundblade30816f22018-11-10 13:40:22 +0700940static inline QCBORError GetNext_MapEntry(QCBORDecodeContext *me, QCBORItem *pDecodedItem, QCBORTagListOut *pTags)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700941{
Laurence Lundbladedbe6f212018-10-28 11:37:53 +0700942 // Stack use: int/ptr 1, QCBORItem -- 56
Laurence Lundblade30816f22018-11-10 13:40:22 +0700943 QCBORError nReturn = GetNext_TaggedItem(me, pDecodedItem, pTags);
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700944 if(nReturn)
945 goto Done;
946
Laurence Lundblade742df4a2018-10-13 20:07:17 +0800947 if(pDecodedItem->uDataType == QCBOR_TYPE_BREAK) {
Laurence Lundbladedbe6f212018-10-28 11:37:53 +0700948 // Break can't be a map entry
Laurence Lundblade742df4a2018-10-13 20:07:17 +0800949 goto Done;
950 }
951
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700952 // If in a map and the right decoding mode, get the label
953 if(DecodeNesting_TypeIsMap(&(me->nesting)) && me->uDecodeMode != QCBOR_DECODE_MODE_MAP_AS_ARRAY) {
954 // In a map and caller wants maps decoded, not treated as arrays
955
956 // Get the next item which will be the real data; Item will be the label
957 QCBORItem LabelItem = *pDecodedItem;
Laurence Lundbladedbe6f212018-10-28 11:37:53 +0700958 nReturn = GetNext_TaggedItem(me, pDecodedItem, pTags);
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700959 if(nReturn)
960 goto Done;
961
Laurence Lundbladefab1b522018-10-19 13:40:52 +0530962 pDecodedItem->uLabelAlloc = LabelItem.uDataAlloc;
963
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700964 if(LabelItem.uDataType == QCBOR_TYPE_TEXT_STRING) {
965 // strings are always good labels
966 pDecodedItem->label.string = LabelItem.val.string;
967 pDecodedItem->uLabelType = QCBOR_TYPE_TEXT_STRING;
968 } else if (QCBOR_DECODE_MODE_MAP_STRINGS_ONLY == me->uDecodeMode) {
969 // It's not a string and we only want strings, probably for easy translation to JSON
970 nReturn = QCBOR_ERR_MAP_LABEL_TYPE;
971 goto Done;
Laurence Lundblade041ffa52018-10-07 11:43:51 +0700972 } else if(LabelItem.uDataType == QCBOR_TYPE_INT64) {
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700973 pDecodedItem->label.int64 = LabelItem.val.int64;
974 pDecodedItem->uLabelType = QCBOR_TYPE_INT64;
975 } else if(LabelItem.uDataType == QCBOR_TYPE_UINT64) {
976 pDecodedItem->label.uint64 = LabelItem.val.uint64;
977 pDecodedItem->uLabelType = QCBOR_TYPE_UINT64;
978 } else if(LabelItem.uDataType == QCBOR_TYPE_BYTE_STRING) {
979 pDecodedItem->label.string = LabelItem.val.string;
Laurence Lundblade57dd1442018-10-15 20:26:28 +0530980 pDecodedItem->uLabelAlloc = LabelItem.uDataAlloc;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700981 pDecodedItem->uLabelType = QCBOR_TYPE_BYTE_STRING;
982 } else {
983 // label is not an int or a string. It is an arrray
984 // or a float or such and this implementation doesn't handle that.
Laurence Lundbladedbe6f212018-10-28 11:37:53 +0700985 // Also, tags on labels are ignored.
Laurence Lundblade30816f22018-11-10 13:40:22 +0700986 nReturn = QCBOR_ERR_MAP_LABEL_TYPE;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700987 goto Done;
988 }
989 }
990
Laurence Lundblade041ffa52018-10-07 11:43:51 +0700991Done:
992 return nReturn;
993}
994
995
996/*
997 Public function, see header qcbor.h file
998 */
Laurence Lundblade30816f22018-11-10 13:40:22 +0700999QCBORError QCBORDecode_GetNextWithTags(QCBORDecodeContext *me, QCBORItem *pDecodedItem, QCBORTagListOut *pTags)
Laurence Lundblade041ffa52018-10-07 11:43:51 +07001000{
Laurence Lundbladedbe6f212018-10-28 11:37:53 +07001001 // Stack ptr/int: 2, QCBORItem : 64
1002
Laurence Lundblade7e0d13b2018-10-16 19:54:13 +05301003 // The public entry point for fetching and parsing the next QCBORItem.
1004 // All the CBOR parsing work is here and in subordinate calls.
Laurence Lundblade30816f22018-11-10 13:40:22 +07001005 QCBORError nReturn;
Laurence Lundblade041ffa52018-10-07 11:43:51 +07001006
Laurence Lundbladedbe6f212018-10-28 11:37:53 +07001007 nReturn = GetNext_MapEntry(me, pDecodedItem, pTags);
Laurence Lundblade20b533d2018-10-08 20:44:53 +08001008 if(nReturn) {
1009 goto Done;
Laurence Lundblade041ffa52018-10-07 11:43:51 +07001010 }
Laurence Lundblade7e0d13b2018-10-16 19:54:13 +05301011
1012 // Break ending arrays/maps are always processed at the end of this function.
1013 // They should never show up here.
Laurence Lundblade6de37062018-10-15 12:22:42 +05301014 if(pDecodedItem->uDataType == QCBOR_TYPE_BREAK) {
Laurence Lundblade6de37062018-10-15 12:22:42 +05301015 nReturn = QCBOR_ERR_BAD_BREAK;
1016 goto Done;
Laurence Lundblade5b8c5852018-10-14 21:11:42 +05301017 }
Laurence Lundbladeb69cad72018-09-13 11:09:01 -07001018
Laurence Lundblade6de37062018-10-15 12:22:42 +05301019 // Record the nesting level for this data item before processing any of
Laurence Lundblade7e0d13b2018-10-16 19:54:13 +05301020 // decrementing and descending.
Laurence Lundblade6de37062018-10-15 12:22:42 +05301021 pDecodedItem->uNestingLevel = DecodeNesting_GetLevel(&(me->nesting));
1022
1023 // Process the item just received for descent or decrement, and
1024 // ascent if decrements are enough to close out a definite length array/map
Laurence Lundblade3a760b02018-10-08 13:46:03 +08001025 if(IsMapOrArray(pDecodedItem->uDataType)) {
Laurence Lundblade9e3651c2018-10-10 11:49:55 +08001026 // If the new item is array or map, the nesting level descends
Laurence Lundblade3a760b02018-10-08 13:46:03 +08001027 nReturn = DecodeNesting_Descend(&(me->nesting), pDecodedItem);
Laurence Lundblade9e3651c2018-10-10 11:49:55 +08001028 // Maps and arrays do count in as items in the map/array that encloses
1029 // them so a decrement needs to be done for them too, but that is done
1030 // only when all the items in them have been processed, not when they
1031 // are opened.
1032 } else {
1033 // Decrement the count of items in the enclosing map/array
1034 // If the count in the enclosing map/array goes to zero, that
Laurence Lundblade6de37062018-10-15 12:22:42 +05301035 // triggers a decrement in the map/array above that and
1036 // an ascend in nesting level.
Laurence Lundblade9e3651c2018-10-10 11:49:55 +08001037 DecodeNesting_DecrementCount(&(me->nesting));
Laurence Lundbladeb69cad72018-09-13 11:09:01 -07001038 }
Laurence Lundblade6de37062018-10-15 12:22:42 +05301039 if(nReturn) {
1040 goto Done;
1041 }
1042
1043 // For indefinite length maps/arrays, looking at any and
1044 // all breaks that might terminate them. The equivalent
1045 // for definite length maps/arrays happens in
1046 // DecodeNesting_DecrementCount().
1047 if(DecodeNesting_IsNested(&(me->nesting)) && DecodeNesting_IsIndefiniteLength(&(me->nesting))) {
1048 while(UsefulInputBuf_BytesUnconsumed(&(me->InBuf))) {
1049 // Peek forward one item to see if it is a break.
1050 QCBORItem Peek;
1051 size_t uPeek = UsefulInputBuf_Tell(&(me->InBuf));
1052 nReturn = GetNext_Item(&(me->InBuf), &Peek, NULL);
1053 if(nReturn) {
1054 goto Done;
1055 }
1056 if(Peek.uDataType != QCBOR_TYPE_BREAK) {
1057 // It is not a break, rewind so it can be processed normally.
1058 UsefulInputBuf_Seek(&(me->InBuf), uPeek);
1059 break;
1060 }
1061 // It is a break. Ascend one nesting level.
Laurence Lundblade7e0d13b2018-10-16 19:54:13 +05301062 // The break is consumed.
Laurence Lundblade6de37062018-10-15 12:22:42 +05301063 nReturn = DecodeNesting_BreakAscend(&(me->nesting));
1064 if(nReturn) {
1065 // break occured outside of an indefinite length array/map
1066 goto Done;
1067 }
1068 }
1069 }
1070
1071 // Tell the caller what level is next. This tells them what maps/arrays
1072 // were closed out and makes it possible for them to reconstruct
1073 // the tree with just the information returned by GetNext
1074 pDecodedItem->uNextNestLevel = DecodeNesting_GetLevel(&(me->nesting));
Laurence Lundbladeb69cad72018-09-13 11:09:01 -07001075
1076Done:
1077 return nReturn;
1078}
1079
1080
Laurence Lundblade30816f22018-11-10 13:40:22 +07001081QCBORError QCBORDecode_GetNext(QCBORDecodeContext *me, QCBORItem *pDecodedItem)
Laurence Lundbladedbe6f212018-10-28 11:37:53 +07001082{
1083 return QCBORDecode_GetNextWithTags(me, pDecodedItem, NULL);
1084}
1085
1086
Laurence Lundbladeb69cad72018-09-13 11:09:01 -07001087/*
Laurence Lundblade6de37062018-10-15 12:22:42 +05301088 Decoding items is done in 5 layered functions, one calling the
Laurence Lundblade0fb2f642018-10-11 19:33:35 +05301089 next one down. If a layer has no work to do for a particular item
1090 it returns quickly.
1091
1092 - QCBORDecode_GetNext -- The top layer manages the beginnings and
1093 ends of maps and arrays. It tracks descending into and ascending
Laurence Lundblade6de37062018-10-15 12:22:42 +05301094 out of maps/arrays. It processes all breaks that terminate
1095 maps and arrays.
Laurence Lundblade0fb2f642018-10-11 19:33:35 +05301096
1097 - GetNext_MapEntry -- This handles the combining of two
1098 items, the label and the data, that make up a map entry.
1099 It only does work on maps. It combines the label and data
1100 items into one labeled item.
1101
1102 - GetNext_TaggedItem -- This handles the type 6 tagged items.
1103 It accumulates all the tags and combines them with the following
1104 non-tagged item. If the tagged item is something that is understood
1105 like a date, the decoding of that item is invoked.
1106
1107 - GetNext_FullItem -- This assembles the sub items that make up
1108 an indefinte length string into one string item. It uses the
Laurence Lundblade6de37062018-10-15 12:22:42 +05301109 string allocater to create contiguous space for the item. It
1110 processes all breaks that are part of indefinite length strings.
Laurence Lundblade0fb2f642018-10-11 19:33:35 +05301111
1112 - GetNext_Item -- This gets and decodes the most atomic
1113 item in CBOR, the thing with an initial byte containing
1114 the major type.
1115
Laurence Lundbladedbe6f212018-10-28 11:37:53 +07001116 Roughly this takes 300 bytes of stack for vars. Need to
1117 evaluate this more carefully and correctly.
1118
Laurence Lundblade0fb2f642018-10-11 19:33:35 +05301119 */
1120
1121
1122/*
Laurence Lundbladeb69cad72018-09-13 11:09:01 -07001123 Public function, see header qcbor.h file
1124 */
Laurence Lundbladedbe6f212018-10-28 11:37:53 +07001125int QCBORDecode_IsTagged(QCBORDecodeContext *me, const QCBORItem *pItem, uint64_t uTag)
1126{
1127 const QCBORTagListIn *pCallerConfiguredTagMap = me->pCallerConfiguredTagList;
1128
1129 uint8_t uTagBitIndex;
1130 // Do not care about errors in pCallerConfiguredTagMap here. They are
1131 // caught during GetNext() before this is called.
1132 if(TagMapper_Lookup(pCallerConfiguredTagMap, uTag, &uTagBitIndex)) {
1133 return 0;
1134 }
1135
1136 const uint64_t uTagBit = 0x01ULL << uTagBitIndex;
1137 return (uTagBit & pItem->uTagBits) != 0;
1138}
1139
1140
1141/*
1142 Public function, see header qcbor.h file
1143 */
Laurence Lundblade30816f22018-11-10 13:40:22 +07001144QCBORError QCBORDecode_Finish(QCBORDecodeContext *me)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -07001145{
Laurence Lundblade041ffa52018-10-07 11:43:51 +07001146 int nReturn = QCBOR_SUCCESS;
1147
Laurence Lundblade20b533d2018-10-08 20:44:53 +08001148 // Error out if all the maps/arrays are not closed out
1149 if(DecodeNesting_IsNested(&(me->nesting))) {
1150 nReturn = QCBOR_ERR_ARRAY_OR_MAP_STILL_OPEN;
1151 goto Done;
1152 }
1153
1154 // Error out if not all the bytes are consumed
1155 if(UsefulInputBuf_BytesUnconsumed(&(me->InBuf))) {
1156 nReturn = QCBOR_ERR_EXTRA_BYTES;
1157 }
1158
1159Done:
Laurence Lundblade6de37062018-10-15 12:22:42 +05301160 // Call the destructor for the string allocator if there is one.
Laurence Lundblade20b533d2018-10-08 20:44:53 +08001161 // Always called, even if there are errors; always have to clean up
Laurence Lundblade041ffa52018-10-07 11:43:51 +07001162 if(me->pStringAllocator) {
1163 QCBORStringAllocator *pAllocator = (QCBORStringAllocator *)me->pStringAllocator;
1164 if(pAllocator->fDestructor) {
1165 (pAllocator->fDestructor)(pAllocator->pAllocaterContext);
1166 }
1167 }
1168
Laurence Lundblade041ffa52018-10-07 11:43:51 +07001169 return nReturn;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -07001170}
1171
1172
1173
1174/*
1175
1176Decoder errors handled in this file
1177
1178 - Hit end of input before it was expected while decoding type and number QCBOR_ERR_HIT_END
Laurence Lundblade041ffa52018-10-07 11:43:51 +07001179
Laurence Lundbladeb69cad72018-09-13 11:09:01 -07001180 - negative integer that is too large for C QCBOR_ERR_INT_OVERFLOW
1181
1182 - Hit end of input while decoding a text or byte string QCBOR_ERR_HIT_END
1183
1184 - Encountered conflicting tags -- e.g., an item is tagged both a date string and an epoch date QCBOR_ERR_UNSUPPORTED
Laurence Lundblade5b8c5852018-10-14 21:11:42 +05301185
Laurence Lundbladeb69cad72018-09-13 11:09:01 -07001186 - Encontered an array or mapp that has too many items QCBOR_ERR_ARRAY_TOO_LONG
1187
1188 - Encountered array/map nesting that is too deep QCBOR_ERR_ARRAY_NESTING_TOO_DEEP
1189
1190 - An epoch date > INT64_MAX or < INT64_MIN was encountered QCBOR_ERR_DATE_OVERFLOW
1191
1192 - The type of a map label is not a string or int QCBOR_ERR_MAP_LABEL_TYPE
1193
1194 - Hit end with arrays or maps still open -- QCBOR_ERR_EXTRA_BYTES
1195
1196 */
1197
Laurence Lundblade041ffa52018-10-07 11:43:51 +07001198
1199
Laurence Lundbladef6531662018-12-04 10:42:22 +09001200
1201/*
1202 This is a very primitive memory allocator. It does not track individual
1203 allocations, only a high-water mark. A free or reallotcation must be of
1204 the last chunk allocated.
1205
1206 All of this following code will get dead-stripped if QCBORDecode_SetMemPool()
1207 is not called.
1208 */
1209
Laurence Lundblade041ffa52018-10-07 11:43:51 +07001210typedef struct {
1211 QCBORStringAllocator StringAllocator;
Laurence Lundbladef6531662018-12-04 10:42:22 +09001212 uint8_t *pStart; // First byte that can be allocated
1213 uint8_t *pEnd; // One past the last byte that can be allocated
1214 uint8_t *pFree; // Where the next free chunk is
Laurence Lundblade041ffa52018-10-07 11:43:51 +07001215} MemPool;
1216
1217
1218/*
Laurence Lundbladef6531662018-12-04 10:42:22 +09001219 Internal function for an allocation
1220
Laurence Lundblade041ffa52018-10-07 11:43:51 +07001221 Code Reviewers: THIS FUNCTION DOES POINTER MATH
1222 */
1223static UsefulBuf MemPool_Alloc(void *ctx, void *pMem, size_t uNewSize)
1224{
Laurence Lundbladef6531662018-12-04 10:42:22 +09001225 MemPool *me = (MemPool *)ctx;
1226 void *pReturn = NULL;
Laurence Lundblade041ffa52018-10-07 11:43:51 +07001227
1228 if(pMem) {
1229 // Realloc case
Laurence Lundbladef6531662018-12-04 10:42:22 +09001230 // This check will work even if uNewSize is a super-large value like UINT64_MAX
1231 if((uNewSize <= (size_t)(me->pEnd - (uint8_t *)pMem)) && ((uint8_t *)pMem >= me->pStart)) {
Laurence Lundblade9e3651c2018-10-10 11:49:55 +08001232 me->pFree = (uint8_t *)pMem + uNewSize;
Laurence Lundbladef6531662018-12-04 10:42:22 +09001233 pReturn = pMem;
Laurence Lundblade041ffa52018-10-07 11:43:51 +07001234 }
1235 } else {
1236 // New chunk case
Laurence Lundbladef6531662018-12-04 10:42:22 +09001237 // This check will work even if uNewSize is a super large value like UINT64_MAX
1238 if(uNewSize <= (size_t)(me->pEnd - me->pFree)) {
1239 pReturn = me->pFree;
Laurence Lundblade041ffa52018-10-07 11:43:51 +07001240 me->pFree += uNewSize;
1241 }
1242 }
1243
1244 return (UsefulBuf){pReturn, uNewSize};
1245}
1246
Laurence Lundbladef6531662018-12-04 10:42:22 +09001247/*
1248 Internal function to free memory
1249 */
Laurence Lundblade041ffa52018-10-07 11:43:51 +07001250static void MemPool_Free(void *ctx, void *pOldMem)
1251{
1252 MemPool *me = (MemPool *)ctx;
Laurence Lundbladef6531662018-12-04 10:42:22 +09001253 me->pFree = pOldMem;
Laurence Lundblade041ffa52018-10-07 11:43:51 +07001254}
1255
Laurence Lundbladef6531662018-12-04 10:42:22 +09001256/*
1257 Public function, see header qcbor.h file
1258 */
Laurence Lundblade30816f22018-11-10 13:40:22 +07001259QCBORError QCBORDecode_SetMemPool(QCBORDecodeContext *me, UsefulBuf Pool, bool bAllStrings)
Laurence Lundblade041ffa52018-10-07 11:43:51 +07001260{
Laurence Lundbladef6531662018-12-04 10:42:22 +09001261 // The first bytes of the Pool passed in are used
1262 // as the context (vtable of sorts) for the memory pool
1263 // allocator.
Laurence Lundblade041ffa52018-10-07 11:43:51 +07001264 if(Pool.len < sizeof(MemPool)+1) {
Laurence Lundblade30816f22018-11-10 13:40:22 +07001265 return QCBOR_ERR_BUFFER_TOO_SMALL;
Laurence Lundblade041ffa52018-10-07 11:43:51 +07001266 }
1267
1268 MemPool *pMP = (MemPool *)Pool.ptr;
1269
Laurence Lundbladef6531662018-12-04 10:42:22 +09001270 // Fill in the "vtable"
Laurence Lundblade041ffa52018-10-07 11:43:51 +07001271 pMP->StringAllocator.fAllocate = MemPool_Alloc;
1272 pMP->StringAllocator.fFree = MemPool_Free;
1273 pMP->StringAllocator.fDestructor = NULL;
1274
Laurence Lundbladef6531662018-12-04 10:42:22 +09001275 // Set up the pointers to the memory to be allocated
Laurence Lundblade570fab52018-10-13 18:28:27 +08001276 pMP->pStart = (uint8_t *)Pool.ptr + sizeof(MemPool);
Laurence Lundblade041ffa52018-10-07 11:43:51 +07001277 pMP->pFree = pMP->pStart;
Laurence Lundblade570fab52018-10-13 18:28:27 +08001278 pMP->pEnd = (uint8_t *)Pool.ptr + Pool.len;
Laurence Lundblade041ffa52018-10-07 11:43:51 +07001279
Laurence Lundbladef6531662018-12-04 10:42:22 +09001280 // More book keeping of context
1281 pMP->StringAllocator.pAllocaterContext = pMP;
1282 me->pStringAllocator = pMP;
1283
1284 // The flag indicating when to use the allocator
Laurence Lundblade041ffa52018-10-07 11:43:51 +07001285 me->bStringAllocateAll = bAllStrings;
Laurence Lundblade5b8c5852018-10-14 21:11:42 +05301286
Laurence Lundblade30816f22018-11-10 13:40:22 +07001287 return QCBOR_SUCCESS;
Laurence Lundblade041ffa52018-10-07 11:43:51 +07001288}
1289
Laurence Lundbladef6531662018-12-04 10:42:22 +09001290
1291/*
1292 Extra little hook to make MemPool testing work right
1293 without adding any code size or overhead to non-test
1294 uses. This will get dead-stripped for non-test use.
1295
1296 This is not a public function.
1297 */
1298size_t MemPoolTestHook_GetPoolSize(void *ctx)
1299{
1300 MemPool *me = (MemPool *)ctx;
1301
1302 return me->pEnd - me->pStart;
1303}
1304