blob: 04ec23c3ace05ae53c2a6e5f89b99669a20c70f6 [file] [log] [blame]
w.denge87b5002025-08-20 10:43:03 +08001/*
2 * Copyright (c) 2004, 2005 Metaparadigm Pte. Ltd.
3 * Michael Clark <michael@metaparadigm.com>
4 * Copyright (c) 2009 Hewlett-Packard Development Company, L.P.
5 *
6 * This library is free software; you can redistribute it and/or modify
7 * it under the terms of the MIT license. See COPYING for details.
8 *
9 */
10
11#include "config.h"
12
13#include "strerror_override.h"
14
15#include <assert.h>
16#ifdef HAVE_LIMITS_H
17#include <limits.h>
18#endif
19#include <math.h>
20#include <stddef.h>
21#include <stdio.h>
22#include <stdlib.h>
23#include <string.h>
24
25#include "arraylist.h"
26#include "debug.h"
27#include "json_inttypes.h"
28#include "json_object.h"
29#include "json_object_private.h"
30#include "json_util.h"
31#include "linkhash.h"
32#include "math_compat.h"
33#include "printbuf.h"
34#include "snprintf_compat.h"
35#include "strdup_compat.h"
36
37/* Avoid ctype.h and locale overhead */
38#define is_plain_digit(c) ((c) >= '0' && (c) <= '9')
39
40#if SIZEOF_LONG_LONG != SIZEOF_INT64_T
41#error The long long type is not 64-bits
42#endif
43
44#ifndef SSIZE_T_MAX
45#if SIZEOF_SSIZE_T == SIZEOF_INT
46#define SSIZE_T_MAX INT_MAX
47#elif SIZEOF_SSIZE_T == SIZEOF_LONG
48#define SSIZE_T_MAX LONG_MAX
49#elif SIZEOF_SSIZE_T == SIZEOF_LONG_LONG
50#define SSIZE_T_MAX LLONG_MAX
51#else
52#error Unable to determine size of ssize_t
53#endif
54#endif
55
56const char *json_hex_chars = "0123456789abcdefABCDEF";
57
58static void json_object_generic_delete(struct json_object *jso);
59
60#if defined(_MSC_VER) && (_MSC_VER <= 1800)
61/* VS2013 doesn't know about "inline" */
62#define inline __inline
63#elif defined(AIX_CC)
64#define inline
65#endif
66
67#ifdef __GNUC__
68#undef isnan
69#undef isinf
70#define isnan(x) __builtin_isnan(x)
71#define isinf(x) __builtin_isinf(x)
72#endif
73
74/*
75 * Helper functions to more safely cast to a particular type of json_object
76 */
77static inline struct json_object_object *JC_OBJECT(struct json_object *jso)
78{
79 return (void *)jso;
80}
81static inline const struct json_object_object *JC_OBJECT_C(const struct json_object *jso)
82{
83 return (const void *)jso;
84}
85static inline struct json_object_array *JC_ARRAY(struct json_object *jso)
86{
87 return (void *)jso;
88}
89static inline const struct json_object_array *JC_ARRAY_C(const struct json_object *jso)
90{
91 return (const void *)jso;
92}
93static inline struct json_object_boolean *JC_BOOL(struct json_object *jso)
94{
95 return (void *)jso;
96}
97static inline const struct json_object_boolean *JC_BOOL_C(const struct json_object *jso)
98{
99 return (const void *)jso;
100}
101static inline struct json_object_double *JC_DOUBLE(struct json_object *jso)
102{
103 return (void *)jso;
104}
105static inline const struct json_object_double *JC_DOUBLE_C(const struct json_object *jso)
106{
107 return (const void *)jso;
108}
109static inline struct json_object_int *JC_INT(struct json_object *jso)
110{
111 return (void *)jso;
112}
113static inline const struct json_object_int *JC_INT_C(const struct json_object *jso)
114{
115 return (const void *)jso;
116}
117static inline struct json_object_string *JC_STRING(struct json_object *jso)
118{
119 return (void *)jso;
120}
121static inline const struct json_object_string *JC_STRING_C(const struct json_object *jso)
122{
123 return (const void *)jso;
124}
125
126#define JC_CONCAT(a, b) a##b
127#define JC_CONCAT3(a, b, c) a##b##c
128
129#define JSON_OBJECT_NEW(jtype) \
130 (struct JC_CONCAT(json_object_, jtype) *)json_object_new( \
131 JC_CONCAT(json_type_, jtype), sizeof(struct JC_CONCAT(json_object_, jtype)), \
132 &JC_CONCAT3(json_object_, jtype, _to_json_string))
133
134static inline struct json_object *json_object_new(enum json_type o_type, size_t alloc_size,
135 json_object_to_json_string_fn *to_json_string);
136
137static void json_object_object_delete(struct json_object *jso_base);
138static void json_object_string_delete(struct json_object *jso);
139static void json_object_array_delete(struct json_object *jso);
140
141static json_object_to_json_string_fn json_object_object_to_json_string;
142static json_object_to_json_string_fn json_object_boolean_to_json_string;
143static json_object_to_json_string_fn json_object_double_to_json_string_default;
144static json_object_to_json_string_fn json_object_int_to_json_string;
145static json_object_to_json_string_fn json_object_string_to_json_string;
146static json_object_to_json_string_fn json_object_array_to_json_string;
147static json_object_to_json_string_fn _json_object_userdata_to_json_string;
148
149#ifndef JSON_NORETURN
150#if defined(_MSC_VER)
151#define JSON_NORETURN __declspec(noreturn)
152#elif defined(__OS400__)
153#define JSON_NORETURN
154#else
155/* 'cold' attribute is for optimization, telling the computer this code
156 * path is unlikely.
157 */
158#define JSON_NORETURN __attribute__((noreturn, cold))
159#endif
160#endif
161/**
162 * Abort and optionally print a message on standard error.
163 * This should be used rather than assert() for unconditional abortion
164 * (in particular for code paths which are never supposed to be run).
165 * */
166JSON_NORETURN static void json_abort(const char *message);
167
168/* helper for accessing the optimized string data component in json_object
169 */
170static inline char *get_string_component_mutable(struct json_object *jso)
171{
172 if (JC_STRING_C(jso)->len < 0)
173 {
174 /* Due to json_object_set_string(), we might have a pointer */
175 return JC_STRING(jso)->c_string.pdata;
176 }
177 return JC_STRING(jso)->c_string.idata;
178}
179static inline const char *get_string_component(const struct json_object *jso)
180{
181 return get_string_component_mutable((void *)(uintptr_t)(const void *)jso);
182}
183
184/* string escaping */
185
186static int json_escape_str(struct printbuf *pb, const char *str, size_t len, int flags)
187{
188 size_t pos = 0, start_offset = 0;
189 unsigned char c;
190 while (len)
191 {
192 --len;
193 c = str[pos];
194 switch (c)
195 {
196 case '\b':
197 case '\n':
198 case '\r':
199 case '\t':
200 case '\f':
201 case '"':
202 case '\\':
203 case '/':
204 if ((flags & JSON_C_TO_STRING_NOSLASHESCAPE) && c == '/')
205 {
206 pos++;
207 break;
208 }
209
210 if (pos > start_offset)
211 printbuf_memappend(pb, str + start_offset, pos - start_offset);
212
213 if (c == '\b')
214 printbuf_memappend(pb, "\\b", 2);
215 else if (c == '\n')
216 printbuf_memappend(pb, "\\n", 2);
217 else if (c == '\r')
218 printbuf_memappend(pb, "\\r", 2);
219 else if (c == '\t')
220 printbuf_memappend(pb, "\\t", 2);
221 else if (c == '\f')
222 printbuf_memappend(pb, "\\f", 2);
223 else if (c == '"')
224 printbuf_memappend(pb, "\\\"", 2);
225 else if (c == '\\')
226 printbuf_memappend(pb, "\\\\", 2);
227 else if (c == '/')
228 printbuf_memappend(pb, "\\/", 2);
229
230 start_offset = ++pos;
231 break;
232 default:
233 if (c < ' ')
234 {
235 char sbuf[7];
236 if (pos > start_offset)
237 printbuf_memappend(pb, str + start_offset,
238 pos - start_offset);
239 snprintf(sbuf, sizeof(sbuf), "\\u00%c%c", json_hex_chars[c >> 4],
240 json_hex_chars[c & 0xf]);
241 printbuf_memappend_fast(pb, sbuf, (int)sizeof(sbuf) - 1);
242 start_offset = ++pos;
243 }
244 else
245 pos++;
246 }
247 }
248 if (pos > start_offset)
249 printbuf_memappend(pb, str + start_offset, pos - start_offset);
250 return 0;
251}
252
253/* reference counting */
254
255struct json_object *json_object_get(struct json_object *jso)
256{
257 if (!jso)
258 return jso;
259
260 // Don't overflow the refcounter.
261 assert(jso->_ref_count < UINT32_MAX);
262
263#if defined(HAVE_ATOMIC_BUILTINS) && defined(ENABLE_THREADING)
264 __sync_add_and_fetch(&jso->_ref_count, 1);
265#else
266 ++jso->_ref_count;
267#endif
268
269 return jso;
270}
271
272int json_object_put(struct json_object *jso)
273{
274 if (!jso)
275 return 0;
276
277 /* Avoid invalid free and crash explicitly instead of (silently)
278 * segfaulting.
279 */
280 assert(jso->_ref_count > 0);
281
282#if defined(HAVE_ATOMIC_BUILTINS) && defined(ENABLE_THREADING)
283 /* Note: this only allow the refcount to remain correct
284 * when multiple threads are adjusting it. It is still an error
285 * for a thread to decrement the refcount if it doesn't "own" it,
286 * as that can result in the thread that loses the race to 0
287 * operating on an already-freed object.
288 */
289 if (__sync_sub_and_fetch(&jso->_ref_count, 1) > 0)
290 return 0;
291#else
292 if (--jso->_ref_count > 0)
293 return 0;
294#endif
295
296 if (jso->_user_delete)
297 jso->_user_delete(jso, jso->_userdata);
298 switch (jso->o_type)
299 {
300 case json_type_object: json_object_object_delete(jso); break;
301 case json_type_array: json_object_array_delete(jso); break;
302 case json_type_string: json_object_string_delete(jso); break;
303 default: json_object_generic_delete(jso); break;
304 }
305 return 1;
306}
307
308/* generic object construction and destruction parts */
309
310static void json_object_generic_delete(struct json_object *jso)
311{
312 printbuf_free(jso->_pb);
313 free(jso);
314}
315
316static inline struct json_object *json_object_new(enum json_type o_type, size_t alloc_size,
317 json_object_to_json_string_fn *to_json_string)
318{
319 struct json_object *jso;
320
321 jso = (struct json_object *)malloc(alloc_size);
322 if (!jso)
323 return NULL;
324
325 jso->o_type = o_type;
326 jso->_ref_count = 1;
327 jso->_to_json_string = to_json_string;
328 jso->_pb = NULL;
329 jso->_user_delete = NULL;
330 jso->_userdata = NULL;
331 //jso->... // Type-specific fields must be set by caller
332
333 return jso;
334}
335
336/* type checking functions */
337
338int json_object_is_type(const struct json_object *jso, enum json_type type)
339{
340 if (!jso)
341 return (type == json_type_null);
342 return (jso->o_type == type);
343}
344
345enum json_type json_object_get_type(const struct json_object *jso)
346{
347 if (!jso)
348 return json_type_null;
349 return jso->o_type;
350}
351
352void *json_object_get_userdata(json_object *jso)
353{
354 return jso ? jso->_userdata : NULL;
355}
356
357void json_object_set_userdata(json_object *jso, void *userdata, json_object_delete_fn *user_delete)
358{
359 // Can't return failure, so abort if we can't perform the operation.
360 assert(jso != NULL);
361
362 // First, clean up any previously existing user info
363 if (jso->_user_delete)
364 jso->_user_delete(jso, jso->_userdata);
365
366 jso->_userdata = userdata;
367 jso->_user_delete = user_delete;
368}
369
370/* set a custom conversion to string */
371
372void json_object_set_serializer(json_object *jso, json_object_to_json_string_fn *to_string_func,
373 void *userdata, json_object_delete_fn *user_delete)
374{
375 json_object_set_userdata(jso, userdata, user_delete);
376
377 if (to_string_func == NULL)
378 {
379 // Reset to the standard serialization function
380 switch (jso->o_type)
381 {
382 case json_type_null: jso->_to_json_string = NULL; break;
383 case json_type_boolean:
384 jso->_to_json_string = &json_object_boolean_to_json_string;
385 break;
386 case json_type_double:
387 jso->_to_json_string = &json_object_double_to_json_string_default;
388 break;
389 case json_type_int: jso->_to_json_string = &json_object_int_to_json_string; break;
390 case json_type_object:
391 jso->_to_json_string = &json_object_object_to_json_string;
392 break;
393 case json_type_array:
394 jso->_to_json_string = &json_object_array_to_json_string;
395 break;
396 case json_type_string:
397 jso->_to_json_string = &json_object_string_to_json_string;
398 break;
399 }
400 return;
401 }
402
403 jso->_to_json_string = to_string_func;
404}
405
406/* extended conversion to string */
407
408const char *json_object_to_json_string_length(struct json_object *jso, int flags, size_t *length)
409{
410 const char *r = NULL;
411 size_t s = 0;
412
413 if (!jso)
414 {
415 s = 4;
416 r = "null";
417 }
418 else if ((jso->_pb) || (jso->_pb = printbuf_new()))
419 {
420 printbuf_reset(jso->_pb);
421
422 if (jso->_to_json_string(jso, jso->_pb, 0, flags) >= 0)
423 {
424 s = (size_t)jso->_pb->bpos;
425 r = jso->_pb->buf;
426 }
427 }
428
429 if (length)
430 *length = s;
431 return r;
432}
433
434const char *json_object_to_json_string_ext(struct json_object *jso, int flags)
435{
436 return json_object_to_json_string_length(jso, flags, NULL);
437}
438
439/* backwards-compatible conversion to string */
440
441const char *json_object_to_json_string(struct json_object *jso)
442{
443 return json_object_to_json_string_ext(jso, JSON_C_TO_STRING_SPACED);
444}
445
446static void indent(struct printbuf *pb, int level, int flags)
447{
448 if (flags & JSON_C_TO_STRING_PRETTY)
449 {
450 if (flags & JSON_C_TO_STRING_PRETTY_TAB)
451 {
452 printbuf_memset(pb, -1, '\t', level);
453 }
454 else
455 {
456 printbuf_memset(pb, -1, ' ', level * 2);
457 }
458 }
459}
460
461/* json_object_object */
462
463static int json_object_object_to_json_string(struct json_object *jso, struct printbuf *pb,
464 int level, int flags)
465{
466 int had_children = 0;
467 struct json_object_iter iter;
468
469 printbuf_strappend(pb, "{" /*}*/);
470 json_object_object_foreachC(jso, iter)
471 {
472 if (had_children)
473 {
474 printbuf_strappend(pb, ",");
475 }
476 if (flags & JSON_C_TO_STRING_PRETTY)
477 printbuf_strappend(pb, "\n");
478 had_children = 1;
479 if (flags & JSON_C_TO_STRING_SPACED && !(flags & JSON_C_TO_STRING_PRETTY))
480 printbuf_strappend(pb, " ");
481 indent(pb, level + 1, flags);
482 printbuf_strappend(pb, "\"");
483 json_escape_str(pb, iter.key, strlen(iter.key), flags);
484 if (flags & JSON_C_TO_STRING_SPACED)
485 printbuf_strappend(pb, "\": ");
486 else
487 printbuf_strappend(pb, "\":");
488 if (iter.val == NULL)
489 printbuf_strappend(pb, "null");
490 else if (iter.val->_to_json_string(iter.val, pb, level + 1, flags) < 0)
491 return -1;
492 }
493 if ((flags & JSON_C_TO_STRING_PRETTY) && had_children)
494 {
495 printbuf_strappend(pb, "\n");
496 indent(pb, level, flags);
497 }
498 if (flags & JSON_C_TO_STRING_SPACED && !(flags & JSON_C_TO_STRING_PRETTY))
499 return printbuf_strappend(pb, /*{*/ " }");
500 else
501 return printbuf_strappend(pb, /*{*/ "}");
502}
503
504static void json_object_lh_entry_free(struct lh_entry *ent)
505{
506 if (!lh_entry_k_is_constant(ent))
507 free(lh_entry_k(ent));
508 json_object_put((struct json_object *)lh_entry_v(ent));
509}
510
511static void json_object_object_delete(struct json_object *jso_base)
512{
513 lh_table_free(JC_OBJECT(jso_base)->c_object);
514 json_object_generic_delete(jso_base);
515}
516
517struct json_object *json_object_new_object(void)
518{
519 struct json_object_object *jso = JSON_OBJECT_NEW(object);
520 if (!jso)
521 return NULL;
522 jso->c_object =
523 lh_kchar_table_new(JSON_OBJECT_DEF_HASH_ENTRIES, &json_object_lh_entry_free);
524 if (!jso->c_object)
525 {
526 json_object_generic_delete(&jso->base);
527 errno = ENOMEM;
528 return NULL;
529 }
530 return &jso->base;
531}
532
533struct lh_table *json_object_get_object(const struct json_object *jso)
534{
535 if (!jso)
536 return NULL;
537 switch (jso->o_type)
538 {
539 case json_type_object: return JC_OBJECT_C(jso)->c_object;
540 default: return NULL;
541 }
542}
543
544int json_object_object_add_ex(struct json_object *jso, const char *const key,
545 struct json_object *const val, const unsigned opts)
546{
547 struct json_object *existing_value = NULL;
548 struct lh_entry *existing_entry;
549 unsigned long hash;
550
551 assert(json_object_get_type(jso) == json_type_object);
552
553 // We lookup the entry and replace the value, rather than just deleting
554 // and re-adding it, so the existing key remains valid.
555 hash = lh_get_hash(JC_OBJECT(jso)->c_object, (const void *)key);
556 existing_entry =
557 (opts & JSON_C_OBJECT_ADD_KEY_IS_NEW)
558 ? NULL
559 : lh_table_lookup_entry_w_hash(JC_OBJECT(jso)->c_object, (const void *)key, hash);
560
561 // The caller must avoid creating loops in the object tree, but do a
562 // quick check anyway to make sure we're not creating a trivial loop.
563 if (jso == val)
564 return -1;
565
566 if (!existing_entry)
567 {
568 const void *const k =
569 (opts & JSON_C_OBJECT_ADD_CONSTANT_KEY) ? (const void *)key : strdup(key);
570 if (k == NULL)
571 return -1;
572 return lh_table_insert_w_hash(JC_OBJECT(jso)->c_object, k, val, hash, opts);
573 }
574 existing_value = (json_object *)lh_entry_v(existing_entry);
575 if (existing_value)
576 json_object_put(existing_value);
577 lh_entry_set_val(existing_entry, val);
578 return 0;
579}
580
581int json_object_object_add(struct json_object *jso, const char *key, struct json_object *val)
582{
583 return json_object_object_add_ex(jso, key, val, 0);
584}
585
586int json_object_object_length(const struct json_object *jso)
587{
588 assert(json_object_get_type(jso) == json_type_object);
589 return lh_table_length(JC_OBJECT_C(jso)->c_object);
590}
591
592size_t json_c_object_sizeof(void)
593{
594 return sizeof(struct json_object);
595}
596
597struct json_object *json_object_object_get(const struct json_object *jso, const char *key)
598{
599 struct json_object *result = NULL;
600 json_object_object_get_ex(jso, key, &result);
601 return result;
602}
603
604json_bool json_object_object_get_ex(const struct json_object *jso, const char *key,
605 struct json_object **value)
606{
607 if (value != NULL)
608 *value = NULL;
609
610 if (NULL == jso)
611 return 0;
612
613 switch (jso->o_type)
614 {
615 case json_type_object:
616 return lh_table_lookup_ex(JC_OBJECT_C(jso)->c_object, (const void *)key,
617 (void **)value);
618 default:
619 if (value != NULL)
620 *value = NULL;
621 return 0;
622 }
623}
624
625void json_object_object_del(struct json_object *jso, const char *key)
626{
627 assert(json_object_get_type(jso) == json_type_object);
628 lh_table_delete(JC_OBJECT(jso)->c_object, key);
629}
630
631/* json_object_boolean */
632
633static int json_object_boolean_to_json_string(struct json_object *jso, struct printbuf *pb,
634 int level, int flags)
635{
636 if (JC_BOOL(jso)->c_boolean)
637 return printbuf_strappend(pb, "true");
638 return printbuf_strappend(pb, "false");
639}
640
641struct json_object *json_object_new_boolean(json_bool b)
642{
643 struct json_object_boolean *jso = JSON_OBJECT_NEW(boolean);
644 if (!jso)
645 return NULL;
646 jso->c_boolean = b;
647 return &jso->base;
648}
649
650json_bool json_object_get_boolean(const struct json_object *jso)
651{
652 if (!jso)
653 return 0;
654 switch (jso->o_type)
655 {
656 case json_type_boolean: return JC_BOOL_C(jso)->c_boolean;
657 case json_type_int:
658 switch (JC_INT_C(jso)->cint_type)
659 {
660 case json_object_int_type_int64: return (JC_INT_C(jso)->cint.c_int64 != 0);
661 case json_object_int_type_uint64: return (JC_INT_C(jso)->cint.c_uint64 != 0);
662 default: json_abort("invalid cint_type");
663 }
664 case json_type_double: return (JC_DOUBLE_C(jso)->c_double != 0);
665 case json_type_string: return (JC_STRING_C(jso)->len != 0);
666 default: return 0;
667 }
668}
669
670int json_object_set_boolean(struct json_object *jso, json_bool new_value)
671{
672 if (!jso || jso->o_type != json_type_boolean)
673 return 0;
674 JC_BOOL(jso)->c_boolean = new_value;
675 return 1;
676}
677
678/* json_object_int */
679
680static int json_object_int_to_json_string(struct json_object *jso, struct printbuf *pb, int level,
681 int flags)
682{
683 /* room for 19 digits, the sign char, and a null term */
684 char sbuf[21];
685 if (JC_INT(jso)->cint_type == json_object_int_type_int64)
686 snprintf(sbuf, sizeof(sbuf), "%" PRId64, JC_INT(jso)->cint.c_int64);
687 else
688 snprintf(sbuf, sizeof(sbuf), "%" PRIu64, JC_INT(jso)->cint.c_uint64);
689 return printbuf_memappend(pb, sbuf, strlen(sbuf));
690}
691
692struct json_object *json_object_new_int(int32_t i)
693{
694 return json_object_new_int64(i);
695}
696
697int32_t json_object_get_int(const struct json_object *jso)
698{
699 int64_t cint64 = 0;
700 double cdouble;
701 enum json_type o_type;
702
703 if (!jso)
704 return 0;
705
706 o_type = jso->o_type;
707 if (o_type == json_type_int)
708 {
709 const struct json_object_int *jsoint = JC_INT_C(jso);
710 if (jsoint->cint_type == json_object_int_type_int64)
711 {
712 cint64 = jsoint->cint.c_int64;
713 }
714 else
715 {
716 if (jsoint->cint.c_uint64 >= INT64_MAX)
717 cint64 = INT64_MAX;
718 else
719 cint64 = (int64_t)jsoint->cint.c_uint64;
720 }
721 }
722 else if (o_type == json_type_string)
723 {
724 /*
725 * Parse strings into 64-bit numbers, then use the
726 * 64-to-32-bit number handling below.
727 */
728 if (json_parse_int64(get_string_component(jso), &cint64) != 0)
729 return 0; /* whoops, it didn't work. */
730 o_type = json_type_int;
731 }
732
733 switch (o_type)
734 {
735 case json_type_int:
736 /* Make sure we return the correct values for out of range numbers. */
737 if (cint64 <= INT32_MIN)
738 return INT32_MIN;
739 if (cint64 >= INT32_MAX)
740 return INT32_MAX;
741 return (int32_t)cint64;
742 case json_type_double:
743 cdouble = JC_DOUBLE_C(jso)->c_double;
744 if (cdouble <= INT32_MIN)
745 return INT32_MIN;
746 if (cdouble >= INT32_MAX)
747 return INT32_MAX;
748 return (int32_t)cdouble;
749 case json_type_boolean: return JC_BOOL_C(jso)->c_boolean;
750 default: return 0;
751 }
752}
753
754int json_object_set_int(struct json_object *jso, int new_value)
755{
756 return json_object_set_int64(jso, (int64_t)new_value);
757}
758
759struct json_object *json_object_new_int64(int64_t i)
760{
761 struct json_object_int *jso = JSON_OBJECT_NEW(int);
762 if (!jso)
763 return NULL;
764 jso->cint.c_int64 = i;
765 jso->cint_type = json_object_int_type_int64;
766 return &jso->base;
767}
768
769struct json_object *json_object_new_uint64(uint64_t i)
770{
771 struct json_object_int *jso = JSON_OBJECT_NEW(int);
772 if (!jso)
773 return NULL;
774 jso->cint.c_uint64 = i;
775 jso->cint_type = json_object_int_type_uint64;
776 return &jso->base;
777}
778
779int64_t json_object_get_int64(const struct json_object *jso)
780{
781 int64_t cint;
782
783 if (!jso)
784 return 0;
785 switch (jso->o_type)
786 {
787 case json_type_int:
788 {
789 const struct json_object_int *jsoint = JC_INT_C(jso);
790 switch (jsoint->cint_type)
791 {
792 case json_object_int_type_int64: return jsoint->cint.c_int64;
793 case json_object_int_type_uint64:
794 if (jsoint->cint.c_uint64 >= INT64_MAX)
795 return INT64_MAX;
796 return (int64_t)jsoint->cint.c_uint64;
797 default: json_abort("invalid cint_type");
798 }
799 }
800 case json_type_double:
801 // INT64_MAX can't be exactly represented as a double
802 // so cast to tell the compiler it's ok to round up.
803 if (JC_DOUBLE_C(jso)->c_double >= (double)INT64_MAX)
804 return INT64_MAX;
805 if (JC_DOUBLE_C(jso)->c_double <= INT64_MIN)
806 return INT64_MIN;
807 return (int64_t)JC_DOUBLE_C(jso)->c_double;
808 case json_type_boolean: return JC_BOOL_C(jso)->c_boolean;
809 case json_type_string:
810 if (json_parse_int64(get_string_component(jso), &cint) == 0)
811 return cint;
812 /* FALLTHRU */
813 default: return 0;
814 }
815}
816
817uint64_t json_object_get_uint64(const struct json_object *jso)
818{
819 uint64_t cuint;
820
821 if (!jso)
822 return 0;
823 switch (jso->o_type)
824 {
825 case json_type_int:
826 {
827 const struct json_object_int *jsoint = JC_INT_C(jso);
828 switch (jsoint->cint_type)
829 {
830 case json_object_int_type_int64:
831 if (jsoint->cint.c_int64 < 0)
832 return 0;
833 return (uint64_t)jsoint->cint.c_int64;
834 case json_object_int_type_uint64: return jsoint->cint.c_uint64;
835 default: json_abort("invalid cint_type");
836 }
837 }
838 case json_type_double:
839 // UINT64_MAX can't be exactly represented as a double
840 // so cast to tell the compiler it's ok to round up.
841 if (JC_DOUBLE_C(jso)->c_double >= (double)UINT64_MAX)
842 return UINT64_MAX;
843 if (JC_DOUBLE_C(jso)->c_double < 0)
844 return 0;
845 return (uint64_t)JC_DOUBLE_C(jso)->c_double;
846 case json_type_boolean: return JC_BOOL_C(jso)->c_boolean;
847 case json_type_string:
848 if (json_parse_uint64(get_string_component(jso), &cuint) == 0)
849 return cuint;
850 /* FALLTHRU */
851 default: return 0;
852 }
853}
854
855int json_object_set_int64(struct json_object *jso, int64_t new_value)
856{
857 if (!jso || jso->o_type != json_type_int)
858 return 0;
859 JC_INT(jso)->cint.c_int64 = new_value;
860 JC_INT(jso)->cint_type = json_object_int_type_int64;
861 return 1;
862}
863
864int json_object_set_uint64(struct json_object *jso, uint64_t new_value)
865{
866 if (!jso || jso->o_type != json_type_int)
867 return 0;
868 JC_INT(jso)->cint.c_uint64 = new_value;
869 JC_INT(jso)->cint_type = json_object_int_type_uint64;
870 return 1;
871}
872
873int json_object_int_inc(struct json_object *jso, int64_t val)
874{
875 struct json_object_int *jsoint;
876 if (!jso || jso->o_type != json_type_int)
877 return 0;
878 jsoint = JC_INT(jso);
879 switch (jsoint->cint_type)
880 {
881 case json_object_int_type_int64:
882 if (val > 0 && jsoint->cint.c_int64 > INT64_MAX - val)
883 {
884 jsoint->cint.c_uint64 = (uint64_t)jsoint->cint.c_int64 + (uint64_t)val;
885 jsoint->cint_type = json_object_int_type_uint64;
886 }
887 else if (val < 0 && jsoint->cint.c_int64 < INT64_MIN - val)
888 {
889 jsoint->cint.c_int64 = INT64_MIN;
890 }
891 else
892 {
893 jsoint->cint.c_int64 += val;
894 }
895 return 1;
896 case json_object_int_type_uint64:
897 if (val > 0 && jsoint->cint.c_uint64 > UINT64_MAX - (uint64_t)val)
898 {
899 jsoint->cint.c_uint64 = UINT64_MAX;
900 }
901 else if (val < 0 && jsoint->cint.c_uint64 < (uint64_t)(-val))
902 {
903 jsoint->cint.c_int64 = (int64_t)jsoint->cint.c_uint64 + val;
904 jsoint->cint_type = json_object_int_type_int64;
905 }
906 else if (val < 0 && jsoint->cint.c_uint64 >= (uint64_t)(-val))
907 {
908 jsoint->cint.c_uint64 -= (uint64_t)(-val);
909 }
910 else
911 {
912 jsoint->cint.c_uint64 += val;
913 }
914 return 1;
915 default: json_abort("invalid cint_type");
916 }
917}
918
919/* json_object_double */
920
921#if defined(HAVE___THREAD)
922// i.e. __thread or __declspec(thread)
923static SPEC___THREAD char *tls_serialization_float_format = NULL;
924#endif
925static char *global_serialization_float_format = NULL;
926
927int json_c_set_serialization_double_format(const char *double_format, int global_or_thread)
928{
929 if (global_or_thread == JSON_C_OPTION_GLOBAL)
930 {
931#if defined(HAVE___THREAD)
932 if (tls_serialization_float_format)
933 {
934 free(tls_serialization_float_format);
935 tls_serialization_float_format = NULL;
936 }
937#endif
938 if (global_serialization_float_format)
939 free(global_serialization_float_format);
940 if (double_format)
941 {
942 char *p = strdup(double_format);
943 if (p == NULL)
944 {
945 _json_c_set_last_err("json_c_set_serialization_double_format: "
946 "out of memory\n");
947 return -1;
948 }
949 global_serialization_float_format = p;
950 }
951 else
952 {
953 global_serialization_float_format = NULL;
954 }
955 }
956 else if (global_or_thread == JSON_C_OPTION_THREAD)
957 {
958#if defined(HAVE___THREAD)
959 if (tls_serialization_float_format)
960 {
961 free(tls_serialization_float_format);
962 tls_serialization_float_format = NULL;
963 }
964 if (double_format)
965 {
966 char *p = strdup(double_format);
967 if (p == NULL)
968 {
969 _json_c_set_last_err("json_c_set_serialization_double_format: "
970 "out of memory\n");
971 return -1;
972 }
973 tls_serialization_float_format = p;
974 }
975 else
976 {
977 tls_serialization_float_format = NULL;
978 }
979#else
980 _json_c_set_last_err("json_c_set_serialization_double_format: not compiled "
981 "with __thread support\n");
982 return -1;
983#endif
984 }
985 else
986 {
987 _json_c_set_last_err("json_c_set_serialization_double_format: invalid "
988 "global_or_thread value: %d\n", global_or_thread);
989 return -1;
990 }
991 return 0;
992}
993
994static int json_object_double_to_json_string_format(struct json_object *jso, struct printbuf *pb,
995 int level, int flags, const char *format)
996{
997 struct json_object_double *jsodbl = JC_DOUBLE(jso);
998 char buf[128], *p, *q;
999 int size;
1000 /* Although JSON RFC does not support
1001 * NaN or Infinity as numeric values
1002 * ECMA 262 section 9.8.1 defines
1003 * how to handle these cases as strings
1004 */
1005 if (isnan(jsodbl->c_double))
1006 {
1007 size = snprintf(buf, sizeof(buf), "NaN");
1008 }
1009 else if (isinf(jsodbl->c_double))
1010 {
1011 if (jsodbl->c_double > 0)
1012 size = snprintf(buf, sizeof(buf), "Infinity");
1013 else
1014 size = snprintf(buf, sizeof(buf), "-Infinity");
1015 }
1016 else
1017 {
1018 const char *std_format = "%.17g";
1019 int format_drops_decimals = 0;
1020 int looks_numeric = 0;
1021
1022 if (!format)
1023 {
1024#if defined(HAVE___THREAD)
1025 if (tls_serialization_float_format)
1026 format = tls_serialization_float_format;
1027 else
1028#endif
1029 if (global_serialization_float_format)
1030 format = global_serialization_float_format;
1031 else
1032 format = std_format;
1033 }
1034 size = snprintf(buf, sizeof(buf), format, jsodbl->c_double);
1035
1036 if (size < 0)
1037 return -1;
1038
1039 p = strchr(buf, ',');
1040 if (p)
1041 *p = '.';
1042 else
1043 p = strchr(buf, '.');
1044
1045 if (format == std_format || strstr(format, ".0f") == NULL)
1046 format_drops_decimals = 1;
1047
1048 looks_numeric = /* Looks like *some* kind of number */
1049 is_plain_digit(buf[0]) || (size > 1 && buf[0] == '-' && is_plain_digit(buf[1]));
1050
1051 if (size < (int)sizeof(buf) - 2 && looks_numeric && !p && /* Has no decimal point */
1052 strchr(buf, 'e') == NULL && /* Not scientific notation */
1053 format_drops_decimals)
1054 {
1055 // Ensure it looks like a float, even if snprintf didn't,
1056 // unless a custom format is set to omit the decimal.
1057 strcat(buf, ".0");
1058 size += 2;
1059 }
1060 if (p && (flags & JSON_C_TO_STRING_NOZERO))
1061 {
1062 /* last useful digit, always keep 1 zero */
1063 p++;
1064 for (q = p; *q; q++)
1065 {
1066 if (*q != '0')
1067 p = q;
1068 }
1069 /* drop trailing zeroes */
1070 if (*p != 0)
1071 *(++p) = 0;
1072 size = p - buf;
1073 }
1074 }
1075 // although unlikely, snprintf can fail
1076 if (size < 0)
1077 return -1;
1078
1079 if (size >= (int)sizeof(buf))
1080 // The standard formats are guaranteed not to overrun the buffer,
1081 // but if a custom one happens to do so, just silently truncate.
1082 size = sizeof(buf) - 1;
1083 printbuf_memappend(pb, buf, size);
1084 return size;
1085}
1086
1087static int json_object_double_to_json_string_default(struct json_object *jso, struct printbuf *pb,
1088 int level, int flags)
1089{
1090 return json_object_double_to_json_string_format(jso, pb, level, flags, NULL);
1091}
1092
1093int json_object_double_to_json_string(struct json_object *jso, struct printbuf *pb, int level,
1094 int flags)
1095{
1096 return json_object_double_to_json_string_format(jso, pb, level, flags,
1097 (const char *)jso->_userdata);
1098}
1099
1100struct json_object *json_object_new_double(double d)
1101{
1102 struct json_object_double *jso = JSON_OBJECT_NEW(double);
1103 if (!jso)
1104 return NULL;
1105 jso->base._to_json_string = &json_object_double_to_json_string_default;
1106 jso->c_double = d;
1107 return &jso->base;
1108}
1109
1110struct json_object *json_object_new_double_s(double d, const char *ds)
1111{
1112 char *new_ds;
1113 struct json_object *jso = json_object_new_double(d);
1114 if (!jso)
1115 return NULL;
1116
1117 new_ds = strdup(ds);
1118 if (!new_ds)
1119 {
1120 json_object_generic_delete(jso);
1121 errno = ENOMEM;
1122 return NULL;
1123 }
1124 json_object_set_serializer(jso, _json_object_userdata_to_json_string, new_ds,
1125 json_object_free_userdata);
1126 return jso;
1127}
1128
1129/*
1130 * A wrapper around json_object_userdata_to_json_string() used only
1131 * by json_object_new_double_s() just so json_object_set_double() can
1132 * detect when it needs to reset the serializer to the default.
1133 */
1134static int _json_object_userdata_to_json_string(struct json_object *jso, struct printbuf *pb,
1135 int level, int flags)
1136{
1137 return json_object_userdata_to_json_string(jso, pb, level, flags);
1138}
1139
1140int json_object_userdata_to_json_string(struct json_object *jso, struct printbuf *pb, int level,
1141 int flags)
1142{
1143 int userdata_len = strlen((const char *)jso->_userdata);
1144 printbuf_memappend(pb, (const char *)jso->_userdata, userdata_len);
1145 return userdata_len;
1146}
1147
1148void json_object_free_userdata(struct json_object *jso, void *userdata)
1149{
1150 free(userdata);
1151}
1152
1153double json_object_get_double(const struct json_object *jso)
1154{
1155 double cdouble;
1156 char *errPtr = NULL;
1157
1158 if (!jso)
1159 return 0.0;
1160 switch (jso->o_type)
1161 {
1162 case json_type_double: return JC_DOUBLE_C(jso)->c_double;
1163 case json_type_int:
1164 switch (JC_INT_C(jso)->cint_type)
1165 {
1166 case json_object_int_type_int64: return JC_INT_C(jso)->cint.c_int64;
1167 case json_object_int_type_uint64: return JC_INT_C(jso)->cint.c_uint64;
1168 default: json_abort("invalid cint_type");
1169 }
1170 case json_type_boolean: return JC_BOOL_C(jso)->c_boolean;
1171 case json_type_string:
1172 errno = 0;
1173 cdouble = strtod(get_string_component(jso), &errPtr);
1174
1175 /* if conversion stopped at the first character, return 0.0 */
1176 if (errPtr == get_string_component(jso))
1177 {
1178 errno = EINVAL;
1179 return 0.0;
1180 }
1181
1182 /*
1183 * Check that the conversion terminated on something sensible
1184 *
1185 * For example, { "pay" : 123AB } would parse as 123.
1186 */
1187 if (*errPtr != '\0')
1188 {
1189 errno = EINVAL;
1190 return 0.0;
1191 }
1192
1193 /*
1194 * If strtod encounters a string which would exceed the
1195 * capacity of a double, it returns +/- HUGE_VAL and sets
1196 * errno to ERANGE. But +/- HUGE_VAL is also a valid result
1197 * from a conversion, so we need to check errno.
1198 *
1199 * Underflow also sets errno to ERANGE, but it returns 0 in
1200 * that case, which is what we will return anyway.
1201 *
1202 * See CERT guideline ERR30-C
1203 */
1204 if ((HUGE_VAL == cdouble || -HUGE_VAL == cdouble) && (ERANGE == errno))
1205 cdouble = 0.0;
1206 return cdouble;
1207 default: errno = EINVAL; return 0.0;
1208 }
1209}
1210
1211int json_object_set_double(struct json_object *jso, double new_value)
1212{
1213 if (!jso || jso->o_type != json_type_double)
1214 return 0;
1215 JC_DOUBLE(jso)->c_double = new_value;
1216 if (jso->_to_json_string == &_json_object_userdata_to_json_string)
1217 json_object_set_serializer(jso, NULL, NULL, NULL);
1218 return 1;
1219}
1220
1221/* json_object_string */
1222
1223static int json_object_string_to_json_string(struct json_object *jso, struct printbuf *pb,
1224 int level, int flags)
1225{
1226 ssize_t len = JC_STRING(jso)->len;
1227 printbuf_strappend(pb, "\"");
1228 json_escape_str(pb, get_string_component(jso), len < 0 ? -(ssize_t)len : len, flags);
1229 printbuf_strappend(pb, "\"");
1230 return 0;
1231}
1232
1233static void json_object_string_delete(struct json_object *jso)
1234{
1235 if (JC_STRING(jso)->len < 0)
1236 free(JC_STRING(jso)->c_string.pdata);
1237 json_object_generic_delete(jso);
1238}
1239
1240static struct json_object *_json_object_new_string(const char *s, const size_t len)
1241{
1242 size_t objsize;
1243 struct json_object_string *jso;
1244
1245 /*
1246 * Structures Actual memory layout
1247 * ------------------- --------------------
1248 * [json_object_string [json_object_string
1249 * [json_object] [json_object]
1250 * ...other fields... ...other fields...
1251 * c_string] len
1252 * bytes
1253 * of
1254 * string
1255 * data
1256 * \0]
1257 */
1258 if (len > (SSIZE_T_MAX - (sizeof(*jso) - sizeof(jso->c_string)) - 1))
1259 return NULL;
1260 objsize = (sizeof(*jso) - sizeof(jso->c_string)) + len + 1;
1261 if (len < sizeof(void *))
1262 // We need a minimum size to support json_object_set_string() mutability
1263 // so we can stuff a pointer into pdata :(
1264 objsize += sizeof(void *) - len;
1265
1266 jso = (struct json_object_string *)json_object_new(json_type_string, objsize,
1267 &json_object_string_to_json_string);
1268
1269 if (!jso)
1270 return NULL;
1271 jso->len = len;
1272 memcpy(jso->c_string.idata, s, len);
1273 // Cast below needed for Clang UB sanitizer
1274 ((char *)jso->c_string.idata)[len] = '\0';
1275 return &jso->base;
1276}
1277
1278struct json_object *json_object_new_string(const char *s)
1279{
1280 return _json_object_new_string(s, strlen(s));
1281}
1282
1283struct json_object *json_object_new_string_len(const char *s, const int len)
1284{
1285 return _json_object_new_string(s, len);
1286}
1287
1288const char *json_object_get_string(struct json_object *jso)
1289{
1290 if (!jso)
1291 return NULL;
1292 switch (jso->o_type)
1293 {
1294 case json_type_string: return get_string_component(jso);
1295 default: return json_object_to_json_string(jso);
1296 }
1297}
1298
1299static inline ssize_t _json_object_get_string_len(const struct json_object_string *jso)
1300{
1301 ssize_t len;
1302 len = jso->len;
1303 return (len < 0) ? -(ssize_t)len : len;
1304}
1305int json_object_get_string_len(const struct json_object *jso)
1306{
1307 if (!jso)
1308 return 0;
1309 switch (jso->o_type)
1310 {
1311 case json_type_string: return _json_object_get_string_len(JC_STRING_C(jso));
1312 default: return 0;
1313 }
1314}
1315
1316static int _json_object_set_string_len(json_object *jso, const char *s, size_t len)
1317{
1318 char *dstbuf;
1319 ssize_t curlen;
1320 ssize_t newlen;
1321 if (jso == NULL || jso->o_type != json_type_string)
1322 return 0;
1323
1324 if (len >= INT_MAX - 1)
1325 // jso->len is a signed ssize_t, so it can't hold the
1326 // full size_t range. json_object_get_string_len returns
1327 // length as int, cap length at INT_MAX.
1328 return 0;
1329
1330 curlen = JC_STRING(jso)->len;
1331 if (curlen < 0) {
1332 if (len == 0) {
1333 free(JC_STRING(jso)->c_string.pdata);
1334 JC_STRING(jso)->len = curlen = 0;
1335 } else {
1336 curlen = -curlen;
1337 }
1338 }
1339
1340 newlen = len;
1341 dstbuf = get_string_component_mutable(jso);
1342
1343 if ((ssize_t)len > curlen)
1344 {
1345 // We have no way to return the new ptr from realloc(jso, newlen)
1346 // and we have no way of knowing whether there's extra room available
1347 // so we need to stuff a pointer in to pdata :(
1348 dstbuf = (char *)malloc(len + 1);
1349 if (dstbuf == NULL)
1350 return 0;
1351 if (JC_STRING(jso)->len < 0)
1352 free(JC_STRING(jso)->c_string.pdata);
1353 JC_STRING(jso)->c_string.pdata = dstbuf;
1354 newlen = -(ssize_t)len;
1355 }
1356 else if (JC_STRING(jso)->len < 0)
1357 {
1358 // We've got enough room in the separate allocated buffer,
1359 // so use it as-is and continue to indicate that pdata is used.
1360 newlen = -(ssize_t)len;
1361 }
1362
1363 memcpy(dstbuf, (const void *)s, len);
1364 dstbuf[len] = '\0';
1365 JC_STRING(jso)->len = newlen;
1366 return 1;
1367}
1368
1369int json_object_set_string(json_object *jso, const char *s)
1370{
1371 return _json_object_set_string_len(jso, s, strlen(s));
1372}
1373
1374int json_object_set_string_len(json_object *jso, const char *s, int len)
1375{
1376 return _json_object_set_string_len(jso, s, len);
1377}
1378
1379/* json_object_array */
1380
1381static int json_object_array_to_json_string(struct json_object *jso, struct printbuf *pb, int level,
1382 int flags)
1383{
1384 int had_children = 0;
1385 size_t ii;
1386
1387 printbuf_strappend(pb, "[");
1388 for (ii = 0; ii < json_object_array_length(jso); ii++)
1389 {
1390 struct json_object *val;
1391 if (had_children)
1392 {
1393 printbuf_strappend(pb, ",");
1394 }
1395 if (flags & JSON_C_TO_STRING_PRETTY)
1396 printbuf_strappend(pb, "\n");
1397 had_children = 1;
1398 if (flags & JSON_C_TO_STRING_SPACED && !(flags & JSON_C_TO_STRING_PRETTY))
1399 printbuf_strappend(pb, " ");
1400 indent(pb, level + 1, flags);
1401 val = json_object_array_get_idx(jso, ii);
1402 if (val == NULL)
1403 printbuf_strappend(pb, "null");
1404 else if (val->_to_json_string(val, pb, level + 1, flags) < 0)
1405 return -1;
1406 }
1407 if ((flags & JSON_C_TO_STRING_PRETTY) && had_children)
1408 {
1409 printbuf_strappend(pb, "\n");
1410 indent(pb, level, flags);
1411 }
1412
1413 if (flags & JSON_C_TO_STRING_SPACED && !(flags & JSON_C_TO_STRING_PRETTY))
1414 return printbuf_strappend(pb, " ]");
1415 return printbuf_strappend(pb, "]");
1416}
1417
1418static void json_object_array_entry_free(void *data)
1419{
1420 json_object_put((struct json_object *)data);
1421}
1422
1423static void json_object_array_delete(struct json_object *jso)
1424{
1425 array_list_free(JC_ARRAY(jso)->c_array);
1426 json_object_generic_delete(jso);
1427}
1428
1429struct json_object *json_object_new_array(void)
1430{
1431 return json_object_new_array_ext(ARRAY_LIST_DEFAULT_SIZE);
1432}
1433struct json_object *json_object_new_array_ext(int initial_size)
1434{
1435 struct json_object_array *jso = JSON_OBJECT_NEW(array);
1436 if (!jso)
1437 return NULL;
1438 jso->c_array = array_list_new2(&json_object_array_entry_free, initial_size);
1439 if (jso->c_array == NULL)
1440 {
1441 free(jso);
1442 return NULL;
1443 }
1444 return &jso->base;
1445}
1446
1447struct array_list *json_object_get_array(const struct json_object *jso)
1448{
1449 if (!jso)
1450 return NULL;
1451 switch (jso->o_type)
1452 {
1453 case json_type_array: return JC_ARRAY_C(jso)->c_array;
1454 default: return NULL;
1455 }
1456}
1457
1458void json_object_array_sort(struct json_object *jso, int (*sort_fn)(const void *, const void *))
1459{
1460 assert(json_object_get_type(jso) == json_type_array);
1461 array_list_sort(JC_ARRAY(jso)->c_array, sort_fn);
1462}
1463
1464struct json_object *json_object_array_bsearch(const struct json_object *key,
1465 const struct json_object *jso,
1466 int (*sort_fn)(const void *, const void *))
1467{
1468 struct json_object **result;
1469
1470 assert(json_object_get_type(jso) == json_type_array);
1471 result = (struct json_object **)array_list_bsearch((const void **)(void *)&key,
1472 JC_ARRAY_C(jso)->c_array, sort_fn);
1473
1474 if (!result)
1475 return NULL;
1476 return *result;
1477}
1478
1479size_t json_object_array_length(const struct json_object *jso)
1480{
1481 assert(json_object_get_type(jso) == json_type_array);
1482 return array_list_length(JC_ARRAY_C(jso)->c_array);
1483}
1484
1485int json_object_array_add(struct json_object *jso, struct json_object *val)
1486{
1487 assert(json_object_get_type(jso) == json_type_array);
1488 return array_list_add(JC_ARRAY(jso)->c_array, val);
1489}
1490
1491int json_object_array_put_idx(struct json_object *jso, size_t idx, struct json_object *val)
1492{
1493 assert(json_object_get_type(jso) == json_type_array);
1494 return array_list_put_idx(JC_ARRAY(jso)->c_array, idx, val);
1495}
1496
1497int json_object_array_del_idx(struct json_object *jso, size_t idx, size_t count)
1498{
1499 assert(json_object_get_type(jso) == json_type_array);
1500 return array_list_del_idx(JC_ARRAY(jso)->c_array, idx, count);
1501}
1502
1503struct json_object *json_object_array_get_idx(const struct json_object *jso, size_t idx)
1504{
1505 assert(json_object_get_type(jso) == json_type_array);
1506 return (struct json_object *)array_list_get_idx(JC_ARRAY_C(jso)->c_array, idx);
1507}
1508
1509static int json_array_equal(struct json_object *jso1, struct json_object *jso2)
1510{
1511 size_t len, i;
1512
1513 len = json_object_array_length(jso1);
1514 if (len != json_object_array_length(jso2))
1515 return 0;
1516
1517 for (i = 0; i < len; i++)
1518 {
1519 if (!json_object_equal(json_object_array_get_idx(jso1, i),
1520 json_object_array_get_idx(jso2, i)))
1521 return 0;
1522 }
1523 return 1;
1524}
1525
1526int json_object_array_shrink(struct json_object *jso, int empty_slots)
1527{
1528 if (empty_slots < 0)
1529 json_abort("json_object_array_shrink called with negative empty_slots");
1530 return array_list_shrink(JC_ARRAY(jso)->c_array, empty_slots);
1531}
1532
1533struct json_object *json_object_new_null(void)
1534{
1535 return NULL;
1536}
1537
1538static int json_object_all_values_equal(struct json_object *jso1, struct json_object *jso2)
1539{
1540 struct json_object_iter iter;
1541 struct json_object *sub;
1542
1543 assert(json_object_get_type(jso1) == json_type_object);
1544 assert(json_object_get_type(jso2) == json_type_object);
1545 /* Iterate over jso1 keys and see if they exist and are equal in jso2 */
1546 json_object_object_foreachC(jso1, iter)
1547 {
1548 if (!lh_table_lookup_ex(JC_OBJECT(jso2)->c_object, (void *)iter.key,
1549 (void **)(void *)&sub))
1550 return 0;
1551 if (!json_object_equal(iter.val, sub))
1552 return 0;
1553 }
1554
1555 /* Iterate over jso2 keys to see if any exist that are not in jso1 */
1556 json_object_object_foreachC(jso2, iter)
1557 {
1558 if (!lh_table_lookup_ex(JC_OBJECT(jso1)->c_object, (void *)iter.key,
1559 (void **)(void *)&sub))
1560 return 0;
1561 }
1562
1563 return 1;
1564}
1565
1566int json_object_equal(struct json_object *jso1, struct json_object *jso2)
1567{
1568 if (jso1 == jso2)
1569 return 1;
1570
1571 if (!jso1 || !jso2)
1572 return 0;
1573
1574 if (jso1->o_type != jso2->o_type)
1575 return 0;
1576
1577 switch (jso1->o_type)
1578 {
1579 case json_type_boolean: return (JC_BOOL(jso1)->c_boolean == JC_BOOL(jso2)->c_boolean);
1580
1581 case json_type_double: return (JC_DOUBLE(jso1)->c_double == JC_DOUBLE(jso2)->c_double);
1582
1583 case json_type_int:
1584 {
1585 struct json_object_int *int1 = JC_INT(jso1);
1586 struct json_object_int *int2 = JC_INT(jso2);
1587 if (int1->cint_type == json_object_int_type_int64)
1588 {
1589 if (int2->cint_type == json_object_int_type_int64)
1590 return (int1->cint.c_int64 == int2->cint.c_int64);
1591 if (int1->cint.c_int64 < 0)
1592 return 0;
1593 return ((uint64_t)int1->cint.c_int64 == int2->cint.c_uint64);
1594 }
1595 // else jso1 is a uint64
1596 if (int2->cint_type == json_object_int_type_uint64)
1597 return (int1->cint.c_uint64 == int2->cint.c_uint64);
1598 if (int2->cint.c_int64 < 0)
1599 return 0;
1600 return (int1->cint.c_uint64 == (uint64_t)int2->cint.c_int64);
1601 }
1602
1603 case json_type_string:
1604 {
1605 return (_json_object_get_string_len(JC_STRING(jso1)) ==
1606 _json_object_get_string_len(JC_STRING(jso2)) &&
1607 memcmp(get_string_component(jso1), get_string_component(jso2),
1608 _json_object_get_string_len(JC_STRING(jso1))) == 0);
1609 }
1610
1611 case json_type_object: return json_object_all_values_equal(jso1, jso2);
1612
1613 case json_type_array: return json_array_equal(jso1, jso2);
1614
1615 case json_type_null: return 1;
1616 };
1617
1618 return 0;
1619}
1620
1621static int json_object_copy_serializer_data(struct json_object *src, struct json_object *dst)
1622{
1623 if (!src->_userdata && !src->_user_delete)
1624 return 0;
1625
1626 if (dst->_to_json_string == json_object_userdata_to_json_string ||
1627 dst->_to_json_string == _json_object_userdata_to_json_string)
1628 {
1629 char *p;
1630 assert(src->_userdata);
1631 p = strdup(src->_userdata);
1632 if (p == NULL)
1633 {
1634 _json_c_set_last_err("json_object_copy_serializer_data: out of memory\n");
1635 return -1;
1636 }
1637 dst->_userdata = p;
1638 }
1639 // else if ... other supported serializers ...
1640 else
1641 {
1642 _json_c_set_last_err(
1643 "json_object_copy_serializer_data: unable to copy unknown serializer data: "
1644 "%p\n", (void *)dst->_to_json_string);
1645 return -1;
1646 }
1647 dst->_user_delete = src->_user_delete;
1648 return 0;
1649}
1650
1651/**
1652 * The default shallow copy implementation. Simply creates a new object of the same
1653 * type but does *not* copy over _userdata nor retain any custom serializer.
1654 * If custom serializers are in use, json_object_deep_copy() must be passed a shallow copy
1655 * implementation that is aware of how to copy them.
1656 *
1657 * This always returns -1 or 1. It will never return 2 since it does not copy the serializer.
1658 */
1659int json_c_shallow_copy_default(json_object *src, json_object *parent, const char *key,
1660 size_t index, json_object **dst)
1661{
1662 switch (src->o_type)
1663 {
1664 case json_type_boolean: *dst = json_object_new_boolean(JC_BOOL(src)->c_boolean); break;
1665
1666 case json_type_double: *dst = json_object_new_double(JC_DOUBLE(src)->c_double); break;
1667
1668 case json_type_int:
1669 switch (JC_INT(src)->cint_type)
1670 {
1671 case json_object_int_type_int64:
1672 *dst = json_object_new_int64(JC_INT(src)->cint.c_int64);
1673 break;
1674 case json_object_int_type_uint64:
1675 *dst = json_object_new_uint64(JC_INT(src)->cint.c_uint64);
1676 break;
1677 default: json_abort("invalid cint_type");
1678 }
1679 break;
1680
1681 case json_type_string:
1682 *dst = json_object_new_string_len(get_string_component(src),
1683 _json_object_get_string_len(JC_STRING(src)));
1684 break;
1685
1686 case json_type_object: *dst = json_object_new_object(); break;
1687
1688 case json_type_array: *dst = json_object_new_array(); break;
1689
1690 default: errno = EINVAL; return -1;
1691 }
1692
1693 if (!*dst)
1694 {
1695 errno = ENOMEM;
1696 return -1;
1697 }
1698 (*dst)->_to_json_string = src->_to_json_string;
1699 // _userdata and _user_delete are copied later
1700 return 1;
1701}
1702
1703/*
1704 * The actual guts of json_object_deep_copy(), with a few additional args
1705 * needed so we can keep track of where we are within the object tree.
1706 *
1707 * Note: caller is responsible for freeing *dst if this fails and returns -1.
1708 */
1709static int json_object_deep_copy_recursive(struct json_object *src, struct json_object *parent,
1710 const char *key_in_parent, size_t index_in_parent,
1711 struct json_object **dst,
1712 json_c_shallow_copy_fn *shallow_copy)
1713{
1714 struct json_object_iter iter;
1715 size_t src_array_len, ii;
1716
1717 int shallow_copy_rc = 0;
1718 shallow_copy_rc = shallow_copy(src, parent, key_in_parent, index_in_parent, dst);
1719 /* -1=error, 1=object created ok, 2=userdata set */
1720 if (shallow_copy_rc < 1)
1721 {
1722 errno = EINVAL;
1723 return -1;
1724 }
1725 assert(*dst != NULL);
1726
1727 switch (src->o_type)
1728 {
1729 case json_type_object:
1730 json_object_object_foreachC(src, iter)
1731 {
1732 struct json_object *jso = NULL;
1733 /* This handles the `json_type_null` case */
1734 if (!iter.val)
1735 jso = NULL;
1736 else if (json_object_deep_copy_recursive(iter.val, src, iter.key, UINT_MAX,
1737 &jso, shallow_copy) < 0)
1738 {
1739 json_object_put(jso);
1740 return -1;
1741 }
1742
1743 if (json_object_object_add(*dst, iter.key, jso) < 0)
1744 {
1745 json_object_put(jso);
1746 return -1;
1747 }
1748 }
1749 break;
1750
1751 case json_type_array:
1752 src_array_len = json_object_array_length(src);
1753 for (ii = 0; ii < src_array_len; ii++)
1754 {
1755 struct json_object *jso = NULL;
1756 struct json_object *jso1 = json_object_array_get_idx(src, ii);
1757 /* This handles the `json_type_null` case */
1758 if (!jso1)
1759 jso = NULL;
1760 else if (json_object_deep_copy_recursive(jso1, src, NULL, ii, &jso,
1761 shallow_copy) < 0)
1762 {
1763 json_object_put(jso);
1764 return -1;
1765 }
1766
1767 if (json_object_array_add(*dst, jso) < 0)
1768 {
1769 json_object_put(jso);
1770 return -1;
1771 }
1772 }
1773 break;
1774
1775 default:
1776 break;
1777 /* else, nothing to do, shallow_copy already did. */
1778 }
1779
1780 if (shallow_copy_rc != 2)
1781 return json_object_copy_serializer_data(src, *dst);
1782
1783 return 0;
1784}
1785
1786int json_object_deep_copy(struct json_object *src, struct json_object **dst,
1787 json_c_shallow_copy_fn *shallow_copy)
1788{
1789 int rc;
1790
1791 /* Check if arguments are sane ; *dst must not point to a non-NULL object */
1792 if (!src || !dst || *dst)
1793 {
1794 errno = EINVAL;
1795 return -1;
1796 }
1797
1798 if (shallow_copy == NULL)
1799 shallow_copy = json_c_shallow_copy_default;
1800
1801 rc = json_object_deep_copy_recursive(src, NULL, NULL, UINT_MAX, dst, shallow_copy);
1802 if (rc < 0)
1803 {
1804 json_object_put(*dst);
1805 *dst = NULL;
1806 }
1807
1808 return rc;
1809}
1810
1811static void json_abort(const char *message)
1812{
1813 if (message != NULL)
1814 fprintf(stderr, "json-c aborts with error: %s\n", message);
1815 abort();
1816}