You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

json_object.c 50 kB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
5 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837
  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. #include "config.h"
  11. #include "strerror_override.h"
  12. #include <assert.h>
  13. #include <ctype.h>
  14. #ifdef HAVE_LIMITS_H
  15. #include <limits.h>
  16. #endif
  17. #include <math.h>
  18. #include <stddef.h>
  19. #include <stdio.h>
  20. #include <stdlib.h>
  21. #include <string.h>
  22. #include "arraylist.h"
  23. #include "debug.h"
  24. #include "json_inttypes.h"
  25. #include "json_object.h"
  26. #include "json_object_private.h"
  27. #include "json_util.h"
  28. #include "linkhash.h"
  29. #include "math_compat.h"
  30. #include "printbuf.h"
  31. #include "snprintf_compat.h"
  32. #include "strdup_compat.h"
  33. #if SIZEOF_LONG_LONG != SIZEOF_INT64_T
  34. #error "The long long type isn't 64-bits"
  35. #endif
  36. // Don't define this. It's not thread-safe.
  37. /* #define REFCOUNT_DEBUG 1 */
  38. const char *json_hex_chars = "0123456789abcdefABCDEF";
  39. static void json_object_generic_delete(struct json_object *jso);
  40. #if defined(_MSC_VER) && (_MSC_VER <= 1800)
  41. /* VS2013 doesn't know about "inline" */
  42. #define inline __inline
  43. #elif defined(AIX_CC)
  44. #define inline
  45. #endif
  46. /*
  47. * Helper functions to more safely cast to a particular type of json_object
  48. */
  49. static inline struct json_object_object *JC_OBJECT(struct json_object *jso)
  50. {
  51. return (void *)jso;
  52. }
  53. static inline const struct json_object_object *JC_OBJECT_C(const struct json_object *jso)
  54. {
  55. return (const void *)jso;
  56. }
  57. static inline struct json_object_array *JC_ARRAY(struct json_object *jso)
  58. {
  59. return (void *)jso;
  60. }
  61. static inline const struct json_object_array *JC_ARRAY_C(const struct json_object *jso)
  62. {
  63. return (const void *)jso;
  64. }
  65. static inline struct json_object_boolean *JC_BOOL(struct json_object *jso)
  66. {
  67. return (void *)jso;
  68. }
  69. static inline const struct json_object_boolean *JC_BOOL_C(const struct json_object *jso)
  70. {
  71. return (const void *)jso;
  72. }
  73. static inline struct json_object_double *JC_DOUBLE(struct json_object *jso)
  74. {
  75. return (void *)jso;
  76. }
  77. static inline const struct json_object_double *JC_DOUBLE_C(const struct json_object *jso)
  78. {
  79. return (const void *)jso;
  80. }
  81. static inline struct json_object_int *JC_INT(struct json_object *jso)
  82. {
  83. return (void *)jso;
  84. }
  85. static inline const struct json_object_int *JC_INT_C(const struct json_object *jso)
  86. {
  87. return (const void *)jso;
  88. }
  89. static inline struct json_object_string *JC_STRING(struct json_object *jso)
  90. {
  91. return (void *)jso;
  92. }
  93. static inline const struct json_object_string *JC_STRING_C(const struct json_object *jso)
  94. {
  95. return (const void *)jso;
  96. }
  97. #define JC_CONCAT(a, b) a##b
  98. #define JC_CONCAT3(a, b, c) a##b##c
  99. #define JSON_OBJECT_NEW(jtype) \
  100. (struct JC_CONCAT(json_object_, jtype) *)json_object_new( \
  101. JC_CONCAT(json_type_, jtype), sizeof(struct JC_CONCAT(json_object_, jtype)), \
  102. &JC_CONCAT3(json_object_, jtype, _to_json_string))
  103. static inline struct json_object *json_object_new(enum json_type o_type, size_t alloc_size,
  104. json_object_to_json_string_fn *to_json_string);
  105. static void json_object_object_delete(struct json_object *jso_base);
  106. static void json_object_string_delete(struct json_object *jso);
  107. static void json_object_array_delete(struct json_object *jso);
  108. static json_object_to_json_string_fn json_object_object_to_json_string;
  109. static json_object_to_json_string_fn json_object_boolean_to_json_string;
  110. static json_object_to_json_string_fn json_object_double_to_json_string_default;
  111. static json_object_to_json_string_fn json_object_int_to_json_string;
  112. static json_object_to_json_string_fn json_object_string_to_json_string;
  113. static json_object_to_json_string_fn json_object_array_to_json_string;
  114. static json_object_to_json_string_fn _json_object_userdata_to_json_string;
  115. #ifndef JSON_NORETURN
  116. #if defined(_MSC_VER)
  117. #define JSON_NORETURN __declspec(noreturn)
  118. #elif defined(__OS400__)
  119. #define JSON_NORETURN
  120. #else
  121. /* 'cold' attribute is for optimization, telling the computer this code
  122. * path is unlikely.
  123. */
  124. #define JSON_NORETURN __attribute__((noreturn, cold))
  125. #endif
  126. #endif
  127. /**
  128. * Abort and optionally print a message on standard error.
  129. * This should be used rather than assert() for unconditional abortion
  130. * (in particular for code paths which are never supposed to be run).
  131. * */
  132. JSON_NORETURN static void json_abort(const char *message);
  133. /* ref count debugging */
  134. #ifdef REFCOUNT_DEBUG
  135. static struct lh_table *json_object_table;
  136. static void json_object_init(void) __attribute__((constructor));
  137. static void json_object_init(void)
  138. {
  139. MC_DEBUG("json_object_init: creating object table\n");
  140. json_object_table = lh_kptr_table_new(128, NULL);
  141. }
  142. static void json_object_fini(void) __attribute__((destructor));
  143. static void json_object_fini(void)
  144. {
  145. struct lh_entry *ent;
  146. if (MC_GET_DEBUG())
  147. {
  148. if (json_object_table->count)
  149. {
  150. MC_DEBUG("json_object_fini: %d referenced objects at exit\n",
  151. json_object_table->count);
  152. lh_foreach(json_object_table, ent)
  153. {
  154. struct json_object *obj = (struct json_object *)lh_entry_v(ent);
  155. MC_DEBUG("\t%s:%p\n", json_type_to_name(obj->o_type), obj);
  156. }
  157. }
  158. }
  159. MC_DEBUG("json_object_fini: freeing object table\n");
  160. lh_table_free(json_object_table);
  161. }
  162. #endif /* REFCOUNT_DEBUG */
  163. /* helper for accessing the optimized string data component in json_object
  164. */
  165. static inline char *get_string_component_mutable(struct json_object *jso)
  166. {
  167. if (JC_STRING_C(jso)->len < 0)
  168. {
  169. /* Due to json_object_set_string(), we might have a pointer */
  170. return JC_STRING(jso)->c_string.pdata;
  171. }
  172. return JC_STRING(jso)->c_string.idata;
  173. }
  174. static inline const char *get_string_component(const struct json_object *jso)
  175. {
  176. return get_string_component_mutable((void *)(uintptr_t)(const void *)jso);
  177. }
  178. /* string escaping */
  179. static int json_escape_str(struct printbuf *pb, const char *str, size_t len, int flags)
  180. {
  181. size_t pos = 0, start_offset = 0;
  182. unsigned char c;
  183. while (len--)
  184. {
  185. c = str[pos];
  186. switch (c)
  187. {
  188. case '\b':
  189. case '\n':
  190. case '\r':
  191. case '\t':
  192. case '\f':
  193. case '"':
  194. case '\\':
  195. case '/':
  196. if ((flags & JSON_C_TO_STRING_NOSLASHESCAPE) && c == '/')
  197. {
  198. pos++;
  199. break;
  200. }
  201. if (pos > start_offset)
  202. printbuf_memappend(pb, str + start_offset, pos - start_offset);
  203. if (c == '\b')
  204. printbuf_memappend(pb, "\\b", 2);
  205. else if (c == '\n')
  206. printbuf_memappend(pb, "\\n", 2);
  207. else if (c == '\r')
  208. printbuf_memappend(pb, "\\r", 2);
  209. else if (c == '\t')
  210. printbuf_memappend(pb, "\\t", 2);
  211. else if (c == '\f')
  212. printbuf_memappend(pb, "\\f", 2);
  213. else if (c == '"')
  214. printbuf_memappend(pb, "\\\"", 2);
  215. else if (c == '\\')
  216. printbuf_memappend(pb, "\\\\", 2);
  217. else if (c == '/')
  218. printbuf_memappend(pb, "\\/", 2);
  219. start_offset = ++pos;
  220. break;
  221. default:
  222. if (c < ' ')
  223. {
  224. char sbuf[7];
  225. if (pos > start_offset)
  226. printbuf_memappend(pb, str + start_offset,
  227. pos - start_offset);
  228. snprintf(sbuf, sizeof(sbuf), "\\u00%c%c", json_hex_chars[c >> 4],
  229. json_hex_chars[c & 0xf]);
  230. printbuf_memappend_fast(pb, sbuf, (int)sizeof(sbuf) - 1);
  231. start_offset = ++pos;
  232. }
  233. else
  234. pos++;
  235. }
  236. }
  237. if (pos > start_offset)
  238. printbuf_memappend(pb, str + start_offset, pos - start_offset);
  239. return 0;
  240. }
  241. /* reference counting */
  242. struct json_object *json_object_get(struct json_object *jso)
  243. {
  244. if (!jso)
  245. return jso;
  246. // Don't overflow the refcounter.
  247. assert(jso->_ref_count < UINT32_MAX);
  248. #if defined(HAVE_ATOMIC_BUILTINS) && defined(ENABLE_THREADING)
  249. __sync_add_and_fetch(&jso->_ref_count, 1);
  250. #else
  251. ++jso->_ref_count;
  252. #endif
  253. return jso;
  254. }
  255. int json_object_put(struct json_object *jso)
  256. {
  257. if (!jso)
  258. return 0;
  259. /* Avoid invalid free and crash explicitly instead of (silently)
  260. * segfaulting.
  261. */
  262. assert(jso->_ref_count > 0);
  263. #if defined(HAVE_ATOMIC_BUILTINS) && defined(ENABLE_THREADING)
  264. /* Note: this only allow the refcount to remain correct
  265. * when multiple threads are adjusting it. It is still an error
  266. * for a thread to decrement the refcount if it doesn't "own" it,
  267. * as that can result in the thread that loses the race to 0
  268. * operating on an already-freed object.
  269. */
  270. if (__sync_sub_and_fetch(&jso->_ref_count, 1) > 0)
  271. return 0;
  272. #else
  273. if (--jso->_ref_count > 0)
  274. return 0;
  275. #endif
  276. if (jso->_user_delete)
  277. jso->_user_delete(jso, jso->_userdata);
  278. switch (jso->o_type)
  279. {
  280. case json_type_object: json_object_object_delete(jso); break;
  281. case json_type_array: json_object_array_delete(jso); break;
  282. case json_type_string: json_object_string_delete(jso); break;
  283. default: json_object_generic_delete(jso); break;
  284. }
  285. return 1;
  286. }
  287. /* generic object construction and destruction parts */
  288. static void json_object_generic_delete(struct json_object *jso)
  289. {
  290. #ifdef REFCOUNT_DEBUG
  291. MC_DEBUG("json_object_delete_%s: %p\n", json_type_to_name(jso->o_type), jso);
  292. lh_table_delete(json_object_table, jso);
  293. #endif /* REFCOUNT_DEBUG */
  294. printbuf_free(jso->_pb);
  295. free(jso);
  296. }
  297. static inline struct json_object *json_object_new(enum json_type o_type, size_t alloc_size,
  298. json_object_to_json_string_fn *to_json_string)
  299. {
  300. struct json_object *jso;
  301. jso = (struct json_object *)malloc(alloc_size);
  302. if (!jso)
  303. return NULL;
  304. jso->o_type = o_type;
  305. jso->_ref_count = 1;
  306. jso->_to_json_string = to_json_string;
  307. jso->_pb = NULL;
  308. jso->_user_delete = NULL;
  309. jso->_userdata = NULL;
  310. //jso->... // Type-specific fields must be set by caller
  311. #ifdef REFCOUNT_DEBUG
  312. lh_table_insert(json_object_table, jso, jso);
  313. MC_DEBUG("json_object_new_%s: %p\n", json_type_to_name(jso->o_type), jso);
  314. #endif /* REFCOUNT_DEBUG */
  315. return jso;
  316. }
  317. /* type checking functions */
  318. int json_object_is_type(const struct json_object *jso, enum json_type type)
  319. {
  320. if (!jso)
  321. return (type == json_type_null);
  322. return (jso->o_type == type);
  323. }
  324. enum json_type json_object_get_type(const struct json_object *jso)
  325. {
  326. if (!jso)
  327. return json_type_null;
  328. return jso->o_type;
  329. }
  330. void *json_object_get_userdata(json_object *jso)
  331. {
  332. return jso ? jso->_userdata : NULL;
  333. }
  334. void json_object_set_userdata(json_object *jso, void *userdata, json_object_delete_fn *user_delete)
  335. {
  336. // Can't return failure, so abort if we can't perform the operation.
  337. assert(jso != NULL);
  338. // First, clean up any previously existing user info
  339. if (jso->_user_delete)
  340. jso->_user_delete(jso, jso->_userdata);
  341. jso->_userdata = userdata;
  342. jso->_user_delete = user_delete;
  343. }
  344. /* set a custom conversion to string */
  345. void json_object_set_serializer(json_object *jso, json_object_to_json_string_fn *to_string_func,
  346. void *userdata, json_object_delete_fn *user_delete)
  347. {
  348. json_object_set_userdata(jso, userdata, user_delete);
  349. if (to_string_func == NULL)
  350. {
  351. // Reset to the standard serialization function
  352. switch (jso->o_type)
  353. {
  354. case json_type_null: jso->_to_json_string = NULL; break;
  355. case json_type_boolean:
  356. jso->_to_json_string = &json_object_boolean_to_json_string;
  357. break;
  358. case json_type_double:
  359. jso->_to_json_string = &json_object_double_to_json_string_default;
  360. break;
  361. case json_type_int: jso->_to_json_string = &json_object_int_to_json_string; break;
  362. case json_type_object:
  363. jso->_to_json_string = &json_object_object_to_json_string;
  364. break;
  365. case json_type_array:
  366. jso->_to_json_string = &json_object_array_to_json_string;
  367. break;
  368. case json_type_string:
  369. jso->_to_json_string = &json_object_string_to_json_string;
  370. break;
  371. }
  372. return;
  373. }
  374. jso->_to_json_string = to_string_func;
  375. }
  376. /* extended conversion to string */
  377. const char *json_object_to_json_string_length(struct json_object *jso, int flags, size_t *length)
  378. {
  379. const char *r = NULL;
  380. size_t s = 0;
  381. if (!jso)
  382. {
  383. s = 4;
  384. r = "null";
  385. }
  386. else if ((jso->_pb) || (jso->_pb = printbuf_new()))
  387. {
  388. printbuf_reset(jso->_pb);
  389. if (jso->_to_json_string(jso, jso->_pb, 0, flags) >= 0)
  390. {
  391. s = (size_t)jso->_pb->bpos;
  392. r = jso->_pb->buf;
  393. }
  394. }
  395. if (length)
  396. *length = s;
  397. return r;
  398. }
  399. const char *json_object_to_json_string_ext(struct json_object *jso, int flags)
  400. {
  401. return json_object_to_json_string_length(jso, flags, NULL);
  402. }
  403. /* backwards-compatible conversion to string */
  404. const char *json_object_to_json_string(struct json_object *jso)
  405. {
  406. return json_object_to_json_string_ext(jso, JSON_C_TO_STRING_SPACED);
  407. }
  408. static void indent(struct printbuf *pb, int level, int flags)
  409. {
  410. if (flags & JSON_C_TO_STRING_PRETTY)
  411. {
  412. if (flags & JSON_C_TO_STRING_PRETTY_TAB)
  413. {
  414. printbuf_memset(pb, -1, '\t', level);
  415. }
  416. else
  417. {
  418. printbuf_memset(pb, -1, ' ', level * 2);
  419. }
  420. }
  421. }
  422. /* json_object_object */
  423. static int json_object_object_to_json_string(struct json_object *jso, struct printbuf *pb,
  424. int level, int flags)
  425. {
  426. int had_children = 0;
  427. struct json_object_iter iter;
  428. printbuf_strappend(pb, "{" /*}*/);
  429. if (flags & JSON_C_TO_STRING_PRETTY)
  430. printbuf_strappend(pb, "\n");
  431. json_object_object_foreachC(jso, iter)
  432. {
  433. if (had_children)
  434. {
  435. printbuf_strappend(pb, ",");
  436. if (flags & JSON_C_TO_STRING_PRETTY)
  437. printbuf_strappend(pb, "\n");
  438. }
  439. had_children = 1;
  440. if (flags & JSON_C_TO_STRING_SPACED && !(flags & JSON_C_TO_STRING_PRETTY))
  441. printbuf_strappend(pb, " ");
  442. indent(pb, level + 1, flags);
  443. printbuf_strappend(pb, "\"");
  444. json_escape_str(pb, iter.key, strlen(iter.key), flags);
  445. if (flags & JSON_C_TO_STRING_SPACED)
  446. printbuf_strappend(pb, "\": ");
  447. else
  448. printbuf_strappend(pb, "\":");
  449. if (iter.val == NULL)
  450. printbuf_strappend(pb, "null");
  451. else if (iter.val->_to_json_string(iter.val, pb, level + 1, flags) < 0)
  452. return -1;
  453. }
  454. if (flags & JSON_C_TO_STRING_PRETTY)
  455. {
  456. if (had_children)
  457. printbuf_strappend(pb, "\n");
  458. indent(pb, level, flags);
  459. }
  460. if (flags & JSON_C_TO_STRING_SPACED && !(flags & JSON_C_TO_STRING_PRETTY))
  461. return printbuf_strappend(pb, /*{*/ " }");
  462. else
  463. return printbuf_strappend(pb, /*{*/ "}");
  464. }
  465. static void json_object_lh_entry_free(struct lh_entry *ent)
  466. {
  467. if (!ent->k_is_constant)
  468. free(lh_entry_k(ent));
  469. json_object_put((struct json_object *)lh_entry_v(ent));
  470. }
  471. static void json_object_object_delete(struct json_object *jso_base)
  472. {
  473. lh_table_free(JC_OBJECT(jso_base)->c_object);
  474. json_object_generic_delete(jso_base);
  475. }
  476. struct json_object *json_object_new_object(void)
  477. {
  478. struct json_object_object *jso = JSON_OBJECT_NEW(object);
  479. if (!jso)
  480. return NULL;
  481. jso->c_object =
  482. lh_kchar_table_new(JSON_OBJECT_DEF_HASH_ENTRIES, &json_object_lh_entry_free);
  483. if (!jso->c_object)
  484. {
  485. json_object_generic_delete(&jso->base);
  486. errno = ENOMEM;
  487. return NULL;
  488. }
  489. return &jso->base;
  490. }
  491. struct lh_table *json_object_get_object(const struct json_object *jso)
  492. {
  493. if (!jso)
  494. return NULL;
  495. switch (jso->o_type)
  496. {
  497. case json_type_object: return JC_OBJECT_C(jso)->c_object;
  498. default: return NULL;
  499. }
  500. }
  501. int json_object_object_add_ex(struct json_object *jso, const char *const key,
  502. struct json_object *const val, const unsigned opts)
  503. {
  504. return json_object_object_add_ex_len(jso, key, strlen(key), val, opts);
  505. }
  506. int json_object_object_add_ex_len(struct json_object *jso, const char *const key, const int len,
  507. struct json_object *const val, const unsigned opts)
  508. {
  509. struct json_object *existing_value;
  510. struct lh_entry *existing_entry;
  511. unsigned long hash;
  512. /** Required due to the `lh_get_hash` function wanting a `const struct lh_string *` */
  513. const struct lh_string hashable = {.length = len, .str = {.pdata = key}};
  514. assert(json_object_get_type(jso) == json_type_object);
  515. // The caller must avoid creating loops in the object tree, but do a
  516. // quick check anyway to make sure we're not creating a trivial loop.
  517. if (jso == val)
  518. {
  519. return -1;
  520. }
  521. // We lookup the entry and replace the value, rather than just deleting
  522. // and re-adding it, so the existing key remains valid.
  523. hash = lh_get_hash(JC_OBJECT(jso)->c_object, (const void *)&hashable);
  524. existing_entry =
  525. (opts & JSON_C_OBJECT_ADD_KEY_IS_NEW)
  526. ? NULL
  527. : lh_table_lookup_entry_w_hash(JC_OBJECT(jso)->c_object, (const void *)key, hash);
  528. if (existing_entry == NULL)
  529. {
  530. const struct lh_string *k = (opts & JSON_C_OBJECT_KEY_IS_CONSTANT)
  531. ? lh_string_new_ptr(len, key)
  532. : lh_string_new_imm(len, key);
  533. if (k == NULL)
  534. {
  535. return -1;
  536. }
  537. return lh_table_insert_w_hash(JC_OBJECT(jso)->c_object, k, val, hash,
  538. opts & ~JSON_C_OBJECT_KEY_IS_CONSTANT);
  539. // `struct lh_string` always needs to be freed,
  540. // so JSON_C_OBJECT_KEY_IS_CONSTANT cannot be set
  541. }
  542. else
  543. {
  544. existing_value = (json_object *)lh_entry_v(existing_entry);
  545. if (existing_value)
  546. {
  547. json_object_put(existing_value);
  548. }
  549. existing_entry->v = val;
  550. return 0;
  551. }
  552. }
  553. int json_object_object_add(struct json_object *jso, const char *key, struct json_object *val)
  554. {
  555. return json_object_object_add_ex_len(jso, key, strlen(key), val, 0);
  556. }
  557. int json_object_object_add_len(struct json_object *jso, const char *key, const int len,
  558. struct json_object *val)
  559. {
  560. return json_object_object_add_ex_len(jso, key, len, val, 0);
  561. }
  562. int json_object_object_length(const struct json_object *jso)
  563. {
  564. assert(json_object_get_type(jso) == json_type_object);
  565. return lh_table_length(JC_OBJECT_C(jso)->c_object);
  566. }
  567. size_t json_c_object_sizeof(void)
  568. {
  569. return sizeof(struct json_object);
  570. }
  571. struct json_object *json_object_object_get(const struct json_object *jso, const char *key)
  572. {
  573. struct json_object *result = NULL;
  574. json_object_object_get_ex_len(jso, key, strlen(key), &result);
  575. return result;
  576. }
  577. struct json_object *json_object_object_get_len(const struct json_object *jso, const char *key,
  578. const int len)
  579. {
  580. struct json_object *result = NULL;
  581. json_object_object_get_ex_len(jso, key, len, &result);
  582. return result;
  583. }
  584. json_bool json_object_object_get_ex(const struct json_object *jso, const char *key,
  585. struct json_object **value)
  586. {
  587. return json_object_object_get_ex_len(jso, key, strlen(key), value);
  588. }
  589. json_bool json_object_object_get_ex_len(const struct json_object *jso, const char *key,
  590. const int len, struct json_object **value)
  591. {
  592. if (value != NULL)
  593. *value = NULL;
  594. if (NULL == jso)
  595. return 0;
  596. switch (jso->o_type)
  597. {
  598. case json_type_object:
  599. return lh_table_lookup_ex(JC_OBJECT_C(jso)->c_object, (const void *)key,
  600. (void **)value);
  601. default:
  602. if (value != NULL)
  603. *value = NULL;
  604. return 0;
  605. }
  606. }
  607. void json_object_object_del(struct json_object *jso, const char *key)
  608. {
  609. assert(json_object_get_type(jso) == json_type_object);
  610. lh_table_delete(JC_OBJECT(jso)->c_object, key);
  611. }
  612. /* json_object_boolean */
  613. static int json_object_boolean_to_json_string(struct json_object *jso, struct printbuf *pb,
  614. int level, int flags)
  615. {
  616. if (JC_BOOL(jso)->c_boolean)
  617. return printbuf_strappend(pb, "true");
  618. return printbuf_strappend(pb, "false");
  619. }
  620. struct json_object *json_object_new_boolean(json_bool b)
  621. {
  622. struct json_object_boolean *jso = JSON_OBJECT_NEW(boolean);
  623. if (!jso)
  624. return NULL;
  625. jso->c_boolean = b;
  626. return &jso->base;
  627. }
  628. json_bool json_object_get_boolean(const struct json_object *jso)
  629. {
  630. if (!jso)
  631. return 0;
  632. switch (jso->o_type)
  633. {
  634. case json_type_boolean: return JC_BOOL_C(jso)->c_boolean;
  635. case json_type_int:
  636. switch (JC_INT_C(jso)->cint_type)
  637. {
  638. case json_object_int_type_int64: return (JC_INT_C(jso)->cint.c_int64 != 0);
  639. case json_object_int_type_uint64: return (JC_INT_C(jso)->cint.c_uint64 != 0);
  640. default: json_abort("invalid cint_type");
  641. }
  642. case json_type_double: return (JC_DOUBLE_C(jso)->c_double != 0);
  643. case json_type_string: return (JC_STRING_C(jso)->len != 0);
  644. default: return 0;
  645. }
  646. }
  647. int json_object_set_boolean(struct json_object *jso, json_bool new_value)
  648. {
  649. if (!jso || jso->o_type != json_type_boolean)
  650. return 0;
  651. JC_BOOL(jso)->c_boolean = new_value;
  652. return 1;
  653. }
  654. /* json_object_int */
  655. static int json_object_int_to_json_string(struct json_object *jso, struct printbuf *pb, int level,
  656. int flags)
  657. {
  658. /* room for 19 digits, the sign char, and a null term */
  659. char sbuf[21];
  660. if (JC_INT(jso)->cint_type == json_object_int_type_int64)
  661. snprintf(sbuf, sizeof(sbuf), "%" PRId64, JC_INT(jso)->cint.c_int64);
  662. else
  663. snprintf(sbuf, sizeof(sbuf), "%" PRIu64, JC_INT(jso)->cint.c_uint64);
  664. return printbuf_memappend(pb, sbuf, strlen(sbuf));
  665. }
  666. struct json_object *json_object_new_int(int32_t i)
  667. {
  668. return json_object_new_int64(i);
  669. }
  670. int32_t json_object_get_int(const struct json_object *jso)
  671. {
  672. int64_t cint64 = 0;
  673. double cdouble;
  674. enum json_type o_type;
  675. if (!jso)
  676. return 0;
  677. o_type = jso->o_type;
  678. if (o_type == json_type_int)
  679. {
  680. const struct json_object_int *jsoint = JC_INT_C(jso);
  681. if (jsoint->cint_type == json_object_int_type_int64)
  682. {
  683. cint64 = jsoint->cint.c_int64;
  684. }
  685. else
  686. {
  687. if (jsoint->cint.c_uint64 >= INT64_MAX)
  688. cint64 = INT64_MAX;
  689. else
  690. cint64 = (int64_t)jsoint->cint.c_uint64;
  691. }
  692. }
  693. else if (o_type == json_type_string)
  694. {
  695. /*
  696. * Parse strings into 64-bit numbers, then use the
  697. * 64-to-32-bit number handling below.
  698. */
  699. if (json_parse_int64(get_string_component(jso), &cint64) != 0)
  700. return 0; /* whoops, it didn't work. */
  701. o_type = json_type_int;
  702. }
  703. switch (o_type)
  704. {
  705. case json_type_int:
  706. /* Make sure we return the correct values for out of range numbers. */
  707. if (cint64 <= INT32_MIN)
  708. return INT32_MIN;
  709. if (cint64 >= INT32_MAX)
  710. return INT32_MAX;
  711. return (int32_t)cint64;
  712. case json_type_double:
  713. cdouble = JC_DOUBLE_C(jso)->c_double;
  714. if (cdouble <= INT32_MIN)
  715. return INT32_MIN;
  716. if (cdouble >= INT32_MAX)
  717. return INT32_MAX;
  718. return (int32_t)cdouble;
  719. case json_type_boolean: return JC_BOOL_C(jso)->c_boolean;
  720. default: return 0;
  721. }
  722. }
  723. int json_object_set_int(struct json_object *jso, int new_value)
  724. {
  725. return json_object_set_int64(jso, (int64_t)new_value);
  726. }
  727. struct json_object *json_object_new_int64(int64_t i)
  728. {
  729. struct json_object_int *jso = JSON_OBJECT_NEW(int);
  730. if (!jso)
  731. return NULL;
  732. jso->cint.c_int64 = i;
  733. jso->cint_type = json_object_int_type_int64;
  734. return &jso->base;
  735. }
  736. struct json_object *json_object_new_uint64(uint64_t i)
  737. {
  738. struct json_object_int *jso = JSON_OBJECT_NEW(int);
  739. if (!jso)
  740. return NULL;
  741. jso->cint.c_uint64 = i;
  742. jso->cint_type = json_object_int_type_uint64;
  743. return &jso->base;
  744. }
  745. int64_t json_object_get_int64(const struct json_object *jso)
  746. {
  747. int64_t cint;
  748. if (!jso)
  749. return 0;
  750. switch (jso->o_type)
  751. {
  752. case json_type_int:
  753. {
  754. const struct json_object_int *jsoint = JC_INT_C(jso);
  755. switch (jsoint->cint_type)
  756. {
  757. case json_object_int_type_int64: return jsoint->cint.c_int64;
  758. case json_object_int_type_uint64:
  759. if (jsoint->cint.c_uint64 >= INT64_MAX)
  760. return INT64_MAX;
  761. return (int64_t)jsoint->cint.c_uint64;
  762. default: json_abort("invalid cint_type");
  763. }
  764. }
  765. case json_type_double:
  766. // INT64_MAX can't be exactly represented as a double
  767. // so cast to tell the compiler it's ok to round up.
  768. if (JC_DOUBLE_C(jso)->c_double >= (double)INT64_MAX)
  769. return INT64_MAX;
  770. if (JC_DOUBLE_C(jso)->c_double <= INT64_MIN)
  771. return INT64_MIN;
  772. return (int64_t)JC_DOUBLE_C(jso)->c_double;
  773. case json_type_boolean: return JC_BOOL_C(jso)->c_boolean;
  774. case json_type_string:
  775. if (json_parse_int64(get_string_component(jso), &cint) == 0)
  776. return cint;
  777. /* FALLTHRU */
  778. default: return 0;
  779. }
  780. }
  781. uint64_t json_object_get_uint64(const struct json_object *jso)
  782. {
  783. uint64_t cuint;
  784. if (!jso)
  785. return 0;
  786. switch (jso->o_type)
  787. {
  788. case json_type_int:
  789. {
  790. const struct json_object_int *jsoint = JC_INT_C(jso);
  791. switch (jsoint->cint_type)
  792. {
  793. case json_object_int_type_int64:
  794. if (jsoint->cint.c_int64 < 0)
  795. return 0;
  796. return (uint64_t)jsoint->cint.c_int64;
  797. case json_object_int_type_uint64: return jsoint->cint.c_uint64;
  798. default: json_abort("invalid cint_type");
  799. }
  800. }
  801. case json_type_double:
  802. // UINT64_MAX can't be exactly represented as a double
  803. // so cast to tell the compiler it's ok to round up.
  804. if (JC_DOUBLE_C(jso)->c_double >= (double)UINT64_MAX)
  805. return UINT64_MAX;
  806. if (JC_DOUBLE_C(jso)->c_double < 0)
  807. return 0;
  808. return (uint64_t)JC_DOUBLE_C(jso)->c_double;
  809. case json_type_boolean: return JC_BOOL_C(jso)->c_boolean;
  810. case json_type_string:
  811. if (json_parse_uint64(get_string_component(jso), &cuint) == 0)
  812. return cuint;
  813. /* FALLTHRU */
  814. default: return 0;
  815. }
  816. }
  817. int json_object_set_int64(struct json_object *jso, int64_t new_value)
  818. {
  819. if (!jso || jso->o_type != json_type_int)
  820. return 0;
  821. JC_INT(jso)->cint.c_int64 = new_value;
  822. JC_INT(jso)->cint_type = json_object_int_type_int64;
  823. return 1;
  824. }
  825. int json_object_set_uint64(struct json_object *jso, uint64_t new_value)
  826. {
  827. if (!jso || jso->o_type != json_type_int)
  828. return 0;
  829. JC_INT(jso)->cint.c_uint64 = new_value;
  830. JC_INT(jso)->cint_type = json_object_int_type_uint64;
  831. return 1;
  832. }
  833. int json_object_int_inc(struct json_object *jso, int64_t val)
  834. {
  835. struct json_object_int *jsoint;
  836. if (!jso || jso->o_type != json_type_int)
  837. return 0;
  838. jsoint = JC_INT(jso);
  839. switch (jsoint->cint_type)
  840. {
  841. case json_object_int_type_int64:
  842. if (val > 0 && jsoint->cint.c_int64 > INT64_MAX - val)
  843. {
  844. jsoint->cint.c_uint64 = (uint64_t)jsoint->cint.c_int64 + (uint64_t)val;
  845. jsoint->cint_type = json_object_int_type_uint64;
  846. }
  847. else if (val < 0 && jsoint->cint.c_int64 < INT64_MIN - val)
  848. {
  849. jsoint->cint.c_int64 = INT64_MIN;
  850. }
  851. else
  852. {
  853. jsoint->cint.c_int64 += val;
  854. }
  855. return 1;
  856. case json_object_int_type_uint64:
  857. if (val > 0 && jsoint->cint.c_uint64 > UINT64_MAX - (uint64_t)val)
  858. {
  859. jsoint->cint.c_uint64 = UINT64_MAX;
  860. }
  861. else if (val < 0 && jsoint->cint.c_uint64 < (uint64_t)(-val))
  862. {
  863. jsoint->cint.c_int64 = (int64_t)jsoint->cint.c_uint64 + val;
  864. jsoint->cint_type = json_object_int_type_int64;
  865. }
  866. else if (val < 0 && jsoint->cint.c_uint64 >= (uint64_t)(-val))
  867. {
  868. jsoint->cint.c_uint64 -= (uint64_t)(-val);
  869. }
  870. else
  871. {
  872. jsoint->cint.c_uint64 += val;
  873. }
  874. return 1;
  875. default: json_abort("invalid cint_type");
  876. }
  877. }
  878. /* json_object_double */
  879. #if defined(HAVE___THREAD)
  880. // i.e. __thread or __declspec(thread)
  881. static SPEC___THREAD char *tls_serialization_float_format = NULL;
  882. #endif
  883. static char *global_serialization_float_format = NULL;
  884. int json_c_set_serialization_double_format(const char *double_format, int global_or_thread)
  885. {
  886. if (global_or_thread == JSON_C_OPTION_GLOBAL)
  887. {
  888. #if defined(HAVE___THREAD)
  889. if (tls_serialization_float_format)
  890. {
  891. free(tls_serialization_float_format);
  892. tls_serialization_float_format = NULL;
  893. }
  894. #endif
  895. if (global_serialization_float_format)
  896. free(global_serialization_float_format);
  897. global_serialization_float_format = double_format ? strdup(double_format) : NULL;
  898. }
  899. else if (global_or_thread == JSON_C_OPTION_THREAD)
  900. {
  901. #if defined(HAVE___THREAD)
  902. if (tls_serialization_float_format)
  903. {
  904. free(tls_serialization_float_format);
  905. tls_serialization_float_format = NULL;
  906. }
  907. tls_serialization_float_format = double_format ? strdup(double_format) : NULL;
  908. #else
  909. _json_c_set_last_err("json_c_set_option: not compiled with __thread support\n");
  910. return -1;
  911. #endif
  912. }
  913. else
  914. {
  915. _json_c_set_last_err("json_c_set_option: invalid global_or_thread value: %d\n",
  916. global_or_thread);
  917. return -1;
  918. }
  919. return 0;
  920. }
  921. static int json_object_double_to_json_string_format(struct json_object *jso, struct printbuf *pb,
  922. int level, int flags, const char *format)
  923. {
  924. struct json_object_double *jsodbl = JC_DOUBLE(jso);
  925. char buf[128], *p, *q;
  926. int size;
  927. /* Although JSON RFC does not support
  928. * NaN or Infinity as numeric values
  929. * ECMA 262 section 9.8.1 defines
  930. * how to handle these cases as strings
  931. */
  932. if (isnan(jsodbl->c_double))
  933. {
  934. size = snprintf(buf, sizeof(buf), "NaN");
  935. }
  936. else if (isinf(jsodbl->c_double))
  937. {
  938. if (jsodbl->c_double > 0)
  939. size = snprintf(buf, sizeof(buf), "Infinity");
  940. else
  941. size = snprintf(buf, sizeof(buf), "-Infinity");
  942. }
  943. else
  944. {
  945. const char *std_format = "%.17g";
  946. int format_drops_decimals = 0;
  947. int looks_numeric = 0;
  948. if (!format)
  949. {
  950. #if defined(HAVE___THREAD)
  951. if (tls_serialization_float_format)
  952. format = tls_serialization_float_format;
  953. else
  954. #endif
  955. if (global_serialization_float_format)
  956. format = global_serialization_float_format;
  957. else
  958. format = std_format;
  959. }
  960. size = snprintf(buf, sizeof(buf), format, jsodbl->c_double);
  961. if (size < 0)
  962. return -1;
  963. p = strchr(buf, ',');
  964. if (p)
  965. *p = '.';
  966. else
  967. p = strchr(buf, '.');
  968. if (format == std_format || strstr(format, ".0f") == NULL)
  969. format_drops_decimals = 1;
  970. looks_numeric = /* Looks like *some* kind of number */
  971. isdigit((unsigned char)buf[0]) ||
  972. (size > 1 && buf[0] == '-' && isdigit((unsigned char)buf[1]));
  973. if (size < (int)sizeof(buf) - 2 && looks_numeric && !p && /* Has no decimal point */
  974. strchr(buf, 'e') == NULL && /* Not scientific notation */
  975. format_drops_decimals)
  976. {
  977. // Ensure it looks like a float, even if snprintf didn't,
  978. // unless a custom format is set to omit the decimal.
  979. strcat(buf, ".0");
  980. size += 2;
  981. }
  982. if (p && (flags & JSON_C_TO_STRING_NOZERO))
  983. {
  984. /* last useful digit, always keep 1 zero */
  985. p++;
  986. for (q = p; *q; q++)
  987. {
  988. if (*q != '0')
  989. p = q;
  990. }
  991. /* drop trailing zeroes */
  992. if (*p != 0)
  993. *(++p) = 0;
  994. size = p - buf;
  995. }
  996. }
  997. // although unlikely, snprintf can fail
  998. if (size < 0)
  999. return -1;
  1000. if (size >= (int)sizeof(buf))
  1001. // The standard formats are guaranteed not to overrun the buffer,
  1002. // but if a custom one happens to do so, just silently truncate.
  1003. size = sizeof(buf) - 1;
  1004. printbuf_memappend(pb, buf, size);
  1005. return size;
  1006. }
  1007. static int json_object_double_to_json_string_default(struct json_object *jso, struct printbuf *pb,
  1008. int level, int flags)
  1009. {
  1010. return json_object_double_to_json_string_format(jso, pb, level, flags, NULL);
  1011. }
  1012. int json_object_double_to_json_string(struct json_object *jso, struct printbuf *pb, int level,
  1013. int flags)
  1014. {
  1015. return json_object_double_to_json_string_format(jso, pb, level, flags,
  1016. (const char *)jso->_userdata);
  1017. }
  1018. struct json_object *json_object_new_double(double d)
  1019. {
  1020. struct json_object_double *jso = JSON_OBJECT_NEW(double);
  1021. if (!jso)
  1022. return NULL;
  1023. jso->base._to_json_string = &json_object_double_to_json_string_default;
  1024. jso->c_double = d;
  1025. return &jso->base;
  1026. }
  1027. struct json_object *json_object_new_double_s(double d, const char *ds)
  1028. {
  1029. char *new_ds;
  1030. struct json_object *jso = json_object_new_double(d);
  1031. if (!jso)
  1032. return NULL;
  1033. new_ds = strdup(ds);
  1034. if (!new_ds)
  1035. {
  1036. json_object_generic_delete(jso);
  1037. errno = ENOMEM;
  1038. return NULL;
  1039. }
  1040. json_object_set_serializer(jso, _json_object_userdata_to_json_string, new_ds,
  1041. json_object_free_userdata);
  1042. return jso;
  1043. }
  1044. /*
  1045. * A wrapper around json_object_userdata_to_json_string() used only
  1046. * by json_object_new_double_s() just so json_object_set_double() can
  1047. * detect when it needs to reset the serializer to the default.
  1048. */
  1049. static int _json_object_userdata_to_json_string(struct json_object *jso, struct printbuf *pb,
  1050. int level, int flags)
  1051. {
  1052. return json_object_userdata_to_json_string(jso, pb, level, flags);
  1053. }
  1054. int json_object_userdata_to_json_string(struct json_object *jso, struct printbuf *pb, int level,
  1055. int flags)
  1056. {
  1057. int userdata_len = strlen((const char *)jso->_userdata);
  1058. printbuf_memappend(pb, (const char *)jso->_userdata, userdata_len);
  1059. return userdata_len;
  1060. }
  1061. void json_object_free_userdata(struct json_object *jso, void *userdata)
  1062. {
  1063. free(userdata);
  1064. }
  1065. double json_object_get_double(const struct json_object *jso)
  1066. {
  1067. double cdouble;
  1068. char *errPtr = NULL;
  1069. if (!jso)
  1070. return 0.0;
  1071. switch (jso->o_type)
  1072. {
  1073. case json_type_double: return JC_DOUBLE_C(jso)->c_double;
  1074. case json_type_int:
  1075. switch (JC_INT_C(jso)->cint_type)
  1076. {
  1077. case json_object_int_type_int64: return JC_INT_C(jso)->cint.c_int64;
  1078. case json_object_int_type_uint64: return JC_INT_C(jso)->cint.c_uint64;
  1079. default: json_abort("invalid cint_type");
  1080. }
  1081. case json_type_boolean: return JC_BOOL_C(jso)->c_boolean;
  1082. case json_type_string:
  1083. errno = 0;
  1084. cdouble = strtod(get_string_component(jso), &errPtr);
  1085. /* if conversion stopped at the first character, return 0.0 */
  1086. if (errPtr == get_string_component(jso))
  1087. {
  1088. errno = EINVAL;
  1089. return 0.0;
  1090. }
  1091. /*
  1092. * Check that the conversion terminated on something sensible
  1093. *
  1094. * For example, { "pay" : 123AB } would parse as 123.
  1095. */
  1096. if (*errPtr != '\0')
  1097. {
  1098. errno = EINVAL;
  1099. return 0.0;
  1100. }
  1101. /*
  1102. * If strtod encounters a string which would exceed the
  1103. * capacity of a double, it returns +/- HUGE_VAL and sets
  1104. * errno to ERANGE. But +/- HUGE_VAL is also a valid result
  1105. * from a conversion, so we need to check errno.
  1106. *
  1107. * Underflow also sets errno to ERANGE, but it returns 0 in
  1108. * that case, which is what we will return anyway.
  1109. *
  1110. * See CERT guideline ERR30-C
  1111. */
  1112. if ((HUGE_VAL == cdouble || -HUGE_VAL == cdouble) && (ERANGE == errno))
  1113. cdouble = 0.0;
  1114. return cdouble;
  1115. default: errno = EINVAL; return 0.0;
  1116. }
  1117. }
  1118. int json_object_set_double(struct json_object *jso, double new_value)
  1119. {
  1120. if (!jso || jso->o_type != json_type_double)
  1121. return 0;
  1122. JC_DOUBLE(jso)->c_double = new_value;
  1123. if (jso->_to_json_string == &_json_object_userdata_to_json_string)
  1124. json_object_set_serializer(jso, NULL, NULL, NULL);
  1125. return 1;
  1126. }
  1127. /* json_object_string */
  1128. static int json_object_string_to_json_string(struct json_object *jso, struct printbuf *pb,
  1129. int level, int flags)
  1130. {
  1131. ssize_t len = JC_STRING(jso)->len;
  1132. printbuf_strappend(pb, "\"");
  1133. json_escape_str(pb, get_string_component(jso), len < 0 ? -(ssize_t)len : len, flags);
  1134. printbuf_strappend(pb, "\"");
  1135. return 0;
  1136. }
  1137. static void json_object_string_delete(struct json_object *jso)
  1138. {
  1139. if (JC_STRING(jso)->len < 0)
  1140. free(JC_STRING(jso)->c_string.pdata);
  1141. json_object_generic_delete(jso);
  1142. }
  1143. static struct json_object *_json_object_new_string(const char *s, const size_t len)
  1144. {
  1145. size_t objsize;
  1146. struct json_object_string *jso;
  1147. /*
  1148. * Structures Actual memory layout
  1149. * ------------------- --------------------
  1150. * [json_object_string [json_object_string
  1151. * [json_object] [json_object]
  1152. * ...other fields... ...other fields...
  1153. * c_string] len
  1154. * bytes
  1155. * of
  1156. * string
  1157. * data
  1158. * \0]
  1159. */
  1160. if (len > (SSIZE_T_MAX - (sizeof(*jso) - sizeof(jso->c_string)) - 1))
  1161. return NULL;
  1162. objsize = (sizeof(*jso) - sizeof(jso->c_string)) + len + 1;
  1163. if (len < sizeof(void *))
  1164. // We need a minimum size to support json_object_set_string() mutability
  1165. // so we can stuff a pointer into pdata :(
  1166. objsize += sizeof(void *) - len;
  1167. jso = (struct json_object_string *)json_object_new(json_type_string, objsize,
  1168. &json_object_string_to_json_string);
  1169. if (!jso)
  1170. return NULL;
  1171. jso->len = len;
  1172. memcpy(jso->c_string.idata, s, len);
  1173. jso->c_string.idata[len] = '\0';
  1174. return &jso->base;
  1175. }
  1176. struct json_object *json_object_new_string(const char *s)
  1177. {
  1178. return _json_object_new_string(s, strlen(s));
  1179. }
  1180. struct json_object *json_object_new_string_len(const char *s, const int len)
  1181. {
  1182. return _json_object_new_string(s, len);
  1183. }
  1184. const char *json_object_get_string(struct json_object *jso)
  1185. {
  1186. if (!jso)
  1187. return NULL;
  1188. switch (jso->o_type)
  1189. {
  1190. case json_type_string: return get_string_component(jso);
  1191. default: return json_object_to_json_string(jso);
  1192. }
  1193. }
  1194. int json_object_get_string_len(const struct json_object *jso)
  1195. {
  1196. ssize_t len;
  1197. if (!jso)
  1198. return 0;
  1199. switch (jso->o_type)
  1200. {
  1201. case json_type_string:
  1202. {
  1203. len = JC_STRING_C(jso)->len;
  1204. return (len < 0) ? -(ssize_t)len : len;
  1205. }
  1206. default: return 0;
  1207. }
  1208. }
  1209. static int _json_object_set_string_len(json_object *jso, const char *s, size_t len)
  1210. {
  1211. char *dstbuf;
  1212. ssize_t curlen;
  1213. ssize_t newlen;
  1214. if (jso == NULL || jso->o_type != json_type_string)
  1215. return 0;
  1216. if (len >= INT_MAX - 1)
  1217. // jso->len is a signed ssize_t, so it can't hold the
  1218. // full size_t range. json_object_get_string_len returns
  1219. // length as int, cap length at INT_MAX.
  1220. return 0;
  1221. dstbuf = get_string_component_mutable(jso);
  1222. curlen = JC_STRING(jso)->len;
  1223. if (curlen < 0)
  1224. curlen = -curlen;
  1225. newlen = len;
  1226. if ((ssize_t)len > curlen)
  1227. {
  1228. // We have no way to return the new ptr from realloc(jso, newlen)
  1229. // and we have no way of knowing whether there's extra room available
  1230. // so we need to stuff a pointer in to pdata :(
  1231. dstbuf = (char *)malloc(len + 1);
  1232. if (dstbuf == NULL)
  1233. return 0;
  1234. if (JC_STRING(jso)->len < 0)
  1235. free(JC_STRING(jso)->c_string.pdata);
  1236. JC_STRING(jso)->c_string.pdata = dstbuf;
  1237. newlen = -(ssize_t)len;
  1238. }
  1239. else if (JC_STRING(jso)->len < 0)
  1240. {
  1241. // We've got enough room in the separate allocated buffer,
  1242. // so use it as-is and continue to indicate that pdata is used.
  1243. newlen = -(ssize_t)len;
  1244. }
  1245. memcpy(dstbuf, (const void *)s, len);
  1246. dstbuf[len] = '\0';
  1247. JC_STRING(jso)->len = newlen;
  1248. return 1;
  1249. }
  1250. int json_object_set_string(json_object *jso, const char *s)
  1251. {
  1252. return _json_object_set_string_len(jso, s, strlen(s));
  1253. }
  1254. int json_object_set_string_len(json_object *jso, const char *s, int len)
  1255. {
  1256. return _json_object_set_string_len(jso, s, len);
  1257. }
  1258. /* json_object_array */
  1259. static int json_object_array_to_json_string(struct json_object *jso, struct printbuf *pb, int level,
  1260. int flags)
  1261. {
  1262. int had_children = 0;
  1263. size_t ii;
  1264. printbuf_strappend(pb, "[");
  1265. if (flags & JSON_C_TO_STRING_PRETTY)
  1266. printbuf_strappend(pb, "\n");
  1267. for (ii = 0; ii < json_object_array_length(jso); ii++)
  1268. {
  1269. struct json_object *val;
  1270. if (had_children)
  1271. {
  1272. printbuf_strappend(pb, ",");
  1273. if (flags & JSON_C_TO_STRING_PRETTY)
  1274. printbuf_strappend(pb, "\n");
  1275. }
  1276. had_children = 1;
  1277. if (flags & JSON_C_TO_STRING_SPACED && !(flags & JSON_C_TO_STRING_PRETTY))
  1278. printbuf_strappend(pb, " ");
  1279. indent(pb, level + 1, flags);
  1280. val = json_object_array_get_idx(jso, ii);
  1281. if (val == NULL)
  1282. printbuf_strappend(pb, "null");
  1283. else if (val->_to_json_string(val, pb, level + 1, flags) < 0)
  1284. return -1;
  1285. }
  1286. if (flags & JSON_C_TO_STRING_PRETTY)
  1287. {
  1288. if (had_children)
  1289. printbuf_strappend(pb, "\n");
  1290. indent(pb, level, flags);
  1291. }
  1292. if (flags & JSON_C_TO_STRING_SPACED && !(flags & JSON_C_TO_STRING_PRETTY))
  1293. return printbuf_strappend(pb, " ]");
  1294. return printbuf_strappend(pb, "]");
  1295. }
  1296. static void json_object_array_entry_free(void *data)
  1297. {
  1298. json_object_put((struct json_object *)data);
  1299. }
  1300. static void json_object_array_delete(struct json_object *jso)
  1301. {
  1302. array_list_free(JC_ARRAY(jso)->c_array);
  1303. json_object_generic_delete(jso);
  1304. }
  1305. struct json_object *json_object_new_array(void)
  1306. {
  1307. return json_object_new_array_ext(ARRAY_LIST_DEFAULT_SIZE);
  1308. }
  1309. struct json_object *json_object_new_array_ext(int initial_size)
  1310. {
  1311. struct json_object_array *jso = JSON_OBJECT_NEW(array);
  1312. if (!jso)
  1313. return NULL;
  1314. jso->c_array = array_list_new2(&json_object_array_entry_free, initial_size);
  1315. if (jso->c_array == NULL)
  1316. {
  1317. free(jso);
  1318. return NULL;
  1319. }
  1320. return &jso->base;
  1321. }
  1322. struct array_list *json_object_get_array(const struct json_object *jso)
  1323. {
  1324. if (!jso)
  1325. return NULL;
  1326. switch (jso->o_type)
  1327. {
  1328. case json_type_array: return JC_ARRAY_C(jso)->c_array;
  1329. default: return NULL;
  1330. }
  1331. }
  1332. void json_object_array_sort(struct json_object *jso, int (*sort_fn)(const void *, const void *))
  1333. {
  1334. assert(json_object_get_type(jso) == json_type_array);
  1335. array_list_sort(JC_ARRAY(jso)->c_array, sort_fn);
  1336. }
  1337. struct json_object *json_object_array_bsearch(const struct json_object *key,
  1338. const struct json_object *jso,
  1339. int (*sort_fn)(const void *, const void *))
  1340. {
  1341. struct json_object **result;
  1342. assert(json_object_get_type(jso) == json_type_array);
  1343. result = (struct json_object **)array_list_bsearch((const void **)(void *)&key,
  1344. JC_ARRAY_C(jso)->c_array, sort_fn);
  1345. if (!result)
  1346. return NULL;
  1347. return *result;
  1348. }
  1349. size_t json_object_array_length(const struct json_object *jso)
  1350. {
  1351. assert(json_object_get_type(jso) == json_type_array);
  1352. return array_list_length(JC_ARRAY_C(jso)->c_array);
  1353. }
  1354. int json_object_array_add(struct json_object *jso, struct json_object *val)
  1355. {
  1356. assert(json_object_get_type(jso) == json_type_array);
  1357. return array_list_add(JC_ARRAY(jso)->c_array, val);
  1358. }
  1359. int json_object_array_put_idx(struct json_object *jso, size_t idx, struct json_object *val)
  1360. {
  1361. assert(json_object_get_type(jso) == json_type_array);
  1362. return array_list_put_idx(JC_ARRAY(jso)->c_array, idx, val);
  1363. }
  1364. int json_object_array_del_idx(struct json_object *jso, size_t idx, size_t count)
  1365. {
  1366. assert(json_object_get_type(jso) == json_type_array);
  1367. return array_list_del_idx(JC_ARRAY(jso)->c_array, idx, count);
  1368. }
  1369. struct json_object *json_object_array_get_idx(const struct json_object *jso, size_t idx)
  1370. {
  1371. assert(json_object_get_type(jso) == json_type_array);
  1372. return (struct json_object *)array_list_get_idx(JC_ARRAY_C(jso)->c_array, idx);
  1373. }
  1374. static int json_array_equal(struct json_object *jso1, struct json_object *jso2)
  1375. {
  1376. size_t len, i;
  1377. len = json_object_array_length(jso1);
  1378. if (len != json_object_array_length(jso2))
  1379. return 0;
  1380. for (i = 0; i < len; i++)
  1381. {
  1382. if (!json_object_equal(json_object_array_get_idx(jso1, i),
  1383. json_object_array_get_idx(jso2, i)))
  1384. return 0;
  1385. }
  1386. return 1;
  1387. }
  1388. int json_object_array_shrink(struct json_object *jso, int empty_slots)
  1389. {
  1390. if (empty_slots < 0)
  1391. json_abort("json_object_array_shrink called with negative empty_slots");
  1392. return array_list_shrink(JC_ARRAY(jso)->c_array, empty_slots);
  1393. }
  1394. struct json_object *json_object_new_null(void)
  1395. {
  1396. return NULL;
  1397. }
  1398. static int json_object_all_values_equal(struct json_object *jso1, struct json_object *jso2)
  1399. {
  1400. struct json_object_iter iter;
  1401. struct json_object *sub;
  1402. assert(json_object_get_type(jso1) == json_type_object);
  1403. assert(json_object_get_type(jso2) == json_type_object);
  1404. /* Iterate over jso1 keys and see if they exist and are equal in jso2 */
  1405. json_object_object_foreachC(jso1, iter)
  1406. {
  1407. if (!lh_table_lookup_ex(JC_OBJECT(jso2)->c_object, (void *)iter.key,
  1408. (void **)(void *)&sub))
  1409. return 0;
  1410. if (!json_object_equal(iter.val, sub))
  1411. return 0;
  1412. }
  1413. /* Iterate over jso2 keys to see if any exist that are not in jso1 */
  1414. json_object_object_foreachC(jso2, iter)
  1415. {
  1416. if (!lh_table_lookup_ex(JC_OBJECT(jso1)->c_object, (void *)iter.key,
  1417. (void **)(void *)&sub))
  1418. return 0;
  1419. }
  1420. return 1;
  1421. }
  1422. int json_object_equal(struct json_object *jso1, struct json_object *jso2)
  1423. {
  1424. if (jso1 == jso2)
  1425. return 1;
  1426. if (!jso1 || !jso2)
  1427. return 0;
  1428. if (jso1->o_type != jso2->o_type)
  1429. return 0;
  1430. switch (jso1->o_type)
  1431. {
  1432. case json_type_boolean: return (JC_BOOL(jso1)->c_boolean == JC_BOOL(jso2)->c_boolean);
  1433. case json_type_double: return (JC_DOUBLE(jso1)->c_double == JC_DOUBLE(jso2)->c_double);
  1434. case json_type_int:
  1435. {
  1436. struct json_object_int *int1 = JC_INT(jso1);
  1437. struct json_object_int *int2 = JC_INT(jso2);
  1438. if (int1->cint_type == json_object_int_type_int64)
  1439. {
  1440. if (int2->cint_type == json_object_int_type_int64)
  1441. return (int1->cint.c_int64 == int2->cint.c_int64);
  1442. if (int1->cint.c_int64 < 0)
  1443. return 0;
  1444. return ((uint64_t)int1->cint.c_int64 == int2->cint.c_uint64);
  1445. }
  1446. // else jso1 is a uint64
  1447. if (int2->cint_type == json_object_int_type_uint64)
  1448. return (int1->cint.c_uint64 == int2->cint.c_uint64);
  1449. if (int2->cint.c_int64 < 0)
  1450. return 0;
  1451. return (int1->cint.c_uint64 == (uint64_t)int2->cint.c_int64);
  1452. }
  1453. case json_type_string:
  1454. {
  1455. return (json_object_get_string_len(jso1) == json_object_get_string_len(jso2) &&
  1456. memcmp(get_string_component(jso1), get_string_component(jso2),
  1457. json_object_get_string_len(jso1)) == 0);
  1458. }
  1459. case json_type_object: return json_object_all_values_equal(jso1, jso2);
  1460. case json_type_array: return json_array_equal(jso1, jso2);
  1461. case json_type_null: return 1;
  1462. };
  1463. return 0;
  1464. }
  1465. static int json_object_copy_serializer_data(struct json_object *src, struct json_object *dst)
  1466. {
  1467. if (!src->_userdata && !src->_user_delete)
  1468. return 0;
  1469. if (dst->_to_json_string == json_object_userdata_to_json_string ||
  1470. dst->_to_json_string == _json_object_userdata_to_json_string)
  1471. {
  1472. dst->_userdata = strdup(src->_userdata);
  1473. }
  1474. // else if ... other supported serializers ...
  1475. else
  1476. {
  1477. _json_c_set_last_err(
  1478. "json_object_deep_copy: unable to copy unknown serializer data: %p\n",
  1479. (void *)dst->_to_json_string);
  1480. return -1;
  1481. }
  1482. dst->_user_delete = src->_user_delete;
  1483. return 0;
  1484. }
  1485. /**
  1486. * The default shallow copy implementation. Simply creates a new object of the same
  1487. * type but does *not* copy over _userdata nor retain any custom serializer.
  1488. * If custom serializers are in use, json_object_deep_copy() must be passed a shallow copy
  1489. * implementation that is aware of how to copy them.
  1490. *
  1491. * This always returns -1 or 1. It will never return 2 since it does not copy the serializer.
  1492. */
  1493. int json_c_shallow_copy_default(json_object *src, json_object *parent, const char *key,
  1494. size_t index, json_object **dst)
  1495. {
  1496. switch (src->o_type)
  1497. {
  1498. case json_type_boolean: *dst = json_object_new_boolean(JC_BOOL(src)->c_boolean); break;
  1499. case json_type_double: *dst = json_object_new_double(JC_DOUBLE(src)->c_double); break;
  1500. case json_type_int:
  1501. switch (JC_INT(src)->cint_type)
  1502. {
  1503. case json_object_int_type_int64:
  1504. *dst = json_object_new_int64(JC_INT(src)->cint.c_int64);
  1505. break;
  1506. case json_object_int_type_uint64:
  1507. *dst = json_object_new_uint64(JC_INT(src)->cint.c_uint64);
  1508. break;
  1509. default: json_abort("invalid cint_type");
  1510. }
  1511. break;
  1512. case json_type_string: *dst = json_object_new_string(get_string_component(src)); break;
  1513. case json_type_object: *dst = json_object_new_object(); break;
  1514. case json_type_array: *dst = json_object_new_array(); break;
  1515. default: errno = EINVAL; return -1;
  1516. }
  1517. if (!*dst)
  1518. {
  1519. errno = ENOMEM;
  1520. return -1;
  1521. }
  1522. (*dst)->_to_json_string = src->_to_json_string;
  1523. // _userdata and _user_delete are copied later
  1524. return 1;
  1525. }
  1526. /*
  1527. * The actual guts of json_object_deep_copy(), with a few additional args
  1528. * needed so we can keep track of where we are within the object tree.
  1529. *
  1530. * Note: caller is responsible for freeing *dst if this fails and returns -1.
  1531. */
  1532. static int json_object_deep_copy_recursive(struct json_object *src, struct json_object *parent,
  1533. const char *key_in_parent, size_t index_in_parent,
  1534. struct json_object **dst,
  1535. json_c_shallow_copy_fn *shallow_copy)
  1536. {
  1537. struct json_object_iter iter;
  1538. size_t src_array_len, ii;
  1539. int shallow_copy_rc = 0;
  1540. shallow_copy_rc = shallow_copy(src, parent, key_in_parent, index_in_parent, dst);
  1541. /* -1=error, 1=object created ok, 2=userdata set */
  1542. if (shallow_copy_rc < 1)
  1543. {
  1544. errno = EINVAL;
  1545. return -1;
  1546. }
  1547. assert(*dst != NULL);
  1548. switch (src->o_type)
  1549. {
  1550. case json_type_object:
  1551. json_object_object_foreachC(src, iter)
  1552. {
  1553. struct json_object *jso = NULL;
  1554. /* This handles the `json_type_null` case */
  1555. if (!iter.val)
  1556. jso = NULL;
  1557. else if (json_object_deep_copy_recursive(iter.val, src, iter.key, UINT_MAX,
  1558. &jso, shallow_copy) < 0)
  1559. {
  1560. json_object_put(jso);
  1561. return -1;
  1562. }
  1563. if (json_object_object_add(*dst, iter.key, jso) < 0)
  1564. {
  1565. json_object_put(jso);
  1566. return -1;
  1567. }
  1568. }
  1569. break;
  1570. case json_type_array:
  1571. src_array_len = json_object_array_length(src);
  1572. for (ii = 0; ii < src_array_len; ii++)
  1573. {
  1574. struct json_object *jso = NULL;
  1575. struct json_object *jso1 = json_object_array_get_idx(src, ii);
  1576. /* This handles the `json_type_null` case */
  1577. if (!jso1)
  1578. jso = NULL;
  1579. else if (json_object_deep_copy_recursive(jso1, src, NULL, ii, &jso,
  1580. shallow_copy) < 0)
  1581. {
  1582. json_object_put(jso);
  1583. return -1;
  1584. }
  1585. if (json_object_array_add(*dst, jso) < 0)
  1586. {
  1587. json_object_put(jso);
  1588. return -1;
  1589. }
  1590. }
  1591. break;
  1592. default:
  1593. break;
  1594. /* else, nothing to do, shallow_copy already did. */
  1595. }
  1596. if (shallow_copy_rc != 2)
  1597. return json_object_copy_serializer_data(src, *dst);
  1598. return 0;
  1599. }
  1600. int json_object_deep_copy(struct json_object *src, struct json_object **dst,
  1601. json_c_shallow_copy_fn *shallow_copy)
  1602. {
  1603. int rc;
  1604. /* Check if arguments are sane ; *dst must not point to a non-NULL object */
  1605. if (!src || !dst || *dst)
  1606. {
  1607. errno = EINVAL;
  1608. return -1;
  1609. }
  1610. if (shallow_copy == NULL)
  1611. shallow_copy = json_c_shallow_copy_default;
  1612. rc = json_object_deep_copy_recursive(src, NULL, NULL, UINT_MAX, dst, shallow_copy);
  1613. if (rc < 0)
  1614. {
  1615. json_object_put(*dst);
  1616. *dst = NULL;
  1617. }
  1618. return rc;
  1619. }
  1620. static void json_abort(const char *message)
  1621. {
  1622. if (message != NULL)
  1623. fprintf(stderr, "json-c aborts with error: %s\n", message);
  1624. abort();
  1625. }