/work/include/cbor/common.h
Line | Count | Source |
1 | | /* |
2 | | * SPDX-FileCopyrightText: 2014-2026 Pavel Kalvoda <me@pavelkalvoda.com> |
3 | | * SPDX-License-Identifier: MIT |
4 | | */ |
5 | | |
6 | | #ifndef LIBCBOR_COMMON_H |
7 | | #define LIBCBOR_COMMON_H |
8 | | |
9 | | #include <assert.h> |
10 | | #include <stdbool.h> |
11 | | #include <stddef.h> |
12 | | #include <stdint.h> |
13 | | #include <stdlib.h> |
14 | | #include <string.h> |
15 | | |
16 | | #include "cbor/cbor_export.h" |
17 | | #include "cbor/configuration.h" |
18 | | #include "data.h" |
19 | | |
20 | | #ifdef __cplusplus |
21 | | extern "C" { |
22 | | |
23 | | /** |
24 | | * C99 is not a subset of C++ -- 'restrict' qualifier is not a part of the |
25 | | * language. This is a workaround to keep it in C headers -- compilers allow |
26 | | * linking non-restrict signatures with restrict implementations. |
27 | | * |
28 | | * If you know a nicer way, please do let me know. |
29 | | */ |
30 | | #define CBOR_RESTRICT_POINTER |
31 | | |
32 | | #else |
33 | | |
34 | | // MSVC + C++ workaround |
35 | | #define CBOR_RESTRICT_POINTER CBOR_RESTRICT_SPECIFIER |
36 | | |
37 | | #endif |
38 | | |
39 | | static const uint8_t cbor_major_version = CBOR_MAJOR_VERSION; |
40 | | static const uint8_t cbor_minor_version = CBOR_MINOR_VERSION; |
41 | | static const uint8_t cbor_patch_version = CBOR_PATCH_VERSION; |
42 | | |
43 | | #define CBOR_VERSION \ |
44 | | _CBOR_TO_STR(CBOR_MAJOR_VERSION) \ |
45 | | "." _CBOR_TO_STR(CBOR_MINOR_VERSION) "." _CBOR_TO_STR(CBOR_PATCH_VERSION) |
46 | | #define CBOR_HEX_VERSION \ |
47 | | ((CBOR_MAJOR_VERSION << 16) | (CBOR_MINOR_VERSION << 8) | CBOR_PATCH_VERSION) |
48 | | |
49 | | /* http://stackoverflow.com/questions/1644868/c-define-macro-for-debug-printing |
50 | | */ |
51 | | #ifdef DEBUG |
52 | | #include <stdio.h> |
53 | | #define _cbor_debug_print(fmt, ...) \ |
54 | | do { \ |
55 | | if (DEBUG) \ |
56 | | fprintf(stderr, "%s:%d:%s(): " fmt, __FILE__, __LINE__, __func__, \ |
57 | | __VA_ARGS__); \ |
58 | | } while (0) |
59 | | extern bool _cbor_enable_assert; |
60 | | // Like `assert`, but can be dynamically disabled in tests to allow testing |
61 | | // invalid behaviors. |
62 | | #define CBOR_ASSERT(e) assert(!_cbor_enable_assert || (e)) |
63 | | #define _CBOR_TEST_DISABLE_ASSERT(block) \ |
64 | | do { \ |
65 | | _cbor_enable_assert = false; \ |
66 | | block _cbor_enable_assert = true; \ |
67 | | } while (0) |
68 | | #else |
69 | | #define debug_print(fmt, ...) \ |
70 | | do { \ |
71 | | } while (0) |
72 | | #define CBOR_ASSERT(e) |
73 | | #define _CBOR_TEST_DISABLE_ASSERT(block) \ |
74 | | do { \ |
75 | | block \ |
76 | | } while (0) |
77 | | #endif |
78 | | |
79 | | #define CBOR_ASSERT_VALID_TYPE(item_type) \ |
80 | | CBOR_ASSERT(item_type >= CBOR_TYPE_UINT && item_type <= CBOR_TYPE_FLOAT_CTRL); |
81 | | |
82 | | #define _CBOR_TO_STR_(x) #x |
83 | | #define _CBOR_TO_STR(x) _CBOR_TO_STR_(x) /* enables proper double expansion */ |
84 | | |
85 | | #ifdef CBOR_HAS_NODISCARD_ATTRIBUTE |
86 | | #define CBOR_NODISCARD [[nodiscard]] |
87 | | #else |
88 | | #define CBOR_NODISCARD |
89 | | #endif |
90 | | |
91 | | #ifdef __GNUC__ |
92 | | #define _CBOR_UNUSED __attribute__((__unused__)) |
93 | | // Fall back to __attribute__((warn_unused_result)) if we don't have |
94 | | // [[nodiscard]] |
95 | | #ifdef CBOR_HAS_NODISCARD_ATTRIBUTE |
96 | | #define _CBOR_NODISCARD CBOR_NODISCARD |
97 | | #else |
98 | | #define _CBOR_NODISCARD __attribute__((warn_unused_result)) |
99 | | #endif |
100 | | #elif defined(_MSC_VER) |
101 | | #define _CBOR_UNUSED __pragma(warning(suppress : 4100 4101)) |
102 | | #define _CBOR_NODISCARD |
103 | | #else |
104 | | #define _CBOR_UNUSED |
105 | | #define _CBOR_NODISCARD |
106 | | #endif |
107 | | |
108 | | #ifdef CBOR_HAS_BUILTIN_UNREACHABLE |
109 | | #define _CBOR_UNREACHABLE __builtin_unreachable() |
110 | | #else |
111 | | #define _CBOR_UNREACHABLE |
112 | | #endif |
113 | | |
114 | | // Keeps a rarely called function out of its callers' hot path |
115 | | #ifdef __GNUC__ |
116 | | #define _CBOR_COLD __attribute__((__noinline__, __cold__)) |
117 | | #else |
118 | | #define _CBOR_COLD |
119 | | #endif |
120 | | |
121 | | typedef void* (*_cbor_malloc_t)(size_t); |
122 | | typedef void* (*_cbor_realloc_t)(void*, size_t); |
123 | | typedef void (*_cbor_free_t)(void*); |
124 | | |
125 | | CBOR_EXPORT extern _cbor_malloc_t _cbor_malloc; |
126 | | CBOR_EXPORT extern _cbor_realloc_t _cbor_realloc; |
127 | | CBOR_EXPORT extern _cbor_free_t _cbor_free; |
128 | | |
129 | | // Macro to short-circuit builder functions when memory allocation fails |
130 | | #define _CBOR_NOTNULL(cbor_item) \ |
131 | | do { \ |
132 | | if (cbor_item == NULL) { \ |
133 | | return NULL; \ |
134 | | } \ |
135 | | } while (0) |
136 | | |
137 | | // Macro to short-circuit builders when memory allocation of nested data |
138 | | // fails |
139 | | #define _CBOR_DEPENDENT_NOTNULL(cbor_item, pointer) \ |
140 | | do { \ |
141 | | if (pointer == NULL) { \ |
142 | | _cbor_free(cbor_item); \ |
143 | | return NULL; \ |
144 | | } \ |
145 | | } while (0) |
146 | | |
147 | | /** Sets the memory management routines to use. |
148 | | * |
149 | | * By default, libcbor will use the standard library `malloc`, `realloc`, |
150 | | * and `free`. |
151 | | * |
152 | | * A custom allocator is the mechanism for putting an absolute limit on the |
153 | | * memory consumed when parsing untrusted CBOR data. Without one, `cbor_load` |
154 | | * uses memory proportional to the size of its input. A capping |
155 | | * `custom_malloc` that returns NULL above a chosen threshold will cause |
156 | | * `cbor_load` to return `CBOR_ERR_MEMERROR` once the threshold is reached. |
157 | | * See `examples/capped_alloc.c` for a self-contained demonstration. |
158 | | * |
159 | | * \rst |
160 | | * .. warning:: |
161 | | * This function modifies the global state and should |
162 | | * therefore be used accordingly. Changing the memory handlers while |
163 | | * allocated items exist will result in a ``free``/``malloc`` mismatch. |
164 | | * This function is not thread safe with respect to both itself and all |
165 | | * the other *libcbor* functions that work with the heap. |
166 | | * |
167 | | * .. note:: |
168 | | * `realloc` implementation must correctly support `NULL` |
169 | | * reallocation (see e.g. http://en.cppreference.com/w/c/memory/realloc) |
170 | | * |
171 | | * .. note:: |
172 | | * `free` implementation must accept `NULL` as a no-op (as the standard |
173 | | * `free` does). libcbor does not allocate storage for empty items and |
174 | | * will pass their `NULL` data pointer to `free` when they are deallocated. |
175 | | * |
176 | | * \endrst |
177 | | * |
178 | | * @param custom_malloc malloc implementation |
179 | | * @param custom_realloc realloc implementation |
180 | | * @param custom_free free implementation |
181 | | */ |
182 | | CBOR_EXPORT void cbor_set_allocs(_cbor_malloc_t custom_malloc, |
183 | | _cbor_realloc_t custom_realloc, |
184 | | _cbor_free_t custom_free); |
185 | | |
186 | | /* |
187 | | * ============================================================================ |
188 | | * Type manipulation |
189 | | * ============================================================================ |
190 | | */ |
191 | | |
192 | | /** Get the type of the item |
193 | | * |
194 | | * @param item |
195 | | * @return The type |
196 | | */ |
197 | | _CBOR_NODISCARD |
198 | | CBOR_EXPORT cbor_type cbor_typeof( |
199 | | const cbor_item_t* item); /* Will be inlined iff link-time opt is enabled */ |
200 | | |
201 | | /* Standard CBOR Major item types */ |
202 | | |
203 | | /** Does the item have the appropriate major type? |
204 | | * @param item the item |
205 | | * @return Is the item an #CBOR_TYPE_UINT? |
206 | | */ |
207 | | _CBOR_NODISCARD |
208 | | CBOR_EXPORT bool cbor_isa_uint(const cbor_item_t* item); |
209 | | |
210 | | /** Does the item have the appropriate major type? |
211 | | * @param item the item |
212 | | * @return Is the item a #CBOR_TYPE_NEGINT? |
213 | | */ |
214 | | _CBOR_NODISCARD |
215 | | CBOR_EXPORT bool cbor_isa_negint(const cbor_item_t* item); |
216 | | |
217 | | /** Does the item have the appropriate major type? |
218 | | * @param item the item |
219 | | * @return Is the item a #CBOR_TYPE_BYTESTRING? |
220 | | */ |
221 | | _CBOR_NODISCARD |
222 | | CBOR_EXPORT bool cbor_isa_bytestring(const cbor_item_t* item); |
223 | | |
224 | | /** Does the item have the appropriate major type? |
225 | | * @param item the item |
226 | | * @return Is the item a #CBOR_TYPE_STRING? |
227 | | */ |
228 | | _CBOR_NODISCARD |
229 | | CBOR_EXPORT bool cbor_isa_string(const cbor_item_t* item); |
230 | | |
231 | | /** Does the item have the appropriate major type? |
232 | | * @param item the item |
233 | | * @return Is the item an #CBOR_TYPE_ARRAY? |
234 | | */ |
235 | | _CBOR_NODISCARD |
236 | | CBOR_EXPORT bool cbor_isa_array(const cbor_item_t* item); |
237 | | |
238 | | /** Does the item have the appropriate major type? |
239 | | * @param item the item |
240 | | * @return Is the item a #CBOR_TYPE_MAP? |
241 | | */ |
242 | | _CBOR_NODISCARD |
243 | | CBOR_EXPORT bool cbor_isa_map(const cbor_item_t* item); |
244 | | |
245 | | /** Does the item have the appropriate major type? |
246 | | * @param item the item |
247 | | * @return Is the item a #CBOR_TYPE_TAG? |
248 | | */ |
249 | | _CBOR_NODISCARD |
250 | | CBOR_EXPORT bool cbor_isa_tag(const cbor_item_t* item); |
251 | | |
252 | | /** Does the item have the appropriate major type? |
253 | | * @param item the item |
254 | | * @return Is the item a #CBOR_TYPE_FLOAT_CTRL? |
255 | | */ |
256 | | _CBOR_NODISCARD |
257 | | CBOR_EXPORT bool cbor_isa_float_ctrl(const cbor_item_t* item); |
258 | | |
259 | | /* Practical types with respect to their semantics (but not tag values) */ |
260 | | |
261 | | /** Is the item an integer, either positive or negative? |
262 | | * @param item the item |
263 | | * @return Is the item an integer, either positive or negative? |
264 | | */ |
265 | | _CBOR_NODISCARD |
266 | | CBOR_EXPORT bool cbor_is_int(const cbor_item_t* item); |
267 | | |
268 | | /** Is the item an a floating point number? |
269 | | * @param item the item |
270 | | * @return Is the item a floating point number? |
271 | | */ |
272 | | _CBOR_NODISCARD |
273 | | CBOR_EXPORT bool cbor_is_float(const cbor_item_t* item); |
274 | | |
275 | | /** Is the item an a boolean? |
276 | | * @param item the item |
277 | | * @return Is the item a boolean? |
278 | | */ |
279 | | _CBOR_NODISCARD |
280 | | CBOR_EXPORT bool cbor_is_bool(const cbor_item_t* item); |
281 | | |
282 | | /** Does this item represent `null` |
283 | | * |
284 | | * \rst |
285 | | * .. warning:: |
286 | | * This is in no way related to the value of the pointer. |
287 | | * Passing a null pointer will most likely result in a crash. |
288 | | * \endrst |
289 | | * |
290 | | * @param item the item |
291 | | * @return Is the item (CBOR logical) null? |
292 | | */ |
293 | | _CBOR_NODISCARD |
294 | | CBOR_EXPORT bool cbor_is_null(const cbor_item_t* item); |
295 | | |
296 | | /** Does this item represent `undefined` |
297 | | * |
298 | | * \rst |
299 | | * .. warning:: |
300 | | * Care must be taken to distinguish nulls and undefined values in C. |
301 | | * \endrst |
302 | | * |
303 | | * @param item the item |
304 | | * @return Is the item (CBOR logical) undefined? |
305 | | */ |
306 | | _CBOR_NODISCARD |
307 | | CBOR_EXPORT bool cbor_is_undef(const cbor_item_t* item); |
308 | | |
309 | | /* |
310 | | * ============================================================================ |
311 | | * Memory management |
312 | | * ============================================================================ |
313 | | */ |
314 | | |
315 | | /** Increases the item's reference count by one |
316 | | * |
317 | | * Constant complexity; items referring to this one or items being |
318 | | * referred to are not updated. |
319 | | * |
320 | | * This function can be used to extend reference counting to client code. |
321 | | * Every reference acquired with `cbor_incref` must be released with |
322 | | * `cbor_decref` (or #cbor_intermediate_decref). |
323 | | * |
324 | | * Defined `static inline` so the single-instruction increment is emitted |
325 | | * directly at the call site — meaningful for hot loops that build |
326 | | * `cbor_item_t` trees, where every constructed item touches the refcount. |
327 | | * |
328 | | * @param item Reference to an item |
329 | | * @return The input \p item |
330 | | */ |
331 | 0 | static inline cbor_item_t* cbor_incref(cbor_item_t* item) { |
332 | 0 | item->refcount++; |
333 | 0 | return item; |
334 | 0 | } |
335 | | |
336 | | /** Slow path of `cbor_decref`: performs the actual deallocation once the |
337 | | * reference count reaches zero. Do not call directly; use `cbor_decref`. |
338 | | * |
339 | | * Split from `cbor_decref` so the fast path (decrement + zero check) can |
340 | | * inline while the iterative tree-deallocation logic — which dominates code |
341 | | * size — stays out of line. |
342 | | */ |
343 | | CBOR_EXPORT void _cbor_decref_free(cbor_item_t* item); |
344 | | |
345 | | /** Decreases the item's reference count by one, deallocating the item if |
346 | | * needed |
347 | | * |
348 | | * In case the item is deallocated, the reference count of any child items |
349 | | * it references is transitively decremented as well, iteratively in constant |
350 | | * stack space and with no additional allocations. |
351 | | * |
352 | | * `*item_ref` is set to `NULL` *only* when the reference count reaches zero |
353 | | * and the item is deallocated. If other references still keep the item alive |
354 | | * (`refcount > 0`), `*item_ref` is left unchanged and must not be accessed |
355 | | * once those remaining references are released. |
356 | | * |
357 | | * The fast path (decrement, check for zero) is `static inline`; only the |
358 | | * uncommon deallocation branch calls into `_cbor_decref_free`. This keeps |
359 | | * every non-final decref a couple of instructions at the call site. |
360 | | * |
361 | | * \rst |
362 | | * See :ref:`refcount-pitfalls` for an example. |
363 | | * \endrst |
364 | | * |
365 | | * @param[in,out] item_ref Pointer to an item reference. `*item_ref` is set to |
366 | | * `NULL` if deallocated, and left unchanged otherwise. |
367 | | */ |
368 | 2.72k | static inline void cbor_decref(cbor_item_t** item_ref) { |
369 | 2.72k | cbor_item_t* item = *item_ref; |
370 | 2.72k | CBOR_ASSERT(item->refcount > 0); |
371 | 2.72k | if (--item->refcount == 0) { |
372 | 2.72k | _cbor_decref_free(item); |
373 | | *item_ref = NULL; |
374 | 2.72k | } |
375 | 2.72k | } |
376 | | |
377 | | /** Decreases the item's reference count by one, deallocating the item if |
378 | | * needed |
379 | | * |
380 | | * Convenience wrapper for `cbor_decref` when its set-to-null behavior is |
381 | | * not needed, for example when releasing a function parameter or a pointer |
382 | | * that is about to go out of scope. Unlike #cbor_move, this function *does* |
383 | | * deallocate \p item when its reference count reaches zero. |
384 | | * |
385 | | * @param item Reference to an item |
386 | | */ |
387 | | CBOR_EXPORT void cbor_intermediate_decref(cbor_item_t* item); |
388 | | |
389 | | /** Get the item's reference count |
390 | | * |
391 | | * Returns the number of direct references to `item`: initialized to `1` on |
392 | | * creation, incremented by `cbor_incref`, container mutators, and item |
393 | | * getters, and decremented by `cbor_decref`, #cbor_intermediate_decref, |
394 | | * #cbor_move, and when an owning container or tag is deallocated or |
395 | | * replaces `item` in a slot. |
396 | | * |
397 | | * \rst |
398 | | * .. warning:: |
399 | | * This does *not* account for transitive references held on ancestor |
400 | | * containers. |
401 | | * \endrst |
402 | | * |
403 | | * @param item the item |
404 | | * @return the reference count |
405 | | */ |
406 | | _CBOR_NODISCARD |
407 | | CBOR_EXPORT size_t cbor_refcount(const cbor_item_t* item); |
408 | | |
409 | | /** Provides CPP-like move construct |
410 | | * |
411 | | * Decreases the reference count by one, but does not deallocate the item |
412 | | * even if its refcount reaches zero. This is useful for passing |
413 | | * intermediate values to functions that increase reference count without |
414 | | * holding a temporary variable. Should only be used with functions that |
415 | | * `incref` their arguments. |
416 | | * |
417 | | * \rst |
418 | | * Typical receivers are :func:`cbor_array_push`, :func:`cbor_map_add`, and |
419 | | * :func:`cbor_build_tag`: |
420 | | * |
421 | | * .. code-block:: c |
422 | | * |
423 | | * cbor_item_t *array = cbor_new_definite_array(1); |
424 | | * cbor_array_push(array, cbor_move(cbor_build_uint8(42))); |
425 | | * cbor_decref(&array); |
426 | | * |
427 | | * .. warning:: |
428 | | * If the item is moved without increasing its reference count afterwards, |
429 | | * the memory will be leaked. This happens when the receiving call fails, |
430 | | * so code that must recover from allocation failures should not use this |
431 | | * pattern; see :ref:`refcount-pitfalls`. |
432 | | * \endrst |
433 | | * |
434 | | * @param item Reference to an item, or `NULL`. |
435 | | * @return the item with reference count decreased by one, or `NULL` if |
436 | | * \p item is `NULL` |
437 | | */ |
438 | | _CBOR_NODISCARD |
439 | | CBOR_EXPORT cbor_item_t* cbor_move(cbor_item_t* item); |
440 | | |
441 | | /** Compares two items for structural (encoding-level) equality |
442 | | * |
443 | | * Two items are structurally equal when they would produce identical bytes |
444 | | * if serialized by a correct CBOR encoder that preserves the in-memory |
445 | | * representation. Every aspect of the encoding counts: |
446 | | * |
447 | | * - **Major type**: `CBOR_TYPE_UINT` and `CBOR_TYPE_NEGINT` are distinct even |
448 | | * if the argument bytes happen to be the same. |
449 | | * - **Integer encoding width**: `cbor_build_uint8(1)` and |
450 | | * `cbor_build_uint16(1)` are *not* structurally equal, even though both |
451 | | * represent the integer 1. Use the integer value accessors (`cbor_get_uint64` |
452 | | * etc.) if you need value-level comparison. |
453 | | * - **Definite vs. indefinite length**: a definite-length array and an |
454 | | * indefinite-length array with the same elements are *not* structurally |
455 | | * equal. |
456 | | * - **Chunk boundaries**: two indefinite bytestrings or strings that carry the |
457 | | * same bytes but split them across a different number of chunks are *not* |
458 | | * structurally equal. |
459 | | * - **Map entry order**: maps are compared positionally — entry at index i in |
460 | | * \p item1 must match entry at index i in \p item2. Maps that carry the same |
461 | | * key-value pairs in a different order are *not* structurally equal. (CBOR |
462 | | * maps are unordered in the data model; for data-model equality see RFC 8949 |
463 | | * §5.6.1.) |
464 | | * - **Float encoding width**: `cbor_build_float2(1.5)` and |
465 | | * `cbor_build_float4(1.5)` are *not* structurally equal. |
466 | | * - **NaN payload**: floating-point NaN values with different bit patterns are |
467 | | * *not* structurally equal. |
468 | | * - **Tag number**: tags with different tag numbers are *not* structurally |
469 | | * equal. |
470 | | * |
471 | | * Runs in time linear in the encoded byte size of the items and performs no |
472 | | * additional memory allocations. |
473 | | * |
474 | | * \rst |
475 | | * .. note:: |
476 | | * This function implements *structural* equality, not the data-model equality |
477 | | * defined by RFC 8949. In the CBOR data model, encoding width is invisible |
478 | | * and maps are unordered sets of key-value pairs. If you need data-model |
479 | | * equality (e.g., ``uint8(1) == uint64(1)``), you must implement it on top |
480 | | * of this library. |
481 | | * \endrst |
482 | | * |
483 | | * Neither \p item1 nor \p item2 may be `NULL`. Passing `NULL` is a |
484 | | * programming error and will trigger an assertion failure in debug builds. |
485 | | * |
486 | | * @param item1 First item; must not be `NULL` |
487 | | * @param item2 Second item; must not be `NULL` |
488 | | * @return `true` if \p item1 and \p item2 are structurally equal |
489 | | */ |
490 | | _CBOR_NODISCARD |
491 | | CBOR_EXPORT bool cbor_structurally_equal(const cbor_item_t* item1, |
492 | | const cbor_item_t* item2); |
493 | | |
494 | | #ifdef __cplusplus |
495 | | } |
496 | | #endif |
497 | | |
498 | | #endif // LIBCBOR_COMMON_H |