Bump to 0.17
[platform/upstream/json-c.git] / json_object.c
1 /*
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
56 const char *json_number_chars = "0123456789.+-eE"; /* Unused, but part of public API, drop for 1.0 */
57 const char *json_hex_chars = "0123456789abcdefABCDEF";
58
59 static void json_object_generic_delete(struct json_object *jso);
60
61 #if defined(_MSC_VER) && (_MSC_VER <= 1800)
62 /* VS2013 doesn't know about "inline" */
63 #define inline __inline
64 #elif defined(AIX_CC)
65 #define inline
66 #endif
67
68 /* define colors */
69 #define ANSI_COLOR_RESET "\033[0m"
70 #define ANSI_COLOR_FG_GREEN "\033[0;32m"
71 #define ANSI_COLOR_FG_BLUE "\033[0;34m"
72 #define ANSI_COLOR_FG_MAGENTA "\033[0;35m"
73
74 /*
75  * Helper functions to more safely cast to a particular type of json_object
76  */
77 static inline struct json_object_object *JC_OBJECT(struct json_object *jso)
78 {
79         return (void *)jso;
80 }
81 static inline const struct json_object_object *JC_OBJECT_C(const struct json_object *jso)
82 {
83         return (const void *)jso;
84 }
85 static inline struct json_object_array *JC_ARRAY(struct json_object *jso)
86 {
87         return (void *)jso;
88 }
89 static inline const struct json_object_array *JC_ARRAY_C(const struct json_object *jso)
90 {
91         return (const void *)jso;
92 }
93 static inline struct json_object_boolean *JC_BOOL(struct json_object *jso)
94 {
95         return (void *)jso;
96 }
97 static inline const struct json_object_boolean *JC_BOOL_C(const struct json_object *jso)
98 {
99         return (const void *)jso;
100 }
101 static inline struct json_object_double *JC_DOUBLE(struct json_object *jso)
102 {
103         return (void *)jso;
104 }
105 static inline const struct json_object_double *JC_DOUBLE_C(const struct json_object *jso)
106 {
107         return (const void *)jso;
108 }
109 static inline struct json_object_int *JC_INT(struct json_object *jso)
110 {
111         return (void *)jso;
112 }
113 static inline const struct json_object_int *JC_INT_C(const struct json_object *jso)
114 {
115         return (const void *)jso;
116 }
117 static inline struct json_object_string *JC_STRING(struct json_object *jso)
118 {
119         return (void *)jso;
120 }
121 static 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
134 static 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
137 static void json_object_object_delete(struct json_object *jso_base);
138 static void json_object_string_delete(struct json_object *jso);
139 static void json_object_array_delete(struct json_object *jso);
140
141 static json_object_to_json_string_fn json_object_object_to_json_string;
142 static json_object_to_json_string_fn json_object_boolean_to_json_string;
143 static json_object_to_json_string_fn json_object_double_to_json_string_default;
144 static json_object_to_json_string_fn json_object_int_to_json_string;
145 static json_object_to_json_string_fn json_object_string_to_json_string;
146 static json_object_to_json_string_fn json_object_array_to_json_string;
147 static 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  * */
166 JSON_NORETURN static void json_abort(const char *message);
167
168 /* helper for accessing the optimized string data component in json_object
169  */
170 static 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 }
179 static 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
186 static 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
255 struct 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
272 int 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
310 static void json_object_generic_delete(struct json_object *jso)
311 {
312         printbuf_free(jso->_pb);
313         free(jso);
314 }
315
316 static 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
338 int 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
345 enum 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
352 void *json_object_get_userdata(json_object *jso)
353 {
354         return jso ? jso->_userdata : NULL;
355 }
356
357 void 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
372 void 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
408 const 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
434 const 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
441 const 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
446 static 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
463 static 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                 if (flags & JSON_C_TO_STRING_COLOR)
483                         printbuf_strappend(pb, ANSI_COLOR_FG_BLUE);
484
485                 printbuf_strappend(pb, "\"");
486                 json_escape_str(pb, iter.key, strlen(iter.key), flags);
487                 printbuf_strappend(pb, "\"");
488
489                 if (flags & JSON_C_TO_STRING_COLOR)
490                         printbuf_strappend(pb, ANSI_COLOR_RESET);
491
492                 if (flags & JSON_C_TO_STRING_SPACED)
493                         printbuf_strappend(pb, ": ");
494                 else
495                         printbuf_strappend(pb, ":");
496
497                 if (iter.val == NULL) {
498                         if (flags & JSON_C_TO_STRING_COLOR)
499                                 printbuf_strappend(pb, ANSI_COLOR_FG_MAGENTA);
500                         printbuf_strappend(pb, "null");
501                         if (flags & JSON_C_TO_STRING_COLOR)
502                                 printbuf_strappend(pb, ANSI_COLOR_RESET);
503                 } else if (iter.val->_to_json_string(iter.val, pb, level + 1, flags) < 0)
504                         return -1;
505         }
506         if ((flags & JSON_C_TO_STRING_PRETTY) && had_children)
507         {
508                 printbuf_strappend(pb, "\n");
509                 indent(pb, level, flags);
510         }
511         if (flags & JSON_C_TO_STRING_SPACED && !(flags & JSON_C_TO_STRING_PRETTY))
512                 return printbuf_strappend(pb, /*{*/ " }");
513         else
514                 return printbuf_strappend(pb, /*{*/ "}");
515 }
516
517 static void json_object_lh_entry_free(struct lh_entry *ent)
518 {
519         if (!lh_entry_k_is_constant(ent))
520                 free(lh_entry_k(ent));
521         json_object_put((struct json_object *)lh_entry_v(ent));
522 }
523
524 static void json_object_object_delete(struct json_object *jso_base)
525 {
526         lh_table_free(JC_OBJECT(jso_base)->c_object);
527         json_object_generic_delete(jso_base);
528 }
529
530 struct json_object *json_object_new_object(void)
531 {
532         struct json_object_object *jso = JSON_OBJECT_NEW(object);
533         if (!jso)
534                 return NULL;
535         jso->c_object =
536             lh_kchar_table_new(JSON_OBJECT_DEF_HASH_ENTRIES, &json_object_lh_entry_free);
537         if (!jso->c_object)
538         {
539                 json_object_generic_delete(&jso->base);
540                 errno = ENOMEM;
541                 return NULL;
542         }
543         return &jso->base;
544 }
545
546 struct lh_table *json_object_get_object(const struct json_object *jso)
547 {
548         if (!jso)
549                 return NULL;
550         switch (jso->o_type)
551         {
552         case json_type_object: return JC_OBJECT_C(jso)->c_object;
553         default: return NULL;
554         }
555 }
556
557 int json_object_object_add_ex(struct json_object *jso, const char *const key,
558                               struct json_object *const val, const unsigned opts)
559 {
560         struct json_object *existing_value = NULL;
561         struct lh_entry *existing_entry;
562         unsigned long hash;
563
564         assert(json_object_get_type(jso) == json_type_object);
565
566         // We lookup the entry and replace the value, rather than just deleting
567         // and re-adding it, so the existing key remains valid.
568         hash = lh_get_hash(JC_OBJECT(jso)->c_object, (const void *)key);
569         existing_entry =
570             (opts & JSON_C_OBJECT_ADD_KEY_IS_NEW)
571                 ? NULL
572                 : lh_table_lookup_entry_w_hash(JC_OBJECT(jso)->c_object, (const void *)key, hash);
573
574         // The caller must avoid creating loops in the object tree, but do a
575         // quick check anyway to make sure we're not creating a trivial loop.
576         if (jso == val)
577                 return -1;
578
579         if (!existing_entry)
580         {
581                 const void *const k =
582                     (opts & JSON_C_OBJECT_ADD_CONSTANT_KEY) ? (const void *)key : strdup(key);
583                 if (k == NULL)
584                         return -1;
585                 return lh_table_insert_w_hash(JC_OBJECT(jso)->c_object, k, val, hash, opts);
586         }
587         existing_value = (json_object *)lh_entry_v(existing_entry);
588         if (existing_value)
589                 json_object_put(existing_value);
590         lh_entry_set_val(existing_entry, val);
591         return 0;
592 }
593
594 int json_object_object_add(struct json_object *jso, const char *key, struct json_object *val)
595 {
596         return json_object_object_add_ex(jso, key, val, 0);
597 }
598
599 int json_object_object_length(const struct json_object *jso)
600 {
601         assert(json_object_get_type(jso) == json_type_object);
602         return lh_table_length(JC_OBJECT_C(jso)->c_object);
603 }
604
605 size_t json_c_object_sizeof(void)
606 {
607         return sizeof(struct json_object);
608 }
609
610 struct json_object *json_object_object_get(const struct json_object *jso, const char *key)
611 {
612         struct json_object *result = NULL;
613         json_object_object_get_ex(jso, key, &result);
614         return result;
615 }
616
617 json_bool json_object_object_get_ex(const struct json_object *jso, const char *key,
618                                     struct json_object **value)
619 {
620         if (value != NULL)
621                 *value = NULL;
622
623         if (NULL == jso)
624                 return 0;
625
626         switch (jso->o_type)
627         {
628         case json_type_object:
629                 return lh_table_lookup_ex(JC_OBJECT_C(jso)->c_object, (const void *)key,
630                                           (void **)value);
631         default:
632                 if (value != NULL)
633                         *value = NULL;
634                 return 0;
635         }
636 }
637
638 void json_object_object_del(struct json_object *jso, const char *key)
639 {
640         assert(json_object_get_type(jso) == json_type_object);
641         lh_table_delete(JC_OBJECT(jso)->c_object, key);
642 }
643
644 /* json_object_boolean */
645
646 static int json_object_boolean_to_json_string(struct json_object *jso, struct printbuf *pb,
647                                               int level, int flags)
648 {
649         int ret;
650
651         if (flags & JSON_C_TO_STRING_COLOR)
652                 printbuf_strappend(pb, ANSI_COLOR_FG_MAGENTA);
653
654         if (JC_BOOL(jso)->c_boolean)
655                 ret = printbuf_strappend(pb, "true");
656         else
657                 ret = printbuf_strappend(pb, "false");
658         if (ret > -1 && flags & JSON_C_TO_STRING_COLOR)
659                 return printbuf_strappend(pb, ANSI_COLOR_RESET);
660         return ret;
661 }
662
663 struct json_object *json_object_new_boolean(json_bool b)
664 {
665         struct json_object_boolean *jso = JSON_OBJECT_NEW(boolean);
666         if (!jso)
667                 return NULL;
668         jso->c_boolean = b;
669         return &jso->base;
670 }
671
672 json_bool json_object_get_boolean(const struct json_object *jso)
673 {
674         if (!jso)
675                 return 0;
676         switch (jso->o_type)
677         {
678         case json_type_boolean: return JC_BOOL_C(jso)->c_boolean;
679         case json_type_int:
680                 switch (JC_INT_C(jso)->cint_type)
681                 {
682                 case json_object_int_type_int64: return (JC_INT_C(jso)->cint.c_int64 != 0);
683                 case json_object_int_type_uint64: return (JC_INT_C(jso)->cint.c_uint64 != 0);
684                 default: json_abort("invalid cint_type");
685                 }
686         case json_type_double: return (JC_DOUBLE_C(jso)->c_double != 0);
687         case json_type_string: return (JC_STRING_C(jso)->len != 0);
688         default: return 0;
689         }
690 }
691
692 int json_object_set_boolean(struct json_object *jso, json_bool new_value)
693 {
694         if (!jso || jso->o_type != json_type_boolean)
695                 return 0;
696         JC_BOOL(jso)->c_boolean = new_value;
697         return 1;
698 }
699
700 /* json_object_int */
701
702 static int json_object_int_to_json_string(struct json_object *jso, struct printbuf *pb, int level,
703                                           int flags)
704 {
705         /* room for 19 digits, the sign char, and a null term */
706         char sbuf[21];
707         if (JC_INT(jso)->cint_type == json_object_int_type_int64)
708                 snprintf(sbuf, sizeof(sbuf), "%" PRId64, JC_INT(jso)->cint.c_int64);
709         else
710                 snprintf(sbuf, sizeof(sbuf), "%" PRIu64, JC_INT(jso)->cint.c_uint64);
711         return printbuf_memappend(pb, sbuf, strlen(sbuf));
712 }
713
714 struct json_object *json_object_new_int(int32_t i)
715 {
716         return json_object_new_int64(i);
717 }
718
719 int32_t json_object_get_int(const struct json_object *jso)
720 {
721         int64_t cint64 = 0;
722         double cdouble;
723         enum json_type o_type;
724
725         if (!jso)
726                 return 0;
727
728         o_type = jso->o_type;
729         if (o_type == json_type_int)
730         {
731                 const struct json_object_int *jsoint = JC_INT_C(jso);
732                 if (jsoint->cint_type == json_object_int_type_int64)
733                 {
734                         cint64 = jsoint->cint.c_int64;
735                 }
736                 else
737                 {
738                         if (jsoint->cint.c_uint64 >= INT64_MAX)
739                                 cint64 = INT64_MAX;
740                         else
741                                 cint64 = (int64_t)jsoint->cint.c_uint64;
742                 }
743         }
744         else if (o_type == json_type_string)
745         {
746                 /*
747                  * Parse strings into 64-bit numbers, then use the
748                  * 64-to-32-bit number handling below.
749                  */
750                 if (json_parse_int64(get_string_component(jso), &cint64) != 0)
751                         return 0; /* whoops, it didn't work. */
752                 o_type = json_type_int;
753         }
754
755         switch (o_type)
756         {
757         case json_type_int:
758                 /* Make sure we return the correct values for out of range numbers. */
759                 if (cint64 <= INT32_MIN)
760                         return INT32_MIN;
761                 if (cint64 >= INT32_MAX)
762                         return INT32_MAX;
763                 return (int32_t)cint64;
764         case json_type_double:
765                 cdouble = JC_DOUBLE_C(jso)->c_double;
766                 if (cdouble <= INT32_MIN)
767                         return INT32_MIN;
768                 if (cdouble >= INT32_MAX)
769                         return INT32_MAX;
770                 return (int32_t)cdouble;
771         case json_type_boolean: return JC_BOOL_C(jso)->c_boolean;
772         default: return 0;
773         }
774 }
775
776 int json_object_set_int(struct json_object *jso, int new_value)
777 {
778         return json_object_set_int64(jso, (int64_t)new_value);
779 }
780
781 struct json_object *json_object_new_int64(int64_t i)
782 {
783         struct json_object_int *jso = JSON_OBJECT_NEW(int);
784         if (!jso)
785                 return NULL;
786         jso->cint.c_int64 = i;
787         jso->cint_type = json_object_int_type_int64;
788         return &jso->base;
789 }
790
791 struct json_object *json_object_new_uint64(uint64_t i)
792 {
793         struct json_object_int *jso = JSON_OBJECT_NEW(int);
794         if (!jso)
795                 return NULL;
796         jso->cint.c_uint64 = i;
797         jso->cint_type = json_object_int_type_uint64;
798         return &jso->base;
799 }
800
801 int64_t json_object_get_int64(const struct json_object *jso)
802 {
803         int64_t cint;
804
805         if (!jso)
806                 return 0;
807         switch (jso->o_type)
808         {
809         case json_type_int:
810         {
811                 const struct json_object_int *jsoint = JC_INT_C(jso);
812                 switch (jsoint->cint_type)
813                 {
814                 case json_object_int_type_int64: return jsoint->cint.c_int64;
815                 case json_object_int_type_uint64:
816                         if (jsoint->cint.c_uint64 >= INT64_MAX)
817                                 return INT64_MAX;
818                         return (int64_t)jsoint->cint.c_uint64;
819                 default: json_abort("invalid cint_type");
820                 }
821         }
822         case json_type_double:
823                 // INT64_MAX can't be exactly represented as a double
824                 // so cast to tell the compiler it's ok to round up.
825                 if (JC_DOUBLE_C(jso)->c_double >= (double)INT64_MAX)
826                         return INT64_MAX;
827                 if (JC_DOUBLE_C(jso)->c_double <= INT64_MIN)
828                         return INT64_MIN;
829                 return (int64_t)JC_DOUBLE_C(jso)->c_double;
830         case json_type_boolean: return JC_BOOL_C(jso)->c_boolean;
831         case json_type_string:
832                 if (json_parse_int64(get_string_component(jso), &cint) == 0)
833                         return cint;
834                 /* FALLTHRU */
835         default: return 0;
836         }
837 }
838
839 uint64_t json_object_get_uint64(const struct json_object *jso)
840 {
841         uint64_t cuint;
842
843         if (!jso)
844                 return 0;
845         switch (jso->o_type)
846         {
847         case json_type_int:
848         {
849                 const struct json_object_int *jsoint = JC_INT_C(jso);
850                 switch (jsoint->cint_type)
851                 {
852                 case json_object_int_type_int64:
853                         if (jsoint->cint.c_int64 < 0)
854                                 return 0;
855                         return (uint64_t)jsoint->cint.c_int64;
856                 case json_object_int_type_uint64: return jsoint->cint.c_uint64;
857                 default: json_abort("invalid cint_type");
858                 }
859         }
860         case json_type_double:
861                 // UINT64_MAX can't be exactly represented as a double
862                 // so cast to tell the compiler it's ok to round up.
863                 if (JC_DOUBLE_C(jso)->c_double >= (double)UINT64_MAX)
864                         return UINT64_MAX;
865                 if (JC_DOUBLE_C(jso)->c_double < 0)
866                         return 0;
867                 return (uint64_t)JC_DOUBLE_C(jso)->c_double;
868         case json_type_boolean: return JC_BOOL_C(jso)->c_boolean;
869         case json_type_string:
870                 if (json_parse_uint64(get_string_component(jso), &cuint) == 0)
871                         return cuint;
872                 /* FALLTHRU */
873         default: return 0;
874         }
875 }
876
877 int json_object_set_int64(struct json_object *jso, int64_t new_value)
878 {
879         if (!jso || jso->o_type != json_type_int)
880                 return 0;
881         JC_INT(jso)->cint.c_int64 = new_value;
882         JC_INT(jso)->cint_type = json_object_int_type_int64;
883         return 1;
884 }
885
886 int json_object_set_uint64(struct json_object *jso, uint64_t new_value)
887 {
888         if (!jso || jso->o_type != json_type_int)
889                 return 0;
890         JC_INT(jso)->cint.c_uint64 = new_value;
891         JC_INT(jso)->cint_type = json_object_int_type_uint64;
892         return 1;
893 }
894
895 int json_object_int_inc(struct json_object *jso, int64_t val)
896 {
897         struct json_object_int *jsoint;
898         if (!jso || jso->o_type != json_type_int)
899                 return 0;
900         jsoint = JC_INT(jso);
901         switch (jsoint->cint_type)
902         {
903         case json_object_int_type_int64:
904                 if (val > 0 && jsoint->cint.c_int64 > INT64_MAX - val)
905                 {
906                         jsoint->cint.c_uint64 = (uint64_t)jsoint->cint.c_int64 + (uint64_t)val;
907                         jsoint->cint_type = json_object_int_type_uint64;
908                 }
909                 else if (val < 0 && jsoint->cint.c_int64 < INT64_MIN - val)
910                 {
911                         jsoint->cint.c_int64 = INT64_MIN;
912                 }
913                 else
914                 {
915                         jsoint->cint.c_int64 += val;
916                 }
917                 return 1;
918         case json_object_int_type_uint64:
919                 if (val > 0 && jsoint->cint.c_uint64 > UINT64_MAX - (uint64_t)val)
920                 {
921                         jsoint->cint.c_uint64 = UINT64_MAX;
922                 }
923                 else if (val < 0 && jsoint->cint.c_uint64 < (uint64_t)(-val))
924                 {
925                         jsoint->cint.c_int64 = (int64_t)jsoint->cint.c_uint64 + val;
926                         jsoint->cint_type = json_object_int_type_int64;
927                 }
928                 else if (val < 0 && jsoint->cint.c_uint64 >= (uint64_t)(-val))
929                 {
930                         jsoint->cint.c_uint64 -= (uint64_t)(-val);
931                 }
932                 else
933                 {
934                         jsoint->cint.c_uint64 += val;
935                 }
936                 return 1;
937         default: json_abort("invalid cint_type");
938         }
939 }
940
941 /* json_object_double */
942
943 #if defined(HAVE___THREAD)
944 // i.e. __thread or __declspec(thread)
945 static SPEC___THREAD char *tls_serialization_float_format = NULL;
946 #endif
947 static char *global_serialization_float_format = NULL;
948
949 int json_c_set_serialization_double_format(const char *double_format, int global_or_thread)
950 {
951         if (global_or_thread == JSON_C_OPTION_GLOBAL)
952         {
953 #if defined(HAVE___THREAD)
954                 if (tls_serialization_float_format)
955                 {
956                         free(tls_serialization_float_format);
957                         tls_serialization_float_format = NULL;
958                 }
959 #endif
960                 if (global_serialization_float_format)
961                         free(global_serialization_float_format);
962                 if (double_format)
963                 {
964                         char *p = strdup(double_format);
965                         if (p == NULL)
966                         {
967                                 _json_c_set_last_err("json_c_set_serialization_double_format: "
968                                                      "out of memory\n");
969                                 return -1;
970                         }
971                         global_serialization_float_format = p;
972                 }
973                 else
974                 {
975                         global_serialization_float_format = NULL;
976                 }
977         }
978         else if (global_or_thread == JSON_C_OPTION_THREAD)
979         {
980 #if defined(HAVE___THREAD)
981                 if (tls_serialization_float_format)
982                 {
983                         free(tls_serialization_float_format);
984                         tls_serialization_float_format = NULL;
985                 }
986                 if (double_format)
987                 {
988                         char *p = strdup(double_format);
989                         if (p == NULL)
990                         {
991                                 _json_c_set_last_err("json_c_set_serialization_double_format: "
992                                                      "out of memory\n");
993                                 return -1;
994                         }
995                         tls_serialization_float_format = p;
996                 }
997                 else
998                 {
999                         tls_serialization_float_format = NULL;
1000                 }
1001 #else
1002                 _json_c_set_last_err("json_c_set_serialization_double_format: not compiled "
1003                                      "with __thread support\n");
1004                 return -1;
1005 #endif
1006         }
1007         else
1008         {
1009                 _json_c_set_last_err("json_c_set_serialization_double_format: invalid "
1010                                      "global_or_thread value: %d\n", global_or_thread);
1011                 return -1;
1012         }
1013         return 0;
1014 }
1015
1016 static int json_object_double_to_json_string_format(struct json_object *jso, struct printbuf *pb,
1017                                                     int level, int flags, const char *format)
1018 {
1019         struct json_object_double *jsodbl = JC_DOUBLE(jso);
1020         char buf[128], *p, *q;
1021         int size;
1022         /* Although JSON RFC does not support
1023          * NaN or Infinity as numeric values
1024          * ECMA 262 section 9.8.1 defines
1025          * how to handle these cases as strings
1026          */
1027         if (isnan(jsodbl->c_double))
1028         {
1029                 size = snprintf(buf, sizeof(buf), "NaN");
1030         }
1031         else if (isinf(jsodbl->c_double))
1032         {
1033                 if (jsodbl->c_double > 0)
1034                         size = snprintf(buf, sizeof(buf), "Infinity");
1035                 else
1036                         size = snprintf(buf, sizeof(buf), "-Infinity");
1037         }
1038         else
1039         {
1040                 const char *std_format = "%.17g";
1041                 int format_drops_decimals = 0;
1042                 int looks_numeric = 0;
1043
1044                 if (!format)
1045                 {
1046 #if defined(HAVE___THREAD)
1047                         if (tls_serialization_float_format)
1048                                 format = tls_serialization_float_format;
1049                         else
1050 #endif
1051                             if (global_serialization_float_format)
1052                                 format = global_serialization_float_format;
1053                         else
1054                                 format = std_format;
1055                 }
1056                 size = snprintf(buf, sizeof(buf), format, jsodbl->c_double);
1057
1058                 if (size < 0)
1059                         return -1;
1060
1061                 p = strchr(buf, ',');
1062                 if (p)
1063                         *p = '.';
1064                 else
1065                         p = strchr(buf, '.');
1066
1067                 if (format == std_format || strstr(format, ".0f") == NULL)
1068                         format_drops_decimals = 1;
1069
1070                 looks_numeric = /* Looks like *some* kind of number */
1071                     is_plain_digit(buf[0]) || (size > 1 && buf[0] == '-' && is_plain_digit(buf[1]));
1072
1073                 if (size < (int)sizeof(buf) - 2 && looks_numeric && !p && /* Has no decimal point */
1074                     strchr(buf, 'e') == NULL && /* Not scientific notation */
1075                     format_drops_decimals)
1076                 {
1077                         // Ensure it looks like a float, even if snprintf didn't,
1078                         //  unless a custom format is set to omit the decimal.
1079                         strcat(buf, ".0");
1080                         size += 2;
1081                 }
1082                 if (p && (flags & JSON_C_TO_STRING_NOZERO))
1083                 {
1084                         /* last useful digit, always keep 1 zero */
1085                         p++;
1086                         for (q = p; *q; q++)
1087                         {
1088                                 if (*q != '0')
1089                                         p = q;
1090                         }
1091                         /* drop trailing zeroes */
1092                         if (*p != 0)
1093                                 *(++p) = 0;
1094                         size = p - buf;
1095                 }
1096         }
1097         // although unlikely, snprintf can fail
1098         if (size < 0)
1099                 return -1;
1100
1101         if (size >= (int)sizeof(buf))
1102                 // The standard formats are guaranteed not to overrun the buffer,
1103                 // but if a custom one happens to do so, just silently truncate.
1104                 size = sizeof(buf) - 1;
1105         printbuf_memappend(pb, buf, size);
1106         return size;
1107 }
1108
1109 static int json_object_double_to_json_string_default(struct json_object *jso, struct printbuf *pb,
1110                                                      int level, int flags)
1111 {
1112         return json_object_double_to_json_string_format(jso, pb, level, flags, NULL);
1113 }
1114
1115 int json_object_double_to_json_string(struct json_object *jso, struct printbuf *pb, int level,
1116                                       int flags)
1117 {
1118         return json_object_double_to_json_string_format(jso, pb, level, flags,
1119                                                         (const char *)jso->_userdata);
1120 }
1121
1122 struct json_object *json_object_new_double(double d)
1123 {
1124         struct json_object_double *jso = JSON_OBJECT_NEW(double);
1125         if (!jso)
1126                 return NULL;
1127         jso->base._to_json_string = &json_object_double_to_json_string_default;
1128         jso->c_double = d;
1129         return &jso->base;
1130 }
1131
1132 struct json_object *json_object_new_double_s(double d, const char *ds)
1133 {
1134         char *new_ds;
1135         struct json_object *jso = json_object_new_double(d);
1136         if (!jso)
1137                 return NULL;
1138
1139         new_ds = strdup(ds);
1140         if (!new_ds)
1141         {
1142                 json_object_generic_delete(jso);
1143                 errno = ENOMEM;
1144                 return NULL;
1145         }
1146         json_object_set_serializer(jso, _json_object_userdata_to_json_string, new_ds,
1147                                    json_object_free_userdata);
1148         return jso;
1149 }
1150
1151 /*
1152  * A wrapper around json_object_userdata_to_json_string() used only
1153  * by json_object_new_double_s() just so json_object_set_double() can
1154  * detect when it needs to reset the serializer to the default.
1155  */
1156 static int _json_object_userdata_to_json_string(struct json_object *jso, struct printbuf *pb,
1157                                                 int level, int flags)
1158 {
1159         return json_object_userdata_to_json_string(jso, pb, level, flags);
1160 }
1161
1162 int json_object_userdata_to_json_string(struct json_object *jso, struct printbuf *pb, int level,
1163                                         int flags)
1164 {
1165         int userdata_len = strlen((const char *)jso->_userdata);
1166         printbuf_memappend(pb, (const char *)jso->_userdata, userdata_len);
1167         return userdata_len;
1168 }
1169
1170 void json_object_free_userdata(struct json_object *jso, void *userdata)
1171 {
1172         free(userdata);
1173 }
1174
1175 double json_object_get_double(const struct json_object *jso)
1176 {
1177         double cdouble;
1178         char *errPtr = NULL;
1179
1180         if (!jso)
1181                 return 0.0;
1182         switch (jso->o_type)
1183         {
1184         case json_type_double: return JC_DOUBLE_C(jso)->c_double;
1185         case json_type_int:
1186                 switch (JC_INT_C(jso)->cint_type)
1187                 {
1188                 case json_object_int_type_int64: return JC_INT_C(jso)->cint.c_int64;
1189                 case json_object_int_type_uint64: return JC_INT_C(jso)->cint.c_uint64;
1190                 default: json_abort("invalid cint_type");
1191                 }
1192         case json_type_boolean: return JC_BOOL_C(jso)->c_boolean;
1193         case json_type_string:
1194                 errno = 0;
1195                 cdouble = strtod(get_string_component(jso), &errPtr);
1196
1197                 /* if conversion stopped at the first character, return 0.0 */
1198                 if (errPtr == get_string_component(jso))
1199                 {
1200                         errno = EINVAL;
1201                         return 0.0;
1202                 }
1203
1204                 /*
1205                  * Check that the conversion terminated on something sensible
1206                  *
1207                  * For example, { "pay" : 123AB } would parse as 123.
1208                  */
1209                 if (*errPtr != '\0')
1210                 {
1211                         errno = EINVAL;
1212                         return 0.0;
1213                 }
1214
1215                 /*
1216                  * If strtod encounters a string which would exceed the
1217                  * capacity of a double, it returns +/- HUGE_VAL and sets
1218                  * errno to ERANGE. But +/- HUGE_VAL is also a valid result
1219                  * from a conversion, so we need to check errno.
1220                  *
1221                  * Underflow also sets errno to ERANGE, but it returns 0 in
1222                  * that case, which is what we will return anyway.
1223                  *
1224                  * See CERT guideline ERR30-C
1225                  */
1226                 if ((HUGE_VAL == cdouble || -HUGE_VAL == cdouble) && (ERANGE == errno))
1227                         cdouble = 0.0;
1228                 return cdouble;
1229         default: errno = EINVAL; return 0.0;
1230         }
1231 }
1232
1233 int json_object_set_double(struct json_object *jso, double new_value)
1234 {
1235         if (!jso || jso->o_type != json_type_double)
1236                 return 0;
1237         JC_DOUBLE(jso)->c_double = new_value;
1238         if (jso->_to_json_string == &_json_object_userdata_to_json_string)
1239                 json_object_set_serializer(jso, NULL, NULL, NULL);
1240         return 1;
1241 }
1242
1243 /* json_object_string */
1244
1245 static int json_object_string_to_json_string(struct json_object *jso, struct printbuf *pb,
1246                                              int level, int flags)
1247 {
1248         ssize_t len = JC_STRING(jso)->len;
1249         if (flags & JSON_C_TO_STRING_COLOR)
1250                 printbuf_strappend(pb, ANSI_COLOR_FG_GREEN);
1251         printbuf_strappend(pb, "\"");
1252         json_escape_str(pb, get_string_component(jso), len < 0 ? -(ssize_t)len : len, flags);
1253         printbuf_strappend(pb, "\"");
1254         if (flags & JSON_C_TO_STRING_COLOR)
1255                 printbuf_strappend(pb, ANSI_COLOR_RESET);
1256         return 0;
1257 }
1258
1259 static void json_object_string_delete(struct json_object *jso)
1260 {
1261         if (JC_STRING(jso)->len < 0)
1262                 free(JC_STRING(jso)->c_string.pdata);
1263         json_object_generic_delete(jso);
1264 }
1265
1266 static struct json_object *_json_object_new_string(const char *s, const size_t len)
1267 {
1268         size_t objsize;
1269         struct json_object_string *jso;
1270
1271         /*
1272          * Structures           Actual memory layout
1273          * -------------------  --------------------
1274          * [json_object_string  [json_object_string
1275          *  [json_object]        [json_object]
1276          *  ...other fields...   ...other fields...
1277          *  c_string]            len
1278          *                       bytes
1279          *                       of
1280          *                       string
1281          *                       data
1282          *                       \0]
1283          */
1284         if (len > (SSIZE_T_MAX - (sizeof(*jso) - sizeof(jso->c_string)) - 1))
1285                 return NULL;
1286         objsize = (sizeof(*jso) - sizeof(jso->c_string)) + len + 1;
1287         if (len < sizeof(void *))
1288                 // We need a minimum size to support json_object_set_string() mutability
1289                 // so we can stuff a pointer into pdata :(
1290                 objsize += sizeof(void *) - len;
1291
1292         jso = (struct json_object_string *)json_object_new(json_type_string, objsize,
1293                                                            &json_object_string_to_json_string);
1294
1295         if (!jso)
1296                 return NULL;
1297         jso->len = len;
1298         memcpy(jso->c_string.idata, s, len);
1299         // Cast below needed for Clang UB sanitizer
1300         ((char *)jso->c_string.idata)[len] = '\0';
1301         return &jso->base;
1302 }
1303
1304 struct json_object *json_object_new_string(const char *s)
1305 {
1306         return _json_object_new_string(s, strlen(s));
1307 }
1308
1309 struct json_object *json_object_new_string_len(const char *s, const int len)
1310 {
1311         return _json_object_new_string(s, len);
1312 }
1313
1314 const char *json_object_get_string(struct json_object *jso)
1315 {
1316         if (!jso)
1317                 return NULL;
1318         switch (jso->o_type)
1319         {
1320         case json_type_string: return get_string_component(jso);
1321         default: return json_object_to_json_string(jso);
1322         }
1323 }
1324
1325 static inline ssize_t _json_object_get_string_len(const struct json_object_string *jso)
1326 {
1327         ssize_t len;
1328         len = jso->len;
1329         return (len < 0) ? -(ssize_t)len : len;
1330 }
1331 int json_object_get_string_len(const struct json_object *jso)
1332 {
1333         if (!jso)
1334                 return 0;
1335         switch (jso->o_type)
1336         {
1337         case json_type_string: return _json_object_get_string_len(JC_STRING_C(jso));
1338         default: return 0;
1339         }
1340 }
1341
1342 static int _json_object_set_string_len(json_object *jso, const char *s, size_t len)
1343 {
1344         char *dstbuf;
1345         ssize_t curlen;
1346         ssize_t newlen;
1347         if (jso == NULL || jso->o_type != json_type_string)
1348                 return 0;
1349
1350         if (len >= INT_MAX - 1)
1351                 // jso->len is a signed ssize_t, so it can't hold the
1352                 // full size_t range. json_object_get_string_len returns
1353                 // length as int, cap length at INT_MAX.
1354                 return 0;
1355
1356         curlen = JC_STRING(jso)->len;
1357         if (curlen < 0) {
1358                 if (len == 0) {
1359                         free(JC_STRING(jso)->c_string.pdata);
1360                         JC_STRING(jso)->len = curlen = 0;
1361                 } else {
1362                         curlen = -curlen;
1363                 }
1364         }
1365
1366         newlen = len;
1367         dstbuf = get_string_component_mutable(jso);
1368
1369         if ((ssize_t)len > curlen)
1370         {
1371                 // We have no way to return the new ptr from realloc(jso, newlen)
1372                 // and we have no way of knowing whether there's extra room available
1373                 // so we need to stuff a pointer in to pdata :(
1374                 dstbuf = (char *)malloc(len + 1);
1375                 if (dstbuf == NULL)
1376                         return 0;
1377                 if (JC_STRING(jso)->len < 0)
1378                         free(JC_STRING(jso)->c_string.pdata);
1379                 JC_STRING(jso)->c_string.pdata = dstbuf;
1380                 newlen = -(ssize_t)len;
1381         }
1382         else if (JC_STRING(jso)->len < 0)
1383         {
1384                 // We've got enough room in the separate allocated buffer,
1385                 // so use it as-is and continue to indicate that pdata is used.
1386                 newlen = -(ssize_t)len;
1387         }
1388
1389         memcpy(dstbuf, (const void *)s, len);
1390         dstbuf[len] = '\0';
1391         JC_STRING(jso)->len = newlen;
1392         return 1;
1393 }
1394
1395 int json_object_set_string(json_object *jso, const char *s)
1396 {
1397         return _json_object_set_string_len(jso, s, strlen(s));
1398 }
1399
1400 int json_object_set_string_len(json_object *jso, const char *s, int len)
1401 {
1402         return _json_object_set_string_len(jso, s, len);
1403 }
1404
1405 /* json_object_array */
1406
1407 static int json_object_array_to_json_string(struct json_object *jso, struct printbuf *pb, int level,
1408                                             int flags)
1409 {
1410         int had_children = 0;
1411         size_t ii;
1412
1413         printbuf_strappend(pb, "[");
1414         for (ii = 0; ii < json_object_array_length(jso); ii++)
1415         {
1416                 struct json_object *val;
1417                 if (had_children)
1418                 {
1419                         printbuf_strappend(pb, ",");
1420                 }
1421                 if (flags & JSON_C_TO_STRING_PRETTY)
1422                         printbuf_strappend(pb, "\n");
1423                 had_children = 1;
1424                 if (flags & JSON_C_TO_STRING_SPACED && !(flags & JSON_C_TO_STRING_PRETTY))
1425                         printbuf_strappend(pb, " ");
1426                 indent(pb, level + 1, flags);
1427                 val = json_object_array_get_idx(jso, ii);
1428                 if (val == NULL) {
1429
1430                         if (flags & JSON_C_TO_STRING_COLOR)
1431                                 printbuf_strappend(pb, ANSI_COLOR_FG_MAGENTA);
1432                         printbuf_strappend(pb, "null");
1433                         if (flags & JSON_C_TO_STRING_COLOR)
1434                                 printbuf_strappend(pb, ANSI_COLOR_RESET);
1435
1436                 } else if (val->_to_json_string(val, pb, level + 1, flags) < 0)
1437                         return -1;
1438         }
1439         if ((flags & JSON_C_TO_STRING_PRETTY) && had_children)
1440         {
1441                 printbuf_strappend(pb, "\n");
1442                 indent(pb, level, flags);
1443         }
1444
1445         if (flags & JSON_C_TO_STRING_SPACED && !(flags & JSON_C_TO_STRING_PRETTY))
1446                 return printbuf_strappend(pb, " ]");
1447         return printbuf_strappend(pb, "]");
1448 }
1449
1450 static void json_object_array_entry_free(void *data)
1451 {
1452         json_object_put((struct json_object *)data);
1453 }
1454
1455 static void json_object_array_delete(struct json_object *jso)
1456 {
1457         array_list_free(JC_ARRAY(jso)->c_array);
1458         json_object_generic_delete(jso);
1459 }
1460
1461 struct json_object *json_object_new_array(void)
1462 {
1463         return json_object_new_array_ext(ARRAY_LIST_DEFAULT_SIZE);
1464 }
1465 struct json_object *json_object_new_array_ext(int initial_size)
1466 {
1467         struct json_object_array *jso = JSON_OBJECT_NEW(array);
1468         if (!jso)
1469                 return NULL;
1470         jso->c_array = array_list_new2(&json_object_array_entry_free, initial_size);
1471         if (jso->c_array == NULL)
1472         {
1473                 free(jso);
1474                 return NULL;
1475         }
1476         return &jso->base;
1477 }
1478
1479 struct array_list *json_object_get_array(const struct json_object *jso)
1480 {
1481         if (!jso)
1482                 return NULL;
1483         switch (jso->o_type)
1484         {
1485         case json_type_array: return JC_ARRAY_C(jso)->c_array;
1486         default: return NULL;
1487         }
1488 }
1489
1490 void json_object_array_sort(struct json_object *jso, int (*sort_fn)(const void *, const void *))
1491 {
1492         assert(json_object_get_type(jso) == json_type_array);
1493         array_list_sort(JC_ARRAY(jso)->c_array, sort_fn);
1494 }
1495
1496 struct json_object *json_object_array_bsearch(const struct json_object *key,
1497                                               const struct json_object *jso,
1498                                               int (*sort_fn)(const void *, const void *))
1499 {
1500         struct json_object **result;
1501
1502         assert(json_object_get_type(jso) == json_type_array);
1503         result = (struct json_object **)array_list_bsearch((const void **)(void *)&key,
1504                                                            JC_ARRAY_C(jso)->c_array, sort_fn);
1505
1506         if (!result)
1507                 return NULL;
1508         return *result;
1509 }
1510
1511 size_t json_object_array_length(const struct json_object *jso)
1512 {
1513         assert(json_object_get_type(jso) == json_type_array);
1514         return array_list_length(JC_ARRAY_C(jso)->c_array);
1515 }
1516
1517 int json_object_array_add(struct json_object *jso, struct json_object *val)
1518 {
1519         assert(json_object_get_type(jso) == json_type_array);
1520         return array_list_add(JC_ARRAY(jso)->c_array, val);
1521 }
1522
1523 int json_object_array_insert_idx(struct json_object *jso, size_t idx, struct json_object *val)
1524 {
1525         assert(json_object_get_type(jso) == json_type_array);
1526         return array_list_insert_idx(JC_ARRAY(jso)->c_array, idx, val);
1527 }
1528
1529 int json_object_array_put_idx(struct json_object *jso, size_t idx, struct json_object *val)
1530 {
1531         assert(json_object_get_type(jso) == json_type_array);
1532         return array_list_put_idx(JC_ARRAY(jso)->c_array, idx, val);
1533 }
1534
1535 int json_object_array_del_idx(struct json_object *jso, size_t idx, size_t count)
1536 {
1537         assert(json_object_get_type(jso) == json_type_array);
1538         return array_list_del_idx(JC_ARRAY(jso)->c_array, idx, count);
1539 }
1540
1541 struct json_object *json_object_array_get_idx(const struct json_object *jso, size_t idx)
1542 {
1543         assert(json_object_get_type(jso) == json_type_array);
1544         return (struct json_object *)array_list_get_idx(JC_ARRAY_C(jso)->c_array, idx);
1545 }
1546
1547 static int json_array_equal(struct json_object *jso1, struct json_object *jso2)
1548 {
1549         size_t len, i;
1550
1551         len = json_object_array_length(jso1);
1552         if (len != json_object_array_length(jso2))
1553                 return 0;
1554
1555         for (i = 0; i < len; i++)
1556         {
1557                 if (!json_object_equal(json_object_array_get_idx(jso1, i),
1558                                        json_object_array_get_idx(jso2, i)))
1559                         return 0;
1560         }
1561         return 1;
1562 }
1563
1564 int json_object_array_shrink(struct json_object *jso, int empty_slots)
1565 {
1566         if (empty_slots < 0)
1567                 json_abort("json_object_array_shrink called with negative empty_slots");
1568         return array_list_shrink(JC_ARRAY(jso)->c_array, empty_slots);
1569 }
1570
1571 struct json_object *json_object_new_null(void)
1572 {
1573         return NULL;
1574 }
1575
1576 static int json_object_all_values_equal(struct json_object *jso1, struct json_object *jso2)
1577 {
1578         struct json_object_iter iter;
1579         struct json_object *sub;
1580
1581         assert(json_object_get_type(jso1) == json_type_object);
1582         assert(json_object_get_type(jso2) == json_type_object);
1583         /* Iterate over jso1 keys and see if they exist and are equal in jso2 */
1584         json_object_object_foreachC(jso1, iter)
1585         {
1586                 if (!lh_table_lookup_ex(JC_OBJECT(jso2)->c_object, (void *)iter.key,
1587                                         (void **)(void *)&sub))
1588                         return 0;
1589                 if (!json_object_equal(iter.val, sub))
1590                         return 0;
1591         }
1592
1593         /* Iterate over jso2 keys to see if any exist that are not in jso1 */
1594         json_object_object_foreachC(jso2, iter)
1595         {
1596                 if (!lh_table_lookup_ex(JC_OBJECT(jso1)->c_object, (void *)iter.key,
1597                                         (void **)(void *)&sub))
1598                         return 0;
1599         }
1600
1601         return 1;
1602 }
1603
1604 int json_object_equal(struct json_object *jso1, struct json_object *jso2)
1605 {
1606         if (jso1 == jso2)
1607                 return 1;
1608
1609         if (!jso1 || !jso2)
1610                 return 0;
1611
1612         if (jso1->o_type != jso2->o_type)
1613                 return 0;
1614
1615         switch (jso1->o_type)
1616         {
1617         case json_type_boolean: return (JC_BOOL(jso1)->c_boolean == JC_BOOL(jso2)->c_boolean);
1618
1619         case json_type_double: return (JC_DOUBLE(jso1)->c_double == JC_DOUBLE(jso2)->c_double);
1620
1621         case json_type_int:
1622         {
1623                 struct json_object_int *int1 = JC_INT(jso1);
1624                 struct json_object_int *int2 = JC_INT(jso2);
1625                 if (int1->cint_type == json_object_int_type_int64)
1626                 {
1627                         if (int2->cint_type == json_object_int_type_int64)
1628                                 return (int1->cint.c_int64 == int2->cint.c_int64);
1629                         if (int1->cint.c_int64 < 0)
1630                                 return 0;
1631                         return ((uint64_t)int1->cint.c_int64 == int2->cint.c_uint64);
1632                 }
1633                 // else jso1 is a uint64
1634                 if (int2->cint_type == json_object_int_type_uint64)
1635                         return (int1->cint.c_uint64 == int2->cint.c_uint64);
1636                 if (int2->cint.c_int64 < 0)
1637                         return 0;
1638                 return (int1->cint.c_uint64 == (uint64_t)int2->cint.c_int64);
1639         }
1640
1641         case json_type_string:
1642         {
1643                 return (_json_object_get_string_len(JC_STRING(jso1)) ==
1644                             _json_object_get_string_len(JC_STRING(jso2)) &&
1645                         memcmp(get_string_component(jso1), get_string_component(jso2),
1646                                _json_object_get_string_len(JC_STRING(jso1))) == 0);
1647         }
1648
1649         case json_type_object: return json_object_all_values_equal(jso1, jso2);
1650
1651         case json_type_array: return json_array_equal(jso1, jso2);
1652
1653         case json_type_null: return 1;
1654         };
1655
1656         return 0;
1657 }
1658
1659 static int json_object_copy_serializer_data(struct json_object *src, struct json_object *dst)
1660 {
1661         if (!src->_userdata && !src->_user_delete)
1662                 return 0;
1663
1664         if (dst->_to_json_string == json_object_userdata_to_json_string ||
1665             dst->_to_json_string == _json_object_userdata_to_json_string)
1666         {
1667                 char *p;
1668                 assert(src->_userdata);
1669                 p = strdup(src->_userdata);
1670                 if (p == NULL)
1671                 {
1672                         _json_c_set_last_err("json_object_copy_serializer_data: out of memory\n");
1673                         return -1;
1674                 }
1675                 dst->_userdata = p;
1676         }
1677         // else if ... other supported serializers ...
1678         else
1679         {
1680                 _json_c_set_last_err(
1681                     "json_object_copy_serializer_data: unable to copy unknown serializer data: "
1682                     "%p\n", (void *)dst->_to_json_string);
1683                 return -1;
1684         }
1685         dst->_user_delete = src->_user_delete;
1686         return 0;
1687 }
1688
1689 /**
1690  * The default shallow copy implementation.  Simply creates a new object of the same
1691  * type but does *not* copy over _userdata nor retain any custom serializer.
1692  * If custom serializers are in use, json_object_deep_copy() must be passed a shallow copy
1693  * implementation that is aware of how to copy them.
1694  *
1695  * This always returns -1 or 1.  It will never return 2 since it does not copy the serializer.
1696  */
1697 int json_c_shallow_copy_default(json_object *src, json_object *parent, const char *key,
1698                                 size_t index, json_object **dst)
1699 {
1700         switch (src->o_type)
1701         {
1702         case json_type_boolean: *dst = json_object_new_boolean(JC_BOOL(src)->c_boolean); break;
1703
1704         case json_type_double: *dst = json_object_new_double(JC_DOUBLE(src)->c_double); break;
1705
1706         case json_type_int:
1707                 switch (JC_INT(src)->cint_type)
1708                 {
1709                 case json_object_int_type_int64:
1710                         *dst = json_object_new_int64(JC_INT(src)->cint.c_int64);
1711                         break;
1712                 case json_object_int_type_uint64:
1713                         *dst = json_object_new_uint64(JC_INT(src)->cint.c_uint64);
1714                         break;
1715                 default: json_abort("invalid cint_type");
1716                 }
1717                 break;
1718
1719         case json_type_string:
1720                 *dst = json_object_new_string_len(get_string_component(src),
1721                                                   _json_object_get_string_len(JC_STRING(src)));
1722                 break;
1723
1724         case json_type_object: *dst = json_object_new_object(); break;
1725
1726         case json_type_array: *dst = json_object_new_array(); break;
1727
1728         default: errno = EINVAL; return -1;
1729         }
1730
1731         if (!*dst)
1732         {
1733                 errno = ENOMEM;
1734                 return -1;
1735         }
1736         (*dst)->_to_json_string = src->_to_json_string;
1737         // _userdata and _user_delete are copied later
1738         return 1;
1739 }
1740
1741 /*
1742  * The actual guts of json_object_deep_copy(), with a few additional args
1743  * needed so we can keep track of where we are within the object tree.
1744  *
1745  * Note: caller is responsible for freeing *dst if this fails and returns -1.
1746  */
1747 static int json_object_deep_copy_recursive(struct json_object *src, struct json_object *parent,
1748                                            const char *key_in_parent, size_t index_in_parent,
1749                                            struct json_object **dst,
1750                                            json_c_shallow_copy_fn *shallow_copy)
1751 {
1752         struct json_object_iter iter;
1753         size_t src_array_len, ii;
1754
1755         int shallow_copy_rc = 0;
1756         shallow_copy_rc = shallow_copy(src, parent, key_in_parent, index_in_parent, dst);
1757         /* -1=error, 1=object created ok, 2=userdata set */
1758         if (shallow_copy_rc < 1)
1759         {
1760                 errno = EINVAL;
1761                 return -1;
1762         }
1763         assert(*dst != NULL);
1764
1765         switch (src->o_type)
1766         {
1767         case json_type_object:
1768                 json_object_object_foreachC(src, iter)
1769                 {
1770                         struct json_object *jso = NULL;
1771                         /* This handles the `json_type_null` case */
1772                         if (!iter.val)
1773                                 jso = NULL;
1774                         else if (json_object_deep_copy_recursive(iter.val, src, iter.key, UINT_MAX,
1775                                                                  &jso, shallow_copy) < 0)
1776                         {
1777                                 json_object_put(jso);
1778                                 return -1;
1779                         }
1780
1781                         if (json_object_object_add(*dst, iter.key, jso) < 0)
1782                         {
1783                                 json_object_put(jso);
1784                                 return -1;
1785                         }
1786                 }
1787                 break;
1788
1789         case json_type_array:
1790                 src_array_len = json_object_array_length(src);
1791                 for (ii = 0; ii < src_array_len; ii++)
1792                 {
1793                         struct json_object *jso = NULL;
1794                         struct json_object *jso1 = json_object_array_get_idx(src, ii);
1795                         /* This handles the `json_type_null` case */
1796                         if (!jso1)
1797                                 jso = NULL;
1798                         else if (json_object_deep_copy_recursive(jso1, src, NULL, ii, &jso,
1799                                                                  shallow_copy) < 0)
1800                         {
1801                                 json_object_put(jso);
1802                                 return -1;
1803                         }
1804
1805                         if (json_object_array_add(*dst, jso) < 0)
1806                         {
1807                                 json_object_put(jso);
1808                                 return -1;
1809                         }
1810                 }
1811                 break;
1812
1813         default:
1814                 break;
1815                 /* else, nothing to do, shallow_copy already did. */
1816         }
1817
1818         if (shallow_copy_rc != 2)
1819                 return json_object_copy_serializer_data(src, *dst);
1820
1821         return 0;
1822 }
1823
1824 int json_object_deep_copy(struct json_object *src, struct json_object **dst,
1825                           json_c_shallow_copy_fn *shallow_copy)
1826 {
1827         int rc;
1828
1829         /* Check if arguments are sane ; *dst must not point to a non-NULL object */
1830         if (!src || !dst || *dst)
1831         {
1832                 errno = EINVAL;
1833                 return -1;
1834         }
1835
1836         if (shallow_copy == NULL)
1837                 shallow_copy = json_c_shallow_copy_default;
1838
1839         rc = json_object_deep_copy_recursive(src, NULL, NULL, UINT_MAX, dst, shallow_copy);
1840         if (rc < 0)
1841         {
1842                 json_object_put(*dst);
1843                 *dst = NULL;
1844         }
1845
1846         return rc;
1847 }
1848
1849 static void json_abort(const char *message)
1850 {
1851         if (message != NULL)
1852                 fprintf(stderr, "json-c aborts with error: %s\n", message);
1853         abort();
1854 }