2 * Copyright (c) 2004, 2005 Metaparadigm Pte. Ltd.
3 * Michael Clark <michael@metaparadigm.com>
4 * Copyright (c) 2009 Hewlett-Packard Development Company, L.P.
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.
13 #include "strerror_override.h"
25 #include "arraylist.h"
27 #include "json_inttypes.h"
28 #include "json_object.h"
29 #include "json_object_private.h"
30 #include "json_util.h"
32 #include "math_compat.h"
34 #include "snprintf_compat.h"
35 #include "strdup_compat.h"
37 /* Avoid ctype.h and locale overhead */
38 #define is_plain_digit(c) ((c) >= '0' && (c) <= '9')
40 #if SIZEOF_LONG_LONG != SIZEOF_INT64_T
41 #error The long long type is not 64-bits
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
52 #error Unable to determine size of ssize_t
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";
59 static void json_object_generic_delete(struct json_object *jso);
61 #if defined(_MSC_VER) && (_MSC_VER <= 1800)
62 /* VS2013 doesn't know about "inline" */
63 #define inline __inline
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"
75 * Helper functions to more safely cast to a particular type of json_object
77 static inline struct json_object_object *JC_OBJECT(struct json_object *jso)
81 static inline const struct json_object_object *JC_OBJECT_C(const struct json_object *jso)
83 return (const void *)jso;
85 static inline struct json_object_array *JC_ARRAY(struct json_object *jso)
89 static inline const struct json_object_array *JC_ARRAY_C(const struct json_object *jso)
91 return (const void *)jso;
93 static inline struct json_object_boolean *JC_BOOL(struct json_object *jso)
97 static inline const struct json_object_boolean *JC_BOOL_C(const struct json_object *jso)
99 return (const void *)jso;
101 static inline struct json_object_double *JC_DOUBLE(struct json_object *jso)
105 static inline const struct json_object_double *JC_DOUBLE_C(const struct json_object *jso)
107 return (const void *)jso;
109 static inline struct json_object_int *JC_INT(struct json_object *jso)
113 static inline const struct json_object_int *JC_INT_C(const struct json_object *jso)
115 return (const void *)jso;
117 static inline struct json_object_string *JC_STRING(struct json_object *jso)
121 static inline const struct json_object_string *JC_STRING_C(const struct json_object *jso)
123 return (const void *)jso;
126 #define JC_CONCAT(a, b) a##b
127 #define JC_CONCAT3(a, b, c) a##b##c
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))
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);
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);
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;
149 #ifndef JSON_NORETURN
150 #if defined(_MSC_VER)
151 #define JSON_NORETURN __declspec(noreturn)
152 #elif defined(__OS400__)
153 #define JSON_NORETURN
155 /* 'cold' attribute is for optimization, telling the computer this code
158 #define JSON_NORETURN __attribute__((noreturn, cold))
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).
166 JSON_NORETURN static void json_abort(const char *message);
168 /* helper for accessing the optimized string data component in json_object
170 static inline char *get_string_component_mutable(struct json_object *jso)
172 if (JC_STRING_C(jso)->len < 0)
174 /* Due to json_object_set_string(), we might have a pointer */
175 return JC_STRING(jso)->c_string.pdata;
177 return JC_STRING(jso)->c_string.idata;
179 static inline const char *get_string_component(const struct json_object *jso)
181 return get_string_component_mutable((void *)(uintptr_t)(const void *)jso);
184 /* string escaping */
186 static int json_escape_str(struct printbuf *pb, const char *str, size_t len, int flags)
188 size_t pos = 0, start_offset = 0;
204 if ((flags & JSON_C_TO_STRING_NOSLASHESCAPE) && c == '/')
210 if (pos > start_offset)
211 printbuf_memappend(pb, str + start_offset, pos - start_offset);
214 printbuf_memappend(pb, "\\b", 2);
216 printbuf_memappend(pb, "\\n", 2);
218 printbuf_memappend(pb, "\\r", 2);
220 printbuf_memappend(pb, "\\t", 2);
222 printbuf_memappend(pb, "\\f", 2);
224 printbuf_memappend(pb, "\\\"", 2);
226 printbuf_memappend(pb, "\\\\", 2);
228 printbuf_memappend(pb, "\\/", 2);
230 start_offset = ++pos;
236 if (pos > start_offset)
237 printbuf_memappend(pb, str + 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;
248 if (pos > start_offset)
249 printbuf_memappend(pb, str + start_offset, pos - start_offset);
253 /* reference counting */
255 struct json_object *json_object_get(struct json_object *jso)
260 // Don't overflow the refcounter.
261 assert(jso->_ref_count < UINT32_MAX);
263 #if defined(HAVE_ATOMIC_BUILTINS) && defined(ENABLE_THREADING)
264 __sync_add_and_fetch(&jso->_ref_count, 1);
272 int json_object_put(struct json_object *jso)
277 /* Avoid invalid free and crash explicitly instead of (silently)
280 assert(jso->_ref_count > 0);
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.
289 if (__sync_sub_and_fetch(&jso->_ref_count, 1) > 0)
292 if (--jso->_ref_count > 0)
296 if (jso->_user_delete)
297 jso->_user_delete(jso, jso->_userdata);
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;
308 /* generic object construction and destruction parts */
310 static void json_object_generic_delete(struct json_object *jso)
312 printbuf_free(jso->_pb);
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)
319 struct json_object *jso;
321 jso = (struct json_object *)malloc(alloc_size);
325 jso->o_type = o_type;
327 jso->_to_json_string = to_json_string;
329 jso->_user_delete = NULL;
330 jso->_userdata = NULL;
331 //jso->... // Type-specific fields must be set by caller
336 /* type checking functions */
338 int json_object_is_type(const struct json_object *jso, enum json_type type)
341 return (type == json_type_null);
342 return (jso->o_type == type);
345 enum json_type json_object_get_type(const struct json_object *jso)
348 return json_type_null;
352 void *json_object_get_userdata(json_object *jso)
354 return jso ? jso->_userdata : NULL;
357 void json_object_set_userdata(json_object *jso, void *userdata, json_object_delete_fn *user_delete)
359 // Can't return failure, so abort if we can't perform the operation.
362 // First, clean up any previously existing user info
363 if (jso->_user_delete)
364 jso->_user_delete(jso, jso->_userdata);
366 jso->_userdata = userdata;
367 jso->_user_delete = user_delete;
370 /* set a custom conversion to string */
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)
375 json_object_set_userdata(jso, userdata, user_delete);
377 if (to_string_func == NULL)
379 // Reset to the standard serialization function
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;
386 case json_type_double:
387 jso->_to_json_string = &json_object_double_to_json_string_default;
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;
393 case json_type_array:
394 jso->_to_json_string = &json_object_array_to_json_string;
396 case json_type_string:
397 jso->_to_json_string = &json_object_string_to_json_string;
403 jso->_to_json_string = to_string_func;
406 /* extended conversion to string */
408 const char *json_object_to_json_string_length(struct json_object *jso, int flags, size_t *length)
410 const char *r = NULL;
418 else if ((jso->_pb) || (jso->_pb = printbuf_new()))
420 printbuf_reset(jso->_pb);
422 if (jso->_to_json_string(jso, jso->_pb, 0, flags) >= 0)
424 s = (size_t)jso->_pb->bpos;
434 const char *json_object_to_json_string_ext(struct json_object *jso, int flags)
436 return json_object_to_json_string_length(jso, flags, NULL);
439 /* backwards-compatible conversion to string */
441 const char *json_object_to_json_string(struct json_object *jso)
443 return json_object_to_json_string_ext(jso, JSON_C_TO_STRING_SPACED);
446 static void indent(struct printbuf *pb, int level, int flags)
448 if (flags & JSON_C_TO_STRING_PRETTY)
450 if (flags & JSON_C_TO_STRING_PRETTY_TAB)
452 printbuf_memset(pb, -1, '\t', level);
456 printbuf_memset(pb, -1, ' ', level * 2);
461 /* json_object_object */
463 static int json_object_object_to_json_string(struct json_object *jso, struct printbuf *pb,
464 int level, int flags)
466 int had_children = 0;
467 struct json_object_iter iter;
469 printbuf_strappend(pb, "{" /*}*/);
470 json_object_object_foreachC(jso, iter)
474 printbuf_strappend(pb, ",");
476 if (flags & JSON_C_TO_STRING_PRETTY)
477 printbuf_strappend(pb, "\n");
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);
485 printbuf_strappend(pb, "\"");
486 json_escape_str(pb, iter.key, strlen(iter.key), flags);
487 printbuf_strappend(pb, "\"");
489 if (flags & JSON_C_TO_STRING_COLOR)
490 printbuf_strappend(pb, ANSI_COLOR_RESET);
492 if (flags & JSON_C_TO_STRING_SPACED)
493 printbuf_strappend(pb, ": ");
495 printbuf_strappend(pb, ":");
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)
506 if ((flags & JSON_C_TO_STRING_PRETTY) && had_children)
508 printbuf_strappend(pb, "\n");
509 indent(pb, level, flags);
511 if (flags & JSON_C_TO_STRING_SPACED && !(flags & JSON_C_TO_STRING_PRETTY))
512 return printbuf_strappend(pb, /*{*/ " }");
514 return printbuf_strappend(pb, /*{*/ "}");
517 static void json_object_lh_entry_free(struct lh_entry *ent)
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));
524 static void json_object_object_delete(struct json_object *jso_base)
526 lh_table_free(JC_OBJECT(jso_base)->c_object);
527 json_object_generic_delete(jso_base);
530 struct json_object *json_object_new_object(void)
532 struct json_object_object *jso = JSON_OBJECT_NEW(object);
536 lh_kchar_table_new(JSON_OBJECT_DEF_HASH_ENTRIES, &json_object_lh_entry_free);
539 json_object_generic_delete(&jso->base);
546 struct lh_table *json_object_get_object(const struct json_object *jso)
552 case json_type_object: return JC_OBJECT_C(jso)->c_object;
553 default: return NULL;
557 int json_object_object_add_ex(struct json_object *jso, const char *const key,
558 struct json_object *const val, const unsigned opts)
560 struct json_object *existing_value = NULL;
561 struct lh_entry *existing_entry;
564 assert(json_object_get_type(jso) == json_type_object);
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);
570 (opts & JSON_C_OBJECT_ADD_KEY_IS_NEW)
572 : lh_table_lookup_entry_w_hash(JC_OBJECT(jso)->c_object, (const void *)key, hash);
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.
581 const void *const k =
582 (opts & JSON_C_OBJECT_ADD_CONSTANT_KEY) ? (const void *)key : strdup(key);
585 return lh_table_insert_w_hash(JC_OBJECT(jso)->c_object, k, val, hash, opts);
587 existing_value = (json_object *)lh_entry_v(existing_entry);
589 json_object_put(existing_value);
590 lh_entry_set_val(existing_entry, val);
594 int json_object_object_add(struct json_object *jso, const char *key, struct json_object *val)
596 return json_object_object_add_ex(jso, key, val, 0);
599 int json_object_object_length(const struct json_object *jso)
601 assert(json_object_get_type(jso) == json_type_object);
602 return lh_table_length(JC_OBJECT_C(jso)->c_object);
605 size_t json_c_object_sizeof(void)
607 return sizeof(struct json_object);
610 struct json_object *json_object_object_get(const struct json_object *jso, const char *key)
612 struct json_object *result = NULL;
613 json_object_object_get_ex(jso, key, &result);
617 json_bool json_object_object_get_ex(const struct json_object *jso, const char *key,
618 struct json_object **value)
628 case json_type_object:
629 return lh_table_lookup_ex(JC_OBJECT_C(jso)->c_object, (const void *)key,
638 void json_object_object_del(struct json_object *jso, const char *key)
640 assert(json_object_get_type(jso) == json_type_object);
641 lh_table_delete(JC_OBJECT(jso)->c_object, key);
644 /* json_object_boolean */
646 static int json_object_boolean_to_json_string(struct json_object *jso, struct printbuf *pb,
647 int level, int flags)
651 if (flags & JSON_C_TO_STRING_COLOR)
652 printbuf_strappend(pb, ANSI_COLOR_FG_MAGENTA);
654 if (JC_BOOL(jso)->c_boolean)
655 ret = printbuf_strappend(pb, "true");
657 ret = printbuf_strappend(pb, "false");
658 if (ret > -1 && flags & JSON_C_TO_STRING_COLOR)
659 return printbuf_strappend(pb, ANSI_COLOR_RESET);
663 struct json_object *json_object_new_boolean(json_bool b)
665 struct json_object_boolean *jso = JSON_OBJECT_NEW(boolean);
672 json_bool json_object_get_boolean(const struct json_object *jso)
678 case json_type_boolean: return JC_BOOL_C(jso)->c_boolean;
680 switch (JC_INT_C(jso)->cint_type)
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");
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);
692 int json_object_set_boolean(struct json_object *jso, json_bool new_value)
694 if (!jso || jso->o_type != json_type_boolean)
696 JC_BOOL(jso)->c_boolean = new_value;
700 /* json_object_int */
702 static int json_object_int_to_json_string(struct json_object *jso, struct printbuf *pb, int level,
705 /* room for 19 digits, the sign char, and a null term */
707 if (JC_INT(jso)->cint_type == json_object_int_type_int64)
708 snprintf(sbuf, sizeof(sbuf), "%" PRId64, JC_INT(jso)->cint.c_int64);
710 snprintf(sbuf, sizeof(sbuf), "%" PRIu64, JC_INT(jso)->cint.c_uint64);
711 return printbuf_memappend(pb, sbuf, strlen(sbuf));
714 struct json_object *json_object_new_int(int32_t i)
716 return json_object_new_int64(i);
719 int32_t json_object_get_int(const struct json_object *jso)
723 enum json_type o_type;
728 o_type = jso->o_type;
729 if (o_type == json_type_int)
731 const struct json_object_int *jsoint = JC_INT_C(jso);
732 if (jsoint->cint_type == json_object_int_type_int64)
734 cint64 = jsoint->cint.c_int64;
738 if (jsoint->cint.c_uint64 >= INT64_MAX)
741 cint64 = (int64_t)jsoint->cint.c_uint64;
744 else if (o_type == json_type_string)
747 * Parse strings into 64-bit numbers, then use the
748 * 64-to-32-bit number handling below.
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;
758 /* Make sure we return the correct values for out of range numbers. */
759 if (cint64 <= INT32_MIN)
761 if (cint64 >= 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)
768 if (cdouble >= INT32_MAX)
770 return (int32_t)cdouble;
771 case json_type_boolean: return JC_BOOL_C(jso)->c_boolean;
776 int json_object_set_int(struct json_object *jso, int new_value)
778 return json_object_set_int64(jso, (int64_t)new_value);
781 struct json_object *json_object_new_int64(int64_t i)
783 struct json_object_int *jso = JSON_OBJECT_NEW(int);
786 jso->cint.c_int64 = i;
787 jso->cint_type = json_object_int_type_int64;
791 struct json_object *json_object_new_uint64(uint64_t i)
793 struct json_object_int *jso = JSON_OBJECT_NEW(int);
796 jso->cint.c_uint64 = i;
797 jso->cint_type = json_object_int_type_uint64;
801 int64_t json_object_get_int64(const struct json_object *jso)
811 const struct json_object_int *jsoint = JC_INT_C(jso);
812 switch (jsoint->cint_type)
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)
818 return (int64_t)jsoint->cint.c_uint64;
819 default: json_abort("invalid cint_type");
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)
827 if (JC_DOUBLE_C(jso)->c_double <= 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)
839 uint64_t json_object_get_uint64(const struct json_object *jso)
849 const struct json_object_int *jsoint = JC_INT_C(jso);
850 switch (jsoint->cint_type)
852 case json_object_int_type_int64:
853 if (jsoint->cint.c_int64 < 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");
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)
865 if (JC_DOUBLE_C(jso)->c_double < 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)
877 int json_object_set_int64(struct json_object *jso, int64_t new_value)
879 if (!jso || jso->o_type != json_type_int)
881 JC_INT(jso)->cint.c_int64 = new_value;
882 JC_INT(jso)->cint_type = json_object_int_type_int64;
886 int json_object_set_uint64(struct json_object *jso, uint64_t new_value)
888 if (!jso || jso->o_type != json_type_int)
890 JC_INT(jso)->cint.c_uint64 = new_value;
891 JC_INT(jso)->cint_type = json_object_int_type_uint64;
895 int json_object_int_inc(struct json_object *jso, int64_t val)
897 struct json_object_int *jsoint;
898 if (!jso || jso->o_type != json_type_int)
900 jsoint = JC_INT(jso);
901 switch (jsoint->cint_type)
903 case json_object_int_type_int64:
904 if (val > 0 && jsoint->cint.c_int64 > INT64_MAX - val)
906 jsoint->cint.c_uint64 = (uint64_t)jsoint->cint.c_int64 + (uint64_t)val;
907 jsoint->cint_type = json_object_int_type_uint64;
909 else if (val < 0 && jsoint->cint.c_int64 < INT64_MIN - val)
911 jsoint->cint.c_int64 = INT64_MIN;
915 jsoint->cint.c_int64 += val;
918 case json_object_int_type_uint64:
919 if (val > 0 && jsoint->cint.c_uint64 > UINT64_MAX - (uint64_t)val)
921 jsoint->cint.c_uint64 = UINT64_MAX;
923 else if (val < 0 && jsoint->cint.c_uint64 < (uint64_t)(-val))
925 jsoint->cint.c_int64 = (int64_t)jsoint->cint.c_uint64 + val;
926 jsoint->cint_type = json_object_int_type_int64;
928 else if (val < 0 && jsoint->cint.c_uint64 >= (uint64_t)(-val))
930 jsoint->cint.c_uint64 -= (uint64_t)(-val);
934 jsoint->cint.c_uint64 += val;
937 default: json_abort("invalid cint_type");
941 /* json_object_double */
943 #if defined(HAVE___THREAD)
944 // i.e. __thread or __declspec(thread)
945 static SPEC___THREAD char *tls_serialization_float_format = NULL;
947 static char *global_serialization_float_format = NULL;
949 int json_c_set_serialization_double_format(const char *double_format, int global_or_thread)
951 if (global_or_thread == JSON_C_OPTION_GLOBAL)
953 #if defined(HAVE___THREAD)
954 if (tls_serialization_float_format)
956 free(tls_serialization_float_format);
957 tls_serialization_float_format = NULL;
960 if (global_serialization_float_format)
961 free(global_serialization_float_format);
964 char *p = strdup(double_format);
967 _json_c_set_last_err("json_c_set_serialization_double_format: "
971 global_serialization_float_format = p;
975 global_serialization_float_format = NULL;
978 else if (global_or_thread == JSON_C_OPTION_THREAD)
980 #if defined(HAVE___THREAD)
981 if (tls_serialization_float_format)
983 free(tls_serialization_float_format);
984 tls_serialization_float_format = NULL;
988 char *p = strdup(double_format);
991 _json_c_set_last_err("json_c_set_serialization_double_format: "
995 tls_serialization_float_format = p;
999 tls_serialization_float_format = NULL;
1002 _json_c_set_last_err("json_c_set_serialization_double_format: not compiled "
1003 "with __thread support\n");
1009 _json_c_set_last_err("json_c_set_serialization_double_format: invalid "
1010 "global_or_thread value: %d\n", global_or_thread);
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)
1019 struct json_object_double *jsodbl = JC_DOUBLE(jso);
1020 char buf[128], *p, *q;
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
1027 if (isnan(jsodbl->c_double))
1029 size = snprintf(buf, sizeof(buf), "NaN");
1031 else if (isinf(jsodbl->c_double))
1033 if (jsodbl->c_double > 0)
1034 size = snprintf(buf, sizeof(buf), "Infinity");
1036 size = snprintf(buf, sizeof(buf), "-Infinity");
1040 const char *std_format = "%.17g";
1041 int format_drops_decimals = 0;
1042 int looks_numeric = 0;
1046 #if defined(HAVE___THREAD)
1047 if (tls_serialization_float_format)
1048 format = tls_serialization_float_format;
1051 if (global_serialization_float_format)
1052 format = global_serialization_float_format;
1054 format = std_format;
1056 size = snprintf(buf, sizeof(buf), format, jsodbl->c_double);
1061 p = strchr(buf, ',');
1065 p = strchr(buf, '.');
1067 if (format == std_format || strstr(format, ".0f") == NULL)
1068 format_drops_decimals = 1;
1070 looks_numeric = /* Looks like *some* kind of number */
1071 is_plain_digit(buf[0]) || (size > 1 && buf[0] == '-' && is_plain_digit(buf[1]));
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)
1077 // Ensure it looks like a float, even if snprintf didn't,
1078 // unless a custom format is set to omit the decimal.
1082 if (p && (flags & JSON_C_TO_STRING_NOZERO))
1084 /* last useful digit, always keep 1 zero */
1086 for (q = p; *q; q++)
1091 /* drop trailing zeroes */
1097 // although unlikely, snprintf can fail
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);
1109 static int json_object_double_to_json_string_default(struct json_object *jso, struct printbuf *pb,
1110 int level, int flags)
1112 return json_object_double_to_json_string_format(jso, pb, level, flags, NULL);
1115 int json_object_double_to_json_string(struct json_object *jso, struct printbuf *pb, int level,
1118 return json_object_double_to_json_string_format(jso, pb, level, flags,
1119 (const char *)jso->_userdata);
1122 struct json_object *json_object_new_double(double d)
1124 struct json_object_double *jso = JSON_OBJECT_NEW(double);
1127 jso->base._to_json_string = &json_object_double_to_json_string_default;
1132 struct json_object *json_object_new_double_s(double d, const char *ds)
1135 struct json_object *jso = json_object_new_double(d);
1139 new_ds = strdup(ds);
1142 json_object_generic_delete(jso);
1146 json_object_set_serializer(jso, _json_object_userdata_to_json_string, new_ds,
1147 json_object_free_userdata);
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.
1156 static int _json_object_userdata_to_json_string(struct json_object *jso, struct printbuf *pb,
1157 int level, int flags)
1159 return json_object_userdata_to_json_string(jso, pb, level, flags);
1162 int json_object_userdata_to_json_string(struct json_object *jso, struct printbuf *pb, int level,
1165 int userdata_len = strlen((const char *)jso->_userdata);
1166 printbuf_memappend(pb, (const char *)jso->_userdata, userdata_len);
1167 return userdata_len;
1170 void json_object_free_userdata(struct json_object *jso, void *userdata)
1175 double json_object_get_double(const struct json_object *jso)
1178 char *errPtr = NULL;
1182 switch (jso->o_type)
1184 case json_type_double: return JC_DOUBLE_C(jso)->c_double;
1186 switch (JC_INT_C(jso)->cint_type)
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");
1192 case json_type_boolean: return JC_BOOL_C(jso)->c_boolean;
1193 case json_type_string:
1195 cdouble = strtod(get_string_component(jso), &errPtr);
1197 /* if conversion stopped at the first character, return 0.0 */
1198 if (errPtr == get_string_component(jso))
1205 * Check that the conversion terminated on something sensible
1207 * For example, { "pay" : 123AB } would parse as 123.
1209 if (*errPtr != '\0')
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.
1221 * Underflow also sets errno to ERANGE, but it returns 0 in
1222 * that case, which is what we will return anyway.
1224 * See CERT guideline ERR30-C
1226 if ((HUGE_VAL == cdouble || -HUGE_VAL == cdouble) && (ERANGE == errno))
1229 default: errno = EINVAL; return 0.0;
1233 int json_object_set_double(struct json_object *jso, double new_value)
1235 if (!jso || jso->o_type != json_type_double)
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);
1243 /* json_object_string */
1245 static int json_object_string_to_json_string(struct json_object *jso, struct printbuf *pb,
1246 int level, int flags)
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);
1259 static void json_object_string_delete(struct json_object *jso)
1261 if (JC_STRING(jso)->len < 0)
1262 free(JC_STRING(jso)->c_string.pdata);
1263 json_object_generic_delete(jso);
1266 static struct json_object *_json_object_new_string(const char *s, const size_t len)
1269 struct json_object_string *jso;
1272 * Structures Actual memory layout
1273 * ------------------- --------------------
1274 * [json_object_string [json_object_string
1275 * [json_object] [json_object]
1276 * ...other fields... ...other fields...
1284 if (len > (SSIZE_T_MAX - (sizeof(*jso) - sizeof(jso->c_string)) - 1))
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;
1292 jso = (struct json_object_string *)json_object_new(json_type_string, objsize,
1293 &json_object_string_to_json_string);
1298 memcpy(jso->c_string.idata, s, len);
1299 // Cast below needed for Clang UB sanitizer
1300 ((char *)jso->c_string.idata)[len] = '\0';
1304 struct json_object *json_object_new_string(const char *s)
1306 return _json_object_new_string(s, strlen(s));
1309 struct json_object *json_object_new_string_len(const char *s, const int len)
1311 return _json_object_new_string(s, len);
1314 const char *json_object_get_string(struct json_object *jso)
1318 switch (jso->o_type)
1320 case json_type_string: return get_string_component(jso);
1321 default: return json_object_to_json_string(jso);
1325 static inline ssize_t _json_object_get_string_len(const struct json_object_string *jso)
1329 return (len < 0) ? -(ssize_t)len : len;
1331 int json_object_get_string_len(const struct json_object *jso)
1335 switch (jso->o_type)
1337 case json_type_string: return _json_object_get_string_len(JC_STRING_C(jso));
1342 static int _json_object_set_string_len(json_object *jso, const char *s, size_t len)
1347 if (jso == NULL || jso->o_type != json_type_string)
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.
1356 curlen = JC_STRING(jso)->len;
1359 free(JC_STRING(jso)->c_string.pdata);
1360 JC_STRING(jso)->len = curlen = 0;
1367 dstbuf = get_string_component_mutable(jso);
1369 if ((ssize_t)len > curlen)
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);
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;
1382 else if (JC_STRING(jso)->len < 0)
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;
1389 memcpy(dstbuf, (const void *)s, len);
1391 JC_STRING(jso)->len = newlen;
1395 int json_object_set_string(json_object *jso, const char *s)
1397 return _json_object_set_string_len(jso, s, strlen(s));
1400 int json_object_set_string_len(json_object *jso, const char *s, int len)
1402 return _json_object_set_string_len(jso, s, len);
1405 /* json_object_array */
1407 static int json_object_array_to_json_string(struct json_object *jso, struct printbuf *pb, int level,
1410 int had_children = 0;
1413 printbuf_strappend(pb, "[");
1414 for (ii = 0; ii < json_object_array_length(jso); ii++)
1416 struct json_object *val;
1419 printbuf_strappend(pb, ",");
1421 if (flags & JSON_C_TO_STRING_PRETTY)
1422 printbuf_strappend(pb, "\n");
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);
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);
1436 } else if (val->_to_json_string(val, pb, level + 1, flags) < 0)
1439 if ((flags & JSON_C_TO_STRING_PRETTY) && had_children)
1441 printbuf_strappend(pb, "\n");
1442 indent(pb, level, flags);
1445 if (flags & JSON_C_TO_STRING_SPACED && !(flags & JSON_C_TO_STRING_PRETTY))
1446 return printbuf_strappend(pb, " ]");
1447 return printbuf_strappend(pb, "]");
1450 static void json_object_array_entry_free(void *data)
1452 json_object_put((struct json_object *)data);
1455 static void json_object_array_delete(struct json_object *jso)
1457 array_list_free(JC_ARRAY(jso)->c_array);
1458 json_object_generic_delete(jso);
1461 struct json_object *json_object_new_array(void)
1463 return json_object_new_array_ext(ARRAY_LIST_DEFAULT_SIZE);
1465 struct json_object *json_object_new_array_ext(int initial_size)
1467 struct json_object_array *jso = JSON_OBJECT_NEW(array);
1470 jso->c_array = array_list_new2(&json_object_array_entry_free, initial_size);
1471 if (jso->c_array == NULL)
1479 struct array_list *json_object_get_array(const struct json_object *jso)
1483 switch (jso->o_type)
1485 case json_type_array: return JC_ARRAY_C(jso)->c_array;
1486 default: return NULL;
1490 void json_object_array_sort(struct json_object *jso, int (*sort_fn)(const void *, const void *))
1492 assert(json_object_get_type(jso) == json_type_array);
1493 array_list_sort(JC_ARRAY(jso)->c_array, sort_fn);
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 *))
1500 struct json_object **result;
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);
1511 size_t json_object_array_length(const struct json_object *jso)
1513 assert(json_object_get_type(jso) == json_type_array);
1514 return array_list_length(JC_ARRAY_C(jso)->c_array);
1517 int json_object_array_add(struct json_object *jso, struct json_object *val)
1519 assert(json_object_get_type(jso) == json_type_array);
1520 return array_list_add(JC_ARRAY(jso)->c_array, val);
1523 int json_object_array_insert_idx(struct json_object *jso, size_t idx, struct json_object *val)
1525 assert(json_object_get_type(jso) == json_type_array);
1526 return array_list_insert_idx(JC_ARRAY(jso)->c_array, idx, val);
1529 int json_object_array_put_idx(struct json_object *jso, size_t idx, struct json_object *val)
1531 assert(json_object_get_type(jso) == json_type_array);
1532 return array_list_put_idx(JC_ARRAY(jso)->c_array, idx, val);
1535 int json_object_array_del_idx(struct json_object *jso, size_t idx, size_t count)
1537 assert(json_object_get_type(jso) == json_type_array);
1538 return array_list_del_idx(JC_ARRAY(jso)->c_array, idx, count);
1541 struct json_object *json_object_array_get_idx(const struct json_object *jso, size_t idx)
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);
1547 static int json_array_equal(struct json_object *jso1, struct json_object *jso2)
1551 len = json_object_array_length(jso1);
1552 if (len != json_object_array_length(jso2))
1555 for (i = 0; i < len; i++)
1557 if (!json_object_equal(json_object_array_get_idx(jso1, i),
1558 json_object_array_get_idx(jso2, i)))
1564 int json_object_array_shrink(struct json_object *jso, int empty_slots)
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);
1571 struct json_object *json_object_new_null(void)
1576 static int json_object_all_values_equal(struct json_object *jso1, struct json_object *jso2)
1578 struct json_object_iter iter;
1579 struct json_object *sub;
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)
1586 if (!lh_table_lookup_ex(JC_OBJECT(jso2)->c_object, (void *)iter.key,
1587 (void **)(void *)&sub))
1589 if (!json_object_equal(iter.val, sub))
1593 /* Iterate over jso2 keys to see if any exist that are not in jso1 */
1594 json_object_object_foreachC(jso2, iter)
1596 if (!lh_table_lookup_ex(JC_OBJECT(jso1)->c_object, (void *)iter.key,
1597 (void **)(void *)&sub))
1604 int json_object_equal(struct json_object *jso1, struct json_object *jso2)
1612 if (jso1->o_type != jso2->o_type)
1615 switch (jso1->o_type)
1617 case json_type_boolean: return (JC_BOOL(jso1)->c_boolean == JC_BOOL(jso2)->c_boolean);
1619 case json_type_double: return (JC_DOUBLE(jso1)->c_double == JC_DOUBLE(jso2)->c_double);
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)
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)
1631 return ((uint64_t)int1->cint.c_int64 == int2->cint.c_uint64);
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)
1638 return (int1->cint.c_uint64 == (uint64_t)int2->cint.c_int64);
1641 case json_type_string:
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);
1649 case json_type_object: return json_object_all_values_equal(jso1, jso2);
1651 case json_type_array: return json_array_equal(jso1, jso2);
1653 case json_type_null: return 1;
1659 static int json_object_copy_serializer_data(struct json_object *src, struct json_object *dst)
1661 if (!src->_userdata && !src->_user_delete)
1664 if (dst->_to_json_string == json_object_userdata_to_json_string ||
1665 dst->_to_json_string == _json_object_userdata_to_json_string)
1668 assert(src->_userdata);
1669 p = strdup(src->_userdata);
1672 _json_c_set_last_err("json_object_copy_serializer_data: out of memory\n");
1677 // else if ... other supported serializers ...
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);
1685 dst->_user_delete = src->_user_delete;
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.
1695 * This always returns -1 or 1. It will never return 2 since it does not copy the serializer.
1697 int json_c_shallow_copy_default(json_object *src, json_object *parent, const char *key,
1698 size_t index, json_object **dst)
1700 switch (src->o_type)
1702 case json_type_boolean: *dst = json_object_new_boolean(JC_BOOL(src)->c_boolean); break;
1704 case json_type_double: *dst = json_object_new_double(JC_DOUBLE(src)->c_double); break;
1707 switch (JC_INT(src)->cint_type)
1709 case json_object_int_type_int64:
1710 *dst = json_object_new_int64(JC_INT(src)->cint.c_int64);
1712 case json_object_int_type_uint64:
1713 *dst = json_object_new_uint64(JC_INT(src)->cint.c_uint64);
1715 default: json_abort("invalid cint_type");
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)));
1724 case json_type_object: *dst = json_object_new_object(); break;
1726 case json_type_array: *dst = json_object_new_array(); break;
1728 default: errno = EINVAL; return -1;
1736 (*dst)->_to_json_string = src->_to_json_string;
1737 // _userdata and _user_delete are copied later
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.
1745 * Note: caller is responsible for freeing *dst if this fails and returns -1.
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)
1752 struct json_object_iter iter;
1753 size_t src_array_len, ii;
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)
1763 assert(*dst != NULL);
1765 switch (src->o_type)
1767 case json_type_object:
1768 json_object_object_foreachC(src, iter)
1770 struct json_object *jso = NULL;
1771 /* This handles the `json_type_null` case */
1774 else if (json_object_deep_copy_recursive(iter.val, src, iter.key, UINT_MAX,
1775 &jso, shallow_copy) < 0)
1777 json_object_put(jso);
1781 if (json_object_object_add(*dst, iter.key, jso) < 0)
1783 json_object_put(jso);
1789 case json_type_array:
1790 src_array_len = json_object_array_length(src);
1791 for (ii = 0; ii < src_array_len; ii++)
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 */
1798 else if (json_object_deep_copy_recursive(jso1, src, NULL, ii, &jso,
1801 json_object_put(jso);
1805 if (json_object_array_add(*dst, jso) < 0)
1807 json_object_put(jso);
1815 /* else, nothing to do, shallow_copy already did. */
1818 if (shallow_copy_rc != 2)
1819 return json_object_copy_serializer_data(src, *dst);
1824 int json_object_deep_copy(struct json_object *src, struct json_object **dst,
1825 json_c_shallow_copy_fn *shallow_copy)
1829 /* Check if arguments are sane ; *dst must not point to a non-NULL object */
1830 if (!src || !dst || *dst)
1836 if (shallow_copy == NULL)
1837 shallow_copy = json_c_shallow_copy_default;
1839 rc = json_object_deep_copy_recursive(src, NULL, NULL, UINT_MAX, dst, shallow_copy);
1842 json_object_put(*dst);
1849 static void json_abort(const char *message)
1851 if (message != NULL)
1852 fprintf(stderr, "json-c aborts with error: %s\n", message);