• source navigation  • diff markup  • identifier search  • freetext search  • 

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

This page was automatically generated by LXR 0.3.1.  •  OpenWrt