Coverage Report

Created: 2026-10-16 07:06

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