blob: 553619440985ae9f130ab9b4b29aac4949ef831b [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.
Laurence Lundbladeee851742020-01-08 08:37:05 -08003 Copyright (c) 2018-2020, Laurence Lundblade.
Laurence Lundbladed92a6162018-11-01 11:38:35 +07004 All rights reserved.
Laurence Lundblade3aee3a32018-12-17 16:17:45 -08005
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 Lundblade3aee3a32018-12-17 16:17:45 -080019
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 Lundbladeee851742020-01-08 08:37:05 -080031 =============================================================================*/
Laurence Lundblade624405d2018-09-18 20:10:47 -070032
Laurence Lundbladeee851742020-01-08 08:37:05 -080033/*=============================================================================
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070034 FILE: qcbor_encode.c
Laurence Lundblade3aee3a32018-12-17 16:17:45 -080035
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070036 DESCRIPTION: This file contains the implementation of QCBOR.
Laurence Lundblade3aee3a32018-12-17 16:17:45 -080037
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070038 EDIT HISTORY FOR FILE:
Laurence Lundblade3aee3a32018-12-17 16:17:45 -080039
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070040 This section contains comments describing changes made to the module.
41 Notice that changes are listed in reverse chronological order.
Laurence Lundblade3aee3a32018-12-17 16:17:45 -080042
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +000043 when who what, where, why
44 -------- ---- ---------------------------------------------------
45 02/07/2020 llundblade QCBOREncode_EncodeHead() and other for bstr hashing.
46 01/25/2020 llundblade Refine use of integer types to quiet static analysis.
47 01/08/2020 llundblade Documentation corrections & improved code formatting.
48 12/30/19 llundblade Add support for decimal fractions and bigfloats.
49 8/7/19 llundblade Prevent encoding simple type reserved values 24..31
50 7/25/19 janjongboom Add indefinite length encoding for maps and arrays
51 4/6/19 llundblade Wrapped bstr returned now includes the wrapping bstr.
52 12/30/18 llundblade Small efficient clever encode of type & argument.
53 11/29/18 llundblade Rework to simpler handling of tags and labels.
54 11/9/18 llundblade Error codes are now enums.
55 11/1/18 llundblade Floating support.
56 10/31/18 llundblade Switch to one license that is almost BSD-3.
57 09/28/18 llundblade Added bstr wrapping feature for COSE implementation.
58 02/05/18 llundbla Works on CPUs which require integer alignment.
59 Requires new version of UsefulBuf.
60 07/05/17 llundbla Add bstr wrapping of maps/arrays for COSE
61 03/01/17 llundbla More data types
62 11/13/16 llundbla Integrate most TZ changes back into github version.
63 09/30/16 gkanike Porting to TZ.
64 03/15/16 llundbla Initial Version.
Laurence Lundblade3aee3a32018-12-17 16:17:45 -080065
Laurence Lundbladeee851742020-01-08 08:37:05 -080066 =============================================================================*/
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070067
68#include "qcbor.h"
Laurence Lundblade12d32c52018-09-19 11:25:27 -070069#include "ieee754.h"
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070070
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070071
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070072
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070073/*
Laurence Lundbladeee851742020-01-08 08:37:05 -080074 Nesting -- This tracks the nesting of maps and arrays.
75
76 The following functions and data type QCBORTrackNesting implement the
77 nesting management for encoding.
78
79 CBOR's two nesting types, arrays and maps, are tracked here. There is
80 a limit of QCBOR_MAX_ARRAY_NESTING to the number of arrays and maps
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070081 that can be nested in one encoding so the encoding context stays
82 small enough to fit on the stack.
Laurence Lundblade3aee3a32018-12-17 16:17:45 -080083
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070084 When an array / map is opened, pCurrentNesting points to the element
Laurence Lundbladeee851742020-01-08 08:37:05 -080085 in pArrays that records the type, start position and accumulates a
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070086 count of the number of items added. When closed the start position is
87 used to go back and fill in the type and number of items in the array
88 / map.
Laurence Lundblade3aee3a32018-12-17 16:17:45 -080089
Laurence Lundbladeee851742020-01-08 08:37:05 -080090 Encoded output can be just items like ints and strings that are not
91 part of any array / map. That is, the first thing encoded does not
92 have to be an array or a map.
93
94 QCBOR has a special feature to allow constructing bstr-wrapped CBOR
95 directly into the output buffer, so an extra buffer for it is not
96 needed. This is implemented as nesting with type
97 CBOR_MAJOR_TYPE_BYTE_STRING and uses this code. Bstr-wrapped CBOR is
98 used by COSE for data that is to be hashed.
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070099 */
100inline static void Nesting_Init(QCBORTrackNesting *pNesting)
101{
Laurence Lundbladeee851742020-01-08 08:37:05 -0800102 // Assumes pNesting has been zeroed
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700103 pNesting->pCurrentNesting = &pNesting->pArrays[0];
104 // Implied CBOR array at the top nesting level. This is never returned,
105 // but makes the item count work correctly.
106 pNesting->pCurrentNesting->uMajorType = CBOR_MAJOR_TYPE_ARRAY;
107}
108
Laurence Lundblade2c40ab82018-12-30 14:20:29 -0800109inline static QCBORError Nesting_Increase(QCBORTrackNesting *pNesting,
110 uint8_t uMajorType,
111 uint32_t uPos)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700112{
Laurence Lundblade30816f22018-11-10 13:40:22 +0700113 QCBORError nReturn = QCBOR_SUCCESS;
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800114
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700115 if(pNesting->pCurrentNesting == &pNesting->pArrays[QCBOR_MAX_ARRAY_NESTING]) {
Laurence Lundbladeee851742020-01-08 08:37:05 -0800116 // Trying to open one too many
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700117 nReturn = QCBOR_ERR_ARRAY_NESTING_TOO_DEEP;
118 } else {
119 pNesting->pCurrentNesting++;
120 pNesting->pCurrentNesting->uCount = 0;
121 pNesting->pCurrentNesting->uStart = uPos;
122 pNesting->pCurrentNesting->uMajorType = uMajorType;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700123 }
124 return nReturn;
125}
126
127inline static void Nesting_Decrease(QCBORTrackNesting *pNesting)
128{
129 pNesting->pCurrentNesting--;
130}
131
Laurence Lundblade1ef8b2d2018-12-14 23:13:34 -0800132inline static QCBORError Nesting_Increment(QCBORTrackNesting *pNesting)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700133{
Laurence Lundblade1ef8b2d2018-12-14 23:13:34 -0800134 if(1 >= QCBOR_MAX_ITEMS_IN_ARRAY - pNesting->pCurrentNesting->uCount) {
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700135 return QCBOR_ERR_ARRAY_TOO_LONG;
136 }
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800137
Laurence Lundblade1ef8b2d2018-12-14 23:13:34 -0800138 pNesting->pCurrentNesting->uCount += 1;
Laurence Lundblade2c40ab82018-12-30 14:20:29 -0800139
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700140 return QCBOR_SUCCESS;
141}
142
143inline static uint16_t Nesting_GetCount(QCBORTrackNesting *pNesting)
144{
145 // The nesting count recorded is always the actual number of individiual
146 // data items in the array or map. For arrays CBOR uses the actual item
147 // count. For maps, CBOR uses the number of pairs. This function returns
148 // the number needed for the CBOR encoding, so it divides the number of
149 // items by two for maps to get the number of pairs. This implementation
150 // takes advantage of the map major type being one larger the array major
Laurence Lundblade2c40ab82018-12-30 14:20:29 -0800151 // type, hence uDivisor is either 1 or 2.
Laurence Lundblade2c40ab82018-12-30 14:20:29 -0800152
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800153 if(pNesting->pCurrentNesting->uMajorType == CBOR_MAJOR_TYPE_MAP) {
154 // Cast back to uint16_t after integer promotion for bit shift
155 return (uint16_t)(pNesting->pCurrentNesting->uCount >> 1);
156 } else {
157 return pNesting->pCurrentNesting->uCount;
158 }
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700159}
160
161inline static uint32_t Nesting_GetStartPos(QCBORTrackNesting *pNesting)
162{
163 return pNesting->pCurrentNesting->uStart;
164}
165
166inline static uint8_t Nesting_GetMajorType(QCBORTrackNesting *pNesting)
167{
168 return pNesting->pCurrentNesting->uMajorType;
169}
170
Laurence Lundbladeee851742020-01-08 08:37:05 -0800171inline static bool Nesting_IsInNest(QCBORTrackNesting *pNesting)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700172{
Laurence Lundbladeee851742020-01-08 08:37:05 -0800173 return pNesting->pCurrentNesting == &pNesting->pArrays[0] ? false : true;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700174}
175
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700176
177
178
179/*
Laurence Lundbladeee851742020-01-08 08:37:05 -0800180 Encoding of the major CBOR types is by these functions:
181
182 CBOR Major Type Public Function
183 0 QCBOREncode_AddUInt64()
184 0, 1 QCBOREncode_AddUInt64(), QCBOREncode_AddInt64()
185 2, 3 QCBOREncode_AddBuffer(), Also QCBOREncode_OpenMapOrArray(),
186 QCBOREncode_CloseMapOrArray()
187 4, 5 QCBOREncode_OpenMapOrArray(), QCBOREncode_CloseMapOrArray(),
188 QCBOREncode_OpenMapOrArrayIndefiniteLength(),
189 QCBOREncode_CloseMapOrArrayIndefiniteLength()
190 6 QCBOREncode_AddTag()
191 7 QCBOREncode_AddDouble(), QCBOREncode_AddType7()
192
193 Additionally, encoding of decimal fractions and bigfloats is by
194 QCBOREncode_AddExponentAndMantissa()
195*/
196
197/*
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700198 Error tracking plan -- Errors are tracked internally and not returned
Laurence Lundbladeee851742020-01-08 08:37:05 -0800199 until QCBOREncode_Finish is called. The CBOR errors are in me->uError.
Laurence Lundblade067035b2018-11-28 17:35:25 -0800200 UsefulOutBuf also tracks whether the buffer is full or not in its
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700201 context. Once either of these errors is set they are never
Laurence Lundblade241705e2018-12-30 18:56:14 -0800202 cleared. Only QCBOREncode_Init() resets them. Or said another way, they must
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700203 never be cleared or we'll tell the caller all is good when it is not.
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800204
Laurence Lundblade241705e2018-12-30 18:56:14 -0800205 Only one error code is reported by QCBOREncode_Finish() even if there are
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700206 multiple errors. The last one set wins. The caller might have to fix
207 one error to reveal the next one they have to fix. This is OK.
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800208
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700209 The buffer full error tracked by UsefulBuf is only pulled out of
210 UsefulBuf in Finish() so it is the one that usually wins. UsefulBuf
211 will never go off the end of the buffer even if it is called again
212 and again when full.
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800213
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700214 It is really tempting to not check for overflow on the count in the
215 number of items in an array. It would save a lot of code, it is
216 extremely unlikely that any one will every put 65,000 items in an
217 array, and the only bad thing that would happen is the CBOR would be
Laurence Lundblade241705e2018-12-30 18:56:14 -0800218 bogus.
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800219
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700220 Since this does not parse any input, you could in theory remove all
221 error checks in this code if you knew the caller called it
222 correctly. Maybe someday CDDL or some such language will be able to
223 generate the code to call this and the calling code would always be
Laurence Lundblade56230d12018-11-01 11:14:51 +0700224 correct. This could also automatically size some of the data
Laurence Lundblade241705e2018-12-30 18:56:14 -0800225 structures like array/map nesting resulting in some stack memory
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700226 savings.
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800227
Laurence Lundbladeee851742020-01-08 08:37:05 -0800228 The 8 errors returned here fall into three categories:
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800229
Laurence Lundblade067035b2018-11-28 17:35:25 -0800230 Sizes
Laurence Lundbladeee851742020-01-08 08:37:05 -0800231 QCBOR_ERR_BUFFER_TOO_LARGE -- Encoded output exceeded UINT32_MAX
232 QCBOR_ERR_BUFFER_TOO_SMALL -- Output buffer too small
233 QCBOR_ERR_ARRAY_NESTING_TOO_DEEP -- Nesting > QCBOR_MAX_ARRAY_NESTING1
234 QCBOR_ERR_ARRAY_TOO_LONG -- Too many things added to an array/map
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800235
Laurence Lundblade067035b2018-11-28 17:35:25 -0800236 Nesting constructed incorrectly
Laurence Lundbladeee851742020-01-08 08:37:05 -0800237 QCBOR_ERR_TOO_MANY_CLOSES -- More close calls than opens
238 QCBOR_ERR_CLOSE_MISMATCH -- Type of close does not match open
Laurence Lundblade067035b2018-11-28 17:35:25 -0800239 QCBOR_ERR_ARRAY_OR_MAP_STILL_OPEN -- Finish called without enough closes
Laurence Lundbladebb1062e2019-08-12 23:28:54 -0700240
241 Would generate not-well-formed CBOR
Laurence Lundbladeee851742020-01-08 08:37:05 -0800242 QCBOR_ERR_UNSUPPORTED -- Simple type between 24 and 31
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700243 */
244
245
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700246/*
247 Public function for initialization. See header qcbor.h
248 */
Laurence Lundblade2296db52018-09-14 18:08:39 -0700249void QCBOREncode_Init(QCBOREncodeContext *me, UsefulBuf Storage)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700250{
251 memset(me, 0, sizeof(QCBOREncodeContext));
Laurence Lundblade1ef8b2d2018-12-14 23:13:34 -0800252 UsefulOutBuf_Init(&(me->OutBuf), Storage);
253 Nesting_Init(&(me->nesting));
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700254}
255
256
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000257/*
258 Public function for initialization. See header qcbor.h
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700259 */
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000260UsefulBufC QCBOREncode_EncodeHead(UsefulBuf buffer,
261 uint8_t uMajorType,
262 uint8_t uMinLen,
263 uint64_t uArgument)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700264{
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000265 /**
266 All CBOR data items have a type and an "argument". The argument is
267 either the value of the item for integer types, the length of the
268 content for string, byte, array and map types, a tag for major type
269 6, and has several uses for major type 7.
270
271 This function encodes the type and the argument. There are several
272 encodings for the argument depending on how large it is and how it is
273 used.
274
275 Every encoding of the type and argument has at least one byte, the
276 "initial byte".
277
278 The top three bits of the initial byte are the major type for the
279 CBOR data item. The eight major types defined by the standard are
280 defined as CBOR_MAJOR_TYPE_xxxx in qcbor.h.
281
282 The remaining five bits, known as "additional information", and
283 possibly more bytes encode the argument. If the argument is less than
284 24, then it is encoded entirely in the five bits. This is neat
285 because it allows you to encode an entire CBOR data item in 1 byte
286 for many values and types (integers 0-23, true, false, and tags).
287
288 If the argument is larger than 24, then it is encoded in 1,2,4 or 8
289 additional bytes, with the number of these bytes indicated by the
290 values of the 5 bits 24, 25, 25 and 27.
291
292 It is possible to encode a particular argument in many ways with this
293 representation. This implementation always uses the smallest
294 possible representation. This conforms with CBOR preferred encoding.
295
296 This function inserts them into the output buffer at the specified
297 position. AppendEncodedTypeAndNumber() appends to the end.
298
299 This function takes care of converting to network byte order.
300
301 This function is also used to insert floats and doubles. Before this
302 function is called the float or double must be copied into a
303 uint64_t. That is how they are passed in. They are then converted to
304 network byte order correctly. The uMinLen parameter makes sure that
305 even if all the digits of a half, float or double are 0 it is still
306 correctly encoded in 2, 4 or 8 bytes.
307 */
Laurence Lundbladee9b00322018-12-30 10:33:26 -0800308 /*
309 This code does endian conversion without hton or knowing the
Laurence Lundblade241705e2018-12-30 18:56:14 -0800310 endianness of the machine using masks and shifts. This avoids the
Laurence Lundbladee9b00322018-12-30 10:33:26 -0800311 dependency on hton and the mess of figuring out how to find the
312 machine's endianness.
Laurence Lundblade2c40ab82018-12-30 14:20:29 -0800313
Laurence Lundbladee9b00322018-12-30 10:33:26 -0800314 This is a good efficient implementation on little-endian machines.
315 A faster and small implementation is possible on big-endian
316 machines because CBOR/network byte order is big endian. However
317 big endian machines are uncommon.
Laurence Lundblade2c40ab82018-12-30 14:20:29 -0800318
Laurence Lundbladee9b00322018-12-30 10:33:26 -0800319 On x86, it is about 200 bytes instead of 500 bytes for the more
320 formal unoptimized code.
Laurence Lundblade2c40ab82018-12-30 14:20:29 -0800321
Laurence Lundbladee9b00322018-12-30 10:33:26 -0800322 This also does the CBOR preferred shortest encoding for integers
323 and is called to do endian conversion for floats.
Laurence Lundblade2c40ab82018-12-30 14:20:29 -0800324
Laurence Lundbladee9b00322018-12-30 10:33:26 -0800325 It works backwards from the LSB to the MSB as needed.
Laurence Lundblade2c40ab82018-12-30 14:20:29 -0800326
Laurence Lundbladee9b00322018-12-30 10:33:26 -0800327 Code Reviewers: THIS FUNCTION DOES POINTER MATH
328 */
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800329 /*
330 The type int is used here for several variables because of the way
331 integer promotion works in C for integer variables that are
332 uint8_t or uint16_t. The basic rule is that they will always be
333 promoted to int if they will fit. All of these integer variables
334 need only hold values less than 255 or are promoted from uint8_t,
335 so they will always fit into an int. Note that promotion is only
336 to unsigned int if the value won't fit into an int even if the
337 promotion is for an unsigned like uint8_t.
338
339 By declaring them int, there are few implicit conversions and fewer
340 casts needed. Code size is reduced a little. It also makes static
341 analyzers happier.
342
343 Note also that declaring them uint8_t won't stop integer wrap
344 around if the code is wrong. It won't make the code more correct.
345
346 https://stackoverflow.com/questions/46073295/implicit-type-promotion-rules
347 https://stackoverflow.com/questions/589575/what-does-the-c-standard-state-the-size-of-int-long-type-to-be
348 */
Laurence Lundbladeee851742020-01-08 08:37:05 -0800349
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000350 // Buffer must have room for the largest CBOR HEAD + one extra as the
351 // one extra is needed for this code to work as it does a pre-decrement.
352 if(buffer.len < QCBOR_HEAD_BUFFER_SIZE) {
353 return NULLUsefulBufC;
354 }
355
356 // Pointer to last valid byte in the buffer
357 uint8_t * const pBufferEnd = &((uint8_t *)buffer.ptr)[QCBOR_HEAD_BUFFER_SIZE-1];
358
359 // Point to the last byte and work backwards
360 uint8_t *pByte = pBufferEnd;
361 // The 5 bits in the initial byte that are not the major type
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800362 int nAdditionalInfo;
Laurence Lundblade2c40ab82018-12-30 14:20:29 -0800363
Jan Jongboom5d827882019-08-07 12:51:15 +0200364 if (uMajorType == CBOR_MAJOR_NONE_TYPE_ARRAY_INDEFINITE_LEN) {
365 uMajorType = CBOR_MAJOR_TYPE_ARRAY;
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800366 nAdditionalInfo = LEN_IS_INDEFINITE;
Jan Jongboom5d827882019-08-07 12:51:15 +0200367 } else if (uMajorType == CBOR_MAJOR_NONE_TYPE_MAP_INDEFINITE_LEN) {
368 uMajorType = CBOR_MAJOR_TYPE_MAP;
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800369 nAdditionalInfo = LEN_IS_INDEFINITE;
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000370 } else if (uArgument < CBOR_TWENTY_FOUR && uMinLen == 0) {
Laurence Lundbladee9b00322018-12-30 10:33:26 -0800371 // Simple case where argument is < 24
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000372 nAdditionalInfo = (int)uArgument;
373 } else if (uMajorType == CBOR_MAJOR_TYPE_SIMPLE && uArgument == CBOR_SIMPLE_BREAK) {
Jan Jongboom4a93a662019-07-25 08:44:58 +0200374 // Break statement can be encoded in single byte too (0xff)
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000375 nAdditionalInfo = (int)uArgument;
Laurence Lundblade04a859b2018-12-11 12:13:02 -0800376 } else {
Laurence Lundbladee9b00322018-12-30 10:33:26 -0800377 /*
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000378 Encode argument in 1,2,4 or 8 bytes. Outer loop
379 runs once for 1 byte and 4 times for 8 bytes.
380 Inner loop runs 1, 2 or 4 times depending on
381 outer loop counter. This works backwards taking
382 8 bits off the argument being encoded at a time
383 until all bits from uNumber have been encoded
384 and the minimum encoding size is reached.
385 Minimum encoding size is for floating point
386 numbers with zero bytes.
Laurence Lundbladee9b00322018-12-30 10:33:26 -0800387 */
Laurence Lundblade04a859b2018-12-11 12:13:02 -0800388 static const uint8_t aIterate[] = {1,1,2,4};
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000389
390 // The parameter passed in is unsigned, but goes negative in the loop
391 // so it must be converted to a signed value.
392 int nMinLen = (int)uMinLen;
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800393 int i;
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000394 for(i = 0; uArgument || nMinLen > 0; i++) {
395 const int nIterations = (int)aIterate[i];
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800396 for(int j = 0; j < nIterations; j++) {
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000397 *--pByte = (uint8_t)(uArgument & 0xff);
398 uArgument = uArgument >> 8;
Laurence Lundblade04a859b2018-12-11 12:13:02 -0800399 }
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800400 nMinLen -= nIterations;
Laurence Lundblade04a859b2018-12-11 12:13:02 -0800401 }
Laurence Lundbladeee851742020-01-08 08:37:05 -0800402 // Additional info is the encoding of the number of additional
403 // bytes to encode argument.
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800404 nAdditionalInfo = LEN_IS_ONE_BYTE-1 + i;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700405 }
Laurence Lundbladef970f1d2018-12-14 01:44:23 -0800406
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800407 /*
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000408 This expression integer-promotes to type int. The code above in
409 function guarantees that nAdditionalInfo will never be larger than
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800410 0x1f. The caller may pass in a too-large uMajor type. The
411 conversion to unint8_t will cause an integer wrap around and
412 incorrect CBOR will be generated, but no security issue will
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000413 occur.
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800414 */
415 *--pByte = (uint8_t)((uMajorType << 5) + nAdditionalInfo);
416
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000417#ifdef EXTRA_ENCODE_HEAD_CHECK
418 /* This is a sanity check that can be turned on to verify the pointer
419 * math in this function is not going wrong. Turn it on and run the
420 * whole test suite to perform the check.
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800421 */
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000422 if(pBufferEnd - pByte > 9 || pBufferEnd - pByte < 1 || pByte < (uint8_t *)buffer.ptr) {
423 return NULLUsefulBufC;
424 }
425#endif
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800426
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000427 // Length will not go negative because the loops run for at most 8 decrements
428 // of pByte, only one other decrement is made, and the array is sized
429 // for this.
430 return (UsefulBufC){pByte, (size_t)(pBufferEnd - pByte)};
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700431}
432
433
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000434/**
435 @brief Append the CBOR head, the major type and argument
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800436
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000437 @param me Encoder context.
438 @param uMajorType Major type to insert.
439 @param uArgument The argument (an integer value or a length).
440 @param uMinLen The minimum number of bytes for encoding the CBOR argument.
441
442 This formats the CBOR "head" and appends it to the output.
443 */
444static void AppendCBORHead(QCBOREncodeContext *me, uint8_t uMajorType, uint64_t uArgument, uint8_t uMinLen)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700445{
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000446 // A stack buffer large enough for a CBOR head
447 UsefulBuf_MAKE_STACK_UB (pBufferForEncodedHead, QCBOR_HEAD_BUFFER_SIZE);
448
449 UsefulBufC EncodedHead = QCBOREncode_EncodeHead(pBufferForEncodedHead,
450 uMajorType,
451 uMinLen,
452 uArgument);
453
454 /* No check for EncodedHead == NULLUsefulBufC is performed here to
455 * save object code. It is very clear that pBufferForEncodedHead
456 * is the correct size. If EncodedHead == NULLUsefulBufC then
457 * UsefulOutBuf_AppendUsefulBuf() will do nothing so there is
458 * no security hole introduced.
459 */
460
461 UsefulOutBuf_AppendUsefulBuf(&(me->OutBuf), EncodedHead);
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700462}
463
464
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000465/**
466 @brief Insert the CBOR head for a map, array or wrapped bstr
467
468 @param me QCBOR encoding context.
469 @param uMajorType One of CBOR_MAJOR_TYPE_XXXX.
470 @param uLen The length of the data item.
471
472 When an array, map or bstr was opened, nothing was done but note
473 the position. This function goes back to that position and inserts
474 the CBOR Head with the major type and length.
475 */
476static void InsertCBORHead(QCBOREncodeContext *me, uint8_t uMajorType, size_t uLen)
477{
478 if(me->uError == QCBOR_SUCCESS) {
479 if(!Nesting_IsInNest(&(me->nesting))) {
480 me->uError = QCBOR_ERR_TOO_MANY_CLOSES;
481 } else if(Nesting_GetMajorType(&(me->nesting)) != uMajorType) {
482 me->uError = QCBOR_ERR_CLOSE_MISMATCH;
483 } else {
484 // A stack buffer large enough for a CBOR head
485 UsefulBuf_MAKE_STACK_UB (pBufferForEncodedHead,QCBOR_HEAD_BUFFER_SIZE);
486
487 UsefulBufC EncodedHead = QCBOREncode_EncodeHead(pBufferForEncodedHead,
488 uMajorType,
489 0,
490 uLen);
491
492 /* No check for EncodedHead == NULLUsefulBufC is performed here to
493 * save object code. It is very clear that pBufferForEncodedHead
494 * is the correct size. If EncodedHead == NULLUsefulBufC then
495 * UsefulOutBuf_InsertUsefulBuf() will do nothing so there is
496 * no security whole introduced.
497 */
498 UsefulOutBuf_InsertUsefulBuf(&(me->OutBuf), EncodedHead, Nesting_GetStartPos(&(me->nesting)) );
499
500 Nesting_Decrease(&(me->nesting));
501 }
502 }
503}
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700504
Laurence Lundblade241705e2018-12-30 18:56:14 -0800505
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700506/*
Laurence Lundbladeee851742020-01-08 08:37:05 -0800507 Public functions for closing arrays and maps. See qcbor.h
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700508 */
Laurence Lundblade067035b2018-11-28 17:35:25 -0800509void QCBOREncode_AddUInt64(QCBOREncodeContext *me, uint64_t uValue)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700510{
Laurence Lundblade067035b2018-11-28 17:35:25 -0800511 if(me->uError == QCBOR_SUCCESS) {
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000512 AppendCBORHead(me, CBOR_MAJOR_TYPE_POSITIVE_INT, uValue, 0);
Laurence Lundblade1ef8b2d2018-12-14 23:13:34 -0800513 me->uError = Nesting_Increment(&(me->nesting));
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700514 }
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700515}
516
Laurence Lundblade56230d12018-11-01 11:14:51 +0700517
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700518/*
Laurence Lundbladeee851742020-01-08 08:37:05 -0800519 Public functions for closing arrays and maps. See qcbor.h
Laurence Lundblade067035b2018-11-28 17:35:25 -0800520 */
521void QCBOREncode_AddInt64(QCBOREncodeContext *me, int64_t nNum)
522{
523 if(me->uError == QCBOR_SUCCESS) {
524 uint8_t uMajorType;
525 uint64_t uValue;
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800526
Laurence Lundblade067035b2018-11-28 17:35:25 -0800527 if(nNum < 0) {
Laurence Lundblade2c40ab82018-12-30 14:20:29 -0800528 // In CBOR -1 encodes as 0x00 with major type negative int.
529 uValue = (uint64_t)(-nNum - 1);
Laurence Lundblade067035b2018-11-28 17:35:25 -0800530 uMajorType = CBOR_MAJOR_TYPE_NEGATIVE_INT;
531 } else {
532 uValue = (uint64_t)nNum;
533 uMajorType = CBOR_MAJOR_TYPE_POSITIVE_INT;
534 }
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000535 AppendCBORHead(me, uMajorType, uValue, 0);
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800536
Laurence Lundblade1ef8b2d2018-12-14 23:13:34 -0800537 me->uError = Nesting_Increment(&(me->nesting));
Laurence Lundblade067035b2018-11-28 17:35:25 -0800538 }
539}
540
541
542/*
Laurence Lundbladeda532272019-04-07 11:40:17 -0700543 Semi-private function. It is exposed to user of the interface, but
544 they will usually call one of the inline wrappers rather than this.
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800545
Laurence Lundbladeee851742020-01-08 08:37:05 -0800546 See qcbor.h
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800547
Laurence Lundbladeda532272019-04-07 11:40:17 -0700548 Does the work of adding actual strings bytes to the CBOR output (as
549 opposed to numbers and opening / closing aggregate types).
550
551 There are four use cases:
552 CBOR_MAJOR_TYPE_BYTE_STRING -- Byte strings
553 CBOR_MAJOR_TYPE_TEXT_STRING -- Text strings
554 CBOR_MAJOR_NONE_TYPE_RAW -- Already-encoded CBOR
555 CBOR_MAJOR_NONE_TYPE_BSTR_LEN_ONLY -- Special case
556
557 The first two add the type and length plus the actual bytes. The
558 third just adds the bytes as the type and length are presumed to be
559 in the bytes. The fourth just adds the type and length for the very
560 special case of QCBOREncode_AddBytesLenOnly().
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700561 */
Laurence Lundblade067035b2018-11-28 17:35:25 -0800562void QCBOREncode_AddBuffer(QCBOREncodeContext *me, uint8_t uMajorType, UsefulBufC Bytes)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700563{
Laurence Lundblade241705e2018-12-30 18:56:14 -0800564 if(me->uError == QCBOR_SUCCESS) {
Laurence Lundblade1ef8b2d2018-12-14 23:13:34 -0800565 // If it is not Raw CBOR, add the type and the length
566 if(uMajorType != CBOR_MAJOR_NONE_TYPE_RAW) {
Laurence Lundbladeda532272019-04-07 11:40:17 -0700567 uint8_t uRealMajorType = uMajorType;
568 if(uRealMajorType == CBOR_MAJOR_NONE_TYPE_BSTR_LEN_ONLY) {
569 uRealMajorType = CBOR_MAJOR_TYPE_BYTE_STRING;
570 }
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000571 AppendCBORHead(me, uRealMajorType, Bytes.len, 0);
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700572 }
Laurence Lundblade2c40ab82018-12-30 14:20:29 -0800573
Laurence Lundbladeda532272019-04-07 11:40:17 -0700574 if(uMajorType != CBOR_MAJOR_NONE_TYPE_BSTR_LEN_ONLY) {
575 // Actually add the bytes
576 UsefulOutBuf_AppendUsefulBuf(&(me->OutBuf), Bytes);
577 }
Laurence Lundblade2c40ab82018-12-30 14:20:29 -0800578
Laurence Lundblade1ef8b2d2018-12-14 23:13:34 -0800579 // Update the array counting if there is any nesting at all
580 me->uError = Nesting_Increment(&(me->nesting));
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700581 }
582}
583
Laurence Lundbladecafcfe12018-10-31 21:59:50 +0700584
Laurence Lundblade55a24832018-10-30 04:35:08 +0700585/*
Laurence Lundbladeee851742020-01-08 08:37:05 -0800586 Public functions for closing arrays and maps. See qcbor.h
Laurence Lundblade55a24832018-10-30 04:35:08 +0700587 */
588void QCBOREncode_AddTag(QCBOREncodeContext *me, uint64_t uTag)
589{
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000590 AppendCBORHead(me, CBOR_MAJOR_TYPE_OPTIONAL, uTag, 0);
Laurence Lundblade55a24832018-10-30 04:35:08 +0700591}
592
593
Laurence Lundblade56230d12018-11-01 11:14:51 +0700594/*
Laurence Lundblade487930f2018-11-30 11:01:45 -0800595 Semi-private function. It is exposed to user of the interface,
596 but they will usually call one of the inline wrappers rather than this.
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800597
Laurence Lundblade487930f2018-11-30 11:01:45 -0800598 See header qcbor.h
Laurence Lundblade56230d12018-11-01 11:14:51 +0700599 */
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000600void QCBOREncode_AddType7(QCBOREncodeContext *me, uint8_t uMinLen, uint64_t uNum)
Laurence Lundblade55a24832018-10-30 04:35:08 +0700601{
Laurence Lundblade487930f2018-11-30 11:01:45 -0800602 if(me->uError == QCBOR_SUCCESS) {
Laurence Lundbladebb1062e2019-08-12 23:28:54 -0700603 if(uNum >= CBOR_SIMPLEV_RESERVED_START && uNum <= CBOR_SIMPLEV_RESERVED_END) {
604 me->uError = QCBOR_ERR_UNSUPPORTED;
605 } else {
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000606 // AppendHead() does endian swapping for the float / double
607 AppendCBORHead(me, CBOR_MAJOR_TYPE_SIMPLE, uNum, uMinLen);
Laurence Lundbladebb1062e2019-08-12 23:28:54 -0700608 me->uError = Nesting_Increment(&(me->nesting));
609 }
Laurence Lundblade487930f2018-11-30 11:01:45 -0800610 }
Laurence Lundblade55a24832018-10-30 04:35:08 +0700611}
612
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700613
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700614/*
Laurence Lundbladeee851742020-01-08 08:37:05 -0800615 Public functions for closing arrays and maps. See qcbor.h
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700616 */
Laurence Lundblade067035b2018-11-28 17:35:25 -0800617void QCBOREncode_AddDouble(QCBOREncodeContext *me, double dNum)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700618{
Laurence Lundblade9682a532020-06-06 18:33:04 -0700619#ifndef QCBOR_CONFIG_DISABLE_ENCODE_IEEE754
Laurence Lundblade067035b2018-11-28 17:35:25 -0800620 const IEEE754_union uNum = IEEE754_DoubleToSmallest(dNum);
Laurence Lundblade9682a532020-06-06 18:33:04 -0700621
Laurence Lundblade487930f2018-11-30 11:01:45 -0800622 QCBOREncode_AddType7(me, uNum.uSize, uNum.uValue);
Laurence Lundblade9682a532020-06-06 18:33:04 -0700623#else
624 QCBOREncode_AddType7(me, sizeof(uint64_t), UsefulBufUtil_CopyDoubleToUint64(dNum));
625#endif
626
627}
628
629
630/*
631 Public functions for closing arrays and maps. See qcbor.h
632 */
633void QCBOREncode_AddFloat(QCBOREncodeContext *me, float fNum)
634{
635#ifndef QCBOR_CONFIG_DISABLE_ENCODE_IEEE754
636 const IEEE754_union uNum = IEEE754_FloatToSmallest(fNum);
637
638 QCBOREncode_AddType7(me, uNum.uSize, uNum.uValue);
639#else
640 QCBOREncode_AddType7(me, sizeof(uint32_t), UsefulBufUtil_CopyFloatToUint32(fNum));
641#endif
Laurence Lundblade067035b2018-11-28 17:35:25 -0800642}
643
644
Laurence Lundblade59289e52019-12-30 13:44:37 -0800645#ifndef QCBOR_CONFIG_DISABLE_EXP_AND_MANTISSA
646/*
647 Semi-public function. It is exposed to the user of the interface, but
648 one of the inline wrappers will usually be called rather than this.
649
650 See qcbor.h
651 */
652void QCBOREncode_AddExponentAndMantissa(QCBOREncodeContext *pMe,
653 uint64_t uTag,
654 UsefulBufC BigNumMantissa,
655 bool bBigNumIsNegative,
656 int64_t nMantissa,
657 int64_t nExponent)
658{
Laurence Lundbladeee851742020-01-08 08:37:05 -0800659 /*
660 This is for encoding either a big float or a decimal fraction,
661 both of which are an array of two items, an exponent and a
662 mantissa. The difference between the two is that the exponent is
663 base-2 for big floats and base-10 for decimal fractions, but that
664 has no effect on the code here.
665 */
Laurence Lundblade59289e52019-12-30 13:44:37 -0800666 QCBOREncode_AddTag(pMe, uTag);
667 QCBOREncode_OpenArray(pMe);
668 QCBOREncode_AddInt64(pMe, nExponent);
669 if(!UsefulBuf_IsNULLC(BigNumMantissa)) {
670 if(bBigNumIsNegative) {
671 QCBOREncode_AddNegativeBignum(pMe, BigNumMantissa);
672 } else {
673 QCBOREncode_AddPositiveBignum(pMe, BigNumMantissa);
674 }
675 } else {
676 QCBOREncode_AddInt64(pMe, nMantissa);
677 }
678 QCBOREncode_CloseArray(pMe);
679}
680#endif /* QCBOR_CONFIG_DISABLE_EXP_AND_MANTISSA */
681
682
Laurence Lundblade067035b2018-11-28 17:35:25 -0800683/*
684 Semi-public function. It is exposed to user of the interface,
685 but they will usually call one of the inline wrappers rather than this.
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800686
Laurence Lundblade067035b2018-11-28 17:35:25 -0800687 See header qcbor.h
688*/
689void QCBOREncode_OpenMapOrArray(QCBOREncodeContext *me, uint8_t uMajorType)
690{
Laurence Lundblade1ef8b2d2018-12-14 23:13:34 -0800691 // Add one item to the nesting level we are in for the new map or array
692 me->uError = Nesting_Increment(&(me->nesting));
Laurence Lundblade241705e2018-12-30 18:56:14 -0800693 if(me->uError == QCBOR_SUCCESS) {
Laurence Lundbladeee851742020-01-08 08:37:05 -0800694 /*
695 The offset where the length of an array or map will get written
696 is stored in a uint32_t, not a size_t to keep stack usage
697 smaller. This checks to be sure there is no wrap around when
698 recording the offset. Note that on 64-bit machines CBOR larger
699 than 4GB can be encoded as long as no array / map offsets occur
700 past the 4GB mark, but the public interface says that the
701 maximum is 4GB to keep the discussion simpler.
702 */
Laurence Lundblade1ef8b2d2018-12-14 23:13:34 -0800703 size_t uEndPosition = UsefulOutBuf_GetEndPosition(&(me->OutBuf));
Laurence Lundbladed39cd392019-01-11 18:17:38 -0800704
Laurence Lundbladeee851742020-01-08 08:37:05 -0800705 /*
706 QCBOR_MAX_ARRAY_OFFSET is slightly less than UINT32_MAX so this
707 code can run on a 32-bit machine and tests can pass on a 32-bit
708 machine. If it was exactly UINT32_MAX, then this code would not
709 compile or run on a 32-bit machine and an #ifdef or some
710 machine size detection would be needed reducing portability.
711 */
Laurence Lundbladed39cd392019-01-11 18:17:38 -0800712 if(uEndPosition >= QCBOR_MAX_ARRAY_OFFSET) {
Laurence Lundblade1ef8b2d2018-12-14 23:13:34 -0800713 me->uError = QCBOR_ERR_BUFFER_TOO_LARGE;
Laurence Lundbladed39cd392019-01-11 18:17:38 -0800714
Laurence Lundblade1ef8b2d2018-12-14 23:13:34 -0800715 } else {
Laurence Lundbladeee851742020-01-08 08:37:05 -0800716 // Increase nesting level because this is a map or array. Cast
717 // from size_t to uin32_t is safe because of check above
Laurence Lundblade1ef8b2d2018-12-14 23:13:34 -0800718 me->uError = Nesting_Increase(&(me->nesting), uMajorType, (uint32_t)uEndPosition);
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700719 }
Laurence Lundblade1ef8b2d2018-12-14 23:13:34 -0800720 }
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700721}
722
Laurence Lundblade59289e52019-12-30 13:44:37 -0800723
Jan Jongboom4a93a662019-07-25 08:44:58 +0200724/*
725 Semi-public function. It is exposed to user of the interface,
726 but they will usually call one of the inline wrappers rather than this.
727
Laurence Lundbladeee851742020-01-08 08:37:05 -0800728 See qcbor.h
Jan Jongboom4a93a662019-07-25 08:44:58 +0200729*/
730void QCBOREncode_OpenMapOrArrayIndefiniteLength(QCBOREncodeContext *me, uint8_t uMajorType)
731{
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000732 // Insert the indefinite length marker (0x9f for arrays, 0xbf for maps)
733 AppendCBORHead(me, uMajorType, 0, 0);
734 // Call the definite-length opener just to do the bookkeeping for
735 // nesting. It will record the position of the opening item in
736 // the encoded output but this is not used when closing this open.
Jan Jongboom4a93a662019-07-25 08:44:58 +0200737 QCBOREncode_OpenMapOrArray(me, uMajorType);
738}
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700739
Laurence Lundbladeee851742020-01-08 08:37:05 -0800740
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700741/*
Laurence Lundbladeee851742020-01-08 08:37:05 -0800742 Public functions for closing arrays and maps. See qcbor.h
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700743 */
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000744void QCBOREncode_CloseMapOrArray(QCBOREncodeContext *me, uint8_t uMajorType)
Laurence Lundbladea954db92018-09-28 19:27:31 -0700745{
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000746 InsertCBORHead(me, uMajorType, Nesting_GetCount(&(me->nesting)));
747}
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800748
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800749
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000750/*
751 Public functions for closing bstr wrapping. See qcbor.h
752 */
753void QCBOREncode_CloseBstrWrap2(QCBOREncodeContext *me, bool bIncludeCBORHead, UsefulBufC *pWrappedCBOR)
754{
755 const size_t uInsertPosition = Nesting_GetStartPos(&(me->nesting));
756 const size_t uEndPosition = UsefulOutBuf_GetEndPosition(&(me->OutBuf));
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800757
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000758 // This can't go negative because the UsefulOutBuf always only grows
759 // and never shrinks. UsefulOutBut itself also has defenses such that
760 // it won't write where it should not even if given hostile input lengths.
761 const size_t uBstrLen = uEndPosition - uInsertPosition;
762
763 // Actually insert
764 InsertCBORHead(me, CBOR_MAJOR_TYPE_BYTE_STRING, uBstrLen);
765
766 if(pWrappedCBOR) {
767 /*
768 Return pointer and length to the enclosed encoded CBOR. The
769 intended use is for it to be hashed (e.g., SHA-256) in a COSE
770 implementation. This must be used right away, as the pointer
771 and length go invalid on any subsequent calls to this function
772 because there might be calls to InsertEncodedTypeAndNumber()
773 that slides data to the right.
774 */
775 size_t uStartOfNew = uInsertPosition;
776 if(!bIncludeCBORHead) {
777 // Skip over the CBOR head to just get the inserted bstr
778 const size_t uNewEndPosition = UsefulOutBuf_GetEndPosition(&(me->OutBuf));
779 uStartOfNew += uNewEndPosition - uEndPosition;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700780 }
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000781 const UsefulBufC PartialResult = UsefulOutBuf_OutUBuf(&(me->OutBuf));
782 *pWrappedCBOR = UsefulBuf_Tail(PartialResult, uStartOfNew);
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700783 }
784}
785
Laurence Lundbladeee851742020-01-08 08:37:05 -0800786
Jan Jongboom4a93a662019-07-25 08:44:58 +0200787/*
Laurence Lundbladeee851742020-01-08 08:37:05 -0800788 Public functions for closing arrays and maps. See qcbor.h
Jan Jongboom4a93a662019-07-25 08:44:58 +0200789 */
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000790void QCBOREncode_CloseMapOrArrayIndefiniteLength(QCBOREncodeContext *me, uint8_t uMajorType)
Jan Jongboom4a93a662019-07-25 08:44:58 +0200791{
792 if(me->uError == QCBOR_SUCCESS) {
793 if(!Nesting_IsInNest(&(me->nesting))) {
794 me->uError = QCBOR_ERR_TOO_MANY_CLOSES;
795 } else if(Nesting_GetMajorType(&(me->nesting)) != uMajorType) {
796 me->uError = QCBOR_ERR_CLOSE_MISMATCH;
797 } else {
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000798 // Append the break marker (0xff for both arrays and maps)
799 AppendCBORHead(me, CBOR_MAJOR_TYPE_SIMPLE, CBOR_SIMPLE_BREAK, 0);
Jan Jongboom4a93a662019-07-25 08:44:58 +0200800
Jan Jongboom4a93a662019-07-25 08:44:58 +0200801 Nesting_Decrease(&(me->nesting));
802 }
803 }
804}
805
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700806
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700807/*
Laurence Lundbladeee851742020-01-08 08:37:05 -0800808 Public functions to finish and get the encoded result. See qcbor.h
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700809 */
Laurence Lundblade30816f22018-11-10 13:40:22 +0700810QCBORError QCBOREncode_Finish(QCBOREncodeContext *me, UsefulBufC *pEncodedCBOR)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700811{
Laurence Lundbladef607a2a2019-07-05 21:25:25 -0700812 QCBORError uReturn = QCBOREncode_GetErrorState(me);
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800813
Laurence Lundblade067035b2018-11-28 17:35:25 -0800814 if(uReturn != QCBOR_SUCCESS) {
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700815 goto Done;
Laurence Lundblade067035b2018-11-28 17:35:25 -0800816 }
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800817
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700818 if (Nesting_IsInNest(&(me->nesting))) {
Laurence Lundblade067035b2018-11-28 17:35:25 -0800819 uReturn = QCBOR_ERR_ARRAY_OR_MAP_STILL_OPEN;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700820 goto Done;
821 }
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800822
Laurence Lundbladeda3f0822018-09-18 19:49:02 -0700823 *pEncodedCBOR = UsefulOutBuf_OutUBuf(&(me->OutBuf));
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800824
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700825Done:
Laurence Lundblade067035b2018-11-28 17:35:25 -0800826 return uReturn;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700827}
828
Laurence Lundblade0595e932018-11-02 22:22:47 +0700829
Laurence Lundblade067035b2018-11-28 17:35:25 -0800830/*
Laurence Lundbladeee851742020-01-08 08:37:05 -0800831 Public functions to finish and get the encoded result. See qcbor.h
Laurence Lundblade067035b2018-11-28 17:35:25 -0800832 */
Laurence Lundblade30816f22018-11-10 13:40:22 +0700833QCBORError QCBOREncode_FinishGetSize(QCBOREncodeContext *me, size_t *puEncodedLen)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700834{
Laurence Lundbladeda3f0822018-09-18 19:49:02 -0700835 UsefulBufC Enc;
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800836
Laurence Lundblade30816f22018-11-10 13:40:22 +0700837 QCBORError nReturn = QCBOREncode_Finish(me, &Enc);
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800838
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700839 if(nReturn == QCBOR_SUCCESS) {
Laurence Lundbladeda3f0822018-09-18 19:49:02 -0700840 *puEncodedLen = Enc.len;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700841 }
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800842
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700843 return nReturn;
844}
845
846
Laurence Lundblade067035b2018-11-28 17:35:25 -0800847
848
849/*
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000850Object code sizes on 64-bit x86 with GCC -Os Jan 2020. GCC compiles smaller
851than LLVM and optimizations have been made to decrease code size. Bigfloat,
852Decimal fractions and indefinite length encoding were added to increase code
853size. Bstr wrapping is now separate which means if you don't use it, it gets
854dead stripped.
855
856_QCBOREncode_EncodeHead 187
857_QCBOREncode_CloseBstrWrap2: 154
858_QCBOREncode_AddExponentAndMantissa: 144
859_QCBOREncode_AddBuffer 105
860_QCBOREncode_OpenMapOrArray 101
861_QCBOREncode_CloseMapOrArrayIndefiniteLength: 72
862_QCBOREncode_Finish 71
863_InsertCBORHead.part.0 66
864_QCBOREncode_CloseMapOrArray 64
865_QCBOREncode_AddType7 58
866_QCBOREncode_AddInt64 57
867_AppendCBORHead 54
868_QCBOREncode_AddUInt64 40
869_QCBOREncode_Init 38
870_Nesting_Increment.isra.0 36
871_QCBOREncode_FinishGetSize: 34
872_QCBOREncode_AddDouble: 26
873_QCBOREncode_AddTag: 15
874Total 1322
875Min_encode use case 776
876
877
Laurence Lundblade241705e2018-12-30 18:56:14 -0800878 Object code sizes on X86 with LLVM compiler and -Os (Dec 30, 2018)
Laurence Lundblade2c40ab82018-12-30 14:20:29 -0800879
Laurence Lundblade9c097392018-12-30 13:52:24 -0800880 _QCBOREncode_Init 69
Laurence Lundblade067035b2018-11-28 17:35:25 -0800881 _QCBOREncode_AddUInt64 76
882 _QCBOREncode_AddInt64 87
Laurence Lundblade1ef8b2d2018-12-14 23:13:34 -0800883 _QCBOREncode_AddBuffer 113
Laurence Lundbladef970f1d2018-12-14 01:44:23 -0800884 _QCBOREncode_AddTag 27
Laurence Lundblade9c097392018-12-30 13:52:24 -0800885 _QCBOREncode_AddType7 87
Laurence Lundbladef970f1d2018-12-14 01:44:23 -0800886 _QCBOREncode_AddDouble 36
Laurence Lundblade1ef8b2d2018-12-14 23:13:34 -0800887 _QCBOREncode_OpenMapOrArray 103
Laurence Lundblade067035b2018-11-28 17:35:25 -0800888 _QCBOREncode_CloseMapOrArray 181
Laurence Lundbladef970f1d2018-12-14 01:44:23 -0800889 _InsertEncodedTypeAndNumber 190
Laurence Lundblade067035b2018-11-28 17:35:25 -0800890 _QCBOREncode_Finish 72
Laurence Lundbladef970f1d2018-12-14 01:44:23 -0800891 _QCBOREncode_FinishGetSize 70
Laurence Lundblade2c40ab82018-12-30 14:20:29 -0800892
Laurence Lundbladef970f1d2018-12-14 01:44:23 -0800893 Total is about 1.1KB
Laurence Lundblade2c40ab82018-12-30 14:20:29 -0800894
Laurence Lundblade067035b2018-11-28 17:35:25 -0800895 _QCBOREncode_CloseMapOrArray is larger because it has a lot
896 of nesting tracking to do and much of Nesting_ inlines
897 into it. It probably can't be reduced much.
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800898
Laurence Lundblade067035b2018-11-28 17:35:25 -0800899 If the error returned by Nesting_Increment() can be ignored
900 because the limit is so high and the consequence of exceeding
901 is proved to be inconsequential, then a lot of if(me->uError)
902 instance can be removed, saving some code.
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800903
Laurence Lundblade067035b2018-11-28 17:35:25 -0800904 */