Coverage Report

Created: 2026-07-16 06:57

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