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"
26 #include "arraylist.h"
28 #include "json_inttypes.h"
29 #include "json_object.h"
30 #include "json_object_private.h"
31 #include "json_util.h"
33 #include "math_compat.h"
35 #include "snprintf_compat.h"
36 #include "strdup_compat.h"
38 #if SIZEOF_LONG_LONG != SIZEOF_INT64_T
39 #error "The long long type isn't 64-bits"
43 #if SIZEOF_SSIZE_T == SIZEOF_INT
44 #define SSIZE_T_MAX INT_MAX
45 #elif SIZEOF_SSIZE_T == SIZEOF_LONG
46 #define SSIZE_T_MAX LONG_MAX
47 #elif SIZEOF_SSIZE_T == SIZEOF_LONG_LONG
48 #define SSIZE_T_MAX LLONG_MAX
50 #error Unable to determine size of ssize_t
54 // Don't define this. It's not thread-safe.
55 /* #define REFCOUNT_DEBUG 1 */
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 * Helper functions to more safely cast to a particular type of json_object
71 static inline struct json_object_object *JC_OBJECT(struct json_object *jso)
75 static inline const struct json_object_object *JC_OBJECT_C(const struct json_object *jso)
77 return (const void *)jso;
79 static inline struct json_object_array *JC_ARRAY(struct json_object *jso)
83 static inline const struct json_object_array *JC_ARRAY_C(const struct json_object *jso)
85 return (const void *)jso;
87 static inline struct json_object_boolean *JC_BOOL(struct json_object *jso)
91 static inline const struct json_object_boolean *JC_BOOL_C(const struct json_object *jso)
93 return (const void *)jso;
95 static inline struct json_object_double *JC_DOUBLE(struct json_object *jso)
99 static inline const struct json_object_double *JC_DOUBLE_C(const struct json_object *jso)
101 return (const void *)jso;
103 static inline struct json_object_int *JC_INT(struct json_object *jso)
107 static inline const struct json_object_int *JC_INT_C(const struct json_object *jso)
109 return (const void *)jso;
111 static inline struct json_object_string *JC_STRING(struct json_object *jso)
115 static inline const struct json_object_string *JC_STRING_C(const struct json_object *jso)
117 return (const void *)jso;
120 #define JC_CONCAT(a, b) a##b
121 #define JC_CONCAT3(a, b, c) a##b##c
123 #define JSON_OBJECT_NEW(jtype) \
124 (struct JC_CONCAT(json_object_, jtype) *)json_object_new( \
125 JC_CONCAT(json_type_, jtype), sizeof(struct JC_CONCAT(json_object_, jtype)), \
126 &JC_CONCAT3(json_object_, jtype, _to_json_string))
128 static inline struct json_object *json_object_new(enum json_type o_type, size_t alloc_size,
129 json_object_to_json_string_fn *to_json_string);
131 static void json_object_object_delete(struct json_object *jso_base);
132 static void json_object_string_delete(struct json_object *jso);
133 static void json_object_array_delete(struct json_object *jso);
135 static json_object_to_json_string_fn json_object_object_to_json_string;
136 static json_object_to_json_string_fn json_object_boolean_to_json_string;
137 static json_object_to_json_string_fn json_object_double_to_json_string_default;
138 static json_object_to_json_string_fn json_object_int_to_json_string;
139 static json_object_to_json_string_fn json_object_string_to_json_string;
140 static json_object_to_json_string_fn json_object_array_to_json_string;
141 static json_object_to_json_string_fn _json_object_userdata_to_json_string;
143 #ifndef JSON_NORETURN
144 #if defined(_MSC_VER)
145 #define JSON_NORETURN __declspec(noreturn)
146 #elif defined(__OS400__)
147 #define JSON_NORETURN
149 /* 'cold' attribute is for optimization, telling the computer this code
152 #define JSON_NORETURN __attribute__((noreturn, cold))
156 * Abort and optionally print a message on standard error.
157 * This should be used rather than assert() for unconditional abortion
158 * (in particular for code paths which are never supposed to be run).
160 JSON_NORETURN static void json_abort(const char *message);
162 /* ref count debugging */
164 #ifdef REFCOUNT_DEBUG
166 static struct lh_table *json_object_table;
168 static void json_object_init(void) __attribute__((constructor));
169 static void json_object_init(void)
171 MC_DEBUG("json_object_init: creating object table\n");
172 json_object_table = lh_kptr_table_new(128, NULL);
175 static void json_object_fini(void) __attribute__((destructor));
176 static void json_object_fini(void)
178 struct lh_entry *ent;
181 if (json_object_table->count)
183 MC_DEBUG("json_object_fini: %d referenced objects at exit\n",
184 json_object_table->count);
185 lh_foreach(json_object_table, ent)
187 struct json_object *obj = (struct json_object *)lh_entry_v(ent);
188 MC_DEBUG("\t%s:%p\n", json_type_to_name(obj->o_type), obj);
192 MC_DEBUG("json_object_fini: freeing object table\n");
193 lh_table_free(json_object_table);
195 #endif /* REFCOUNT_DEBUG */
197 /* helper for accessing the optimized string data component in json_object
199 static inline char *get_string_component_mutable(struct json_object *jso)
201 if (JC_STRING_C(jso)->len < 0)
203 /* Due to json_object_set_string(), we might have a pointer */
204 return JC_STRING(jso)->c_string.pdata;
206 return JC_STRING(jso)->c_string.idata;
208 static inline const char *get_string_component(const struct json_object *jso)
210 return get_string_component_mutable((void *)(uintptr_t)(const void *)jso);
213 /* string escaping */
215 static int json_escape_str(struct printbuf *pb, const char *str, size_t len, int flags)
217 int pos = 0, start_offset = 0;
232 if ((flags & JSON_C_TO_STRING_NOSLASHESCAPE) && c == '/')
238 if (pos - start_offset > 0)
239 printbuf_memappend(pb, str + start_offset, pos - start_offset);
242 printbuf_memappend(pb, "\\b", 2);
244 printbuf_memappend(pb, "\\n", 2);
246 printbuf_memappend(pb, "\\r", 2);
248 printbuf_memappend(pb, "\\t", 2);
250 printbuf_memappend(pb, "\\f", 2);
252 printbuf_memappend(pb, "\\\"", 2);
254 printbuf_memappend(pb, "\\\\", 2);
256 printbuf_memappend(pb, "\\/", 2);
258 start_offset = ++pos;
264 if (pos - start_offset > 0)
265 printbuf_memappend(pb, str + start_offset,
267 snprintf(sbuf, sizeof(sbuf), "\\u00%c%c", json_hex_chars[c >> 4],
268 json_hex_chars[c & 0xf]);
269 printbuf_memappend_fast(pb, sbuf, (int)sizeof(sbuf) - 1);
270 start_offset = ++pos;
276 if (pos - start_offset > 0)
277 printbuf_memappend(pb, str + start_offset, pos - start_offset);
281 /* reference counting */
283 struct json_object *json_object_get(struct json_object *jso)
288 // Don't overflow the refcounter.
289 assert(jso->_ref_count < UINT32_MAX);
291 #if defined(HAVE_ATOMIC_BUILTINS) && defined(ENABLE_THREADING)
292 __sync_add_and_fetch(&jso->_ref_count, 1);
300 int json_object_put(struct json_object *jso)
305 /* Avoid invalid free and crash explicitly instead of (silently)
308 assert(jso->_ref_count > 0);
310 #if defined(HAVE_ATOMIC_BUILTINS) && defined(ENABLE_THREADING)
311 /* Note: this only allow the refcount to remain correct
312 * when multiple threads are adjusting it. It is still an error
313 * for a thread to decrement the refcount if it doesn't "own" it,
314 * as that can result in the thread that loses the race to 0
315 * operating on an already-freed object.
317 if (__sync_sub_and_fetch(&jso->_ref_count, 1) > 0)
320 if (--jso->_ref_count > 0)
324 if (jso->_user_delete)
325 jso->_user_delete(jso, jso->_userdata);
328 case json_type_object: json_object_object_delete(jso); break;
329 case json_type_array: json_object_array_delete(jso); break;
330 case json_type_string: json_object_string_delete(jso); break;
331 default: json_object_generic_delete(jso); break;
336 /* generic object construction and destruction parts */
338 static void json_object_generic_delete(struct json_object *jso)
340 #ifdef REFCOUNT_DEBUG
341 MC_DEBUG("json_object_delete_%s: %p\n", json_type_to_name(jso->o_type), jso);
342 lh_table_delete(json_object_table, jso);
343 #endif /* REFCOUNT_DEBUG */
344 printbuf_free(jso->_pb);
348 static inline struct json_object *json_object_new(enum json_type o_type, size_t alloc_size,
349 json_object_to_json_string_fn *to_json_string)
351 struct json_object *jso;
353 jso = (struct json_object *)malloc(alloc_size);
357 jso->o_type = o_type;
359 jso->_to_json_string = to_json_string;
361 jso->_user_delete = NULL;
362 jso->_userdata = NULL;
363 //jso->... // Type-specific fields must be set by caller
365 #ifdef REFCOUNT_DEBUG
366 lh_table_insert(json_object_table, jso, jso);
367 MC_DEBUG("json_object_new_%s: %p\n", json_type_to_name(jso->o_type), jso);
368 #endif /* REFCOUNT_DEBUG */
372 /* type checking functions */
374 int json_object_is_type(const struct json_object *jso, enum json_type type)
377 return (type == json_type_null);
378 return (jso->o_type == type);
381 enum json_type json_object_get_type(const struct json_object *jso)
384 return json_type_null;
388 void *json_object_get_userdata(json_object *jso)
390 return jso ? jso->_userdata : NULL;
393 void json_object_set_userdata(json_object *jso, void *userdata, json_object_delete_fn *user_delete)
395 // Can't return failure, so abort if we can't perform the operation.
398 // First, clean up any previously existing user info
399 if (jso->_user_delete)
400 jso->_user_delete(jso, jso->_userdata);
402 jso->_userdata = userdata;
403 jso->_user_delete = user_delete;
406 /* set a custom conversion to string */
408 void json_object_set_serializer(json_object *jso, json_object_to_json_string_fn *to_string_func,
409 void *userdata, json_object_delete_fn *user_delete)
411 json_object_set_userdata(jso, userdata, user_delete);
413 if (to_string_func == NULL)
415 // Reset to the standard serialization function
418 case json_type_null: jso->_to_json_string = NULL; break;
419 case json_type_boolean:
420 jso->_to_json_string = &json_object_boolean_to_json_string;
422 case json_type_double:
423 jso->_to_json_string = &json_object_double_to_json_string_default;
425 case json_type_int: jso->_to_json_string = &json_object_int_to_json_string; break;
426 case json_type_object:
427 jso->_to_json_string = &json_object_object_to_json_string;
429 case json_type_array:
430 jso->_to_json_string = &json_object_array_to_json_string;
432 case json_type_string:
433 jso->_to_json_string = &json_object_string_to_json_string;
439 jso->_to_json_string = to_string_func;
442 /* extended conversion to string */
444 const char *json_object_to_json_string_length(struct json_object *jso, int flags, size_t *length)
446 const char *r = NULL;
454 else if ((jso->_pb) || (jso->_pb = printbuf_new()))
456 printbuf_reset(jso->_pb);
458 if (jso->_to_json_string(jso, jso->_pb, 0, flags) >= 0)
460 s = (size_t)jso->_pb->bpos;
470 const char *json_object_to_json_string_ext(struct json_object *jso, int flags)
472 return json_object_to_json_string_length(jso, flags, NULL);
475 /* backwards-compatible conversion to string */
477 const char *json_object_to_json_string(struct json_object *jso)
479 return json_object_to_json_string_ext(jso, JSON_C_TO_STRING_SPACED);
482 static void indent(struct printbuf *pb, int level, int flags)
484 if (flags & JSON_C_TO_STRING_PRETTY)
486 if (flags & JSON_C_TO_STRING_PRETTY_TAB)
488 printbuf_memset(pb, -1, '\t', level);
492 printbuf_memset(pb, -1, ' ', level * 2);
497 /* json_object_object */
499 static int json_object_object_to_json_string(struct json_object *jso, struct printbuf *pb,
500 int level, int flags)
502 int had_children = 0;
503 struct json_object_iter iter;
505 printbuf_strappend(pb, "{" /*}*/);
506 if (flags & JSON_C_TO_STRING_PRETTY)
507 printbuf_strappend(pb, "\n");
508 json_object_object_foreachC(jso, iter)
512 printbuf_strappend(pb, ",");
513 if (flags & JSON_C_TO_STRING_PRETTY)
514 printbuf_strappend(pb, "\n");
517 if (flags & JSON_C_TO_STRING_SPACED && !(flags & JSON_C_TO_STRING_PRETTY))
518 printbuf_strappend(pb, " ");
519 indent(pb, level + 1, flags);
520 printbuf_strappend(pb, "\"");
521 json_escape_str(pb, iter.key, strlen(iter.key), flags);
522 if (flags & JSON_C_TO_STRING_SPACED)
523 printbuf_strappend(pb, "\": ");
525 printbuf_strappend(pb, "\":");
526 if (iter.val == NULL)
527 printbuf_strappend(pb, "null");
528 else if (iter.val->_to_json_string(iter.val, pb, level + 1, flags) < 0)
531 if (flags & JSON_C_TO_STRING_PRETTY)
534 printbuf_strappend(pb, "\n");
535 indent(pb, level, flags);
537 if (flags & JSON_C_TO_STRING_SPACED && !(flags & JSON_C_TO_STRING_PRETTY))
538 return printbuf_strappend(pb, /*{*/ " }");
540 return printbuf_strappend(pb, /*{*/ "}");
543 static void json_object_lh_entry_free(struct lh_entry *ent)
545 if (!ent->k_is_constant)
546 free(lh_entry_k(ent));
547 json_object_put((struct json_object *)lh_entry_v(ent));
550 static void json_object_object_delete(struct json_object *jso_base)
552 lh_table_free(JC_OBJECT(jso_base)->c_object);
553 json_object_generic_delete(jso_base);
556 struct json_object *json_object_new_object(void)
558 struct json_object_object *jso = JSON_OBJECT_NEW(object);
562 lh_kchar_table_new(JSON_OBJECT_DEF_HASH_ENTRIES, &json_object_lh_entry_free);
565 json_object_generic_delete(&jso->base);
572 struct lh_table *json_object_get_object(const struct json_object *jso)
578 case json_type_object: return JC_OBJECT_C(jso)->c_object;
579 default: return NULL;
583 int json_object_object_add_ex(struct json_object *jso, const char *const key,
584 struct json_object *const val, const unsigned opts)
586 struct json_object *existing_value = NULL;
587 struct lh_entry *existing_entry;
590 assert(json_object_get_type(jso) == json_type_object);
592 // We lookup the entry and replace the value, rather than just deleting
593 // and re-adding it, so the existing key remains valid.
594 hash = lh_get_hash(JC_OBJECT(jso)->c_object, (const void *)key);
596 (opts & JSON_C_OBJECT_ADD_KEY_IS_NEW)
598 : lh_table_lookup_entry_w_hash(JC_OBJECT(jso)->c_object, (const void *)key, hash);
600 // The caller must avoid creating loops in the object tree, but do a
601 // quick check anyway to make sure we're not creating a trivial loop.
607 const void *const k =
608 (opts & JSON_C_OBJECT_KEY_IS_CONSTANT) ? (const void *)key : strdup(key);
611 return lh_table_insert_w_hash(JC_OBJECT(jso)->c_object, k, val, hash, opts);
613 existing_value = (json_object *)lh_entry_v(existing_entry);
615 json_object_put(existing_value);
616 existing_entry->v = val;
620 int json_object_object_add(struct json_object *jso, const char *key, struct json_object *val)
622 return json_object_object_add_ex(jso, key, val, 0);
625 int json_object_object_length(const struct json_object *jso)
627 assert(json_object_get_type(jso) == json_type_object);
628 return lh_table_length(JC_OBJECT_C(jso)->c_object);
631 size_t json_c_object_sizeof(void)
633 return sizeof(struct json_object);
636 struct json_object *json_object_object_get(const struct json_object *jso, const char *key)
638 struct json_object *result = NULL;
639 json_object_object_get_ex(jso, key, &result);
643 json_bool json_object_object_get_ex(const struct json_object *jso, const char *key,
644 struct json_object **value)
654 case json_type_object:
655 return lh_table_lookup_ex(JC_OBJECT_C(jso)->c_object, (const void *)key,
664 void json_object_object_del(struct json_object *jso, const char *key)
666 assert(json_object_get_type(jso) == json_type_object);
667 lh_table_delete(JC_OBJECT(jso)->c_object, key);
670 /* json_object_boolean */
672 static int json_object_boolean_to_json_string(struct json_object *jso, struct printbuf *pb,
673 int level, int flags)
675 if (JC_BOOL(jso)->c_boolean)
676 return printbuf_strappend(pb, "true");
677 return printbuf_strappend(pb, "false");
680 struct json_object *json_object_new_boolean(json_bool b)
682 struct json_object_boolean *jso = JSON_OBJECT_NEW(boolean);
689 json_bool json_object_get_boolean(const struct json_object *jso)
695 case json_type_boolean: return JC_BOOL_C(jso)->c_boolean;
697 switch (JC_INT_C(jso)->cint_type)
699 case json_object_int_type_int64: return (JC_INT_C(jso)->cint.c_int64 != 0);
700 case json_object_int_type_uint64: return (JC_INT_C(jso)->cint.c_uint64 != 0);
701 default: json_abort("invalid cint_type");
703 case json_type_double: return (JC_DOUBLE_C(jso)->c_double != 0);
704 case json_type_string: return (JC_STRING_C(jso)->len != 0);
709 int json_object_set_boolean(struct json_object *jso, json_bool new_value)
711 if (!jso || jso->o_type != json_type_boolean)
713 JC_BOOL(jso)->c_boolean = new_value;
717 /* json_object_int */
719 static int json_object_int_to_json_string(struct json_object *jso, struct printbuf *pb, int level,
722 /* room for 19 digits, the sign char, and a null term */
724 if (JC_INT(jso)->cint_type == json_object_int_type_int64)
725 snprintf(sbuf, sizeof(sbuf), "%" PRId64, JC_INT(jso)->cint.c_int64);
727 snprintf(sbuf, sizeof(sbuf), "%" PRIu64, JC_INT(jso)->cint.c_uint64);
728 return printbuf_memappend(pb, sbuf, strlen(sbuf));
731 struct json_object *json_object_new_int(int32_t i)
733 return json_object_new_int64(i);
736 int32_t json_object_get_int(const struct json_object *jso)
740 enum json_type o_type;
745 o_type = jso->o_type;
746 if (o_type == json_type_int)
748 const struct json_object_int *jsoint = JC_INT_C(jso);
749 if (jsoint->cint_type == json_object_int_type_int64)
751 cint64 = jsoint->cint.c_int64;
755 if (jsoint->cint.c_uint64 >= INT64_MAX)
758 cint64 = (int64_t)jsoint->cint.c_uint64;
761 else if (o_type == json_type_string)
764 * Parse strings into 64-bit numbers, then use the
765 * 64-to-32-bit number handling below.
767 if (json_parse_int64(get_string_component(jso), &cint64) != 0)
768 return 0; /* whoops, it didn't work. */
769 o_type = json_type_int;
775 /* Make sure we return the correct values for out of range numbers. */
776 if (cint64 <= INT32_MIN)
778 if (cint64 >= INT32_MAX)
780 return (int32_t)cint64;
781 case json_type_double:
782 cdouble = JC_DOUBLE_C(jso)->c_double;
783 if (cdouble <= INT32_MIN)
785 if (cdouble >= INT32_MAX)
787 return (int32_t)cdouble;
788 case json_type_boolean: return JC_BOOL_C(jso)->c_boolean;
793 int json_object_set_int(struct json_object *jso, int new_value)
795 return json_object_set_int64(jso, (int64_t)new_value);
798 struct json_object *json_object_new_int64(int64_t i)
800 struct json_object_int *jso = JSON_OBJECT_NEW(int);
803 jso->cint.c_int64 = i;
804 jso->cint_type = json_object_int_type_int64;
808 struct json_object *json_object_new_uint64(uint64_t i)
810 struct json_object_int *jso = JSON_OBJECT_NEW(int);
813 jso->cint.c_uint64 = i;
814 jso->cint_type = json_object_int_type_uint64;
818 int64_t json_object_get_int64(const struct json_object *jso)
828 const struct json_object_int *jsoint = JC_INT_C(jso);
829 switch (jsoint->cint_type)
831 case json_object_int_type_int64: return jsoint->cint.c_int64;
832 case json_object_int_type_uint64:
833 if (jsoint->cint.c_uint64 >= INT64_MAX)
835 return (int64_t)jsoint->cint.c_uint64;
836 default: json_abort("invalid cint_type");
839 case json_type_double:
840 // INT64_MAX can't be exactly represented as a double
841 // so cast to tell the compiler it's ok to round up.
842 if (JC_DOUBLE_C(jso)->c_double >= (double)INT64_MAX)
844 if (JC_DOUBLE_C(jso)->c_double <= INT64_MIN)
846 return (int64_t)JC_DOUBLE_C(jso)->c_double;
847 case json_type_boolean: return JC_BOOL_C(jso)->c_boolean;
848 case json_type_string:
849 if (json_parse_int64(get_string_component(jso), &cint) == 0)
856 uint64_t json_object_get_uint64(const struct json_object *jso)
866 const struct json_object_int *jsoint = JC_INT_C(jso);
867 switch (jsoint->cint_type)
869 case json_object_int_type_int64:
870 if (jsoint->cint.c_int64 < 0)
872 return (uint64_t)jsoint->cint.c_int64;
873 case json_object_int_type_uint64: return jsoint->cint.c_uint64;
874 default: json_abort("invalid cint_type");
877 case json_type_double:
878 // UINT64_MAX can't be exactly represented as a double
879 // so cast to tell the compiler it's ok to round up.
880 if (JC_DOUBLE_C(jso)->c_double >= (double)UINT64_MAX)
882 if (JC_DOUBLE_C(jso)->c_double < 0)
884 return (uint64_t)JC_DOUBLE_C(jso)->c_double;
885 case json_type_boolean: return JC_BOOL_C(jso)->c_boolean;
886 case json_type_string:
887 if (json_parse_uint64(get_string_component(jso), &cuint) == 0)
894 int json_object_set_int64(struct json_object *jso, int64_t new_value)
896 if (!jso || jso->o_type != json_type_int)
898 JC_INT(jso)->cint.c_int64 = new_value;
899 JC_INT(jso)->cint_type = json_object_int_type_int64;
903 int json_object_set_uint64(struct json_object *jso, uint64_t new_value)
905 if (!jso || jso->o_type != json_type_int)
907 JC_INT(jso)->cint.c_uint64 = new_value;
908 JC_INT(jso)->cint_type = json_object_int_type_uint64;
912 int json_object_int_inc(struct json_object *jso, int64_t val)
914 struct json_object_int *jsoint;
915 if (!jso || jso->o_type != json_type_int)
917 jsoint = JC_INT(jso);
918 switch (jsoint->cint_type)
920 case json_object_int_type_int64:
921 if (val > 0 && jsoint->cint.c_int64 > INT64_MAX - val)
923 jsoint->cint.c_uint64 = (uint64_t)jsoint->cint.c_int64 + (uint64_t)val;
924 jsoint->cint_type = json_object_int_type_uint64;
926 else if (val < 0 && jsoint->cint.c_int64 < INT64_MIN - val)
928 jsoint->cint.c_int64 = INT64_MIN;
932 jsoint->cint.c_int64 += val;
935 case json_object_int_type_uint64:
936 if (val > 0 && jsoint->cint.c_uint64 > UINT64_MAX - (uint64_t)val)
938 jsoint->cint.c_uint64 = UINT64_MAX;
940 else if (val < 0 && jsoint->cint.c_uint64 < (uint64_t)(-val))
942 jsoint->cint.c_int64 = (int64_t)jsoint->cint.c_uint64 + val;
943 jsoint->cint_type = json_object_int_type_int64;
945 else if (val < 0 && jsoint->cint.c_uint64 >= (uint64_t)(-val))
947 jsoint->cint.c_uint64 -= (uint64_t)(-val);
951 jsoint->cint.c_uint64 += val;
954 default: json_abort("invalid cint_type");
958 /* json_object_double */
960 #if defined(HAVE___THREAD)
961 // i.e. __thread or __declspec(thread)
962 static SPEC___THREAD char *tls_serialization_float_format = NULL;
964 static char *global_serialization_float_format = NULL;
966 int json_c_set_serialization_double_format(const char *double_format, int global_or_thread)
968 if (global_or_thread == JSON_C_OPTION_GLOBAL)
970 #if defined(HAVE___THREAD)
971 if (tls_serialization_float_format)
973 free(tls_serialization_float_format);
974 tls_serialization_float_format = NULL;
977 if (global_serialization_float_format)
978 free(global_serialization_float_format);
979 global_serialization_float_format = double_format ? strdup(double_format) : NULL;
981 else if (global_or_thread == JSON_C_OPTION_THREAD)
983 #if defined(HAVE___THREAD)
984 if (tls_serialization_float_format)
986 free(tls_serialization_float_format);
987 tls_serialization_float_format = NULL;
989 tls_serialization_float_format = double_format ? strdup(double_format) : NULL;
991 _json_c_set_last_err("json_c_set_option: not compiled with __thread support\n");
997 _json_c_set_last_err("json_c_set_option: invalid global_or_thread value: %d\n",
1004 static int json_object_double_to_json_string_format(struct json_object *jso, struct printbuf *pb,
1005 int level, int flags, const char *format)
1007 struct json_object_double *jsodbl = JC_DOUBLE(jso);
1008 char buf[128], *p, *q;
1010 /* Although JSON RFC does not support
1011 * NaN or Infinity as numeric values
1012 * ECMA 262 section 9.8.1 defines
1013 * how to handle these cases as strings
1015 if (isnan(jsodbl->c_double))
1017 size = snprintf(buf, sizeof(buf), "NaN");
1019 else if (isinf(jsodbl->c_double))
1021 if (jsodbl->c_double > 0)
1022 size = snprintf(buf, sizeof(buf), "Infinity");
1024 size = snprintf(buf, sizeof(buf), "-Infinity");
1028 const char *std_format = "%.17g";
1029 int format_drops_decimals = 0;
1030 int looks_numeric = 0;
1034 #if defined(HAVE___THREAD)
1035 if (tls_serialization_float_format)
1036 format = tls_serialization_float_format;
1039 if (global_serialization_float_format)
1040 format = global_serialization_float_format;
1042 format = std_format;
1044 size = snprintf(buf, sizeof(buf), format, jsodbl->c_double);
1049 p = strchr(buf, ',');
1053 p = strchr(buf, '.');
1055 if (format == std_format || strstr(format, ".0f") == NULL)
1056 format_drops_decimals = 1;
1058 looks_numeric = /* Looks like *some* kind of number */
1059 isdigit((unsigned char)buf[0]) ||
1060 (size > 1 && buf[0] == '-' && isdigit((unsigned char)buf[1]));
1062 if (size < (int)sizeof(buf) - 2 && looks_numeric && !p && /* Has no decimal point */
1063 strchr(buf, 'e') == NULL && /* Not scientific notation */
1064 format_drops_decimals)
1066 // Ensure it looks like a float, even if snprintf didn't,
1067 // unless a custom format is set to omit the decimal.
1071 if (p && (flags & JSON_C_TO_STRING_NOZERO))
1073 /* last useful digit, always keep 1 zero */
1075 for (q = p; *q; q++)
1080 /* drop trailing zeroes */
1086 // although unlikely, snprintf can fail
1090 if (size >= (int)sizeof(buf))
1091 // The standard formats are guaranteed not to overrun the buffer,
1092 // but if a custom one happens to do so, just silently truncate.
1093 size = sizeof(buf) - 1;
1094 printbuf_memappend(pb, buf, size);
1098 static int json_object_double_to_json_string_default(struct json_object *jso, struct printbuf *pb,
1099 int level, int flags)
1101 return json_object_double_to_json_string_format(jso, pb, level, flags, NULL);
1104 int json_object_double_to_json_string(struct json_object *jso, struct printbuf *pb, int level,
1107 return json_object_double_to_json_string_format(jso, pb, level, flags,
1108 (const char *)jso->_userdata);
1111 struct json_object *json_object_new_double(double d)
1113 struct json_object_double *jso = JSON_OBJECT_NEW(double);
1116 jso->base._to_json_string = &json_object_double_to_json_string_default;
1121 struct json_object *json_object_new_double_s(double d, const char *ds)
1124 struct json_object *jso = json_object_new_double(d);
1128 new_ds = strdup(ds);
1131 json_object_generic_delete(jso);
1135 json_object_set_serializer(jso, _json_object_userdata_to_json_string, new_ds,
1136 json_object_free_userdata);
1141 * A wrapper around json_object_userdata_to_json_string() used only
1142 * by json_object_new_double_s() just so json_object_set_double() can
1143 * detect when it needs to reset the serializer to the default.
1145 static int _json_object_userdata_to_json_string(struct json_object *jso, struct printbuf *pb,
1146 int level, int flags)
1148 return json_object_userdata_to_json_string(jso, pb, level, flags);
1151 int json_object_userdata_to_json_string(struct json_object *jso, struct printbuf *pb, int level,
1154 int userdata_len = strlen((const char *)jso->_userdata);
1155 printbuf_memappend(pb, (const char *)jso->_userdata, userdata_len);
1156 return userdata_len;
1159 void json_object_free_userdata(struct json_object *jso, void *userdata)
1164 double json_object_get_double(const struct json_object *jso)
1167 char *errPtr = NULL;
1171 switch (jso->o_type)
1173 case json_type_double: return JC_DOUBLE_C(jso)->c_double;
1175 switch (JC_INT_C(jso)->cint_type)
1177 case json_object_int_type_int64: return JC_INT_C(jso)->cint.c_int64;
1178 case json_object_int_type_uint64: return JC_INT_C(jso)->cint.c_uint64;
1179 default: json_abort("invalid cint_type");
1181 case json_type_boolean: return JC_BOOL_C(jso)->c_boolean;
1182 case json_type_string:
1184 cdouble = strtod(get_string_component(jso), &errPtr);
1186 /* if conversion stopped at the first character, return 0.0 */
1187 if (errPtr == get_string_component(jso))
1194 * Check that the conversion terminated on something sensible
1196 * For example, { "pay" : 123AB } would parse as 123.
1198 if (*errPtr != '\0')
1205 * If strtod encounters a string which would exceed the
1206 * capacity of a double, it returns +/- HUGE_VAL and sets
1207 * errno to ERANGE. But +/- HUGE_VAL is also a valid result
1208 * from a conversion, so we need to check errno.
1210 * Underflow also sets errno to ERANGE, but it returns 0 in
1211 * that case, which is what we will return anyway.
1213 * See CERT guideline ERR30-C
1215 if ((HUGE_VAL == cdouble || -HUGE_VAL == cdouble) && (ERANGE == errno))
1218 default: errno = EINVAL; return 0.0;
1222 int json_object_set_double(struct json_object *jso, double new_value)
1224 if (!jso || jso->o_type != json_type_double)
1226 JC_DOUBLE(jso)->c_double = new_value;
1227 if (jso->_to_json_string == &_json_object_userdata_to_json_string)
1228 json_object_set_serializer(jso, NULL, NULL, NULL);
1232 /* json_object_string */
1234 static int json_object_string_to_json_string(struct json_object *jso, struct printbuf *pb,
1235 int level, int flags)
1237 ssize_t len = JC_STRING(jso)->len;
1238 printbuf_strappend(pb, "\"");
1239 json_escape_str(pb, get_string_component(jso), len < 0 ? -(ssize_t)len : len, flags);
1240 printbuf_strappend(pb, "\"");
1244 static void json_object_string_delete(struct json_object *jso)
1246 if (JC_STRING(jso)->len < 0)
1247 free(JC_STRING(jso)->c_string.pdata);
1248 json_object_generic_delete(jso);
1251 static struct json_object *_json_object_new_string(const char *s, const size_t len)
1254 struct json_object_string *jso;
1257 * Structures Actual memory layout
1258 * ------------------- --------------------
1259 * [json_object_string [json_object_string
1260 * [json_object] [json_object]
1261 * ...other fields... ...other fields...
1269 if (len > (SSIZE_T_MAX - (sizeof(*jso) - sizeof(jso->c_string)) - 1))
1271 objsize = (sizeof(*jso) - sizeof(jso->c_string)) + len + 1;
1272 if (len < sizeof(void *))
1273 // We need a minimum size to support json_object_set_string() mutability
1274 // so we can stuff a pointer into pdata :(
1275 objsize += sizeof(void *) - len;
1277 jso = (struct json_object_string *)json_object_new(json_type_string, objsize,
1278 &json_object_string_to_json_string);
1283 memcpy(jso->c_string.idata, s, len);
1284 jso->c_string.idata[len] = '\0';
1288 struct json_object *json_object_new_string(const char *s)
1290 return _json_object_new_string(s, strlen(s));
1293 struct json_object *json_object_new_string_len(const char *s, const int len)
1295 return _json_object_new_string(s, len);
1298 const char *json_object_get_string(struct json_object *jso)
1302 switch (jso->o_type)
1304 case json_type_string: return get_string_component(jso);
1305 default: return json_object_to_json_string(jso);
1308 int json_object_get_string_len(const struct json_object *jso)
1313 switch (jso->o_type)
1315 case json_type_string:
1317 len = JC_STRING_C(jso)->len;
1318 return (len < 0) ? -(ssize_t)len : len;
1324 static int _json_object_set_string_len(json_object *jso, const char *s, size_t len)
1329 if (jso == NULL || jso->o_type != json_type_string)
1332 if (len >= SSIZE_T_MAX - 1)
1333 // jso->len is a signed ssize_t, so it can't hold the
1334 // full size_t range.
1337 dstbuf = get_string_component_mutable(jso);
1338 curlen = JC_STRING(jso)->len;
1343 if ((ssize_t)len > curlen)
1345 // We have no way to return the new ptr from realloc(jso, newlen)
1346 // and we have no way of knowing whether there's extra room available
1347 // so we need to stuff a pointer in to pdata :(
1348 dstbuf = (char *)malloc(len + 1);
1351 if (JC_STRING(jso)->len < 0)
1352 free(JC_STRING(jso)->c_string.pdata);
1353 JC_STRING(jso)->c_string.pdata = dstbuf;
1354 newlen = -(ssize_t)len;
1356 else if (JC_STRING(jso)->len < 0)
1358 // We've got enough room in the separate allocated buffer,
1359 // so use it as-is and continue to indicate that pdata is used.
1360 newlen = -(ssize_t)len;
1363 memcpy(dstbuf, (const void *)s, len);
1365 JC_STRING(jso)->len = newlen;
1369 int json_object_set_string(json_object *jso, const char *s)
1371 return _json_object_set_string_len(jso, s, strlen(s));
1374 int json_object_set_string_len(json_object *jso, const char *s, int len)
1376 return _json_object_set_string_len(jso, s, len);
1379 /* json_object_array */
1381 static int json_object_array_to_json_string(struct json_object *jso, struct printbuf *pb, int level,
1384 int had_children = 0;
1387 printbuf_strappend(pb, "[");
1388 if (flags & JSON_C_TO_STRING_PRETTY)
1389 printbuf_strappend(pb, "\n");
1390 for (ii = 0; ii < json_object_array_length(jso); ii++)
1392 struct json_object *val;
1395 printbuf_strappend(pb, ",");
1396 if (flags & JSON_C_TO_STRING_PRETTY)
1397 printbuf_strappend(pb, "\n");
1400 if (flags & JSON_C_TO_STRING_SPACED && !(flags & JSON_C_TO_STRING_PRETTY))
1401 printbuf_strappend(pb, " ");
1402 indent(pb, level + 1, flags);
1403 val = json_object_array_get_idx(jso, ii);
1405 printbuf_strappend(pb, "null");
1406 else if (val->_to_json_string(val, pb, level + 1, flags) < 0)
1409 if (flags & JSON_C_TO_STRING_PRETTY)
1412 printbuf_strappend(pb, "\n");
1413 indent(pb, level, flags);
1416 if (flags & JSON_C_TO_STRING_SPACED && !(flags & JSON_C_TO_STRING_PRETTY))
1417 return printbuf_strappend(pb, " ]");
1418 return printbuf_strappend(pb, "]");
1421 static void json_object_array_entry_free(void *data)
1423 json_object_put((struct json_object *)data);
1426 static void json_object_array_delete(struct json_object *jso)
1428 array_list_free(JC_ARRAY(jso)->c_array);
1429 json_object_generic_delete(jso);
1432 struct json_object *json_object_new_array(void)
1434 return json_object_new_array_ext(ARRAY_LIST_DEFAULT_SIZE);
1436 struct json_object *json_object_new_array_ext(int initial_size)
1438 struct json_object_array *jso = JSON_OBJECT_NEW(array);
1441 jso->c_array = array_list_new2(&json_object_array_entry_free, initial_size);
1442 if (jso->c_array == NULL)
1450 struct array_list *json_object_get_array(const struct json_object *jso)
1454 switch (jso->o_type)
1456 case json_type_array: return JC_ARRAY_C(jso)->c_array;
1457 default: return NULL;
1461 void json_object_array_sort(struct json_object *jso, int (*sort_fn)(const void *, const void *))
1463 assert(json_object_get_type(jso) == json_type_array);
1464 array_list_sort(JC_ARRAY(jso)->c_array, sort_fn);
1467 struct json_object *json_object_array_bsearch(const struct json_object *key,
1468 const struct json_object *jso,
1469 int (*sort_fn)(const void *, const void *))
1471 struct json_object **result;
1473 assert(json_object_get_type(jso) == json_type_array);
1474 result = (struct json_object **)array_list_bsearch((const void **)(void *)&key,
1475 JC_ARRAY_C(jso)->c_array, sort_fn);
1482 size_t json_object_array_length(const struct json_object *jso)
1484 assert(json_object_get_type(jso) == json_type_array);
1485 return array_list_length(JC_ARRAY_C(jso)->c_array);
1488 int json_object_array_add(struct json_object *jso, struct json_object *val)
1490 assert(json_object_get_type(jso) == json_type_array);
1491 return array_list_add(JC_ARRAY(jso)->c_array, val);
1494 int json_object_array_put_idx(struct json_object *jso, size_t idx, struct json_object *val)
1496 assert(json_object_get_type(jso) == json_type_array);
1497 return array_list_put_idx(JC_ARRAY(jso)->c_array, idx, val);
1500 int json_object_array_del_idx(struct json_object *jso, size_t idx, size_t count)
1502 assert(json_object_get_type(jso) == json_type_array);
1503 return array_list_del_idx(JC_ARRAY(jso)->c_array, idx, count);
1506 struct json_object *json_object_array_get_idx(const struct json_object *jso, size_t idx)
1508 assert(json_object_get_type(jso) == json_type_array);
1509 return (struct json_object *)array_list_get_idx(JC_ARRAY_C(jso)->c_array, idx);
1512 static int json_array_equal(struct json_object *jso1, struct json_object *jso2)
1516 len = json_object_array_length(jso1);
1517 if (len != json_object_array_length(jso2))
1520 for (i = 0; i < len; i++)
1522 if (!json_object_equal(json_object_array_get_idx(jso1, i),
1523 json_object_array_get_idx(jso2, i)))
1529 int json_object_array_shrink(struct json_object *jso, int empty_slots)
1531 if (empty_slots < 0)
1532 json_abort("json_object_array_shrink called with negative empty_slots");
1533 return array_list_shrink(JC_ARRAY(jso)->c_array, empty_slots);
1536 struct json_object *json_object_new_null(void)
1541 static int json_object_all_values_equal(struct json_object *jso1, struct json_object *jso2)
1543 struct json_object_iter iter;
1544 struct json_object *sub;
1546 assert(json_object_get_type(jso1) == json_type_object);
1547 assert(json_object_get_type(jso2) == json_type_object);
1548 /* Iterate over jso1 keys and see if they exist and are equal in jso2 */
1549 json_object_object_foreachC(jso1, iter)
1551 if (!lh_table_lookup_ex(JC_OBJECT(jso2)->c_object, (void *)iter.key,
1552 (void **)(void *)&sub))
1554 if (!json_object_equal(iter.val, sub))
1558 /* Iterate over jso2 keys to see if any exist that are not in jso1 */
1559 json_object_object_foreachC(jso2, iter)
1561 if (!lh_table_lookup_ex(JC_OBJECT(jso1)->c_object, (void *)iter.key,
1562 (void **)(void *)&sub))
1569 int json_object_equal(struct json_object *jso1, struct json_object *jso2)
1577 if (jso1->o_type != jso2->o_type)
1580 switch (jso1->o_type)
1582 case json_type_boolean: return (JC_BOOL(jso1)->c_boolean == JC_BOOL(jso2)->c_boolean);
1584 case json_type_double: return (JC_DOUBLE(jso1)->c_double == JC_DOUBLE(jso2)->c_double);
1588 struct json_object_int *int1 = JC_INT(jso1);
1589 struct json_object_int *int2 = JC_INT(jso2);
1590 if (int1->cint_type == json_object_int_type_int64)
1592 if (int2->cint_type == json_object_int_type_int64)
1593 return (int1->cint.c_int64 == int2->cint.c_int64);
1594 if (int1->cint.c_int64 < 0)
1596 return ((uint64_t)int1->cint.c_int64 == int2->cint.c_uint64);
1598 // else jso1 is a uint64
1599 if (int2->cint_type == json_object_int_type_uint64)
1600 return (int1->cint.c_uint64 == int2->cint.c_uint64);
1601 if (int2->cint.c_int64 < 0)
1603 return (int1->cint.c_uint64 == (uint64_t)int2->cint.c_int64);
1606 case json_type_string:
1608 return (json_object_get_string_len(jso1) == json_object_get_string_len(jso2) &&
1609 memcmp(get_string_component(jso1), get_string_component(jso2),
1610 json_object_get_string_len(jso1)) == 0);
1613 case json_type_object: return json_object_all_values_equal(jso1, jso2);
1615 case json_type_array: return json_array_equal(jso1, jso2);
1617 case json_type_null: return 1;
1623 static int json_object_copy_serializer_data(struct json_object *src, struct json_object *dst)
1625 if (!src->_userdata && !src->_user_delete)
1628 if (dst->_to_json_string == json_object_userdata_to_json_string ||
1629 dst->_to_json_string == _json_object_userdata_to_json_string)
1631 dst->_userdata = strdup(src->_userdata);
1633 // else if ... other supported serializers ...
1636 _json_c_set_last_err(
1637 "json_object_deep_copy: unable to copy unknown serializer data: %p\n",
1638 (void *)dst->_to_json_string);
1641 dst->_user_delete = src->_user_delete;
1646 * The default shallow copy implementation. Simply creates a new object of the same
1647 * type but does *not* copy over _userdata nor retain any custom serializer.
1648 * If custom serializers are in use, json_object_deep_copy() must be passed a shallow copy
1649 * implementation that is aware of how to copy them.
1651 * This always returns -1 or 1. It will never return 2 since it does not copy the serializer.
1653 int json_c_shallow_copy_default(json_object *src, json_object *parent, const char *key,
1654 size_t index, json_object **dst)
1656 switch (src->o_type)
1658 case json_type_boolean: *dst = json_object_new_boolean(JC_BOOL(src)->c_boolean); break;
1660 case json_type_double: *dst = json_object_new_double(JC_DOUBLE(src)->c_double); break;
1663 switch (JC_INT(src)->cint_type)
1665 case json_object_int_type_int64:
1666 *dst = json_object_new_int64(JC_INT(src)->cint.c_int64);
1668 case json_object_int_type_uint64:
1669 *dst = json_object_new_uint64(JC_INT(src)->cint.c_uint64);
1671 default: json_abort("invalid cint_type");
1675 case json_type_string: *dst = json_object_new_string(get_string_component(src)); break;
1677 case json_type_object: *dst = json_object_new_object(); break;
1679 case json_type_array: *dst = json_object_new_array(); break;
1681 default: errno = EINVAL; return -1;
1689 (*dst)->_to_json_string = src->_to_json_string;
1690 // _userdata and _user_delete are copied later
1695 * The actual guts of json_object_deep_copy(), with a few additional args
1696 * needed so we can keep track of where we are within the object tree.
1698 * Note: caller is responsible for freeing *dst if this fails and returns -1.
1700 static int json_object_deep_copy_recursive(struct json_object *src, struct json_object *parent,
1701 const char *key_in_parent, size_t index_in_parent,
1702 struct json_object **dst,
1703 json_c_shallow_copy_fn *shallow_copy)
1705 struct json_object_iter iter;
1706 size_t src_array_len, ii;
1708 int shallow_copy_rc = 0;
1709 shallow_copy_rc = shallow_copy(src, parent, key_in_parent, index_in_parent, dst);
1710 /* -1=error, 1=object created ok, 2=userdata set */
1711 if (shallow_copy_rc < 1)
1716 assert(*dst != NULL);
1718 switch (src->o_type)
1720 case json_type_object:
1721 json_object_object_foreachC(src, iter)
1723 struct json_object *jso = NULL;
1724 /* This handles the `json_type_null` case */
1727 else if (json_object_deep_copy_recursive(iter.val, src, iter.key, -1, &jso,
1730 json_object_put(jso);
1734 if (json_object_object_add(*dst, iter.key, jso) < 0)
1736 json_object_put(jso);
1742 case json_type_array:
1743 src_array_len = json_object_array_length(src);
1744 for (ii = 0; ii < src_array_len; ii++)
1746 struct json_object *jso = NULL;
1747 struct json_object *jso1 = json_object_array_get_idx(src, ii);
1748 /* This handles the `json_type_null` case */
1751 else if (json_object_deep_copy_recursive(jso1, src, NULL, ii, &jso,
1754 json_object_put(jso);
1758 if (json_object_array_add(*dst, jso) < 0)
1760 json_object_put(jso);
1768 /* else, nothing to do, shallow_copy already did. */
1771 if (shallow_copy_rc != 2)
1772 return json_object_copy_serializer_data(src, *dst);
1777 int json_object_deep_copy(struct json_object *src, struct json_object **dst,
1778 json_c_shallow_copy_fn *shallow_copy)
1782 /* Check if arguments are sane ; *dst must not point to a non-NULL object */
1783 if (!src || !dst || *dst)
1789 if (shallow_copy == NULL)
1790 shallow_copy = json_c_shallow_copy_default;
1792 rc = json_object_deep_copy_recursive(src, NULL, NULL, -1, dst, shallow_copy);
1795 json_object_put(*dst);
1802 static void json_abort(const char *message)
1804 if (message != NULL)
1805 fprintf(stderr, "json-c aborts with error: %s\n", message);