652 Commits

Author SHA1 Message Date
Eric Hawicz
6bfab90c87 Issue #867: disallow control characters in strict mode. 2024-09-15 10:37:45 -04:00
Eric Hawicz
ecb7a4c9a3 Merge pull request #864 from pavelzw/patch-1
Build pkg-config for msvc as well
2024-08-29 21:08:52 -04:00
Pavel Zwerschke
906d1581de Update CMakeLists.txt 2024-08-29 10:55:02 +02:00
Pavel Zwerschke
9b8d170d1f Build pkg-config for msvc as well 2024-06-18 00:11:13 +02:00
Eric Hawicz
6e481aa061 Merge pull request #861 from bhaible/handle-another-oom-condition
Handle yet another out-of-memory condition.
2024-05-05 09:49:26 -04:00
Eric Haszlakiewicz
781675758f Although CMAKE_C_COMPILER_FRONTEND_VARIANT is defined, it's not always set to some value. Fix builds for cases when it's blank. 2024-04-28 17:15:42 +00:00
Bruno Haible
833233faa8 Handle yet another out-of-memory condition.
duplocale() can return NULL, with errno set to ENOMEM.
In this case, bail out and set the current error code to
json_tokener_error_memory.
2024-04-22 01:54:10 +02:00
Eric Hawicz
31a22fb2da Issue #857: fix a few places where json_tokener should have been returning json_tokener_error_memory but wasn't. 2024-04-21 10:37:16 -04:00
Eric Hawicz
0051f2dbe0 Merge pull request #858 from alurm/master
json_tokener.h: json_tokener_parse_verbose: fix typo
2024-04-16 11:23:09 -04:00
Alan Urmancheev
0741ce3918 json_tokener.h: json_tokener_parse_verbose: fix typo 2024-04-16 14:56:00 +00:00
Eric Hawicz
e3464a2ab4 Issue #829: attempt to detect clang-cl.exe and pass MSVC-compatile command line arguments. 2024-03-29 22:40:45 -04:00
Eric Hawicz
61016412fb Issue #850: fill in & adjust the "@returns" docs for several functions. 2024-03-29 18:46:05 -04:00
Eric Hawicz
f2eac07129 doxygen can't handle html on heading, split that to separate lines
https://github.com/doxygen/doxygen/issues/10466
2024-03-29 18:45:22 -04:00
Eric Hawicz
e93ae70417 Fix issue #854: Set error=json_tokener_error_memory in json_tokener_parser_verbose() when allocating the tokener fails. 2024-03-29 18:09:12 -04:00
Eric Hawicz
0bc2dd5e60 Merge pull request #852 from fedefrancescon/docs/micro-typo-fix
docs: micro typo in json_object_put doc
2024-03-02 17:31:24 -05:00
Federico Francescon
9c44c7ed52 docs: micro typo in json_object_get doc 2024-03-02 22:41:10 +01:00
Eric Hawicz
401249cbdf Merge pull request #831 from neheb/1
rename WIN32 to _WIN32
2024-02-08 08:11:57 -05:00
Rosen Penev
66f7869219 rename WIN32 to _WIN32
The latter is the proper macro defined by Windows headers.

Fixes compilation under at least clang-cl which mandates function
declarations.

Signed-off-by: Rosen Penev <rosenp@gmail.com>
2024-02-07 18:06:55 -08:00
Eric Hawicz
dabed80523 Merge pull request #849 from rouault/random_seed_toctou
random_seed.c: add a Coverity Scan suppression
2024-01-08 12:45:39 -05:00
Even Rouault
f6c8eba84e random_seed.c: add a Coverity Scan suppression
Coverity Scan warns about the use of open() after stat() being a
potential TOCTOU (Time of check time of use) issue. But here there is no
such issue.
2024-01-07 20:55:38 +01:00
Eric Hawicz
76f819e51d Merge pull request #846 from evo-i/CMP0153
Use execute_process instead of exec_program
2023-12-17 07:23:07 -05:00
evo
eef983b1df Update CMakeLists.txt
Replace with `execute_process` available on v3.0+
2023-12-17 11:19:20 +03:00
evo
c0cf4bc23b Update CMakeLists.txt
Now saved to variable.
2023-12-17 00:32:21 +03:00
evo
e85c8ada54 Fix ECHO_OUTPUT_VARIABLE 2023-12-17 00:23:51 +03:00
evo
2c84476c77 [CMP0153](https://cmake.org/cmake/help/latest/policy/CMP0153.html) 2023-12-12 16:28:41 +03:00
Eric Haszlakiewicz
407ddb4350 Issue #842 - fix one particular sign conversion warning.
There are many others that show up if we were to add -Wsign-conversions,
but this is the only one using a literal constant.
2023-11-30 13:59:13 +00:00
Eric Hawicz
33337523f5 Merge pull request #839 from ffontaine/master
json_pointer.c: initialize idx
2023-11-08 18:11:13 -05:00
Fabrice Fontaine
7ff7eab603 json_pointer.c: initialize idx
Fix the following build failure with gcc 5:

/home/thomas/autobuild/instance-2/output-1/build/json-c-0.17/json_pointer.c: In function 'json_pointer_result_get_recursive':
/home/thomas/autobuild/instance-2/output-1/build/json-c-0.17/json_pointer.c:193:25: error: 'idx' may be used uninitialized in this function [-Werror=maybe-uninitialized]
    res->index_in_parent = idx;
                         ^

Fixes:
 - http://autobuild.buildroot.org/results/523b35a979d59121fe4e18c38171792b06233940/

Signed-off-by: Fabrice Fontaine <fontaine.fabrice@gmail.com>
2023-11-08 22:42:48 +01:00
Eric Hawicz
88bce2b38e Merge pull request #837 from HansolChoe/fix-tokener-parse-ex-fuzzer
Add type checking for parsed objects in tokener_parse_ex_fuzzer
2023-10-19 07:49:32 -04:00
HansolChoe
a907f7dd1b tokener_parse_ex_fuzzer: add type checking for parsed object 2023-10-19 16:55:15 +09:00
Eric Hawicz
ad8b8afa7d Take 2 fixing the placement of json_tokener_error_memory in the enum. (json_tokener_error_size is an actual error, *not* a measure of the size of the enum!) 2023-09-22 22:26:21 -04:00
Eric Hawicz
4186537557 Merge pull request #827 from robert-pang/master
Resolve build issue in tokener_parse_ex_fuzzer.c
2023-09-11 00:13:45 +02:00
Eric Hawicz
9ff6b68baf Merge pull request #826 from emlix/cmake-policies
CMake: remove needless policy setting
2023-09-11 00:10:55 +02:00
Robert Pang
1a7defaa69 Fix variable and API names in tokener_parse_ex_fuzzer.cc to resolve build issue. 2023-09-05 13:58:51 -07:00
Rolf Eike Beer
c4a615a052 CMake: request all policies up to CMake 3.12 being set to NEW 2023-09-05 14:31:24 +02:00
Rolf Eike Beer
159822dd8a CMake: request consistent minimum version 2023-09-05 14:31:14 +02:00
Rolf Eike Beer
990acb4e19 CMake: remove needless policy setting
These policies were all introduced before CMake 3.9, so they will automatically
be initialized to the new behavior when requesting a minimum version of 3.9.
2023-09-05 12:14:46 +02:00
Eric Haszlakiewicz
502522a93d Update the master branch to version 0.17.99 2023-08-12 19:08:59 +00:00
Eric Hawicz
12ea386989 Add an abi-check.sh script that shows how to run the abi-compliance-checker, update release creation steps slightly. 2023-08-12 14:56:51 -04:00
Eric Haszlakiewicz
6dd8618170 Also fix messages returned from json_tokener_error_desc() (broke due to the ordering change of enum json_tokener_error) 2023-08-12 18:52:32 +00:00
Eric Hawicz
3dad6941da Move the json_tokener_error_memory entry to the end of enum json_tokener_error to restore binary compatibility with 0.16 2023-08-12 13:54:50 -04:00
Eric Hawicz
f7e9d8e216 Update the AUTHORS file and add issues_closed_for_0.17.md for the upcoming 0.17 release 2023-08-12 13:53:27 -04:00
Eric Hawicz
85ed501a3d Update the ChangeLog for 0.17 based on notable commits since 0.16 2023-08-08 17:31:38 -04:00
Eric Hawicz
077661f3d1 Fix issue #823: add back json_number_chars, but only because it's part of the public API. 2023-08-06 15:36:19 -04:00
Eric Hawicz
87127d31c6 Merge pull request #679 from GitMensch/patch-1
Let json-c be used with obsolete compilers
2023-08-05 22:32:37 -04:00
Eric Hawicz
1ee12100b6 PR #679: add workaround for old compilers w/o stdint.h (i.e. VS2008 and earlier) 2023-08-05 22:11:30 -04:00
Eric Hawicz
0bcfb6bc84 Merge pull request #822 from SSharshunov/master
Added option to disable app build
2023-08-04 11:47:23 -04:00
Sergey Sharshunov
bef40a342e Added option to disable app build 2023-08-04 19:46:50 +05:00
Eric Hawicz
2316dbae85 Merge pull request #702 from commodo/json_patch
json_patch: add first implementation only with patch application
2023-07-31 22:19:30 -04:00
Eric Hawicz
612ba56f06 Don't export json_pointer_get_internal, move json_object_array_insert_idx and json_patch_apply to the JSONC_0.17 section in json-c.sym 2023-07-31 22:18:04 -04:00
Eric Hawicz
469bc0e4bb Work around a somewhat misleading warning about "a function declaration without a prototype is deprecated in all versions of C" in test1.c 2023-07-31 22:18:04 -04:00
Eric Hawicz
ce3184243a Fix json_patch_apply handling of removing the whole document (i.e. "path":"").
Enable all disabled tests, add a few more including some with null documents.
2023-07-31 22:18:04 -04:00
Eric Hawicz
9dbf2880cc Adjust the behavior of the args passed to json_patch_apply to make it easier to do in place modifications, and add a struct json_patch_error to report more details on failures. 2023-07-31 22:18:04 -04:00
Eric Hawicz
a14a3a680c Fix an uninitialized memory access in json_pointer.
Add comments describing when the fields of the internal struct json_pointer_get_result are valid.
2023-07-31 22:18:03 -04:00
Eric Hawicz
efc530594b Create a json_pointer_private.h and move a few things there, fix test warnings, note array_list_insert_idx is private. 2023-07-31 22:18:03 -04:00
Alexandru Ardelean
3b8363fcdc tests: test_json_patch: add test suite for JSON patch
Essentially, this change adds the test cases from this repo:
   https://github.com/json-patch/json-patch-tests

Specifically:
   https://github.com/json-patch/json-patch-tests/blob/master/spec_tests.json
   https://github.com/json-patch/json-patch-tests/blob/master/tests.json

The files were taken at the date of this commit, at git hash
  ea3af85790cb72893d0676597814b7532019c24e

Some tests may not have an 'expected' or 'error' field. Those are ignored.
One test was disabled manually via "disabled_in_json_c", because it tries
an impossible test, i.e. to add 2 "op" fields in the same patch entry,
something which is impossible in a JSON object.

For the 'error' cases, right now we only test that an error happens.
Later, we can extend this to check the error codes.

Signed-off-by: Alexandru Ardelean <ardeleanalex@gmail.com>
2023-07-31 22:18:03 -04:00
Alexandru Ardelean
538b046884 json_patch: add first implementation only with patch application
Initially I wanted to also do a function that generates the JSON patch from
two JSON documents, but even just applying the JSON patch was a bit of
work, especially when needing to satisfy all the test-cases.

This change defines all the operation in the RFC6902. The addition isn't
too big (for the json_patch_apply() function), as part of the heavy lifting
is also done by JSON pointer logic.

All the ops were tested with the test-cases defined at:
  https://github.com/json-patch/json-patch-tests

RFC6902: https://tools.ietf.org/html/rfc6902

Signed-off-by: Alexandru Ardelean <ardeleanalex@gmail.com>
2023-07-31 22:18:01 -04:00
Alexandru Ardelean
e4d9fbd52a json_pointer: split json_pointer_set_with_array_cb()
JSON patch is a bit more clear on how some array operations should be
handled. Unfortunately, handling them on a case-by-case is a bit tricky
because it's difficult to satisfy properly an 'add' operating with a 'move'
operation and the basic json_pointer_set().

With json_pointer_set{f}() we use json_object_array_put_idx() to insert a
value at a certain index.

With JSON patch:
* for the 'add' operation, we need to insert a value at a given index,
  which means shifting existing values by one to the right
  - also, we cannot allow values to be inserted/added outside the bounds of
    the array
* a 'move' operation, is described as a 'remove' and then an 'add';
  for arrays this complicates things, because when we want to a move a
  value within the array, we have to remove it first (during which the size
  of the array is reduced by one); when the size of the array is reduced by
  one, we can't add it to the last position in the array (before the
  remove)

The only sane method to handle this (after a few considerations) is to
provide a callback to the function that does the final put/insert into
the array. That way, we can do some final checks where these are needed to
handle each corner-case.

Signed-off-by: Alexandru Ardelean <ardeleanalex@gmail.com>
2023-07-31 22:17:30 -04:00
Alexandru Ardelean
1c38dea651 json_pointer: move array out-of-bounds check outside of is_valid_index()
The out-of-bounds check is useful when trying to index/obtain a value from
an array.
However, when we set a value to a specific JSON pointer, we can allow
values that are outside the length of the current array.
The RFC6901 doc isn't clear on that aspect, and doing so is a bit more
in-line with how json_object_array_{put,insert}_idx() functions behave.

This changes the behavior of json_pointer_set{f}() because now a value can
be set anywhere in the array.

Also, added a test-case for this behavior change.

Signed-off-by: Alexandru Ardelean <ardeleanalex@gmail.com>
2023-07-31 22:17:30 -04:00
Alexandru Ardelean
5a46a3b76d json_pointer: introduce json_pointer_get_internal() for internal usage
For JSON patch, we require that we get access to the parent of a JSON
object as well in order to do some operations via the API.

For example, given the object:
{
  "foo": "bar",
  "array", [ 1, 2, 3]
}

Using JSON pointer with the path
 * '/foo' will return 'bar' of type string
 * '/array/0' will return '1', of type integer

The problem is, that if we do 'json_object_put()' on any of the objects
above, this will not detach them from the parent, because there is no
information back to the parent.

One way to fix this, is to introduce links back to the parent, and have
these links be made by 'json_object_array_{put,insert}_idx()' and
'json_object_object_add{_ex}()'[1].

[1] For json_object_object_add_ex() we would need to de-constify the second
parameter, as we need to change it's internal state when being added to a
parent object. It may break some applications, but who knows.

But, since this information is needed mostly for JSON patch, another way to
address this, is to also retrieve the parent of an object via JSON pointer
and use json_object_object_del() and json_object_array_del_idx() on the
object's parent.

Signed-off-by: Alexandru Ardelean <ardeleanalex@gmail.com>
2023-07-31 22:17:30 -04:00
Alexandru Ardelean
43d3118935 json_pointer: convert index to size_t type
The index cannot be negative when parsing in is_valid_index(), because we
don't allow the '-' character in a string before we get to the strtol()
function.

So, might as well remove the negative check (for idx) in is_valid_index()
and convert it to size_t. That may allow for higher values for the index
(which can be insane, but some people may want to try it).

Signed-off-by: Alexandru Ardelean <ardeleanalex@gmail.com>
2023-07-31 22:17:30 -04:00
Alexandru Ardelean
d5c5b2caec tests: test1: add test cases for json_object_array_insert_idx()
This change adds a few test cases to test the behavior of the new
json_object_array_insert_idx() function, to make sure it behaves according
to specification in doc-string.

This test uses assert() vs the old method of comparing outputs.
This will cause the test to fail because the outputs won't match, since the
assert() will kick in.

Signed-off-by: Alexandru Ardelean <ardeleanalex@gmail.com>
2023-07-31 22:17:30 -04:00
Alexandru Ardelean
a86d7a8f5a json_object: introduce json_object_array_insert_idx() API function
The behavior of the json_object_array_put_idx() is that, if a user wants to
insert an element inside a JSON array, the element will be replaced.

For some cases, a user would want to insert an element into the JSON array
and shift the elements to the right.

For indexes that are outside the length of the current array this behaves
like json_object_array_put_idx().
If a user wants to enforce that the JSON array is not expanded, then the
json_object_array_length() function can be used to guard against that.

The main driver for this change is JSON patch, where the 'add' operation in
an array means inserting a value at a certain index and shifting everything
by one.

Signed-off-by: Alexandru Ardelean <ardeleanalex@gmail.com>
2023-07-31 22:17:30 -04:00
Alexandru Ardelean
5568916eb1 json_pointer: fix comments about printf() variants of set/get()
These were wrong. Some details about the json_pointer_setf() &
json_pointer_getf() were added in the json_pointer_set() &
json_pointer_get() doc-strings.

This change removes them.

Signed-off-by: Alexandru Ardelean <ardeleanalex@gmail.com>
2023-07-31 22:17:30 -04:00
Eric Hawicz
71d845e819 Issue #668: add the option to specify "cmake -DUSELOCALE_NEEDS_FREELOCALE=1" to work around a bug in older versions of FreeBSD (<12.4). 2023-07-30 13:38:15 -04:00
Eric Hawicz
c8b0a90e95 Issue #808: turn off -Wshorten-64-to-32 for clang builds (aka iOS builds) to workaround "implicit conversion loses integer precision" warnings. 2023-07-30 11:38:01 -04:00
Eric Hawicz
9b36c72945 Merge pull request #772 from cosmo-ray/color
add JSON_C_TO_STRING_COLOR option
2023-07-13 18:04:48 -04:00
Matthias Gatto
9803032b9d add JSON_C_TO_STRING_COLOR option
This option enable color in json_object_to_json_string_ext.
I've try to made something similar to jq output,
but I've color true/false and null in purple,
as it's what is common color scheme used in programing language in emacs.

also add a '-c' option into json_parser to test it.

note: that I could have done a color() function similar to
what is done with indent(), but as the code is pretty small
I've keep it as it. so if you want  me to use a subfunction
tell me and I'll do it.

Signed-off-by: Matthias Gatto <matthias.gatto@protonmail.com>
2023-07-10 20:45:20 +02:00
Eric Hawicz
bdfdb5fe10 Skip apps when we're included in someone else's build. Inspired by ssrlive in PR #813. 2023-07-06 20:56:49 -04:00
Eric Hawicz
11311ed2a3 Fix the -f option to apps/json_parse, add a -F <arg> option to specify arbitrary flags to pass to json_object_to_json_string_ext(). 2023-07-04 12:00:31 -04:00
Eric Hawicz
e9d3ab209a Merge pull request #759 from c3h2-ctf/truncation
json_tokener_parse_ex: handle out of memory errors
2023-07-04 11:45:57 -04:00
Eric Haszlakiewicz
4d529f92dc Issue #688: Only exclude generated doc/* files, keep the CMakeLists.txt, etc... so the nodoc tarball can still be built. 2023-07-01 18:02:00 +00:00
Eric Haszlakiewicz
d0f32a5a43 Stop linking a copy of _json_c_strerror() (strerror_override.c) into the tests.
That hasn't been needed since since commit 6068d3f, which changed that code to
 check an env var instead ("_JSON_C_STRERROR_ENABLE").
Fixes issue #812, about dup symbols in static builds with clang.
2023-03-28 23:08:39 +00:00
Eric Hawicz
efd536af48 Merge pull request #810 from dijonkitchen/patch-1
docs: update to Internet Standard reference
2023-03-10 14:54:44 -05:00
JC (Jonathan Chen)
4d5507f5dc docs: update to Internet Standard reference 2023-03-10 11:10:29 -05:00
Eric Haszlakiewicz
d1716fe431 Bump up the minimum cmake version to 3.9.
This gets us up to a version that supports features we're already using
(i.e. add_compile_options), but stops short of a cmake that requires
c++11, which some OSes still don't support.
Closes issue #774
2023-02-23 01:01:14 +00:00
Eric Haszlakiewicz
1741bcd3ea Issue #570: note brief instructions for building on Android. 2023-01-05 00:25:09 +00:00
Eric Hawicz
343f24f920 Merge pull request #804 from yrashk/cmp-0042
Problem: cmake 3.25.1 warns about CMP0042 not being set
2022-12-27 09:32:33 -05:00
Eric Hawicz
6ec5e5842d Merge pull request #803 from yrashk/patch-2
Problem: confusing error message in snprintf_compat.h
2022-12-27 09:26:30 -05:00
Eric Hawicz
b6ba9429d0 Merge pull request #802 from yrashk/patch-1
Problem: modern CMake warns about version 2.8
2022-12-27 09:25:58 -05:00
Yurii Rashkovskii
3cc0c47221 Problem: cmake 3.25.1 warns about CMP0042 not being set
Solution: set it explictly to OLD behavior
2022-12-23 15:05:46 -08:00
Yurii Rashkovskii
7b971b52aa Problem: confusing error message in snprintf_compat.h
Solution: fix it to reflect what's happening properly
2022-12-23 14:35:36 -08:00
Yurii Rashkovskii
debe8b70b7 Problem: modern CMake warns about version 2.8
The warning is as follows:

```
Compatibility with CMake < 2.8.12 will be removed from a future version of CMake.
```

Solution: set it at 2.8.12
2022-12-23 14:33:31 -08:00
Eric Hawicz
79c147203e Merge pull request #796 from fedefrancescon/test-add-int-get
Added Test for get int functions
2022-11-16 22:23:11 -05:00
Federico Francescon
1a2fdc49e7 Fixed test_int_get expected output 2022-11-16 01:33:02 +01:00
Federico Francescon
b1fb1508ee Added basic tests for json_object_get_int, json_object_get_int64, json_object_get_uint64 2022-11-16 00:49:18 +01:00
Eric Haszlakiewicz
bc35549f90 Update expected output for test_parse, missed in the previous commit. 2022-10-30 19:42:42 +00:00
Eric Haszlakiewicz
d6f46ae104 Explicitly check for integer overflow/underflow when parsing integers with JSON_TOKENER_STRICT. 2022-10-30 19:39:30 +00:00
Eric Haszlakiewicz
c50bf9df9c Apply same EINVAL handling to json_parse_uint64() as was done for json_parse_int64(). Document that overflow/underflow for these functions is not an error, but sets errno=ERANGE. 2022-10-30 03:25:32 +00:00
Eric Haszlakiewicz
57bef5edc4 Issue #792 - set errno=EINVAL if parsing the string in json_parse_int64 fails, to match the docs for json_object_get_int. 2022-10-26 02:19:38 +00:00
Eric Hawicz
777dd06be8 Merge pull request #790 from Sarcares/patch-1
Small update to README file
2022-09-13 22:15:48 -04:00
Luca Mannella
84248a7884 Small update to README file
it could be necessary to execute make install
2022-09-12 17:29:47 +02:00
Eric Hawicz
81f0807b63 Merge pull request #784 from rouault/get_time_seed_coverity_scan_silence
get_time_seed(): silence warning emitted by Coverity Scan static analyzer
2022-08-16 18:10:06 -04:00
Even Rouault
57ea393004 get_time_seed(): silence warning emitted by Coverity Scan static analyzer
It warns about the return of time() being truncated to 32 bit, which is
not an issue here.
(this warning was emitted because of the https://github.com/OSGeo/gdal
project embedding a copy of libjson-c and running Coverity Scan
analysis)
2022-08-16 11:11:58 +02:00
Eric Hawicz
9417f4e726 Merge pull request #783 from kraj/master
Fix build with clang-15+
2022-08-14 08:19:19 -04:00
Khem Raj
257b29c991 json_pointer.c: Move idx_val declaration to top of function
This helps compiling with MS compiler, error seems to be
due to defining a variable within the body of the function
its allowed in c99 but not in c89. This should fix build with
MSVC 16.0.40219.1 compiler from Visual Studio 14 2015

Signed-off-by: Khem Raj <raj.khem@gmail.com>
2022-08-14 00:46:28 -07:00
Khem Raj
d1deed499f json_inttypes.h: Define ssize_t on windows platforms
Signed-off-by: Khem Raj <raj.khem@gmail.com>
2022-08-13 21:45:11 -07:00
Khem Raj
6eca65617a Fix build with clang-15+
Fixes
json_util.c:63:35: error: a function declaration without a prototype is deprecated in all versions of C [-We
rror,-Wstrict-prototypes]
const char *json_util_get_last_err()
                                  ^
                                   void

Signed-off-by: Khem Raj <raj.khem@gmail.com>
2022-08-13 20:47:20 -07:00
Eric Hawicz
ac4dfa44cb Merge pull request #782 from DimitriPapadopoulos/codespell
Fix typos found by codespell
2022-08-13 09:43:50 -04:00
Dimitri Papadopoulos
9462c0a7b5 Fix typos found by codespell
Do not fix typos from past commits found in release notes.
2022-08-13 15:47:40 +03:00
Eric Haszlakiewicz
bdd5e03d6e Apply some of the fixes from PR #740, although by using size_t instead of castings. 2022-07-31 19:28:48 +00:00
Eric Hawicz
4b0c6de760 Merge pull request #757 from c3h2-ctf/big
json_object_from_fd_ex: fail if file is too large
2022-07-31 14:27:32 -04:00
Eric Haszlakiewicz
253a5fa99d Issue #705: disable locale handling when building for a uClibc system because its duplocale() function (intentionally) crashes. 2022-07-30 20:27:35 +00:00
Eric Haszlakiewicz
9749b0cb66 When serializing with JSON_C_TO_STRING_PRETTY set, keep the opening and closing curly or square braces on same line for empty objects or arrays. Issue #778. 2022-07-30 19:27:14 +00:00
Eric Haszlakiewicz
2e9b7456a5 Update Travis links to point at travis-ci.com instead of travis-ci.org 2022-07-26 23:47:58 +00:00
Eric Haszlakiewicz
5282e73600 Entirely drop mode bits from open(O_RDONLY) to avoid warnings on certain platforms. Fixes issue #779. 2022-07-26 23:43:30 +00:00
Eric Haszlakiewicz
8b35a78d29 Trim a few travis builds, update others to more recent toolchains. 2022-07-24 20:37:14 +00:00
Eric Haszlakiewicz
22773b1e51 Fix the expected output for test_set_serializer. 2022-07-24 19:00:27 +00:00
Eric Haszlakiewicz
16208fc01a Add test to check for the memory leak mentioned in issue #781 2022-07-24 18:59:26 +00:00
Eric Hawicz
2a2d861bc0 Merge pull request #781 from dddaniel/master
Fix memory leak with emtpy strings in json_object_set_string
2022-07-24 14:15:42 -04:00
Daniel Danzberger
213bb5caa1 Fix memory leak with emtpy strings in json_object_set_string
When a json string object is updated with a bigger string, a new
malloc'ed buffer is used to store the new string and it's size is made
negative to indicate that an external buffer is in use.

When that same json string object get's updated again with an empty
stirng (size = 0), the new external malloc'ed buffer is still used.
But the fact that the new size value is not negative removes the
indicator that the externally malloc'ed buffer is used.

This becomes a problem when the object get's updated again with any
other string, because a new buffer will be malloced and linked to the
object while to old one won't be free'd.

This causes a memory leak when updating a json string with
json_object_set_stirng() which has previously been updated
with an empty string.

Example:
--
obj = json_object_new_string("data");
json_object_set_string(obj, "more data");
json_object_set_string(obj, "");
json_object_set_string(obj, "other data"); /* leaks */
--

This commit fixes the issue by free'ing the external buffer when an
empty string is set and use the internal one again.

Signed-off-by: Daniel Danzberger <daniel@dd-wrt.com>
2022-07-24 19:03:49 +02:00
Eric Haszlakiewicz
d28ac67dde Fix issue #775 - use a loop instead of list(TRANSFORM ...) to support cmake < 3.12. 2022-06-27 02:15:24 +00:00
Eric Hawicz
5d98f7825a Merge pull request #776 from stoeckmann/typo
Fix typo
2022-06-21 21:39:00 -04:00
Tobias Stoeckmann
f63573460c Fix typo 2022-06-21 14:39:01 +02:00
Eric Haszlakiewicz
6ee0a35a20 Fix #771/#768 by marking usage() as "noreturn" instead of using "FALLTHRU" in the case statement where it'd called. 2022-06-13 01:02:53 +00:00
Eric Hawicz
11546bfd07 Merge pull request #769 from An7ar35/issue-768
Issue #768
2022-06-03 23:14:16 -04:00
An7ar35
5d00384e0d missing 'FALLTHRU' added to sort out error messages when using "-Werror=implicit-fallthrough" flag 2022-06-01 12:36:33 +02:00
Eric Haszlakiewicz
49c3721a5a Unset NDEBUG so assert() is enabled in all tests. One more fix there when building with -DCMAKE_BUILD_TYPE=release. 2022-05-30 15:39:54 +00:00
Eric Haszlakiewicz
2f0942bdd7 Specify dependent libraries, including -lbsd, in a more consistent way so linking against a static json-c works better. Related issue #766
Use target_link_libraries, plus fill in Libs.private in json-c.pc so pkg-config --static --libs works appropriately.
Also, only link against libbsd when arc4random is actually found there.
2022-05-30 15:30:11 +00:00
Eric Haszlakiewicz
6ba1adf8ef Include the tests and apps directories at the _end_, since order in the
cmake rules matters, and fix compile warnings now that we're building
those sources with all the regular flags.
2022-05-30 14:33:16 +00:00
Eric Haszlakiewicz
86b46cac07 Add --disable-static and --disable-dynamic options to the cmake-configure script. 2022-05-30 14:31:08 +00:00
Eric Haszlakiewicz
f2fc1ca00a Note the DSIABLE_JSON_POINTER and DISABLE_EXTRA_LIBS build options on the README 2022-04-14 12:57:43 +00:00
Eric Haszlakiewicz
acccefd770 Add a "Getting Help" section to the README. 2022-04-14 12:55:32 +00:00
Eric Haszlakiewicz
de5a64888a Update the master branch to version 16.99 2022-04-14 12:29:39 +00:00
Eric Haszlakiewicz
7e3eba72db Clarify how to set the uploaded release tarballs to be publically readable. 2022-04-14 12:17:59 +00:00
Eric Haszlakiewicz
7d303478a4 Update the ChangeLog with recent changes, in preparation for a 0.16 release.
Add a list of issues closed for this release.
2022-04-14 01:05:38 +00:00
Eric Haszlakiewicz
66dcdf549e Add new authors since the 0.15 release, tweak instructions for how to update that list. 2022-04-14 01:04:53 +00:00
Eric Hawicz
4902f9cb87 Merge pull request #765 from jvoisin/patch-1
Improve a bit the coverage of the fuzzer
2022-04-13 14:28:51 -04:00
Julien Voisin
558d48a6f3 Improve a bit the coverage of the fuzzer 2022-04-13 15:42:46 +02:00
Eric Haszlakiewicz
46b58ad9e7 Fix issue #764: adjust test_util_file to match new output (changed in 6e53347) 2022-04-08 22:58:24 +00:00
Eric Hawicz
0b937f6173 Merge pull request #758 from c3h2-ctf/context
Preserve context if out of memory
2022-04-04 18:01:39 -04:00
Eric Hawicz
65274cf3b5 Update issue templates 2022-04-04 17:10:31 -04:00
Tobias Stoeckmann
0c0d901443 Preserve context if out of memory
If memory allocation fails in json_c_set_serialization_double_format or
json_object_copy_serializer_data then return with an error value and
preserve previous values without overriding them with NULL.
2022-03-31 18:05:48 +02:00
Eric Haszlakiewicz
e244146dfd Remove single quote from #error line. Fixes issue #761 2022-03-25 01:12:07 +00:00
Eric Hawicz
a1c092bd7b Merge pull request #760 from BonsaiYi/error
Code style: removed unneeded double-quotes
2022-03-23 00:14:36 -04:00
BonsaY
716978f20d Code style removed unneeded double-quotes
this way, it complies with the other #error usages
2022-03-21 21:10:45 +01:00
Tobias Stoeckmann
9e6acc9a4e json_tokener_parse_ex: handle out of memory errors
Do not silently truncate values or skip entries if out of memory errors
occur.

Proof of Concept:

- Create poc.c, a program which creates an eight megabyte large json
  object with key "A" and a lot of "B"s as value, one of them is
  UTF-formatted:

```c
 #include <err.h>
 #include <stdio.h>
 #include <string.h>

 #include "json.h"

 #define STR_LEN (8 * 1024 * 1024)
 #define STR_PREFIX "{ \"A\": \""
 #define STR_SUFFIX "\\u0042\" }"

int main(void) {
  char *str;
  struct json_tokener *tok;
  struct json_object *obj;

  if ((tok = json_tokener_new()) == NULL)
    errx(1, "json_tokener_new");

  if ((str = malloc(STR_LEN)) == NULL)
    err(1, "malloc");
  memset(str, 'B', STR_LEN);
  memcpy(str, STR_PREFIX, sizeof(STR_PREFIX) - 1);
  memcpy(str + STR_LEN - sizeof(STR_SUFFIX), STR_SUFFIX, sizeof(STR_SUFFIX));

  obj = json_tokener_parse(str);
  free(str);

  printf("%p\n", obj);
  if (obj != NULL) {
    printf("%.*s\n", 50, json_object_to_json_string(obj));
    json_object_put(obj);
  }

  json_tokener_free(tok);
  return 0;
}
```
- Compile and run poc, assuming you have enough free heap space:
```
gcc $(pkg-config --cflags --libs) -o poc poc.c
./poc
0x559421e15de0
{ "A": "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
```
- Reduce available heap and run again, which leads to truncation:
```
ulimit -d 10000
./poc
0x555a5b453de0
{ "A": "B" }
```
- Compile json-c with this change and run with reduced heap again:
```
ulimit -d 10000
./poc
(nil)
```

The output is limited to 70 characters, i.e. json-c parses the 8 MB
string correctly but the poc does not print all of them to the screen.

The truncation occurs because the parser tries to add all chars up
to the UTF-8 formatted 'B' at once. Since memory is limited to 10 MB
there is not enough for this operation. The parser does not fail but
continues normally.

Another possibility is to create a json file close to 2 GB and run a
program on a system with limited amount of RAM, i.e. around 3 GB. But
ulimit restrictions are much easier for proof of concepts.

Treat memory errors correctly and abort operations.
2022-03-20 17:42:47 +01:00
Tobias Stoeckmann
5accae04bb json_object_from_fd_ex: fail if file is too large
If the input file is too large to fit into a printbuf then return an
error value instead of silently truncating the parsed content.

This introduces errno handling into printbuf to distinguish between an
input file being too large and running out of memory.
2022-03-20 13:17:37 +01:00
Eric Hawicz
79459b2de2 Merge pull request #755 from c3h2-ctf/error
Fix error messages
2022-03-19 10:05:48 -04:00
Eric Hawicz
2326e34390 Merge pull request #754 from c3h2-ctf/doc
Minor improvements to documentation
2022-03-19 10:04:58 -04:00
Tobias Stoeckmann
6e533471a8 Fix error messages
Error messages did not reflect actual function names.
2022-03-19 10:59:43 +01:00
Tobias Stoeckmann
a7d85bfba9 Fix typos in comments
Spotted during code reviews.
2022-03-19 10:39:56 +01:00
Tobias Stoeckmann
cbc603b587 Adjusted URLs
Most of these sites support HTTPS (some forward to HTTPS when accessing
the HTTP versions). Use HTTPS directly if supported.

Some URLs led to 404 error pages. Adjusted the links to point to
new locations.

I did not adjust the Microsoft HTML Help Workshop link because it seems
that this software is not available anymore. Instead of removing the
link entirely I kept it there in case it helps someone to find the
software on archived websites.
2022-03-19 10:34:55 +01:00
Eric Hawicz
f0d93cee14 Merge pull request #748 from c3h2-ctf/printbuf
sprintbuf(): test for all vsnprintf error values
2022-03-07 00:06:57 -05:00
Eric Hawicz
9b832c8710 Merge pull request #752 from c3h2-ctf/typos
Fix typos
2022-03-06 23:33:42 -05:00
Tobias Stoeckmann
543a8eb5f9 Fix typos
Mostly found with codespell and during code review.
2022-03-06 16:07:36 +01:00
Tobias Stoeckmann
94b2a0cb29 sprintbuf(): test for all vsnprintf error values
The POSIX specification states that vsnprintf returns "a negative value"
in case of error, but the code checks explicitly only for -1.
2022-03-06 16:05:32 +01:00
Eric Hawicz
a4389f4f30 Merge pull request #749 from c3h2-ctf/sprintbuf
sprintbuf(): handle printbuf_memappend errors
2022-03-03 21:32:09 -05:00
Eric Hawicz
4493db76d6 Merge pull request #750 from c3h2-ctf/clearmem
printbuf_memset(): set gaps to zero
2022-03-03 21:29:27 -05:00
Eric Hawicz
1491d92038 Merge pull request #751 from c3h2-ctf/arguments
printbuf: do not allow invalid arguments
2022-03-03 21:26:22 -05:00
Tobias Stoeckmann
d07da04c14 sprintbuf(): handle printbuf_memappend errors
If errors occur in printbuf_memappend, then these errors should be
propagated through sprintbuf to indicate the error to the user.

Proof of Concept:
```
 #include <err.h>
 #include <limits.h>
 #include <stdio.h>

 #include "json.h"

 int
 main(void) {
  struct printbuf *pb;
  if ((pb = printbuf_new()) == NULL)
   err(1, "printbuf_new");
  if (printbuf_memset(pb, INT_MAX - 9, 'a', 1) < 0)
   errx(1, "printbuf_memset");
  printf("length: %d\n", printbuf_length(pb));
  printf("sprintbuf: %d\n", sprintbuf(pb, "string too long"));
  printf("length: %d\n", printbuf_length(pb));
  printbuf_free(pb);
  return 0;
 }
```

You can see that sprintbuf does not return an error but length is still
the same, i.e. the string "string too long" has not been appended.

I would like to add this as a unit test but it really depends on the
operating system if printbuf_memset() would fail if not enough memory is
available or not.
2022-03-03 21:24:27 +01:00
Tobias Stoeckmann
63c602ff80 printbuf_memset(): set gaps to zero
It is possible to have a printbuf with "gaps", i.e. areas within the
print buffer which have not been initialized by using printbuf_memset.

Always clear memory in such cases.

Example:
```
struct printbuf *pb = printbuf_new();
printbuf_memset(pb, 10, 'a', 2);
```
In this case pb->buf[0] is '\0' but pb->buf[1] up to pb->buf[9] are
not set. The length would be 12 due to successful printbuf_memset.
2022-03-03 21:18:53 +01:00
Tobias Stoeckmann
4355242477 printbuf: do not allow invalid arguments
If invalid arguments are passed to printbuf functions return -1 to
protect printbuf internals.
2022-03-03 21:15:19 +01:00
Eric Hawicz
bd56cc8bf7 Merge pull request #745 from c3h2-ctf/vasprintf
vasprintf(): avoid out of memory accesses
2022-02-27 08:34:21 -05:00
Eric Hawicz
723ac8cbb5 Merge pull request #746 from rouault/typo_fixes
Fix typos in code comments and ChangeLog
2022-02-26 23:45:15 -05:00
Even Rouault
3bb54f97e7 Fix typos in code comments and ChangeLog 2022-02-25 00:14:47 +01:00
Tobias Stoeckmann
5c72257220 vasprintf(): avoid out of memory accesses
Systems without vasprintf fall back to implementation in header file
vasprintf_compat.h. This version could run into heap overflow issues
with very long arguments or formats provoking a lot of output.

The vsnprintf function returns a negative value if more than INT_MAX
characters would be written since its int return type could not
handle this (and %n couldn't handle it either).

Before testing for a possible error value the additional char for
\0 is already added. A -1 error code would not be detected.

Increment only after implicitly casting to an unsigned value to avoid
signed integer overflow if INT_MAX has been returned.

Use va_copy to duplicate the original ap argument for multiple uses
on non-WIN32 systems. At least with glibc the test suite would fail
because the arguments are not reset after leaving the vsnprintf call.

Removed support for apparently very old glibc versions which do not
comply with vsnprintf standard descriptions. It breaks support for
modern ones which are not forced to return -1 in case of error. The
standard specifies merely "a negative value".

How to reproduce:

- Use a system without vasprintf
- Alternatively remove -D_GNU_SOURCE from CMakeLists.txt
- Compile and run:

  #include "json.h"
  int main(void) {
    struct printbuf *pb = printbuf_new();
    sprintbuf(pb, "prefix %2147483647s", "*");
    printbuf_free(pb);
    return 0;
  }
2022-02-24 23:06:57 +01:00
Eric Hawicz
66cce0a1d7 Merge pull request #739 from rouault/avoid_unsigned_integer_overflow
json_escape_str(): avoid harmless unsigned integer overflow
2022-02-18 20:21:18 -05:00
Eric Hawicz
b11f79c52c Merge pull request #741 from rouault/json_type_to_name_formatter
json_type_to_name(): use correct printf() formatter
2022-02-18 20:08:31 -05:00
Eric Hawicz
78246db72f Merge pull request #742 from rouault/json_object_copy_serializer_data_add_assertion
json_object_copy_serializer_data(): add assertion
2022-02-18 20:08:02 -05:00
Eric Hawicz
a1ea216878 Merge pull request #744 from Kizuna-Meraki/close-random
Close file on error path.
2022-02-18 20:07:33 -05:00
Kizuna-Meraki
d783ad76c7 Close file on error path.
The file was only be closed when there was no error and
was being left open when there was an error. By moving
the close(fd) statement out of the if-clause, the file
can be close regardless if there is an error or not.
After the file is closed, it can be checked for errors.
2022-02-17 21:27:01 +01:00
Even Rouault
f2c0df404b json_type_to_name(): use correct printf() formatter
Was detected by Coverity Scan when analyzing GDAL's code base which has
a copy of json-c
2022-01-31 00:27:41 +01:00
Even Rouault
82d9433813 json_object_copy_serializer_data(): add assertion
This makes Coverity Scan happier since it believes that the initial
check ``if (!src->_userdata && !src->_user_delete)`` could mean that
src->_user_data may be nullptr.
2022-01-16 20:50:58 +01:00
Even Rouault
296db618e9 json_escape_str(): avoid harmless unsigned integer overflow
Current behaviour is perfectly valid, since wrap-over upon overflow is
well defined behaviour for unsigned types, but it is nevertheless nice to be
able to build with -fsanitize=undefined,unsigned-integer-overflow

There is no significant effect on the generated assembly as can be seen
on the diff of objdump -d output on a optimized build (the compiler
just decided to switch the order of a comparison):

@@ -135,8 +135,8 @@
  1d0:	0f 84 70 ff ff ff    	je     146 <json_escape_str+0x146>
  1d6:	4c 3b 24 24          	cmp    (%rsp),%r12
  1da:	0f 85 2d ff ff ff    	jne    10d <json_escape_str+0x10d>
- 1e0:	49 39 f4             	cmp    %rsi,%r12
- 1e3:	0f 87 b7 00 00 00    	ja     2a0 <json_escape_str+0x2a0>
+ 1e0:	4c 39 e6             	cmp    %r12,%rsi
+ 1e3:	0f 82 b7 00 00 00    	jb     2a0 <json_escape_str+0x2a0>
  1e9:	48 8b 44 24 18       	mov    0x18(%rsp),%rax
  1ee:	64 48 33 04 25 28 00 	xor    %fs:0x28,%rax
  1f5:	00 00
2022-01-12 23:44:39 +01:00
Eric Hawicz
3b4f1e92ad Merge pull request #737 from tniessen/patch-1
Fix typo in README
2022-01-11 21:25:38 -05:00
Tobias Nießen
928fa96db7 Fix typo in README 2022-01-10 00:12:25 +01:00
Eric Haszlakiewicz
a5c2e11460 Cause the cmake include dirs to also have ${CMAKE_INSTALL_INCLUDEDIR}/json-c, so downstream packages that use cmake to link against json-c can choose whether to include headers as just e.g. #include <json_object.h>, if they care to do so.
Update the README to better explain this, and make a few other tweaks.
2021-12-22 02:52:37 +00:00
Eric Haszlakiewicz
2d2382d709 Add linkhash accessor functions (lh_table_head(), lh_entry_next(), etc...) to pave the way for making the lh_table and lh_entry structure opaque in the future.
Update the docs to mark all members of those structures deprecated, and
 suggest what to use instead.
2021-11-30 03:27:55 +00:00
Eric Haszlakiewicz
320548caf6 Drop the REFCOUNT_DEBUG code, it hasn't been used in ages. 2021-11-30 03:08:02 +00:00
Eric Hawicz
9a90b8477b Merge pull request #734 from json-c/newer-appveyor
Newer appveyor config for VS2022 etc...
Update the appveyor config to specify "image" instead of just "os", and build for VS2017, VS2019 and VS2022.
2021-11-29 13:40:41 -05:00
Eric Haszlakiewicz
1cb56e705f Put the most recent image first in appveyor builds. 2021-11-29 18:21:05 +00:00
Eric Haszlakiewicz
1763edaba3 Skip most "Release" builds. s/b_config/CONFIGURATION/ to fix artifact creation. 2021-11-29 18:18:48 +00:00
Eric Haszlakiewicz
a5fed59756 There doesn't seem to be a way to extend the appveyor build matrix for just one image, so instead list a whole bunch of excluded builds. 2021-11-27 02:55:29 +00:00
Eric Haszlakiewicz
0910e18bbd Use the newer appveyor images to build for VS2017 and VS2019. Trim the number of builds we do. 2021-11-27 02:29:26 +00:00
Eric Haszlakiewicz
f1fb9abf14 Note the need to also set CTEST_OUTPUT_ON_FAILURE to get test output 2021-11-26 22:49:42 +00:00
Eric Hawicz
42aa6f7257 Merge pull request #732 from DiracResearch/fix/static_include_dirs
Fix/static include dirs
2021-11-11 23:52:43 -05:00
Robert Bielik
286b4fdd27 Fix uninitialized value error for clang-8 msan 2021-11-11 10:23:05 +01:00
Robert Bielik
a66a6cc51b Fix for clang ub sanitizer 2021-11-11 09:51:18 +01:00
Robert Bielik
21f767f63f Add target include dirs for static library as well 2021-11-11 09:37:53 +01:00
Eric Hawicz
9b0fb2b33e Merge pull request #727 from jobol/propo2
Really use prefix JSON_C_OBJECT_ADD_
2021-10-22 19:06:11 -04:00
José Bollo
8bf3b45a29 Really use prefix JSON_C_OBJECT_ADD_*
This change introduces JSON_C_OBJECT_ADD_CONSTANT_KEY
as a replacement of JSON_C_OBJECT_KEY_IS_CONSTANT.

The description of json_object_object_add_ex tells to
look at the flags JSON_C_OBJECT_ADD_* but it is not
for JSON_C_OBJECT_KEY_IS_CONSTANT.

From the point of vue of a developper using json-c,
the function json_object_object_add_ex is mainly used,
not the hash facility, it seems more natural to provide
a regular naming of prefix JSON_C_OBJECT_ADD_CONSTANT_KEY.
2021-10-19 11:18:17 +02:00
Eric Hawicz
05c5d15075 Merge pull request #729 from DeX77/patch-1
* don't assume includedir
2021-10-17 14:23:28 -04:00
DeX77
d6d4b71d7d * don't assume includedir
This change syncs the public header include install location with what gets written into pkgconfig file.
2021-10-15 11:12:39 +02:00
Eric Hawicz
382f9462c2 Merge pull request #726 from leongross/fix/test-cmake3.1
fix cmake version for tests
2021-10-09 09:17:25 -04:00
Leon Gross
8be2ffdcd7 fix cmake version for tests 2021-10-06 15:29:33 +02:00
Eric Hawicz
4fc44f32df Merge pull request #722 from imaami/fix-json_tokener_new_ex-use-after-free
Fix use-after-free in json_tokener_new_ex()
2021-09-04 23:16:13 -04:00
Juuso Alasuutari
9361d8d3a8 Fix use-after-free in json_tokener_new_ex()
The failure path taken in the event of printbuf_new() returning NULL
calls free() on tok->stack after already having freed tok. Swap the
order of the two calls to fix an obvious memory access violation.

Fixes: bcb6d7d347 ("Handle allocation failure in json_tokener_new_ex")
Signed-off-by: Juuso Alasuutari <juuso.alasuutari@gmail.com>
2021-09-04 20:14:30 +03:00
Eric Hawicz
dc1ef7d566 Merge pull request #718 from Pawday/master
CMake create uninstall target if unix generator is used
2021-07-31 22:46:01 -04:00
Pawday
e91e4cc9fb Setted cmake "uninstall" target to exist in unix like operating systems only 2021-07-26 18:52:29 +03:00
Eric Haszlakiewicz
f61f1a7a91 Add workaround for Visual Studio not knowing about "inline". 2021-07-25 20:31:59 +00:00
Eric Haszlakiewicz
db6a6cc2b2 Switch the Travis build to use osx_image: xcode12.5, in an attempt to avoid timeouts with Homebrew. 2021-07-25 20:03:55 +00:00
Eric Haszlakiewicz
6a0df2609e Merge some old work to include (some of) PR #464 into the current master branch. 2021-07-25 19:07:06 +00:00
Eric Haszlakiewicz
8c727e5ce1 Only define an "uninstall" target if it's not already defined (e.g. by projects that include json-c) 2021-07-25 15:11:11 +00:00
Eric Hawicz
be9671e48a Merge pull request #714 from Hex052/clang-format_AfterCaseLabel
Add AfterCaseLabel to .clang-format
2021-07-05 18:18:06 -04:00
Hex052
9dde931a1c Add AfterCaseLabel to .clang-format
This is to fix the behavior that might've changed between older versions of clang-format, I'm not sure.
Version 10 tries to put the bracket on the same line as case without this.
2021-07-04 18:28:21 -08:00
Eric Haszlakiewicz
75bf657cc2 If inttypes.h is present, use it, even on Windows. 2021-06-13 21:12:22 +00:00
Eric Haszlakiewicz
9ca50cf2f8 Issue #709: adjust some include guards to be a bit more json-c specific. 2021-06-02 23:53:23 +00:00
Eric Hawicz
0b7e78c309 Merge pull request #706 from davidjmccann/master
Check __STDC_VERSION__ is defined before checking its value
2021-05-15 08:41:24 -04:00
David McCann
00098efc96 Merge branch 'json-c:master' into master 2021-05-13 06:34:10 +01:00
David McCann
9b53c92ea3 Check __STDC_VERSION__ is defined before checking its value
Prevent an undef warning regarding __STDC_VERSION__ by checking whether it is defined before checking its value.
2021-05-13 06:31:18 +01:00
Eric Hawicz
cd7109f767 Merge pull request #696 from ssrlive/master
To avoid target exe file export JSON functions.
2021-05-01 15:21:31 -04:00
Eric Hawicz
78e390a261 Merge pull request #701 from commodo/configurable-opts
[RFC] json_pointer: allow the feature to be disabled
2021-04-17 17:26:49 -04:00
Alexandru Ardelean
8abeebc9b2 json_pointer: allow the feature to be disabled
Some users may not want to included it in their build/system. So allow a
cmake symbol to disable it.

A user can do 'cmake -DDISABLE_JSON_POINTER=ON <json_c_root_dir>' and
disable the json_pointer functionality. That saves about 17 KB (on an
x86_64) machine. This may be useful on smaller embedded systems; even
though the saving would be fewer kilobytes.

One thing that also needs to change a bit, is that the 'json.h' be
autogenerated via cmake, in order to conditionally include that
"json_pointer.h" file.

Signed-off-by: Alexandru Ardelean <ardeleanalex@gmail.com>
2021-04-16 11:49:38 +03:00
Alexandru Ardelean
1f8b64f62c tests: CMakeLists.txt: move test names to variable
The intent is to be able to disable some features that get built into the
library. When we do that, we also need to disable some tests.

It's easier when adjusting a variable that contains the list of test names,
versus modifying the list in the foreach() statement.

Signed-off-by: Alexandru Ardelean <ardeleanalex@gmail.com>
2021-04-16 09:32:17 +03:00
Eric Hawicz
94909840be Merge pull request #700 from Philosoph228/werror-fix
Fix unused variable for Win32 build in random_seed.c
2021-04-14 22:38:36 -04:00
Philosoph228
9c0565100a random_seed: fix unused variable for win32 build 2021-04-13 11:47:01 +05:00
ssrlive
ba181548bc To avoid target exe file export JSON functions. 2021-03-02 14:27:40 +08:00
Eric Haszlakiewicz
041cef434a Add a DISABLE_EXTRA_LIBS option to skip using libbsd, per @neheb's request on issue #692/commit 0f61f692. 2021-02-15 20:19:56 +00:00
Eric Haszlakiewicz
f787810890 If arc4random is used, don't bother compiling in the other fallback methods since they'll never be used. Fixes PR#695 about unreachable code too. 2021-02-13 03:23:58 +00:00
Eric Hawicz
7c859c54e4 Merge pull request #694 from ihsinme/patch-1
fix invalid unsigned arithmetic.
2021-02-06 17:25:24 -05:00
ihsinme
c456963110 Update json_object.c 2021-02-05 18:58:20 +03:00
Eric Haszlakiewicz
0f61f6921b Iesue #692: use arc4random() if it's available (in libc on BSD systems, and libbsd on Linux). 2021-01-13 01:57:25 +00:00
Eric Haszlakiewicz
69d650528d Keep the doc directory in the nodoc release tarball, just exclude its contents. 2021-01-13 01:30:16 +00:00
Eric Hawicz
4754f47434 Merge pull request #674 from ploxiln/random_seed_err_continue
random_seed: on error, continue to next method
2021-01-12 20:22:54 -05:00
Eric Hawicz
1fcb9e476b Merge pull request #689 from neheb/patch-1
fix compilation with clang
2020-12-18 21:30:14 -05:00
Rosen Penev
987d3b2c86 fix compilation with clang
Fixes the following warning:

json_pointer.c:230:7: warning: implicit declaration of function
    'vasprintf' is invalid in C99 [-Wimplicit-function-declaration]
            rc = vasprintf(&path_copy, path_fmt, args);
2020-12-17 19:59:37 -08:00
Pierce Lopez
0fd3b7d316 random_seed: on error, continue to next method
instead of exiting the process
2020-10-07 01:22:30 -04:00
Eric Hawicz
df27756491 Merge pull request #667 from stoeckmann/regression
Fixed test1 regression.
2020-09-11 20:56:51 -04:00
Tobias Stoeckmann
7af593c140 Fixed test1 regression.
SIZEOF_SIZE_T might be only defined in config.h.

Include config.h for these systems to pass tests which are only
supposed to be run on 32 bit systems.

Fixes issue #666.
2020-09-11 21:09:40 +02:00
Eric Hawicz
785a94b7a2 Merge pull request #665 from stoeckmann/tokener
Handle more allocation failures in json_tokener* functions
2020-08-24 09:51:41 -04:00
Eric Hawicz
eb08a92218 Merge pull request #660 from stoeckmann/arraylist
Validate size arguments in arraylist functions.
2020-08-24 09:51:18 -04:00
Tobias Stoeckmann
369e8477d2 Validate size arguments in arraylist functions.
The array_list_new2 function, which is externally reachable through
json_object_new_array_ext, does not check if specified initial size
actually fits into memory on 32 bit architectures.

It also allows negative values, which could lead to an overflow on these
architectures as well. I have added test cases for these situations.

While at it, also protect array_list_shrink against too large
empty_slots argument. No test added because it takes a huge length
value, therefore a lot of items within the array, to overflow the
calculation. In theory this affects 64 bit sytems as well, but since the
arraylist API is not supposed to be used by external applications
according to its header file, the call is protected due to int
limitation of json_object_array_shrink.
2020-08-24 12:13:50 +02:00
Eric Hawicz
b4e72c2655 Merge pull request #664 from stoeckmann/string
Limit strings at INT_MAX length
2020-08-23 16:43:31 -04:00
Eric Hawicz
f941931804 Merge pull request #663 from stoeckmann/strerror
Properly format errnos in _json_c_strerror
2020-08-23 16:38:21 -04:00
Eric Hawicz
1bc7a6b223 Merge pull request #662 from stoeckmann/random
Prevent signed overflow in get_time_seed
2020-08-23 16:34:40 -04:00
Tobias Stoeckmann
df62119b7f Prevent signed overflow in get_time_seed
Casting time(2) return value to int and multiplying the result with
such a constant will definitely lead to a signed overflow by this day.

Since signed overflows are undefined behaviour in C, avoid this.

Casting to unsigned is more than enough since the upper bits of a
64 bit time_t value will be removed with the int conversion anyway.
2020-08-22 13:25:21 +02:00
Tobias Stoeckmann
bcb6d7d347 Handle allocation failure in json_tokener_new_ex
The allocation of printbuf_new might fail. Return NULL to indicate tis
error to the caller. Otherwise later usage of the returned tokener would
lead to null pointer dereference.
2020-08-22 13:18:10 +02:00
Tobias Stoeckmann
e50154f615 Cap string length at INT_MAX.
Several issues occur if a string is longer than INT_MAX:

- The function json_object_get_string_len returns the length of a string
  as int. If the string is longer than INT_MAX, the result would be
  negative.
- That in turn would lead to possible out of boundary access when
  comparing these strings with memcmp and the returned length as done in
  json_object_equal.
- If json_escape_str is called with such strings, out of boundary
  accesses can occur due to internal int handling (also fixed).
- The string cannot be printed out due to printbuffer limits at
  INT_MAX (which is still true after this commit).

Such huge strings can only be inserted through API calls at this point
because input files are capped at INT_MAX anyway.

Due to huge amount of RAM needed to reproduce these issues I have not
added test cases.
2020-08-22 13:16:36 +02:00
Tobias Stoeckmann
583911a66c Aligned comment in _json_object_new_string
The comment only aligns correctly if tab size is 4. Replaced
spaces with tabs to stay in sync with style of other lines.
2020-08-22 13:07:45 +02:00
Tobias Stoeckmann
4298431150 Properly format errnos in _json_c_strerror
The function _json_c_strerror does not properly format unknown errnos.
The int to ascii loop ignores the leading digit if the number can be
divided by 10 and if an errno has been formatted, shorter errnos would
not properly terminate the newly created string, showing the ending
numbers of the previous output.

A test case has been added to show these effects.

Since this function has been introduced for tests, the effect of this on
real life code is basically non-existing. First an environment variable
has to be set to activate this strerror code and second an unknown errno
would have to be encountered.
2020-08-22 11:35:50 +02:00
Eric Haszlakiewicz
2b439ea598 Fix json_object_get_boolean() doc for the object and array cases (always returns 0), and add those cases to the test_cast test.
See also issue #658.
2020-08-17 14:57:21 +00:00
Eric Hawicz
cf30cba4ac Merge pull request #657 from stoeckmann/getrandom
Use GRND_NONBLOCK with getrandom.
2020-08-15 15:01:41 -04:00
Tobias Stoeckmann
f052e42f56 Use GRND_NONBLOCK with getrandom.
The json-c library is used in cryptsetup for LUKS2 header information.
Since cryptsetup can be called very early during boot, the developers
avoid getrandom() calls in their own code base for now. [1]

Introducing a blocking getrandom() call in json-c therefore introduces
this issue for cryptsetup as well. Even though cryptsetup issues do not
have to be json-c issues, here is my proposal:

Let's use a non-blocking call, falling back to other sources if the call
would block. Since getrandom() accesses urandom, it must mean that we
are in an early boot phase -- otherwise the call would not block
according to its manual page.

As stated in manual page of random(4), accessing /dev/urandom won't
block but return weak random numbers, therefore this fallback would work
for json-c.

While at it, fixed the debug message.

[1] https://gitlab.com/cryptsetup/cryptsetup/-/merge_requests/47
    which references to https://lwn.net/Articles/800509/
2020-08-15 15:52:17 +02:00
Eric Hawicz
104b408ee8 Merge pull request #656 from pogaram/fix-warnings
Fixed warnings
2020-08-14 16:57:32 -04:00
Aram Poghosyan
0ffb384409 Fixed warnings 2020-08-14 11:45:33 +04:00
Eric Hawicz
98b7ee93fd Merge pull request #655 from MarcT512/issue654
json_parse: Fix read past end of buffer
2020-08-07 10:18:30 -04:00
Marc
4e9e44e525 Fix read past end of buffer
Resolves https://github.com/json-c/json-c/issues/654
2020-08-07 10:49:45 +01:00
Eric Haszlakiewicz
8c7849e6e3 Eliminate use of ctype.h and replace isdigit() and tolower() with non-locale-sensitive approaches. 2020-08-02 04:06:44 +00:00
Eric Haszlakiewicz
f3d8006d34 Neither vertical tab nor formfeed are considered whitespace per the JSON spec, remove them from is_ws_char(). 2020-08-02 03:59:56 +00:00
Eric Haszlakiewicz
8b43ff0c22 Merge the is_ws_char() and is_hex_char() changes to json_tokener from branch 'ramiropolla/for_upstream' (PR #464) 2020-08-02 02:55:45 +00:00
Eric Haszlakiewicz
bfec9c8685 Take a hint from PR #464 and use json_object_new_string_len() to avoid a needless extra strlen() call.
Also, create a _json_object_get_string_len() for internal use when we know
for sure the object we're dealing with is a json_type_string.
2020-08-02 02:23:01 +00:00
Eric Hawicz
56a89f902f Merge pull request #653 from lamby/966657-json-c-please-make-the-build-reproducible
Make the documentation build reproducibly
2020-08-01 22:06:38 -04:00
Chris Lamb
46eea84554 Make the documentation build reproducibly
Whilst working on the Reproducible Builds effort [0] I noticed that
json-c could not be built reproducibly.

This is because it used the full, absolute path name as an (sanitised)
input to a filename, resulting in some binary package containing, for
example:

  /usr/share/doc/libjson-c-dev/html/md__build_1st_json-c-0_815_issues_closed_for_0_813.html
                                        ^^^^^^^^^^^^^^^^^^^^^^
or

  /usr/share/doc/libjson-c-dev/html/md__build_2_json-c-0_815_2nd_issues_closed_for_0_813.html
                                        ^^^^^^^^^^^^^^^^^^^^^^^^

These differing values are based on the path in which json-c is built. This was
originally filed in Debian as #966657 [1].

 [0] https://reproducible-builds.org/
 [1] https://bugs.debian.org/966657
2020-08-01 11:26:55 +01:00
Eric Hawicz
88cce7b9c5 Merge pull request #651 from alanc/getrandom
Getrandom
2020-07-31 20:30:11 -04:00
Alan Coopersmith
6cf4847796 Use getrandom() if available in json_c_get_random_seed
Lower overhead than opening & reading from /dev/urandom, and works
in chroots and other situtations where /dev/urandom is not available.
Falls back to existing methods when kernel doesn't support the syscall.
2020-07-31 08:28:07 -07:00
Eric Haszlakiewicz
002411293d Issue #649: Drop the generated doc/Doxyfile when creating a release. 2020-07-28 03:52:22 +00:00
Eric Hawicz
66f8ca3c03 Merge pull request #650 from sartura/readme-update
README: fix spelling errors
2020-07-27 10:31:05 -04:00
Jakov Smolic
55bf2d365d README: fix spelling errors
Signed-off-by: Jakov Smolic <jakov.smolic@sartura.hr>
2020-07-27 15:05:55 +02:00
Eric Haszlakiewicz
47189b5ff1 Include updating the json-c-current-releaes gh-pages symlink as part of the release process. 2020-07-26 15:51:07 +00:00
Eric Haszlakiewicz
de02d09c32 Update the master branch to version 0.15.99 2020-07-26 15:26:53 +00:00
Eric Haszlakiewicz
870965e1ea Update AUTHORS, add issues_closed_for_0.15.md, tweak the release checklist slightly. 2020-07-24 03:17:13 +00:00
Eric Hawicz
616b1050b2 Merge pull request #648 from MarcT512/rbf
Fix "may be used uninitialized" Release build failure
2020-07-23 22:26:58 -04:00
Marc
4a23d3413d Fix "may be used uninitialized" Release build failure
Fixes https://github.com/json-c/json-c/issues/647
2020-07-23 18:19:12 +01:00
Eric Haszlakiewicz
730e3d044f Issue #594 - provide an OVERRIDE_GET_RANDOM_SEED cmake variable to override json_c_get_random_seed() for embedded platforms where time(NULL) doesn't work.
Example:
mkdir build && cd build
cmake -DOVERRIDE_GET_RANDOM_SEED='do { extern uint32_t getMsTicks(void); int ms = getMsTicks() * 433494437; return ms; } while(0)' ..
2020-07-22 02:25:03 +00:00
Eric Hawicz
64de4b6e9f Merge pull request #646 from pascal-cuoq/fix_645
Cast to unsigned char instead of int when calling tolower (Fixes #645)
2020-07-21 21:24:59 -04:00
Pascal Cuoq
1962ba7de3 Fixes #645 2020-07-21 17:54:26 +02:00
Eric Haszlakiewicz
024e835f4c Update the ChangeLog with recent changes, in preparation for a 0.15 release. 2020-07-20 03:39:01 +00:00
Eric Haszlakiewicz
78a0f2ea5d Remove the obsolete config.h.win32 2020-07-17 03:47:28 +00:00
Eric Haszlakiewicz
e46b9cdb7d Fix a number of things with the generated docs, including translating triple-backtick code blocks into a form doxygen understands. 2020-07-17 03:46:21 +00:00
Eric Haszlakiewicz
9a7de35b92 Add some more detail about how to use json-c in README.md. 2020-07-17 03:42:38 +00:00
Eric Haszlakiewicz
cb10a13e94 Remove the THIS_FUNCTION_IS_DEPRECATED define, we stopped using it long ago. 2020-07-17 03:20:29 +00:00
Eric Haszlakiewicz
2508109b18 Remove the obsolete README.json_object-split.md, and mark README.md as being the doxygen mainpage. 2020-07-12 19:16:19 +00:00
Eric Haszlakiewicz
4d9f6dd22e Issue #642: improve the docs for json_object_put() and json_object_get(). 2020-07-12 18:43:27 +00:00
Eric Haszlakiewicz
2330c6f0de Expand the doc for json_object_array_get_idx() to explain that it does not adjust refcounts. 2020-07-12 17:55:46 +00:00
Eric Haszlakiewicz
6542d33cd1 Issue #641: Add a cast to void * to address some theoretically undefined printf behavior. 2020-07-11 15:03:00 +00:00
Eric Haszlakiewicz
10a9ac245e Issue #642: improve docs for json_tokener.h and json_object_object_add(). 2020-07-11 04:04:58 +00:00
Eric Haszlakiewicz
6fa8b7ff42 Don't export json-c symbols starting with an underscore, put deprecated exports into a "JSONC_PRIVATE" version, and note stuff to do during releases.
See also PR #639 and issue #621
2020-07-04 19:00:10 +00:00
Eric Haszlakiewicz
6068d3f6d1 Change the strerror_override handling to check $_JSON_C_STRERROR_OVERRIDE instead of using a variable, so we don't need to export it. 2020-07-04 18:58:00 +00:00
Eric Hawicz
b01d50b8dc Merge pull request #639 from smcv/symbol-versions
build: Add a symbol version to all exported symbols
2020-07-04 14:26:20 -04:00
Simon McVittie
c2c94024f5 build: Add symbol versions to all exported symbols
With this version script, newly-linked binaries that depend on the
json-c shared library will refer to its symbols in a versioned form,
preventing their references from being resolved to a symbol of the same
name exported by json-glib or libjansson if those libraries appear in
dependency search order before json-c, which will usually result in
a crash. This is necessary because ELF symbol resolution normally uses
a single flat namespace, not a tree like Windows symbol resolution.
At least one symbol (json_object_iter_next()) is exported by all three
JSON libraries.

Linking with -Bsymbolic is not enough to have this effect in all cases,
because -Bsymbolic only affects symbol lookup within a shared object,
for example when json_object_set_serializer() calls
json_object_set_userdata(). It does not affect calls from external
code into json-c, unless json-c was statically linked into the
external caller.

This change will also not prevent code that depends on json-glib or
libjansson from finding json-c's symbols and crashing; to prevent
that, a corresponding change in json-glib or libjansson would be needed.

Adding a symbol-version is a backwards-compatible change, but once
added, removing or changing the symbol-version on a symbol would be an
incompatible change that requires a SONAME bump.

Resolves: https://github.com/json-c/json-c/issues/621
(when combined with an equivalent change to libjansson).

Signed-off-by: Simon McVittie <smcv@collabora.com>
2020-07-01 18:24:26 +01:00
Eric Haszlakiewicz
6465e74020 Use constants referring to the signed integer types when setting SSIZE_T_MAX.
In practice, the sizes of the signed and unsigned integer types will
almost cetainly be the same, but this is more correct.
Pointed out in issue #638.
2020-07-01 00:34:46 +00:00
Eric Haszlakiewicz
34334e5d3f Replace one call to json_object_new_array() with json_object_new_array_ext() to ensure it at least minimally works. 2020-06-29 02:35:26 +00:00
Eric Haszlakiewicz
0b67caec1a Add doc comment for json_object_new_array_ext(). 2020-06-29 02:31:32 +00:00
Eric Haszlakiewicz
a4e3700972 Fix code formatting 2020-06-29 02:31:18 +00:00
Eric Haszlakiewicz
5f3bf70f03 Make sure TEST_PARSE_CHUNKSIZE is valid if it's set. 2020-06-29 02:18:34 +00:00
Eric Haszlakiewicz
f23486a321 In the json_tokener_state_number case, explicitly adjust what "number" characters are allowed based on the exact micro-state that we're in, and check for invalid following characters in a different way, to allow a valid json_type_number object to be returned at the top level.
This causes previously failing strings like "123-456" to return a valid json_object with the appropriate value.  If you care about the trailing content, call json_tokener_parse_ex() and check the parse end point with json_tokener_get_parse_end().
2020-06-29 02:14:26 +00:00
Eric Haszlakiewicz
6eac6986c9 Fix incremental parsing of invalid numbers with exponents, such as "0e+-" and "12.3E12E12", while still allowing "0e+" in non-strict mode.
Deprecate the json_parse_double() function from json_util.h
2020-06-27 15:35:04 +00:00
Eric Haszlakiewicz
84e6032883 Issue #635: Fix "expression has no effect" warning in json_tokener.c by casting to void. 2020-06-23 02:51:46 +00:00
Eric Haszlakiewicz
7a72805e34 Fix memory leak in test_parse's single_incremental_parse(). 2020-06-22 01:12:03 +00:00
Eric Haszlakiewicz
7d3c2d9fad Drop extra blank lines from arraylist.h 2020-06-21 18:30:40 +00:00
Eric Haszlakiewicz
a68566bf6a Issue #616: Change the parsing of surrogate pairs in unicode escapes so it uses a couple of additional states instead of assuming the low surrogate is already present, to ensure that we correctly handle various cases of incremental parsing. 2020-06-21 18:29:57 +00:00
Eric Haszlakiewicz
197e372464 In test_parse, fix lengths passed during a couple of incremental tests.
Add an optional way to use an incremental chunk size ($TEST_PARSE_CHUNKSIZE)
for all of the single_basic_parse tests, in additional to the regular way.
2020-06-21 17:36:38 +00:00
Eric Haszlakiewicz
36118b681e Rearrange the json_tokener_state_escape_unicode case in json_tokener to simplify the code slightly and make it a bit easier to understand.
While here, drop the utf8_replacement_char that is unnecesarily added if we run out of input in the middle of a unicode escape.  No other functional changes (yet).
2020-06-21 03:10:55 +00:00
Eric Haszlakiewicz
50179fb09f Update the json_tokener_parse_ex() docs to clarify that the final '\0' character is to be included in length passed in. 2020-06-21 02:35:42 +00:00
Eric Hawicz
da76ee26e7 Merge pull request #633 from dota17/issue616
fix issue 616: support the surrogate pair in split file.
2020-06-20 22:33:17 -04:00
Eric Haszlakiewicz
e26a1195f4 Add json_object_array_shrink() (and array_list_shrink()) and use it in json_tokener to minimize the amount of memory used. This results in a 39%-50% reduction in memory use (peak RSS, peak heap usage) on the jc-bench benchmark and 9% shorter runtime.
Also add the json_object_new_array_ext, array_list_new2, and array_list_shrink functions.
2020-06-20 18:03:04 +00:00
Eric Hawicz
99bb2121c6 Merge pull request #632 from json-c/json_object-split
Json object split
2020-06-20 13:04:32 -04:00
Eric Haszlakiewicz
0710c835a1 Reformat the json_object-split branch with clang-format 2020-06-16 13:17:58 +00:00
Eric Hawicz
401b29c021 Merge pull request #634 from micahsnyder/json-c-fPIC
Issue #508: `-fPIC` to link libjson-c.a with libs
2020-06-14 17:56:35 -04:00
Micah Snyder
60494684a1 Issue #508: -fPIC to link libjson-c.a with libs
json-c has symbol collisions with other popular C JSON libraries.
To prevent random crashes in downstream applications that may use a
library which depends on json-c, the solution is to statically link
libjson-c.a into those libraries.

`-fPIC`/`-fPIE` is required when building a `.a` so it can be linked
into a `.so`.
2020-06-14 12:35:49 -04:00
Eric Haszlakiewicz
9128ec49b1 Include unistd.h to fix the build on OSX 2020-06-14 03:11:44 +00:00
Eric Haszlakiewicz
5ebfeaedc5 Drop the _delete field from struct json_object and call the type-specific delete functions directly from json_object_put. (Thanks @dota17 for the suggestion in PR #632!) 2020-06-13 18:34:35 +00:00
Eric Haszlakiewicz
4c10712114 Drop the useless "char data[1]" from struct json_object. Fix a typo in a comment. 2020-06-13 18:25:32 +00:00
dota17
c1b872d817 fix issue 616: support the surrogate pair in split file. 2020-06-08 17:19:32 +08:00
Eric Haszlakiewicz
85c244f048 Eliminate unnecessary cast that was added to test_double_serializer. 2020-06-07 18:50:10 +00:00
Eric Haszlakiewicz
02fe2e0ccd Summarize the changes from the json_object-split branch in the ChangeLog. 2020-06-07 18:45:17 +00:00
Eric Haszlakiewicz
ecdfeb18cf Move the ssize_t typedef from json_inttypes.h to json_object_private.h so as not to affect publically exposed symbols. 2020-06-07 18:29:56 +00:00
Eric Haszlakiewicz
66d91fdf86 The split of json_object into type-specific sub-structures is now functionally complete.
Remove all of the temporary defines, structures, old compat fuctions, extra fields, etc... that were needed during the conversion to a split set of json_object_* structures.
2020-06-07 17:23:56 +00:00
Eric Haszlakiewicz
c4cc673071 More fixes for old MSVC builds. 2020-06-07 15:25:59 +00:00
Eric Haszlakiewicz
0a16b23adf Fix typo in previous commit to check for SSIZE_T on MSVC. 2020-06-07 15:19:29 +00:00
Eric Haszlakiewicz
eab1375123 Change CMakeLists.txt to look for SSIZE_T on MSVC too. 2020-06-07 03:36:59 +00:00
Eric Haszlakiewicz
b0466b626b On MSVC, add a ssize_t typedef using SSIZE_T from BaseTsd.h 2020-06-07 03:27:13 +00:00
Eric Haszlakiewicz
0fc9d91277 Kick json_type_string out of struct json_object.
The default is now that string data is stored inline at the end of json_object, though to allow for json_object_set_string() to set a _longer_ string, we still need to allow for the possibility of a separate char * pointer.
All json types have been split out now, next step it cleanup.
2020-06-07 02:56:59 +00:00
Eric Hawicz
bc06f82f85 Merge pull request #628 from clamwin/compat-fixes-master
get_cryptgenrandom_seed: compat with old windows + fallback
2020-06-03 23:53:46 -04:00
Gianluigi Tiesi
481d0a8ede get_cryptgenrandom_seed: compat with old windows + fallback 2020-06-03 07:51:42 +02:00
Eric Haszlakiewicz
1c6086a86a Apply the fix from @pointbre in issue #626 to skip "inline" on AIX, but invert the test to make it a little easier to understand. 2020-05-31 03:22:14 +00:00
Eric Haszlakiewicz
fe308b8862 Issue #626: Restore compatibility with cmake 2.8 by adjusting quoting and explicitly defining the PROJECT_VERSION* variables. 2020-05-30 19:37:46 +00:00
Eric Haszlakiewicz
9ecb1222bd Kick json_type_int and json_type_double out of struct json_object.
Clean up the code in json_object_new_* a bit by dropping unnecesary json_object_base variables.
2020-05-26 02:31:35 +00:00
Eric Haszlakiewicz
0351bb55c8 Declare variables earlier, to appease Visual Studio 2010. 2020-05-25 04:10:11 +00:00
Eric Haszlakiewicz
d1f83bf5ea Kick json_type_boolean out of struct json_object. 2020-05-25 04:05:32 +00:00
Eric Haszlakiewicz
5d89fc8a9d Add some backwards compat for Visual Studio 2013. 2020-05-25 03:52:36 +00:00
Eric Haszlakiewicz
02b687b9a6 Kick json_type_array out of struct json_object; re-enable the test_deep_copy test. 2020-05-25 03:44:56 +00:00
Eric Haszlakiewicz
853b4b5dee Start splitting struct json_object into multiple sub-types, as descibed at https://github.com/json-c/json-c/wiki/Proposal:-struct-json_object-split
The current changes split out _only_ json_type_object, and thus have a number of hacks
 to allow the code to continue to build and work.

Originally  mentioned in issue #535.
When complete, this will probably invalidate #552.
This is likely to cause notable conflicts in any other significant un-merged
changes, such as PR#620.
2020-05-25 03:18:36 +00:00
Eric Haszlakiewicz
4a546e7b2f In arraylist, use malloc instead of calloc, avoid clearing with memeset until we really need to, and micro-optimize array_list_add(). 2020-05-24 03:54:04 +00:00
Eric Hawicz
fbe1543644 Merge pull request #622 from besser82/topic/besser82/doc_subdir
doc: Move Doxyfile into doc subdir.
2020-05-18 15:30:21 -04:00
Björn Esser
1e94da779a CMake: Fix grammar: written -> wrote. 2020-05-18 20:36:16 +02:00
Björn Esser
61e2bae511 doc: Move Doxyfile into doc subdir 2020-05-18 20:36:16 +02:00
Eric Haszlakiewicz
fa6a7dccb9 With the change in cc80203, Doxyfile no longer needs to be updated for a release. 2020-05-18 17:31:22 +00:00
Eric Hawicz
cc802039a8 Merge pull request #619 from besser82/topic/besser82/doxygen_oot
CMake: Fix out-of-tree build for Doxygen documentation.
2020-05-18 13:30:13 -04:00
Eric Hawicz
12b2e1159d Merge pull request #618 from besser82/topic/besser82/test_deep_copy
test_deep_copy: Fix assertion value.
2020-05-18 13:29:21 -04:00
Björn Esser
8f3592b3d5 CMake: Fix out-of-tree build for Doxygen documentation. 2020-05-18 18:20:33 +02:00
Björn Esser
3008401b2a test_deep_copy: Fix assertion value. 2020-05-18 17:06:37 +02:00
Eric Hawicz
a8a0590921 Merge pull request #617 from besser82/topic/besser82/option_disable_tls
Add an option to disable the use of thread-local storage.
2020-05-18 10:25:54 -04:00
Björn Esser
a85d2395ff README: Update configuration options for CMake. 2020-05-18 12:41:18 +02:00
Björn Esser
76dd99abb2 CMake: Re-format config-option block and re-order it alphabetically. 2020-05-18 12:34:08 +02:00
Björn Esser
78642dcb9b CMake: Add an option to disable the use of thread-local storage.
Using thread-local storage may not be desired in all environments
and/or use-cases, thus there should be an option to disable its use
on purpose.

Fixes #451.
2020-05-18 12:27:19 +02:00
Björn Esser
dd040ba446 tests: Fix test_double_serializer without thread-local storage. 2020-05-18 12:27:00 +02:00
Eric Hawicz
5b15c7567d Merge pull request #614 from stoeckmann/format
Prevent truncation on custom double formatters.
2020-05-16 21:04:11 -04:00
Eric Hawicz
311c5e5b2b Update issue templates 2020-05-16 20:55:20 -04:00
Tobias Stoeckmann
5385a566db Prevent truncation on custom double formatters.
A custom double formatter can lead to truncation of the rest of the
JSON document.

If a custom formatter completely fills the buffer used by snprintf
with a trailing dot or comma and the formatting option
JSON_C_TO_STRING_NOZERO has been specified, then an iterator moves
past the ending '\0' (off-by-one buffer overflow) to set an
additional '\0' and adds the first '\0' into the printbuf.

Since '\0' will eventually be considered the terminating character
of the complete printbuf result, all trailing characters are lost.

This leads to an incomplete JSON string as can be seen with the
test case.

The off-by-one can be noticed if compiled with address sanitizer.

Since this is a very special case and a malformed formatter could
do way more harm and is the responsibility of the user of this
library, this is just a protective measure to keep json-c code as
robust as possible.
2020-05-16 15:26:16 +02:00
Eric Haszlakiewicz
0a3d22b9bb Revert part of PR#606 and use isnan/isinf again, but provide macro implementations of those in math_compat.h is needed, as it seems to be on AIX and IBM i systems. 2020-05-16 01:29:18 +00:00
Eric Hawicz
1526c84a13 Merge pull request #606 from davidjmccann/master
Improved support for IBM operating systems
2020-05-15 21:15:18 -04:00
David McCann
add7b13a9a Improved support for IBM operating systems
Fix compiler errors and warnings when building on IBM operating systems such as AIX and IBM i.
2020-05-14 15:39:35 +01:00
Eric Haszlakiewicz
d414d3eabc Issue #604: add check for __MINGW32__ in snprintf_compat.h 2020-05-13 14:53:05 +00:00
Eric Haszlakiewicz
2e71fe0963 Display a bit of info about what exactly we're benchmarking. 2020-05-11 03:05:20 +00:00
Eric Haszlakiewicz
199c52e2db Ignore the bench/work and bench/data directories. 2020-05-11 03:04:10 +00:00
Eric Hawicz
3648c3ed2c Merge pull request #602 from ploxiln/parse_uint64_errno
fix json_parse_uint64() usage of errno
2020-05-10 21:15:47 -04:00
Pierce Lopez
003b58782b fix json_parse_uint64() usage of errno
introduced in #542
fixes #601
2020-05-10 13:38:12 -04:00
Eric Haszlakiewicz
26f080997d Fix snprintf on windows problem for test4. 2020-05-10 04:04:28 +00:00
Eric Haszlakiewicz
06742d6277 Issue #600: don't rename the static library on Windows, it _needs_ to have a different name because the dll build also creates a "json-c.lib" file. 2020-05-10 03:58:51 +00:00
Eric Haszlakiewicz
a59d5acfab Re-format after recent change to fix linkhash. 2020-05-10 03:58:27 +00:00
Eric Haszlakiewicz
4f43a077a4 Issue #598: avoid building static libraries twice. 2020-05-10 03:48:45 +00:00
Eric Haszlakiewicz
519dfe1591 Issue #599: Fix the backwards check in lh_table_insert_w_hash() that was preventing adding more than 11 objects.
Add a test to check for this too.
2020-05-10 03:36:05 +00:00
Eric Hawicz
45b6416652 Merge branch 'master' of https://github.com/json-c/json-c 2020-05-08 22:25:15 -04:00
Eric Hawicz
abc9a0731b Merge pull request #597 from ploxiln/json_parse_usage
json_parse demo: fix and use usage() function
2020-05-08 22:23:28 -04:00
Pierce Lopez
090ae4e4d4 json_parse demo: fix and use usage() function 2020-05-08 18:27:35 -04:00
Eric Hawicz
22870ac2bd Merge pull request #595 from dota17/static_shared
Support to build both static and shared libraries
2020-05-07 23:23:15 -04:00
hofnarr
a100573eec cmake-configure: fix enable-static option 2020-05-08 02:27:06 +03:00
hofnarr
558ef8609c cmake: change variable name 2020-05-08 02:19:38 +03:00
hofnarr
929d74512a cmake: add list for build targets 2020-05-08 02:16:52 +03:00
dota17
e97fc20bfd update 2020-05-07 14:50:43 +08:00
Eric Hawicz
31243e4d12 Merge pull request #592 from stoeckmann/oob
Prevent out of boundary write on malicious input
2020-05-06 23:31:15 -04:00
Tobias Stoeckmann
d07b910149 Fix integer overflows.
The data structures linkhash and printbuf are limited to 2 GB in size
due to a signed integer being used to track their current size.

If too much data is added, then size variable can overflow, which is
an undefined behaviour in C programming language.

Assuming that a signed int overflow just leads to a negative value,
like it happens on many sytems (Linux i686/amd64 with gcc), then
printbuf is vulnerable to an out of boundary write on 64 bit systems.
2020-05-06 20:46:12 +02:00
dota17
952db0f397 support to build both static and shared libraries 2020-05-06 14:46:47 +08:00
Tobias Stoeckmann
77d935b7ae Prevent division by zero in linkhash.
If a linkhash with a size of zero is created, then modulo operations
are prone to division by zero operations.

Purely protective measure against bad usage.
2020-05-04 19:46:45 +02:00
Tobias Stoeckmann
099016b7e8 Protect array_list_del_idx against size_t overflow.
If the assignment of stop overflows due to idx and count being
larger than SIZE_T_MAX in sum, out of boundary access could happen.

It takes invalid usage of this function for this to happen, but
I decided to add this check so array_list_del_idx is as safe against
bad usage as the other arraylist functions.
2020-05-04 19:41:16 +02:00
Eric Haszlakiewicz
8e3d3d5544 Make the benchmark work with pre-cmake versions of json-c. Fetch a few more data files. 2020-05-04 03:40:40 +00:00
Eric Haszlakiewicz
c66e7377f3 In jc-bench.sh, decode the --before and --after args. Use a separate data dir to avoid re-downloading files when the work dir is cleared. 2020-05-04 03:24:39 +00:00
Eric Haszlakiewicz
8086314026 Issue #589: drop the rdrand test loops to just 3, tweak comments and add some links to bug reports, and decrease the nesting level of the has_rdrand() function. 2020-05-04 01:33:15 +00:00
Eric Hawicz
a555d0e2f2 Merge pull request #589 from Xyene/detect-broken-rdrand
Detect broken RDRAND during initialization
2020-05-03 21:13:48 -04:00
Tudor Brindus
4d36b0287d Detect broken RDRAND during initialization
Some CPUs advertise RDRAND in CPUID, but return 0xFFFFFFFF
unconditionally. To avoid locking up later, test RDRAND during
initialization, and if it returns 0xFFFFFFFF, mark it as nonexistent.

Fixes #588.
2020-05-03 15:15:24 -04:00
Eric Hawicz
9b64c3e347 Fix printf format issues in apps/json_parse, and actually call the usage() function. 2020-05-03 14:55:12 -04:00
Eric Hawicz
ee90110f9b Merge pull request #590 from Xyene/fix-cpuid-segfault
Fix segmentation fault in CPUID check
2020-05-03 14:52:31 -04:00
Tudor Brindus
0e5bbcaa16 Fix segmentation fault in CPUID check 2020-05-03 14:39:31 -04:00
Eric Haszlakiewicz
f9605e9072 Fix cmake-configure to accept "--prefix=<foo>" in addition to "--prefix <foo>" (see also Issue #591) 2020-05-03 03:50:50 +00:00
Eric Haszlakiewicz
1059007024 Add an initial version of a benchmarking harness for json-c, to be able to more easily compare the performance of different library versions. 2020-04-27 04:00:00 +00:00
Eric Haszlakiewicz
d9981f67dd Extend the CMakeLists.txt in the apps directory to be usable as a standalone build, to link against other versions of json-c.
Tweak json_parse.c slightly to allow it to build against older json-c versions.
2020-04-26 04:02:36 +00:00
Eric Haszlakiewicz
00272292a7 The json_parse command line app doesn't build on Windows, disable it. 2020-04-21 21:35:41 +00:00
Eric Haszlakiewicz
55d053118e Add an apps directory, and a json_parse program to parse an input file and report on memory usage.
This is intended to provide a way, during development, to test out the memory
and performance impacts of a change.
2020-04-21 03:57:56 +00:00
Eric Haszlakiewicz
f6f76f9430 Add a JSON_TOKENER_ALLOW_TRAILING_CHARS flag for json_tokener_set_flags() to allow multiple objects to be parsed from input even when JSON_TOKENER_STRICT is set. 2020-04-21 03:53:44 +00:00
Eric Haszlakiewicz
05623b3a2e Add an tok_flags field to explicitly specify tokener flags in test_parse and eliminate the previous bogus calls to json_tokener_set_flags() 2020-04-21 03:53:44 +00:00
Eric Haszlakiewicz
fa6bc1e2d7 Issue #471: always create directories with mode 0755, regardless of umask. 2020-04-21 03:19:17 +00:00
Eric Haszlakiewicz
8b511c402b Issue #585: don't install config.h 2020-04-21 01:13:21 +00:00
Eric Haszlakiewicz
ba4527904a Add a few missing git commands to the release checklist, and change the S3 storage to "Standard", since it's actually (barely) cheaper than "Reduced Redundancy" now. 2020-04-19 04:17:29 +00:00
Eric Haszlakiewicz
2babb5b780 Update the master branch to version 0.0.14.99 2020-04-19 03:57:08 +00:00
Eric Haszlakiewicz
31ab57ca8b Fill in the ChangeLog for the upcoming 0.14 release. 2020-04-19 01:31:48 +00:00
Eric Haszlakiewicz
9ed00a694b Fill in a few more pre-release steps to match what we've done for the 0.14 release.
Move the list of contributors to the AUTHORS file.
2020-04-19 01:28:24 +00:00
Eric Haszlakiewicz
4badbe9c20 Rewrite the issued_closed_for_* files so they display a bit nicer. 2020-04-18 03:22:52 +00:00
Eric Haszlakiewicz
0a95f98b8d Explicitly mark several things in json_tokener deprecated. 2020-04-18 02:42:46 +00:00
Eric Haszlakiewicz
ecb9354bb1 Re-do clang-format. 2020-04-18 02:14:13 +00:00
Eric Haszlakiewicz
23ddcbd4da Make json_abort() internal to json_object.c 2020-04-18 02:05:37 +00:00
Eric Haszlakiewicz
5cc11289b4 Make json_tokener_validate_utf8() internal to json_tokener.c, and improve the docs a bit. 2020-04-18 02:02:06 +00:00
Eric Haszlakiewicz
4dc0f1718e Merge pull request #582 from dota17/list_closed_issue_pr
add the list of issues& prs closed
2020-04-17 13:32:17 -04:00
dota17
4313465f25 update 2020-04-17 09:47:30 +08:00
dota17
8bdb420d0f manual adjustment 2020-04-16 16:30:14 +08:00
dota17
6bf6a9e248 add the list of issues& prs closed 2020-04-16 16:15:04 +08:00
Eric Haszlakiewicz
a9114392b4 Merge pull request #524 from dota17/addTestCase_obj_token
Increase coverage
2020-04-15 23:35:21 -04:00
Eric Haszlakiewicz
04bb0fca73 Merge pull request #581 from Jehan/wip/Jehan/no-strict-prototypes-windows
CMakeLists: do not enforce strict prototypes on Windows.
2020-04-15 23:32:59 -04:00
dota17
b14363ae32 remove unsuitable case 2020-04-15 20:06:12 +08:00
Jehan
8c33d1c3c9 CMakeLists: do not enforce strict prototypes on Windows.
On Windows, or at least when cross-built with Mingw-w64, build fails
because strict prototype fails on an included file (thus nothing we can
do about in json-c code):

> from /home/jehan/dev/src/json-c/json_util.c:44:
> /home/jehan/.local/share/crossroad/roads/w64/json-c/include/minwindef.h:196:3: error: function declaration isn't a prototype [-Werror=strict-prototypes]
>   196 |   typedef INT_PTR (WINAPI *FARPROC) ();
>       |   ^~~~~~~
> /home/jehan/.local/share/crossroad/roads/w64/json-c/include/minwindef.h:197:3: error: function declaration isn't a prototype [-Werror=strict-prototypes]
>   197 |   typedef INT_PTR (WINAPI *NEARPROC) ();
>       |   ^~~~~~~
> /home/jehan/.local/share/crossroad/roads/w64/json-c/include/minwindef.h:198:3: error: function declaration isn't a prototype [-Werror=strict-prototypes]
>   198 |   typedef INT_PTR (WINAPI *PROC) ();
>       |   ^~~~~~~

Let's just disable the errors for Windows build.
2020-04-15 13:03:11 +02:00
Eric Haszlakiewicz
7fb8d56458 Merge pull request #580 from besser82/topic/besser82/fix_cmake_tests
Fix CMake tests for enforced strict prototypes.
2020-04-14 15:17:21 -04:00
Björn Esser
053eaa61d7 Fix CMake tests for enforced strict prototypes. 2020-04-14 20:42:32 +02:00
Eric Haszlakiewicz
ab5425a6a6 Merge pull request #527 from dota17/arraylist_test
Arraylist testcase
2020-04-14 10:28:16 -04:00
Eric Haszlakiewicz
511edb51a4 Merge pull request #579 from besser82/topic/besser82/strict-prototypes
Enforce strict prototypes.
2020-04-14 10:25:13 -04:00
dota17
2876fcc137 clang-format two test_util_file.c and test_object_iterator.c 2020-04-14 10:15:27 +08:00
chenguoping
8096125618 Increased the test coverage of json_util.c from 76% to 90.3%. 2020-04-14 10:10:47 +08:00
chenguoping
f56c5c1a60 Increased the test coverage of json_object_iterator.c from 0% to 100% 2020-04-14 10:03:58 +08:00
dota17
74bbe349c4 clang-format test1.c 2020-04-14 09:20:51 +08:00
chenguoping
110c60fcdd fix valgrind errors 2020-04-14 09:13:29 +08:00
chenguoping
76e1472808 testcase for array_list 2020-04-14 09:13:06 +08:00
Björn Esser
d0dc3489dc Enforce strict prototypes. 2020-04-13 11:29:52 +02:00
Eric Haszlakiewicz
4742a2ab1d Merge pull request #578 from besser82/topic/besser82/pkgconfig_install
CMake: Install pkgconfig file in proper location by default
2020-04-12 20:52:01 -04:00
Björn Esser
165e6f58fc CMake: Install pkgconfig file in proper location by default
The default location for pkconfig files on most systems is:
  ${CMAKE_INSTALL_LIBDIR}/pkgconfig

Thus the file should get installed in there by default.
2020-04-12 19:21:54 +02:00
Eric Haszlakiewicz
8269f90956 Merge pull request #577 from besser82/topic/besser82/json_c_version_test_verbose_on_fail
Be verbose on failing json_c_version test.
2020-04-11 22:35:40 -04:00
Björn Esser
5e699f7f73 Be verbose on failing json_c_version test. 2020-04-11 21:09:31 +02:00
Eric Haszlakiewicz
c58d56ab7c Merge pull request #576 from besser82/topic/besser82/increase_coverage
Test coverage for json_c_version.
2020-04-11 14:45:45 -04:00
Eric Haszlakiewicz
d52f1ff2c1 Merge pull request #575 from besser82/topic/besser82/cosmetics
Small cosmetics.
2020-04-11 14:18:37 -04:00
Björn Esser
d47fb12e85 Test coverage for json_c_version. 2020-04-11 12:33:59 +02:00
Björn Esser
73a2ed115a Remove multiple trailing newlines at EOF. 2020-04-11 10:35:42 +02:00
Björn Esser
fd0ae5aba6 gitignore: Add build folder. 2020-04-11 09:41:04 +02:00
Björn Esser
78cd37fb18 Clean trailing white-space. 2020-04-11 09:41:04 +02:00
Björn Esser
37355cf0e6 Fix line terminators to be UNIX. 2020-04-11 09:40:57 +02:00
Eric Haszlakiewicz
270dc2f999 Update README.md to remove autoconf instructions in favor of cmake. 2020-04-11 03:24:51 +00:00
Eric Haszlakiewicz
0734c5303d Merge pull request #572 from besser82/topic/besser82/cmake_fixes
Small fixes to CMakeLists
2020-04-10 22:08:27 -04:00
Chen
69ceb38f2f Merge pull request #573 from besser82/topic/besser82/coverage
Fix coveralls submission.
2020-04-11 09:31:43 +08:00
Björn Esser
0dac15c1ca Fix coveralls submission.
coveralls-cpp is dead and does not work anymore.
Fortunately there is coveralls-lcov available.
2020-04-10 18:07:38 +02:00
Björn Esser
e756777c92 CMake: Check whether BSYMBOLIC is supported by the linker.
Linking with '-Bsymbolic-functions' is supported for ELF-binaries, only.
2020-04-10 17:29:35 +02:00
Björn Esser
58670ec64e CMake: Build Doxygen documentation out-of-tree. 2020-04-10 14:20:57 +02:00
Björn Esser
a989651bd4 CMake: Fix appending of linker flags.
There was a typo in `CMAKE_SHARED_LINKER_FLAGS`.
2020-04-10 14:16:02 +02:00
Eric Haszlakiewicz
61392c867f List the set of contributors since the 0.13 branch 2020-04-10 02:11:48 +00:00
Eric Haszlakiewicz
0a070ef312 Fix one more assert("!invalid cint_type") to use json_abort(...) instead. 2020-04-10 01:26:04 +00:00
Eric Haszlakiewicz
545464322b Issue #568: fix the strtoll and strtoull handing so config.h ends up creating defines for those only when needed, which should exclude mingw environments. 2020-04-09 20:58:28 +00:00
Eric Haszlakiewicz
b64bdfe381 Remove autoconf files from .gitignore. 2020-04-09 02:55:21 +00:00
Eric Haszlakiewicz
0c60125211 Update the oss-fuzz build script to try to get it to work with cmake. 2020-04-09 02:35:41 +00:00
Eric Haszlakiewicz
95737df9d4 Remove autoconf machinery, we're using cmake now. Update the release checklist to account for that, plus fill in other tasks and clean it up a bit. 2020-04-09 02:15:31 +00:00
Eric Haszlakiewicz
96ab2f6596 osx builds also need -DDISABLE_BSYMBOLIC=ON 2020-04-08 03:04:27 +00:00
Eric Haszlakiewicz
96bb334650 I have NFC why osx fails when "set -e" is in effect, but leave it off and clean up the rest of the debuging code in the travis config. 2020-04-08 02:54:10 +00:00
Eric Haszlakiewicz
f357081b57 Not all systems (e.g. osx) have malloc.h, include stdlib.h instead. 2020-04-08 02:53:48 +00:00
Eric Haszlakiewicz
2782a6b62c Try yet again to fix the osx build, this time do set +e 2020-04-08 02:39:03 +00:00
Eric Haszlakiewicz
a86ae1df9a Another attempt at debugging the travis osx build, this time just ignore errors. 2020-04-08 02:28:02 +00:00
Eric Haszlakiewicz
829e0829dd Wait a while before exiting travis to allow output to flush. 2020-04-08 02:17:14 +00:00
Eric Haszlakiewicz
cf8421c36d Apparently cmake is already installed on travis osx builds. Try another approach to figure out what was failing. 2020-04-08 02:02:25 +00:00
Eric Haszlakiewicz
fb0b653612 Install cmake on osx travis builds. s/make check/make test/ 2020-04-08 01:45:49 +00:00
Eric Haszlakiewicz
a3b82cbc77 Perform the travis build in a subdir, so the distcheck target works. 2020-04-08 01:34:22 +00:00
Eric Haszlakiewicz
677a8ccf44 Switch travis to use cmake instead of autoconf. 2020-04-08 01:21:11 +00:00
Eric Haszlakiewicz
19bbf2c069 Add includes and split off json_types.h to help ensure that headers can be included in any order. 2020-04-06 13:55:27 +00:00
Eric Haszlakiewicz
5e19c26cae Don't let clang-format rearrange Windows includes, since they need to be in a particular order. 2020-04-06 02:47:34 +00:00
Eric Haszlakiewicz
9acc4e9d71 Format random_seed.c with clang-format, with key asm sections excluded. 2020-04-06 01:52:28 +00:00
Eric Haszlakiewicz
9a494081cb Update the style guide to mention that we're using clang-format now. 2020-04-06 01:49:14 +00:00
Eric Haszlakiewicz
31f1ab2be1 Merge pull request #555 from dota17/chang_format_3
Format json-c with clang-format tool
2020-04-03 00:13:34 -04:00
dota17
8b162c4b89 clang-format the files 2020-04-03 11:39:30 +08:00
dota17
c117d8a8a8 add the disabling formatting coments and adjust the partial code manuly 2020-04-03 11:28:04 +08:00
dota17
a8cec740f0 add options 2020-04-03 11:27:25 +08:00
dota17
df7833e9a3 clang-format 2020-04-03 11:27:08 +08:00
Eric Haszlakiewicz
ed54353d84 Merge pull request #563 from robybeen/master
Changed order of calloc args to match stdlib
2020-04-02 22:35:21 -04:00
Robert
5d9b8e0fef Changed order of calloc args to match stdlib (2)
Although it is currently working, it's worth to stick with the stdlib definition to avoid further problems
2020-04-02 19:28:55 +02:00
Robert
56f81811c2 Changed order of calloc args to match stdlib
Although it is currently working, it's worth to stick with the stdlib definition to avoid further problems
2020-04-02 19:23:10 +02:00
Eric Haszlakiewicz
6afcf1606b Merge pull request #562 from dota17/testcase_add
Bugfix and testcases supplements
2020-04-02 11:23:39 -04:00
dota17
3822177473 add test cases 2020-03-31 19:12:45 +08:00
Chen
c2ba379b03 Merge pull request #561 from dota17/add_badge
add the badge in README.md and test the coveralls
2020-03-31 10:54:45 +08:00
dota17
203bacb24d add the badge in README.md and test the coveralls 2020-03-30 17:17:28 +08:00
Chen
d1650a582e Merge pull request #541 from dota17/coveralls_final
add coveralls auto tool to json-c
2020-03-28 10:42:17 +08:00
dota17
541a0b609a modify the coveralls configuration file 2020-03-23 11:38:18 +08:00
Chen
353ef26bda Merge pull request #558 from dota17/doc_message_modify
modify the doc target message
2020-03-20 11:17:20 +08:00
dota17
1204a1fded modify the doc target message 2020-03-19 10:27:27 +08:00
Eric Haszlakiewicz
a06339215e Merge pull request #556 from Jehan/wip/Jehan/fix-broken-mingw-w64
Fixes various Wreturn-type and Wimplicit-fallthrough errors on Mingw-w64
2020-03-16 21:24:14 -05:00
Jehan
b15e7ba470 Fixes various Wreturn-type and Wimplicit-fallthrough errors on Mingw-w64
This is a recent regression since commit
6359b79847 which added various assert(0)
calls (often replacing return-s).
With Ming-W64 compiler, json-c build was failing with various errors of
the sort:

> /home/jehan/dev/src/json-c/json_object.c: In function 'json_object_int_inc':
> /home/jehan/dev/src/json-c/json_object.c:841:1: error: control reaches end of non-void function [-Werror=return-type]
>   841 | }
>       | ^
> In file included from /home/jehan/dev/src/json-c/json_object.c:17:
> /home/jehan/dev/src/json-c/json_object.c: In function 'json_object_get_double':
> /home/jehan/.local/share/crossroad/roads/w64/json-c/include/assert.h:76:4: error: this statement may fall through [-Werror=implicit-fallthrough=]
>    76 |   (_assert(#_Expression,__FILE__,__LINE__),0))
>       |    ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> /home/jehan/dev/src/json-c/json_object.c:1070:7: note: in expansion of macro 'assert'
>  1070 |       assert(0);
>       |       ^~~~~~
> /home/jehan/dev/src/json-c/json_object.c:1072:3: note: here
>  1072 |   case json_type_boolean:
>       |   ^~~~

The problem is that Mingw-w64 does not consider assert() as a noreturn
(even assert(0)), because it has to be compatible by Microsoft
libraries. See the discussion here:
https://sourceforge.net/p/mingw-w64/bugs/306/

Instead let's create a new json_abort() function which is basically just
an abort() function with an optional message, for such cases where
abortion was non-conditional (using assert() and using the assertion
condition as a message here was clearly a misuse of the function). And
mark json_abort() as 'noreturn', as well as 'cold' for optimization
purpose (this is code we expect to never run, unless there is a bug,
that is).

Finally let's use this json_abort() instead of previous misused assert()
calls.
2020-03-16 19:53:28 +01:00
Eric Haszlakiewicz
e94eb90f9f Merge pull request #546 from dota17/make_unistall
Add uninstall target in cmake
2020-03-10 22:12:13 -05:00
dota17
c14c6caa32 delete -r in uninstall 2020-03-11 10:47:04 +08:00
Eric Haszlakiewicz
a8c9284f06 Merge pull request #547 from dota17/assert_test
modify json-c default build type, and fix up the assert() errors in t…
2020-03-03 07:54:21 -06:00
dota17
0030e905b4 modify RELEASE 2020-03-03 14:16:13 +08:00
dota17
e56ab0146f update testcase and delete debug -O0 build 2020-03-02 20:19:35 +08:00
Eric Haszlakiewicz
b3296e778f Follow up the PR#542: improve assert() calls, simplify code in json_object_equal(). 2020-03-02 02:08:49 +00:00
Eric Haszlakiewicz
737aee40c4 Merge pull request #542 from dota17/adduint64_final
add uint64 data to json-c
2020-03-01 08:51:26 -05:00
dota17
2d44f865c3 modify json-c default build type, and fix up the assert() errors in testcase 2020-02-29 15:32:42 +08:00
dota17
6359b79847 update json_object.c and testcase, delete json_object_uint_inc() 2020-02-28 17:51:56 +08:00
dota17
9532f94fa4 modify partial functions and testcase, in order to support automatic conversion for int64/uint64 2020-02-28 09:25:02 +08:00
dota17
1160c8625c Add uninstall target in cmake 2020-02-27 21:02:31 +08:00
dota17
c816de212b modify the json_object, replace c_int64/c_uint64 with struct{union{int64, uint64},...} 2020-02-27 10:26:27 +08:00
Eric Haszlakiewicz
30e00cf757 Merge pull request #545 from dota17/make_doc
add doc target in cmake
2020-02-26 20:56:22 -05:00
dota17
e3b6521baa add doc target on cmake 2020-02-26 18:18:07 +08:00
Eric Haszlakiewicz
5a2b9139f9 Merge pull request #544 from dota17/distcheck
Increase distcheck target in cmake
2020-02-25 21:48:35 -05:00
Eric Haszlakiewicz
a0129c9761 Merge pull request #543 from dota17/readme
Readme
2020-02-25 21:38:18 -05:00
dota17
77d7a99c75 Increase distcheck target in cmake 2020-02-25 19:15:40 +08:00
Chen
0ccb296263 Update README.md 2020-02-25 16:20:41 +08:00
dota17
f69fbd897b Added documentation for camke-configure 2020-02-25 15:01:05 +08:00
dota17
3c3b5920f7 add uint64 data to json-c 2020-02-25 14:51:35 +08:00
dota17
c684b1d40b add coveralls auto tool to json-c 2020-02-18 10:39:43 +08:00
Eric Haszlakiewicz
518f337ce8 Issue #539: use a internal-only serializer function in json_object_new_double_s() to avoid potential conflicts with user code that uses the json_object_userdata_to_json_string serializer. Also, document the serializer-resetting behavior of json_object_set_double(). 2020-02-14 03:48:02 +00:00
Eric Haszlakiewicz
4bf7ffa984 Issue #539: be sure to clean up at the end of test_set_value. 2020-02-14 03:25:46 +00:00
Eric Haszlakiewicz
ae13ca524a Issue #539: reset the serializer when json_object_set_double() is called and the current serializer is the one that json_object_new_double_s() used. 2020-02-13 03:11:10 +00:00
Eric Haszlakiewicz
0ffdbb2395 Merge pull request #531 from dota17/utf8test
validate utf-8 string
2020-02-05 21:56:06 -05:00
Eric Haszlakiewicz
1934eddf29 Merge pull request #536 from dota17/new_null
add json_object_new_null()
2020-01-21 23:23:53 -05:00
dota17
7ad72b81c5 update comment 2020-01-22 09:56:52 +08:00
dota17
010f33d460 add json_object_new_null 2020-01-20 16:46:46 +08:00
dota17
787a8b3f1c update code 2020-01-20 10:41:24 +08:00
Eric Haszlakiewicz
360d28b961 Merge pull request #533 from sunpoet/master
Fix "make check"
2020-01-12 22:42:02 -05:00
Po-Chuan Hsieh
bb5971ba2a Fix make check
cc -DHAVE_CONFIG_H -I. -I..  -I.. -I../tests    -O2 -pipe  -fstack-protector-strong -fno-strict-aliasing  -Wall -Werror -Wcast-qual -Wno-error=deprecated-declarations -Wextra -Wno-unused-parameter -D_GNU_SOURCE -D_REENTRANT -MT test_parse.o -MD -MP -MF .deps/test_parse.Tpo -c -o test_parse.o test_parse.c
test_parse.c:256:14: error: adding 'int' to a string does not append to the string [-Werror,-Wstring-plus-int]
        { "null123" + 4,       4, 3, json_tokener_success, 1 },
          ~~~~~~~~~~^~~
test_parse.c:256:14: note: use array indexing to silence this warning
        { "null123" + 4,       4, 3, json_tokener_success, 1 },
                    ^
          &         [  ]
test_parse.c:258:12: error: adding 'int' to a string does not append to the string [-Werror,-Wstring-plus-int]
        { "nullx" + 4,         2, 0, json_tokener_error_parse_unexpected, 1 },
          ~~~~~~~~^~~
test_parse.c:258:12: note: use array indexing to silence this warning
        { "nullx" + 4,         2, 0, json_tokener_error_parse_unexpected, 1 },
                  ^
          &       [  ]
test_parse.c:260:25: error: adding 'int' to a string does not append to the string [-Werror,-Wstring-plus-int]
        { "{\"a\":1}{\"b\":2}" + 7,
          ~~~~~~~~~~~~~~~~~~~~~^~~
test_parse.c:260:25: note: use array indexing to silence this warning
        { "{\"a\":1}{\"b\":2}" + 7,
                               ^
          &                    [  ]
3 errors generated.
*** Error code 1

Stop.
2020-01-11 07:20:44 +00:00
dota17
eca74dcccf test utf8 2020-01-10 18:33:14 +08:00
Eric Haszlakiewicz
e651e96a5b Merge pull request #526 from dota17/addTestCase_printbuf
Increased the test coverage of printbuf.c 82% to 92%.
2020-01-03 08:32:53 -05:00
Eric Haszlakiewicz
a255510cca Merge pull request #525 from dota17/addPointerTestcase
update pointer test case
2020-01-03 08:31:41 -05:00
chenguoping
8c0cb0bd28 Increased the test coverage of printbuf.c 82% to 92%. 2020-01-03 14:34:35 +08:00
Eric Haszlakiewicz
0421772bbc Merge pull request #523 from dota17/updatetestcase
update tsetcase for tokener_c
2020-01-02 22:22:57 -05:00
Eric Haszlakiewicz
4bfed6eb2f Merge pull request #522 from dota17/addVisitTestcase
update json_visit testcase
2020-01-02 22:22:09 -05:00
dota17
5fe4448541 update tsetcase for tokener_c 2020-01-02 19:19:12 +08:00
dota17
a5089f5a79 update json_visit testcase 2020-01-02 16:41:37 +08:00
dota17
48ae9e8874 update pointer test case 2020-01-02 10:49:29 +08:00
Eric Haszlakiewicz
ee34939e74 Merge pull request #519 from dota17/addTestCase_obj_token
Add test case obj token
2019-12-29 16:02:04 -05:00
chenguoping
424b315ce0 pointer types discards qualifiers 2019-12-27 15:39:31 +08:00
chenguoping
1446572997 add testcases of object and token 2019-12-27 15:07:00 +08:00
Eric Haszlakiewicz
d6b968dff7 Merge pull request #512 from JaapKeuter/cmake_test
Properly append to CMAKE_C_FLAGS string
2019-12-12 22:30:15 -05:00
Jaap Keuter
78d8e5c3d5 Properly append to CMAKE_C_FLAGS string
Contrary to other CMAKE variables the CMAKE_C_FLAGS variable is the
composed string of flags for the C compiler. It is therefore not a list
to append to. Current implementation results in these incorrect CFLAGS,
e.g., "-O2 -g -fblahblah;-UNDEBUG". Extending the CFLAGS this way
results in the proper CFLAGS, e.g., "-O2 -g -fblahblah -UNDEBUG".
2019-12-12 21:28:03 +01:00
Eric Haszlakiewicz
6c55f65d07 Set cmake policy CMP0075, to have check_include_file use the value of CMAKE_REQUIRED_LIBRARIES (currently, adds -lm). See issue #510. 2019-12-06 00:15:14 -05:00
Eric Haszlakiewicz
0819a55ffb Undefine NDEBUG for tests - cmake version. See issue #501. 2019-12-05 23:18:59 -05:00
Eric Haszlakiewicz
37b4da6b92 Merge pull request #501 from andy5995/iss_406-2
undefine NDEBUG for tests
2019-12-05 23:18:46 -05:00
Eric Haszlakiewicz
581b94b3bd Add a shim script to ease shift from autoconf to cmake. 2019-12-01 23:42:40 -05:00
Eric Haszlakiewicz
11a638048d Add a few missing features to the cmake setup that are present in configure.ac:
Include all compiler warnings, and provide DISABLE_WERROR to make them not be errors.
 Define _REENTRANT, if setting it works.
 Set -Bsymbolic-functions, and provide DISABLE_BSYMBOLIC to turn that off.
 Implement the check for HAS_GNU_WARNING_LONG
2019-11-26 23:02:15 -05:00
Eric Haszlakiewicz
a92e6d2c28 Set the soversion in the cmake built library, and arrange for the file name to be generated appropriately too. 2019-11-25 23:26:48 -05:00
Eric Haszlakiewicz
41f434e89f Fix test_util_file for VS2013 too, but skip all the tests for anything older than that because the limitations are too inconvenient. 2019-11-23 23:55:04 -05:00
Eric Haszlakiewicz
b99be9cf4e Fix up the test_util_file test for builds on Windows VS2015. 2019-11-23 23:14:24 -05:00
Eric Haszlakiewicz
7f30afc6e5 Fix some Windows compile issues, add JSON_EXPORT's, fix bogus character escapes, define __func__ and omit unistd.h if needed. 2019-11-23 20:31:14 -05:00
Eric Haszlakiewicz
f19abcf981 Get the cmake build a bit closer to the autoconf one: include json_visit.h, and fix the version stamped in json-c.pc. 2019-11-23 15:34:23 -05:00
Eric Haszlakiewicz
bdaff94e9a Build and run the tests as part of the cmake build. 2019-11-23 15:15:48 -05:00
Eric Haszlakiewicz
25aedddcdf Fix memory leaks in test_double_serializer, and make sure all tests return 0 at the end of main(). 2019-11-23 12:05:28 -05:00
Eric Haszlakiewicz
3d3b014971 Add a quick way (JSONC_TEST_TRACE=1) to turn on shell tracing in tests. 2019-11-23 12:03:27 -05:00
Eric Haszlakiewicz
b1ad748842 Extend test_double_serializer to check NaN and Infinity handling. 2019-11-22 22:56:33 -05:00
Eric Haszlakiewicz
af8dd4a307 Define vars earlier to fix old Windows builds. 2019-11-10 20:35:30 -05:00
Eric Haszlakiewicz
baed9983b3 Add a json_object_from_fd_ex() function, to allow the max nesting depth to be specified. 2019-11-10 00:14:44 -05:00
Eric Haszlakiewicz
ac26ea9c5b Add a test for serializing the double value -1.0. 2019-11-10 00:13:00 -05:00
Eric Haszlakiewicz
ddd049045d Merge pull request #505 from grdowns/vcpkg-instructions
Add vcpkg installation instructions
2019-09-26 22:23:52 -04:00
grdowns
7ef51239a9 Update dependencies 2019-09-26 17:11:49 -07:00
grdowns
760c1e284c Add vcpkg installation instructions 2019-09-26 17:09:39 -07:00
Eric Haszlakiewicz
eae040a84a Issue #488: use JSON_EXPORT on functions so they are properly exported on Windows. 2019-09-08 22:42:36 -04:00
Eric Haszlakiewicz
374ffe87c6 Issue #463: fix newlocale() call to use LC_NUMERIC_MASK instead of LC_NUMERIC, and remove incorrect comment.
The second call to newlocale() with LC_TIME accidentally made things
 work because LC_TIME == LC_NUMERIC_MASK on some platforms.
2019-09-08 22:27:30 -04:00
Eric Haszlakiewicz
05b41b159e Add a json_tokener_get_parse_end() function to replace direct access of tok->char_offset. 2019-09-08 21:35:37 -04:00
Eric Haszlakiewicz
087534c030 Minor cleanup of includes in a couple of tests. 2019-09-08 21:34:13 -04:00
Eric Haszlakiewicz
d0b87ee87b Add an explicit cast to double to squash a -Wimplicit-int-float-conversion warning.
Though we will no longer be comparing exactly against INT64_MAX, this is ok
because any value of that magnitude stored in a double will *also* have been
rounded up, so the comparison will work appropriately.
2019-08-12 00:30:45 +00:00
andy5995
8799623806 undefine NDEBUG for tests
(closes #406)
2019-07-30 14:34:51 -05:00
Eric Haszlakiewicz
a91aa5e35d Merge pull request #499 from andy5995/travis_valgrind
.travis.yml:test on more recent clang and gcc versions
2019-07-27 09:29:57 -04:00
andy5995
509600a7f7 add xenial default clang with CHECK enabled 2019-07-26 23:51:18 -05:00
andy5995
4f69529a04 add missing dist 2019-07-26 23:36:01 -05:00
andy5995
dd08b70e46 manually use apt-get to install packages on bionic 2019-07-26 23:21:20 -05:00
andy5995
dd0eef6aab add tests on bionic beaver 2019-07-26 22:42:53 -05:00
andy5995
163db3f6d0 revert toolchain back to "test" 2019-07-26 22:24:12 -05:00
andy5995
1da4b23235 change key 2019-07-26 22:24:12 -05:00
andy5995
a49f1dee8a use "non-test" ppa
Maybe something weird about how gcc is configured with the test
toolchain?
2019-07-26 22:24:12 -05:00
andy5995
897b49f475 remove useless condition that shows logs 2019-07-26 22:24:12 -05:00
andy5995
b140c473d1 install doxygen so 'make distcheck' can succeed 2019-07-26 22:24:12 -05:00
andy5995
6288be340c test for more compilers 2019-07-26 22:24:12 -05:00
andy5995
57e79e1d0b show the logs if tests fail 2019-07-26 22:24:12 -05:00
andy5995
50e7fff0f3 .travis.yml:install valgrind
(#498)
2019-07-26 22:24:12 -05:00
Eric Haszlakiewicz
c8e1b59ae5 Merge pull request #495 from andy5995/README_typos
README.md:fix 2 typos
2019-07-26 23:08:11 -04:00
andy5995
1c7e891e44 "make its use in" [skip ci] 2019-07-26 12:59:24 -05:00
Eric Haszlakiewicz
4a94ddbd8b Merge pull request #500 from andy5995/add_missing_test_deps
test/Makefile.am:add missing deps for test1 and test2
2019-07-26 09:48:34 -04:00
andy5995
e2f46b9f79 partial revert (make use) [skip ci] 2019-07-25 22:55:07 -05:00
Eric Haszlakiewicz
68abf12afa Issue #498: Fix a memory leak bug introduced in test_double_serializer in 485f2a02 by adding a json_object_put call. 2019-07-26 03:35:38 +00:00
Eric Haszlakiewicz
48984dbd42 Merge pull request #496 from andy5995/pointer_doc
json_pointer.h:suggest minor grammar improvement for pointer doc
2019-07-25 22:58:22 -04:00
andy5995
8ab8df1170 test/Makefile.am:add missing deps for test1 and test2
Allows the tests to pass when running `make distcheck`

This fixes the 2 broken tests I mentioned at
https://github.com/json-c/json-c/pull/499#discussion_r306998261
2019-07-25 14:59:56 -05:00
andy5995
a9c34d5531 json_pointer.h:suggest minor grammar improvement for pointer doc 2019-07-23 23:53:06 -05:00
andy5995
3969487376 README.md:fix 2 typos 2019-07-23 23:43:59 -05:00
Eric Haszlakiewicz
07ea04e651 Merge pull request #491 from ploxiln/disable_werror
build: add option --disable-werror to configure
2019-06-09 14:05:46 -04:00
Pierce Lopez
634900d270 tests: appease -Wwrite-strings 2019-06-09 12:17:06 -04:00
Pierce Lopez
44605744dc build: fix compiler option -Wwrite-strings
was typod as -Wwrite-string
2019-06-09 10:55:50 -04:00
Pierce Lopez
21c886534f build: add --disable-werror option to configure
to omit -Werror compiler option
2019-06-09 10:53:56 -04:00
Eric Haszlakiewicz
2b1903cc69 Merge pull request #485 from myd7349/fix-cmake-module
Install CMake module files
2019-05-30 22:38:29 -04:00
Eric Haszlakiewicz
485f2a02c7 Issue #486: append a missing ".0" to negative double values too. 2019-05-28 02:44:22 +00:00
myd7349
c2036ab9fc Install CMake module files 2019-05-18 19:44:29 +08:00
Eric Haszlakiewicz
3e81b4abe3 Merge pull request #474 from Jehan/fix-pc-file-cmake
Installation directories empty with CMake in pkg-config.
2019-01-26 10:55:50 -05:00
Jehan
c46a0636c6 Installation directories empty with CMake in pkg-config.
CMake was not properly substituting the installation dir variables (they
ended up all empty), so the pkg-config results were also wrongs. For
instance cflags was: -I -I/json-c
Even though json-c was found at configure time, this obviously broke the
build of any application using it.
2019-01-26 12:30:40 +01:00
Eric Haszlakiewicz
f1713b3f62 Merge pull request #473 from besser82/fixup/docs_utf8
Convert ChangeLog to valid UTF-8 encoding.
2019-01-23 22:47:27 -05:00
Björn Esser
259d5078c4 Clean trailing white-spaces in ChangeLog. 2019-01-22 17:07:14 +01:00
Björn Esser
6b0745ea1f Convert ChangeLog to valid UTF-8 encoding. 2019-01-22 17:07:14 +01:00
Ramiro Polla
38a112380b json_object: cleanup of *set_string* functions
This commit also has the side-effect that errno is set on failed calls
to json_object_set_string(_len).
2018-12-21 00:30:26 +01:00
Ramiro Polla
906188e1cf json_object: speed up creation of objects
Instead of using calloc(), call malloc() and initialize the relevant
fields individually.

speedup for 32-bit: ~15%
speedup for 64-bit: ~ 5%
2018-12-21 00:30:26 +01:00
Ramiro Polla
c9a0ac5886 json_tokener: optimize parsing of integer values
speedup for 32-bit: ~8%
speedup for 64-bit: ~9%
2018-12-21 00:30:21 +01:00
Ramiro Polla
d98fc501fb json_tokener: optimize check for number characters
speedup for 32-bit: ~5%
speedup for 64-bit: ~3%
2018-12-21 00:24:17 +01:00
Ramiro Polla
45c601bfa4 json_tokener: optimize check for hex characters
speedup for 32-bit: ~1%
speedup for 64-bit: ~1%
2018-12-21 00:24:17 +01:00
Ramiro Polla
158c248d5c json_tokener: optimize check for whitespace characters
speedup for 32-bit: ~15%
speedup for 64-bit: ~ 2%
2018-12-21 00:24:17 +01:00
Ramiro Polla
ab3e40b37c json_object_deep_copy: fix deep copy of strings containing '\0' 2018-12-20 22:26:06 +01:00
Ramiro Polla
1f46d2f40f json_object_private: remove _delete field
This field is set based on o_type when the object is created and it is
not changed during the lifetime of the object. Therefore we can check
o_type to choose the proper delete function in json_object_put(), and
save sizeof(void *) bytes in struct json_object_private.
2018-12-20 22:26:06 +01:00
Eric Haszlakiewicz
39c9fa0a2b Merge pull request #468 from rkalidas/compiler-fixes
Fix compiler warnings
2018-12-19 11:09:01 -05:00
Rubasri Kalidas
3003161eff Fix compiler warnings 2018-12-18 11:30:57 -06:00
Eric Haszlakiewicz
6460446aa6 Switch to building a dynamic lib by default. Tweak language in the README.md slightly. Inspired by PR#452. 2018-12-11 20:59:08 -05:00
Eric Haszlakiewicz
ee4691c9fb Merge pull request #453 from darjankrijan/master
Fixed misalignment in JSON string due to space after \n being printed...
2018-12-11 20:17:43 -05:00
Darjan Krijan
9c4b07faec Removed newly created test case and incorporated it into test1.test and test2.test 2018-12-07 17:39:59 +01:00
Darjan Krijan
7a9075c16b Added test cases for spaced pretty and pretty_tab used together 2018-12-07 17:30:15 +01:00
Eric Haszlakiewicz
240627f260 Merge pull request #454 from ramiropolla/json_object_private
json_object_private: save 8 bytes in struct json_object in 64-bit arc…
2018-11-30 09:49:35 -05:00
Eric Haszlakiewicz
745cadc944 Merge pull request #461 from andy5995/issue_422
json_object.c:set errno in json_object_get_double()
2018-11-28 20:39:42 -05:00
Eric Haszlakiewicz
83cb93b7ae Merge pull request #462 from andy5995/issue_460
json_object.h:document json_object_new_string_len()
2018-11-28 20:39:13 -05:00
andy5995
2942870325 remove [in] from params description
Keeping this would be inconsistent with the other documentation
2018-11-28 16:55:19 -06:00
andy5995
3b108935d0 json_object.h:document json_object_new_string_len()
I also added a couple trivial, but related, suggestions.

closes #460
2018-11-27 11:35:45 -06:00
andy5995
506a32d4ab json_object.c:set errno in json_object_get_double()
closes #422
2018-11-26 21:12:06 -06:00
Eric Haszlakiewicz
7539ab2d2e Merge pull request #459 from andy5995/issue_438
README.html:fix link to Doxygen docs, remove WIN32 link
2018-11-25 21:19:02 -05:00
Eric Haszlakiewicz
753de5a5a9 Merge pull request #458 from andy5995/README_files_link
README.md:fix dead "file.html" link
2018-11-25 21:17:40 -05:00
Eric Haszlakiewicz
80bf857b27 Merge pull request #457 from andy5995/gitignore_build
.gitignore:add build directory
2018-11-25 21:14:34 -05:00
Eric Haszlakiewicz
aa831c7960 Merge pull request #456 from andy5995/style_perms
STYLE.txt:remove executable permissions
2018-11-25 21:14:14 -05:00
andy5995
fc1b113b29 README.html:fix link to Doxygen docs, remove WIN32 link
fixes #438
[skip ci]
2018-11-25 07:09:00 -06:00
andy5995
71f5c2d50b README.md:fix dead "file.html" link 2018-11-25 06:51:21 -06:00
andy5995
c3e11d6812 .gitignore:add build directory 2018-11-25 06:45:21 -06:00
andy5995
dba65cbd30 STYLE.txt:remove executable permissions 2018-11-25 06:43:02 -06:00
Ramiro Polla
5bb5e2e8fc json_object_private: save 8 bytes in struct json_object in 64-bit architectures
- there is no need for _ref_count to be uint_fast32_t (the compiler
  might decide to use a 64-bit int). make it uint32_t instead.
- reorder the 32-bit integer fields (o_type and _ref_count) so that
  there is no wasted 4-byte gap after each of them.
2018-11-24 04:16:36 +01:00
Darjan Krijan
b0bceaa8bf Added a test for the space after \n issue with flags=JSON_C_TO_STRING_SPACED|JSON_C_TO_STRING_PRETTY|(JSON_C_TO_STRING_PRETTY_TAB) used in json_object_array_to_json_string 2018-11-21 22:41:13 +01:00
Darjan Krijan
3943960874 Removed spaces after \n for arrays as well 2018-11-21 22:34:01 +01:00
Darjan Krijan
e8cec5c9e4 Fixed misalignment in JSON string due to space after \n being printed when choosing JSON_C_TO_STRING_SPACED together with JSON_C_TO_STRING_PRETTY in json_object_array_to_json_string 2018-11-20 22:21:27 +01:00
Eric Haszlakiewicz
ebe520e96e Merge pull request #450 from drizt/subproject
Allow use json-c cmake as subproject
2018-10-20 23:01:20 -04:00
Ivan Romanov
ba5a02e8a9 Allow use json-c cmake as subproject
Now json-c can be bundled to any cmake-based project and used with
couple lines of code:

add_subdirectory(json-c EXCLUDE_FROM_ALL)
target_link_libraries(MyProject json-c)
2018-10-20 10:50:15 +05:00
Eric Haszlakiewicz
994e6c1f60 Re-add creation and installation of the json-c.pc file to the cmake build. 2018-09-01 15:06:14 -04:00
Eric Haszlakiewicz
705e2fd010 Merge pull request #444 from Hawk777/document-ref-count-tokener
Document refcount of json_tokener_parse_ex return
2018-08-31 01:16:53 -04:00
Christopher Head
31d4d3dee7 Document refcount of json_tokener_parse_ex return 2018-08-30 09:18:29 -07:00
Eric Haszlakiewicz
0a8ac2ed92 Merge pull request #441 from changyongGuo/c_flag_error
fix c flag loss during cmake building
2018-08-14 20:40:49 -04:00
changyong guo
08c8231cc8 fix c flag loss during cmake building 2018-08-14 13:52:18 +08:00
Eric Haszlakiewicz
bf29aa0f8c Merge pull request #434 from unmanned-player/devel
The real CMake support
2018-07-28 11:59:46 -04:00
Eric Haszlakiewicz
91f9884591 Merge pull request #436 from jobol/master
Improve pkgconfig setting
2018-07-26 23:28:42 -04:00
Jose Bollo
d189d7b5ff Improve pkgconfig setting
This changes allows to use #include <json-c/json.h>
instead of just #include <json.h>

This is normally possible but in some tricky case
this usage is broken without this change.

Here is the case that I encountered. I had to
compile json-c fresh version for some investigations
on newer versions. Then I installed it on my local
environment using option --prefix. After that I
had 2 versions:

 - the system wide version in usual locations
   /usr/lib and /usr/include
 - mine in my HOME directory

Then, as I'm used to include <json-c/json.h>, the
included iheder's version was the system wide one
whereas the linked lib was mine.

Signed-off-by: Jose Bollo <jose.bollo@iot.bzh>
2018-07-25 15:51:02 +02:00
Unmanned Player
f2e991a341 The real CMake support
This patch provides a CMakeLists.txt file to build JSON-C library without relying on auto-tools support. This makes the build a bit more portable and cleaner.

It can detect headers and symbols and generate config.h header file based on those detections. It cannot yet handle ctest(1) as the testing itself depends on comparing the output against files. Testing would need some creative abuse of CMake :) This will be provided a few patches later and may possibly involve refactoring test cases.

The patch has been tested on GCC 4.8.5 (Linux), GCC 7.2.0 (MinGW) and Microsoft Visual C++ 16.0 (2010?) locally. Also, compiles correctly on Travis CI and AppVeyor without errors.
2018-07-24 08:06:13 +10:00
Eric Haszlakiewicz
2327b23d8e Merge pull request #431 from LeSpocky/cmake
cmake: Bump required version
2018-07-12 22:26:48 -04:00
Alexander Dahl
901d59b29f cmake: Bump required version
Using 'project(foo VERSION 1.0)' requires CMake 3.0, the VERSION option
is not part of CMake 2.8.7, see:

* https://cmake.org/cmake/help/v2.8.7/cmake.html#command:project
* https://cmake.org/cmake/help/v3.0/release/3.0.0.html#commands

The property C_STANDARD was introduced with CMake 3.1, see:

* https://cmake.org/cmake/help/v3.1/release/3.1.0.html#properties

Signed-off-by: Alexander Dahl <post@lespocky.de>
2018-07-12 21:25:38 +02:00
Eric Haszlakiewicz
3df1f98b4a Explain why we're not setting the output name for static libraries when on Windows. 2018-06-23 22:10:55 -04:00
Eric Haszlakiewicz
a056893263 Merge pull request #415 from sgbihu/master
Resolve windows name conflict
2018-06-23 22:08:25 -04:00
Eric Haszlakiewicz
e3752b5894 Issue #418: Fix docs for json_util_from_fd and json_util_from_file to say that they return NULL on failures. 2018-06-14 22:24:45 -04:00
Eric Haszlakiewicz
c1c71097a1 Issue #419: document that NULL may be passed to json_object_put(). 2018-06-12 23:16:31 -04:00
Eric Haszlakiewicz
fb042f449b Merge pull request #421 from lt-holman/install_header_file
install json_object_iterator.h header file
2018-06-08 23:45:47 -04:00
Keith Holman
37a2edf468 install json_object_iterator.h header file
When building the project using cmake then installing it.  The
definitions in `json_object_iterator.h` are required but not installed
by the cmake install rule.  This patch adds the `json_object_iterator.h`
file to the list of files to install.

Signed-off-by: Keith Holman <keith.holman@windriver.com>
2018-06-07 13:19:27 -04:00
Eric Haszlakiewicz
4bbc72f633 Merge pull request #420 from angelskieglazki/master
arraylist: Fixed names of parameters for callback function
2018-06-02 23:01:04 -04:00
max
7a4759f165 arraylist: Fix names of parameters for callback function 2018-06-01 18:21:06 +03:00
Eric Haszlakiewicz
4414d068b3 Always create debug info (pdb file) even for release builds. 2018-05-27 21:50:57 -04:00
Eric Haszlakiewicz
7038bb8061 Try the appveyor changes again, using %Configuration% instead of "Debug" 2018-05-27 18:20:32 -04:00
Eric Haszlakiewicz
dfc0fddf22 Include the json-c.lib, .pdb and .exp files in the zip file created by the appveyor build, since it seems they're needed for linking and debugging. 2018-05-27 16:07:11 -04:00
Liang, Gao
0b3616d580 Resolve windows name conflict
1. The windows dll will output the lib and dll, and rename the static
    lib will have conflict on windows.
2. Delete rename code to dismiss the conflict.
2018-05-21 16:34:13 +08:00
Eric Haszlakiewicz
c75ebe8973 Merge pull request #410 from janczer/fix-typos
Fixed typos
2018-04-24 22:01:09 -04:00
janczer
8bd62177e7 Fixed typos 2018-04-24 16:00:38 +02:00
Eric Haszlakiewicz
f8c632f579 Issue #407: fix incorrect casts in calls to ctype functions (isdigit and isspace) so we don't crash when asserts are enabled on certain platforms and characters > 128 are parsed. 2018-03-25 18:25:58 -04:00
Eric Haszlakiewicz
da4b34355d Add an parse test for content starting with a UTF8 BOM, which is _not_ a valid start to a JSON message. 2018-03-25 18:23:42 -04:00
Eric Haszlakiewicz
104aef0a6e Update the change log for the 0.13.1 release. 2018-03-05 22:54:57 -05:00
Eric Haszlakiewicz
2fd95844c3 Issue #396: check for toolchain compatibilty with _REENTRANT before adding it to CFLAGS. 2018-03-04 22:32:45 -05:00
Eric Haszlakiewicz
1e301d94be Merge pull request #402 from derwolfe/fuzz
Add fuzzers from OSS-Fuzz
2018-02-19 13:54:18 -05:00
Chris Wolfe
1e08150838 pull in fuzzers, add CI scripts later 2018-02-05 19:26:24 -06:00
Eric Haszlakiewicz
f8eb1dec64 Merge pull request #399 from jonathan-wiens/bugfix/initialize_variable
Avoid uninitialized variable warnings
2018-01-26 23:46:33 -05:00
Jonathan Wiens
cdc4e9f64b Avoid uninitialized variable warnings
Fix json_object_object_foreach to avoid uninitialized variable warnings
using ANSI C or MSC.
2018-01-17 15:57:52 +01:00
Eric Haszlakiewicz
250de31f17 Bump the major version of the .so library generated up to 4.0 to avoid conflicts because some downstream packagers of json-c had already done their own bump to ".so.3" for a much older 0.12 release. 2018-01-15 23:31:55 -05:00
Eric Haszlakiewicz
c652b6ad29 PR#394: fix breakage with VS build. 2017-12-24 14:42:58 -05:00
Eric Haszlakiewicz
d5da847f51 PR#394: don't always append the ".0" if the double value rounds to zero because some custom formats *will* include it (e.g. %.2f).
Also try to accomodate formats to explicitly exclude the decimal (e.g. %.0f).
2017-12-24 13:45:52 -05:00
Eric Haszlakiewicz
0992aac61f Remove the TRUE and FALSE defines. 2017-12-23 09:42:17 -05:00
Eric Haszlakiewicz
cfd09c87f0 Merge pull request #393 from besser82/enhancement/unsigned_refcount
json_object_private: Use unsigned 32-bit integer type for refcount
2017-12-17 09:52:27 -05:00
Björn Esser
c233f5c05e json_object_private: Use unsigned 32-bit integer type for refcount 2017-12-17 12:51:17 +01:00
Eric Haszlakiewicz
5ea6a05bfa Merge pull request #389 from besser82/bugfix/invalid_free
json_object: Avoid double free (and thus a segfault) when ref_count gets < 0
2017-12-14 09:28:06 -05:00
Björn Esser
9aca3b6a08 json_object: Avoid invalid free (and thus a segfault) when ref_count gets < 0 2017-12-14 14:36:07 +01:00
Eric Haszlakiewicz
8c214902d9 Merge pull request #386 from besser82/bugfix/aclocal_amflags
Makefile: Add ACLOCAL_AMFLAGS
2017-12-13 22:03:20 -05:00
Eric Haszlakiewicz
e411b1a36e Merge pull request #391 from rikardfalkeborn/fix-const-function-define
Fix non-GNUC define for JSON_C_CONST_FUNCTION
2017-12-13 21:51:13 -05:00
Rikard Falkeborn
84dcc01da1 Fix non-GNUC define for JSON_C_CONST_FUNCTION 2017-12-13 22:29:16 +01:00
Björn Esser
87556afe2a Makefile: Add ACLOCAL_AMFLAGS
This is recommended by the libtool manual.
2017-12-13 01:26:35 +01:00
Eric Haszlakiewicz
5b6d62259a Apply gcc's "const" attribute to the json_c_object_sizeof() function as an optimizer hint. Also, rename that function from json_object_sizeof(). 2017-12-12 18:26:51 -05:00
Eric Haszlakiewicz
94fd101601 Merge pull request #388 from besser82/enhancement/json_object_sizeof
json_object: Add size_t json_object_sizeof()
2017-12-12 18:14:40 -05:00
Eric Haszlakiewicz
25afa92ed5 Merge pull request #387 from LeSpocky/doc
doc: Use other doxygen feature to specify mainpage
2017-12-12 09:13:36 -05:00
Björn Esser
c123a1c21b json_object: Add size_t json_object_sizeof() 2017-12-11 16:16:15 +01:00
Alexander Dahl
89747ac758 doc: Use other doxygen feature to specify mainpage
Previously a special tag was added to README.md to make this the
main page in Doxygen generated docs. When viewing the README on the
GitHub page this tag was not hidden.

After upgrading to Doxygen 1.8.8 (and above) in changeset
219025727d a new Doxygen feature can be
used to specify the main page: Since release 1.8.3 Doxygen has a special
option to set a markdown file as main page. When using this option we
can drop the tag, making the README rendered by GitHub nice to look at.

Fixes: ae66b24369
2017-12-11 09:46:28 +01:00
Eric Haszlakiewicz
a19031411d Remove the previously deprecated lh_table_lookup() function, in favor of lh_table_lookup_ex(). 2017-12-10 00:27:01 -05:00
Eric Haszlakiewicz
f83cf244cd Remove the previously deprecated bits.h and the lh_abort() function. 2017-12-10 00:25:00 -05:00
Eric Haszlakiewicz
963e707ca4 Drop mention of README-WIN32.html in the release checklist. 2017-12-09 15:12:08 -05:00
Eric Haszlakiewicz
0631c37c7f Update the master branch to version 0.13.99 2017-12-09 14:59:48 -05:00
Eric Haszlakiewicz
8c4a941475 Tweak the release checklist slightly to fix problems noticed during this past release process. 2017-12-09 14:59:05 -05:00
155 changed files with 12499 additions and 5159 deletions

55
.clang-format Normal file
View File

@@ -0,0 +1,55 @@
BasedOnStyle: LLVM
# If true, clang-format will attempt to re-flow comments
ReflowComments: false
# The column limit.
ColumnLimit: 100
# Indent width for line continuations.
ContinuationIndentWidth: 4
# The number of columns to use for indentation.
IndentWidth: 8
# The number of columns used for tab stops.
TabWidth: 8
UseTab: ForIndentation
# Options for aligning backslashes in escaped newlines.
AlignEscapedNewlines: Left
# Short Block Style
AllowShortBlocksOnASingleLine: true
# If true, short case labels will be contracted to a single line.
AllowShortCaseLabelsOnASingleLine: true
# Dependent on the value, int f() { return 0; } can be put on a single line.
AllowShortFunctionsOnASingleLine: Empty
# The brace breaking style to use.
BreakBeforeBraces: Custom
# Control of individual brace wrapping cases.
BraceWrapping:
# Wrap brackets inside of a case
AfterCaseLabel: true
# Wrap class definition.
AfterClass: true
# Wrap control statements
AfterControlStatement: true
# Wrap enum definitions.
AfterEnum: true
# Wrap function definitions.
AfterFunction: true
# Wrap namespace definitions.
AfterNamespace: true
# Wrap struct definitions.
AfterStruct: true
# Wrap union definitions.
AfterUnion: true
# Wrap extern blocks.
AfterExternBlock: false
# Wrap before catch.
BeforeCatch: true
# Wrap before else.
BeforeElse: true
# Indent the wrapped braces themselves.
IndentBraces: false
# If false, empty function body can be put on a single line.
SplitEmptyFunction: false
# If false, empty record (e.g. class, struct or union) body can be put on a single line.
SplitEmptyRecord: false
# If false, empty namespace body can be put on a single line.
SplitEmptyNamespace: false

View File

@@ -1,5 +1,5 @@
# EditorConfig # EditorConfig
# http://EditorConfig.org # https://EditorConfig.org
# top-most EditorConfig file # top-most EditorConfig file
root = true root = true

23
.github/ISSUE_TEMPLATE/bug_report.md vendored Normal file
View File

@@ -0,0 +1,23 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
Note: for general questions and comments, please use the forums at:
https://groups.google.com/g/json-c
**Describe the bug**
A clear and concise description of what the bug is, and any information about where you're running into the bug that you feel might be relevant.
**Steps To Reproduce**
List the steps to reproduce the behavior.
If possible, please attach a sample json file and/or a minimal code example.
**Version and Platform**
- json-c version: [e.g. json-c-0.14, or a specific commit hash]
- OS: [e.g. Ubuntu 20.04, Debian Buster, NetBSD 9, etc...]
- Custom cmake/build flags, if any

54
.gitignore vendored
View File

@@ -12,9 +12,7 @@
*.autosave *.autosave
# Tests # Tests
/test-driver
/tests/Makefile /tests/Makefile
/tests/Makefile.in
/tests/test1 /tests/test1
/tests/test1Formatted /tests/test1Formatted
/tests/test2 /tests/test2
@@ -29,6 +27,7 @@
/tests/test_double_serializer /tests/test_double_serializer
/tests/test_float /tests/test_float
/tests/test_int_add /tests/test_int_add
/tests/test_int_get
/tests/test_json_pointer /tests/test_json_pointer
/tests/test_locale /tests/test_locale
/tests/test_null /tests/test_null
@@ -44,17 +43,12 @@
/tests/*.trs /tests/*.trs
# Generated folders # Generated folders
/build
/Debug /Debug
/Release /Release
/*/Debug /*/Debug
/*/Release /*/Release
# Generated binaries
*.lo
*.o
/libjson-c.la
/libjson.la
# Archives # Archives
*.zip *.zip
*.tar.* *.tar.*
@@ -74,38 +68,28 @@
*.dmg *.dmg
*.ipa *.ipa
.deps/ # It's not good practice to build directly in the source tree
.libs/ # but ignore cmake auto-generated files anyway:
/aclocal.m4
/autoconf-archive
/autom4te.cache
/config.guess
/config.h.in
/json_config.h /json_config.h
/compile /json.h
/config.h /config.h
/config.log
/config.status
/config.sub
/configure
/depcomp
/doc
/install-sh
/json.pc
/json-c.pc /json-c.pc
/json-c-uninstalled.pc
/libtool
/ltmain.sh
/Makefile /Makefile
/Makefile.in
/missing
/stamp-h1
/stamp-h2
# cmake auto-generated files
/CMakeCache.txt /CMakeCache.txt
/CMakeFiles /CMakeFiles
/cmake_install.cmake /CMakeDoxyfile.in
/include /*.cmake
/DartConfiguration.tcl
/tests/CMakeFiles/
/tests/*.cmake
/Testing/
# ...and build artifacts.
/doc/html
/libjson-c.a /libjson-c.a
/libjson-c.so /libjson-c.so
/libjson-c.so.*
# Benchmarking input and output
/bench/data
/bench/work

View File

@@ -1,32 +1,147 @@
language: cpp language: cpp
matrix:
compiler: include:
- gcc
- clang # ubuntu xenial 16.04
# gcc 5 is the default on xenial
addons: - os: linux
apt: dist: xenial
packages: compiler: gcc
- cppcheck addons:
apt:
os: packages:
- linux - valgrind
- osx - cppcheck
- doxygen
before_install: - cmake
- echo $LANG env: CHECK="true"
- echo $LC_ALL
- set -e # ubuntu bionic 18.04
# gcc 7 is the default on bionic
install: - os: linux
- sh autogen.sh dist: bionic
compiler: gcc
before_script: addons:
- ./configure apt:
packages:
script: - valgrind
- make - cppcheck
- doxygen
after_success: - cmake
- make check env: CHECK="true"
- if type cppcheck &> /dev/null ; then cppcheck --error-exitcode=1 --quiet *.h *.c tests/ ; fi
# ubuntu focal fossa 20.04
# gcc 9 is the default on bionic
- os: linux
dist: focal
compiler: gcc
addons:
apt:
packages:
- valgrind
- cppcheck
- doxygen
- cmake
env: CHECK="true"
# clang
# xenial
- os: linux
dist: xenial
compiler: clang
addons:
apt:
sources:
- llvm-toolchain-xenial-6.0
packages:
- clang-6.0
- cmake
env: MATRIX_EVAL="CC=clang-6.0 && CXX=clang++-6.0"
# clang-7 is the default on focal, xenial and bionic
- os: linux
dist: focal
compiler: clang
addons:
apt:
packages:
- valgrind
- cppcheck
- doxygen
- cmake
env: CHECK="true"
# osx
- os: osx
osx_image: xcode13.4
env: XCODE="true" CHECK="true"
# run coveralls
- os: linux
dist: xenial
compiler: gcc
addons:
apt:
packages:
- lcov
env: CHECK="true"
before_install:
- sudo gem install coveralls-lcov
- echo $CC
- echo $LANG
- echo $LC_ALL
- set -e
- if [ "$TRAVIS_OS_NAME" = "linux" ]; then
eval "${MATRIX_EVAL}";
if [ -n "$MATRIX_EVAL" ] && [ "$TRAVIS_COMPILER" != "clang" ]; then
sudo apt-get install -y $CC;
fi;
fi
before_script:
- export CFLAGS="-fprofile-arcs -ftest-coverage"
- mkdir build && cd build && cmake ..
script:
- make
- make test
after_success:
- cd ..
- lcov -d build/ -b . -c -o build/all_coverage.info
- lcov -r build/all_coverage.info '/usr/*' '*CMakeFiles*' '*fuzz*' '*test*' -o build/coverage.info
- coveralls-lcov --verbose build/coverage.info
# allow_failures:
# - os: osx
before_install:
- echo $CC
- echo $LANG
- echo $LC_ALL
- set -e
- if [ "$TRAVIS_OS_NAME" = "linux" ]; then
eval "${MATRIX_EVAL}";
if [ -n "$MATRIX_EVAL" ] && [ "$TRAVIS_COMPILER" != "clang" ]; then
sudo apt-get install -y $CC;
fi;
fi
before_script:
# XXX osx on travis doesn't work w/ set -e, so turn it off :(
- set +e
- mkdir -p build || echo "Failed to mkdir build"
- cd build || echo "Failed to cd build"
- cmake .. || echo "Failed to run cmake"
script:
- make
# when using bionic, Travis seems to ignore the "addons" section, so installing the packages with apt-get...
- if [ -n "$CHECK" ]; then
if [ "$TRAVIS_OS_NAME" = "osx" ]; then
brew install doxygen;
else
if [ "$TRAVIS_DIST" = "bionic" ]; then
sudo apt-get install -y valgrind cppcheck doxygen;
fi;
fi;
make distcheck;
if type cppcheck &> /dev/null ; then cppcheck --error-exitcode=1 --quiet *.h *.c tests/ ; fi;
fi

74
AUTHORS
View File

@@ -1,5 +1,71 @@
Michael Clark <michael@metaparadigm.com> Alan Coopersmith <alan.coopersmith@oracle.com>
Jehiah Czebotar <jehiah@gmail.com> Alexander Dahl <post@lespocky.de>
Eric Haszlakiewicz <hawicz+json-c@gmail.com> Alexandru Ardelean <ardeleanalex@gmail.com>
An7ar35 <eadavison@protonmail.com>
andy5995 <andy400-dev@yahoo.com>
Aram Poghosyan <Aram.Poghosyan@teamviewer.com>
Björn Esser <besser82@fedoraproject.org>
BonsaY <bonsay@posteo.de>
changyong guo <guo1487@163.com>
chenguoping <chenguopingdota@163.com>
Chris Lamb <lamby@debian.org>
Christopher Head <chead@chead.ca>
Chris Wolfe <chriswwolfe@gmail.com>
C. Watford (christopher.watford@gmail.com) C. Watford (christopher.watford@gmail.com)
Daniel Danzberger <daniel@dd-wrt.com>
Darjan Krijan <darjan_krijan@gmx.de>
David McCann <mccannd@uk.ibm.com>
DeX77 <dex@dragonslave.de>
Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com>
dota17 <chenguopingdota@163.com>
Eric Haszlakiewicz <erh+git@nimenees.com>
Eric Hawicz <erh+git@nimenees.com>
Even Rouault <even.rouault@spatialys.com>
Federico Francescon <federico.francescon@higeco.com>
Gianluigi Tiesi <sherpya@netfarm.it>
grdowns <grdowns@microsoft.com>
Hex052 <elijahiff@gmail.com>
hofnarr <hofnarr@hofnarr.fi>
ihsinme <61293369+ihsinme@users.noreply.github.com>
Ivan Romanov <drizt@land.ru>
Jaap Keuter <jaap.keuter@xs4all.nl>
Jakov Smolic <jakov.smolic@sartura.hr>
janczer <menshikov.ivn@gmail.com>
JC (Jonathan Chen) <jc@dijonkitchen.org>
Jehan <jehan@girinstud.io>
Jehiah Czebotar <jehiah@gmail.com>
Jonathan Wiens <j.wiens@teles.com>
Jose Bollo <jose.bollo@iot.bzh>
José Bollo <jose.bollo@iot.bzh>
Juuso Alasuutari <juuso.alasuutari@gmail.com>
Keith Holman <keith.holman@windriver.com>
Khem Raj <raj.khem@gmail.com>
Kizuna-Meraki <z9@kizunameraki.de>
Leon Gross <leon.gross@rub.de>
Liang, Gao <liang.gao@intel.com>
Luca Mannella <luca.mannella@studenti.polito.it>
Marc <34656315+MarcT512@users.noreply.github.com>
Matthias Gatto <matthias.gatto@protonmail.com>
max <mpano91@gmail.com>
Micah Snyder <micasnyd@cisco.com>
Michael Clark <michael@metaparadigm.com>
myd7349 <myd7349@gmail.com>
Pascal Cuoq <cuoq@trust-in-soft.com>
Pawday <pawday@mail.ru>
Philosoph228 <philosoph228@gmail.com>
Pierce Lopez <pierce.lopez@gmail.com>
Po-Chuan Hsieh <sunpoet@sunpoet.net>
Ramiro Polla <ramiro.polla@gmail.com>
Rikard Falkeborn <rikard.falkeborn@gmail.com>
Robert Bielik <robert.bielik@dirac.com>
Robert <roby_p97@yahoo.com>
Rosen Penev <rosenp@gmail.com>
Rubasri Kalidas <rubasri.kalidas@intel.com>
Sergey Sharshunov <s.sharshunov@gmail.com>
Simon McVittie <smcv@collabora.com>
ssrlive <30760636+ssrlive@users.noreply.github.com>
Tobias Nießen <tniessen@users.noreply.github.com>
Tobias Stoeckmann <tobias@stoeckmann.org>
Tudor Brindus <me@tbrindus.ca>
Unmanned Player <36690541+unmanned-player@users.noreply.github.com>
Yurii Rashkovskii <yrashk@gmail.com>

View File

@@ -1,136 +1,587 @@
#Licensed under the MIT license. See LICENSE file in the project root for full license information. # CMake 3.9 was released in 2017/07
# As of 2023, many versions of Linux, NetBSD and FreeBSD provide,
# and many OpenWRT packages require, much newer CMake packages.
# We're stopping before 3.10 because that version starts requiring
# c++11, which isn't available on e.g HPUX.
cmake_minimum_required(VERSION 3.9...3.12)
cmake_minimum_required(VERSION 2.8.7) # JSON-C library is C only project.
cmake_policy(SET CMP0048 NEW) # PROJECT_VERSION{,_MAJOR,_MINOR,_PATCH} set by project():
project(json-c VERSION 0.12.99) project(json-c LANGUAGES C VERSION 0.17.99)
# set default build type if not specified by user
include(CheckSymbolExists) if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE debug)
check_symbol_exists(strtoll "stdlib.h" HAVE_STRTOLL)
set(cmake_strtoll "strtoll")
if (NOT HAVE_STRTOLL)
# Use _strtoi64 if strtoll is not available.
check_symbol_exists(_strtoi64 stdlib.h have_strtoi64)
if (have_strtoi64)
set(HAVE_STRTOLL 1)
set(cmake_strtoll "_strtoi64")
# could do the same for strtoull, if needed
endif ()
endif ()
if(MSVC)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /wd4100 /wd4996 /wd4244 /wd4706 /wd4702 /wd4127 /wd4701")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /wd4100 /wd4996 /wd4244 /wd4706 /wd4702 /wd4127 /wd4701")
set(cmake_create_config 1)
elseif(MINGW)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Werror -D_GNU_SOURCE=1")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Werror -D_GNU_SOURCE=1")
if (MSYS OR CMAKE_GENERATOR STREQUAL "Unix Makefiles")
execute_process(COMMAND echo ${CMAKE_CURRENT_SOURCE_DIR} WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})
execute_process(COMMAND sh autogen.sh WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})
execute_process(COMMAND sh ./configure WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})
file(COPY ./config.h DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/include/)
file(COPY ./json_config.h DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/include/)
else()
set(cmake_create_config 1)
endif()
elseif(UNIX)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Werror")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Werror -D_GNU_SOURCE")
execute_process(COMMAND echo ${CMAKE_CURRENT_SOURCE_DIR} WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})
execute_process(COMMAND sh autogen.sh WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})
execute_process(COMMAND ./configure WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})
file(COPY ./config.h DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/include/)
file(COPY ./json_config.h DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/include/)
endif() endif()
if (cmake_create_config) set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -O2")
file(REMOVE ./config.h) # make sure any stale one is gone
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/config.h.win32 ${CMAKE_CURRENT_BINARY_DIR}/include/config.h)
file(COPY ./json_config.h.win32 DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/include/)
file(RENAME ${CMAKE_CURRENT_BINARY_DIR}/include/json_config.h.win32 ${CMAKE_CURRENT_BINARY_DIR}/include/json_config.h)
endif ()
include_directories(${CMAKE_CURRENT_BINARY_DIR}/include) include(CTest)
# Set some packaging variables.
set(CPACK_PACKAGE_NAME "${PROJECT_NAME}")
set(CPACK_PACKAGE_VERSION_MAJOR "${PROJECT_VERSION_MAJOR}")
set(CPACK_PACKAGE_VERSION_MINOR "${PROJECT_VERSION_MINOR}")
set(CPACK_PACKAGE_VERSION_PATCH "${PROJECT_VERSION_PATCH}")
set(JSON_C_BUGREPORT "json-c@googlegroups.com")
set(CPACK_SOURCE_IGNORE_FILES
${PROJECT_SOURCE_DIR}/build
${PROJECT_SOURCE_DIR}/cmake-build-debug
${PROJECT_SOURCE_DIR}/pack
${PROJECT_SOURCE_DIR}/.idea
${PROJECT_SOURCE_DIR}/.DS_Store
${PROJECT_SOURCE_DIR}/.git
${PROJECT_SOURCE_DIR}/.vscode)
include(CheckSymbolExists)
include(CheckIncludeFile)
include(CheckIncludeFiles)
include(CheckCSourceCompiles)
include(CheckTypeSize)
include(CPack)
include(GNUInstallDirs)
include(CMakePackageConfigHelpers)
option(BUILD_SHARED_LIBS "Default to building shared libraries" ON)
option(BUILD_STATIC_LIBS "Default to building static libraries" ON)
if (BUILD_SHARED_LIBS)
add_definitions(-D JSON_C_DLL)
endif()
# Generate a release merge and test it to verify the correctness of republishing the package.
ADD_CUSTOM_TARGET(distcheck
COMMAND make package_source
COMMAND tar -xvf "${PROJECT_NAME}-${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}.${PROJECT_VERSION_PATCH}-Source.tar.gz"
COMMAND mkdir "${PROJECT_NAME}-${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}.${PROJECT_VERSION_PATCH}-Source/build"
COMMAND cmake "${PROJECT_NAME}-${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}.${PROJECT_VERSION_PATCH}-Source/" -B"./${PROJECT_NAME}-${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}.${PROJECT_VERSION_PATCH}-Source/build/"
COMMAND make -C "${PROJECT_NAME}-${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}.${PROJECT_VERSION_PATCH}-Source/build"
COMMAND make test -C "${PROJECT_NAME}-${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}.${PROJECT_VERSION_PATCH}-Source/build"
COMMAND rm -rf "${PROJECT_NAME}-${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}.${PROJECT_VERSION_PATCH}-Source"
)
# Enable or disable features. By default, all features are turned off.
option(DISABLE_BSYMBOLIC "Avoid linking with -Bsymbolic-function." OFF)
option(DISABLE_THREAD_LOCAL_STORAGE "Disable using Thread-Local Storage (HAVE___THREAD)." OFF)
option(DISABLE_WERROR "Avoid treating compiler warnings as fatal errors." OFF)
option(ENABLE_RDRAND "Enable RDRAND Hardware RNG Hash Seed." OFF)
option(ENABLE_THREADING "Enable partial threading support." OFF)
option(OVERRIDE_GET_RANDOM_SEED "Override json_c_get_random_seed() with custom code." OFF)
option(DISABLE_EXTRA_LIBS "Avoid linking against extra libraries, such as libbsd." OFF)
option(DISABLE_JSON_POINTER "Disable JSON pointer (RFC6901) and JSON patch support." OFF)
option(DISABLE_JSON_PATCH "Disable JSON patch (RFC6902) support." OFF)
option(NEWLOCALE_NEEDS_FREELOCALE "Work around newlocale bugs in old FreeBSD by calling freelocale" OFF)
option(BUILD_APPS "Default to building apps" ON)
if (UNIX OR MINGW OR CYGWIN)
list(APPEND CMAKE_REQUIRED_DEFINITIONS -D_GNU_SOURCE)
endif()
if (UNIX)
list(APPEND CMAKE_REQUIRED_LIBRARIES m)
endif()
if (MSVC)
list(APPEND CMAKE_REQUIRED_DEFINITIONS /D_CRT_SECURE_NO_DEPRECATE)
list(APPEND CMAKE_REQUIRED_FLAGS /wd4996)
endif()
if (NOT DISABLE_STATIC_FPIC)
# Use '-fPIC'/'-fPIE' option.
# This will allow other libraries to statically link in libjson-c.a
# which in turn prevents crashes in downstream apps that may use
# a different JSON library with identical symbol names.
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
endif()
check_include_file("fcntl.h" HAVE_FCNTL_H)
check_include_file("inttypes.h" HAVE_INTTYPES_H)
check_include_file(stdarg.h HAVE_STDARG_H)
check_include_file(strings.h HAVE_STRINGS_H)
check_include_file(string.h HAVE_STRING_H)
check_include_file(syslog.h HAVE_SYSLOG_H)
check_include_files("stdlib.h;stdarg.h;string.h;float.h" STDC_HEADERS)
check_include_file(unistd.h HAVE_UNISTD_H)
check_include_file(sys/types.h HAVE_SYS_TYPES_H)
check_include_file(sys/resource.h HAVE_SYS_RESOURCE_H) # for getrusage
check_include_file("dlfcn.h" HAVE_DLFCN_H)
check_include_file("endian.h" HAVE_ENDIAN_H)
check_include_file("limits.h" HAVE_LIMITS_H)
check_include_file("locale.h" HAVE_LOCALE_H)
check_include_file("memory.h" HAVE_MEMORY_H)
check_include_file(stdint.h HAVE_STDINT_H)
check_include_file(stdlib.h HAVE_STDLIB_H)
check_include_file(sys/cdefs.h HAVE_SYS_CDEFS_H)
check_include_file(sys/param.h HAVE_SYS_PARAM_H)
check_include_file(sys/random.h HAVE_SYS_RANDOM_H)
check_include_file(sys/stat.h HAVE_SYS_STAT_H)
check_include_file(xlocale.h HAVE_XLOCALE_H)
# Set json-c specific vars to stamp into json_config.h
# in a way that hopefully won't conflict with other
# projects that use json-c.
if (HAVE_INTTYPES_H)
set(JSON_C_HAVE_INTTYPES_H 1)
endif()
if (HAVE_STDINT_H)
set(JSON_C_HAVE_STDINT_H 1)
endif()
check_symbol_exists(_isnan "float.h" HAVE_DECL__ISNAN)
check_symbol_exists(_finite "float.h" HAVE_DECL__FINITE)
if ((MSVC AND NOT (MSVC_VERSION LESS 1800)) OR MINGW OR CYGWIN OR UNIX)
check_symbol_exists(INFINITY "math.h" HAVE_DECL_INFINITY)
check_symbol_exists(isinf "math.h" HAVE_DECL_ISINF)
check_symbol_exists(isnan "math.h" HAVE_DECL_ISNAN)
check_symbol_exists(nan "math.h" HAVE_DECL_NAN)
endif()
check_symbol_exists(_doprnt "stdio.h" HAVE_DOPRNT)
if (UNIX OR MINGW OR CYGWIN)
check_symbol_exists(snprintf "stdio.h" HAVE_SNPRINTF)
endif()
check_symbol_exists(vasprintf "stdio.h" HAVE_VASPRINTF)
check_symbol_exists(vsnprintf "stdio.h" HAVE_VSNPRINTF)
check_symbol_exists(vprintf "stdio.h" HAVE_VPRINTF)
check_symbol_exists(arc4random "stdlib.h" HAVE_ARC4RANDOM)
if (NOT HAVE_ARC4RANDOM AND DISABLE_EXTRA_LIBS STREQUAL "OFF")
check_include_file(bsd/stdlib.h HAVE_BSD_STDLIB_H)
if (HAVE_BSD_STDLIB_H)
list(APPEND CMAKE_REQUIRED_LIBRARIES "bsd")
unset(HAVE_ARC4RANDOM CACHE)
check_symbol_exists(arc4random "bsd/stdlib.h" HAVE_ARC4RANDOM)
if (NOT HAVE_ARC4RANDOM)
list(REMOVE_ITEM CMAKE_REQUIRED_LIBRARIES "bsd")
endif()
endif()
endif()
if (HAVE_FCNTL_H)
check_symbol_exists(open "fcntl.h" HAVE_OPEN)
endif()
if (HAVE_STDLIB_H)
check_symbol_exists(realloc "stdlib.h" HAVE_REALLOC)
endif()
if (HAVE_LOCALE_H)
check_symbol_exists(setlocale "locale.h" HAVE_SETLOCALE)
check_symbol_exists(uselocale "locale.h" HAVE_USELOCALE)
endif()
# uClibc *intentionally* crashes in duplocale(), at least as of:
# https://github.com/ffainelli/uClibc/blob/266bdc1/libc/misc/locale/locale.c#L1322
# So, if it looks like we're compiling for a system like that just disable
# locale handling entirely.
execute_process (COMMAND ${CMAKE_C_COMPILER} -dumpmachine ERROR_QUIET OUTPUT_VARIABLE CMAKE_GNU_C_MACHINE)
if (CMAKE_GNU_C_MACHINE MATCHES "uclibc")
message(STATUS "Detected uClibc compiler, disabling locale handling")
set(HAVE_SETLOCALE 0)
set(HAVE_USELOCALE 0)
endif()
if (HAVE_STRINGS_H)
check_symbol_exists(strcasecmp "strings.h" HAVE_STRCASECMP)
check_symbol_exists(strncasecmp "strings.h" HAVE_STRNCASECMP)
endif()
if (HAVE_STRING_H)
check_symbol_exists(strdup "string.h" HAVE_STRDUP)
check_symbol_exists(strerror "string.h" HAVE_STRERROR)
endif()
if (HAVE_SYSLOG_H)
check_symbol_exists(vsyslog "syslog.h" HAVE_VSYSLOG)
endif()
if (HAVE_SYS_RANDOM_H)
check_symbol_exists(getrandom "sys/random.h" HAVE_GETRANDOM)
endif()
if (HAVE_SYS_RESOURCE_H)
check_symbol_exists(getrusage "sys/resource.h" HAVE_GETRUSAGE)
endif()
check_symbol_exists(strtoll "stdlib.h" HAVE_STRTOLL)
check_symbol_exists(strtoull "stdlib.h" HAVE_STRTOULL)
set(json_c_strtoll "strtoll")
if (NOT HAVE_STRTOLL)
# Use _strtoi64 if strtoll is not available.
check_symbol_exists(_strtoi64 "stdlib.h" __have_strtoi64)
if (__have_strtoi64)
#set(HAVE_STRTOLL 1)
set(json_c_strtoll "_strtoi64")
endif()
endif()
set(json_c_strtoull "strtoull")
if (NOT HAVE_STRTOULL)
# Use _strtoui64 if strtoull is not available.
check_symbol_exists(_strtoui64 "stdlib.h" __have_strtoui64)
if (__have_strtoui64)
#set(HAVE_STRTOULL 1)
set(json_c_strtoull "_strtoui64")
endif()
endif()
check_type_size(int SIZEOF_INT)
check_type_size(int64_t SIZEOF_INT64_T)
check_type_size(long SIZEOF_LONG)
check_type_size("long long" SIZEOF_LONG_LONG)
check_type_size("size_t" SIZEOF_SIZE_T)
if (MSVC)
list(APPEND CMAKE_EXTRA_INCLUDE_FILES BaseTsd.h)
check_type_size("SSIZE_T" SIZEOF_SSIZE_T)
else()
check_type_size("ssize_t" SIZEOF_SSIZE_T)
endif()
check_c_source_compiles(
"
extern void json_object_get();
__asm__(\".section .gnu.json_object_get\\n\\t.ascii \\\"Please link against libjson-c instead of libjson\\\"\\n\\t.text\");
int main(int c, char *v) { return 0;}
"
HAS_GNU_WARNING_LONG)
check_c_source_compiles(
"int main() { int i, x = 0; i = __sync_add_and_fetch(&x,1); return x; }"
HAVE_ATOMIC_BUILTINS)
if (NOT DISABLE_THREAD_LOCAL_STORAGE)
check_c_source_compiles(
"__thread int x = 0; int main() { return 0; }"
HAVE___THREAD)
if (HAVE___THREAD)
set(SPEC___THREAD __thread)
elseif (MSVC)
set(SPEC___THREAD __declspec(thread))
endif()
endif()
# Hardware random number is not available on Windows? Says, config.h.win32. Best to preserve compatibility.
if (WIN32)
set(ENABLE_RDRAND 0)
endif()
# Once we've done basic symbol/header searches let's add them in.
configure_file(${PROJECT_SOURCE_DIR}/cmake/config.h.in ${PROJECT_BINARY_DIR}/config.h)
message(STATUS "Wrote ${PROJECT_BINARY_DIR}/config.h")
configure_file(${PROJECT_SOURCE_DIR}/cmake/json_config.h.in ${PROJECT_BINARY_DIR}/json_config.h)
message(STATUS "Wrote ${PROJECT_BINARY_DIR}/json_config.h")
if (NOT DEFINED CMAKE_C_COMPILER_FRONTEND_VARIANT OR "${CMAKE_C_COMPILER_FRONTEND_VARIANT}" STREQUAL "") # only available in cmake 3.14+
if ("${CMAKE_C_COMPILER_ID}" STREQUAL "MSVC")
set(CMAKE_C_COMPILER_FRONTEND_VARIANT "MSVC")
elseif ("${CMAKE_C_COMPILER_ID}" STREQUAL "GNU")
set(CMAKE_C_COMPILER_FRONTEND_VARIANT "GNU")
elseif ("${CMAKE_C_COMPILER_ID}" STREQUAL "Clang")
# Detect clang-cl.exe, it is Clang but with MSVC compatible command line arguments
execute_process (COMMAND ${CMAKE_C_COMPILER} -? ERROR_QUIET OUTPUT_QUIET RESULT_VARIABLE _clang_result)
if (_clang_result EQUAL 0)
set(CMAKE_C_COMPILER_FRONTEND_VARIANT "MSVC")
else()
set(CMAKE_C_COMPILER_FRONTEND_VARIANT "GNU")
message(STATUS, "clang result is NOT 0")
endif()
endif()
endif()
if ("${CMAKE_C_COMPILER_FRONTEND_VARIANT}" STREQUAL "GNU" OR "${CMAKE_C_COMPILER_FRONTEND_VARIANT}" STREQUAL "Clang")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -ffunction-sections -fdata-sections")
if ("${DISABLE_WERROR}" STREQUAL "OFF")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Werror")
endif()
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wcast-qual")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-error=deprecated-declarations")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wextra")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wwrite-strings")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-unused-parameter")
if (NOT WIN32)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wstrict-prototypes")
endif()
add_definitions(-D_GNU_SOURCE)
if ("${CMAKE_C_COMPILER_FRONTEND_VARIANT}" STREQUAL "Clang")
# Remove this for 1.0 when we can bump the ABI and actually fix these warnings.
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-shorten-64-to-32")
endif()
elseif ("${CMAKE_C_COMPILER_FRONTEND_VARIANT}" STREQUAL "MSVC")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /DEBUG")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /wd4100")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /wd4996")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /wd4244")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /wd4706")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /wd4702")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /wd4127")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /wd4701")
endif()
if (NOT ("${CMAKE_C_COMPILER_FRONTEND_VARIANT}" STREQUAL "MSVC"))
check_c_source_compiles(
"
/* uClibc toolchains without threading barf when _REENTRANT is defined */
#define _REENTRANT 1
#include <sys/types.h>
int main (void)
{
return 0;
}
"
REENTRANT_WORKS
)
if (REENTRANT_WORKS)
add_compile_options("-D_REENTRANT")
endif()
# OSX Mach-O doesn't support linking with '-Bsymbolic-functions'.
# Others may not support it, too.
list(APPEND CMAKE_REQUIRED_LIBRARIES "-Wl,-Bsymbolic-functions")
check_c_source_compiles(
"
int main (void)
{
return 0;
}
"
BSYMBOLIC_WORKS
)
list(REMOVE_ITEM CMAKE_REQUIRED_LIBRARIES "-Wl,-Bsymbolic-functions")
if (DISABLE_BSYMBOLIC STREQUAL "OFF" AND BSYMBOLIC_WORKS)
set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,-Bsymbolic-functions")
# XXX need cmake>=3.13 for this:
#add_link_options("-Wl,-Bsymbolic-functions")
endif()
file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/check-version-script.sym" "TEST { global: *; };")
list(APPEND CMAKE_REQUIRED_LIBRARIES "-Wl,--version-script,${CMAKE_CURRENT_BINARY_DIR}/check-version-script.sym")
check_c_source_compiles(
"
int main (void)
{
return 0;
}
"
VERSION_SCRIPT_WORKS
)
list(REMOVE_ITEM CMAKE_REQUIRED_LIBRARIES "-Wl,--version-script,${CMAKE_CURRENT_BINARY_DIR}/check-version-script.sym")
if (VERSION_SCRIPT_WORKS)
set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,--version-script,${CMAKE_CURRENT_SOURCE_DIR}/json-c.sym")
endif()
endif()
if ($ENV{VALGRIND})
# Build so that valgrind doesn't complain about linkhash.c
add_definitions(-DVALGRIND=1)
endif()
set(JSON_C_PUBLIC_HEADERS set(JSON_C_PUBLIC_HEADERS
./json.h # Note: config.h is _not_ included here
${CMAKE_CURRENT_BINARY_DIR}/include/config.h ${PROJECT_BINARY_DIR}/json_config.h
${CMAKE_CURRENT_BINARY_DIR}/include/json_config.h
./arraylist.h ${PROJECT_BINARY_DIR}/json.h
./debug.h ${PROJECT_SOURCE_DIR}/arraylist.h
./json_c_version.h ${PROJECT_SOURCE_DIR}/debug.h
./json_inttypes.h ${PROJECT_SOURCE_DIR}/json_c_version.h
./json_object.h ${PROJECT_SOURCE_DIR}/json_inttypes.h
./json_pointer.h ${PROJECT_SOURCE_DIR}/json_object.h
./json_tokener.h ${PROJECT_SOURCE_DIR}/json_object_iterator.h
./json_util.h ${PROJECT_SOURCE_DIR}/json_tokener.h
./linkhash.h ${PROJECT_SOURCE_DIR}/json_types.h
./printbuf.h ${PROJECT_SOURCE_DIR}/json_util.h
${PROJECT_SOURCE_DIR}/json_visit.h
${PROJECT_SOURCE_DIR}/linkhash.h
${PROJECT_SOURCE_DIR}/printbuf.h
) )
set(JSON_C_HEADERS set(JSON_C_HEADERS
${JSON_C_PUBLIC_HEADERS} ${JSON_C_PUBLIC_HEADERS}
./json_object_private.h ${PROJECT_SOURCE_DIR}/json_object_private.h
./random_seed.h ${PROJECT_SOURCE_DIR}/json_pointer_private.h
./strerror_override.h ${PROJECT_SOURCE_DIR}/random_seed.h
./strerror_override_private.h ${PROJECT_SOURCE_DIR}/strerror_override.h
./math_compat.h ${PROJECT_SOURCE_DIR}/math_compat.h
./snprintf_compat.h ${PROJECT_SOURCE_DIR}/snprintf_compat.h
./strdup_compat.h ${PROJECT_SOURCE_DIR}/strdup_compat.h
./vasprintf_compat.h ${PROJECT_SOURCE_DIR}/vasprintf_compat.h
) )
set(JSON_C_SOURCES set(JSON_C_SOURCES
./arraylist.c ${PROJECT_SOURCE_DIR}/arraylist.c
./debug.c ${PROJECT_SOURCE_DIR}/debug.c
./json_c_version.c ${PROJECT_SOURCE_DIR}/json_c_version.c
./json_object.c ${PROJECT_SOURCE_DIR}/json_object.c
./json_object_iterator.c ${PROJECT_SOURCE_DIR}/json_object_iterator.c
./json_pointer.c ${PROJECT_SOURCE_DIR}/json_tokener.c
./json_tokener.c ${PROJECT_SOURCE_DIR}/json_util.c
./json_util.c ${PROJECT_SOURCE_DIR}/json_visit.c
./json_visit.c ${PROJECT_SOURCE_DIR}/linkhash.c
./linkhash.c ${PROJECT_SOURCE_DIR}/printbuf.c
./printbuf.c ${PROJECT_SOURCE_DIR}/random_seed.c
./random_seed.c ${PROJECT_SOURCE_DIR}/strerror_override.c
./strerror_override.c
) )
add_library(json-c if (NOT DISABLE_JSON_POINTER)
SHARED set(JSON_C_PUBLIC_HEADERS ${JSON_C_PUBLIC_HEADERS} ${PROJECT_SOURCE_DIR}/json_pointer.h)
set(JSON_C_SOURCES ${JSON_C_SOURCES} ${PROJECT_SOURCE_DIR}/json_pointer.c)
set(JSON_H_JSON_POINTER "#include \"json_pointer.h\"")
if (NOT DISABLE_JSON_PATCH)
set(JSON_C_PUBLIC_HEADERS ${JSON_C_PUBLIC_HEADERS} ${PROJECT_SOURCE_DIR}/json_patch.h)
set(JSON_C_SOURCES ${JSON_C_SOURCES} ${PROJECT_SOURCE_DIR}/json_patch.c)
set(JSON_H_JSON_PATCH "#include \"json_patch.h\"")
endif()
else()
set(JSON_H_JSON_POINTER "")
set(JSON_H_JSON_PATCH "")
endif()
configure_file(json.h.cmakein ${PROJECT_BINARY_DIR}/json.h @ONLY)
include_directories(${PROJECT_SOURCE_DIR})
include_directories(${PROJECT_BINARY_DIR})
add_subdirectory(doc)
# "uninstall" custom target for make generators in unix like operating systems
# and if that target is not present
if (CMAKE_GENERATOR STREQUAL "Unix Makefiles")
if(NOT TARGET uninstall)
add_custom_target(uninstall
COMMAND cat ${PROJECT_BINARY_DIR}/install_manifest.txt | xargs rm
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
)
endif()
endif()
# XXX for a normal full distribution we'll need to figure out
# XXX how to build both shared and static libraries.
# Probably leverage that to build a local VALGRIND=1 library for testing too.
add_library(${PROJECT_NAME}
${JSON_C_SOURCES} ${JSON_C_SOURCES}
${JSON_C_HEADERS} ${JSON_C_HEADERS}
) )
set_target_properties(${PROJECT_NAME} PROPERTIES
add_library(json-c-static VERSION 5.3.0
STATIC SOVERSION 5)
${JSON_C_SOURCES} list(APPEND CMAKE_TARGETS ${PROJECT_NAME})
${JSON_C_HEADERS} # If json-c is used as subroject it set to target correct interface -I flags and allow
# to build external target without extra include_directories(...)
target_include_directories(${PROJECT_NAME}
PUBLIC
$<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}>
$<BUILD_INTERFACE:${PROJECT_BINARY_DIR}>
) )
set_property(TARGET json-c PROPERTY C_STANDARD 99) target_link_libraries(${PROJECT_NAME} PUBLIC ${CMAKE_REQUIRED_LIBRARIES})
set_property(TARGET json-c-static PROPERTY C_STANDARD 99)
set_target_properties(json-c-static PROPERTIES OUTPUT_NAME json-c)
install(TARGETS json-c json-c-static # Allow to build static and shared libraries at the same time
RUNTIME DESTINATION bin if (BUILD_STATIC_LIBS AND BUILD_SHARED_LIBS)
LIBRARY DESTINATION lib set(STATIC_LIB ${PROJECT_NAME}-static)
ARCHIVE DESTINATION lib add_library(${STATIC_LIB} STATIC
) ${JSON_C_SOURCES}
${JSON_C_HEADERS}
)
target_include_directories(${PROJECT_NAME}-static
PUBLIC
$<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}>
$<BUILD_INTERFACE:${PROJECT_BINARY_DIR}>
)
install(FILES ${JSON_C_PUBLIC_HEADERS} DESTINATION ${CMAKE_INSTALL_PREFIX}/include/json-c ) target_link_libraries(${PROJECT_NAME}-static PUBLIC ${CMAKE_REQUIRED_LIBRARIES})
if (UNIX) # rename the static library
set(prefix ${CMAKE_INSTALL_PREFIX}) if (NOT MSVC)
set(exec_prefix ${CMAKE_INSTALL_PREFIX}/bin) set_target_properties(${STATIC_LIB} PROPERTIES
set(libdir ${CMAKE_INSTALL_PREFIX}/lib) OUTPUT_NAME ${PROJECT_NAME}
set(includedir ${CMAKE_INSTALL_PREFIX}/include) )
set(VERSION ${PROJECT_VERSION}) endif()
configure_file(json-c.pc.in json-c.pc @ONLY) list(APPEND CMAKE_TARGETS ${STATIC_LIB})
set(INSTALL_PKGCONFIG_DIR "${CMAKE_INSTALL_PREFIX}/lib/pkgconfig" CACHE PATH "Installation directory for pkgconfig (.pc) files")
install(FILES ${CMAKE_BINARY_DIR}/json-c.pc DESTINATION "${INSTALL_PKGCONFIG_DIR}")
endif () endif ()
# Always create new install dirs with 0755 permissions, regardless of umask
set(CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS
OWNER_READ
OWNER_WRITE
OWNER_EXECUTE
GROUP_READ
GROUP_EXECUTE
WORLD_READ
WORLD_EXECUTE
)
install(TARGETS ${CMAKE_TARGETS}
EXPORT ${PROJECT_NAME}-targets
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} ${CMAKE_INSTALL_INCLUDEDIR}/json-c
)
install(EXPORT ${PROJECT_NAME}-targets
FILE ${PROJECT_NAME}-targets.cmake
NAMESPACE ${PROJECT_NAME}::
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}
)
configure_package_config_file(
"cmake/Config.cmake.in"
${PROJECT_BINARY_DIR}/${PROJECT_NAME}-config.cmake
INSTALL_DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}"
)
install(
FILES ${PROJECT_BINARY_DIR}/${PROJECT_NAME}-config.cmake
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}
)
SET(prefix ${CMAKE_INSTALL_PREFIX})
# exec_prefix is prefix by default and CMake does not have the
# concept.
SET(exec_prefix ${CMAKE_INSTALL_PREFIX})
SET(libdir ${CMAKE_INSTALL_FULL_LIBDIR})
SET(includedir ${CMAKE_INSTALL_FULL_INCLUDEDIR})
SET(VERSION ${PROJECT_VERSION})
# Linking against the static json-c requires
# dependent packages to include additional libs:
SET(LIBS_LIST ${CMAKE_REQUIRED_LIBRARIES})
# Note: We would need cmake >= 3.12 in order to use list(TRANSFORM ...)
function(list_transform_prepend var prefix)
set(temp "")
foreach(f ${${var}})
list(APPEND temp "${prefix}${f}")
endforeach()
set(${var} "${temp}" PARENT_SCOPE)
endfunction()
list_transform_prepend(LIBS_LIST "-l")
string(REPLACE ";" " " LIBS "${LIBS_LIST}")
configure_file(json-c.pc.in json-c.pc @ONLY)
set(INSTALL_PKGCONFIG_DIR "${CMAKE_INSTALL_LIBDIR}/pkgconfig" CACHE PATH "Installation directory for pkgconfig (.pc) files")
install(FILES ${PROJECT_BINARY_DIR}/json-c.pc DESTINATION "${INSTALL_PKGCONFIG_DIR}")
install(FILES ${JSON_C_PUBLIC_HEADERS} DESTINATION ${CMAKE_INSTALL_FULL_INCLUDEDIR}/json-c)
if (CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME AND BUILD_TESTING AND
(NOT MSVC OR NOT (MSVC_VERSION LESS 1800)) # Tests need at least VS2013
)
add_subdirectory(tests)
endif()
if (CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME AND BUILD_APPS)
# skip apps when we're included in someone else's build
if (NOT MSVC) # cmd line apps don't built on Windows currently.
add_subdirectory(apps)
endif()
endif()

273
ChangeLog
View File

@@ -1,4 +1,253 @@
0.17 (up to commit 077661f, 2023-08-08)
========================================
Deprecated and removed features:
--------------------------------
* None
New features
------------
* json_patch: add first implementation only with patch application
* Add --disable-static and --disable-dynamic options to the cmake-configure script.
* Add -DBUILD_APPS=NO option to disable app build
* Minimum cmake version is now 3.9
Significant changes and bug fixes
---------------------------------
* When serializing with JSON_C_TO_STRING_PRETTY set, keep the opening and
closing curly or square braces on same line for empty objects or arrays.
* Disable locale handling when targeting a uClibc system due to problems
with its duplocale() function.
* When parsing with JSON_TOKENER_STRICT set, integer overflow/underflow
now result in a json_tokener_error_parse_number. Without that flag
values are capped at INT64_MIN/UINT64_MAX.
* Fix memory leak with emtpy strings in json_object_set_string
* json_object_from_fd_ex: fail if file is too large (>=INT_MAX bytes)
* Add back json_number_chars, but only because it's part of the public API.
* Entirely drop mode bits from open(O_RDONLY) to avoid warnings on certain
platforms.
* Specify dependent libraries, including -lbsd, in a more consistent way so
linking against a static json-c works better
* Fix a variety of build problems and add & improve tests
* Update RFC reference to https://www.rfc-editor.org/rfc/rfc8259
***
0.16 (up to commit 66dcdf5, 2022-04-13)
========================================
Deprecated and removed features:
--------------------------------
* JSON_C_OBJECT_KEY_IS_CONSTANT is deprecated in favor of
JSON_C_OBJECT_ADD_CONSTANT_KEY
* Direct access to lh_table and lh_entry structure members is deprecated.
Use access functions instead, lh_table_head(), lh_entry_next(), etc...
* Drop REFCOUNT_DEBUG code.
New features
------------
* The 0.16 release introduces no new features
Build changes
-------------
* Add a DISABLE_EXTRA_LIBS option to skip using libbsd
* Add a DISABLE_JSON_POINTER option to skip compiling in json_pointer support.
Significant changes and bug fixes
---------------------------------
* Cap string length at INT_MAX to avoid various issues with very long strings.
* json_object_deep_copy: fix deep copy of strings containing '\0'
* Fix read past end of buffer in the "json_parse" command
* Avoid out of memory accesses in the locally provided vasprintf() function
(for those platforms that use it)
* Handle allocation failure in json_tokener_new_ex
* Fix use-after-free in json_tokener_new_ex() in the event of printbuf_new() returning NULL
* printbuf_memset(): set gaps to zero - areas within the print buffer which
have not been initialized by using printbuf_memset
* printbuf: return -1 on invalid arguments (len < 0 or total buffer > INT_MAX)
* sprintbuf(): propagate printbuf_memappend errors back to the caller
Optimizations
--------------
* Speed up parsing by replacing ctype functions with simplified, faster
non-locale-sensitive ones in json_tokener and json_object_to_json_string.
* Neither vertical tab nor formfeed are considered whitespace per the JSON spec
* json_object: speed up creation of objects, calloc() -> malloc() + set fields
* Avoid needless extra strlen() call in json_c_shallow_copy_default() and
json_object_equal() when the object is known to be a json_type_string.
Other changes
-------------
* Validate size arguments in arraylist functions.
* Use getrandom() if available; with GRND_NONBLOCK to allow use of json-c
very early during boot, such as part of cryptsetup.
* Use arc4random() if it's available.
* random_seed: on error, continue to next method instead of exiting the process
* Close file when unable to read from /dev/urandom in get_dev_random_seed()
***
0.15 (up to commit 870965e, 2020/07/26)
========================================
Deprecated and removed features:
--------------------------------
* Deprecate `array_list_new()` in favor of `array_list_new2()`
* Remove the THIS_FUNCTION_IS_DEPRECATED define.
* Remove config.h.win32
New features
------------
* Add a `JSON_TOKENER_ALLOW_TRAILING_CHARS` flag to allow multiple objects
to be parsed even when `JSON_TOKENER_STRICT` is set.
* Add `json_object_new_array_ext(int)` and `array_list_new_2(int)` to allow
arrays to be allocated with the exact size needed, when known.
* Add `json_object_array_shrink()` (and `array_list_shrink()`) and use it in
json_tokener to minimize the amount of memory used.
* Add a json_parse binary, for use in testing changes (not installed, but
available in the apps directory).
Build changes
-------------
* #639/#621 - Add symbol versions to all exported symbols
* #508/#634 - Always enable -fPIC to allow use of the json-c static library in
other libraries
* Build both static and shared libraries at the same time.
* #626 - Restore compatibility with cmake 2.8
* #471 - Always create directories with mode 0755, regardless of umask.
* #606/#604 - Improve support for OSes like AIX and IBM i, as well as for
MINGW32 and old versions of MSVC
* #451/#617 - Add a DISABLE_THREAD_LOCAL_STORAGE cmake option to disable
the use of thread-local storage.
Significant changes and bug fixes
---------------------------------
* Split the internal json_object structure into several sub-types, one for
each json_type (json_object_object, json_object_string, etc...).
This improves memory usage and speed, with the benchmark under
bench/ report 5.8% faster test time and 6%(max RSS)-12%(peak heap)
less memory usage.
Memory used just for json_object structures decreased 27%, so use cases
with fewer arrays and/or strings would benefit more.
* Minimize memory usage in array handling in json_tokener by shrinking
arrays to the exact number of elements parsed. On bench/ benchmark:
9% faster test time, 39%(max RSS)-50%(peak heap) less memory usage.
Add json_object_array_shrink() and array_list_shrink() functions.
* #616 - Parsing of surrogate pairs in unicode escapes now properly handles
incremental parsing.
* Fix incremental parsing of numbers, especially those with exponents, e.g.
so parsing "[0", "e+", "-]" now properly returns an error.
Strict mode now rejects missing exponents ("0e").
* Successfully return number objects at the top level even when they are
followed by a "-", "." or "e". This makes parsing things like "123-45"
behave consistently with things like "123xyz".
Other changes
-------------
* #589 - Detect broken RDRAND during initialization; also, fix segfault
in the CPUID check.
* #592 - Fix integer overflows to prevert out of bounds write on large input.
* Protect against division by zero in linkhash, when created with zero size.
* #602 - Fix json_parse_uint64() internal error checking, leaving the retval
untouched in more failure cases.
* #614 - Prevent truncation when custom double formatters insert extra \0's
***
0.14 (up to commit 9ed00a6, 2020/04/14)
=========================================
Deprecated and removed features:
--------------------------------
* bits.h has been removed
* lh_abort() has been removed
* lh_table_lookup() has been removed, use lh_table_lookup_ex() instead.
* Remove TRUE and FALSE defines, use 1 and 0 instead.
Build changes:
--------------
## Deprecated and removed features:
* bits.h has been removed
* lh_abort() has been removed
* lh_table_lookup() has been removed, use lh_table_lookup_ex() instead.
* Remove TRUE and FALSE defines, use 1 and 0 instead.
* autoconf support, including autogen.sh, has been removed. See details about cmake, below.
* With the addition of json_tokener_get_parse_end(), access to internal fields of json_tokener, as well as use of many other symbols and types in json_tokener.h, is deprecated now.
* The use of Android.configure.mk to build for Android no longer works, and it is unknown how (or if) the new cmake-based build machinery can be used.
* Reports of success, or pull requests to correct issues are welcome.
## Notable improvements and new features
### Builds and documentation
* Build machinery has been switched to CMake. See README.md for details about how to build.
* TL;DR: `mkdir build ; cd build ; cmake -DCMAKE_INSTALL_PREFIX=/some/path ../json-c ; make all test install`
* To ease the transition, there is a `cmake-configure` wrapper that emulates the old autoconf-based configure script.
* This has enabled improvements to the build on Windows system; also all public functions have been fixed to be properly exported. For best results, use Visual Studio 2015 or newer.
* The json-c style guide has been updated to specify the use of clang-format, and all code has been reformatted.
* Since many lines of code have trivial changes now, when using git blame, be sure to specify -w
* Numerous improvements have been made to the documentation including function effects on refcounts, when passing a NULL is safe, and so on.
### json_tokener changes
* Added a json_tokener_get_parse_end() function to replace direct access of tok->char_offset.
* The char_offset field, and the rest of the json_tokener structure remain exposed for now, but expect a future release to hide it like is done with json_object_private.h
* json_tokener_parse_ex() now accepts a new JSON_TOKENER_VALIDATE_UTF8 flag to validate that input is UTF8.
* If validation fails, json_tokener_get_error(tok) will return json_tokener_error_parse_utf8_string (see enum json_tokener_error).
### Other changes and additions
* Add support for unsigned 64-bit integers, uint64_t, to gain one extra bit of magnitude for positive ints.
* json_tokener will now parse values up to UINT64_MAX (18446744073709551615)
* Existing methods returning int32_t or int64_t will cap out-of-range values at INT32_MAX or INT64_MAX, preserving existing behavior.
* The implementation includes the possibility of easily extending this to larger sizes in the future.
* A total of 7 new functions were added:
* json_object_get_uint64 ( struct json_object const* jso )
* json_object_new_uint64 ( uint64_t i )
* json_object_set_uint64 ( struct json_object* jso, uint64_t new_value )
* json_parse_uint64 ( char const* buf, uint64_t* retval )
* See description of uint64 support, above.
* json_tokener_get_parse_end ( struct json_tokener* tok )
* See details under "json_tokener changes", above.
* json_object_from_fd_ex ( int fd, int in_depth )
* Allows the max nesting depth to be specified.
* json_object_new_null ( )
* Simply returns NULL. Its use is not recommended.
* The size of struct json_object has decreased from 96 bytes to 88 bytes.
### Testing
* Many updates were made to test cases, increasing code coverage.
* There is now a quick way (JSONC_TEST_TRACE=1) to turn on shell tracing in tests.
* To run tests, use `make test`; the old "check" target no longer exists.
## Significant bug fixes
For the full list of issues and pull requests since the previous release, please see issues_closed_for_0.14.md
* [Issue #389](https://github.com/json-c/json-c/issues/389): Add an assert to explicitly crash when _ref_count is corrupted, instead of a later "double free" error.
* [Issue #407](https://github.com/json-c/json-c/issues/407): fix incorrect casts in calls to ctype functions (isdigit and isspace) so we don't crash when asserts are enabled on certain platforms and characters > 128 are parsed.
* [Issue #418](https://github.com/json-c/json-c/issues/418): Fix docs for json_util_from_fd and json_util_from_file to say that they return NULL on failures.
* [Issue #422](https://github.com/json-c/json-c/issues/422): json_object.c:set errno in json_object_get_double() when called on a json_type_string object with bad content.
* [Issue #453](https://github.com/json-c/json-c/issues/453): Fixed misalignment in JSON serialization when JSON_C_TO_STRING_SPACED and JSON_C_TO_STRING_PRETTY are used together.
* [Issue #463](https://github.com/json-c/json-c/issues/463): fix newlocale() call to use LC_NUMERIC_MASK instead of LC_NUMERIC, and remove incorrect comment.
* [Issue #486](https://github.com/json-c/json-c/issues/486): append a missing ".0" to negative double values to ensure they are serialized as floating point numbers.
* [Issue #488](https://github.com/json-c/json-c/issues/488): use JSON_EXPORT on functions so they are properly exported on Windows.
* [Issue #539](https://github.com/json-c/json-c/issues/539): use an internal-only serializer function in json_object_new_double_s() to avoid potential conflicts with user code that uses the json_object_userdata_to_json_string serializer.
***
0.13.1 (up to commit 0f814e5, 2018/03/04)
=========================================
* Bump the major version of the .so library generated up to 4.0 to avoid
conflicts because some downstream packagers of json-c had already done
their own bump to ".so.3" for a much older 0.12 release.
* Add const size_t json_c_object_sizeof()
* Avoid invalid free (and thus a segfault) when ref_count gets < 0
* PR#394: fix handling of custom double formats that include a ".0"
* Avoid uninitialized variable warnings in json_object_object_foreach
* Issue #396: fix build for certain uClibc based systems.
* Add a top level fuzz directory for fuzzers run by OSS-Fuzz
0.13 (up to commit 5dae561, 2017/11/29) 0.13 (up to commit 5dae561, 2017/11/29)
================================= =================================
@@ -13,7 +262,7 @@ See issues_closed_for_0.13.md for a complete list.
Deprecated and removed features: Deprecated and removed features:
-------------------------------- --------------------------------
* All internal use of bits.h has been eliminated. The file will be removed. * All internal use of bits.h has been eliminated. The file will be removed.
Do not use: hexdigit(), error_ptr(), error_descrition() and it_error() Do not use: hexdigit(), error_ptr(), error_descrition() and it_error()
* lh_abort() is deprecated. It will be removed. * lh_abort() is deprecated. It will be removed.
Behavior changes: Behavior changes:
@@ -25,7 +274,7 @@ Behavior changes:
* Use size_t for array length and size. Platforms where sizeof(size_t) != sizeof(int) may not be backwards compatible * Use size_t for array length and size. Platforms where sizeof(size_t) != sizeof(int) may not be backwards compatible
See commits 45c56b, 92e9a5 and others. See commits 45c56b, 92e9a5 and others.
* Check for failue when allocating memory, returning NULL and errno=ENOMEM. * Check for failure when allocating memory, returning NULL and errno=ENOMEM.
See commit 2149a04. See commit 2149a04.
* Change json_object_object_add() return type from void to int, and will return -1 on failures, instead of exiting. (Note: this is not an ABI change) * Change json_object_object_add() return type from void to int, and will return -1 on failures, instead of exiting. (Note: this is not an ABI change)
@@ -156,11 +405,11 @@ List of new functions added:
* Make the json_tokener_errors array local. It has been deprecated for * Make the json_tokener_errors array local. It has been deprecated for
a while, and json_tokener_error_desc() should be used instead. a while, and json_tokener_error_desc() should be used instead.
* change the floating point output format to %.17g so values with * change the floating point output format to %.17g so values with
more than 6 digits show up in the output. more than 6 digits show up in the output.
* Remove the old libjson.so name compatibility support. The library is * Remove the old libjson.so name compatibility support. The library is
only created as libjson-c.so now and headers are only installed only created as libjson-c.so now and headers are only installed
into the ${prefix}/json-c directory. into the ${prefix}/json-c directory.
* When supported by the linker, add the -Bsymbolic-functions flag. * When supported by the linker, add the -Bsymbolic-functions flag.
@@ -216,7 +465,7 @@ List of new functions added:
* Add an alternative iterator implementation, see json_object_iterator.h * Add an alternative iterator implementation, see json_object_iterator.h
* Make json_object_iter public to enable external use of the * Make json_object_iter public to enable external use of the
json_object_object_foreachC macro. json_object_object_foreachC macro.
* Add a printbuf_memset() function to provide an effecient way to set and * Add a printbuf_memset() function to provide an efficient way to set and
append things like whitespace indentation. append things like whitespace indentation.
* Adjust json_object_is_type and json_object_get_type so they return * Adjust json_object_is_type and json_object_get_type so they return
json_type_null for NULL objects and handle NULL passed to json_type_null for NULL objects and handle NULL passed to
@@ -226,7 +475,7 @@ List of new functions added:
* Allow json_tokener_parse_ex() to be re-used to parse multiple object. * Allow json_tokener_parse_ex() to be re-used to parse multiple object.
Also, fix some parsing issues with capitalized hexadecimal numbers and Also, fix some parsing issues with capitalized hexadecimal numbers and
number in E notation. number in E notation.
* Add json_tokener_get_error() and json_tokener_error_desc() to better * Add json_tokener_get_error() and json_tokener_error_desc() to better
encapsulate the process of retrieving errors while parsing. encapsulate the process of retrieving errors while parsing.
* Various improvements to the documentation of many functions. * Various improvements to the documentation of many functions.
* Add new json_object_array_sort() function. * Add new json_object_array_sort() function.
@@ -273,7 +522,7 @@ List of new functions added:
Brent Miller, bdmiller at yahoo dash inc dot com Brent Miller, bdmiller at yahoo dash inc dot com
* Disable REFCOUNT_DEBUG by default in json_object.c * Disable REFCOUNT_DEBUG by default in json_object.c
* Don't use this as a variable, so we can compile with a C++ compiler * Don't use this as a variable, so we can compile with a C++ compiler
* Add casts from void* to type of assignment when using malloc * Add casts from void* to type of assignment when using malloc
* Add #ifdef __cplusplus guards to all of the headers * Add #ifdef __cplusplus guards to all of the headers
* Add typedefs for json_object, json_tokener, array_list, printbuf, lh_table * Add typedefs for json_object, json_tokener, array_list, printbuf, lh_table
Michael Clark, <michael@metaparadigm.com> Michael Clark, <michael@metaparadigm.com>
@@ -302,14 +551,14 @@ List of new functions added:
0.7 0.7
=== ===
* Add escaping of backslash to json output * Add escaping of backslash to json output
* Add escaping of foward slash on tokenizing and output * Add escaping of forward slash on tokenizing and output
* Changes to internal tokenizer from using recursion to * Changes to internal tokenizer from using recursion to
using a depth state structure to allow incremental parsing using a depth state structure to allow incremental parsing
0.6 0.6
=== ===
* Fix bug in escaping of control characters * Fix bug in escaping of control characters
Johan Bj<EFBFBD>rklund, johbjo09 at kth dot se Johan Björklund, johbjo09 at kth dot se
* Remove include "config.h" from headers (should only * Remove include "config.h" from headers (should only
be included from .c files) be included from .c files)
Michael Clark <michael@metaparadigm.com> Michael Clark <michael@metaparadigm.com>
@@ -357,13 +606,13 @@ List of new functions added:
Added a Win32/Win64 compliant implementation of strndup Added a Win32/Win64 compliant implementation of strndup
* json_util.c - C. Watford (christopher.watford@gmail.com) * json_util.c - C. Watford (christopher.watford@gmail.com)
Added cast and mask to suffice size_t v. unsigned int conversion Added cast and mask to suffice size_t v. unsigned int conversion
correctness correctness
* json_tokener.c - sign reversal issue on error info for nested object parse * json_tokener.c - sign reversal issue on error info for nested object parse
spotted by Johan Bj<EFBFBD>rklund (johbjo09 at kth.se) spotted by Johan Björklund (johbjo09 at kth.se)
* json_object.c - escape " in json_escape_str * json_object.c - escape " in json_escape_str
* Change to automake and libtool to build shared and static library * Change to automake and libtool to build shared and static library
Michael Clark <michael@metaparadigm.com> Michael Clark <michael@metaparadigm.com>
0.1 0.1
=== ===
* initial release * initial release

View File

@@ -1,3 +1,2 @@
See README.md for installation instructions. See README.md for installation instructions.

View File

@@ -1,118 +0,0 @@
EXTRA_DIST = README.md README.html
EXTRA_DIST += config.h.win32
EXTRA_DIST += Doxyfile
EXTRA_DIST += issues_closed_for_0.13.md
dist-hook:
test -d "$(distdir)/doc" || mkdir "$(distdir)/doc"
chmod -R u+w "$(distdir)/doc"
cd "$(distdir)" && doxygen
SUBDIRS = . tests
lib_LTLIBRARIES = libjson-c.la
pkgconfigdir = $(libdir)/pkgconfig
pkgconfig_DATA = json-c.pc
libjson_cincludedir = $(includedir)/json-c
libjson_cinclude_HEADERS = \
arraylist.h \
bits.h \
debug.h \
json.h \
json_c_version.h \
json_config.h \
json_inttypes.h \
json_object.h \
json_object_iterator.h \
json_pointer.h \
json_tokener.h \
json_util.h \
json_visit.h \
linkhash.h \
printbuf.h
noinst_HEADERS=\
json_object_private.h \
math_compat.h \
strdup_compat.h \
snprintf_compat.h \
vasprintf_compat.h \
random_seed.h \
strerror_override.h
libjson_c_la_LDFLAGS = -version-info 3:0:0 -no-undefined @JSON_BSYMBOLIC_LDFLAGS@
libjson_c_la_SOURCES = \
arraylist.c \
debug.c \
json_c_version.c \
json_object.c \
json_object_iterator.c \
json_pointer.c \
json_tokener.c \
json_util.c \
json_visit.c \
linkhash.c \
printbuf.c \
random_seed.c \
strerror_override.c \
strerror_override_private.h
DISTCLEANFILES=
DISTCLEANFILES+= \
config.h \
json-c-uninstalled.pc \
json-c.pc \
json_config.h
distclean-local:
-rm -rf $(testsubdir)
JSON_CLEANFILES=
JSON_CLEANFILES+= \
Makefile.in \
aclocal.m4 \
autom4te.cache/ \
compile \
config.guess \
config.h.in \
config.sub \
configure \
depcomp \
install-sh \
ltmain.sh \
missing \
test-driver \
tests/Makefile.in
JSON_CLEANFILES+= \
libtool \
stamp-h1 \
stamp-h2
# There's no built-in way to remove these after all the other
# maintainer-clean steps happen, so do it explicitly here.
really-clean:
$(MAKE) maintainer-clean
rm -rf ${JSON_CLEANFILES}
uninstall-local:
rm -rf "$(DESTDIR)@includedir@/json-c"
rm -f "$(DESTDIR)@includedir@/json"
ANDROID_CFLAGS = -I$(top_srcdir) -DHAVE_CONFIG_H
Android.mk: Makefile.am
androgenizer -:PROJECT json-c \
-:SHARED libjson-c \
-:TAGS eng debug \
-:REL_TOP $(top_srcdir) -:ABS_TOP $(abs_top_srcdir) \
-:SOURCES $(libjson_c_la_SOURCES) $(nodist_libjson_c_la_SOURCES) \
-:CFLAGS $(DEFS) $(ANDROID_CFLAGS) $(libjson_c_la_CFLAGS) \
-:LDFLAGS $(libjson_c_la_LDFLAGS) $(libjson_c_la_LIBADD) \
-:HEADER_TARGET json-c \
-:HEADERS $(libjson_cinclude_HEADERS) \
-:PASSTHROUGH LOCAL_ARM_MODE:=arm \
> $@

View File

@@ -8,8 +8,8 @@
<h2>JSON-C - A JSON implementation in C</h2> <h2>JSON-C - A JSON implementation in C</h2>
<h3>Overview</h3> <h3>Overview</h3>
<p>JSON-C implements a reference counting object model that allows you to easily <p>JSON-C implements a reference counting object model that allows you to easily
construct JSON objects in C, output them as JSON formatted strings and parse construct JSON objects in C, output them as JSON formatted strings and parse
JSON formatted strings back into the C representation of JSON objects. JSON formatted strings back into the C representation of JSON objects.
It aims to conform to <a href="https://tools.ietf.org/html/rfc7159">RFC 7159</a>. It aims to conform to <a href="https://tools.ietf.org/html/rfc7159">RFC 7159</a>.
</p> </p>
@@ -26,13 +26,12 @@
</ul> </ul>
<h3>Documentation</h3> <h3>Documentation</h3>
<P>Doxygen generated documentation exists <a href="doc/html/json__object_8h.html">here</a> <P>Doxygen generated documentation exists <a href="https://json-c.github.io/json-c/">here</a>.</P>
and Win32 specific notes can be found <a href="README-WIN32.html">here</a>.</P>
<h3><a href="https://github.com/json-c/json-c">GIT Reposository</a></h3> <h3><a href="https://github.com/json-c/json-c">GIT Reposository</a></h3>
<p><strong><code>git clone https://github.com/json-c/json-c.git</code></strong></p> <p><strong><code>git clone https://github.com/json-c/json-c.git</code></strong></p>
<h3><a href="http://groups.google.com/group/json-c">Mailing List</a></h3> <h3><a href="https://groups.google.com/group/json-c">Mailing List</a></h3>
<pi>Send email to <strong><code>json-c <i>&lt;at&gt;</i> googlegroups <i>&lt;dot&gt;</i> com</code></strong></p> <pi>Send email to <strong><code>json-c <i>&lt;at&gt;</i> googlegroups <i>&lt;dot&gt;</i> com</code></strong></p>
<h3><a href="COPYING">License</a></h3> <h3><a href="COPYING">License</a></h3>

359
README.md
View File

@@ -1,141 +1,277 @@
`json-c` {#mainpage} \mainpage
json-c
======== ========
1. [Overview and Build Status](#overview) 1. [Overview and Build Status](#overview)
2. [Building on Unix](#buildunix) 2. [Getting Help](#gettinghelp)
3. [Install Prerequisites](#installprereq) 3. [Building on Unix](#buildunix)
4. [Building with partial threading support](#buildthreaded) * [Prerequisites](#installprereq)
5. [Linking to libjson-c](#linking) * [Build commands](#buildcmds)
6. [Using json-c](#using) 4. [CMake options](#CMake)
5. [Testing](#testing)
6. [Building with `vcpkg`](#buildvcpkg)
7. [Building for Android](#android)
7. [Linking to libjson-c](#linking)
8. [Using json-c](#using)
JSON-C - A JSON implementation in C <a name="overview"></a> <a name="overview"></a>
JSON-C - A JSON implementation in C
----------------------------------- -----------------------------------
Build Status JSON-C implements a reference counting object model that allows you to easily
* [AppVeyor Build](https://ci.appveyor.com/project/hawicz/json-c) ![AppVeyor Build Status](https://ci.appveyor.com/api/projects/status/github/json-c/json-c?branch=master&svg=true) construct JSON objects in C, output them as JSON formatted strings and parse
* [Travis Build](https://travis-ci.org/json-c/json-c) ![Travis Build Status](https://travis-ci.org/json-c/json-c.svg?branch=master)
JSON-C implements a reference counting object model that allows you to easily
construct JSON objects in C, output them as JSON formatted strings and parse
JSON formatted strings back into the C representation of JSON objects. JSON formatted strings back into the C representation of JSON objects.
It aims to conform to [RFC 7159](https://tools.ietf.org/html/rfc7159). It aims to conform to [RFC 8259](https://www.rfc-editor.org/rfc/rfc8259).
Skip down to [Using json-c](#using)
Building on Unix with `git`, `gcc` and `autotools` <a name="buildunix"></a> or check out the [API docs](https://json-c.github.io/json-c/),
-------------------------------------------------- if you already have json-c installed and ready to use.
Home page for json-c: https://github.com/json-c/json-c/wiki Home page for json-c: https://github.com/json-c/json-c/wiki
<a name="gettinghelp"></a>
Getting Help
------------
If you have questions about using json-c, please start a thread on
our forums at: https://groups.google.com/forum/#!forum/json-c
If you believe you've discovered a bug, report it at
(https://github.com/json-c/json-c/issues). Please be sure to include
the version of json-c you're using, the OS you're running on, and any
other relevant details. Fully reproducible test cases and/or patches
to fix problems are greatly appreciated.
Fixes for bugs, or small new features can be directly submitted as a
[pull request](https://github.com/json-c/json-c/pulls). For major new
features or large changes of any kind, please first start a discussion
on the [forums](https://groups.google.com/forum/#!forum/json-c).
<a name="buildunix"></a>
Building on Unix with `git`, `gcc` and `cmake`
--------------------------------------------------
If you already have json-c installed, see [Linking to `libjson-c`](#linking)
for how to build and link your program against it.
Build Status
* [AppVeyor Build](https://ci.appveyor.com/project/hawicz/json-c) ![AppVeyor Build Status](https://ci.appveyor.com/api/projects/status/github/json-c/json-c?branch=master&svg=true)
* [Travis Build](https://app.travis-ci.com/github/json-c/json-c) ![Travis Build Status](https://api.travis-ci.com/json-c/json-c.svg?branch=master)
Test Status
* [Coveralls](https://coveralls.io/github/json-c/json-c?branch=master) [![Coverage Status](https://coveralls.io/repos/github/json-c/json-c/badge.svg?branch=master)](https://coveralls.io/github/json-c/json-c?branch=master)
<a name="installprereq"></a>
### Prerequisites: ### Prerequisites:
See also the "Installing prerequisites" section below.
- `gcc`, `clang`, or another C compiler - `gcc`, `clang`, or another C compiler
- `libtool>=2.2.6b`
If you're not using a release tarball, you'll also need: - `cmake>=2.8`, `>=3.16` recommended, `cmake=>3.1` for tests
- `autoconf>=2.64` (`autoreconf`) To generate docs you'll also need:
- `automake>=1.13`
Make sure you have a complete `libtool` install, including `libtoolize`.
To generate docs (e.g. as part of make distcheck) you'll also need:
- `doxygen>=1.8.13` - `doxygen>=1.8.13`
If you are on a relatively modern system, you'll likely be able to install
the prerequisites using your OS's packaging system.
### Install using apt (e.g. Ubuntu 16.04.2 LTS)
```sh
sudo apt install git
sudo apt install cmake
sudo apt install doxygen # optional
sudo apt install valgrind # optional
```
<a name="buildcmds"></a>
### Build instructions: ### Build instructions:
`json-c` GitHub repo: https://github.com/json-c/json-c `json-c` GitHub repo: https://github.com/json-c/json-c
```sh ```sh
$ git clone https://github.com/json-c/json-c.git $ git clone https://github.com/json-c/json-c.git
$ cd json-c $ mkdir json-c-build
$ sh autogen.sh $ cd json-c-build
$ cmake ../json-c # See CMake section below for custom arguments
``` ```
followed by Note: it's also possible to put your build directory inside the json-c
source directory, or even not use a separate build directory at all, but
certain things might not work quite right (notably, `make distcheck`)
Then:
```sh ```sh
$ ./configure # --enable-threading
$ make $ make
$ make install $ make test
$ make USE_VALGRIND=0 test # optionally skip using valgrind
$ sudo make install # it could be necessary to execute make install
``` ```
To build and run the test programs:
### Generating documentation with Doxygen:
The library documentation can be generated directly from the source code using Doxygen tool:
```sh ```sh
$ make check # in build directory
$ make USE_VALGRIND=0 check # optionally skip using valgrind make doc
google-chrome doc/html/index.html
``` ```
Install prerequisites <a name="installprereq"></a>
-----------------------
If you are on a relatively modern system, you'll likely be able to install <a name="CMake"></a>
the prerequisites using your OS's packaging system. CMake Options
--------------------
### Install using apt (e.g. Ubuntu 16.04.2 LTS) The json-c library is built with [CMake](https://cmake.org/cmake-tutorial/),
```sh which can take a few options.
sudo apt install git
sudo apt install autoconf automake libtool
sudo apt install valgrind # optional
```
Then start from the "git clone" command, above. Variable | Type | Description
-----------------------------|--------|--------------
CMAKE_INSTALL_PREFIX | String | The install location.
CMAKE_BUILD_TYPE | String | Defaults to "debug".
BUILD_SHARED_LIBS | Bool | The default build generates a dynamic (dll/so) library. Set this to OFF to create a static library only.
BUILD_STATIC_LIBS | Bool | The default build generates a static (lib/a) library. Set this to OFF to create a shared library only.
DISABLE_STATIC_FPIC | Bool | The default builds position independent code. Set this to OFF to create a shared library only.
DISABLE_BSYMBOLIC | Bool | Disable use of -Bsymbolic-functions.
DISABLE_THREAD_LOCAL_STORAGE | Bool | Disable use of Thread-Local Storage (HAVE___THREAD).
DISABLE_WERROR | Bool | Disable use of -Werror.
DISABLE_EXTRA_LIBS | Bool | Disable use of extra libraries, libbsd
DISABLE_JSON_POINTER | Bool | Omit json_pointer support from the build.
ENABLE_RDRAND | Bool | Enable RDRAND Hardware RNG Hash Seed.
ENABLE_THREADING | Bool | Enable partial threading support.
OVERRIDE_GET_RANDOM_SEED | String | A block of code to use instead of the default implementation of json_c_get_random_seed(), e.g. on embedded platforms where not even the fallback to time() works. Must be a single line.
### Manually install and build autoconf, automake and libtool Pass these options as `-D` on CMake's command-line.
For older OS's that don't have up-to-date version of the packages will
require a bit more work. For example, CentOS release 5.11, etc...
```sh ```sh
curl -O http://ftp.gnu.org/gnu/autoconf/autoconf-2.69.tar.gz # build a static library only
curl -O http://ftp.gnu.org/gnu/automake/automake-1.15.tar.gz cmake -DBUILD_SHARED_LIBS=OFF ..
curl -O http://ftp.gnu.org/gnu/libtool/libtool-2.2.6b.tar.gz
tar xzf autoconf-2.69.tar.gz
tar xzf automake-1.15.tar.gz
tar xzf libtool-2.2.6b.tar.gz
export PATH=${HOME}/ac_install/bin:$PATH
(cd autoconf-2.69 && \
./configure --prefix ${HOME}/ac_install && \
make && \
make install)
(cd automake-1.15 && \
./configure --prefix ${HOME}/ac_install && \
make && \
make install)
(cd libtool-2.2.6b && \
./configure --prefix ${HOME}/ac_install && \
make && \
make install)
``` ```
### Building with partial threading support
Building with partial threading support <a name="buildthreaded"></a>
----------------------------------------
Although json-c does not support fully multi-threaded access to Although json-c does not support fully multi-threaded access to
object trees, it has some code to help make use in threaded programs object trees, it has some code to help make its use in threaded programs
a bit safer. Currently, this is limited to using atomic operations for a bit safer. Currently, this is limited to using atomic operations for
json_object_get() and json_object_put(). json_object_get() and json_object_put().
Since this may have a performance impact, of at least 3x slower Since this may have a performance impact, of at least 3x slower
according to https://stackoverflow.com/a/11609063, it is disabled by according to https://stackoverflow.com/a/11609063, it is disabled by
default. You may turn it on by adjusting your configure command with: default. You may turn it on by adjusting your cmake command with:
--enable-threading -DENABLE_THREADING=ON
Separately, the default hash function used for object field keys, Separately, the default hash function used for object field keys,
lh_char_hash, uses a compare-and-swap operation to ensure the randomly lh_char_hash, uses a compare-and-swap operation to ensure the random
seed is only generated once. Because this is a one-time operation, it seed is only generated once. Because this is a one-time operation, it
is always compiled in when the compare-and-swap operation is available. is always compiled in when the compare-and-swap operation is available.
Linking to `libjson-c` <a name="linking"> ### cmake-configure wrapper script
For those familiar with the old autoconf/autogen.sh/configure method,
there is a `cmake-configure` wrapper script to ease the transition to cmake.
```sh
mkdir build
cd build
../cmake-configure --prefix=/some/install/path
make
```
cmake-configure can take a few options.
| options | Description|
| ---- | ---- |
| prefix=PREFIX | install architecture-independent files in PREFIX |
| enable-threading | Enable code to support partly multi-threaded use |
| enable-rdrand | Enable RDRAND Hardware RNG Hash Seed generation on supported x86/x64 platforms. |
| enable-shared | build shared libraries [default=yes] |
| enable-static | build static libraries [default=yes] |
| disable-Bsymbolic | Avoid linking with -Bsymbolic-function |
| disable-werror | Avoid treating compiler warnings as fatal errors |
<a name="testing"></a>
Testing:
----------
By default, if valgrind is available running tests uses it.
That can slow the tests down considerably, so to disable it use:
```sh
export USE_VALGRIND=0
```
To run tests a separate build directory is recommended:
```sh
mkdir build-test
cd build-test
# VALGRIND=1 causes -DVALGRIND=1 to be passed when compiling code
# which uses slightly slower, but valgrind-safe code.
VALGRIND=1 cmake ..
make
make test
# By default, if valgrind is available running tests uses it.
make USE_VALGRIND=0 test # optionally skip using valgrind
```
If a test fails, check `Testing/Temporary/LastTest.log`,
`tests/testSubDir/${testname}/${testname}.vg.out`, and other similar files.
If there is insufficient output try:
```sh
VERBOSE=1 CTEST_OUTPUT_ON_FAILURE=1 make test
```
or
```sh
JSONC_TEST_TRACE=1 make test
```
and check the log files again.
<a name="buildvcpkg"></a>
Building on Unix and Windows with `vcpkg`
--------------------------------------------------
You can download and install JSON-C using the [vcpkg](https://github.com/Microsoft/vcpkg/) dependency manager:
git clone https://github.com/Microsoft/vcpkg.git
cd vcpkg
./bootstrap-vcpkg.sh
./vcpkg integrate install
vcpkg install json-c
The JSON-C port in vcpkg is kept up to date by Microsoft team members and community contributors. If the version is out of date, please [create an issue or pull request](https://github.com/Microsoft/vcpkg) on the vcpkg repository.
<a name="android">
Building for Android
----------------------
Building on Android is now particularly well supported, but there
have been some reports of success using
https://developer.android.com/ndk/guides/cmake
```
mkdir json-c-build
cd json-c-build/
export NDK_HOME=~/Library/Android/sdk/ndk/22.1.7171670/
cmake \
--toolchain=$NDK_HOME/build/cmake/android.toolchain.cmake \
-DANDROID_STL=none \
-DANDROID_ABI=arm64-v8a \
-DANDROID_PLATFORM=android-29 \
-DANDROID_LD=lld \
-DCMAKE_BUILD_TYPE=MinSizeRel \
-DCMAKE_INSTALL_PREFIX=<install prefix> \
-DENABLE_THREADING=true \
..
make install
```
<a name="linking">
Linking to `libjson-c`
---------------------- ----------------------
If your system has `pkgconfig`, If your system has `pkgconfig`,
@@ -146,28 +282,75 @@ CFLAGS += $(shell pkg-config --cflags json-c)
LDFLAGS += $(shell pkg-config --libs json-c) LDFLAGS += $(shell pkg-config --libs json-c)
``` ```
Without `pkgconfig`, you would do something like this: Without `pkgconfig`, you might do something like this:
```make ```make
JSON_C_DIR=/path/to/json_c/install JSON_C_DIR=/path/to/json_c/install
CFLAGS += -I$(JSON_C_DIR)/include/json-c CFLAGS += -I$(JSON_C_DIR)/include/json-c
# Or to use lines like: #include <json-c/json_object.h>
#CFLAGS += -I$(JSON_C_DIR)/include
LDFLAGS+= -L$(JSON_C_DIR)/lib -ljson-c LDFLAGS+= -L$(JSON_C_DIR)/lib -ljson-c
``` ```
If your project uses cmake:
Using json-c <a name="using"> * Add to your CMakeLists.txt file:
```cmake
find_package(json-c CONFIG)
target_link_libraries(${PROJECT_NAME} PRIVATE json-c::json-c)
```
* Then you might run in your project:
```sh
cd build
cmake -DCMAKE_PREFIX_PATH=/path/to/json_c/install/lib64/cmake ..
```
<a name="using">
Using json-c
------------ ------------
To use json-c you can either include json.h, or preferrably, one of the To use json-c you can either include json.h, or preferably, one of the
following more specific header files: following more specific header files:
* json_object.h - Core types and methods. * json_object.h - Core types and methods.
* json_tokener.h - Methods for parsing and serializing json-c object trees. * json_tokener.h - Methods for parsing and serializing json-c object trees.
* json_pointer.h - JSON Pointer (RFC 6901) implementation for retrieving * json_pointer.h - JSON Pointer (RFC 6901) implementation for retrieving
objects from a json-c object tree. objects from a json-c object tree.
* json_object_iterator.h - Methods for iterating over single json_object instances. * json_object_iterator.h - Methods for iterating over single json_object instances. (See also `json_object_object_foreach()` in json_object.h)
* json_visit.h - Methods for walking a tree of json-c objects. * json_visit.h - Methods for walking a tree of json-c objects.
* json_util.h - Miscelleanous utility functions. * json_util.h - Miscellaneous utility functions.
For a full list of headers see [files.html](files.html) For a full list of headers see [files.html](https://json-c.github.io/json-c/json-c-current-release/doc/html/files.html)
The primary type in json-c is json_object. It describes a reference counted
tree of json objects which are created by either parsing text with a
json_tokener (i.e. `json_tokener_parse_ex()`), or by creating
(with `json_object_new_object()`, `json_object_new_int()`, etc...) and adding
(with `json_object_object_add()`, `json_object_array_add()`, etc...) them
individually.
Typically, every object in the tree will have one reference, from its parent.
When you are done with the tree of objects, you call json_object_put() on just
the root object to free it, which recurses down through any child objects
calling json_object_put() on each one of those in turn.
You can get a reference to a single child
(`json_object_object_get()` or `json_object_array_get_idx()`)
and use that object as long as its parent is valid.
If you need a child object to live longer than its parent, you can
increment the child's refcount (`json_object_get()`) to allow it to survive
the parent being freed or it being removed from its parent
(`json_object_object_del()` or `json_object_array_del_idx()`)
When parsing text, the json_tokener object is independent from the json_object
that it returns. It can be allocated (`json_tokener_new()`)
used one or multiple times (`json_tokener_parse_ex()`, and
freed (`json_tokener_free()`) while the json_object objects live on.
A json_object tree can be serialized back into a string with
`json_object_to_json_string_ext()`. The string that is returned
is only valid until the next "to_json_string" call on that same object.
Also, it is freed when the json_object is freed.

View File

@@ -1,81 +1,130 @@
Release checklist: # Release checklist:
release=0.12 ## Pre-release tasks
git clone https://github.com/json-c/json-c json-c-${release}
cd json-c-${release} * Figure out whether a release is worthwhile to do.
* Analyze the previous release branch to see if anything should have been
applied to master.
* Collect changes and assemble tentative release notes.
* Identify previous release branch point
* Check commit logs between previous branch point and now for
notable changes worth mentioning
* Create a new issues_closed_for_X.Y.md file
* Include notable entries from here in the release notes.
* Analyze APIs between previous release branch and master to produce list of
changes (added/removed/updated funcs, etc...), and detect backwards compat
issues.
* https://github.com/lvc/abi-compliance-checker
* See also `abi-check.sh`
* If the new release is not backwards compatible, then this is a MAJOR release.
* Mention removed features in ChangeLog
* Consider re-adding backwards compatible support, through symbol
aliases and appropriate entries in json-c.sym
* Be sure any new symbols are listed in json-c.sym as part of
the _new_ release version.
* Update the AUTHORS file
PREV=$(git tag | tail -1)
( git log -r ${PREV}..HEAD | grep Author: | sed -e's/Author: //' ; cat AUTHORS ) | sort -u > A1
mv A1 AUTHORS
* Exclude mentioning changes that have already been included in a point
release of the previous release branch.
* Update ChangeLog with relevant notes before branching.
* Check that the compile works on Linux - automatic through Travis
* Check that the compile works on NetBSD
* Check that the compile works on Windows - automatic through AppVeyor
## Release creation
Start creating the new release:
PREV=$(git tag | tail -1)
PREV=${PREV#json-c-}
PREV=${PREV%-*}
release=0.$((${PREV#*.} + 1))
cd ~
git clone https://github.com/json-c/json-c json-c-${release}
rm -rf distcheck
mkdir distcheck
cd distcheck
# Note, the build directory *must* be entirely separate from
# the source tree for distcheck to work properly.
cmake -DCMAKE_BUILD_TYPE=Release ../json-c-${release}
make distcheck
cd ..
Check that the compile works on Linux
Check that the compile works on NetBSD
Check that the compile works on Windows
Run "make distcheck" and fix any problems
(e.g. adding new files to SOURCES variables in Makefile.am)
Check ChangeLog to see if anything should be added.
Make any fixes/changes *before* branching. Make any fixes/changes *before* branching.
git branch json-c-${release} cd json-c-${release}
git checkout json-c-${release} git checkout -b json-c-${release}
------------ ------------
Update the version in json_c_version.h Using ${release}:
Update the version in Doxyfile Update the version in json_c_version.h
Update the version in configure.ac Update the version in CMakeLists.txt (VERSION in the project(...) line)
Update the version in CMakeLists.txt
Use ${release}.
Update the libjson_la_LDFLAGS line in Makefile.am to the new version. Update the set_target_properties() line in CmakeLists.txt to set the shared
Generally, unless we're doing a major release, change: library version. Generally, unless we're doing a major release, change:
-version-info x:y:z VERSION x.y.z
to to
-version-info x:y+1:z VERSION x.y+1.z
------------ git commit -a -m "Bump version to ${release}"
Generate the configure script and other files: If we're doing a major release (SONAME bump), also bump the version
sh autogen.sh of ALL symbols in json-c.sym.
git add -f Makefile.in aclocal.m4 config.guess config.h.in \ See explanation at https://github.com/json-c/json-c/issues/621
config.sub configure depcomp install-sh \ More info at: https://software.intel.com/sites/default/files/m/a/1/e/dsohowto.pdf
ltmain.sh missing tests/Makefile.in \
INSTALL
# check for anything else to be added:
git status --ignored
git commit
------------ ------------
Generate the doxygen documentation: Generate the doxygen documentation:
doxygen
git add -f doc (cd ../distcheck && make doc)
git commit doc cp -r -p ../distcheck/doc/{html,Doxyfile} doc/.
rm doc/Doxyfile # Remove generated file w/ hardcoded paths
git add -f doc
git commit doc -m "Generate docs for the ${release} release"
------------ ------------
cd .. Create the release tarballs:
echo .git > excludes
echo autom4te.cache >> excludes
tar -czf json-c-${release}.tar.gz -X excludes json-c-${release}
echo doc >> excludes cd ..
tar -czf json-c-${release}-nodoc.tar.gz -X excludes json-c-${release} echo .git > excludes
tar -czf json-c-${release}.tar.gz -X excludes json-c-${release}
echo 'doc/*.cmake' >> excludes
echo 'doc/CMakeFiles' >> excludes
echo 'doc/Makefile' >> excludes
echo 'doc/Doxyfile' >> excludes
echo 'doc/html' >> excludes
tar -czf json-c-${release}-nodoc.tar.gz -X excludes json-c-${release}
------------ ------------
Tag the branch: Tag the branch:
cd json-c-${release}
git tag -a json-c-${release}-$(date +%Y%m%d) -m "Release json-c-${release}"
git push origin json-c-${release} cd json-c-${release}
git push --tags git tag -a json-c-${release}-$(date +%Y%m%d) -m "Release json-c-${release}"
git push origin json-c-${release}
git push --tags
------------ ------------
Go to Amazon S3 service at: Go to Amazon S3 service at:
https://console.aws.amazon.com/s3/ https://console.aws.amazon.com/s3/
Upload the two tarballs in the json-c_releases folder. Upload the two tarballs in the json-c_releases/releases folder.
When uploading, use "Reduced Redundancy", and make the uploaded files publicly accessible. * Expand "Permissions", pick "Grant public-read access"
* Expand "Properties", ensure "Standard" storage class is picked.
Logout of Amazon S3, and verify that the files are visible. Logout of Amazon S3, and verify that the files are visible.
https://s3.amazonaws.com/json-c_releases/releases/index.html https://s3.amazonaws.com/json-c_releases/releases/index.html
@@ -84,53 +133,57 @@ Logout of Amazon S3, and verify that the files are visible.
Post-release checklist: Post-release checklist:
git checkout master git checkout master
Add new section to ChangeLog
Update the version in json_c_version.h
Update the version in Doxyfile
Update the version in configure.ac
Update the version in CMakeLists.txt
Use ${release}.99 to indicate a version "newer" than anything on the branch.
Leave the libjson_la_LDFLAGS line in Makefile.am alone. Add new section to ChangeLog for ${release}+1
For more details see:
http://www.gnu.org/software/libtool/manual/html_node/Updating-version-info.html Use ${release}.99 to indicate a version "newer" than anything on the branch:
Update the version in json_c_version.h
Update the version in CMakeLists.txt
Update the set_target_properties() line in CmakeLists.txt to match the release branch.
Add a new empty section to the json-c.sym file, for ${release}+1
git commit -a -m "Update the master branch to version ${release}.99"
git push
------------ ------------
Update the gh-pages branch with new docs: Update the gh-pages branch with new docs:
cd json-c-${release} cd json-c-${release}
git checkout json-c-${release} git checkout json-c-${release}
cd .. cd ..
git clone -b gh-pages https://github.com/json-c/json-c json-c-pages git clone -b gh-pages https://github.com/json-c/json-c json-c-pages
cd json-c-pages cd json-c-pages
mkdir json-c-${release} mkdir json-c-${release}
cp -R ../json-c-${release}/doc json-c-${release}/. cp -R ../json-c-${release}/doc json-c-${release}/.
cp ../json-c-${release}/README-WIN32.html json-c-${release}/. git add json-c-${release}
git add json-c-${release} rm json-c-current-release
git commit ln -s json-c-${release} json-c-current-release
git commit -a -m "Add the ${release} docs."
vi index.html vi index.html
Add/change links to current release. # Add/change links to current release.
git commit index.html git commit -a -m "Update the doc links to point at ${release}"
git push git push
------------ ------------
Update checksums on wiki page. Update checksums on wiki page.
cd .. cd ..
openssl sha -sha256 json-c*gz openssl sha -sha256 json-c*gz
openssl md5 json-c*gz openssl md5 json-c*gz
Copy and paste this output into the wiki page at: Copy and paste this output into the wiki page at:
https://github.com/json-c/json-c/wiki * https://github.com/json-c/json-c/wiki
* https://github.com/json-c/json-c/wiki/Old-Releases
------------ ------------
Send an email to the mailing list. Send an email to the mailing list.

62
STYLE.txt Executable file → Normal file
View File

@@ -1,31 +1,31 @@
In general: In general:
For minor changes to a function, copy the existing formatting. For minor changes to a function, copy the existing formatting.
When changing the style, commit that separately from other changes. When changing the style, commit that separately from other changes.
For new code and major changes to a function, switch to the official json-c style. For new code and major changes to a function, switch to the official json-c style.
Official json-c style: Official json-c style:
Aim for readability, not strict conformance to fixed style rules.
These rules are not comprehensive. Look to existing code for guidelines. Aim for readability, not strict conformance to fixed style rules.
Indentation is tab based, with continuations of long lines starting with tabs then spaces for alignment. Formatting is tab based; previous attempts at proper alignment with
Try to line up components of continuation lines with corresponding part of the line above (i.e. "indent -lp" effect), but avoid excessive identation tha causes extra line wraps. spaces for continuation lines have been abandoned in favor of the
e.g. (T=tab, S=space): convenience of using clang-format.
TTTTsome_long_func_call(arg1, arg2, Refer to the .clang-format file for details, and run the tool before commit:
TTTTSSSSSSSSSSSSSSSSSSSarg3, arg4);
TTTTsome_reallly_really_long_func_name(arg1, clang-format -i somefile.c foo.h
TTTTTarg2, arg3, arg4);
There should be a space between "if"/"while" and the following parenthesis. For sections of code that would be significantly negatively impacted, surround
"case" lines are indented at the same level as the "switch" statement. them with magic comments to disable formatting:
Commas are followed by a single space.
Include spaces around most non-unary, non-postfix operators, "=", "==', "&", "||", etc... /* clang-format off */
Function calls have no space between the name and the parenthesis. ...code...
Curly braces go on their own line. /* clang-format on */
Curly braces may be omitted.
Naming: Naming:
Words within function and variable names are separated with underscores. Avoid camel case. Words within function and variable names are separated with underscores. Avoid camel case.
Prefer longer, more descriptive names, but not excessively so. No single letter variable names. Prefer longer, more descriptive names, but not excessively so. No single letter variable names.
Other: Other:
Variables should be defined for the smallest scope needed. Variables should be defined for the smallest scope needed.
Functions should be defined static when possible. Functions should be defined static when possible.
When possible, avoid exposing internals in the public API. When possible, avoid exposing internals in the public API.

42
abi-check.sh Normal file
View File

@@ -0,0 +1,42 @@
#!/bin/sh
prev=0.16
release=0.17
# ... clone json-c, abi-compliance-checker, abi-dumper
mkdir build
cd build
CFLAGS=-Og cmake -DCMAKE_INSTALL_PREFIX=~/json-c-installs/json-c-${release} ..
make && make test && make install
# Assume the old version has already been built
cd ~/abi-compliance-checker
mkxml()
{
ver="$1"
cat <<EOF > json-c-${ver}.xml
<foo>
<version>
${ver}
</version>
<headers>
../json-c-installs/json-c-${ver}/include/json-c
</headers>
<libs>
../json-c-installs/json-c-${ver}/lib64/libjson-c.so
</libs>
</foo>
EOF
}
mkxml ${release}
mkxml ${prev}
perl abi-compliance-checker.pl -lib json-c -dump json-c-${prev}.xml -dump-path ./ABI-${prev}.dump
perl abi-compliance-checker.pl -lib json-c -dump json-c-${release}.xml -dump-path ./ABI-${release}.dump
perl abi-compliance-checker.pl -l json-c -old ABI-${prev}.dump -new ABI-${release}.dump
echo "look in compat_reports/json-c/..."

122
apps/CMakeLists.txt Normal file
View File

@@ -0,0 +1,122 @@
cmake_minimum_required(VERSION 2.8) # see ../CMakeLists.txt for why 2.8
if(POLICY CMP0075)
cmake_policy(SET CMP0075 NEW)
endif()
include(CheckSymbolExists)
include(CheckIncludeFile)
include(CMakePackageConfigHelpers)
# First, sort out whether we're running inside a json-c build,
# or standalone, such as part of a benchmark build.
if ("${PROJECT_NAME}" STREQUAL "json-c")
# Part of an overall json-c build
set(APPS_LINK_LIBS "${PROJECT_NAME}")
# We know we have this in our current sources:
set(HAVE_JSON_TOKENER_GET_PARSE_END)
else()
# Standalone mode, using an already installed json-c library, somewhere.
# The path to the json-c install must be specified with -DCMAKE_PREFIX_PATH=...
project(apps)
find_package(PkgConfig)
# PkgConfig is supposed to include CMAKE_PREFIX_PATH in the PKG_CONFIG_PATH
# that's used when running pkg-config, but it just doesn't work :(
# https://gitlab.kitware.com/cmake/cmake/issues/18150
#set(PKG_CONFIG_USE_CMAKE_PREFIX_PATH True)
# Instead, we handle it explicitly here and update PKG_CONFIG_PATH ourselves.
if (NOT CMAKE_PREFIX_PATH)
message(FATAL_ERROR "Please specify -DCMAKE_PREFIX_PATH=... when running cmake.")
endif()
# Note: find_file isn't recursive :(
find_file(PC_FILE_PATH "json-c.pc"
PATHS "${CMAKE_PREFIX_PATH}/lib64" "${CMAKE_PREFIX_PATH}/lib"
PATH_SUFFIXES "pkgconfig"
NO_DEFAULT_PATH)
get_filename_component(PC_DIR_PATH "${PC_FILE_PATH}" DIRECTORY)
set(ENV{PKG_CONFIG_PATH} "$ENV{PKG_CONFIG_PATH}:${PC_DIR_PATH}")
message(STATUS "PC_FILE_PATH=${PC_FILE_PATH}")
message(STATUS "PC_DIR_PATH=${PC_DIR_PATH}")
pkg_check_modules(PC_JSONC json-c)
if (PC_JSONC_FOUND)
message(STATUS "Found json-c using pkg-config: ${PC_JSONC_PREFIX}")
message(STATUS " PC_JSONC_INCLUDE_DIRS=${PC_JSONC_INCLUDE_DIRS}")
message(STATUS " PC_JSONC_LIBRARIES=${PC_JSONC_LIBRARIES}")
message(STATUS " PC_JSONC_LIBRARY_DIRS=${PC_JSONC_LIBRARY_DIRS}")
link_directories(${PC_JSONC_LIBRARY_DIRS})
include_directories(${PC_JSONC_INCLUDE_DIRS})
# for target_link_libraries(...)
set(APPS_INCLUDE_DIRS ${PC_JSONC_INCLUDE_DIRS})
set(APPS_LINK_DIRS ${PC_JSONC_LIBRARY_DIRS})
set(APPS_LINK_LIBS ${PC_JSONC_LIBRARIES})
else()
message(STATUS "Using find_package to locate json-c")
# Note: find_package needs CMAKE_PREFIX_PATH set appropriately.
# XXX json-c's installed cmake files don't actually set up what's
# needed to use find_package() by itself, so we're just using it
# to confirm the top of the install location.
find_package(json-c CONFIG) # sets json-c_DIR
# Assume json-c-config.cmake is in lib64/cmake/json-c/
get_filename_component(json-c_TOP "${json-c_DIR}/../../.." ABSOLUTE)
get_filename_component(json-c_LIBDIR "${json-c_DIR}/../.." ABSOLUTE)
message(STATUS " json-c_TOP=${json-c_TOP}")
message(STATUS " json-c_DIR=${json-c_DIR}")
message(STATUS " json-c_LIBDIR=${json-c_LIBDIR}")
link_directories(${json-c_LIBDIR})
include_directories(${json-c_TOP}/include)
include_directories(${json-c_TOP}/include/json-c)
set(APPS_LINK_DIRS "${json-c_LIBDIR}")
set(APPS_INCLUDE_DIRS "${json-c_TOP}/include;${json-c_TOP}/include/json-c")
set(APPS_LINK_LIBS json-c)
endif()
set(CMAKE_REQUIRED_LINK_OPTIONS "-L${APPS_LINK_DIRS}")
set(CMAKE_REQUIRED_LIBRARIES ${APPS_LINK_LIBS})
set(CMAKE_REQUIRED_INCLUDES ${APPS_INCLUDE_DIRS})
check_symbol_exists(json_tokener_get_parse_end "json_tokener.h" HAVE_JSON_TOKENER_GET_PARSE_END)
endif() # end "standalone mode" block
# ---------------------------------
check_include_file(sys/resource.h HAVE_SYS_RESOURCE_H) # for getrusage
if (HAVE_SYS_RESOURCE_H)
check_symbol_exists(getrusage "sys/resource.h" HAVE_GETRUSAGE)
endif()
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/cmake/apps_config.h.in
${PROJECT_BINARY_DIR}/apps_config.h)
message(STATUS "Wrote ${PROJECT_BINARY_DIR}/apps_config.h")
# ---------------------------------
include_directories(PUBLIC ${CMAKE_SOURCE_DIR})
include_directories(${PROJECT_SOURCE_DIR})
include_directories(${PROJECT_BINARY_DIR})
# ---------------------------------
# Now, finally, the actual executables we're building:
add_executable(json_parse json_parse.c)
target_link_libraries(json_parse PRIVATE ${APPS_LINK_LIBS})
# Note: it is intentional that there are no install instructions here yet.
# When/if the interface of the app(s) listed here settles down enough to
# publish as part of a regular build that will be added.

View File

@@ -0,0 +1,8 @@
/* Define to 1 if you have the <sys/resource.h> header file. */
#cmakedefine HAVE_SYS_RESOURCE_H
/* Define if you have the `getrusage' function. */
#cmakedefine HAVE_GETRUSAGE
#cmakedefine HAVE_JSON_TOKENER_GET_PARSE_END

204
apps/json_parse.c Normal file
View File

@@ -0,0 +1,204 @@
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <getopt.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "apps_config.h"
/* XXX for a regular program, these should be <json-c/foo.h>
* but that's inconvenient when building in the json-c source tree.
*/
#include "json_object.h"
#include "json_tokener.h"
#include "json_util.h"
#ifdef HAVE_SYS_RESOURCE_H
#include <sys/resource.h>
#include <sys/time.h>
#endif
#ifndef JSON_NORETURN
#if defined(_MSC_VER)
#define JSON_NORETURN __declspec(noreturn)
#elif defined(__OS400__)
#define JSON_NORETURN
#else
/* 'cold' attribute is for optimization, telling the computer this code
* path is unlikely.
*/
#define JSON_NORETURN __attribute__((noreturn, cold))
#endif
#endif
static int formatted_output = JSON_C_TO_STRING_SPACED;
static int show_output = 1;
static int strict_mode = 0;
static int color = 0;
static const char *fname = NULL;
#ifndef HAVE_JSON_TOKENER_GET_PARSE_END
#define json_tokener_get_parse_end(tok) ((tok)->char_offset)
#endif
JSON_NORETURN static void usage(const char *argv0, int exitval, const char *errmsg);
static void showmem(void);
static int parseit(int fd, int (*callback)(struct json_object *));
static int showobj(struct json_object *new_obj);
static void showmem(void)
{
#ifdef HAVE_GETRUSAGE
struct rusage rusage;
memset(&rusage, 0, sizeof(rusage));
getrusage(RUSAGE_SELF, &rusage);
fprintf(stderr, "maxrss: %ld KB\n", rusage.ru_maxrss);
#endif
}
static int parseit(int fd, int (*callback)(struct json_object *))
{
struct json_object *obj;
char buf[32768];
ssize_t ret;
int depth = JSON_TOKENER_DEFAULT_DEPTH;
json_tokener *tok;
tok = json_tokener_new_ex(depth);
if (!tok)
{
fprintf(stderr, "unable to allocate json_tokener: %s\n", strerror(errno));
return 1;
}
json_tokener_set_flags(tok, JSON_TOKENER_STRICT
#ifdef JSON_TOKENER_ALLOW_TRAILING_CHARS
| JSON_TOKENER_ALLOW_TRAILING_CHARS
#endif
);
// XXX push this into some kind of json_tokener_parse_fd API?
// json_object_from_fd isn't flexible enough, and mirroring
// everything you can do with a tokener into json_util.c seems
// like the wrong approach.
size_t total_read = 0;
while ((ret = read(fd, buf, sizeof(buf))) > 0)
{
size_t retu = (size_t)ret; // We know it's positive
total_read += retu;
size_t start_pos = 0;
while (start_pos != retu)
{
obj = json_tokener_parse_ex(tok, &buf[start_pos], retu - start_pos);
enum json_tokener_error jerr = json_tokener_get_error(tok);
size_t parse_end = json_tokener_get_parse_end(tok);
if (obj == NULL && jerr != json_tokener_continue)
{
const char *aterr = (start_pos + parse_end < (int)sizeof(buf)) ?
&buf[start_pos + parse_end] : "";
fflush(stdout);
size_t fail_offset = total_read - retu + start_pos + parse_end;
fprintf(stderr, "Failed at offset %lu: %s %c\n", (unsigned long)fail_offset,
json_tokener_error_desc(jerr), aterr[0]);
json_tokener_free(tok);
return 1;
}
if (obj != NULL)
{
int cb_ret = callback(obj);
json_object_put(obj);
if (cb_ret != 0)
{
json_tokener_free(tok);
return 1;
}
}
start_pos += json_tokener_get_parse_end(tok);
assert(start_pos <= retu);
}
}
if (ret < 0)
{
fprintf(stderr, "error reading fd %d: %s\n", fd, strerror(errno));
}
json_tokener_free(tok);
return 0;
}
static int showobj(struct json_object *new_obj)
{
if (new_obj == NULL)
{
fprintf(stderr, "%s: Failed to parse\n", fname);
return 1;
}
fprintf(stderr, "Successfully parsed object from %s\n", fname);
if (show_output)
{
const char *output;
output = json_object_to_json_string_ext(new_obj, formatted_output | color);
printf("%s\n", output);
}
showmem();
return 0;
}
static void usage(const char *argv0, int exitval, const char *errmsg)
{
FILE *fp = stdout;
if (exitval != 0)
fp = stderr;
if (errmsg != NULL)
fprintf(fp, "ERROR: %s\n\n", errmsg);
fprintf(fp, "Usage: %s [-f|-F <arg>] [-n] [-s]\n", argv0);
fprintf(fp, " -f - Format the output to stdout with JSON_C_TO_STRING_PRETTY (default is JSON_C_TO_STRING_SPACED)\n");
fprintf(fp, " -F - Format the output to stdout with <arg>, e.g. 0 for JSON_C_TO_STRING_PLAIN\n");
fprintf(fp, " -n - No output\n");
fprintf(fp, " -c - color\n");
fprintf(fp, " -s - Parse in strict mode, flags:\n");
fprintf(fp, " JSON_TOKENER_STRICT|JSON_TOKENER_ALLOW_TRAILING_CHARS\n");
fprintf(fp, " Diagnostic information will be emitted to stderr\n");
fprintf(fp, "\nWARNING WARNING WARNING\n");
fprintf(fp, "This is a prototype, it may change or be removed at any time!\n");
exit(exitval);
}
int main(int argc, char **argv)
{
int opt;
while ((opt = getopt(argc, argv, "fF:hnsc")) != -1)
{
switch (opt)
{
case 'f': formatted_output = JSON_C_TO_STRING_PRETTY; break;
case 'F': formatted_output = atoi(optarg); break;
case 'n': show_output = 0; break;
case 's': strict_mode = 1; break;
case 'c': color = JSON_C_TO_STRING_COLOR; break;
case 'h': usage(argv[0], 0, NULL);
default: /* '?' */ usage(argv[0], EXIT_FAILURE, "Unknown arguments");
}
}
if (optind >= argc)
{
usage(argv[0], EXIT_FAILURE, "Expected argument after options");
}
fname = argv[optind];
int fd = open(argv[optind], O_RDONLY, 0);
showmem();
if (parseit(fd, showobj) != 0)
exit(EXIT_FAILURE);
showmem();
exit(EXIT_SUCCESS);
}

View File

@@ -1,39 +1,125 @@
version: '{branch}.{build}' version: '{branch}.{build}'
os: Windows Server 2012 R2
image:
configuration: # b_toolset: v143
- Debug - Visual Studio 2022
- Release
platform: x64 # VS2015 also used for earlier VS builds
environment: # aka os: Windows Server 2012 R2
matrix: - Visual Studio 2015
- PlatformToolset: v140
- PlatformToolset: v120 # aka os: Windows Server 2016
- PlatformToolset: Windows7.1SDK # b_toolset: v141
- Visual Studio 2017
build_script:
- cmake . # aka os: Windows Server 2019
- > # b_toolset: v142
msbuild "json-c.vcxproj" /m /verbosity:normal - Visual Studio 2019
/logger:"C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll"
/p:PlatformToolset=%PlatformToolset% /p:OutDir=lib\ platform: x64
after_build: environment:
- md include\json-c matrix:
- copy json.h include\json-c\* - b_toolset: Windows7.1SDK
- copy debug.h include\json-c\*
- copy linkhash.h include\json-c\* - b_toolset: v120
- copy arraylist.h include\json-c\*
- copy json_util.h include\json-c\* - b_toolset: v140
- copy json_object.h include\json-c\*
- copy json_tokener.h include\json-c\* - b_toolset: v141
- copy json_object_iterator.h include\json-c\*
- copy json_c_version.h include\json-c\* - b_toolset: v142
- copy json_inttypes.h include\json-c\*
- copy include\json_config.h include\json-c\* - b_toolset: v143
- copy json_object_private.h include\json-c\*
- 7z a json-c.lib.zip lib\json-c.dll include\json-c\*.h configuration:
- Debug
artifacts: - Release
- path: json-c.lib.zip
name: json-c.lib.zip build_script:
- cmake -T %b_toolset% -DCMAKE_BUILD_TYPE=%CONFIGURATION% -DCMAKE_INSTALL_PREFIX=t_install .
- cmake --build . --target install
matrix:
exclude:
# Skip release builds for all except the newest image
- image: Visual Studio 2015
configuration: Release
# In the "old" image, new toolsets aren't available:
- image: Visual Studio 2015
b_toolset: v141
- image: Visual Studio 2015
b_toolset: v142
- image: Visual Studio 2015
b_toolset: v143
# ----
- image: Visual Studio 2017
configuration: Release
# In the "new" images, exclude all toolsets except the relevant
# one for that image:
- image: Visual Studio 2017
b_toolset: Windows7.1SDK
- image: Visual Studio 2017
b_toolset: v120
- image: Visual Studio 2017
b_toolset: v140
- image: Visual Studio 2017
b_toolset: v142
- image: Visual Studio 2017
b_toolset: v143
# ----
- image: Visual Studio 2019
configuration: Release
- image: Visual Studio 2019
b_toolset: Windows7.1SDK
- image: Visual Studio 2019
b_toolset: v120
- image: Visual Studio 2019
b_toolset: v140
- image: Visual Studio 2019
b_toolset: v141
- image: Visual Studio 2019
b_toolset: v143
# ----
- image: Visual Studio 2022
b_toolset: Windows7.1SDK
- image: Visual Studio 2022
b_toolset: v120
- image: Visual Studio 2022
b_toolset: v140
- image: Visual Studio 2022
b_toolset: v141
- image: Visual Studio 2022
b_toolset: v142
after_build:
- cd t_install
- 7z a ../json-c.win32.%b_toolset%.%CONFIGURATION%.zip *
artifacts:
- path: json-c.win32.%b_toolset%.%CONFIGURATION%.zip
name: json-c.win32.%b_toolset%.%CONFIGURATION%.zip

View File

@@ -14,12 +14,12 @@
#include <limits.h> #include <limits.h>
#ifdef STDC_HEADERS #ifdef STDC_HEADERS
# include <stdlib.h> #include <stdlib.h>
# include <string.h> #include <string.h>
#endif /* STDC_HEADERS */ #endif /* STDC_HEADERS */
#if defined(HAVE_STRINGS_H) && !defined(_STRING_H) && !defined(__USE_BSD) #if defined(HAVE_STRINGS_H) && !defined(_STRING_H) && !defined(__USE_BSD)
# include <strings.h> #include <strings.h>
#endif /* HAVE_STRINGS_H */ #endif /* HAVE_STRINGS_H */
#ifndef SIZE_T_MAX #ifndef SIZE_T_MAX
@@ -36,111 +36,191 @@
#include "arraylist.h" #include "arraylist.h"
struct array_list* struct array_list *array_list_new(array_list_free_fn *free_fn)
array_list_new(array_list_free_fn *free_fn)
{ {
struct array_list *arr; return array_list_new2(free_fn, ARRAY_LIST_DEFAULT_SIZE);
arr = (struct array_list*)calloc(1, sizeof(struct array_list));
if(!arr) return NULL;
arr->size = ARRAY_LIST_DEFAULT_SIZE;
arr->length = 0;
arr->free_fn = free_fn;
if(!(arr->array = (void**)calloc(sizeof(void*), arr->size))) {
free(arr);
return NULL;
}
return arr;
} }
extern void struct array_list *array_list_new2(array_list_free_fn *free_fn, int initial_size)
array_list_free(struct array_list *arr)
{ {
size_t i; struct array_list *arr;
for(i = 0; i < arr->length; i++)
if(arr->array[i]) arr->free_fn(arr->array[i]); if (initial_size < 0 || (size_t)initial_size >= SIZE_T_MAX / sizeof(void *))
free(arr->array); return NULL;
free(arr); arr = (struct array_list *)malloc(sizeof(struct array_list));
if (!arr)
return NULL;
arr->size = initial_size;
arr->length = 0;
arr->free_fn = free_fn;
if (!(arr->array = (void **)malloc(arr->size * sizeof(void *))))
{
free(arr);
return NULL;
}
return arr;
} }
void* extern void array_list_free(struct array_list *arr)
array_list_get_idx(struct array_list *arr, size_t i)
{ {
if(i >= arr->length) return NULL; size_t i;
return arr->array[i]; for (i = 0; i < arr->length; i++)
if (arr->array[i])
arr->free_fn(arr->array[i]);
free(arr->array);
free(arr);
}
void *array_list_get_idx(struct array_list *arr, size_t i)
{
if (i >= arr->length)
return NULL;
return arr->array[i];
} }
static int array_list_expand_internal(struct array_list *arr, size_t max) static int array_list_expand_internal(struct array_list *arr, size_t max)
{ {
void *t; void *t;
size_t new_size; size_t new_size;
if(max < arr->size) return 0; if (max < arr->size)
/* Avoid undefined behaviour on size_t overflow */ return 0;
if( arr->size >= SIZE_T_MAX / 2 ) /* Avoid undefined behaviour on size_t overflow */
new_size = max; if (arr->size >= SIZE_T_MAX / 2)
else new_size = max;
{ else
new_size = arr->size << 1; {
if (new_size < max) new_size = arr->size << 1;
new_size = max; if (new_size < max)
} new_size = max;
if (new_size > (~((size_t)0)) / sizeof(void*)) return -1; }
if (!(t = realloc(arr->array, new_size*sizeof(void*)))) return -1; if (new_size > (~((size_t)0)) / sizeof(void *))
arr->array = (void**)t; return -1;
(void)memset(arr->array + arr->size, 0, (new_size-arr->size)*sizeof(void*)); if (!(t = realloc(arr->array, new_size * sizeof(void *))))
arr->size = new_size; return -1;
return 0; arr->array = (void **)t;
arr->size = new_size;
return 0;
} }
int int array_list_shrink(struct array_list *arr, size_t empty_slots)
array_list_put_idx(struct array_list *arr, size_t idx, void *data)
{ {
if (idx > SIZE_T_MAX - 1 ) return -1; void *t;
if(array_list_expand_internal(arr, idx+1)) return -1; size_t new_size;
if(idx < arr->length && arr->array[idx])
arr->free_fn(arr->array[idx]); if (empty_slots >= SIZE_T_MAX / sizeof(void *) - arr->length)
arr->array[idx] = data; return -1;
if(arr->length <= idx) arr->length = idx + 1; new_size = arr->length + empty_slots;
return 0; if (new_size == arr->size)
return 0;
if (new_size > arr->size)
return array_list_expand_internal(arr, new_size);
if (new_size == 0)
new_size = 1;
if (!(t = realloc(arr->array, new_size * sizeof(void *))))
return -1;
arr->array = (void **)t;
arr->size = new_size;
return 0;
} }
int int array_list_insert_idx(struct array_list *arr, size_t idx, void *data)
array_list_add(struct array_list *arr, void *data)
{ {
return array_list_put_idx(arr, arr->length, data); size_t move_amount;
if (idx >= arr->length)
return array_list_put_idx(arr, idx, data);
/* we're at full size, what size_t can support */
if (arr->length == SIZE_T_MAX)
return -1;
if (array_list_expand_internal(arr, arr->length + 1))
return -1;
move_amount = (arr->length - idx) * sizeof(void *);
memmove(arr->array + idx + 1, arr->array + idx, move_amount);
arr->array[idx] = data;
arr->length++;
return 0;
} }
void //static inline int _array_list_put_idx(struct array_list *arr, size_t idx, void *data)
array_list_sort(struct array_list *arr, int(*sort_fn)(const void *, const void *)) int array_list_put_idx(struct array_list *arr, size_t idx, void *data)
{ {
qsort(arr->array, arr->length, sizeof(arr->array[0]), sort_fn); if (idx > SIZE_T_MAX - 1)
return -1;
if (array_list_expand_internal(arr, idx + 1))
return -1;
if (idx < arr->length && arr->array[idx])
arr->free_fn(arr->array[idx]);
arr->array[idx] = data;
if (idx > arr->length)
{
/* Zero out the arraylist slots in between the old length
and the newly added entry so we know those entries are
empty.
e.g. when setting array[7] in an array that used to be
only 5 elements longs, array[5] and array[6] need to be
set to 0.
*/
memset(arr->array + arr->length, 0, (idx - arr->length) * sizeof(void *));
}
if (arr->length <= idx)
arr->length = idx + 1;
return 0;
} }
void* array_list_bsearch(const void **key, struct array_list *arr, int array_list_add(struct array_list *arr, void *data)
int (*sort_fn)(const void *, const void *))
{ {
return bsearch(key, arr->array, arr->length, sizeof(arr->array[0]), /* Repeat some of array_list_put_idx() so we can skip several
sort_fn); checks that we know are unnecessary when appending at the end
*/
size_t idx = arr->length;
if (idx > SIZE_T_MAX - 1)
return -1;
if (array_list_expand_internal(arr, idx + 1))
return -1;
arr->array[idx] = data;
arr->length++;
return 0;
} }
size_t void array_list_sort(struct array_list *arr, int (*compar)(const void *, const void *))
array_list_length(struct array_list *arr)
{ {
return arr->length; qsort(arr->array, arr->length, sizeof(arr->array[0]), compar);
} }
int void *array_list_bsearch(const void **key, struct array_list *arr,
array_list_del_idx( struct array_list *arr, size_t idx, size_t count ) int (*compar)(const void *, const void *))
{
return bsearch(key, arr->array, arr->length, sizeof(arr->array[0]), compar);
}
size_t array_list_length(struct array_list *arr)
{
return arr->length;
}
int array_list_del_idx(struct array_list *arr, size_t idx, size_t count)
{ {
size_t i, stop; size_t i, stop;
/* Avoid overflow in calculation with large indices. */
if (idx > SIZE_T_MAX - count)
return -1;
stop = idx + count; stop = idx + count;
if ( idx >= arr->length || stop > arr->length ) return -1; if (idx >= arr->length || stop > arr->length)
for ( i = idx; i < stop; ++i ) { return -1;
if ( arr->array[i] ) arr->free_fn( arr->array[i] ); for (i = idx; i < stop; ++i)
{
// Because put_idx can skip entries, we need to check if
// there's actually anything in each slot we're erasing.
if (arr->array[i])
arr->free_fn(arr->array[i]);
} }
memmove( arr->array + idx, arr->array + stop, (arr->length - stop) * sizeof(void*) ); memmove(arr->array + idx, arr->array + stop, (arr->length - stop) * sizeof(void *));
arr->length -= count; arr->length -= count;
return 0; return 0;
} }

View File

@@ -15,53 +15,73 @@
* Although this is exposed by the json_object_get_array() method, * Although this is exposed by the json_object_get_array() method,
* it is not recommended for direct use. * it is not recommended for direct use.
*/ */
#ifndef _arraylist_h_ #ifndef _json_c_arraylist_h_
#define _arraylist_h_ #define _json_c_arraylist_h_
#ifdef __cplusplus #ifdef __cplusplus
extern "C" { extern "C" {
#endif #endif
#include <stddef.h>
#define ARRAY_LIST_DEFAULT_SIZE 32 #define ARRAY_LIST_DEFAULT_SIZE 32
typedef void (array_list_free_fn) (void *data); typedef void(array_list_free_fn)(void *data);
struct array_list struct array_list
{ {
void **array; void **array;
size_t length; size_t length;
size_t size; size_t size;
array_list_free_fn *free_fn; array_list_free_fn *free_fn;
}; };
typedef struct array_list array_list; typedef struct array_list array_list;
extern struct array_list* /**
array_list_new(array_list_free_fn *free_fn); * Allocate an array_list of the default size (32).
* @deprecated Use array_list_new2() instead.
*/
extern struct array_list *array_list_new(array_list_free_fn *free_fn);
extern void /**
array_list_free(struct array_list *al); * Allocate an array_list of the desired size.
*
* If possible, the size should be chosen to closely match
* the actual number of elements expected to be used.
* If the exact size is unknown, there are tradeoffs to be made:
* - too small - the array_list code will need to call realloc() more
* often (which might incur an additional memory copy).
* - too large - will waste memory, but that can be mitigated
* by calling array_list_shrink() once the final size is known.
*
* @see array_list_shrink
*/
extern struct array_list *array_list_new2(array_list_free_fn *free_fn, int initial_size);
extern void* extern void array_list_free(struct array_list *al);
array_list_get_idx(struct array_list *al, size_t i);
extern int extern void *array_list_get_idx(struct array_list *al, size_t i);
array_list_put_idx(struct array_list *al, size_t i, void *data);
extern int extern int array_list_insert_idx(struct array_list *al, size_t i, void *data);
array_list_add(struct array_list *al, void *data);
extern size_t extern int array_list_put_idx(struct array_list *al, size_t i, void *data);
array_list_length(struct array_list *al);
extern void extern int array_list_add(struct array_list *al, void *data);
array_list_sort(struct array_list *arr, int(*compar)(const void *, const void *));
extern void* array_list_bsearch(const void **key, extern size_t array_list_length(struct array_list *al);
struct array_list *arr,
int (*sort_fn)(const void *, const void *));
extern int extern void array_list_sort(struct array_list *arr, int (*compar)(const void *, const void *));
array_list_del_idx(struct array_list *arr, size_t idx, size_t count);
extern void *array_list_bsearch(const void **key, struct array_list *arr,
int (*compar)(const void *, const void *));
extern int array_list_del_idx(struct array_list *arr, size_t idx, size_t count);
/**
* Shrink the array list to just enough to fit the number of elements in it,
* plus empty_slots.
*/
extern int array_list_shrink(struct array_list *arr, size_t empty_slots);
#ifdef __cplusplus #ifdef __cplusplus
} }

View File

@@ -1,8 +0,0 @@
Autoconf Archive fetched from:
http://gnu.mirror.iweb.com/autoconf-archive/autoconf-archive-2015.09.25.tar.xz
Grabbed the minimum files needed for the AX_APPEND_COMPILE_FLAGS and
AX_COMPILE_CHECK_SIZEOF macros.

View File

@@ -1,65 +0,0 @@
# ===========================================================================
# http://www.gnu.org/software/autoconf-archive/ax_append_compile_flags.html
# ===========================================================================
#
# SYNOPSIS
#
# AX_APPEND_COMPILE_FLAGS([FLAG1 FLAG2 ...], [FLAGS-VARIABLE], [EXTRA-FLAGS])
#
# DESCRIPTION
#
# For every FLAG1, FLAG2 it is checked whether the compiler works with the
# flag. If it does, the flag is added FLAGS-VARIABLE
#
# If FLAGS-VARIABLE is not specified, the current language's flags (e.g.
# CFLAGS) is used. During the check the flag is always added to the
# current language's flags.
#
# If EXTRA-FLAGS is defined, it is added to the current language's default
# flags (e.g. CFLAGS) when the check is done. The check is thus made with
# the flags: "CFLAGS EXTRA-FLAGS FLAG". This can for example be used to
# force the compiler to issue an error when a bad flag is given.
#
# NOTE: This macro depends on the AX_APPEND_FLAG and
# AX_CHECK_COMPILE_FLAG. Please keep this macro in sync with
# AX_APPEND_LINK_FLAGS.
#
# LICENSE
#
# Copyright (c) 2011 Maarten Bosmans <mkbosmans@gmail.com>
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
#
# As a special exception, the respective Autoconf Macro's copyright owner
# gives unlimited permission to copy, distribute and modify the configure
# scripts that are the output of Autoconf when processing the Macro. You
# need not follow the terms of the GNU General Public License when using
# or distributing such scripts, even though portions of the text of the
# Macro appear in them. The GNU General Public License (GPL) does govern
# all other use of the material that constitutes the Autoconf Macro.
#
# This special exception to the GPL applies to versions of the Autoconf
# Macro released by the Autoconf Archive. When you make and distribute a
# modified version of the Autoconf Macro, you may extend this special
# exception to the GPL to apply to your modified version as well.
#serial 4
AC_DEFUN([AX_APPEND_COMPILE_FLAGS],
[AX_REQUIRE_DEFINED([AX_CHECK_COMPILE_FLAG])
AX_REQUIRE_DEFINED([AX_APPEND_FLAG])
for flag in $1; do
AX_CHECK_COMPILE_FLAG([$flag], [AX_APPEND_FLAG([$flag], [$2])], [], [$3])
done
])dnl AX_APPEND_COMPILE_FLAGS

View File

@@ -1,71 +0,0 @@
# ===========================================================================
# http://www.gnu.org/software/autoconf-archive/ax_append_flag.html
# ===========================================================================
#
# SYNOPSIS
#
# AX_APPEND_FLAG(FLAG, [FLAGS-VARIABLE])
#
# DESCRIPTION
#
# FLAG is appended to the FLAGS-VARIABLE shell variable, with a space
# added in between.
#
# If FLAGS-VARIABLE is not specified, the current language's flags (e.g.
# CFLAGS) is used. FLAGS-VARIABLE is not changed if it already contains
# FLAG. If FLAGS-VARIABLE is unset in the shell, it is set to exactly
# FLAG.
#
# NOTE: Implementation based on AX_CFLAGS_GCC_OPTION.
#
# LICENSE
#
# Copyright (c) 2008 Guido U. Draheim <guidod@gmx.de>
# Copyright (c) 2011 Maarten Bosmans <mkbosmans@gmail.com>
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
#
# As a special exception, the respective Autoconf Macro's copyright owner
# gives unlimited permission to copy, distribute and modify the configure
# scripts that are the output of Autoconf when processing the Macro. You
# need not follow the terms of the GNU General Public License when using
# or distributing such scripts, even though portions of the text of the
# Macro appear in them. The GNU General Public License (GPL) does govern
# all other use of the material that constitutes the Autoconf Macro.
#
# This special exception to the GPL applies to versions of the Autoconf
# Macro released by the Autoconf Archive. When you make and distribute a
# modified version of the Autoconf Macro, you may extend this special
# exception to the GPL to apply to your modified version as well.
#serial 6
AC_DEFUN([AX_APPEND_FLAG],
[dnl
AC_PREREQ(2.64)dnl for _AC_LANG_PREFIX and AS_VAR_SET_IF
AS_VAR_PUSHDEF([FLAGS], [m4_default($2,_AC_LANG_PREFIX[FLAGS])])
AS_VAR_SET_IF(FLAGS,[
AS_CASE([" AS_VAR_GET(FLAGS) "],
[*" $1 "*], [AC_RUN_LOG([: FLAGS already contains $1])],
[
AS_VAR_APPEND(FLAGS,[" $1"])
AC_RUN_LOG([: FLAGS="$FLAGS"])
])
],
[
AS_VAR_SET(FLAGS,[$1])
AC_RUN_LOG([: FLAGS="$FLAGS"])
])
AS_VAR_POPDEF([FLAGS])dnl
])dnl AX_APPEND_FLAG

View File

@@ -1,74 +0,0 @@
# ===========================================================================
# http://www.gnu.org/software/autoconf-archive/ax_check_compile_flag.html
# ===========================================================================
#
# SYNOPSIS
#
# AX_CHECK_COMPILE_FLAG(FLAG, [ACTION-SUCCESS], [ACTION-FAILURE], [EXTRA-FLAGS], [INPUT])
#
# DESCRIPTION
#
# Check whether the given FLAG works with the current language's compiler
# or gives an error. (Warnings, however, are ignored)
#
# ACTION-SUCCESS/ACTION-FAILURE are shell commands to execute on
# success/failure.
#
# If EXTRA-FLAGS is defined, it is added to the current language's default
# flags (e.g. CFLAGS) when the check is done. The check is thus made with
# the flags: "CFLAGS EXTRA-FLAGS FLAG". This can for example be used to
# force the compiler to issue an error when a bad flag is given.
#
# INPUT gives an alternative input source to AC_COMPILE_IFELSE.
#
# NOTE: Implementation based on AX_CFLAGS_GCC_OPTION. Please keep this
# macro in sync with AX_CHECK_{PREPROC,LINK}_FLAG.
#
# LICENSE
#
# Copyright (c) 2008 Guido U. Draheim <guidod@gmx.de>
# Copyright (c) 2011 Maarten Bosmans <mkbosmans@gmail.com>
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
#
# As a special exception, the respective Autoconf Macro's copyright owner
# gives unlimited permission to copy, distribute and modify the configure
# scripts that are the output of Autoconf when processing the Macro. You
# need not follow the terms of the GNU General Public License when using
# or distributing such scripts, even though portions of the text of the
# Macro appear in them. The GNU General Public License (GPL) does govern
# all other use of the material that constitutes the Autoconf Macro.
#
# This special exception to the GPL applies to versions of the Autoconf
# Macro released by the Autoconf Archive. When you make and distribute a
# modified version of the Autoconf Macro, you may extend this special
# exception to the GPL to apply to your modified version as well.
#serial 4
AC_DEFUN([AX_CHECK_COMPILE_FLAG],
[AC_PREREQ(2.64)dnl for _AC_LANG_PREFIX and AS_VAR_IF
AS_VAR_PUSHDEF([CACHEVAR],[ax_cv_check_[]_AC_LANG_ABBREV[]flags_$4_$1])dnl
AC_CACHE_CHECK([whether _AC_LANG compiler accepts $1], CACHEVAR, [
ax_check_save_flags=$[]_AC_LANG_PREFIX[]FLAGS
_AC_LANG_PREFIX[]FLAGS="$[]_AC_LANG_PREFIX[]FLAGS $4 $1"
AC_COMPILE_IFELSE([m4_default([$5],[AC_LANG_PROGRAM()])],
[AS_VAR_SET(CACHEVAR,[yes])],
[AS_VAR_SET(CACHEVAR,[no])])
_AC_LANG_PREFIX[]FLAGS=$ax_check_save_flags])
AS_VAR_IF(CACHEVAR,yes,
[m4_default([$2], :)],
[m4_default([$3], :)])
AS_VAR_POPDEF([CACHEVAR])dnl
])dnl AX_CHECK_COMPILE_FLAGS

View File

@@ -1,114 +0,0 @@
# ===========================================================================
# http://www.gnu.org/software/autoconf-archive/ax_compile_check_sizeof.html
# ===========================================================================
#
# SYNOPSIS
#
# AX_COMPILE_CHECK_SIZEOF(TYPE [, HEADERS [, EXTRA_SIZES...]])
#
# DESCRIPTION
#
# This macro checks for the size of TYPE using compile checks, not run
# checks. You can supply extra HEADERS to look into. the check will cycle
# through 1 2 4 8 16 and any EXTRA_SIZES the user supplies. If a match is
# found, it will #define SIZEOF_`TYPE' to that value. Otherwise it will
# emit a configure time error indicating the size of the type could not be
# determined.
#
# The trick is that C will not allow duplicate case labels. While this is
# valid C code:
#
# switch (0) case 0: case 1:;
#
# The following is not:
#
# switch (0) case 0: case 0:;
#
# Thus, the AC_TRY_COMPILE will fail if the currently tried size does not
# match.
#
# Here is an example skeleton configure.in script, demonstrating the
# macro's usage:
#
# AC_PROG_CC
# AC_CHECK_HEADERS(stddef.h unistd.h)
# AC_TYPE_SIZE_T
# AC_CHECK_TYPE(ssize_t, int)
#
# headers='#ifdef HAVE_STDDEF_H
# #include <stddef.h>
# #endif
# #ifdef HAVE_UNISTD_H
# #include <unistd.h>
# #endif
# '
#
# AX_COMPILE_CHECK_SIZEOF(char)
# AX_COMPILE_CHECK_SIZEOF(short)
# AX_COMPILE_CHECK_SIZEOF(int)
# AX_COMPILE_CHECK_SIZEOF(long)
# AX_COMPILE_CHECK_SIZEOF(unsigned char *)
# AX_COMPILE_CHECK_SIZEOF(void *)
# AX_COMPILE_CHECK_SIZEOF(size_t, $headers)
# AX_COMPILE_CHECK_SIZEOF(ssize_t, $headers)
# AX_COMPILE_CHECK_SIZEOF(ptrdiff_t, $headers)
# AX_COMPILE_CHECK_SIZEOF(off_t, $headers)
#
# LICENSE
#
# Copyright (c) 2008 Kaveh Ghazi <ghazi@caip.rutgers.edu>
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
#
# As a special exception, the respective Autoconf Macro's copyright owner
# gives unlimited permission to copy, distribute and modify the configure
# scripts that are the output of Autoconf when processing the Macro. You
# need not follow the terms of the GNU General Public License when using
# or distributing such scripts, even though portions of the text of the
# Macro appear in them. The GNU General Public License (GPL) does govern
# all other use of the material that constitutes the Autoconf Macro.
#
# This special exception to the GPL applies to versions of the Autoconf
# Macro released by the Autoconf Archive. When you make and distribute a
# modified version of the Autoconf Macro, you may extend this special
# exception to the GPL to apply to your modified version as well.
#serial 5
AU_ALIAS([AC_COMPILE_CHECK_SIZEOF], [AX_COMPILE_CHECK_SIZEOF])
AC_DEFUN([AX_COMPILE_CHECK_SIZEOF],
[changequote(<<, >>)dnl
dnl The name to #define.
define(<<AC_TYPE_NAME>>, translit(sizeof_$1, [a-z *], [A-Z_P]))dnl
dnl The cache variable name.
define(<<AC_CV_NAME>>, translit(ac_cv_sizeof_$1, [ *], [_p]))dnl
changequote([, ])dnl
AC_MSG_CHECKING(size of $1)
AC_CACHE_VAL(AC_CV_NAME,
[for ac_size in 4 8 1 2 16 $3 ; do # List sizes in rough order of prevalence.
AC_TRY_COMPILE([#include "confdefs.h"
#include <sys/types.h>
$2
], [switch (0) case 0: case (sizeof ($1) == $ac_size):;], AC_CV_NAME=$ac_size)
if test x$AC_CV_NAME != x ; then break; fi
done
])
if test x$AC_CV_NAME = x ; then
AC_MSG_ERROR([cannot determine a size for $1])
fi
AC_MSG_RESULT($AC_CV_NAME)
AC_DEFINE_UNQUOTED(AC_TYPE_NAME, $AC_CV_NAME, [The number of bytes in type $1])
undefine([AC_TYPE_NAME])dnl
undefine([AC_CV_NAME])dnl
])

View File

@@ -1,37 +0,0 @@
# ===========================================================================
# http://www.gnu.org/software/autoconf-archive/ax_require_defined.html
# ===========================================================================
#
# SYNOPSIS
#
# AX_REQUIRE_DEFINED(MACRO)
#
# DESCRIPTION
#
# AX_REQUIRE_DEFINED is a simple helper for making sure other macros have
# been defined and thus are available for use. This avoids random issues
# where a macro isn't expanded. Instead the configure script emits a
# non-fatal:
#
# ./configure: line 1673: AX_CFLAGS_WARN_ALL: command not found
#
# It's like AC_REQUIRE except it doesn't expand the required macro.
#
# Here's an example:
#
# AX_REQUIRE_DEFINED([AX_CHECK_LINK_FLAG])
#
# LICENSE
#
# Copyright (c) 2014 Mike Frysinger <vapier@gentoo.org>
#
# Copying and distribution of this file, with or without modification, are
# permitted in any medium without royalty provided the copyright notice
# and this notice are preserved. This file is offered as-is, without any
# warranty.
#serial 1
AC_DEFUN([AX_REQUIRE_DEFINED], [dnl
m4_ifndef([$1], [m4_fatal([macro ]$1[ is not defined; is a m4 file missing?])])
])dnl AX_REQUIRE_DEFINED

View File

@@ -1,13 +0,0 @@
#!/bin/sh
autoreconf -v --install || exit 1
# If there are any options, assume the user wants to run configure.
# To run configure w/o any options, use ./autogen.sh --configure
if [ $# -gt 0 ] ; then
case "$1" in
--conf*)
shift 1
;;
esac
exec ./configure "$@"
fi

80
bench/README.bench.md Normal file
View File

@@ -0,0 +1,80 @@
Benchmark tests for json-c
General strategy:
-------------------
* Identify "after" commit hash
* Use provided directory
* Use provided commit hash
* Local changes in current working directory
* ${cur_branch}
* Identify "before" commit hash, in order of preference
* Use provided directory
* Use provided commit hash
* Use origin/${cur_branch}, if different from ${after_commit}
* Use previous release
* If not using existing dir, clone to src-${after_commit}
* or, checkout appropriate commit in existing src-${after_commit}
* Create build & install dirs for ${after_commit}
* Build & install ${after_commit}
* Compile benchmark programs against install-${after_commit}
* If not using existing dir, clone to src-${before_commit}
* or, checkout appropriate commit in existing src-${before_commit}
* Create build & install dirs for ${before_commit}
* Build & install ${before_commit}
* Compile benchmark programs against install-${before_commit}
* Run benchmark in each location
* Compare results
heaptrack memory profiler
---------------------------
https://milianw.de/blog/heaptrack-a-heap-memory-profiler-for-linux.html
```
yum install libdwarf-devel elfutils boost-devel libunwind-devel
git clone git://anongit.kde.org/heaptrack
cd heaptrack
mkdir build
cd build
cmake -DCMAKE_BUILD_TYPE=RelWithDebInfo \
-DCMAKE_INSTALL_PREFIX=$HOME/heaptrack-install ..
make install
```
Issues
--------
* jc-bench.sh is incomplete.
* valgrind massif misreports "extra-heap" bytes?
"json_parse -n canada.json" shows 38640 KB maxrss.
Using valgrind --tool=massif, a large amount of memory is listed as
wasted "extra-heap" bytes. (~5.6MB)
```
valgrind --tool=massif --massif-out-file=massif.out ./json_parse -n ~/canada.json
ms_print massif.out
```
Using heaptrack, and analyzing the histogram, only shows ~2.6MB
```
heaptrack ./json_parse -n canada.json
heaptrack --analyze heaptrack*gz -H histogram.out
awk ' { s=$1; count=$2; ru=(int((s+ 15) / 16)) * 16; wasted = ((ru-s)*count); print s, count, ru-s, wasted; total=total+wasted} END { print "Total: ", total }' histogram.out
```
With the (unreleased) arraylist trimming changes, maxrss reported by
getrusage() goes down, but massif claims *more* total usage, and a HUGE
extra-heap amount (50% of total).

284
bench/jc-bench.sh Executable file
View File

@@ -0,0 +1,284 @@
#!/bin/sh
#
# Benchmarking harness for json-c
#
# Use this to compare the behavior of two different versions of the library,
# such as json-c-0.14 release vs master, master vs local changes, etc...
#
set -e
trap 'echo "FAILED!"' EXIT
RUNDIR=$(dirname "$0")
RUNDIR=$(cd "$RUNDIR" && pwd)
TOP=$(cd "$RUNDIR/.." && pwd)
usage()
{
exitval=$1
errmsg=$2
if [ $exitval -ne 0 ] ; then
exec 1>&2
fi
if [ ! -z "$errmsg" ] ; then
echo "ERROR: $errmsg" 1>&2
fi
cat <<EOF
Usage: $0 [-h] [-v] [--build] [--run] [--compare] ...XAX...
EOF
exit $extival
}
before_arg=
after_arg=
do_all=1
do_build=0
do_run=0
do_compare=0
while [ $# -gt 0 ] ; do
case "$1" in
--before)
before_arg=$2
shift
;;
--after)
after_arg=$2
shift
;;
--build)
do_all=0
do_build=1
;;
--run)
do_all=0
do_run=1
;;
--compare)
do_all=0
do_compare=1
;;
-h)
usage 0 ""
;;
-v)
set -x
;;
*)
usage 1 "Unknown args: $*"
;;
esac
shift
done
WORK="${RUNDIR}/work"
mkdir -p "${WORK}"
DATA="${RUNDIR}/data"
mkdir -p "${DATA}"
for file in citm_catalog.json twitter.json canada.json ; do
if [ ! -r "${DATA}/${file}" ] ; then
echo "Fetching ${file} from github.com/mloskot/json_benchmark"
URL="https://github.com/mloskot/json_benchmark/raw/master/data/${file}"
curl -s -L -o "${DATA}/${file}" "$URL"
fi
done
echo
# Identify "after" commit hash, in order of preference
if [ ! -z "$after_arg" -a -d "$after_arg" ] ; then
# Use provided directory
after_src_dir="$after_arg"
after_commit=
echo "Using provided directory [$after_arg] as 'after'"
else
_commit=
if [ ! -z "$after_arg" ] ; then
# Use provided commit hash
_commit=$(git rev-parse --verify "$after_arg")
fi
if [ ! -z "$_commit" ] ;then
after_src_dir= # i.e. current tree
after_commit="$_commit"
echo "Using provided commit [$after_arg => $_commit] as 'after'"
else
# Local changes in current working directory
# ${cur_branch}
after_src_dir=$TOP
after_commit=
echo "Using local changes in $TOP as 'after'"
fi
fi
# Identify "before" commit hash, in order of preference
if [ ! -z "$before_arg" -a -d "$before_arg" ] ; then
# Use provided directory
before_src_dir="$before_arg"
before_commit=
echo "Using provided directory [$before_arg] as 'before'"
else
_commit=
if [ ! -z "$before_arg" ] ; then
# Use provided commit hash
_commit=$(git rev-parse --verify "$before_arg")
fi
if [ ! -z "$_commit" ] ;then
before_src_dir= # i.e. current tree
before_commit="$_commit"
echo "Using provided commit [$before_arg => $_commit] as 'before'"
else
# Use origin/${cur_branch}, if different from ${after_commit}
_cur_branch=$(git rev-parse --abbrev-ref HEAD)
_commit=
if [ ! -z "${_cur_branch}" ] ; then
_commit=$(git rev-parse --verify "origin/${_cur_branch}")
echo "Using origin/${_cur_branch} [$_commit] as 'before'"
fi
if [ "$_commit" = "${after_commit}" ] ; then
_commit=
fi
fi
if [ ! -z "$_commit" ] ; then
before_src_dir= # i.e. current tree
before_commit="$_commit"
else
# Use previous release
before_src_dir= # i.e. current tree
before_commit="$(git tag | sort | tail -1)"
echo "Using previous release [$before_commit] as 'before'"
fi
fi
echo
compile_benchmark()
{
local bname=$1
local src_dir="$2"
local src_commit="$3"
local build_dir="${WORK}/$bname/build"
local inst_dir="${WORK}/$bname/install"
local bench_dir="${WORK}/$bname/bench"
echo
echo "=========== $bname ==========="
echo
mkdir -p "${build_dir}"
mkdir -p "${inst_dir}"
mkdir -p "${bench_dir}"
if [ ! -z "$src_commit" ] ; then
# Resolve the short hash, tag or branch name to full hash
src_commit=$(git rev-parse $src_commit)
fi
# No src dir specified, clone and checkout $src_commit
if [ -z "$src_dir" ] ; then
src_dir="${WORK}/$bname/src"
echo "=== Using sources in $src_dir"
mkdir -p "$src_dir"
at_commit=$(git --git-dir="$src_dir/.git" rev-parse HEAD 2> /dev/null || true)
echo "at_commit: $at_commit"
if [ -z "$at_commit" ] ; then
# Assume it's an empty dir
git clone -n "$TOP" "$src_dir"
fi
git -C "$src_dir" --git-dir="$src_dir/.git" checkout "$src_commit"
fi
# else, use the provided $src_dir
if [ -e "${src_dir}/CMakeLists.txt" ] ; then
cd "${build_dir}"
cmake -DCMAKE_INSTALL_PREFIX="${inst_dir}" "${src_dir}"
else
# Old versions of json-c used automake/autoconf
cd "${src_dir}"
sh autogen.sh # always run it, configure doesn't always work
cd "${build_dir}"
"${src_dir}/configure" --prefix="${inst_dir}"
fi
make all install
cd "${bench_dir}"
cmake -DCMAKE_PREFIX_PATH="${inst_dir}" "${TOP}/apps"
make all
}
# XXX TODO: name "after" and "before" uniquely using the dir & commit
if [ $do_all -ne 0 -o $do_build -ne 0 ] ; then
sleep 5 # Wait slightly, to allow the human to read the message
# about what exactly we're doing to benchmark.
compile_benchmark "after" "${after_src_dir}" "${after_commit}"
compile_benchmark "before" "${before_src_dir}" "${before_commit}"
fi
run_benchmark()
{
local bname=$1
local inst_dir="${WORK}/$bname/install"
local bench_dir="${WORK}/$bname/bench"
local INPUT=${DATA}/canada.json
cd "${bench_dir}"
mkdir -p results
(time ./json_parse -n "${INPUT}") > results/basic_timing.out 2>&1
valgrind --tool=massif --massif-out-file=massif.out ./json_parse -n "${INPUT}"
ms_print massif.out > results/ms_print.out
heaptrack -o heaptrack_out ./json_parse -n "${INPUT}"
heaptrack --analyze heaptrack_out.gz -H histogram.out > results/heaptrack.out
awk ' { s=$1; count=$2; ru=(int((s+ 15) / 16)) * 16; wasted = ((ru-s)*count); print s, count, ru-s, wasted; total=total+wasted} END { print "Total: ", total }' histogram.out > results/histogram2.out
# XXX stamp some info about what was built & run into ./results/.
echo "DONE with $bname"
}
if [ $do_all -ne 0 -o $do_run -ne 0 ] ; then
run_benchmark "after"
run_benchmark "before"
fi
if [ $do_compare -ne 0 ] ; then
# XXX this needs better analysis
cd "${WORK}"
diff -udr before/bench/results after/bench/results || true
else
echo "To compare results, run:"
echo "$0 --compare"
fi
trap '' EXIT
:<<=cut
Benchmarks to run:
* Parse JSON strings, of various sizes and characteristics
* Flags: STRICT vs. non-STRICT, validate UTF8
* Serialization time
* plain, spaces, pretty
* json_c_visit tests
* JSON pointer tests
Things to record and compare:
* Running time
* Peak memory usage
* Useful bytes vs. overhead for memory allocations
* Total number of allocations
* Average allocation size
* Log of all allocation sizes
=cut

36
bits.h
View File

@@ -1,36 +0,0 @@
/**
* @file
* @brief Do not use, only contains deprecated defines.
* @deprecated Use json_util.h instead.
*
* $Id: bits.h,v 1.10 2006/01/30 23:07:57 mclark Exp $
*
* Copyright (c) 2004, 2005 Metaparadigm Pte. Ltd.
* Michael Clark <michael@metaparadigm.com>
*
* This library is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See COPYING for details.
*
*/
#ifndef _bits_h_
#define _bits_h_
/**
* @deprecated
*/
#define hexdigit(x) (((x) <= '9') ? (x) - '0' : ((x) & 7) + 9)
/**
* @deprecated
*/
#define error_ptr(error) ((void*)error)
/**
* @deprecated
*/
#define error_description(error) (json_tokener_get_error(error))
/**
* @deprecated
*/
#define is_error(ptr) (ptr == NULL)
#endif

100
cmake-configure Executable file
View File

@@ -0,0 +1,100 @@
#!/bin/bash
# Wrapper around cmake to emulate useful options
# from the previous autoconf-based configure script.
RUNDIR=$(dirname "$0")
RUNDIR=$(cd "$RUNDIR" && pwd)
CURDIR=$(pwd)
FLAGS=()
usage()
{
exitval="$1"
errmsg="$2"
if [ $exitval -ne 0 ] ; then
exec 1>&2
fi
if [ ! -z "$errmsg" ] ; then
echo "ERROR: $errmsg" 1>&2
fi
cat <<EOF
$0 [<configure_options>] [-- [<cmake options>]]
--prefix=PREFIX install architecture-independent files in PREFIX
--enable-threading Enable code to support partly multi-threaded use
--enable-rdrand Enable RDRAND Hardware RNG Hash Seed generation on
supported x86/x64 platforms.
--enable-shared build shared libraries [default=yes]
--enable-static build static libraries [default=yes]
--disable-Bsymbolic Avoid linking with -Bsymbolic-function
--disable-werror Avoid treating compiler warnings as fatal errors
--disable-extra-libs Avoid linking against extra libraries, such as libbsd
EOF
exit
}
if [ "$CURDIR" = "$RUNDIR" ] ; then
usage 1 "Please mkdir some other build directory, and run this script from there."
fi
if ! cmake --version ; then
usage 1 "Unable to find a working cmake, please be sure you have it installed and on your PATH"
fi
while [ $# -gt 0 ] ; do
case "$1" in
-h|--help)
usage 0
;;
--prefix)
FLAGS+=(-DCMAKE_INSTALL_PREFIX="$2")
shift
;;
--prefix=*)
FLAGS+=(-DCMAKE_INSTALL_PREFIX="${1##--prefix=}")
;;
--enable-threading)
FLAGS+=(-DENABLE_THREADING=ON)
;;
--enable-rdrand)
FLAGS+=(-DENABLE_RDRAND=ON)
;;
--enable-shared)
FLAGS+=(-DBUILD_SHARED_LIBS=ON)
;;
--disable-shared)
FLAGS+=(-DBUILD_SHARED_LIBS=OFF)
;;
--enable-static)
FLAGS+=(-DBUILD_STATIC_LIBS=ON)
;;
--disable-static)
FLAGS+=(-DBUILD_STATIC_LIBS=OFF)
;;
--disable-Bsymbolic)
FLAGS+=(-DDISABLE_BSYMBOLIC=ON)
;;
--disable-werror)
FLAGS+=(-DDISABLE_WERROR=ON)
;;
--disable-extra-libs)
FLAGS+=(-DDISABLE_EXTRA_LIBS=ON)
;;
--)
shift
break
;;
-*)
usage 1 "Unknown arguments: $*"
;;
*)
break
;;
esac
shift
done
exec cmake "${FLAGS[@]}" "$@" "${RUNDIR}"

4
cmake/Config.cmake.in Normal file
View File

@@ -0,0 +1,4 @@
@PACKAGE_INIT@
include("${CMAKE_CURRENT_LIST_DIR}/@PROJECT_NAME@-targets.cmake")
check_required_components("@PROJECT_NAME@")

231
cmake/config.h.in Normal file
View File

@@ -0,0 +1,231 @@
/* Enable RDRAND Hardware RNG Hash Seed */
#cmakedefine ENABLE_RDRAND "@ENABLE_RDRAND@"
/* Override json_c_get_random_seed() with custom code */
#cmakedefine OVERRIDE_GET_RANDOM_SEED @OVERRIDE_GET_RANDOM_SEED@
/* Enable partial threading support */
#cmakedefine ENABLE_THREADING "@@"
/* Define if .gnu.warning accepts long strings. */
#cmakedefine HAS_GNU_WARNING_LONG "@@"
/* Define to 1 if you have the <dlfcn.h> header file. */
#cmakedefine HAVE_DLFCN_H
/* Define to 1 if you have the <endian.h> header file. */
#cmakedefine HAVE_ENDIAN_H
/* Define to 1 if you have the <fcntl.h> header file. */
#cmakedefine HAVE_FCNTL_H
/* Define to 1 if you have the <inttypes.h> header file. */
#cmakedefine HAVE_INTTYPES_H
/* Define to 1 if you have the <limits.h> header file. */
#cmakedefine HAVE_LIMITS_H
/* Define to 1 if you have the <locale.h> header file. */
#cmakedefine HAVE_LOCALE_H
/* Define to 1 if you have the <memory.h> header file. */
#cmakedefine HAVE_MEMORY_H
/* Define to 1 if you have the <stdarg.h> header file. */
#cmakedefine HAVE_STDARG_H
/* Define to 1 if you have the <stdint.h> header file. */
#cmakedefine HAVE_STDINT_H
/* Define to 1 if you have the <stdlib.h> header file. */
#cmakedefine HAVE_STDLIB_H
/* Define to 1 if you have the <strings.h> header file. */
#cmakedefine HAVE_STRINGS_H
/* Define to 1 if you have the <string.h> header file. */
#cmakedefine HAVE_STRING_H
/* Define to 1 if you have the <syslog.h> header file. */
#cmakedefine HAVE_SYSLOG_H @HAVE_SYSLOG_H@
/* Define to 1 if you have the <sys/cdefs.h> header file. */
#cmakedefine HAVE_SYS_CDEFS_H
/* Define to 1 if you have the <sys/param.h> header file. */
#cmakedefine HAVE_SYS_PARAM_H @HAVE_SYS_PARAM_H@
/* Define to 1 if you have the <sys/random.h> header file. */
#cmakedefine HAVE_SYS_RANDOM_H
/* Define to 1 if you have the <sys/resource.h> header file. */
#cmakedefine HAVE_SYS_RESOURCE_H
/* Define to 1 if you have the <sys/stat.h> header file. */
#cmakedefine HAVE_SYS_STAT_H
/* Define to 1 if you have the <sys/types.h> header file. */
#cmakedefine HAVE_SYS_TYPES_H @HAVE_SYS_TYPES_H@
/* Define to 1 if you have the <unistd.h> header file. */
#cmakedefine HAVE_UNISTD_H @HAVE_UNISTD_H@
/* Define to 1 if you have the <xlocale.h> header file. */
#cmakedefine HAVE_XLOCALE_H
/* Define to 1 if you have the <bsd/stdlib.h> header file. */
#cmakedefine HAVE_BSD_STDLIB_H
/* Define to 1 if you have `arc4random' */
#cmakedefine HAVE_ARC4RANDOM
/* Define to 1 if you don't have `vprintf' but do have `_doprnt.' */
#cmakedefine HAVE_DOPRNT
/* Has atomic builtins */
#cmakedefine HAVE_ATOMIC_BUILTINS
/* Define to 1 if you have the declaration of `INFINITY', and to 0 if you
don't. */
#cmakedefine HAVE_DECL_INFINITY
/* Define to 1 if you have the declaration of `isinf', and to 0 if you don't.
*/
#cmakedefine HAVE_DECL_ISINF
/* Define to 1 if you have the declaration of `isnan', and to 0 if you don't.
*/
#cmakedefine HAVE_DECL_ISNAN
/* Define to 1 if you have the declaration of `nan', and to 0 if you don't. */
#cmakedefine HAVE_DECL_NAN
/* Define to 1 if you have the declaration of `_finite', and to 0 if you
don't. */
#cmakedefine HAVE_DECL__FINITE
/* Define to 1 if you have the declaration of `_isnan', and to 0 if you don't.
*/
#cmakedefine HAVE_DECL__ISNAN
/* Define to 1 if you have the `open' function. */
#cmakedefine HAVE_OPEN
/* Define to 1 if you have the `realloc' function. */
#cmakedefine HAVE_REALLOC
/* Define to 1 if you have the `setlocale' function. */
#cmakedefine HAVE_SETLOCALE
/* Define to 1 if you have the `snprintf' function. */
#cmakedefine HAVE_SNPRINTF
/* Define to 1 if you have the `strcasecmp' function. */
#cmakedefine HAVE_STRCASECMP @HAVE_STRCASECMP@
/* Define to 1 if you have the `strdup' function. */
#cmakedefine HAVE_STRDUP
/* Define to 1 if you have the `strerror' function. */
#cmakedefine HAVE_STRERROR
/* Define to 1 if you have the `strncasecmp' function. */
#cmakedefine HAVE_STRNCASECMP @HAVE_STRNCASECMP@
/* Define to 1 if you have the `uselocale' function. */
#cmakedefine HAVE_USELOCALE
/* Define to 1 if newlocale() needs freelocale() called on it's `base` argument */
#cmakedefine NEWLOCALE_NEEDS_FREELOCALE
/* Define to 1 if you have the `vasprintf' function. */
#cmakedefine HAVE_VASPRINTF
/* Define to 1 if you have the `vprintf' function. */
#cmakedefine HAVE_VPRINTF
/* Define to 1 if you have the `vsnprintf' function. */
#cmakedefine HAVE_VSNPRINTF
/* Define to 1 if you have the `vsyslog' function. */
#cmakedefine HAVE_VSYSLOG @HAVE_VSYSLOG@
/* Define if you have the `getrandom' function. */
#cmakedefine HAVE_GETRANDOM
/* Define if you have the `getrusage' function. */
#cmakedefine HAVE_GETRUSAGE
#cmakedefine HAVE_STRTOLL
#if !defined(HAVE_STRTOLL)
#define strtoll @json_c_strtoll@
/* #cmakedefine json_c_strtoll @json_c_strtoll@*/
#endif
#cmakedefine HAVE_STRTOULL
#if !defined(HAVE_STRTOULL)
#define strtoull @json_c_strtoull@
/* #cmakedefine json_c_strtoull @json_c_strtoull@ */
#endif
/* Have __thread */
#cmakedefine HAVE___THREAD
/* Public define for json_inttypes.h */
#cmakedefine JSON_C_HAVE_INTTYPES_H @JSON_C_HAVE_INTTYPES_H@
/* Name of package */
#define PACKAGE "@PROJECT_NAME@"
/* Define to the address where bug reports for this package should be sent. */
#define PACKAGE_BUGREPORT "@JSON_C_BUGREPORT@"
/* Define to the full name of this package. */
#define PACKAGE_NAME "@PROJECT_NAME@"
/* Define to the full name and version of this package. */
#define PACKAGE_STRING "@PROJECT_NAME@ @CPACK_PACKAGE_VERSION_MAJOR@.@CPACK_PACKAGE_VERSION_MINOR@.@CPACK_PACKAGE_VERSION_PATCH@"
/* Define to the one symbol short name of this package. */
#define PACKAGE_TARNAME "@PROJECT_NAME@"
/* Define to the home page for this package. */
#define PACKAGE_URL "https://github.com/json-c/json-c"
/* Define to the version of this package. */
#define PACKAGE_VERSION "@CPACK_PACKAGE_VERSION_MAJOR@.@CPACK_PACKAGE_VERSION_MINOR@.@CPACK_PACKAGE_VERSION_PATCH@"
/* The number of bytes in type int */
#cmakedefine SIZEOF_INT @SIZEOF_INT@
/* The number of bytes in type int64_t */
#cmakedefine SIZEOF_INT64_T @SIZEOF_INT64_T@
/* The number of bytes in type long */
#cmakedefine SIZEOF_LONG @SIZEOF_LONG@
/* The number of bytes in type long long */
#cmakedefine SIZEOF_LONG_LONG @SIZEOF_LONG_LONG@
/* The number of bytes in type size_t */
#cmakedefine SIZEOF_SIZE_T @SIZEOF_SIZE_T@
/* The number of bytes in type ssize_t */
#cmakedefine SIZEOF_SSIZE_T @SIZEOF_SSIZE_T@
/* Specifier for __thread */
#cmakedefine SPEC___THREAD @SPEC___THREAD@
/* Define to 1 if you have the ANSI C header files. */
#cmakedefine STDC_HEADERS
/* Version number of package */
#define VERSION "@CPACK_PACKAGE_VERSION_MAJOR@.@CPACK_PACKAGE_VERSION_MINOR@.@CPACK_PACKAGE_VERSION_PATCH@"
/* Define to empty if `const' does not conform to ANSI C. */
#cmakedefine const
/* Define to `unsigned int' if <sys/types.h> does not define. */
#cmakedefine size_t

5
cmake/json_config.h.in Normal file
View File

@@ -0,0 +1,5 @@
/* Define to 1 if you have the <inttypes.h> header file. */
#cmakedefine JSON_C_HAVE_INTTYPES_H @JSON_C_HAVE_INTTYPES_H@
/* Define to 1 if you have the <stdint.h> header file. */
#cmakedefine JSON_C_HAVE_STDINT_H @JSON_C_HAVE_STDINT_H@

View File

@@ -1,205 +0,0 @@
/* config.h.in. Generated from configure.ac by autoheader. */
/* Enable RDRANR Hardware RNG Hash Seed */
#undef ENABLE_RDRAND
/* Define if .gnu.warning accepts long strings. */
#undef HAS_GNU_WARNING_LONG
/* Define to 1 if you have the declaration of `INFINITY', and to 0 if you
don't. */
#if (defined(_MSC_VER) && _MSC_VER >= 1800) || defined(__MINGW32__)
#define HAVE_DECL_INFINITY 1
#endif
/* Define to 1 if you have the declaration of `isinf', and to 0 if you don't.
*/
#if (defined(_MSC_VER) && _MSC_VER >= 1800) || defined(__MINGW32__)
#define HAVE_DECL_ISINF 1
#endif
/* Define to 1 if you have the declaration of `isnan', and to 0 if you don't.
*/
#if (defined(_MSC_VER) && _MSC_VER >= 1800) || defined(__MINGW32__)
#define HAVE_DECL_ISNAN 1
#endif
/* Define to 1 if you have the declaration of `nan', and to 0 if you don't. */
#if (defined(_MSC_VER) && _MSC_VER >= 1800) || defined(__MINGW32__)
#define HAVE_DECL_NAN 1
#endif
/* Define to 1 if you have the declaration of `_finite', and to 0 if you
don't. */
#define HAVE_DECL__FINITE 1
/* Define to 1 if you have the declaration of `_isnan', and to 0 if you don't.
*/
#define HAVE_DECL__ISNAN 1
/* Define to 1 if you have the <dlfcn.h> header file. */
#define HAVE_DLFCN_H 1
/* Define to 1 if you don't have `vprintf' but do have `_doprnt.' */
#define HAVE_DOPRNT 1
/* Define to 1 if you have the <endian.h> header file. */
#undef HAVE_ENDIAN_H
/* Define to 1 if you have the <fcntl.h> header file. */
#define HAVE_FCNTL_H 1
/* Define to 1 if you have the <inttypes.h> header file. */
#define HAVE_INTTYPES_H 1
/* Define to 1 if you have the <limits.h> header file. */
#define HAVE_LIMITS_H 1
/* Define to 1 if you have the <locale.h> header file. */
#define HAVE_LOCALE_H 1
/* Define to 1 if your system has a GNU libc compatible `malloc' function, and
to 0 otherwise. */
#define HAVE_MALLOC 1
/* Define to 1 if you have the <memory.h> header file. */
#define HAVE_MEMORY_H 1
/* Define to 1 if you have the `open' function. */
#define HAVE_OPEN 1
/* Define to 1 if your system has a GNU libc compatible `realloc' function,
and to 0 otherwise. */
#define HAVE_REALLOC 1
/* Define to 1 if you have the `setlocale' function. */
#define HAVE_SETLOCALE 1
/* Define to 1 if you have the `snprintf' function. */
#if defined(__MINGW32__)
#define HAVE_SNPRINTF 1
#else
#undef HAVE_SNPRINTF
#endif
/* Define to 1 if you have the <stdarg.h> header file. */
#define HAVE_STDARG_H 1
/* Define to 1 if you have the <stdint.h> header file. */
#define HAVE_STDINT_H 1
/* Define to 1 if you have the <stdlib.h> header file. */
#define HAVE_STDLIB_H 1
/* Define to 1 if you have the `strcasecmp' function. */
#define HAVE_STRCASECMP 1
/* Define to 1 if you have the `strdup' function. */
#define HAVE_STRDUP 0
/* Define to 1 if you have the `strerror' function. */
#define HAVE_STRERROR 1
/* Define to 1 if you have the <strings.h> header file. */
#undef HAVE_STRINGS_H
/* Define to 1 if you have the <string.h> header file. */
#define HAVE_STRING_H 1
/* Define to 1 if you have the `strncasecmp' function. */
#if defined(__MINGW32__)
#define HAVE_STRNCASECMP 1
#else
#undef HAVE_STRNCASECMP
#endif
#cmakedefine HAVE_STRTOLL
#cmakedefine strtoll @cmake_strtoll@
/* Define to 1 if you have the <syslog.h> header file. */
#undef HAVE_SYSLOG_H
/* Define to 1 if you have the <sys/cdefs.h> header file. */
#define HAVE_SYS_CDEFS_H 1
/* Define to 1 if you have the <sys/param.h> header file. */
#if defined(__MINGW32__)
#define HAVE_SYS_PARAM_H 1
#else
#undef HAVE_SYS_PARAM_H
#endif
/* Define to 1 if you have the <sys/stat.h> header file. */
#define HAVE_SYS_STAT_H 1
/* Define to 1 if you have the <sys/types.h> header file. */
#define HAVE_SYS_TYPES_H 1
/* Define to 1 if you have the <unistd.h> header file. */
#if defined(__MINGW32__)
#define HAVE_UNISTD_H 1
#else
#undef HAVE_UNISTD_H
#endif
/* Define to 1 if you have the `vasprintf' function. */
#if defined(__MINGW32__)
#define HAVE_VASPRINTF 1
#else
#undef HAVE_VASPRINTF
#endif
/* Define to 1 if you have the `vprintf' function. */
#define HAVE_VPRINTF 1
/* Define to 1 if you have the `vsnprintf' function. */
#define HAVE_VSNPRINTF 1
/* Define to 1 if you have the `vsyslog' function. */
#undef HAVE_VSYSLOG
/* Define to the sub-directory in which libtool stores uninstalled libraries.
*/
#undef LT_OBJDIR
/* Define to 1 if your C compiler doesn't accept -c and -o together. */
/* #undef NO_MINUS_C_MINUS_O */
/* Name of package */
#define PACKAGE "json-c"
/* Define to the address where bug reports for this package should be sent. */
#define PACKAGE_BUGREPORT "json-c@googlegroups.com"
/* Define to the full name of this package. */
#define PACKAGE_NAME "JSON C Library"
/* Define to the full name and version of this package. */
#define PACKAGE_STRING "JSON C Library 0.12.99"
/* Define to the one symbol short name of this package. */
#define PACKAGE_TARNAME "json-c"
/* Define to the home page for this package. */
#define PACKAGE_URL "https://github.com/json-c/json-c"
/* Define to the version of this package. */
#define PACKAGE_VERSION "0.12.99"
/* Define to 1 if you have the ANSI C header files. */
#define STDC_HEADERS 1
/* Version number of package */
#define VERSION "0.12.99"
/* Define to empty if `const' does not conform to ANSI C. */
/* #undef const */
/* Define to rpl_malloc if the replacement function should be used. */
/* #undef malloc */
/* Define to rpl_realloc if the replacement function should be used. */
/* #undef realloc */
/* Define to `unsigned int' if <sys/types.h> does not define. */
/* #undef size_t */

View File

@@ -1,186 +0,0 @@
AC_PREREQ(2.64)
# Process this file with autoconf to produce a configure script.
AC_INIT([json-c], 0.12.99, [json-c@googlegroups.com])
AM_INIT_AUTOMAKE
AC_CONFIG_MACRO_DIRS([autoconf-archive/m4])
AC_PROG_MAKE_SET
AC_CANONICAL_HOST
AC_ARG_ENABLE(threading,
AS_HELP_STRING([--enable-threading],
[Enable code to support partly multi-threaded use]),
[if test x$enableval = xyes; then
enable_threading=yes
AC_DEFINE(ENABLE_THREADING, 1, [Enable partial threading support])
fi])
if test "x$enable_threading" = "xyes"; then
AC_MSG_RESULT([Partial multi-threaded support enabled.])
else
AC_MSG_RESULT([Multi-threaded support disabled. Use --enable-threading to enable.])
fi
AC_ARG_ENABLE(rdrand,
AS_HELP_STRING([--enable-rdrand],
[Enable RDRAND Hardware RNG Hash Seed generation on supported x86/x64 platforms.]),
[if test x$enableval = xyes; then
enable_rdrand=yes
AC_DEFINE(ENABLE_RDRAND, 1, [Enable RDRAND Hardware RNG Hash Seed])
fi])
if test "x$enable_rdrand" = "xyes"; then
AC_MSG_RESULT([RDRAND Hardware RNG Hash Seed enabled on supported x86/x64 platforms])
else
AC_MSG_RESULT([RDRAND Hardware RNG Hash Seed disabled. Use --enable-rdrand to enable])
fi
# enable silent build by default
m4_ifdef([AM_SILENT_RULES], [AM_SILENT_RULES([yes])])
# Checks for programs.
# Checks for libraries.
# Checks for header files.
AM_PROG_CC_C_O
AC_PROG_CC_C99
AC_CONFIG_HEADER(config.h)
AC_CONFIG_HEADER(json_config.h)
AC_HEADER_STDC
AC_CHECK_HEADERS(fcntl.h limits.h strings.h syslog.h unistd.h [sys/cdefs.h] [sys/param.h] stdarg.h locale.h xlocale.h endian.h)
AC_CHECK_HEADER(inttypes.h,[AC_DEFINE([JSON_C_HAVE_INTTYPES_H],[1],[Public define for json_inttypes.h])])
# Checks for typedefs, structures, and compiler characteristics.
AC_C_CONST
AC_TYPE_SIZE_T
AC_CACHE_CHECK([for __thread support], ac_cv___thread, [dnl
AC_LINK_IFELSE([dnl
AC_LANG_PROGRAM([[#undef __thread
static __thread int a; int foo (int b) { return a + b; }]],
[[exit (foo (0));]])],
ac_cv___thread=yes, ac_cv___thread=no)
])
AS_IF([test "x$ac_cv___thread" != xno],
[AC_DEFINE(HAVE___THREAD, 1, [Have __thread])
AC_DEFINE(SPEC___THREAD, [__thread], [Specifier for __thread])]
)
# Checks for library functions.
AC_FUNC_VPRINTF
AC_FUNC_MEMCMP
AC_CHECK_FUNCS([realloc])
AC_CHECK_FUNCS(strcasecmp strdup strerror snprintf vsnprintf vasprintf open vsyslog strncasecmp setlocale)
AC_CHECK_DECLS([INFINITY], [], [], [[#include <math.h>]])
AC_CHECK_DECLS([nan], [], [], [[#include <math.h>]])
AC_CHECK_DECLS([isnan], [], [], [[#include <math.h>]])
AC_CHECK_DECLS([isinf], [], [], [[#include <math.h>]])
AC_CHECK_DECLS([_isnan], [], [], [[#include <float.h>]])
AC_CHECK_DECLS([_finite], [], [], [[#include <float.h>]])
AC_MSG_CHECKING(for GCC atomic builtins)
AC_LINK_IFELSE(
[
AC_LANG_SOURCE([[
int main() {
volatile unsigned int val = 1;
/* Note: __sync_val_compare_and_swap isn't checked here
* because it's protected by __GCC_HAVE_SYNC_COMPARE_AND_SWAP_<n>,
* which is automatically defined by gcc.
*/
__sync_add_and_fetch(&val, 1);
__sync_sub_and_fetch(&val, 1);
return 0;
}
]])
],
[
AC_MSG_RESULT([yes])
AC_DEFINE([HAVE_ATOMIC_BUILTINS],[1],[Has atomic builtins])
],
[
AC_MSG_RESULT([no])
AC_MSG_WARN([json-c will be built without atomic refcounts because atomic builtins are missing])
])
case "${host_os}" in
linux*)
AC_CHECK_FUNCS([uselocale])
;;
*) # Nothing
;;
esac
if test "$ac_cv_have_decl_isnan" = "yes" ; then
AC_TRY_LINK([#include <math.h>], [float f = 0.0; return isnan(f)], [], [LIBS="$LIBS -lm"])
fi
#check if .section.gnu.warning accepts long strings (for __warn_references)
AC_LANG_PUSH([C])
AC_MSG_CHECKING([if .gnu.warning accepts long strings])
AC_LINK_IFELSE([AC_LANG_SOURCE([[
extern void json_object_get();
__asm__(".section .gnu.json_object_get,\n\t.ascii \"Please link against libjson-c instead of libjson\"\n\t.text");
int main(int c,char* v) {return 0;}
]])], [
AC_DEFINE(HAS_GNU_WARNING_LONG, 1, [Define if .gnu.warning accepts long strings.])
AC_MSG_RESULT(yes)
], [
AC_MSG_RESULT(no)
])
AC_LANG_POP([C])
LT_INIT
# Check for the -Bsymbolic-functions linker flag
AC_ARG_ENABLE([Bsymbolic],
[AS_HELP_STRING([--disable-Bsymbolic], [Avoid linking with -Bsymbolic-function])],
[],
[enable_Bsymbolic=check])
AS_IF([test "x$enable_Bsymbolic" = "xcheck"],
[
saved_LDFLAGS="${LDFLAGS}"
AC_MSG_CHECKING([for -Bsymbolic-functions linker flag])
LDFLAGS=-Wl,-Bsymbolic-functions
AC_TRY_LINK([], [int main (void) { return 0; }],
[
AC_MSG_RESULT([yes])
enable_Bsymbolic=yes
],
[
AC_MSG_RESULT([no])
enable_Bsymbolic=no
])
LDFLAGS="${saved_LDFLAGS}"
])
AS_IF([test "x$enable_Bsymbolic" = "xyes"], [JSON_BSYMBOLIC_LDFLAGS=-Wl[,]-Bsymbolic-functions])
AC_SUBST(JSON_BSYMBOLIC_LDFLAGS)
AX_APPEND_COMPILE_FLAGS([-Wall -Werror -Wcast-qual -Wno-error=deprecated-declarations])
AX_APPEND_COMPILE_FLAGS([-Wextra -Wwrite-string -Wno-unused-parameter])
AX_APPEND_COMPILE_FLAGS([-D_GNU_SOURCE -D_REENTRANT])
AX_COMPILE_CHECK_SIZEOF(int)
AX_COMPILE_CHECK_SIZEOF(long)
AX_COMPILE_CHECK_SIZEOF(long long)
AX_COMPILE_CHECK_SIZEOF(size_t, [#include <stdint.h>])
AX_COMPILE_CHECK_SIZEOF(int64_t, [#include <stdint.h>])
AC_CONFIG_FILES([
Makefile
json-c.pc
tests/Makefile
json-c-uninstalled.pc
])
AC_OUTPUT

63
debug.c
View File

@@ -11,17 +11,17 @@
#include "config.h" #include "config.h"
#include <stdarg.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <stdarg.h>
#if HAVE_SYSLOG_H #if HAVE_SYSLOG_H
# include <syslog.h> #include <syslog.h>
#endif /* HAVE_SYSLOG_H */ #endif /* HAVE_SYSLOG_H */
#if HAVE_UNISTD_H #if HAVE_UNISTD_H
# include <unistd.h> #include <unistd.h>
#endif /* HAVE_UNISTD_H */ #endif /* HAVE_UNISTD_H */
#if HAVE_SYS_PARAM_H #if HAVE_SYS_PARAM_H
@@ -33,51 +33,64 @@
static int _syslog = 0; static int _syslog = 0;
static int _debug = 0; static int _debug = 0;
void mc_set_debug(int debug) { _debug = debug; } void mc_set_debug(int debug)
int mc_get_debug(void) { return _debug; } {
_debug = debug;
}
int mc_get_debug(void)
{
return _debug;
}
extern void mc_set_syslog(int syslog) extern void mc_set_syslog(int syslog)
{ {
_syslog = syslog; _syslog = syslog;
} }
void mc_debug(const char *msg, ...) void mc_debug(const char *msg, ...)
{ {
va_list ap; va_list ap;
if(_debug) { if (_debug)
va_start(ap, msg); {
va_start(ap, msg);
#if HAVE_VSYSLOG #if HAVE_VSYSLOG
if(_syslog) { if (_syslog)
vsyslog(LOG_DEBUG, msg, ap); {
} else vsyslog(LOG_DEBUG, msg, ap);
}
else
#endif #endif
vprintf(msg, ap); vprintf(msg, ap);
va_end(ap); va_end(ap);
} }
} }
void mc_error(const char *msg, ...) void mc_error(const char *msg, ...)
{ {
va_list ap; va_list ap;
va_start(ap, msg); va_start(ap, msg);
#if HAVE_VSYSLOG #if HAVE_VSYSLOG
if(_syslog) { if (_syslog)
{
vsyslog(LOG_ERR, msg, ap); vsyslog(LOG_ERR, msg, ap);
} else }
else
#endif #endif
vfprintf(stderr, msg, ap); vfprintf(stderr, msg, ap);
va_end(ap); va_end(ap);
} }
void mc_info(const char *msg, ...) void mc_info(const char *msg, ...)
{ {
va_list ap; va_list ap;
va_start(ap, msg); va_start(ap, msg);
#if HAVE_VSYSLOG #if HAVE_VSYSLOG
if(_syslog) { if (_syslog)
{
vsyslog(LOG_INFO, msg, ap); vsyslog(LOG_INFO, msg, ap);
} else }
else
#endif #endif
vfprintf(stderr, msg, ap); vfprintf(stderr, msg, ap);
va_end(ap); va_end(ap);
} }

63
debug.h
View File

@@ -14,8 +14,8 @@
* @file * @file
* @brief Do not use, json-c internal, may be changed or removed at any time. * @brief Do not use, json-c internal, may be changed or removed at any time.
*/ */
#ifndef _DEBUG_H_ #ifndef _JSON_C_DEBUG_H_
#define _DEBUG_H_ #define _JSON_C_DEBUG_H_
#include <stdlib.h> #include <stdlib.h>
@@ -23,14 +23,22 @@
extern "C" { extern "C" {
#endif #endif
extern void mc_set_debug(int debug); #ifndef JSON_EXPORT
extern int mc_get_debug(void); #if defined(_MSC_VER) && defined(JSON_C_DLL)
#define JSON_EXPORT __declspec(dllexport)
#else
#define JSON_EXPORT extern
#endif
#endif
extern void mc_set_syslog(int syslog); JSON_EXPORT void mc_set_debug(int debug);
JSON_EXPORT int mc_get_debug(void);
extern void mc_debug(const char *msg, ...); JSON_EXPORT void mc_set_syslog(int syslog);
extern void mc_error(const char *msg, ...);
extern void mc_info(const char *msg, ...); JSON_EXPORT void mc_debug(const char *msg, ...);
JSON_EXPORT void mc_error(const char *msg, ...);
JSON_EXPORT void mc_info(const char *msg, ...);
#ifndef __STRING #ifndef __STRING
#define __STRING(x) #x #define __STRING(x) #x
@@ -38,17 +46,24 @@ extern void mc_info(const char *msg, ...);
#ifndef PARSER_BROKEN_FIXED #ifndef PARSER_BROKEN_FIXED
#define JASSERT(cond) do {} while(0) #define JASSERT(cond) \
do \
{ \
} while (0)
#else #else
#define JASSERT(cond) do { \ #define JASSERT(cond) \
if (!(cond)) { \ do \
mc_error("cjson assert failure %s:%d : cond \"" __STRING(cond) "failed\n", __FILE__, __LINE__); \ { \
*(int *)0 = 1;\ if (!(cond)) \
abort(); \ { \
}\ mc_error("cjson assert failure %s:%d : cond \"" __STRING(cond) "failed\n", \
} while(0) __FILE__, __LINE__); \
*(int *)0 = 1; \
abort(); \
} \
} while (0)
#endif #endif
@@ -61,11 +76,19 @@ extern void mc_info(const char *msg, ...);
#define MC_DEBUG(x, ...) mc_debug(x, ##__VA_ARGS__) #define MC_DEBUG(x, ...) mc_debug(x, ##__VA_ARGS__)
#define MC_INFO(x, ...) mc_info(x, ##__VA_ARGS__) #define MC_INFO(x, ...) mc_info(x, ##__VA_ARGS__)
#else #else
#define MC_SET_DEBUG(x) if (0) mc_set_debug(x) #define MC_SET_DEBUG(x) \
if (0) \
mc_set_debug(x)
#define MC_GET_DEBUG() (0) #define MC_GET_DEBUG() (0)
#define MC_SET_SYSLOG(x) if (0) mc_set_syslog(x) #define MC_SET_SYSLOG(x) \
#define MC_DEBUG(x, ...) if (0) mc_debug(x, ##__VA_ARGS__) if (0) \
#define MC_INFO(x, ...) if (0) mc_info(x, ##__VA_ARGS__) mc_set_syslog(x)
#define MC_DEBUG(x, ...) \
if (0) \
mc_debug(x, ##__VA_ARGS__)
#define MC_INFO(x, ...) \
if (0) \
mc_info(x, ##__VA_ARGS__)
#endif #endif
#ifdef __cplusplus #ifdef __cplusplus

16
doc/CMakeLists.txt Normal file
View File

@@ -0,0 +1,16 @@
# generate doxygen documentation for json-c API
find_package(Doxygen)
if (DOXYGEN_FOUND)
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/Doxyfile.in
${CMAKE_CURRENT_BINARY_DIR}/Doxyfile)
message(STATUS "Wrote ${CMAKE_CURRENT_BINARY_DIR}/Doxyfile")
add_custom_target(doc
COMMAND ${DOXYGEN_EXECUTABLE} ${CMAKE_CURRENT_BINARY_DIR}/Doxyfile)
else (DOXYGEN_FOUND)
message("Warning: doxygen not found, the 'doc' target will not be included")
endif(DOXYGEN_FOUND)

View File

@@ -20,7 +20,7 @@
# This tag specifies the encoding used for all characters in the config file # This tag specifies the encoding used for all characters in the config file
# that follow. The default is UTF-8 which is also the encoding used for all text # that follow. The default is UTF-8 which is also the encoding used for all text
# before the first occurrence of this tag. Doxygen uses libiconv (or the iconv # before the first occurrence of this tag. Doxygen uses libiconv (or the iconv
# built into libc) for the transcoding. See http://www.gnu.org/software/libiconv # built into libc) for the transcoding. See https://www.gnu.org/software/libiconv
# for the list of possible encodings. # for the list of possible encodings.
# The default value is: UTF-8. # The default value is: UTF-8.
@@ -38,7 +38,7 @@ PROJECT_NAME = json-c
# could be handy for archiving the generated documentation or if some version # could be handy for archiving the generated documentation or if some version
# control system is used. # control system is used.
PROJECT_NUMBER = 0.12.99 PROJECT_NUMBER = @PROJECT_VERSION@
# Using the PROJECT_BRIEF tag one can provide an optional one line description # Using the PROJECT_BRIEF tag one can provide an optional one line description
# for a project that appears at the top of each page and should give viewer a # for a project that appears at the top of each page and should give viewer a
@@ -58,7 +58,7 @@ PROJECT_LOGO =
# entered, it will be relative to the location where doxygen was started. If # entered, it will be relative to the location where doxygen was started. If
# left blank the current directory will be used. # left blank the current directory will be used.
OUTPUT_DIRECTORY = doc OUTPUT_DIRECTORY = @CMAKE_CURRENT_BINARY_DIR@
# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create 4096 sub- # If the CREATE_SUBDIRS tag is set to YES, then doxygen will create 4096 sub-
# directories (in 2 levels) under the output directory of each output format and # directories (in 2 levels) under the output directory of each output format and
@@ -152,7 +152,7 @@ FULL_PATH_NAMES = YES
# will be relative from the directory where doxygen is started. # will be relative from the directory where doxygen is started.
# This tag requires that the tag FULL_PATH_NAMES is set to YES. # This tag requires that the tag FULL_PATH_NAMES is set to YES.
STRIP_FROM_PATH = STRIP_FROM_PATH = @CMAKE_SOURCE_DIR@
# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the # The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the
# path mentioned in the documentation of a class, which tells the reader which # path mentioned in the documentation of a class, which tells the reader which
@@ -285,7 +285,7 @@ EXTENSION_MAPPING =
# If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments # If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments
# according to the Markdown format, which allows for more readable # according to the Markdown format, which allows for more readable
# documentation. See http://daringfireball.net/projects/markdown/ for details. # documentation. See https://daringfireball.net/projects/markdown/ for details.
# The output of markdown processing is further processed by doxygen, so you can # The output of markdown processing is further processed by doxygen, so you can
# mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in # mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in
# case of backward compatibilities issues. # case of backward compatibilities issues.
@@ -318,7 +318,7 @@ BUILTIN_STL_SUPPORT = NO
CPP_CLI_SUPPORT = NO CPP_CLI_SUPPORT = NO
# Set the SIP_SUPPORT tag to YES if your project consists of sip (see: # Set the SIP_SUPPORT tag to YES if your project consists of sip (see:
# http://www.riverbankcomputing.co.uk/software/sip/intro) sources only. Doxygen # https://www.riverbankcomputing.co.uk/software/sip/intro) sources only. Doxygen
# will parse them like normal C++ but will assume all classes use public instead # will parse them like normal C++ but will assume all classes use public instead
# of private inheritance when no explicit protection keyword is present. # of private inheritance when no explicit protection keyword is present.
# The default value is: NO. # The default value is: NO.
@@ -427,7 +427,7 @@ EXTRACT_PACKAGE = NO
# included in the documentation. # included in the documentation.
# The default value is: NO. # The default value is: NO.
EXTRACT_STATIC = NO EXTRACT_STATIC = YES
# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) defined # If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) defined
# locally in source files will be included in the documentation. If set to NO # locally in source files will be included in the documentation. If set to NO
@@ -677,7 +677,7 @@ LAYOUT_FILE =
# The CITE_BIB_FILES tag can be used to specify one or more bib files containing # The CITE_BIB_FILES tag can be used to specify one or more bib files containing
# the reference definitions. This must be a list of .bib files. The .bib # the reference definitions. This must be a list of .bib files. The .bib
# extension is automatically appended if omitted. This requires the bibtex tool # extension is automatically appended if omitted. This requires the bibtex tool
# to be installed. See also http://en.wikipedia.org/wiki/BibTeX for more info. # to be installed. See also https://en.wikipedia.org/wiki/BibTeX for more info.
# For LaTeX the style of the bibliography can be controlled using # For LaTeX the style of the bibliography can be controlled using
# LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the # LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the
# search path. See also \cite for info how to create references. # search path. See also \cite for info how to create references.
@@ -753,13 +753,12 @@ WARN_LOGFILE =
# spaces. # spaces.
# Note: If this tag is empty the current directory is searched. # Note: If this tag is empty the current directory is searched.
INPUT = README.md \ INPUT = @CMAKE_SOURCE_DIR@ @CMAKE_BINARY_DIR@
.
# This tag can be used to specify the character encoding of the source files # This tag can be used to specify the character encoding of the source files
# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses # that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses
# libiconv (or the iconv built into libc) for the transcoding. See the libiconv # libiconv (or the iconv built into libc) for the transcoding. See the libiconv
# documentation (see: http://www.gnu.org/software/libiconv) for the list of # documentation (see: https://www.gnu.org/software/libiconv) for the list of
# possible encodings. # possible encodings.
# The default value is: UTF-8. # The default value is: UTF-8.
@@ -806,7 +805,13 @@ EXCLUDE_SYMLINKS = NO
# Note that the wildcards are matched against the file with absolute path, so to # Note that the wildcards are matched against the file with absolute path, so to
# exclude all test directories for example use the pattern */test/* # exclude all test directories for example use the pattern */test/*
EXCLUDE_PATTERNS = EXCLUDE_PATTERNS = \
*/json_object_private.h \
*/debug.h \
*/*config.h \
*/random_seed.h \
*/strerror_*h \
*/*compat.h
# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names # The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names
# (namespaces, classes, functions, etc.) that should be excluded from the # (namespaces, classes, functions, etc.) that should be excluded from the
@@ -817,7 +822,11 @@ EXCLUDE_PATTERNS =
# Note that the wildcards are matched against the file with absolute path, so to # Note that the wildcards are matched against the file with absolute path, so to
# exclude all test directories use the pattern */test/* # exclude all test directories use the pattern */test/*
EXCLUDE_SYMBOLS = EXCLUDE_SYMBOLS = \
_json_c_* \
_LH_* \
_printbuf_* \
__STRING
# The EXAMPLE_PATH tag can be used to specify one or more files or directories # The EXAMPLE_PATH tag can be used to specify one or more files or directories
# that contain example code fragments that are included (see the \include # that contain example code fragments that are included (see the \include
@@ -860,7 +869,7 @@ IMAGE_PATH =
# code is scanned, but not when the output code is generated. If lines are added # code is scanned, but not when the output code is generated. If lines are added
# or removed, the anchors will not be placed correctly. # or removed, the anchors will not be placed correctly.
INPUT_FILTER = INPUT_FILTER = @CMAKE_CURRENT_SOURCE_DIR@/fixup_markdown.sh
# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern # The FILTER_PATTERNS tag can be used to specify filters on a per file pattern
# basis. Doxygen will compare the file name with each pattern and apply the # basis. Doxygen will compare the file name with each pattern and apply the
@@ -891,7 +900,7 @@ FILTER_SOURCE_PATTERNS =
# (index.html). This can be useful if you have a project on for instance GitHub # (index.html). This can be useful if you have a project on for instance GitHub
# and want to reuse the introduction page also for the doxygen output. # and want to reuse the introduction page also for the doxygen output.
USE_MDFILE_AS_MAINPAGE = USE_MDFILE_AS_MAINPAGE = README.md
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
# Configuration options related to source browsing # Configuration options related to source browsing
@@ -952,7 +961,7 @@ SOURCE_TOOLTIPS = YES
# If the USE_HTAGS tag is set to YES then the references to source code will # If the USE_HTAGS tag is set to YES then the references to source code will
# point to the HTML generated by the htags(1) tool instead of doxygen built-in # point to the HTML generated by the htags(1) tool instead of doxygen built-in
# source browser. The htags tool is part of GNU's global source tagging system # source browser. The htags tool is part of GNU's global source tagging system
# (see http://www.gnu.org/software/global/global.html). You will need version # (see https://www.gnu.org/software/global/global.html). You will need version
# 4.8.6 or higher. # 4.8.6 or higher.
# #
# To use it do the following: # To use it do the following:
@@ -980,7 +989,7 @@ USE_HTAGS = NO
VERBATIM_HEADERS = NO VERBATIM_HEADERS = NO
# If the CLANG_ASSISTED_PARSING tag is set to YES, then doxygen will use the # If the CLANG_ASSISTED_PARSING tag is set to YES, then doxygen will use the
# clang parser (see: http://clang.llvm.org/) for more accurate parsing at the # clang parser (see: https://clang.llvm.org/) for more accurate parsing at the
# cost of reduced performance. This can be particularly helpful with template # cost of reduced performance. This can be particularly helpful with template
# rich C++ code for which doxygen's built-in parser lacks the necessary type # rich C++ code for which doxygen's built-in parser lacks the necessary type
# information. # information.
@@ -1094,7 +1103,7 @@ HTML_STYLESHEET =
# cascading style sheets that are included after the standard style sheets # cascading style sheets that are included after the standard style sheets
# created by doxygen. Using this option one can overrule certain style aspects. # created by doxygen. Using this option one can overrule certain style aspects.
# This is preferred over using HTML_STYLESHEET since it does not replace the # This is preferred over using HTML_STYLESHEET since it does not replace the
# standard style sheet and is therefor more robust against future updates. # standard style sheet and is therefore more robust against future updates.
# Doxygen will copy the style sheet files to the output directory. # Doxygen will copy the style sheet files to the output directory.
# Note: The order of the extra stylesheet files is of importance (e.g. the last # Note: The order of the extra stylesheet files is of importance (e.g. the last
# stylesheet in the list overrules the setting of the previous ones in the # stylesheet in the list overrules the setting of the previous ones in the
@@ -1116,7 +1125,7 @@ HTML_EXTRA_FILES =
# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen # The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen
# will adjust the colors in the stylesheet and background images according to # will adjust the colors in the stylesheet and background images according to
# this color. Hue is specified as an angle on a colorwheel, see # this color. Hue is specified as an angle on a colorwheel, see
# http://en.wikipedia.org/wiki/Hue for more information. For instance the value # https://en.wikipedia.org/wiki/Hue for more information. For instance the value
# 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300 # 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300
# purple, and 360 is red again. # purple, and 360 is red again.
# Minimum value: 0, maximum value: 359, default value: 220. # Minimum value: 0, maximum value: 359, default value: 220.
@@ -1174,12 +1183,13 @@ HTML_INDEX_NUM_ENTRIES = 100
# If the GENERATE_DOCSET tag is set to YES, additional index files will be # If the GENERATE_DOCSET tag is set to YES, additional index files will be
# generated that can be used as input for Apple's Xcode 3 integrated development # generated that can be used as input for Apple's Xcode 3 integrated development
# environment (see: http://developer.apple.com/tools/xcode/), introduced with # environment (see: https://developer.apple.com/tools/xcode/), introduced with
# OSX 10.5 (Leopard). To create a documentation set, doxygen will generate a # OSX 10.5 (Leopard). To create a documentation set, doxygen will generate a
# Makefile in the HTML output directory. Running make will produce the docset in # Makefile in the HTML output directory. Running make will produce the docset in
# that directory and running make install will install the docset in # that directory and running make install will install the docset in
# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at # ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at
# startup. See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html # startup. See
# https://developer.apple.com/library/archive/featuredarticles/DoxygenXcode/
# for more information. # for more information.
# The default value is: NO. # The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES. # This tag requires that the tag GENERATE_HTML is set to YES.
@@ -1295,7 +1305,7 @@ QCH_FILE =
# The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help # The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help
# Project output. For more information please see Qt Help Project / Namespace # Project output. For more information please see Qt Help Project / Namespace
# (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#namespace). # (see: https://doc.qt.io/archives/qt-4.8/qthelpproject.html#namespace).
# The default value is: org.doxygen.Project. # The default value is: org.doxygen.Project.
# This tag requires that the tag GENERATE_QHP is set to YES. # This tag requires that the tag GENERATE_QHP is set to YES.
@@ -1303,8 +1313,8 @@ QHP_NAMESPACE = org.doxygen.Project
# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt # The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt
# Help Project output. For more information please see Qt Help Project / Virtual # Help Project output. For more information please see Qt Help Project / Virtual
# Folders (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#virtual- # Folders (see:
# folders). # https://doc.qt.io/archives/qt-4.8/qthelpproject.html#virtual-folders).
# The default value is: doc. # The default value is: doc.
# This tag requires that the tag GENERATE_QHP is set to YES. # This tag requires that the tag GENERATE_QHP is set to YES.
@@ -1312,23 +1322,23 @@ QHP_VIRTUAL_FOLDER = doc
# If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom # If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom
# filter to add. For more information please see Qt Help Project / Custom # filter to add. For more information please see Qt Help Project / Custom
# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom- # Filters (see:
# filters). # https://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom-filters).
# This tag requires that the tag GENERATE_QHP is set to YES. # This tag requires that the tag GENERATE_QHP is set to YES.
QHP_CUST_FILTER_NAME = QHP_CUST_FILTER_NAME =
# The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the # The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the
# custom filter to add. For more information please see Qt Help Project / Custom # custom filter to add. For more information please see Qt Help Project / Custom
# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom- # Filters (see:
# filters). # https://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom-filters).
# This tag requires that the tag GENERATE_QHP is set to YES. # This tag requires that the tag GENERATE_QHP is set to YES.
QHP_CUST_FILTER_ATTRS = QHP_CUST_FILTER_ATTRS =
# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this # The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this
# project's filter section matches. Qt Help Project / Filter Attributes (see: # project's filter section matches. Qt Help Project / Filter Attributes (see:
# http://qt-project.org/doc/qt-4.8/qthelpproject.html#filter-attributes). # https://doc.qt.io/archives/qt-4.8/qthelpproject.html#filter-attributes).
# This tag requires that the tag GENERATE_QHP is set to YES. # This tag requires that the tag GENERATE_QHP is set to YES.
QHP_SECT_FILTER_ATTRS = QHP_SECT_FILTER_ATTRS =
@@ -1433,7 +1443,7 @@ FORMULA_FONTSIZE = 10
FORMULA_TRANSPARENT = YES FORMULA_TRANSPARENT = YES
# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see # Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see
# http://www.mathjax.org) which uses client side Javascript for the rendering # https://www.mathjax.org) which uses client side Javascript for the rendering
# instead of using prerendered bitmaps. Use this if you do not have LaTeX # instead of using prerendered bitmaps. Use this if you do not have LaTeX
# installed or if you want to formulas look prettier in the HTML output. When # installed or if you want to formulas look prettier in the HTML output. When
# enabled you may also need to install MathJax separately and configure the path # enabled you may also need to install MathJax separately and configure the path
@@ -1445,7 +1455,7 @@ USE_MATHJAX = NO
# When MathJax is enabled you can set the default output format to be used for # When MathJax is enabled you can set the default output format to be used for
# the MathJax output. See the MathJax site (see: # the MathJax output. See the MathJax site (see:
# http://docs.mathjax.org/en/latest/output.html) for more details. # https://docs.mathjax.org/en/latest/output/) for more details.
# Possible values are: HTML-CSS (which is slower, but has the best # Possible values are: HTML-CSS (which is slower, but has the best
# compatibility), NativeMML (i.e. MathML) and SVG. # compatibility), NativeMML (i.e. MathML) and SVG.
# The default value is: HTML-CSS. # The default value is: HTML-CSS.
@@ -1460,11 +1470,11 @@ MATHJAX_FORMAT = HTML-CSS
# MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax # MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax
# Content Delivery Network so you can quickly see the result without installing # Content Delivery Network so you can quickly see the result without installing
# MathJax. However, it is strongly recommended to install a local copy of # MathJax. However, it is strongly recommended to install a local copy of
# MathJax from http://www.mathjax.org before deployment. # MathJax from https://www.mathjax.org before deployment.
# The default value is: http://cdn.mathjax.org/mathjax/latest. # The default value is: https://cdn.mathjax.org/mathjax/latest.
# This tag requires that the tag USE_MATHJAX is set to YES. # This tag requires that the tag USE_MATHJAX is set to YES.
MATHJAX_RELPATH = http://cdn.mathjax.org/mathjax/latest MATHJAX_RELPATH = https://cdn.mathjax.org/mathjax/latest
# The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax # The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax
# extension names that should be enabled during MathJax rendering. For example # extension names that should be enabled during MathJax rendering. For example
@@ -1475,7 +1485,7 @@ MATHJAX_EXTENSIONS =
# The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces # The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces
# of code that will be used on startup of the MathJax code. See the MathJax site # of code that will be used on startup of the MathJax code. See the MathJax site
# (see: http://docs.mathjax.org/en/latest/output.html) for more details. For an # (see: https://docs.mathjax.org/en/latest/output/) for more details. For an
# example see the documentation. # example see the documentation.
# This tag requires that the tag USE_MATHJAX is set to YES. # This tag requires that the tag USE_MATHJAX is set to YES.
@@ -1522,7 +1532,7 @@ SERVER_BASED_SEARCH = NO
# #
# Doxygen ships with an example indexer ( doxyindexer) and search engine # Doxygen ships with an example indexer ( doxyindexer) and search engine
# (doxysearch.cgi) which are based on the open source search engine library # (doxysearch.cgi) which are based on the open source search engine library
# Xapian (see: http://xapian.org/). # Xapian (see: https://xapian.org/).
# #
# See the section "External Indexing and Searching" for details. # See the section "External Indexing and Searching" for details.
# The default value is: NO. # The default value is: NO.
@@ -1535,7 +1545,7 @@ EXTERNAL_SEARCH = NO
# #
# Doxygen ships with an example indexer ( doxyindexer) and search engine # Doxygen ships with an example indexer ( doxyindexer) and search engine
# (doxysearch.cgi) which are based on the open source search engine library # (doxysearch.cgi) which are based on the open source search engine library
# Xapian (see: http://xapian.org/). See the section "External Indexing and # Xapian (see: https://xapian.org/). See the section "External Indexing and
# Searching" for details. # Searching" for details.
# This tag requires that the tag SEARCHENGINE is set to YES. # This tag requires that the tag SEARCHENGINE is set to YES.
@@ -1637,8 +1647,8 @@ EXTRA_PACKAGES =
# Note: Only use a user-defined header if you know what you are doing! The # Note: Only use a user-defined header if you know what you are doing! The
# following commands have a special meaning inside the header: $title, # following commands have a special meaning inside the header: $title,
# $datetime, $date, $doxygenversion, $projectname, $projectnumber, # $datetime, $date, $doxygenversion, $projectname, $projectnumber,
# $projectbrief, $projectlogo. Doxygen will replace $title with the empy string, # $projectbrief, $projectlogo. Doxygen will replace $title with the empty string,
# for the replacement values of the other commands the user is refered to # for the replacement values of the other commands the user is referred to
# HTML_HEADER. # HTML_HEADER.
# This tag requires that the tag GENERATE_LATEX is set to YES. # This tag requires that the tag GENERATE_LATEX is set to YES.
@@ -1708,7 +1718,7 @@ LATEX_SOURCE_CODE = NO
# The LATEX_BIB_STYLE tag can be used to specify the style to use for the # The LATEX_BIB_STYLE tag can be used to specify the style to use for the
# bibliography, e.g. plainnat, or ieeetr. See # bibliography, e.g. plainnat, or ieeetr. See
# http://en.wikipedia.org/wiki/BibTeX and \cite for more info. # https://en.wikipedia.org/wiki/BibTeX and \cite for more info.
# The default value is: plain. # The default value is: plain.
# This tag requires that the tag GENERATE_LATEX is set to YES. # This tag requires that the tag GENERATE_LATEX is set to YES.
@@ -1975,7 +1985,9 @@ INCLUDE_FILE_PATTERNS =
# recursively expanded use the := operator instead of the = operator. # recursively expanded use the := operator instead of the = operator.
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES. # This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
PREDEFINED = THIS_FUNCTION_IS_DEPRECATED(f)=f PREDEFINED = \
_LH_INLINE=inline \
JSON_C_CONST_FUNCTION(func)=func
# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then this # If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then this
# tag can be used to specify a list of macro names that should be expanded. The # tag can be used to specify a list of macro names that should be expanded. The
@@ -2062,7 +2074,7 @@ CLASS_DIAGRAMS = YES
# You can define message sequence charts within doxygen comments using the \msc # You can define message sequence charts within doxygen comments using the \msc
# command. Doxygen will then run the mscgen tool (see: # command. Doxygen will then run the mscgen tool (see:
# http://www.mcternan.me.uk/mscgen/)) to produce the chart and insert it in the # https://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the
# documentation. The MSCGEN_PATH tag allows you to specify the directory where # documentation. The MSCGEN_PATH tag allows you to specify the directory where
# the mscgen tool resides. If left empty the tool is assumed to be found in the # the mscgen tool resides. If left empty the tool is assumed to be found in the
# default search path. # default search path.
@@ -2084,7 +2096,7 @@ HIDE_UNDOC_RELATIONS = YES
# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is # If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is
# available from the path. This tool is part of Graphviz (see: # available from the path. This tool is part of Graphviz (see:
# http://www.graphviz.org/), a graph visualization toolkit from AT&T and Lucent # https://www.graphviz.org/), a graph visualization toolkit from AT&T and Lucent
# Bell Labs. The other options in this section have no effect if this option is # Bell Labs. The other options in this section have no effect if this option is
# set to NO # set to NO
# The default value is: YES. # The default value is: YES.

6
doc/fixup_markdown.sh Executable file
View File

@@ -0,0 +1,6 @@
#!/bin/sh
#
# Doxygen markdown doesn't support triple-backticks like github does.
# Convert all of those to space-prefixed blocks instead.
#
awk '/```/ { prefix=!prefix; print ""; next; } { if (prefix) { printf " "; } print $0; } ' "$@"

6
fuzz/README.md Normal file
View File

@@ -0,0 +1,6 @@
# Fuzzers
This directory contains fuzzers that
target [llvm's LibFuzzer](https://llvm.org/docs/LibFuzzer.html). They are built
and run automatically by
Google's [OSS-Fuzz](https://github.com/google/oss-fuzz/) infrastructure.

52
fuzz/build.sh Executable file
View File

@@ -0,0 +1,52 @@
#!/bin/bash -eu
# Copyright 2018 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
################################################################################
# This should be run from the top of the json-c source tree.
mkdir build
cd build
cmake -DBUILD_SHARED_LIBS=OFF ..
make -j$(nproc)
LIB=$(pwd)/libjson-c.a
cd ..
# These seem to be set externally, but let's assign defaults to
# make it possible to at least partially test this standalone.
: ${SRC:=$(dirname "$0")}
: ${OUT:=$SRC/out}
: ${CXX:=gcc}
: ${CXXFLAGS:=}
[ -d "$OUT" ] || mkdir "$OUT"
cp $SRC/*.dict $OUT/.
# XXX this doesn't seem to make much sense, since $SRC is presumably
# the "fuzz" directory, which is _inside_ the json-c repo, rather than
# the other way around, but I'm just preserving existing behavior. -erh
INCS=$SRC/json-c
# Compat when testing standalone
[ -e "${INCS}" ] || ln -s .. "${INCS}"
set -x
set -v
for f in $SRC/*_fuzzer.cc; do
fuzzer=$(basename "$f" _fuzzer.cc)
$CXX $CXXFLAGS -std=c++11 -I$INCS \
$SRC/${fuzzer}_fuzzer.cc -o $OUT/${fuzzer}_fuzzer \
-lFuzzingEngine $LIB
done

View File

@@ -0,0 +1,22 @@
#include <stdint.h>
#include <json.h>
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
{
const char *data1 = reinterpret_cast<const char *>(data);
json_tokener *tok = json_tokener_new();
json_object *obj = json_tokener_parse_ex(tok, data1, size);
if (json_object_is_type(obj, json_type_object)) {
json_object_object_foreach(obj, key, val) {
(void)json_object_get_type(val);
(void)json_object_get_string(val);
}
}
(void)json_object_to_json_string_ext(obj, JSON_C_TO_STRING_PRETTY | JSON_C_TO_STRING_SPACED);
json_object_put(obj);
json_tokener_free(tok);
return 0;
}

View File

@@ -0,0 +1,18 @@
"{"
"}"
","
"["
"]"
","
":"
"e"
"e+"
"e-"
"E"
"E+"
"E-"
"\""
"null"
"1"
"1.234"
"3e4"

View File

@@ -1,267 +1,270 @@
This list was created with: This list was created with:
```
curl https://api.github.com/search/issues?q="repo%3Ajson-c%2Fjson-c+closed%3A>2014-04-10+created%3A<2017-12-01&sort=created&order=asc&per_page=400&page=1" > issues1.out curl https://api.github.com/search/issues?q="repo%3Ajson-c%2Fjson-c+closed%3A>2014-04-10+created%3A<2017-12-01&sort=created&order=asc&per_page=400&page=1" > issues1.out
curl https://api.github.com/search/issues?q="repo%3Ajson-c%2Fjson-c+closed%3A>2014-04-10+created%3A<2017-12-01&sort=created&order=asc&per_page=400&page=2" > issues2.out curl https://api.github.com/search/issues?q="repo%3Ajson-c%2Fjson-c+closed%3A>2014-04-10+created%3A<2017-12-01&sort=created&order=asc&per_page=400&page=2" > issues2.out
curl https://api.github.com/search/issues?q="repo%3Ajson-c%2Fjson-c+closed%3A>2014-04-10+created%3A<2017-12-01&sort=created&order=asc&per_page=400&page=3" > issues3.out curl https://api.github.com/search/issues?q="repo%3Ajson-c%2Fjson-c+closed%3A>2014-04-10+created%3A<2017-12-01&sort=created&order=asc&per_page=400&page=3" > issues3.out
jq -r '.items[] | "[" + .title + "](" + .url + ")" | tostring' issues?.out > issues.md jq -r '.items[] | "[" + .title + "](" + .url + ")" | tostring' issues?.out > issues.md
sed -e's,^\[ *\(.*\)\](https://api.github.com/.*/\([0-9].*\)),[Issue #\2](https://github.com/json-c/json-c/issues/\2) - \1,' -i issues.md
#... manual editing ... #... manual editing ...
```
---- ----
Issues and Pull Requests closed for the 0.13 release Issues and Pull Requests closed for the 0.13 release
(since commit f84d9c, the 0.12 branch point, 2014-04-10) (since commit f84d9c, the 0.12 branch point, 2014-04-10)
[Make json_object_object_add() indicate success or failure, test fix](https://api.github.com/repos/json-c/json-c/issues/61)
[Build fixes (make dist and make distcheck)](https://api.github.com/repos/json-c/json-c/issues/113)
[Fixing build](https://api.github.com/repos/json-c/json-c/issues/124)
[Fix compile error(variable size set but not used) on g++4.6](https://api.github.com/repos/json-c/json-c/issues/125)
[Removed unused size variable.](https://api.github.com/repos/json-c/json-c/issues/126)
[remove unused `size` variable](https://api.github.com/repos/json-c/json-c/issues/127)
[Remove unused variable from json_tokenizer.c](https://api.github.com/repos/json-c/json-c/issues/128)
[Failed to compile under Ubuntu 13.10 32bit](https://api.github.com/repos/json-c/json-c/issues/130)
[undefined symbol: __sync_val_compare_and_swap_4 ](https://api.github.com/repos/json-c/json-c/issues/131)
[Remove unused variable 'size'](https://api.github.com/repos/json-c/json-c/issues/132)
[Update and rename README to README.md](https://api.github.com/repos/json-c/json-c/issues/133)
[Must remove variable size...](https://api.github.com/repos/json-c/json-c/issues/134)
[bits.h uses removed json_tokener_errors\[error\]](https://api.github.com/repos/json-c/json-c/issues/135)
[Error when running make check](https://api.github.com/repos/json-c/json-c/issues/136)
[config.h.in should not be in git](https://api.github.com/repos/json-c/json-c/issues/137)
[Can't build on RHEL 6.5 due to dependency on automake-1.14](https://api.github.com/repos/json-c/json-c/issues/138)
[Code bug in random_test.c evaluating same expression twice ](https://api.github.com/repos/json-c/json-c/issues/140)
[Removed duplicate check in random_seed test - bug #140](https://api.github.com/repos/json-c/json-c/issues/141)
[Please undeprecate json_object_object_get](https://api.github.com/repos/json-c/json-c/issues/142)
[Introduce json_object_from_fd](https://api.github.com/repos/json-c/json-c/issues/144)
[Handle % character properly](https://api.github.com/repos/json-c/json-c/issues/145)
[TAGS rename](https://api.github.com/repos/json-c/json-c/issues/146)
[Bump the soname](https://api.github.com/repos/json-c/json-c/issues/148)
[SONAME bump](https://api.github.com/repos/json-c/json-c/issues/149)
[Fix build using MinGW.](https://api.github.com/repos/json-c/json-c/issues/150)
[Remove json_type enum trailing comma](https://api.github.com/repos/json-c/json-c/issues/151)
[error while compiling json-c library version 0.11](https://api.github.com/repos/json-c/json-c/issues/152)
[improve doc for json_object_to_json_string()](https://api.github.com/repos/json-c/json-c/issues/153)
[double precision](https://api.github.com/repos/json-c/json-c/issues/154)
[add bsearch for arrays](https://api.github.com/repos/json-c/json-c/issues/155)
[Remove trailing whitespaces](https://api.github.com/repos/json-c/json-c/issues/156)
[JSON-C shall not exit on calloc fail.](https://api.github.com/repos/json-c/json-c/issues/157)
[while using json-c 0.11, I am facing strange crash issue in json_object_put.](https://api.github.com/repos/json-c/json-c/issues/158)
[json_tokener.c compile error](https://api.github.com/repos/json-c/json-c/issues/159)
[missing header file on windows??](https://api.github.com/repos/json-c/json-c/issues/160)
[Is there a way to append to file?](https://api.github.com/repos/json-c/json-c/issues/161)
[json_util: add directory check for POSIX distros](https://api.github.com/repos/json-c/json-c/issues/162)
[Fix Win32 build problems](https://api.github.com/repos/json-c/json-c/issues/163)
[made it compile and link on Widnows (as static library)](https://api.github.com/repos/json-c/json-c/issues/164)
[json_object_to_json_string_ext length](https://api.github.com/repos/json-c/json-c/issues/165)
[Can't build on Windows with Visual Studio 2010](https://api.github.com/repos/json-c/json-c/issues/167)
[Tightening the number parsing algorithm](https://api.github.com/repos/json-c/json-c/issues/168)
[Doesn't compile on ubuntu 14.04, 64bit](https://api.github.com/repos/json-c/json-c/issues/169)
[Generated files in repository](https://api.github.com/repos/json-c/json-c/issues/170)
[Update configuration for VS2010 and win64](https://api.github.com/repos/json-c/json-c/issues/171)
[Adding support for parsing octal numbers](https://api.github.com/repos/json-c/json-c/issues/172)
[json_parse_int64 doesn't work correctly at illumos](https://api.github.com/repos/json-c/json-c/issues/173)
[Adding JSON_C_TO_STRING_PRETTY_TAB flag](https://api.github.com/repos/json-c/json-c/issues/174)
[make check fails 4 tests with overflows when built with ASAN](https://api.github.com/repos/json-c/json-c/issues/175)
[Possible to delete an array element at a given idx ?](https://api.github.com/repos/json-c/json-c/issues/176)
[Fix compiler warnings](https://api.github.com/repos/json-c/json-c/issues/177)
[Unable to compile on CentOS5](https://api.github.com/repos/json-c/json-c/issues/178)
[Added array_list_del_idx and json_object_array_del_idx](https://api.github.com/repos/json-c/json-c/issues/179)
[Enable silent build by default](https://api.github.com/repos/json-c/json-c/issues/180)
[json_tokener_parse_ex accepts invalid JSON](https://api.github.com/repos/json-c/json-c/issues/181)
[Link against libm when needed](https://api.github.com/repos/json-c/json-c/issues/182)
[Apply compile warning fix to master branch](https://api.github.com/repos/json-c/json-c/issues/183)
[Use only GCC-specific flags when compiling with GCC](https://api.github.com/repos/json-c/json-c/issues/184)
[compile error](https://api.github.com/repos/json-c/json-c/issues/185)
[Syntax error](https://api.github.com/repos/json-c/json-c/issues/186)
[array_list_get_idx and negative indexes.](https://api.github.com/repos/json-c/json-c/issues/187)
[json_object_object_foreach warnings](https://api.github.com/repos/json-c/json-c/issues/188)
[noisy json_object_from_file: error opening file](https://api.github.com/repos/json-c/json-c/issues/189)
[warning: initialization discards const qualifier from pointer target type \[enabled by default\]](https://api.github.com/repos/json-c/json-c/issues/190)
[json_tokener_parse accepts invalid JSON {"key": "value" , }](https://api.github.com/repos/json-c/json-c/issues/192)
[Make serialization format of doubles configurable](https://api.github.com/repos/json-c/json-c/issues/193)
[Add utility function for comparing json_objects](https://api.github.com/repos/json-c/json-c/issues/194)
[Call uselocale instead of setlocale](https://api.github.com/repos/json-c/json-c/issues/195)
[Performance improvements](https://api.github.com/repos/json-c/json-c/issues/196)
[Time for a new release?](https://api.github.com/repos/json-c/json-c/issues/197)
[Fix possible memory leak and remove superfluous NULL checks before free()](https://api.github.com/repos/json-c/json-c/issues/198)
[Fix build in Visual Studio](https://api.github.com/repos/json-c/json-c/issues/199)
[Add build scripts for CI platforms](https://api.github.com/repos/json-c/json-c/issues/200)
[disable forward-slash escaping?](https://api.github.com/repos/json-c/json-c/issues/201)
[Array with objects support](https://api.github.com/repos/json-c/json-c/issues/202)
[Add source position/coordinates to API](https://api.github.com/repos/json-c/json-c/issues/203)
[json-c/json.h not found ](https://api.github.com/repos/json-c/json-c/issues/204)
[json-c Compiled with Visual Studios](https://api.github.com/repos/json-c/json-c/issues/205)
[what do i use in place of json_object_object_get?](https://api.github.com/repos/json-c/json-c/issues/206)
[Add support for property pairs directly added to arrays](https://api.github.com/repos/json-c/json-c/issues/207)
[Performance enhancements (mainly) to json_object_to_json_string()](https://api.github.com/repos/json-c/json-c/issues/208)
[fix regression from 2d549662be832da838aa063da2efa78ee3b99668](https://api.github.com/repos/json-c/json-c/issues/209)
[Use size_t for arrays](https://api.github.com/repos/json-c/json-c/issues/210)
[Atomic updates for the refcount](https://api.github.com/repos/json-c/json-c/issues/211)
[Refcount doesn't work between threads](https://api.github.com/repos/json-c/json-c/issues/212)
[fix to compile with microsoft visual c++ 2010](https://api.github.com/repos/json-c/json-c/issues/213)
[Some non-GNU systems support __sync_val_compare_and_swap](https://api.github.com/repos/json-c/json-c/issues/214)
[Build json-c for window 64 bit.](https://api.github.com/repos/json-c/json-c/issues/215)
[configure: check realloc with AC_CHECK_FUNCS() to fix cross-compilation.](https://api.github.com/repos/json-c/json-c/issues/216)
[Checking for functions in float.h](https://api.github.com/repos/json-c/json-c/issues/217)
[Use a macro to indicate C99 to the compiler](https://api.github.com/repos/json-c/json-c/issues/218)
[Fix various potential null ptr deref and int32 overflows](https://api.github.com/repos/json-c/json-c/issues/219)
[Add utility function for comparing json_objects](https://api.github.com/repos/json-c/json-c/issues/220)
[JSON_C_TO_STRING_NOSLASHESCAPE works incorrectly](https://api.github.com/repos/json-c/json-c/issues/221)
[Fix issue #221: JSON_C_TO_STRING_NOSLASHESCAPE works incorrectly](https://api.github.com/repos/json-c/json-c/issues/222)
[Clarify json_object_get_string documentation of NULL handling & return](https://api.github.com/repos/json-c/json-c/issues/223)
[json_tokener.c - all warnings being treated as errors](https://api.github.com/repos/json-c/json-c/issues/224)
[Hi, will you support clib as a "registry"?](https://api.github.com/repos/json-c/json-c/issues/225)
[Bump SOVERSION to 3](https://api.github.com/repos/json-c/json-c/issues/227)
[avoid double slashes from json](https://api.github.com/repos/json-c/json-c/issues/228)
[configure fails: checking size of size_t... configure: error: cannot determine a size for size_t](https://api.github.com/repos/json-c/json-c/issues/229)
[Use stdint.h to check for size_t size](https://api.github.com/repos/json-c/json-c/issues/230)
[Fix size_t size check for first-time builds](https://api.github.com/repos/json-c/json-c/issues/231)
[tests/tests1: fix printf format for size_t arguments](https://api.github.com/repos/json-c/json-c/issues/232)
[Include stddef.h in json_object.h](https://api.github.com/repos/json-c/json-c/issues/233)
[Add public API to use userdata independently of custom serializer](https://api.github.com/repos/json-c/json-c/issues/234)
[Undefined symbols Error for architecture x86_64 on Mac ](https://api.github.com/repos/json-c/json-c/issues/235)
[Building a project which uses json-c with flag -Wcast-qual causes compilation errors](https://api.github.com/repos/json-c/json-c/issues/236)
[handle escaped utf-8](https://api.github.com/repos/json-c/json-c/issues/237)
[linkhash.c: optimised the table_free path](https://api.github.com/repos/json-c/json-c/issues/238)
[initialize null terminator of new printbuf](https://api.github.com/repos/json-c/json-c/issues/239)
[Compile error: Variable set but not used](https://api.github.com/repos/json-c/json-c/issues/240)
[getting error in date string 19\/07\/2016, fixed for error 19/07/2016](https://api.github.com/repos/json-c/json-c/issues/241)
[json_tokener_parse error](https://api.github.com/repos/json-c/json-c/issues/242)
[Fix #165](https://api.github.com/repos/json-c/json-c/issues/243)
[Error while compiling source from RHEL5, could you please help me to fix this ](https://api.github.com/repos/json-c/json-c/issues/244)
[json-c compile in window xp](https://api.github.com/repos/json-c/json-c/issues/245)
[Mac: uselocale failed to build](https://api.github.com/repos/json-c/json-c/issues/246)
[json_object_array_del_idx function has segment fault error?](https://api.github.com/repos/json-c/json-c/issues/247)
[Minor changes in C source code](https://api.github.com/repos/json-c/json-c/issues/248)
[Improving README](https://api.github.com/repos/json-c/json-c/issues/249)
[Improving .gitignore](https://api.github.com/repos/json-c/json-c/issues/250)
[Adding a file for EditorConfig](https://api.github.com/repos/json-c/json-c/issues/251)
[Very minor changes not related to C source code](https://api.github.com/repos/json-c/json-c/issues/252)
[Adding a test with cppcheck for Travis CI](https://api.github.com/repos/json-c/json-c/issues/253)
[Very minor changes to some tests](https://api.github.com/repos/json-c/json-c/issues/254)
[Minor changes in C source code](https://api.github.com/repos/json-c/json-c/issues/255)
[Mailing list dead?](https://api.github.com/repos/json-c/json-c/issues/256)
[Defining a coding style](https://api.github.com/repos/json-c/json-c/issues/257)
[Enable CI services](https://api.github.com/repos/json-c/json-c/issues/258)
[Fails to parse valid json](https://api.github.com/repos/json-c/json-c/issues/259)
[Adding an object to itself](https://api.github.com/repos/json-c/json-c/issues/260)
[Lack of proper documentation](https://api.github.com/repos/json-c/json-c/issues/261)
[Add Cmakefile and fix compiler warning.](https://api.github.com/repos/json-c/json-c/issues/262)
[Compiler Warnings with VS2015](https://api.github.com/repos/json-c/json-c/issues/263)
[successed in simple test while failed in my project](https://api.github.com/repos/json-c/json-c/issues/264)
[Conformance report for reference](https://api.github.com/repos/json-c/json-c/issues/265)
[crash perhaps related to reference counting](https://api.github.com/repos/json-c/json-c/issues/266)
[Removes me as Win32 maintainer, because I'm not.](https://api.github.com/repos/json-c/json-c/issues/267)
[Documentation of json_object_to_json_string gives no information about memory management](https://api.github.com/repos/json-c/json-c/issues/268)
[json_object_<type>_set(json_object *o,<type> value) API for value setting in json object private structure](https://api.github.com/repos/json-c/json-c/issues/269)
[new API json_object_new_double_f(doubel d,const char * fmt);](https://api.github.com/repos/json-c/json-c/issues/270)
[Cannot compile using CMake on macOS](https://api.github.com/repos/json-c/json-c/issues/271)
[fixed wrong object name in json_object_all_values_equal](https://api.github.com/repos/json-c/json-c/issues/273)
[Support for 64 bit pointers on Windows](https://api.github.com/repos/json-c/json-c/issues/274)
[Out-of-bounds read in json_tokener_parse_ex](https://api.github.com/repos/json-c/json-c/issues/275)
[ ./configure for centos release 6.7(final) failure](https://api.github.com/repos/json-c/json-c/issues/276)
[Json object set xxx](https://api.github.com/repos/json-c/json-c/issues/277)
[Serialization of double with no fractional component drops trailing zero](https://api.github.com/repos/json-c/json-c/issues/278)
[Segmentation fault in array_list_length()](https://api.github.com/repos/json-c/json-c/issues/279)
[Should json_object_array_get_idx check whether input obj is array? ](https://api.github.com/repos/json-c/json-c/issues/280)
[how to pretty print json-c? ](https://api.github.com/repos/json-c/json-c/issues/281)
[ignore temporary files](https://api.github.com/repos/json-c/json-c/issues/282)
[json_pointer: add first revision based on RFC 6901](https://api.github.com/repos/json-c/json-c/issues/283)
[Resusing json_tokener object](https://api.github.com/repos/json-c/json-c/issues/284)
[Revert "compat/strdup.h: move common compat check for strdup() to own](https://api.github.com/repos/json-c/json-c/issues/285)
[json_tokener_parse_ex() returns json_tokener_continue on zero-length string](https://api.github.com/repos/json-c/json-c/issues/286)
[json_pointer: extend setter & getter with printf() style arguments](https://api.github.com/repos/json-c/json-c/issues/287)
[Fix _GNU_SOURCE define for vasprintf](https://api.github.com/repos/json-c/json-c/issues/288)
[bugfix: floating point representaion without fractional part ](https://api.github.com/repos/json-c/json-c/issues/289)
[duplicate an json_object](https://api.github.com/repos/json-c/json-c/issues/290)
[isspace assert error](https://api.github.com/repos/json-c/json-c/issues/291)
[configure error "./configure: line 13121: syntax error near unexpected token `-Wall'"](https://api.github.com/repos/json-c/json-c/issues/292)
[how to make with bitcode for ios](https://api.github.com/repos/json-c/json-c/issues/293)
[Adding UTF-8 validation. Fixes #122](https://api.github.com/repos/json-c/json-c/issues/294)
[cross compile w/ mingw](https://api.github.com/repos/json-c/json-c/issues/295)
[Missing functions header in json_object.h](https://api.github.com/repos/json-c/json-c/issues/296)
[could not parse string to Json object? Like string str=\"helloworld;E\\test\\log\\;end\"](https://api.github.com/repos/json-c/json-c/issues/297)
[Building using CMake doesn't work](https://api.github.com/repos/json-c/json-c/issues/298)
[Improve json_object -> string performance](https://api.github.com/repos/json-c/json-c/issues/299)
[Running tests with MinGW build](https://api.github.com/repos/json-c/json-c/issues/300)
[How to deep copy json_object in C++ ?](https://api.github.com/repos/json-c/json-c/issues/301)
[json_tokener_parse_ex doesn't parse JSON values](https://api.github.com/repos/json-c/json-c/issues/302)
[fix doc in tokener header file](https://api.github.com/repos/json-c/json-c/issues/303)
[(.text+0x72846): undefined reference to `is_error'](https://api.github.com/repos/json-c/json-c/issues/304)
[Fix compilation without C-99 option](https://api.github.com/repos/json-c/json-c/issues/305)
[./configure: line 12748 -error=deprecated-declarations](https://api.github.com/repos/json-c/json-c/issues/306)
[Memory leak in json_tokener_parse](https://api.github.com/repos/json-c/json-c/issues/307)
[AM_PROG_LIBTOOL not found on Linux](https://api.github.com/repos/json-c/json-c/issues/308)
[GCC 7 reports various -Wimplicit-fallthrough= errors](https://api.github.com/repos/json-c/json-c/issues/309)
[Add FALLTHRU comment to handle GCC7 warnings.](https://api.github.com/repos/json-c/json-c/issues/310)
[Fix error C3688 when compiling on Visual Studio 2015](https://api.github.com/repos/json-c/json-c/issues/311)
[Fix CMake Build process improved for MinGW and MSYS2](https://api.github.com/repos/json-c/json-c/issues/312)
[VERBOSE=1 make check; tests/test_util_file.test.c and tests/test_util_file.expected out of sync](https://api.github.com/repos/json-c/json-c/issues/313)
[Passing -1 to json_tokener_parse_ex is possibly unsafe](https://api.github.com/repos/json-c/json-c/issues/315)
[Memory Returned by json_object_to_json_string not freed](https://api.github.com/repos/json-c/json-c/issues/316)
[json_object_get_string gives segmentation error](https://api.github.com/repos/json-c/json-c/issues/317)
[PVS-Studio static analyzer analyze results](https://api.github.com/repos/json-c/json-c/issues/318)
[Windows: Fix dynamic library build with Visual Studio](https://api.github.com/repos/json-c/json-c/issues/319)
[Can't compile in Mac OS X El Capitan](https://api.github.com/repos/json-c/json-c/issues/320)
[build,cmake: fix vasprintf implicit definition and generate both static & shared libs](https://api.github.com/repos/json-c/json-c/issues/321)
[can not link with libjson-c.a](https://api.github.com/repos/json-c/json-c/issues/322)
[implicit fallthrough detected by gcc 7.1](https://api.github.com/repos/json-c/json-c/issues/323)
[JsonPath like function?](https://api.github.com/repos/json-c/json-c/issues/324)
[Fix stack buffer overflow in json_object_double_to_json_string_format()](https://api.github.com/repos/json-c/json-c/issues/325)
[why json-c so hard to compile](https://api.github.com/repos/json-c/json-c/issues/327)
[json_object: implement json_object_deep_copy() function](https://api.github.com/repos/json-c/json-c/issues/328)
[build,cmake: build,cmake: rename libjson-c-static.a to libjson-c.a](https://api.github.com/repos/json-c/json-c/issues/329)
[tests: symlink basic tests to a single file that has the common code](https://api.github.com/repos/json-c/json-c/issues/330)
[Safe use of snprintf() / vsnprintf() for Visual studio, and thread-safety fix](https://api.github.com/repos/json-c/json-c/issues/331)
[Valgrind: invalid read after json_object_array_del_idx.](https://api.github.com/repos/json-c/json-c/issues/332)
[Replace obsolete AM_PROG_LIBTOOL](https://api.github.com/repos/json-c/json-c/issues/333)
[README.md: show build status tag from travis-ci.org](https://api.github.com/repos/json-c/json-c/issues/335)
[tests: fix tests in travis-ci.org](https://api.github.com/repos/json-c/json-c/issues/336)
[Synchronize "potentially racy" random seed in lh_char_hash()](https://api.github.com/repos/json-c/json-c/issues/337)
[implement json_object_int_inc(json_object *, int64_t)](https://api.github.com/repos/json-c/json-c/issues/338)
[Json schema validation](https://api.github.com/repos/json-c/json-c/issues/339)
[strerror_override: add extern "C" and JSON_EXPORT specifiers for Visual C++ compilers](https://api.github.com/repos/json-c/json-c/issues/340)
[character "/" parse as "\/"](https://api.github.com/repos/json-c/json-c/issues/341)
[ No such file or directory "/usr/include/json.h"](https://api.github.com/repos/json-c/json-c/issues/342)
[Can't parse json](https://api.github.com/repos/json-c/json-c/issues/343)
[Fix Mingw build](https://api.github.com/repos/json-c/json-c/issues/344)
[Fix make dist and make distcheck](https://api.github.com/repos/json-c/json-c/issues/345)
[Clamp double to int32 when narrowing in json_object_get_int.](https://api.github.com/repos/json-c/json-c/issues/346)
[MSVC linker error json_c_strerror](https://api.github.com/repos/json-c/json-c/issues/347)
[why](https://api.github.com/repos/json-c/json-c/issues/348)
[`missing` is missing?](https://api.github.com/repos/json-c/json-c/issues/349)
[stderror-override and disable-shared](https://api.github.com/repos/json-c/json-c/issues/350)
[SIZE_T_MAX redefined from limits.h](https://api.github.com/repos/json-c/json-c/issues/351)
[`INSTALL` overrides an automake script.](https://api.github.com/repos/json-c/json-c/issues/352)
[Documentation issues](https://api.github.com/repos/json-c/json-c/issues/353)
[Fixes #351 #352 #353 ](https://api.github.com/repos/json-c/json-c/issues/354)
[1.make it can been compiled with Visual Studio 2010 by modify the CMakeList.txt and others](https://api.github.com/repos/json-c/json-c/issues/355)
[VS2008 test test_util_file.cpp err!](https://api.github.com/repos/json-c/json-c/issues/356)
[__json_c_strerror incompatibility with link-time optimization](https://api.github.com/repos/json-c/json-c/issues/357)
[make issue](https://api.github.com/repos/json-c/json-c/issues/358)
[update CMakeLists.txt for compile with visual studio at least 2010](https://api.github.com/repos/json-c/json-c/issues/359)
[Use strtoll() to parse ints](https://api.github.com/repos/json-c/json-c/issues/360)
[Fix double to int cast overflow in json_object_get_int64.](https://api.github.com/repos/json-c/json-c/issues/361)
[CMake Package Config](https://api.github.com/repos/json-c/json-c/issues/362)
[Issue #338, add json_object_add_int functions](https://api.github.com/repos/json-c/json-c/issues/363)
[Cmake is Errir](https://api.github.com/repos/json-c/json-c/issues/364)
[added fallthrough for gcc7](https://api.github.com/repos/json-c/json-c/issues/365)
[how to check the json string,crash!](https://api.github.com/repos/json-c/json-c/issues/366)
[Is json-c support "redirect" semantic?](https://api.github.com/repos/json-c/json-c/issues/367)
[Add examples](https://api.github.com/repos/json-c/json-c/issues/368)
[How to build json-c library for android?](https://api.github.com/repos/json-c/json-c/issues/369)
[Compiling using clang-cl](https://api.github.com/repos/json-c/json-c/issues/370)
[Invalid parsing for Infinity with json-c 0.12](https://api.github.com/repos/json-c/json-c/issues/371)
[Json-c 0.12: Fixed Infinity bug](https://api.github.com/repos/json-c/json-c/issues/372)
[build: fix build on appveyor CI](https://api.github.com/repos/json-c/json-c/issues/373)
[Undefined symbols for architecture x86_64:](https://api.github.com/repos/json-c/json-c/issues/374)
[what would happened when json_object_object_add add the same key](https://api.github.com/repos/json-c/json-c/issues/375)
[Eclipse error ](https://api.github.com/repos/json-c/json-c/issues/376)
[on gcc 7.2.0 on my linux distribution with json-c 2013-04-02 source](https://api.github.com/repos/json-c/json-c/issues/377)
[ Eclipse: library (libjson-c) not found, but configured](https://api.github.com/repos/json-c/json-c/issues/378)
[error: this statement may fall through \[-Werror=implicit-fallthrough=\]](https://api.github.com/repos/json-c/json-c/issues/379)
[Build on Windows](https://api.github.com/repos/json-c/json-c/issues/380)
[Fix makedist](https://api.github.com/repos/json-c/json-c/issues/381)
[Memory leak for json_tokener_parse_ex for version 0.12.1](https://api.github.com/repos/json-c/json-c/issues/382)
[Fix a compiler warning.](https://api.github.com/repos/json-c/json-c/issues/383)
[Fix a VS 2015 compiler warnings.](https://api.github.com/repos/json-c/json-c/issues/384)
* [Issue #61](https://github.com/json-c/json-c/issues/61) - Make json_object_object_add() indicate success or failure, test fix \
* [Issue #113](https://github.com/json-c/json-c/issues/113) - Build fixes (make dist and make distcheck) \
* [Issue #124](https://github.com/json-c/json-c/issues/124) - Fixing build \
* [Issue #125](https://github.com/json-c/json-c/issues/125) - Fix compile error(variable size set but not used) on g++4.6 \
* [Issue #126](https://github.com/json-c/json-c/issues/126) - Removed unused size variable. \
* [Issue #127](https://github.com/json-c/json-c/issues/127) - remove unused `size` variable \
* [Issue #128](https://github.com/json-c/json-c/issues/128) - Remove unused variable from json_tokenizer.c \
* [Issue #130](https://github.com/json-c/json-c/issues/130) - Failed to compile under Ubuntu 13.10 32bit \
* [Issue #131](https://github.com/json-c/json-c/issues/131) - undefined symbol: __sync_val_compare_and_swap_4 \
* [Issue #132](https://github.com/json-c/json-c/issues/132) - Remove unused variable 'size' \
* [Issue #133](https://github.com/json-c/json-c/issues/133) - Update and rename README to README.md \
* [Issue #134](https://github.com/json-c/json-c/issues/134) - Must remove variable size... \
* [Issue #135](https://github.com/json-c/json-c/issues/135) - bits.h uses removed json_tokener_errors\[error\] \
* [Issue #136](https://github.com/json-c/json-c/issues/136) - Error when running make check \
* [Issue #137](https://github.com/json-c/json-c/issues/137) - config.h.in should not be in git \
* [Issue #138](https://github.com/json-c/json-c/issues/138) - Can't build on RHEL 6.5 due to dependency on automake-1.14 \
* [Issue #140](https://github.com/json-c/json-c/issues/140) - Code bug in random_test.c evaluating same expression twice \
* [Issue #141](https://github.com/json-c/json-c/issues/141) - Removed duplicate check in random_seed test - bug #140 \
* [Issue #142](https://github.com/json-c/json-c/issues/142) - Please undeprecate json_object_object_get \
* [Issue #144](https://github.com/json-c/json-c/issues/144) - Introduce json_object_from_fd \
* [Issue #145](https://github.com/json-c/json-c/issues/145) - Handle % character properly \
* [Issue #146](https://github.com/json-c/json-c/issues/146) - TAGS rename \
* [Issue #148](https://github.com/json-c/json-c/issues/148) - Bump the soname \
* [Issue #149](https://github.com/json-c/json-c/issues/149) - SONAME bump \
* [Issue #150](https://github.com/json-c/json-c/issues/150) - Fix build using MinGW. \
* [Issue #151](https://github.com/json-c/json-c/issues/151) - Remove json_type enum trailing comma \
* [Issue #152](https://github.com/json-c/json-c/issues/152) - error while compiling json-c library version 0.11 \
* [Issue #153](https://github.com/json-c/json-c/issues/153) - improve doc for json_object_to_json_string() \
* [Issue #154](https://github.com/json-c/json-c/issues/154) - double precision \
* [Issue #155](https://github.com/json-c/json-c/issues/155) - add bsearch for arrays \
* [Issue #156](https://github.com/json-c/json-c/issues/156) - Remove trailing whitespaces \
* [Issue #157](https://github.com/json-c/json-c/issues/157) - JSON-C shall not exit on calloc fail. \
* [Issue #158](https://github.com/json-c/json-c/issues/158) - while using json-c 0.11, I am facing strange crash issue in json_object_put. \
* [Issue #159](https://github.com/json-c/json-c/issues/159) - json_tokener.c compile error \
* [Issue #160](https://github.com/json-c/json-c/issues/160) - missing header file on windows?? \
* [Issue #161](https://github.com/json-c/json-c/issues/161) - Is there a way to append to file? \
* [Issue #162](https://github.com/json-c/json-c/issues/162) - json_util: add directory check for POSIX distros \
* [Issue #163](https://github.com/json-c/json-c/issues/163) - Fix Win32 build problems \
* [Issue #164](https://github.com/json-c/json-c/issues/164) - made it compile and link on Widnows (as static library) \
* [Issue #165](https://github.com/json-c/json-c/issues/165) - json_object_to_json_string_ext length \
* [Issue #167](https://github.com/json-c/json-c/issues/167) - Can't build on Windows with Visual Studio 2010 \
* [Issue #168](https://github.com/json-c/json-c/issues/168) - Tightening the number parsing algorithm \
* [Issue #169](https://github.com/json-c/json-c/issues/169) - Doesn't compile on ubuntu 14.04, 64bit \
* [Issue #170](https://github.com/json-c/json-c/issues/170) - Generated files in repository \
* [Issue #171](https://github.com/json-c/json-c/issues/171) - Update configuration for VS2010 and win64 \
* [Issue #172](https://github.com/json-c/json-c/issues/172) - Adding support for parsing octal numbers \
* [Issue #173](https://github.com/json-c/json-c/issues/173) - json_parse_int64 doesn't work correctly at illumos \
* [Issue #174](https://github.com/json-c/json-c/issues/174) - Adding JSON_C_TO_STRING_PRETTY_TAB flag \
* [Issue #175](https://github.com/json-c/json-c/issues/175) - make check fails 4 tests with overflows when built with ASAN \
* [Issue #176](https://github.com/json-c/json-c/issues/176) - Possible to delete an array element at a given idx ? \
* [Issue #177](https://github.com/json-c/json-c/issues/177) - Fix compiler warnings \
* [Issue #178](https://github.com/json-c/json-c/issues/178) - Unable to compile on CentOS5 \
* [Issue #179](https://github.com/json-c/json-c/issues/179) - Added array_list_del_idx and json_object_array_del_idx \
* [Issue #180](https://github.com/json-c/json-c/issues/180) - Enable silent build by default \
* [Issue #181](https://github.com/json-c/json-c/issues/181) - json_tokener_parse_ex accepts invalid JSON \
* [Issue #182](https://github.com/json-c/json-c/issues/182) - Link against libm when needed \
* [Issue #183](https://github.com/json-c/json-c/issues/183) - Apply compile warning fix to master branch \
* [Issue #184](https://github.com/json-c/json-c/issues/184) - Use only GCC-specific flags when compiling with GCC \
* [Issue #185](https://github.com/json-c/json-c/issues/185) - compile error \
* [Issue #186](https://github.com/json-c/json-c/issues/186) - Syntax error \
* [Issue #187](https://github.com/json-c/json-c/issues/187) - array_list_get_idx and negative indexes. \
* [Issue #188](https://github.com/json-c/json-c/issues/188) - json_object_object_foreach warnings \
* [Issue #189](https://github.com/json-c/json-c/issues/189) - noisy json_object_from_file: error opening file \
* [Issue #190](https://github.com/json-c/json-c/issues/190) - warning: initialization discards const qualifier from pointer target type \[enabled by default\] \
* [Issue #192](https://github.com/json-c/json-c/issues/192) - json_tokener_parse accepts invalid JSON {"key": "value" , } \
* [Issue #193](https://github.com/json-c/json-c/issues/193) - Make serialization format of doubles configurable \
* [Issue #194](https://github.com/json-c/json-c/issues/194) - Add utility function for comparing json_objects \
* [Issue #195](https://github.com/json-c/json-c/issues/195) - Call uselocale instead of setlocale \
* [Issue #196](https://github.com/json-c/json-c/issues/196) - Performance improvements \
* [Issue #197](https://github.com/json-c/json-c/issues/197) - Time for a new release? \
* [Issue #198](https://github.com/json-c/json-c/issues/198) - Fix possible memory leak and remove superfluous NULL checks before free() \
* [Issue #199](https://github.com/json-c/json-c/issues/199) - Fix build in Visual Studio \
* [Issue #200](https://github.com/json-c/json-c/issues/200) - Add build scripts for CI platforms \
* [Issue #201](https://github.com/json-c/json-c/issues/201) - disable forward-slash escaping? \
* [Issue #202](https://github.com/json-c/json-c/issues/202) - Array with objects support \
* [Issue #203](https://github.com/json-c/json-c/issues/203) - Add source position/coordinates to API \
* [Issue #204](https://github.com/json-c/json-c/issues/204) - json-c/json.h not found \
* [Issue #205](https://github.com/json-c/json-c/issues/205) - json-c Compiled with Visual Studios \
* [Issue #206](https://github.com/json-c/json-c/issues/206) - what do i use in place of json_object_object_get? \
* [Issue #207](https://github.com/json-c/json-c/issues/207) - Add support for property pairs directly added to arrays \
* [Issue #208](https://github.com/json-c/json-c/issues/208) - Performance enhancements (mainly) to json_object_to_json_string() \
* [Issue #209](https://github.com/json-c/json-c/issues/209) - fix regression from 2d549662be832da838aa063da2efa78ee3b99668 \
* [Issue #210](https://github.com/json-c/json-c/issues/210) - Use size_t for arrays \
* [Issue #211](https://github.com/json-c/json-c/issues/211) - Atomic updates for the refcount \
* [Issue #212](https://github.com/json-c/json-c/issues/212) - Refcount doesn't work between threads \
* [Issue #213](https://github.com/json-c/json-c/issues/213) - fix to compile with microsoft visual c++ 2010 \
* [Issue #214](https://github.com/json-c/json-c/issues/214) - Some non-GNU systems support __sync_val_compare_and_swap \
* [Issue #215](https://github.com/json-c/json-c/issues/215) - Build json-c for window 64 bit. \
* [Issue #216](https://github.com/json-c/json-c/issues/216) - configure: check realloc with AC_CHECK_FUNCS() to fix cross-compilation. \
* [Issue #217](https://github.com/json-c/json-c/issues/217) - Checking for functions in float.h \
* [Issue #218](https://github.com/json-c/json-c/issues/218) - Use a macro to indicate C99 to the compiler \
* [Issue #219](https://github.com/json-c/json-c/issues/219) - Fix various potential null ptr deref and int32 overflows \
* [Issue #220](https://github.com/json-c/json-c/issues/220) - Add utility function for comparing json_objects \
* [Issue #221](https://github.com/json-c/json-c/issues/221) - JSON_C_TO_STRING_NOSLASHESCAPE works incorrectly \
* [Issue #222](https://github.com/json-c/json-c/issues/222) - Fix issue #221: JSON_C_TO_STRING_NOSLASHESCAPE works incorrectly \
* [Issue #223](https://github.com/json-c/json-c/issues/223) - Clarify json_object_get_string documentation of NULL handling & return \
* [Issue #224](https://github.com/json-c/json-c/issues/224) - json_tokener.c - all warnings being treated as errors \
* [Issue #225](https://github.com/json-c/json-c/issues/225) - Hi, will you support clib as a "registry"? \
* [Issue #227](https://github.com/json-c/json-c/issues/227) - Bump SOVERSION to 3 \
* [Issue #228](https://github.com/json-c/json-c/issues/228) - avoid double slashes from json \
* [Issue #229](https://github.com/json-c/json-c/issues/229) - configure fails: checking size of size_t... configure: error: cannot determine a size for size_t \
* [Issue #230](https://github.com/json-c/json-c/issues/230) - Use stdint.h to check for size_t size \
* [Issue #231](https://github.com/json-c/json-c/issues/231) - Fix size_t size check for first-time builds \
* [Issue #232](https://github.com/json-c/json-c/issues/232) - tests/tests1: fix printf format for size_t arguments \
* [Issue #233](https://github.com/json-c/json-c/issues/233) - Include stddef.h in json_object.h \
* [Issue #234](https://github.com/json-c/json-c/issues/234) - Add public API to use userdata independently of custom serializer \
* [Issue #235](https://github.com/json-c/json-c/issues/235) - Undefined symbols Error for architecture x86_64 on Mac \
* [Issue #236](https://github.com/json-c/json-c/issues/236) - Building a project which uses json-c with flag -Wcast-qual causes compilation errors \
* [Issue #237](https://github.com/json-c/json-c/issues/237) - handle escaped utf-8 \
* [Issue #238](https://github.com/json-c/json-c/issues/238) - linkhash.c: optimised the table_free path \
* [Issue #239](https://github.com/json-c/json-c/issues/239) - initialize null terminator of new printbuf \
* [Issue #240](https://github.com/json-c/json-c/issues/240) - Compile error: Variable set but not used \
* [Issue #241](https://github.com/json-c/json-c/issues/241) - getting error in date string 19\/07\/2016, fixed for error 19/07/2016 \
* [Issue #242](https://github.com/json-c/json-c/issues/242) - json_tokener_parse error \
* [Issue #243](https://github.com/json-c/json-c/issues/243) - Fix #165 \
* [Issue #244](https://github.com/json-c/json-c/issues/244) - Error while compiling source from RHEL5, could you please help me to fix this \
* [Issue #245](https://github.com/json-c/json-c/issues/245) - json-c compile in window xp \
* [Issue #246](https://github.com/json-c/json-c/issues/246) - Mac: uselocale failed to build \
* [Issue #247](https://github.com/json-c/json-c/issues/247) - json_object_array_del_idx function has segment fault error? \
* [Issue #248](https://github.com/json-c/json-c/issues/248) - Minor changes in C source code \
* [Issue #249](https://github.com/json-c/json-c/issues/249) - Improving README \
* [Issue #250](https://github.com/json-c/json-c/issues/250) - Improving .gitignore \
* [Issue #251](https://github.com/json-c/json-c/issues/251) - Adding a file for EditorConfig \
* [Issue #252](https://github.com/json-c/json-c/issues/252) - Very minor changes not related to C source code \
* [Issue #253](https://github.com/json-c/json-c/issues/253) - Adding a test with cppcheck for Travis CI \
* [Issue #254](https://github.com/json-c/json-c/issues/254) - Very minor changes to some tests \
* [Issue #255](https://github.com/json-c/json-c/issues/255) - Minor changes in C source code \
* [Issue #256](https://github.com/json-c/json-c/issues/256) - Mailing list dead? \
* [Issue #257](https://github.com/json-c/json-c/issues/257) - Defining a coding style \
* [Issue #258](https://github.com/json-c/json-c/issues/258) - Enable CI services \
* [Issue #259](https://github.com/json-c/json-c/issues/259) - Fails to parse valid json \
* [Issue #260](https://github.com/json-c/json-c/issues/260) - Adding an object to itself \
* [Issue #261](https://github.com/json-c/json-c/issues/261) - Lack of proper documentation \
* [Issue #262](https://github.com/json-c/json-c/issues/262) - Add Cmakefile and fix compiler warning. \
* [Issue #263](https://github.com/json-c/json-c/issues/263) - Compiler Warnings with VS2015 \
* [Issue #264](https://github.com/json-c/json-c/issues/264) - successed in simple test while failed in my project \
* [Issue #265](https://github.com/json-c/json-c/issues/265) - Conformance report for reference \
* [Issue #266](https://github.com/json-c/json-c/issues/266) - crash perhaps related to reference counting \
* [Issue #267](https://github.com/json-c/json-c/issues/267) - Removes me as Win32 maintainer, because I'm not. \
* [Issue #268](https://github.com/json-c/json-c/issues/268) - Documentation of json_object_to_json_string gives no information about memory management \
* [Issue #269](https://github.com/json-c/json-c/issues/269) - json_object_<type>_set(json_object *o,<type> value) API for value setting in json object private structure \
* [Issue #270](https://github.com/json-c/json-c/issues/270) - new API json_object_new_double_f(doubel d,const char * fmt); \
* [Issue #271](https://github.com/json-c/json-c/issues/271) - Cannot compile using CMake on macOS \
* [Issue #273](https://github.com/json-c/json-c/issues/273) - fixed wrong object name in json_object_all_values_equal \
* [Issue #274](https://github.com/json-c/json-c/issues/274) - Support for 64 bit pointers on Windows \
* [Issue #275](https://github.com/json-c/json-c/issues/275) - Out-of-bounds read in json_tokener_parse_ex \
* [Issue #276](https://github.com/json-c/json-c/issues/276) - ./configure for centos release 6.7(final) failure \
* [Issue #277](https://github.com/json-c/json-c/issues/277) - Json object set xxx \
* [Issue #278](https://github.com/json-c/json-c/issues/278) - Serialization of double with no fractional component drops trailing zero \
* [Issue #279](https://github.com/json-c/json-c/issues/279) - Segmentation fault in array_list_length() \
* [Issue #280](https://github.com/json-c/json-c/issues/280) - Should json_object_array_get_idx check whether input obj is array? \
* [Issue #281](https://github.com/json-c/json-c/issues/281) - how to pretty print json-c? \
* [Issue #282](https://github.com/json-c/json-c/issues/282) - ignore temporary files \
* [Issue #283](https://github.com/json-c/json-c/issues/283) - json_pointer: add first revision based on RFC 6901 \
* [Issue #284](https://github.com/json-c/json-c/issues/284) - Resusing json_tokener object \
* [Issue #285](https://github.com/json-c/json-c/issues/285) - Revert "compat/strdup.h: move common compat check for strdup() to own \
* [Issue #286](https://github.com/json-c/json-c/issues/286) - json_tokener_parse_ex() returns json_tokener_continue on zero-length string \
* [Issue #287](https://github.com/json-c/json-c/issues/287) - json_pointer: extend setter & getter with printf() style arguments \
* [Issue #288](https://github.com/json-c/json-c/issues/288) - Fix _GNU_SOURCE define for vasprintf \
* [Issue #289](https://github.com/json-c/json-c/issues/289) - bugfix: floating point representaion without fractional part \
* [Issue #290](https://github.com/json-c/json-c/issues/290) - duplicate an json_object \
* [Issue #291](https://github.com/json-c/json-c/issues/291) - isspace assert error \
* [Issue #292](https://github.com/json-c/json-c/issues/292) - configure error "./configure: line 13121: syntax error near unexpected token `-Wall'" \
* [Issue #293](https://github.com/json-c/json-c/issues/293) - how to make with bitcode for ios \
* [Issue #294](https://github.com/json-c/json-c/issues/294) - Adding UTF-8 validation. Fixes #122 \
* [Issue #295](https://github.com/json-c/json-c/issues/295) - cross compile w/ mingw \
* [Issue #296](https://github.com/json-c/json-c/issues/296) - Missing functions header in json_object.h \
* [Issue #297](https://github.com/json-c/json-c/issues/297) - could not parse string to Json object? Like string str=\"helloworld;E\\test\\log\\;end\" \
* [Issue #298](https://github.com/json-c/json-c/issues/298) - Building using CMake doesn't work \
* [Issue #299](https://github.com/json-c/json-c/issues/299) - Improve json_object -> string performance \
* [Issue #300](https://github.com/json-c/json-c/issues/300) - Running tests with MinGW build \
* [Issue #301](https://github.com/json-c/json-c/issues/301) - How to deep copy json_object in C++ ? \
* [Issue #302](https://github.com/json-c/json-c/issues/302) - json_tokener_parse_ex doesn't parse JSON values \
* [Issue #303](https://github.com/json-c/json-c/issues/303) - fix doc in tokener header file \
* [Issue #304](https://github.com/json-c/json-c/issues/304) - (.text+0x72846): undefined reference to `is_error' \
* [Issue #305](https://github.com/json-c/json-c/issues/305) - Fix compilation without C-99 option \
* [Issue #306](https://github.com/json-c/json-c/issues/306) - ./configure: line 12748 -error=deprecated-declarations \
* [Issue #307](https://github.com/json-c/json-c/issues/307) - Memory leak in json_tokener_parse \
* [Issue #308](https://github.com/json-c/json-c/issues/308) - AM_PROG_LIBTOOL not found on Linux \
* [Issue #309](https://github.com/json-c/json-c/issues/309) - GCC 7 reports various -Wimplicit-fallthrough= errors \
* [Issue #310](https://github.com/json-c/json-c/issues/310) - Add FALLTHRU comment to handle GCC7 warnings. \
* [Issue #311](https://github.com/json-c/json-c/issues/311) - Fix error C3688 when compiling on Visual Studio 2015 \
* [Issue #312](https://github.com/json-c/json-c/issues/312) - Fix CMake Build process improved for MinGW and MSYS2 \
* [Issue #313](https://github.com/json-c/json-c/issues/313) - VERBOSE=1 make check; tests/test_util_file.test.c and tests/test_util_file.expected out of sync \
* [Issue #315](https://github.com/json-c/json-c/issues/315) - Passing -1 to json_tokener_parse_ex is possibly unsafe \
* [Issue #316](https://github.com/json-c/json-c/issues/316) - Memory Returned by json_object_to_json_string not freed \
* [Issue #317](https://github.com/json-c/json-c/issues/317) - json_object_get_string gives segmentation error \
* [Issue #318](https://github.com/json-c/json-c/issues/318) - PVS-Studio static analyzer analyze results \
* [Issue #319](https://github.com/json-c/json-c/issues/319) - Windows: Fix dynamic library build with Visual Studio \
* [Issue #320](https://github.com/json-c/json-c/issues/320) - Can't compile in Mac OS X El Capitan \
* [Issue #321](https://github.com/json-c/json-c/issues/321) - build,cmake: fix vasprintf implicit definition and generate both static & shared libs \
* [Issue #322](https://github.com/json-c/json-c/issues/322) - can not link with libjson-c.a \
* [Issue #323](https://github.com/json-c/json-c/issues/323) - implicit fallthrough detected by gcc 7.1 \
* [Issue #324](https://github.com/json-c/json-c/issues/324) - JsonPath like function? \
* [Issue #325](https://github.com/json-c/json-c/issues/325) - Fix stack buffer overflow in json_object_double_to_json_string_format() \
* [Issue #327](https://github.com/json-c/json-c/issues/327) - why json-c so hard to compile \
* [Issue #328](https://github.com/json-c/json-c/issues/328) - json_object: implement json_object_deep_copy() function \
* [Issue #329](https://github.com/json-c/json-c/issues/329) - build,cmake: build,cmake: rename libjson-c-static.a to libjson-c.a \
* [Issue #330](https://github.com/json-c/json-c/issues/330) - tests: symlink basic tests to a single file that has the common code \
* [Issue #331](https://github.com/json-c/json-c/issues/331) - Safe use of snprintf() / vsnprintf() for Visual studio, and thread-safety fix \
* [Issue #332](https://github.com/json-c/json-c/issues/332) - Valgrind: invalid read after json_object_array_del_idx. \
* [Issue #333](https://github.com/json-c/json-c/issues/333) - Replace obsolete AM_PROG_LIBTOOL \
* [Issue #335](https://github.com/json-c/json-c/issues/335) - README.md: show build status tag from travis-ci.org \
* [Issue #336](https://github.com/json-c/json-c/issues/336) - tests: fix tests in travis-ci.org \
* [Issue #337](https://github.com/json-c/json-c/issues/337) - Synchronize "potentially racy" random seed in lh_char_hash() \
* [Issue #338](https://github.com/json-c/json-c/issues/338) - implement json_object_int_inc(json_object *, int64_t) \
* [Issue #339](https://github.com/json-c/json-c/issues/339) - Json schema validation \
* [Issue #340](https://github.com/json-c/json-c/issues/340) - strerror_override: add extern "C" and JSON_EXPORT specifiers for Visual C++ compilers \
* [Issue #341](https://github.com/json-c/json-c/issues/341) - character "/" parse as "\/" \
* [Issue #342](https://github.com/json-c/json-c/issues/342) - No such file or directory "/usr/include/json.h" \
* [Issue #343](https://github.com/json-c/json-c/issues/343) - Can't parse json \
* [Issue #344](https://github.com/json-c/json-c/issues/344) - Fix Mingw build \
* [Issue #345](https://github.com/json-c/json-c/issues/345) - Fix make dist and make distcheck \
* [Issue #346](https://github.com/json-c/json-c/issues/346) - Clamp double to int32 when narrowing in json_object_get_int. \
* [Issue #347](https://github.com/json-c/json-c/issues/347) - MSVC linker error json_c_strerror \
* [Issue #348](https://github.com/json-c/json-c/issues/348) - why \
* [Issue #349](https://github.com/json-c/json-c/issues/349) - `missing` is missing? \
* [Issue #350](https://github.com/json-c/json-c/issues/350) - stderror-override and disable-shared \
* [Issue #351](https://github.com/json-c/json-c/issues/351) - SIZE_T_MAX redefined from limits.h \
* [Issue #352](https://github.com/json-c/json-c/issues/352) - `INSTALL` overrides an automake script. \
* [Issue #353](https://github.com/json-c/json-c/issues/353) - Documentation issues \
* [Issue #354](https://github.com/json-c/json-c/issues/354) - Fixes #351 #352 #353 \
* [Issue #355](https://github.com/json-c/json-c/issues/355) - 1.make it can been compiled with Visual Studio 2010 by modify the CMakeList.txt and others \
* [Issue #356](https://github.com/json-c/json-c/issues/356) - VS2008 test test_util_file.cpp err! \
* [Issue #357](https://github.com/json-c/json-c/issues/357) - __json_c_strerror incompatibility with link-time optimization \
* [Issue #358](https://github.com/json-c/json-c/issues/358) - make issue \
* [Issue #359](https://github.com/json-c/json-c/issues/359) - update CMakeLists.txt for compile with visual studio at least 2010 \
* [Issue #360](https://github.com/json-c/json-c/issues/360) - Use strtoll() to parse ints \
* [Issue #361](https://github.com/json-c/json-c/issues/361) - Fix double to int cast overflow in json_object_get_int64. \
* [Issue #362](https://github.com/json-c/json-c/issues/362) - CMake Package Config \
* [Issue #363](https://github.com/json-c/json-c/issues/363) - Issue #338, add json_object_add_int functions \
* [Issue #364](https://github.com/json-c/json-c/issues/364) - Cmake is Errir \
* [Issue #365](https://github.com/json-c/json-c/issues/365) - added fallthrough for gcc7 \
* [Issue #366](https://github.com/json-c/json-c/issues/366) - how to check the json string,crash! \
* [Issue #367](https://github.com/json-c/json-c/issues/367) - Is json-c support "redirect" semantic? \
* [Issue #368](https://github.com/json-c/json-c/issues/368) - Add examples \
* [Issue #369](https://github.com/json-c/json-c/issues/369) - How to build json-c library for android? \
* [Issue #370](https://github.com/json-c/json-c/issues/370) - Compiling using clang-cl \
* [Issue #371](https://github.com/json-c/json-c/issues/371) - Invalid parsing for Infinity with json-c 0.12 \
* [Issue #372](https://github.com/json-c/json-c/issues/372) - Json-c 0.12: Fixed Infinity bug \
* [Issue #373](https://github.com/json-c/json-c/issues/373) - build: fix build on appveyor CI \
* [Issue #374](https://github.com/json-c/json-c/issues/374) - Undefined symbols for architecture x86_64: \
* [Issue #375](https://github.com/json-c/json-c/issues/375) - what would happened when json_object_object_add add the same key \
* [Issue #376](https://github.com/json-c/json-c/issues/376) - Eclipse error \
* [Issue #377](https://github.com/json-c/json-c/issues/377) - on gcc 7.2.0 on my linux distribution with json-c 2013-04-02 source \
* [Issue #378](https://github.com/json-c/json-c/issues/378) - Eclipse: library (libjson-c) not found, but configured \
* [Issue #379](https://github.com/json-c/json-c/issues/379) - error: this statement may fall through \[-Werror=implicit-fallthrough=\] \
* [Issue #380](https://github.com/json-c/json-c/issues/380) - Build on Windows \
* [Issue #381](https://github.com/json-c/json-c/issues/381) - Fix makedist \
* [Issue #382](https://github.com/json-c/json-c/issues/382) - Memory leak for json_tokener_parse_ex for version 0.12.1 \
* [Issue #383](https://github.com/json-c/json-c/issues/383) - Fix a compiler warning. \
* [Issue #384](https://github.com/json-c/json-c/issues/384) - Fix a VS 2015 compiler warnings. \

202
issues_closed_for_0.14.md Normal file
View File

@@ -0,0 +1,202 @@
This list was created with:
```
curl https://api.github.com/search/issues?q="repo%3Ajson-c%2Fjson-c+closed%3A>2017-12-07+created%3A<2020-04-17&sort=created&order=asc&per_page=400&page=1" > issues1.out
curl https://api.github.com/search/issues?q="repo%3Ajson-c%2Fjson-c+closed%3A>2017-12-07+created%3A<2020-04-17&sort=created&order=asc&per_page=400&page=2" > issues2.out
curl https://api.github.com/search/issues?q="repo%3Ajson-c%2Fjson-c+closed%3A>2017-12-07+created%3A<2020-04-17&sort=created&order=asc&per_page=400&page=3" > issues3.out
jq -r '.items[] | "[" + .title + "](" + .url + ")" | tostring' issues?.out > issues.md
sed -e's,^\[ *\(.*\)\](https://api.github.com/.*/\([0-9].*\)),[Issue #\2](https://github.com/json-c/json-c/issues/\2) - \1,' -i issues.md
#... manual editing ...
```
----
Issues and Pull Requests closed for the 0.14 release (since commit d582d3a(2017-12-07) to a911439(2020-04-17))
* [Issue #122](https://github.com/json-c/json-c/issues/122) - Add utf-8 validation when parsing strings. \
* [Issue #139](https://github.com/json-c/json-c/issues/139) - json_object_from_file cannot accept max_depth \
* [Issue #143](https://github.com/json-c/json-c/issues/143) - RFE / enhancement for full 64-bit signed/unsigned support \
* [Issue #147](https://github.com/json-c/json-c/issues/147) - Please introduce soname bump if API changed \
* [Issue #166](https://github.com/json-c/json-c/issues/166) - Need a way to specify nesting depth when opening JSON file \
* [Issue #226](https://github.com/json-c/json-c/issues/226) - There is no json_object_new_null() \
* [Issue #314](https://github.com/json-c/json-c/issues/314) - new release ? \
* [Issue #326](https://github.com/json-c/json-c/issues/326) - Please extend api json_object_get_uint64 \
* [Issue #334](https://github.com/json-c/json-c/issues/334) - Switch json-c builds to use CMake \
* [Issue #386](https://github.com/json-c/json-c/issues/386) - Makefile: Add ACLOCAL_AMFLAGS \
* [Issue #387](https://github.com/json-c/json-c/issues/387) - doc: Use other doxygen feature to specify mainpage \
* [Issue #388](https://github.com/json-c/json-c/issues/388) - json_object: Add size_t json_object_sizeof() \
* [Issue #389](https://github.com/json-c/json-c/issues/389) - json_object: Avoid double free (and thus a segfault) when ref_count gets < 0 \
* [Issue #390](https://github.com/json-c/json-c/issues/390) - json_object: Add const size_t json_c_object_sizeof() \
* [Issue #391](https://github.com/json-c/json-c/issues/391) - Fix non-GNUC define for JSON_C_CONST_FUNCTION \
* [Issue #392](https://github.com/json-c/json-c/issues/392) - json_object: Avoid invalid free (and thus a segfault) when ref_count gets < 0 \
* [Issue #393](https://github.com/json-c/json-c/issues/393) - json_object_private: Use unsigned 32-bit integer type for refcount \
* [Issue #394](https://github.com/json-c/json-c/issues/394) - Problem serializing double \
* [Issue #395](https://github.com/json-c/json-c/issues/395) - Key gets modified if it contains "\" \
* [Issue #396](https://github.com/json-c/json-c/issues/396) - Build failure with no threads uClibc toolchain \
* [Issue #397](https://github.com/json-c/json-c/issues/397) - update json object with key. \
* [Issue #398](https://github.com/json-c/json-c/issues/398) - Build failed. \
* [Issue #399](https://github.com/json-c/json-c/issues/399) - Avoid uninitialized variable warnings \
* [Issue #400](https://github.com/json-c/json-c/issues/400) - How to generate static lib (.a) \
* [Issue #401](https://github.com/json-c/json-c/issues/401) - Warnings with Valgrind \
* [Issue #402](https://github.com/json-c/json-c/issues/402) - Add fuzzers from OSS-Fuzz \
* [Issue #403](https://github.com/json-c/json-c/issues/403) - Segmentation fault when double quotes is used \
* [Issue #404](https://github.com/json-c/json-c/issues/404) - valgrind: memory leak \
* [Issue #405](https://github.com/json-c/json-c/issues/405) - Missing API to determine an object is empty \
* [Issue #406](https://github.com/json-c/json-c/issues/406) - Undefine NDEBUG for tests \
* [Issue #407](https://github.com/json-c/json-c/issues/407) - json_tokener_parse is crash \
* [Issue #408](https://github.com/json-c/json-c/issues/408) - bug in array_list_del_idx when array_list_length()==1 \
* [Issue #410](https://github.com/json-c/json-c/issues/410) - Fixed typos \
* [Issue #411](https://github.com/json-c/json-c/issues/411) - Crash- signal SIGSEGV, Segmentation fault. ../sysdeps/x86_64/strlen.S: No such file or directory. \
* [Issue #412](https://github.com/json-c/json-c/issues/412) - json_type changes during inter process communication. \
* [Issue #413](https://github.com/json-c/json-c/issues/413) - how to read object of type `json_object *` in c++ \
* [Issue #414](https://github.com/json-c/json-c/issues/414) - [Question] How JSON-c stores the serialized data in memory? \
* [Issue #415](https://github.com/json-c/json-c/issues/415) - Resolve windows name conflict \
* [Issue #416](https://github.com/json-c/json-c/issues/416) - segmentation fault in json_tokener_parse \
* [Issue #417](https://github.com/json-c/json-c/issues/417) - json_tokener_parse json_object_object_get_ex with string value which is json string \
* [Issue #418](https://github.com/json-c/json-c/issues/418) - json_object_from_* return value documented incorrectly \
* [Issue #419](https://github.com/json-c/json-c/issues/419) - Suggestion: document (and define) that json_object_put() accepts NULL pointer to object \
* [Issue #420](https://github.com/json-c/json-c/issues/420) - arraylist: Fixed names of parameters for callback function \
* [Issue #421](https://github.com/json-c/json-c/issues/421) - install json_object_iterator.h header file \
* [Issue #422](https://github.com/json-c/json-c/issues/422) - json_object_get_double() does not set errno when there is no valid conversion \
* [Issue #423](https://github.com/json-c/json-c/issues/423) - memory leak \
* [Issue #424](https://github.com/json-c/json-c/issues/424) - Parse string contains "\" or "/" errors \
* [Issue #425](https://github.com/json-c/json-c/issues/425) - what this is? \
* [Issue #426](https://github.com/json-c/json-c/issues/426) - __deprecated not supported on clang. \
* [Issue #427](https://github.com/json-c/json-c/issues/427) - CMake: builds involving this target will not be correct \
* [Issue #430](https://github.com/json-c/json-c/issues/430) - json_object_object_del() and Segmentation fault \
* [Issue #431](https://github.com/json-c/json-c/issues/431) - cmake: Bump required version \
* [Issue #432](https://github.com/json-c/json-c/issues/432) - The real CMake support. \
* [Issue #433](https://github.com/json-c/json-c/issues/433) - The real CMake support. \
* [Issue #434](https://github.com/json-c/json-c/issues/434) - The real CMake support \
* [Issue #435](https://github.com/json-c/json-c/issues/435) - json_object_object_del() segmentation fault \
* [Issue #436](https://github.com/json-c/json-c/issues/436) - Improve pkgconfig setting \
* [Issue #437](https://github.com/json-c/json-c/issues/437) - Bad link in README.md \
* [Issue #438](https://github.com/json-c/json-c/issues/438) - Bad link in README.html \
* [Issue #439](https://github.com/json-c/json-c/issues/439) - reserved identifier violation \
* [Issue #440](https://github.com/json-c/json-c/issues/440) - Use of angle brackets around file names for include statements \
* [Issue #441](https://github.com/json-c/json-c/issues/441) - fix c flag loss during cmake building \
* [Issue #442](https://github.com/json-c/json-c/issues/442) - error in configure file \
* [Issue #443](https://github.com/json-c/json-c/issues/443) - remove pretty spaces when using pretty tabs \
* [Issue #444](https://github.com/json-c/json-c/issues/444) - Document refcount of json_tokener_parse_ex return \
* [Issue #445](https://github.com/json-c/json-c/issues/445) - Add missing "make check" target to cmake config \
* [Issue #446](https://github.com/json-c/json-c/issues/446) - Forward slashes get escaped \
* [Issue #448](https://github.com/json-c/json-c/issues/448) - Buffer overflow in json-c \
* [Issue #449](https://github.com/json-c/json-c/issues/449) - Need of json_type_int64 returned by json_object_get_type() \
* [Issue #450](https://github.com/json-c/json-c/issues/450) - Allow use json-c cmake as subproject \
* [Issue #452](https://github.com/json-c/json-c/issues/452) - Update README.md \
* [Issue #453](https://github.com/json-c/json-c/issues/453) - Fixed misalignment in JSON string due to space after \n being printed... \
* [Issue #454](https://github.com/json-c/json-c/issues/454) - json_object_private: save 8 bytes in struct json_object in 64-bit arc \
* [Issue #455](https://github.com/json-c/json-c/issues/455) - index.html:fix dead link \
* [Issue #456](https://github.com/json-c/json-c/issues/456) - STYLE.txt:remove executable permissions \
* [Issue #457](https://github.com/json-c/json-c/issues/457) - .gitignore:add build directory \
* [Issue #458](https://github.com/json-c/json-c/issues/458) - README.md:fix dead "file.html" link \
* [Issue #459](https://github.com/json-c/json-c/issues/459) - README.html:fix link to Doxygen docs, remove WIN32 link \
* [Issue #460](https://github.com/json-c/json-c/issues/460) - No docs for json_object_new_string_len() \
* [Issue #461](https://github.com/json-c/json-c/issues/461) - json_object.c:set errno in json_object_get_double() \
* [Issue #462](https://github.com/json-c/json-c/issues/462) - json_object.h:document json_object_new_string_len() \
* [Issue #463](https://github.com/json-c/json-c/issues/463) - please check newlocale api first argument valuse. \
* [Issue #465](https://github.com/json-c/json-c/issues/465) - CMakeLists.txt doesn't contain json_object_iterator.h which json.h includes \
* [Issue #466](https://github.com/json-c/json-c/issues/466) - configure:3610: error: C compiler cannot create executables \
* [Issue #467](https://github.com/json-c/json-c/issues/467) - Fix compiler warnings \
* [Issue #468](https://github.com/json-c/json-c/issues/468) - Fix compiler warnings \
* [Issue #469](https://github.com/json-c/json-c/issues/469) - Build under alpine with pecl install & docker-php-ext-enable? \
* [Issue #470](https://github.com/json-c/json-c/issues/470) - cfuhash_foreach_remove doesn't upate cfuhash_num_entries \
* [Issue #472](https://github.com/json-c/json-c/issues/472) - Segmentation fault in json_object_iter_begin \
* [Issue #473](https://github.com/json-c/json-c/issues/473) - Convert ChangeLog to valid UTF-8 encoding. \
* [Issue #474](https://github.com/json-c/json-c/issues/474) - Installation directories empty with CMake in pkg-config. \
* [Issue #475](https://github.com/json-c/json-c/issues/475) - improvement proposal for json_object_object_foreach \
* [Issue #477](https://github.com/json-c/json-c/issues/477) - Hang/Crash with large strings \
* [Issue #478](https://github.com/json-c/json-c/issues/478) - json_object_get_string_len returns 0 when value is number \
* [Issue #479](https://github.com/json-c/json-c/issues/479) - I want to use it in iOS or Android but I can't compile \
* [Issue #480](https://github.com/json-c/json-c/issues/480) - json-c-0.12.1 failed making from source code \
* [Issue #481](https://github.com/json-c/json-c/issues/481) - error while loading shared libraries: libjson-c.so.4 \
* [Issue #482](https://github.com/json-c/json-c/issues/482) - Error "double free or corruption" after free() \
* [Issue #483](https://github.com/json-c/json-c/issues/483) - compatible with rarely-used Chinese characters in GBK charset \
* [Issue #485](https://github.com/json-c/json-c/issues/485) - Install CMake module files \
* [Issue #486](https://github.com/json-c/json-c/issues/486) - In the case of negative double value, it is formatted without including ".0" \
* [Issue #488](https://github.com/json-c/json-c/issues/488) - Some APIs are not exported when built as shared lib on Win32 \
* [Issue #489](https://github.com/json-c/json-c/issues/489) - Don't use -Werror by default \
* [Issue #490](https://github.com/json-c/json-c/issues/490) - do not compile with -Werror by default \
* [Issue #491](https://github.com/json-c/json-c/issues/491) - build: add option --disable-werror to configure \
* [Issue #492](https://github.com/json-c/json-c/issues/492) - lack some quick usage in readme \
* [Issue #494](https://github.com/json-c/json-c/issues/494) - Code generator? \
* [Issue #495](https://github.com/json-c/json-c/issues/495) - README.md:fix 2 typos \
* [Issue #496](https://github.com/json-c/json-c/issues/496) - json_pointer.h:suggest minor grammar improvement for pointer doc \
* [Issue #497](https://github.com/json-c/json-c/issues/497) - add common header for all tests \
* [Issue #498](https://github.com/json-c/json-c/issues/498) - double_serializer_test fails (with valgrind) \
* [Issue #499](https://github.com/json-c/json-c/issues/499) - .travis.yml:test on more recent clang and gcc versions \
* [Issue #500](https://github.com/json-c/json-c/issues/500) - test/Makefile.am:add missing deps for test1 and test2 \
* [Issue #501](https://github.com/json-c/json-c/issues/501) - undefine NDEBUG for tests \
* [Issue #502](https://github.com/json-c/json-c/issues/502) - configure error \
* [Issue #503](https://github.com/json-c/json-c/issues/503) - json-c retuns OK when Invalid json string is passed \
* [Issue #504](https://github.com/json-c/json-c/issues/504) - json_object_put coredump \
* [Issue #505](https://github.com/json-c/json-c/issues/505) - Add vcpkg installation instructions \
* [Issue #506](https://github.com/json-c/json-c/issues/506) - Cannot parse more than one object \
* [Issue #509](https://github.com/json-c/json-c/issues/509) - Sometimes a double value is not serialized \
* [Issue #510](https://github.com/json-c/json-c/issues/510) - Bump so-name and improve CMake \
* [Issue #511](https://github.com/json-c/json-c/issues/511) - Reduce lines for better optimization \
* [Issue #512](https://github.com/json-c/json-c/issues/512) - Properly append to CMAKE_C_FLAGS string \
* [Issue #513](https://github.com/json-c/json-c/issues/513) - What does `userdata` means?And what is the case we can use it? \
* [Issue #514](https://github.com/json-c/json-c/issues/514) - Json c 0.13 \
* [Issue #515](https://github.com/json-c/json-c/issues/515) - Mies suomesta fixes segfaults and logic errors \
* [Issue #516](https://github.com/json-c/json-c/issues/516) - Lja slight mods \
* [Issue #518](https://github.com/json-c/json-c/issues/518) - Escape character "\\003\", get unexpected value \
* [Issue #519](https://github.com/json-c/json-c/issues/519) - Add test case obj token \
* [Issue #520](https://github.com/json-c/json-c/issues/520) - Adding type uint64 \
* [Issue #521](https://github.com/json-c/json-c/issues/521) - build cmake windows 10 \
* [Issue #522](https://github.com/json-c/json-c/issues/522) - update json_visit testcase \
* [Issue #523](https://github.com/json-c/json-c/issues/523) - update tsetcase for tokener_c \
* [Issue #524](https://github.com/json-c/json-c/issues/524) - Increase coverage \
* [Issue #525](https://github.com/json-c/json-c/issues/525) - update pointer test case \
* [Issue #526](https://github.com/json-c/json-c/issues/526) - Increased the test coverage of printbuf.c 82% to 92%. \
* [Issue #527](https://github.com/json-c/json-c/issues/527) - Arraylist testcase \
* [Issue #528](https://github.com/json-c/json-c/issues/528) - Solve issue #108. Skip \u0000 while parsing. \
* [Issue #529](https://github.com/json-c/json-c/issues/529) - Increased the test coverage of json_c_version.c 0% to 100%. \
* [Issue #530](https://github.com/json-c/json-c/issues/530) - validate utf-8 string before parse \
* [Issue #531](https://github.com/json-c/json-c/issues/531) - validate utf-8 string \
* [Issue #532](https://github.com/json-c/json-c/issues/532) - json_object_object_get_ex returning the original object \
* [Issue #533](https://github.com/json-c/json-c/issues/533) - Fix "make check" \
* [Issue #535](https://github.com/json-c/json-c/issues/535) - short string optimization: excessive array length \
* [Issue #536](https://github.com/json-c/json-c/issues/536) - add json_object_new_null() \
* [Issue #538](https://github.com/json-c/json-c/issues/538) - update shortstring and arraylist parameters \
* [Issue #539](https://github.com/json-c/json-c/issues/539) - double serializes to the old value after set_double \
* [Issue #541](https://github.com/json-c/json-c/issues/541) - add coveralls auto tool to json-c \
* [Issue #542](https://github.com/json-c/json-c/issues/542) - add uint64 data to json-c \
* [Issue #543](https://github.com/json-c/json-c/issues/543) - Readme \
* [Issue #544](https://github.com/json-c/json-c/issues/544) - Increase distcheck target in cmake \
* [Issue #545](https://github.com/json-c/json-c/issues/545) - add doc target in cmake \
* [Issue #546](https://github.com/json-c/json-c/issues/546) - Add uninstall target in cmake \
* [Issue #547](https://github.com/json-c/json-c/issues/547) - modify json-c default build type, and fix up the assert() errors in t \
* [Issue #548](https://github.com/json-c/json-c/issues/548) - Solve some problems about cmake build type (debug/release) \
* [Issue #549](https://github.com/json-c/json-c/issues/549) - lib installation issues \
* [Issue #550](https://github.com/json-c/json-c/issues/550) - Format codes with clang-format tool? \
* [Issue #551](https://github.com/json-c/json-c/issues/551) - Allow hexadecimal number format convention parsing \
* [Issue #553](https://github.com/json-c/json-c/issues/553) - Fix/clang ubsan \
* [Issue #554](https://github.com/json-c/json-c/issues/554) - RFC 8259 compatibility mode \
* [Issue #555](https://github.com/json-c/json-c/issues/555) - Format json-c with clang-format tool \
* [Issue #556](https://github.com/json-c/json-c/issues/556) - Fixes various Wreturn-type and Wimplicit-fallthrough errors on Mingw-w64 \
* [Issue #557](https://github.com/json-c/json-c/issues/557) - Add option in CMAKE to not build documentation \
* [Issue #558](https://github.com/json-c/json-c/issues/558) - modify the doc target message \
* [Issue #559](https://github.com/json-c/json-c/issues/559) - json_c_visit() not exported on Windows \
* [Issue #560](https://github.com/json-c/json-c/issues/560) - error: implicit declaration of function '_strtoi64' \
* [Issue #561](https://github.com/json-c/json-c/issues/561) - add the badge in README.md and test the coveralls \
* [Issue #562](https://github.com/json-c/json-c/issues/562) - Bugfix and testcases supplements \
* [Issue #563](https://github.com/json-c/json-c/issues/563) - Changed order of calloc args to match stdlib \
* [Issue #564](https://github.com/json-c/json-c/issues/564) - Remove autogenerated files \
* [Issue #565](https://github.com/json-c/json-c/issues/565) - test the CI and ignore this PR \
* [Issue #566](https://github.com/json-c/json-c/issues/566) - add the json_types.h to Makefile.am \
* [Issue #567](https://github.com/json-c/json-c/issues/567) - Install json_types.h with autotools build as well. \
* [Issue #568](https://github.com/json-c/json-c/issues/568) - Adding better support to MinGW \
* [Issue #569](https://github.com/json-c/json-c/issues/569) - Handling of -Bsymbolic-function in CMakeLists.txt is deficient \
* [Issue #571](https://github.com/json-c/json-c/issues/571) - CMake: Bump SONAME to 5. \
* [Issue #572](https://github.com/json-c/json-c/issues/572) - Small fixes to CMakeLists \
* [Issue #573](https://github.com/json-c/json-c/issues/573) - Fix coveralls submission. \
* [Issue #574](https://github.com/json-c/json-c/issues/574) - autogen.sh missing from repository \
* [Issue #575](https://github.com/json-c/json-c/issues/575) - Small cosmetics. \
* [Issue #576](https://github.com/json-c/json-c/issues/576) - Test coverage for json_c_version. \
* [Issue #577](https://github.com/json-c/json-c/issues/577) - Be verbose on failing json_c_version test. \
* [Issue #578](https://github.com/json-c/json-c/issues/578) - CMake: Install pkgconfig file in proper location by default \
* [Issue #579](https://github.com/json-c/json-c/issues/579) - Enforce strict prototypes. \
* [Issue #580](https://github.com/json-c/json-c/issues/580) - Fix CMake tests for enforced strict prototypes. \
* [Issue #581](https://github.com/json-c/json-c/issues/581) - CMakeLists: do not enforce strict prototypes on Windows. \

85
issues_closed_for_0.15.md Normal file
View File

@@ -0,0 +1,85 @@
This list was created with:
```
curl "https://api.github.com/search/issues?q=repo%3Ajson-c%2Fjson-c+closed%3A>2020-04-18+created%3A<2020-07-23&sort=created&order=asc&per_page=100&page=1" > issues1.out
jq -r '.items[] | "[" + .title + "](" + .url + ")" | tostring' issues?.out > issues.md
sed -e's,^\[ *\(.*\)\](https://api.github.com/.*/\([0-9].*\)),* [Issue #\2](https://github.com/json-c/json-c/issues/\2) - \1,' -i issues.md
#... manual editing ...
```
----
Issues and Pull Requests closed for the 0.15 release
(since commit 31ab57ca, the 0.14 branch point, 2020-04-19)
* [Issue #428](https://github.com/json-c/json-c/issues/428) - Added new_null() function
* [Issue #429](https://github.com/json-c/json-c/issues/429) - Conflict of interest between JSON_C_TO_STRING_SPACED and JSON_C_TO_STRING_PRETTY
* [Issue #451](https://github.com/json-c/json-c/issues/451) - Add option to disable HAVE___THREAD
* [Issue #471](https://github.com/json-c/json-c/issues/471) - create folders with mode 0755 when building
* [Issue #476](https://github.com/json-c/json-c/issues/476) - Add new function named json_object_new_string_noalloc
* [Issue #484](https://github.com/json-c/json-c/issues/484) - Add support for uint64
* [Issue #487](https://github.com/json-c/json-c/issues/487) - Any plans to make new release? (0.14)
* [Issue #493](https://github.com/json-c/json-c/issues/493) - Kdopen rename library
* [Issue #507](https://github.com/json-c/json-c/issues/507) - Double value -1.0 converts to integer in json_object_to_json_string()
* [Issue #508](https://github.com/json-c/json-c/issues/508) - Recommend enabling the `-fPIC` compiler flag by default
* [Issue #517](https://github.com/json-c/json-c/issues/517) - Lja mods
* [Issue #534](https://github.com/json-c/json-c/issues/534) - Both json-c and json-glib have json_object_get_type()
* [Issue #584](https://github.com/json-c/json-c/issues/584) - CMake: SOVERSION and the major library VERSION need to be in lockstep.
* [Issue #585](https://github.com/json-c/json-c/issues/585) - CMake: Do not install config.h, as it is not a public header file.
* [Issue #586](https://github.com/json-c/json-c/issues/586) - 10796 Segmentation fault
* [Issue #588](https://github.com/json-c/json-c/issues/588) - Broken RDRAND causes infinite looping
* [Issue #589](https://github.com/json-c/json-c/issues/589) - Detect broken RDRAND during initialization
* [Issue #590](https://github.com/json-c/json-c/issues/590) - Fix segmentation fault in CPUID check
* [Issue #591](https://github.com/json-c/json-c/issues/591) - Update README.md
* [Issue #592](https://github.com/json-c/json-c/issues/592) - Prevent out of boundary write on malicious input
* [Issue #593](https://github.com/json-c/json-c/issues/593) - Building both static and shared libraries
* [Issue #594](https://github.com/json-c/json-c/issues/594) - Some subsequent call of lh_get_hash not working
* [Issue #595](https://github.com/json-c/json-c/issues/595) - Support to build both static and shared libraries
* [Issue #596](https://github.com/json-c/json-c/issues/596) - QA Notice: Package triggers severe warnings
* [Issue #597](https://github.com/json-c/json-c/issues/597) - json_parse demo: fix and use usage() function
* [Issue #598](https://github.com/json-c/json-c/issues/598) - Turning off shared libs causes target duplication or build error
* [Issue #599](https://github.com/json-c/json-c/issues/599) - cannot add more than 11 objects. Is this a known issue?
* [Issue #600](https://github.com/json-c/json-c/issues/600) - Library name conflicts on Windows are back again
* [Issue #601](https://github.com/json-c/json-c/issues/601) - json_tokener_parse() in master sets errno=1 "Operation not permitted"
* [Issue #602](https://github.com/json-c/json-c/issues/602) - fix json_parse_uint64() internal error checking with errno
* [Issue #603](https://github.com/json-c/json-c/issues/603) - Backport of fixes from master branch.
* [Issue #604](https://github.com/json-c/json-c/issues/604) - commit f2e991a3419ee4078e8915e840b1a0d9003b349e breaks cross-compilation with mingw
* [Issue #605](https://github.com/json-c/json-c/issues/605) - Update to 0.15 release
* [Issue #606](https://github.com/json-c/json-c/issues/606) - Improved support for IBM operating systems
* [Issue #607](https://github.com/json-c/json-c/issues/607) - json-c-0.13.x: Fix CVE-2020-12762 - json-c through 0.14 has an integer overflow and out-of-bounds write ...
* [Issue #608](https://github.com/json-c/json-c/issues/608) - json-c-0.14: Fix CVE-2020-12762 - json-c through 0.14 has an integer overflow and out-of-bounds write ...
* [Issue #609](https://github.com/json-c/json-c/issues/609) - use unsigned types for sizes in lh_table and entries
* [Issue #610](https://github.com/json-c/json-c/issues/610) - let's not call lh_table_resize with INT_MAX
* [Issue #611](https://github.com/json-c/json-c/issues/611) - json-c-0.12.x: Fix CVE-2020-12762 - json-c through 0.14 has an integer overflow and out-of-bounds write ...
* [Issue #613](https://github.com/json-c/json-c/issues/613) - json-c-0.10: Fix CVE-2020-12762 - json-c through 0.14 has an integer overflow and out-of-bounds write ...
* [Issue #614](https://github.com/json-c/json-c/issues/614) - Prevent truncation on custom double formatters.
* [Issue #615](https://github.com/json-c/json-c/issues/615) - New release with security fix
* [Issue #616](https://github.com/json-c/json-c/issues/616) - Parsing fails if UTF-16 low surrogate pair is not in same chunk is the high pair
* [Issue #617](https://github.com/json-c/json-c/issues/617) - Add an option to disable the use of thread-local storage.
* [Issue #618](https://github.com/json-c/json-c/issues/618) - test_deep_copy: Fix assertion value.
* [Issue #619](https://github.com/json-c/json-c/issues/619) - CMake: Fix out-of-tree build for Doxygen documentation.
* [Issue #621](https://github.com/json-c/json-c/issues/621) - json-c and jansson libraries have symbol conflicts
* [Issue #622](https://github.com/json-c/json-c/issues/622) - doc: Move Doxyfile into doc subdir.
* [Issue #623](https://github.com/json-c/json-c/issues/623) - json_tokener_parse : Segmentation fault
* [Issue #626](https://github.com/json-c/json-c/issues/626) - Fixes for cmake 2.8.12 + link issue on AIX 6.1/cc 11.01
* [Issue #627](https://github.com/json-c/json-c/issues/627) - Compat fixes
* [Issue #628](https://github.com/json-c/json-c/issues/628) - get_cryptgenrandom_seed: compat with old windows + fallback
* [Issue #629](https://github.com/json-c/json-c/issues/629) - [0.12] Remove the Visual Studio project file
* [Issue #630](https://github.com/json-c/json-c/issues/630) - Linking with Windows MINGW not working
* [Issue #632](https://github.com/json-c/json-c/issues/632) - Json object split
* [Issue #633](https://github.com/json-c/json-c/issues/633) - fix issue 616: support the surrogate pair in split file.
* [Issue #634](https://github.com/json-c/json-c/issues/634) - Issue #508: `-fPIC` to link libjson-c.a with libs
* [Issue #635](https://github.com/json-c/json-c/issues/635) - expression has no effect warning in json_tokener.c
* [Issue #636](https://github.com/json-c/json-c/issues/636) - json_object_get_string free str memory
* [Issue #637](https://github.com/json-c/json-c/issues/637) - json_object_put() has 'double free or corruption (out) '
* [Issue #638](https://github.com/json-c/json-c/issues/638) - json-c/json_object.c:50:2: error: #error Unable to determine size of ssize_t
* [Issue #639](https://github.com/json-c/json-c/issues/639) - build: Add a symbol version to all exported symbols
* [Issue #640](https://github.com/json-c/json-c/issues/640) - Fix build issues with SSIZE_MAX on 64bit Linux
* [Issue #641](https://github.com/json-c/json-c/issues/641) - Formal verification of your test suite
* [Issue #642](https://github.com/json-c/json-c/issues/642) - Please provide more precise informations about when to call json_object_put
* [Issue #643](https://github.com/json-c/json-c/issues/643) - not able to compare with string
* [Issue #644](https://github.com/json-c/json-c/issues/644) - Why src->_userdata not checked before calling strdup?
* [Issue #645](https://github.com/json-c/json-c/issues/645) - Misuse of tolower() in json_tokener.c
* [Issue #646](https://github.com/json-c/json-c/issues/646) - Cast to unsigned char instead of int when calling tolower (Fixes #645)

107
issues_closed_for_0.16.md Normal file
View File

@@ -0,0 +1,107 @@
This list was created with:
```
PREV=2020-07-23
NOW=2022-04-13
curl "https://api.github.com/search/issues?q=repo%3Ajson-c%2Fjson-c+closed%3A>${PREV}+created%3A<${NOW}&sort=created&order=asc&per_page=100&page=1" > issues1.out
jq -r '.items[] | "[" + .title + "](" + .url + ")" | tostring' issues?.out > issues.md
sed -e's,^\[ *\(.*\)\](https://api.github.com/.*/\([0-9].*\)),* [Issue #\2](https://github.com/json-c/json-c/issues/\2) - \1,' -i issues.md
cat issues.md >> issues_closed_for_0.16.md
```
* [Issue #464](https://github.com/json-c/json-c/issues/464) - Speed up parsing and object creation
* [Issue #540](https://github.com/json-c/json-c/issues/540) - request: json_init_library
* [Issue #631](https://github.com/json-c/json-c/issues/631) - New 0.14 release requests
* [Issue #647](https://github.com/json-c/json-c/issues/647) - "cmake -DCMAKE_BUILD_TYPE=Release" fails with error: 'cint64' may be used uninitialized
* [Issue #648](https://github.com/json-c/json-c/issues/648) - Fix "may be used uninitialized" Release build failure
* [Issue #649](https://github.com/json-c/json-c/issues/649) - json-c tag 0.15 tarball contains a file doc/Doxyfile and generated doxygen files in doc/html
* [Issue #650](https://github.com/json-c/json-c/issues/650) - README: fix spelling errors
* [Issue #651](https://github.com/json-c/json-c/issues/651) - Getrandom
* [Issue #652](https://github.com/json-c/json-c/issues/652) - Waste memory
* [Issue #653](https://github.com/json-c/json-c/issues/653) - Make the documentation build reproducibly
* [Issue #654](https://github.com/json-c/json-c/issues/654) - A stack-buffer-overflow in json_parse.c:89:44
* [Issue #655](https://github.com/json-c/json-c/issues/655) - json_parse: Fix read past end of buffer
* [Issue #656](https://github.com/json-c/json-c/issues/656) - Fixed warnings
* [Issue #657](https://github.com/json-c/json-c/issues/657) - Use GRND_NONBLOCK with getrandom.
* [Issue #658](https://github.com/json-c/json-c/issues/658) - json_object_get_boolean() returns wrong result for objects and arrays
* [Issue #659](https://github.com/json-c/json-c/issues/659) - fix json_object_get_boolean() to behave like documented
* [Issue #660](https://github.com/json-c/json-c/issues/660) - Validate size arguments in arraylist functions.
* [Issue #661](https://github.com/json-c/json-c/issues/661) - Cleanup of some code parts
* [Issue #662](https://github.com/json-c/json-c/issues/662) - Prevent signed overflow in get_time_seed
* [Issue #663](https://github.com/json-c/json-c/issues/663) - Properly format errnos in _json_c_strerror
* [Issue #664](https://github.com/json-c/json-c/issues/664) - Limit strings at INT_MAX length
* [Issue #665](https://github.com/json-c/json-c/issues/665) - Handle more allocation failures in json_tokener* functions
* [Issue #666](https://github.com/json-c/json-c/issues/666) - test1 json_object_new_array_ext test is failing
* [Issue #667](https://github.com/json-c/json-c/issues/667) - Fixed test1 regression.
* [Issue #670](https://github.com/json-c/json-c/issues/670) - Created Stone-Paper-Scissor Game by C language
* [Issue #672](https://github.com/json-c/json-c/issues/672) - Calling exit() after failure to generate random seed
* [Issue #673](https://github.com/json-c/json-c/issues/673) - switchcasemenuproject
* [Issue #674](https://github.com/json-c/json-c/issues/674) - random_seed: on error, continue to next method
* [Issue #682](https://github.com/json-c/json-c/issues/682) - libjson-c-dev vs libjson-c3
* [Issue #683](https://github.com/json-c/json-c/issues/683) - [Question] Is it possible to clear a ptr of json_object?
* [Issue #684](https://github.com/json-c/json-c/issues/684) - json_tokener_parse_verbose failed with core dump
* [Issue #685](https://github.com/json-c/json-c/issues/685) - json_tokener_parse memory leak?
* [Issue #689](https://github.com/json-c/json-c/issues/689) - fix compilation with clang
* [Issue #690](https://github.com/json-c/json-c/issues/690) - "1," produces an object with int 1; "1" produces a null object
* [Issue #691](https://github.com/json-c/json-c/issues/691) - failed tests
* [Issue #692](https://github.com/json-c/json-c/issues/692) - patch to add arc4random
* [Issue #693](https://github.com/json-c/json-c/issues/693) - Optional parameter for packing as array
* [Issue #694](https://github.com/json-c/json-c/issues/694) - fix invalid unsigned arithmetic.
* [Issue #695](https://github.com/json-c/json-c/issues/695) - /tmp/json-c/random_seed.c:327:6: error
* [Issue #696](https://github.com/json-c/json-c/issues/696) - To avoid target exe file export JSON functions.
* [Issue #697](https://github.com/json-c/json-c/issues/697) - json_object_get_string() return value truncated when assigning it to a pointer type in Win32 App
* [Issue #698](https://github.com/json-c/json-c/issues/698) - Feature request: set allocator
* [Issue #699](https://github.com/json-c/json-c/issues/699) - Linking to libjson-c Issue
* [Issue #700](https://github.com/json-c/json-c/issues/700) - Fix unused variable for Win32 build in random_seed.c
* [Issue #701](https://github.com/json-c/json-c/issues/701) - [RFC] json_pointer: allow the feature to be disabled
* [Issue #703](https://github.com/json-c/json-c/issues/703) - Fix vasprintf fallback
* [Issue #706](https://github.com/json-c/json-c/issues/706) - Check __STDC_VERSION__ is defined before checking its value
* [Issue #707](https://github.com/json-c/json-c/issues/707) - How to build json-c-0.15 for arm arch
* [Issue #708](https://github.com/json-c/json-c/issues/708) - direct access to elements
* [Issue #709](https://github.com/json-c/json-c/issues/709) - Include guards not namespaced / build errors for debug.h with openNDS
* [Issue #710](https://github.com/json-c/json-c/issues/710) - 'file system sandbox blocked mmap()' error on iOS
* [Issue #711](https://github.com/json-c/json-c/issues/711) - creating a json object
* [Issue #712](https://github.com/json-c/json-c/issues/712) - building json-c using cmake for ESP32
* [Issue #713](https://github.com/json-c/json-c/issues/713) - When value converted to char* can not compare it with another value
* [Issue #714](https://github.com/json-c/json-c/issues/714) - Add AfterCaseLabel to .clang-format
* [Issue #716](https://github.com/json-c/json-c/issues/716) - Fixed cmake command
* [Issue #717](https://github.com/json-c/json-c/issues/717) - Cmake is able delete all files by "clean" target
* [Issue #718](https://github.com/json-c/json-c/issues/718) - CMake create uninstall target if unix generator is used
* [Issue #719](https://github.com/json-c/json-c/issues/719) - Parsing multiple JSON strings
* [Issue #722](https://github.com/json-c/json-c/issues/722) - Fix use-after-free in json_tokener_new_ex()
* [Issue #723](https://github.com/json-c/json-c/issues/723) - if set __stdcall (/Gz)
* [Issue #724](https://github.com/json-c/json-c/issues/724) - #723
* [Issue #725](https://github.com/json-c/json-c/issues/725) - json_object_from_file() execution segment error
* [Issue #726](https://github.com/json-c/json-c/issues/726) - fix cmake version for tests
* [Issue #727](https://github.com/json-c/json-c/issues/727) - Really use prefix JSON_C_OBJECT_ADD_
* [Issue #728](https://github.com/json-c/json-c/issues/728) - DRAFT PROPOSAL - Add option JSON_C_OBJECT_ADD_IF_NOT_NULL
* [Issue #729](https://github.com/json-c/json-c/issues/729) - * don't assume includedir
* [Issue #731](https://github.com/json-c/json-c/issues/731) - Json-c Error
* [Issue #732](https://github.com/json-c/json-c/issues/732) - Fix/static include dirs
* [Issue #734](https://github.com/json-c/json-c/issues/734) - Newer appveyor config for VS2022 etc...
* [Issue #735](https://github.com/json-c/json-c/issues/735) - Add policy_max to minimum required cmake version
* [Issue #736](https://github.com/json-c/json-c/issues/736) - json_object.c:308: json_object_put: Assertion `jso->_ref_count > 0' failed
* [Issue #737](https://github.com/json-c/json-c/issues/737) - Fix typo in README
* [Issue #738](https://github.com/json-c/json-c/issues/738) - General question - Is there an SLA for handling newly detected security issues?
* [Issue #739](https://github.com/json-c/json-c/issues/739) - json_escape_str(): avoid harmless unsigned integer overflow
* [Issue #741](https://github.com/json-c/json-c/issues/741) - json_type_to_name(): use correct printf() formatter
* [Issue #742](https://github.com/json-c/json-c/issues/742) - json_object_copy_serializer_data(): add assertion
* [Issue #743](https://github.com/json-c/json-c/issues/743) - Cmd adb root
* [Issue #744](https://github.com/json-c/json-c/issues/744) - Close file on error path.
* [Issue #745](https://github.com/json-c/json-c/issues/745) - vasprintf(): avoid out of memory accesses
* [Issue #746](https://github.com/json-c/json-c/issues/746) - Fix typos in code comments and ChangeLog
* [Issue #747](https://github.com/json-c/json-c/issues/747) - json_object_put: Assertion `jso->_ref_count > 0' failed
* [Issue #748](https://github.com/json-c/json-c/issues/748) - sprintbuf(): test for all vsnprintf error values
* [Issue #749](https://github.com/json-c/json-c/issues/749) - sprintbuf(): handle printbuf_memappend errors
* [Issue #750](https://github.com/json-c/json-c/issues/750) - printbuf_memset(): set gaps to zero
* [Issue #751](https://github.com/json-c/json-c/issues/751) - printbuf: do not allow invalid arguments
* [Issue #752](https://github.com/json-c/json-c/issues/752) - Fix typos
* [Issue #753](https://github.com/json-c/json-c/issues/753) - CTest failed in MSVC build
* [Issue #754](https://github.com/json-c/json-c/issues/754) - Minor improvements to documentation
* [Issue #755](https://github.com/json-c/json-c/issues/755) - Fix error messages
* [Issue #758](https://github.com/json-c/json-c/issues/758) - Preserve context if out of memory
* [Issue #760](https://github.com/json-c/json-c/issues/760) - Code style: removed unneeded double-quotes
* [Issue #761](https://github.com/json-c/json-c/issues/761) - Last commit merged to master breaks compilation
* [Issue #762](https://github.com/json-c/json-c/issues/762) - how to merge two jsons by json-c
* [Issue #763](https://github.com/json-c/json-c/issues/763) - Question: sort_fn arguments
* [Issue #764](https://github.com/json-c/json-c/issues/764) - Make test fail on test case test_util_file

88
issues_closed_for_0.17.md Normal file
View File

@@ -0,0 +1,88 @@
This list was created with:
```
PREV=2022-04-13
NOW=2023-08-12
curl "https://api.github.com/search/issues?q=repo%3Ajson-c%2Fjson-c+closed%3A>${PREV}+created%3A<${NOW}&sort=created&order=asc&per_page=100&page=1" > issues1.out
jq -r '.items[] | "[" + .title + "](" + .url + ")" | tostring' issues?.out > issues.md
sed -e's,^\[ *\(.*\)\](https://api.github.com/.*/\([0-9].*\)),* [Issue #\2](https://github.com/json-c/json-c/issues/\2) - \1,' -i issues.md
cat issues.md >> issues_closed_for_0.17.md
```
* [Issue #191](https://github.com/json-c/json-c/issues/191) - Override int64 to only display uint64 strings
* [Issue #537](https://github.com/json-c/json-c/issues/537) - Replace '\0' only when parsing key, not change data in value.
* [Issue #570](https://github.com/json-c/json-c/issues/570) - Figure out what needs to be done with Android.configure.mk
* [Issue #587](https://github.com/json-c/json-c/issues/587) - Store the hashValue to avoid repeating the hash calculation during the hash resize.
* [Issue #612](https://github.com/json-c/json-c/issues/612) - json-c-0.11: Fix CVE-2020-12762 - json-c through 0.14 has an integer overflow and out-of-bounds write ...
* [Issue #620](https://github.com/json-c/json-c/issues/620) - Introduce json_object_new_string_{ext,noalloc}().
* [Issue #624](https://github.com/json-c/json-c/issues/624) - json-c-0.14: Detect broken RDRAND during initialization.
* [Issue #625](https://github.com/json-c/json-c/issues/625) - json-c-0.13.x: Detect broken RDRAND during initialization.
* [Issue #668](https://github.com/json-c/json-c/issues/668) - Memory usage regression due to newlocal() on older FreeBSD releases
* [Issue #676](https://github.com/json-c/json-c/issues/676) - dereferencing type-punned pointer might break strict-aliasing rules [-Werror=strict-aliasing]
* [Issue #677](https://github.com/json-c/json-c/issues/677) - Naming conflict when using both json-c and jansson
* [Issue #679](https://github.com/json-c/json-c/issues/679) - Let json-c be used with obsolete compilers
* [Issue #681](https://github.com/json-c/json-c/issues/681) - json_tokener_parse_ex: `null` (4 bytes) only parses as valid JSON when passed with null terminator (5 bytes). Documentation issue?
* [Issue #686](https://github.com/json-c/json-c/issues/686) - Remove dependency on libM::getrandom
* [Issue #687](https://github.com/json-c/json-c/issues/687) - Does not build on Apple Silicon M1
* [Issue #688](https://github.com/json-c/json-c/issues/688) - json-c-0.15-nodoc.tar.gz build fails
* [Issue #702](https://github.com/json-c/json-c/issues/702) - json_patch: add first implementation only with patch application
* [Issue #704](https://github.com/json-c/json-c/issues/704) - add json_object_array_insert_idx() + test-cases + fix json_pointer doc-strings
* [Issue #705](https://github.com/json-c/json-c/issues/705) - segmentation fault on json-c parsing methods in cross compiled target
* [Issue #721](https://github.com/json-c/json-c/issues/721) - cmake test fails with building json-c with icc
* [Issue #730](https://github.com/json-c/json-c/issues/730) - Need a comparison with other JSON libraries in C
* [Issue #733](https://github.com/json-c/json-c/issues/733) - Official release? 1.0?
* [Issue #756](https://github.com/json-c/json-c/issues/756) - Question: Is there any way to build this with Gnu Make?
* [Issue #757](https://github.com/json-c/json-c/issues/757) - json_object_from_fd_ex: fail if file is too large
* [Issue #759](https://github.com/json-c/json-c/issues/759) - json_tokener_parse_ex: handle out of memory errors
* [Issue #766](https://github.com/json-c/json-c/issues/766) - Some people have trouble with undefined references to arc4random
* [Issue #767](https://github.com/json-c/json-c/issues/767) - How to create a character array using json-c
* [Issue #768](https://github.com/json-c/json-c/issues/768) - commits from May 30, 2022 killed my docker build process
* [Issue #769](https://github.com/json-c/json-c/issues/769) - Issue #768
* [Issue #770](https://github.com/json-c/json-c/issues/770) - json_parse.c:170:13: error: this statement may fall through
* [Issue #771](https://github.com/json-c/json-c/issues/771) - fix fallthough warning
* [Issue #772](https://github.com/json-c/json-c/issues/772) - add JSON_C_TO_STRING_COLOR option
* [Issue #773](https://github.com/json-c/json-c/issues/773) - problem with u_int64_t
* [Issue #774](https://github.com/json-c/json-c/issues/774) - The function add_compile_options was added to CMake version 2.8.12 and later but your minimum is 2.8 which will not work
* [Issue #775](https://github.com/json-c/json-c/issues/775) - list(TRANSFORM ...) is not available prior to CMake 3.12.
* [Issue #776](https://github.com/json-c/json-c/issues/776) - Fix typo
* [Issue #777](https://github.com/json-c/json-c/issues/777) - Don't try to change locale when libc only supports the C locale
* [Issue #778](https://github.com/json-c/json-c/issues/778) - Do not insert newlines when converting empty arrays to json string and JSON_C_TO_STRING_PRETTY is used
* [Issue #779](https://github.com/json-c/json-c/issues/779) - Fix compiling for Android
* [Issue #780](https://github.com/json-c/json-c/issues/780) - Memory Leak when setting empty strings when c_string.pdata is used
* [Issue #781](https://github.com/json-c/json-c/issues/781) - Fix memory leak with emtpy strings in json_object_set_string
* [Issue #782](https://github.com/json-c/json-c/issues/782) - Fix typos found by codespell
* [Issue #783](https://github.com/json-c/json-c/issues/783) - Fix build with clang-15+
* [Issue #784](https://github.com/json-c/json-c/issues/784) - get_time_seed(): silence warning emitted by Coverity Scan static analyzer
* [Issue #786](https://github.com/json-c/json-c/issues/786) - ghpages update was not published for json-c-0.16
* [Issue #787](https://github.com/json-c/json-c/issues/787) - -static linker flag result in building failed
* [Issue #788](https://github.com/json-c/json-c/issues/788) - Clear sensitive information.
* [Issue #789](https://github.com/json-c/json-c/issues/789) - Unnecessary struct declaration and unsafe function usage
* [Issue #790](https://github.com/json-c/json-c/issues/790) - Small update to README file
* [Issue #791](https://github.com/json-c/json-c/issues/791) - json_object_object_foreach not ISO-C compliant
* [Issue #792](https://github.com/json-c/json-c/issues/792) - ` json_object_get_int` does not set `EINVAL` on invalid string
* [Issue #794](https://github.com/json-c/json-c/issues/794) - replaced
* [Issue #796](https://github.com/json-c/json-c/issues/796) - Added Test for get int functions
* [Issue #797](https://github.com/json-c/json-c/issues/797) - make uninstall
* [Issue #798](https://github.com/json-c/json-c/issues/798) - API to deal with enums is missing
* [Issue #799](https://github.com/json-c/json-c/issues/799) - json_object_put: Assertion `jso->_ref_count > 0' failed.
* [Issue #800](https://github.com/json-c/json-c/issues/800) - String converted to scientific notation
* [Issue #801](https://github.com/json-c/json-c/issues/801) - #error You do not have strncasecmp on your system.
* [Issue #802](https://github.com/json-c/json-c/issues/802) - Problem: modern CMake warns about version 2.8
* [Issue #803](https://github.com/json-c/json-c/issues/803) - Problem: confusing error message in snprintf_compat.h
* [Issue #804](https://github.com/json-c/json-c/issues/804) - Problem: cmake 3.25.1 warns about CMP0042 not being set
* [Issue #806](https://github.com/json-c/json-c/issues/806) - The problem is libjson-c.dylib incompatible with OS version
* [Issue #807](https://github.com/json-c/json-c/issues/807) - json simple parse syntax
* [Issue #808](https://github.com/json-c/json-c/issues/808) - iOS Build using cmake fails due to 64 to 32bits conversion precision loss
* [Issue #809](https://github.com/json-c/json-c/issues/809) - Feature request json_object_new_uint()
* [Issue #810](https://github.com/json-c/json-c/issues/810) - docs: update to Internet Standard reference
* [Issue #811](https://github.com/json-c/json-c/issues/811) - dependence on execution character set
* [Issue #812](https://github.com/json-c/json-c/issues/812) - Duplicate symbol when compiling with clang-cl
* [Issue #813](https://github.com/json-c/json-c/issues/813) - Build apps only in project itself.
* [Issue #814](https://github.com/json-c/json-c/issues/814) - Code execution order
* [Issue #816](https://github.com/json-c/json-c/issues/816) - Hi I need to generate libjson-c.so.3 and libjson-c.so.3.0.1, please help with steps
* [Issue #818](https://github.com/json-c/json-c/issues/818) - error: a function declaration without a prototype is deprecated in all versions of C
* [Issue #819](https://github.com/json-c/json-c/issues/819) - build with intel 2023 fails on vasprintf
* [Issue #820](https://github.com/json-c/json-c/issues/820) - ISO C forbids in
* [Issue #821](https://github.com/json-c/json-c/issues/821) - Any release planing for 0.17?
* [Issue #822](https://github.com/json-c/json-c/issues/822) - Added option to disable app build
* [Issue #823](https://github.com/json-c/json-c/issues/823) - Symbol not found during linking stage of libjson-c.so

View File

@@ -1,11 +0,0 @@
prefix=
exec_prefix=
libdir=@abs_top_builddir@
includedir=@abs_top_srcdir@
Name: json
Description: JSON implementation in C
Version: @VERSION@
Requires:
Libs: -L@abs_top_builddir@ -ljson-c
Cflags: -I@abs_top_srcdir@

View File

@@ -9,4 +9,4 @@ Version: @VERSION@
Requires: Requires:
Libs.private: @LIBS@ Libs.private: @LIBS@
Libs: -L${libdir} -ljson-c Libs: -L${libdir} -ljson-c
Cflags: -I${includedir}/json-c Cflags: -I${includedir} -I${includedir}/json-c

182
json-c.sym Normal file
View File

@@ -0,0 +1,182 @@
/*
* Symbol versioning for libjson-c.
* All exported symbols must be listed here.
*
* See
* https://software.intel.com/sites/default/files/m/a/1/e/dsohowto.pdf
*/
/*
* Symbols in JSONC_PRIVATE are exported for historical
* reasons, but should not be used outside of json-c.
*/
JSONC_PRIVATE {
array_list_add;
array_list_del_idx;
array_list_free;
array_list_new;
array_list_put_idx;
array_list_sort;
json_hex_chars;
json_parse_double;
json_parse_int64;
json_parse_uint64;
lh_table_delete;
lh_table_delete_entry;
lh_table_free;
lh_table_insert;
lh_table_insert_w_hash;
lh_table_new;
lh_table_resize;
mc_debug;
mc_error;
mc_get_debug;
mc_info;
mc_set_debug;
mc_set_syslog;
printbuf_free;
printbuf_memappend;
printbuf_memset;
printbuf_new;
printbuf_reset;
sprintbuf;
# Used by tests:
_json_c_strerror;
};
JSONC_0.14 {
global:
array_list_bsearch;
array_list_get_idx;
array_list_length;
json_c_get_random_seed;
json_c_object_sizeof;
json_c_set_serialization_double_format;
json_c_shallow_copy_default;
json_c_version;
json_c_version_num;
json_c_visit;
json_global_set_string_hash;
json_number_chars;
json_object_array_add;
json_object_array_bsearch;
json_object_array_del_idx;
json_object_array_get_idx;
json_object_array_length;
json_object_array_put_idx;
json_object_array_sort;
json_object_deep_copy;
json_object_double_to_json_string;
json_object_equal;
json_object_free_userdata;
json_object_from_fd;
json_object_from_fd_ex;
json_object_from_file;
json_object_get;
json_object_get_array;
json_object_get_boolean;
json_object_get_double;
json_object_get_int64;
json_object_get_int;
json_object_get_object;
json_object_get_string;
json_object_get_string_len;
json_object_get_type;
json_object_get_uint64;
json_object_get_userdata;
json_object_int_inc;
json_object_is_type;
json_object_iter_begin;
json_object_iter_end;
json_object_iter_equal;
json_object_iter_init_default;
json_object_iter_next;
json_object_iter_peek_name;
json_object_iter_peek_value;
json_object_new_array;
json_object_new_boolean;
json_object_new_double;
json_object_new_double_s;
json_object_new_int64;
json_object_new_int;
json_object_new_null;
json_object_new_object;
json_object_new_string;
json_object_new_string_len;
json_object_new_uint64;
json_object_object_add;
json_object_object_add_ex;
json_object_object_del;
json_object_object_get;
json_object_object_get_ex;
json_object_object_length;
json_object_put;
json_object_set_boolean;
json_object_set_double;
json_object_set_int64;
json_object_set_int;
json_object_set_serializer;
json_object_set_string;
json_object_set_string_len;
json_object_set_uint64;
json_object_set_userdata;
json_object_to_fd;
json_object_to_file;
json_object_to_file_ext;
json_object_to_json_string;
json_object_to_json_string_ext;
json_object_to_json_string_length;
json_object_userdata_to_json_string;
json_pointer_get;
json_pointer_getf;
json_pointer_set;
json_pointer_setf;
json_tokener_error_desc;
json_tokener_free;
json_tokener_get_error;
json_tokener_get_parse_end;
json_tokener_new;
json_tokener_new_ex;
json_tokener_parse;
json_tokener_parse_ex;
json_tokener_parse_verbose;
json_tokener_reset;
json_tokener_set_flags;
json_type_to_name;
json_util_get_last_err;
lh_char_equal;
lh_kchar_table_new;
lh_kptr_table_new;
lh_ptr_equal;
lh_table_length;
lh_table_lookup_entry;
lh_table_lookup_entry_w_hash;
lh_table_lookup_ex;
local:
*;
};
JSONC_0.15 {
global:
array_list_new2;
array_list_shrink;
json_object_array_shrink;
json_object_new_array_ext;
} JSONC_0.14;
JSONC_0.16 {
# No new symbols in 0.16
} JSONC_0.15;
JSONC_0.17 {
global:
json_object_array_insert_idx;
json_patch_apply;
# array_list_insert_idx is intentionally not exported
} JSONC_0.16;
JSONC_0.18 {
# global:
} JSONC_0.17;

View File

@@ -21,15 +21,16 @@
extern "C" { extern "C" {
#endif #endif
#include "debug.h"
#include "linkhash.h"
#include "arraylist.h" #include "arraylist.h"
#include "json_util.h" #include "debug.h"
#include "json_object.h"
#include "json_pointer.h"
#include "json_tokener.h"
#include "json_object_iterator.h"
#include "json_c_version.h" #include "json_c_version.h"
#include "json_object.h"
#include "json_object_iterator.h"
@JSON_H_JSON_PATCH@
@JSON_H_JSON_POINTER@
#include "json_tokener.h"
#include "json_util.h"
#include "linkhash.h"
#ifdef __cplusplus #ifdef __cplusplus
} }

View File

@@ -17,4 +17,3 @@ int json_c_version_num(void)
{ {
return JSON_C_VERSION_NUM; return JSON_C_VERSION_NUM;
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2012 Eric Haszlakiewicz * Copyright (c) 2012,2017 Eric Haszlakiewicz
* *
* This library is free software; you can redistribute it and/or modify * This library is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See COPYING for details. * it under the terms of the MIT license. See COPYING for details.
@@ -12,19 +12,30 @@
#ifndef _json_c_version_h_ #ifndef _json_c_version_h_
#define _json_c_version_h_ #define _json_c_version_h_
#ifdef __cplusplus
extern "C" {
#endif
#define JSON_C_MAJOR_VERSION 0 #define JSON_C_MAJOR_VERSION 0
#define JSON_C_MINOR_VERSION 12 #define JSON_C_MINOR_VERSION 17
#define JSON_C_MICRO_VERSION 99 #define JSON_C_MICRO_VERSION 99
#define JSON_C_VERSION_NUM ((JSON_C_MAJOR_VERSION << 16) | \ #define JSON_C_VERSION_NUM \
(JSON_C_MINOR_VERSION << 8) | \ ((JSON_C_MAJOR_VERSION << 16) | (JSON_C_MINOR_VERSION << 8) | JSON_C_MICRO_VERSION)
JSON_C_MICRO_VERSION) #define JSON_C_VERSION "0.17.99"
#define JSON_C_VERSION "0.12.99"
#ifndef JSON_EXPORT
#if defined(_MSC_VER) && defined(JSON_C_DLL)
#define JSON_EXPORT __declspec(dllexport)
#else
#define JSON_EXPORT extern
#endif
#endif
/** /**
* @see JSON_C_VERSION * @see JSON_C_VERSION
* @return the version of the json-c library as a string * @return the version of the json-c library as a string
*/ */
const char *json_c_version(void); /* Returns JSON_C_VERSION */ JSON_EXPORT const char *json_c_version(void); /* Returns JSON_C_VERSION */
/** /**
* The json-c version encoded into an int, with the low order 8 bits * The json-c version encoded into an int, with the low order 8 bits
@@ -35,6 +46,10 @@ const char *json_c_version(void); /* Returns JSON_C_VERSION */
* @see JSON_C_VERSION_NUM * @see JSON_C_VERSION_NUM
* @return the version of the json-c library as an int * @return the version of the json-c library as an int
*/ */
int json_c_version_num(void); /* Returns JSON_C_VERSION_NUM */ JSON_EXPORT int json_c_version_num(void); /* Returns JSON_C_VERSION_NUM */
#ifdef __cplusplus
}
#endif
#endif #endif

View File

@@ -13,11 +13,25 @@
#include <inttypes.h> #include <inttypes.h>
#else #else
#ifdef JSON_C_HAVE_STDINT_H
#include <stdint.h> #include <stdint.h>
#else
/* Really only valid for old MS compilers, VS2008 and earlier: */
typedef __int32 int32_t;
typedef unsigned __int32 uint32_t;
typedef __int64 int64_t;
typedef unsigned __int64 uint64_t;
#endif
#define PRId64 "I64d" #define PRId64 "I64d"
#define SCNd64 "I64d" #define SCNd64 "I64d"
#define PRIu64 "I64u"
#endif #endif
#if defined(_MSC_VER)
#include <BaseTsd.h>
typedef SSIZE_T ssize_t;
#endif
#endif #endif

File diff suppressed because it is too large Load Diff

View File

@@ -18,24 +18,16 @@
#define _json_object_h_ #define _json_object_h_
#ifdef __GNUC__ #ifdef __GNUC__
#define THIS_FUNCTION_IS_DEPRECATED(func) func __attribute__ ((deprecated)) #define JSON_C_CONST_FUNCTION(func) func __attribute__((const))
#elif defined(_MSC_VER)
#define THIS_FUNCTION_IS_DEPRECATED(func) __declspec(deprecated) func
#elif defined(__clang__)
#define THIS_FUNCTION_IS_DEPRECATED(func) func __deprecated
#else #else
#define THIS_FUNCTION_IS_DEPRECATED(func) func #define JSON_C_CONST_FUNCTION(func) func
#endif #endif
#if defined(_MSC_VER) #include "json_inttypes.h"
#define JSON_EXPORT __declspec(dllexport) #include "json_types.h"
#else #include "printbuf.h"
#define JSON_EXPORT extern
#endif
#include <stddef.h> #include <stddef.h>
#include "json_inttypes.h"
#include "printbuf.h"
#ifdef __cplusplus #ifdef __cplusplus
extern "C" { extern "C" {
@@ -48,22 +40,22 @@ extern "C" {
* json_object_to_file_ext() functions which causes the output * json_object_to_file_ext() functions which causes the output
* to have no extra whitespace or formatting applied. * to have no extra whitespace or formatting applied.
*/ */
#define JSON_C_TO_STRING_PLAIN 0 #define JSON_C_TO_STRING_PLAIN 0
/** /**
* A flag for the json_object_to_json_string_ext() and * A flag for the json_object_to_json_string_ext() and
* json_object_to_file_ext() functions which causes the output to have * json_object_to_file_ext() functions which causes the output to have
* minimal whitespace inserted to make things slightly more readable. * minimal whitespace inserted to make things slightly more readable.
*/ */
#define JSON_C_TO_STRING_SPACED (1<<0) #define JSON_C_TO_STRING_SPACED (1 << 0)
/** /**
* A flag for the json_object_to_json_string_ext() and * A flag for the json_object_to_json_string_ext() and
* json_object_to_file_ext() functions which causes * json_object_to_file_ext() functions which causes
* the output to be formatted. * the output to be formatted.
* *
* See the "Two Space Tab" option at http://jsonformatter.curiousconcept.com/ * See the "Two Space Tab" option at https://jsonformatter.curiousconcept.com/
* for an example of the format. * for an example of the format.
*/ */
#define JSON_C_TO_STRING_PRETTY (1<<1) #define JSON_C_TO_STRING_PRETTY (1 << 1)
/** /**
* A flag for the json_object_to_json_string_ext() and * A flag for the json_object_to_json_string_ext() and
* json_object_to_file_ext() functions which causes * json_object_to_file_ext() functions which causes
@@ -71,28 +63,37 @@ extern "C" {
* *
* Instead of a "Two Space Tab" this gives a single tab character. * Instead of a "Two Space Tab" this gives a single tab character.
*/ */
#define JSON_C_TO_STRING_PRETTY_TAB (1<<3) #define JSON_C_TO_STRING_PRETTY_TAB (1 << 3)
/** /**
* A flag to drop trailing zero for float values * A flag to drop trailing zero for float values
*/ */
#define JSON_C_TO_STRING_NOZERO (1<<2) #define JSON_C_TO_STRING_NOZERO (1 << 2)
/** /**
* Don't escape forward slashes. * Don't escape forward slashes.
*/ */
#define JSON_C_TO_STRING_NOSLASHESCAPE (1<<4) #define JSON_C_TO_STRING_NOSLASHESCAPE (1 << 4)
/**
* A flag for the json_object_to_json_string_ext() and
* json_object_to_file_ext() functions which causes
* the output to be formatted.
*
* Use color for printing json.
*/
#define JSON_C_TO_STRING_COLOR (1 << 5)
/** /**
* A flag for the json_object_object_add_ex function which * A flag for the json_object_object_add_ex function which
* causes the value to be added without a check if it already exists. * causes the value to be added without a check if it already exists.
* Note: it is the responsibilty of the caller to ensure that no * Note: it is the responsibility of the caller to ensure that no
* key is added multiple times. If this is done, results are * key is added multiple times. If this is done, results are
* unpredictable. While this option is somewhat dangerous, it * unpredictable. While this option is somewhat dangerous, it
* permits potentially large performance savings in code that * permits potentially large performance savings in code that
* knows for sure the key values are unique (e.g. because the * knows for sure the key values are unique (e.g. because the
* code adds a well-known set of constant key values). * code adds a well-known set of constant key values).
*/ */
#define JSON_C_OBJECT_ADD_KEY_IS_NEW (1<<1) #define JSON_C_OBJECT_ADD_KEY_IS_NEW (1 << 1)
/** /**
* A flag for the json_object_object_add_ex function which * A flag for the json_object_object_add_ex function which
* flags the key as being constant memory. This means that * flags the key as being constant memory. This means that
@@ -108,15 +109,17 @@ extern "C" {
* key is given as a real constant value in the function * key is given as a real constant value in the function
* call, e.g. as in * call, e.g. as in
* json_object_object_add_ex(obj, "ip", json, * json_object_object_add_ex(obj, "ip", json,
* JSON_C_OBJECT_KEY_IS_CONSTANT); * JSON_C_OBJECT_ADD_CONSTANT_KEY);
*/ */
#define JSON_C_OBJECT_KEY_IS_CONSTANT (1<<2) #define JSON_C_OBJECT_ADD_CONSTANT_KEY (1 << 2)
/**
#undef FALSE * This flag is an alias to JSON_C_OBJECT_ADD_CONSTANT_KEY.
#define FALSE ((json_bool)0) * Historically, this flag was used first and the new name
* JSON_C_OBJECT_ADD_CONSTANT_KEY was introduced for version
#undef TRUE * 0.16.00 in order to have regular naming.
#define TRUE ((json_bool)1) * Use of this flag is now legacy.
*/
#define JSON_C_OBJECT_KEY_IS_CONSTANT JSON_C_OBJECT_ADD_CONSTANT_KEY
/** /**
* Set the global value of an option, which will apply to all * Set the global value of an option, which will apply to all
@@ -134,68 +137,46 @@ extern "C" {
*/ */
#define JSON_C_OPTION_THREAD (1) #define JSON_C_OPTION_THREAD (1)
/**
* A structure to use with json_object_object_foreachC() loops.
* Contains key, val and entry members.
*/
struct json_object_iter
{
char *key;
struct json_object *val;
struct lh_entry *entry;
};
typedef struct json_object_iter json_object_iter;
typedef int json_bool;
/**
* @brief The core type for all type of JSON objects handled by json-c
*/
typedef struct json_object json_object;
/**
* Type of custom user delete functions. See json_object_set_serializer.
*/
typedef void (json_object_delete_fn)(struct json_object *jso, void *userdata);
/**
* Type of a custom serialization function. See json_object_set_serializer.
*/
typedef int (json_object_to_json_string_fn)(struct json_object *jso,
struct printbuf *pb,
int level,
int flags);
/* supported object types */
typedef enum json_type {
/* If you change this, be sure to update json_type_to_name() too */
json_type_null,
json_type_boolean,
json_type_double,
json_type_int,
json_type_object,
json_type_array,
json_type_string
} json_type;
/* reference counting functions */ /* reference counting functions */
/** /**
* Increment the reference count of json_object, thereby grabbing shared * Increment the reference count of json_object, thereby taking ownership of it.
* ownership of obj. *
* Cases where you might need to increase the refcount include:
* - Using an object field or array index (retrieved through
* `json_object_object_get()` or `json_object_array_get_idx()`)
* beyond the lifetime of the parent object.
* - Detaching an object field or array index from its parent object
* (using `json_object_object_del()` or `json_object_array_del_idx()`)
* - Sharing a json_object with multiple (not necessarily parallel) threads
* of execution that all expect to free it (with `json_object_put()`) when
* they're done.
* *
* @param obj the json_object instance * @param obj the json_object instance
* @see json_object_put()
* @see json_object_object_get()
* @see json_object_array_get_idx()
*/ */
JSON_EXPORT struct json_object* json_object_get(struct json_object *obj); JSON_EXPORT struct json_object *json_object_get(struct json_object *obj);
/** /**
* Decrement the reference count of json_object and free if it reaches zero. * Decrement the reference count of json_object and free if it reaches zero.
*
* You must have ownership of obj prior to doing this or you will cause an * You must have ownership of obj prior to doing this or you will cause an
* imbalance in the reference count. * imbalance in the reference count, leading to a classic use-after-free bug.
* In particular, you normally do not need to call `json_object_put()` on the
* json_object returned by `json_object_object_get()` or `json_object_array_get_idx()`.
*
* Just like after calling `free()` on a block of memory, you must not use
* `obj` after calling `json_object_put()` on it or any object that it
* is a member of (unless you know you've called `json_object_get(obj)` to
* explicitly increment the refcount).
*
* NULL may be passed, in which case this is a no-op.
* *
* @param obj the json_object instance * @param obj the json_object instance
* @returns 1 if the object was freed. * @returns 1 if the object was freed, 0 if only the refcount was decremented
* @see json_object_get()
*/ */
JSON_EXPORT int json_object_put(struct json_object *obj); JSON_EXPORT int json_object_put(struct json_object *obj);
@@ -210,6 +191,7 @@ JSON_EXPORT int json_object_put(struct json_object *obj);
json_type_object, json_type_object,
json_type_array, json_type_array,
json_type_string json_type_string
* @returns 1 if the object is of the specified type, 0 otherwise
*/ */
JSON_EXPORT int json_object_is_type(const struct json_object *obj, enum json_type type); JSON_EXPORT int json_object_is_type(const struct json_object *obj, enum json_type type);
@@ -229,7 +211,6 @@ JSON_EXPORT int json_object_is_type(const struct json_object *obj, enum json_typ
*/ */
JSON_EXPORT enum json_type json_object_get_type(const struct json_object *obj); JSON_EXPORT enum json_type json_object_get_type(const struct json_object *obj);
/** Stringify object to json format. /** Stringify object to json format.
* Equivalent to json_object_to_json_string_ext(obj, JSON_C_TO_STRING_SPACED) * Equivalent to json_object_to_json_string_ext(obj, JSON_C_TO_STRING_SPACED)
* The pointer you get is an internal of your json object. You don't * The pointer you get is an internal of your json object. You don't
@@ -239,7 +220,7 @@ JSON_EXPORT enum json_type json_object_get_type(const struct json_object *obj);
* @param obj the json_object instance * @param obj the json_object instance
* @returns a string in JSON format * @returns a string in JSON format
*/ */
JSON_EXPORT const char* json_object_to_json_string(struct json_object *obj); JSON_EXPORT const char *json_object_to_json_string(struct json_object *obj);
/** Stringify object to json format /** Stringify object to json format
* @see json_object_to_json_string() for details on how to free string. * @see json_object_to_json_string() for details on how to free string.
@@ -247,8 +228,7 @@ JSON_EXPORT const char* json_object_to_json_string(struct json_object *obj);
* @param flags formatting options, see JSON_C_TO_STRING_PRETTY and other constants * @param flags formatting options, see JSON_C_TO_STRING_PRETTY and other constants
* @returns a string in JSON format * @returns a string in JSON format
*/ */
JSON_EXPORT const char* json_object_to_json_string_ext(struct json_object *obj, int JSON_EXPORT const char *json_object_to_json_string_ext(struct json_object *obj, int flags);
flags);
/** Stringify object to json format /** Stringify object to json format
* @see json_object_to_json_string() for details on how to free string. * @see json_object_to_json_string() for details on how to free string.
@@ -257,8 +237,8 @@ flags);
* @param length a pointer where, if not NULL, the length (without null) is stored * @param length a pointer where, if not NULL, the length (without null) is stored
* @returns a string in JSON format and the length if not NULL * @returns a string in JSON format and the length if not NULL
*/ */
JSON_EXPORT const char* json_object_to_json_string_length(struct json_object *obj, int JSON_EXPORT const char *json_object_to_json_string_length(struct json_object *obj, int flags,
flags, size_t *length); size_t *length);
/** /**
* Returns the userdata set by json_object_set_userdata() or * Returns the userdata set by json_object_set_userdata() or
@@ -266,7 +246,7 @@ flags, size_t *length);
* *
* @param jso the object to return the userdata for * @param jso the object to return the userdata for
*/ */
JSON_EXPORT void* json_object_get_userdata(json_object *jso); JSON_EXPORT void *json_object_get_userdata(json_object *jso);
/** /**
* Set an opaque userdata value for an object * Set an opaque userdata value for an object
@@ -294,7 +274,7 @@ JSON_EXPORT void* json_object_get_userdata(json_object *jso);
* @param user_delete an optional function from freeing userdata * @param user_delete an optional function from freeing userdata
*/ */
JSON_EXPORT void json_object_set_userdata(json_object *jso, void *userdata, JSON_EXPORT void json_object_set_userdata(json_object *jso, void *userdata,
json_object_delete_fn *user_delete); json_object_delete_fn *user_delete);
/** /**
* Set a custom serialization function to be used when this particular object * Set a custom serialization function to be used when this particular object
@@ -327,9 +307,8 @@ JSON_EXPORT void json_object_set_userdata(json_object *jso, void *userdata,
* @param user_delete an optional function from freeing userdata * @param user_delete an optional function from freeing userdata
*/ */
JSON_EXPORT void json_object_set_serializer(json_object *jso, JSON_EXPORT void json_object_set_serializer(json_object *jso,
json_object_to_json_string_fn *to_string_func, json_object_to_json_string_fn *to_string_func,
void *userdata, void *userdata, json_object_delete_fn *user_delete);
json_object_delete_fn *user_delete);
#ifdef __clang__ #ifdef __clang__
/* /*
@@ -348,7 +327,7 @@ JSON_EXPORT void json_object_set_serializer(json_object *jso,
* @param jso unused * @param jso unused
* @param userdata the pointer that is passed to free(). * @param userdata the pointer that is passed to free().
*/ */
json_object_delete_fn json_object_free_userdata; JSON_EXPORT json_object_delete_fn json_object_free_userdata;
/** /**
* Copy the jso->_userdata string over to pb as-is. * Copy the jso->_userdata string over to pb as-is.
@@ -359,14 +338,13 @@ json_object_delete_fn json_object_free_userdata;
* @param level Ignored. * @param level Ignored.
* @param flags Ignored. * @param flags Ignored.
*/ */
json_object_to_json_string_fn json_object_userdata_to_json_string; JSON_EXPORT json_object_to_json_string_fn json_object_userdata_to_json_string;
#ifdef __clang__ #ifdef __clang__
/* } */ /* } */
#pragma clang diagnostic pop #pragma clang diagnostic pop
#endif #endif
/* object type methods */ /* object type methods */
/** Create a new empty object with a reference count of 1. The caller of /** Create a new empty object with a reference count of 1. The caller of
@@ -379,30 +357,41 @@ json_object_to_json_string_fn json_object_userdata_to_json_string;
* *
* @returns a json_object of type json_type_object * @returns a json_object of type json_type_object
*/ */
JSON_EXPORT struct json_object* json_object_new_object(void); JSON_EXPORT struct json_object *json_object_new_object(void);
/** Get the hashtable of a json_object of type json_type_object /** Get the hashtable of a json_object of type json_type_object
* @param obj the json_object instance * @param obj the json_object instance
* @returns a linkhash * @returns a linkhash
*/ */
JSON_EXPORT struct lh_table* json_object_get_object(const struct json_object *obj); JSON_EXPORT struct lh_table *json_object_get_object(const struct json_object *obj);
/** Get the size of an object in terms of the number of fields it has. /** Get the size of an object in terms of the number of fields it has.
* @param obj the json_object whose length to return * @param obj the json_object whose length to return
*/ */
JSON_EXPORT int json_object_object_length(const struct json_object* obj); JSON_EXPORT int json_object_object_length(const struct json_object *obj);
/** Get the sizeof (struct json_object).
* @returns a size_t with the sizeof (struct json_object)
*/
JSON_C_CONST_FUNCTION(JSON_EXPORT size_t json_c_object_sizeof(void));
/** Add an object field to a json_object of type json_type_object /** Add an object field to a json_object of type json_type_object
* *
* The reference count will *not* be incremented. This is to make adding * The reference count of `val` will *not* be incremented, in effect
* fields to objects in code more compact. If you want to retain a reference * transferring ownership that object to `obj`, and thus `val` will be
* to an added object, independent of the lifetime of obj, you must wrap the * freed when `obj` is. (i.e. through `json_object_put(obj)`)
* passed object with json_object_get.
* *
* Upon calling this, the ownership of val transfers to obj. Thus you must * If you want to retain a reference to the added object, independent
* make sure that you do in fact have ownership over this object. For instance, * of the lifetime of obj, you must increment the refcount with
* json_object_new_object will give you ownership until you transfer it, * `json_object_get(val)` (and later release it with json_object_put()).
* whereas json_object_object_get does not. *
* Since ownership transfers to `obj`, you must make sure
* that you do in fact have ownership over `val`. For instance,
* json_object_new_object() will give you ownership until you transfer it,
* whereas json_object_object_get() does not.
*
* Any previous object stored under `key` in `obj` will have its refcount
* decremented, and be freed normally if that drops to zero.
* *
* @param obj the json_object instance * @param obj the json_object instance
* @param key the object field name (a private copy will be duplicated) * @param key the object field name (a private copy will be duplicated)
@@ -411,8 +400,8 @@ JSON_EXPORT int json_object_object_length(const struct json_object* obj);
* @return On success, <code>0</code> is returned. * @return On success, <code>0</code> is returned.
* On error, a negative value is returned. * On error, a negative value is returned.
*/ */
JSON_EXPORT int json_object_object_add(struct json_object* obj, const char *key, JSON_EXPORT int json_object_object_add(struct json_object *obj, const char *key,
struct json_object *val); struct json_object *val);
/** Add an object field to a json_object of type json_type_object /** Add an object field to a json_object of type json_type_object
* *
@@ -424,20 +413,18 @@ JSON_EXPORT int json_object_object_add(struct json_object* obj, const char *key,
* @param obj the json_object instance * @param obj the json_object instance
* @param key the object field name (a private copy will be duplicated) * @param key the object field name (a private copy will be duplicated)
* @param val a json_object or NULL member to associate with the given field * @param val a json_object or NULL member to associate with the given field
* @param opts process-modifying options. To specify multiple options, use * @param opts process-modifying options. To specify multiple options, use
* arithmetic or (OPT1|OPT2) * (OPT1|OPT2)
*/ */
JSON_EXPORT int json_object_object_add_ex(struct json_object* obj, JSON_EXPORT int json_object_object_add_ex(struct json_object *obj, const char *const key,
const char *const key, struct json_object *const val, const unsigned opts);
struct json_object *const val,
const unsigned opts);
/** Get the json_object associate with a given object field. /** Get the json_object associate with a given object field.
* Deprecated/discouraged: used json_object_object_get_ex instead. * Deprecated/discouraged: used json_object_object_get_ex instead.
* *
* This returns NULL if the field is found but its value is null, or if * This returns NULL if the field is found but its value is null, or if
* the field is not found, or if obj is not a json_type_object. If you * the field is not found, or if obj is not a json_type_object. If you
* need to distinguis between these cases, use json_object_object_get_ex(). * need to distinguish between these cases, use json_object_object_get_ex().
* *
* *No* reference counts will be changed. There is no need to manually adjust * *No* reference counts will be changed. There is no need to manually adjust
* reference counts through the json_object_put/json_object_get methods unless * reference counts through the json_object_put/json_object_get methods unless
@@ -453,8 +440,8 @@ JSON_EXPORT int json_object_object_add_ex(struct json_object* obj,
* @param key the object field name * @param key the object field name
* @returns the json_object associated with the given field name * @returns the json_object associated with the given field name
*/ */
JSON_EXPORT struct json_object* json_object_object_get(const struct json_object* obj, JSON_EXPORT struct json_object *json_object_object_get(const struct json_object *obj,
const char *key); const char *key);
/** Get the json_object associated with a given object field. /** Get the json_object associated with a given object field.
* *
@@ -472,11 +459,10 @@ JSON_EXPORT struct json_object* json_object_object_get(const struct json_object*
* associated with the given field name. * associated with the given field name.
* *
* It is safe to pass a NULL value. * It is safe to pass a NULL value.
* @returns whether or not the key exists * @returns 1 if the key exists, 0 otherwise
*/ */
JSON_EXPORT json_bool json_object_object_get_ex(const struct json_object* obj, JSON_EXPORT int json_object_object_get_ex(const struct json_object *obj, const char *key,
const char *key, struct json_object **value);
struct json_object **value);
/** Delete the given json_object field /** Delete the given json_object field
* *
@@ -487,7 +473,7 @@ JSON_EXPORT json_bool json_object_object_get_ex(const struct json_object* obj,
* @param obj the json_object instance * @param obj the json_object instance
* @param key the object field name * @param key the object field name
*/ */
JSON_EXPORT void json_object_object_del(struct json_object* obj, const char *key); JSON_EXPORT void json_object_object_del(struct json_object *obj, const char *key);
/** /**
* Iterate through all keys and values of an object. * Iterate through all keys and values of an object.
@@ -502,61 +488,80 @@ JSON_EXPORT void json_object_object_del(struct json_object* obj, const char *key
* @param val the local name for the json_object* object variable defined in * @param val the local name for the json_object* object variable defined in
* the body * the body
*/ */
#if defined(__GNUC__) && !defined(__STRICT_ANSI__) && __STDC_VERSION__ >= 199901L #if defined(__GNUC__) && !defined(__STRICT_ANSI__) && (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L)
# define json_object_object_foreach(obj,key,val) \ #define json_object_object_foreach(obj, key, val) \
char *key = NULL; \ char *key = NULL; \
struct json_object *val __attribute__((__unused__)) = NULL; \ struct json_object *val __attribute__((__unused__)) = NULL; \
for(struct lh_entry *entry ## key = json_object_get_object(obj)->head, *entry_next ## key = NULL; \ for (struct lh_entry *entry##key = lh_table_head(json_object_get_object(obj)), \
({ if(entry ## key) { \ *entry_next##key = NULL; \
key = (char*)lh_entry_k(entry ## key); \ ({ \
val = (struct json_object*)lh_entry_v(entry ## key); \ if (entry##key) \
entry_next ## key = entry ## key->next; \ { \
} ; entry ## key; }); \ key = (char *)lh_entry_k(entry##key); \
entry ## key = entry_next ## key ) val = (struct json_object *)lh_entry_v(entry##key); \
entry_next##key = lh_entry_next(entry##key); \
}; \
entry##key; \
}); \
entry##key = entry_next##key)
#else /* ANSI C or MSC */ #else /* ANSI C or MSC */
# define json_object_object_foreach(obj,key,val) \ #define json_object_object_foreach(obj, key, val) \
char *key;\ char *key = NULL; \
struct json_object *val; \ struct json_object *val = NULL; \
struct lh_entry *entry ## key; \ struct lh_entry *entry##key; \
struct lh_entry *entry_next ## key = NULL; \ struct lh_entry *entry_next##key = NULL; \
for(entry ## key = json_object_get_object(obj)->head; \ for (entry##key = lh_table_head(json_object_get_object(obj)); \
(entry ## key ? ( \ (entry##key ? (key = (char *)lh_entry_k(entry##key), \
key = (char*)lh_entry_k(entry ## key), \ val = (struct json_object *)lh_entry_v(entry##key), \
val = (struct json_object*)lh_entry_v(entry ## key), \ entry_next##key = lh_entry_next(entry##key), entry##key) \
entry_next ## key = entry ## key->next, \ : 0); \
entry ## key) : 0); \ entry##key = entry_next##key)
entry ## key = entry_next ## key)
#endif /* defined(__GNUC__) && !defined(__STRICT_ANSI__) && __STDC_VERSION__ >= 199901L */ #endif /* defined(__GNUC__) && !defined(__STRICT_ANSI__) && (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) */
/** Iterate through all keys and values of an object (ANSI C Safe) /** Iterate through all keys and values of an object (ANSI C Safe)
* @param obj the json_object instance * @param obj the json_object instance
* @param iter the object iterator, use type json_object_iter * @param iter the object iterator, use type json_object_iter
*/ */
#define json_object_object_foreachC(obj,iter) \ #define json_object_object_foreachC(obj, iter) \
for(iter.entry = json_object_get_object(obj)->head; \ for (iter.entry = lh_table_head(json_object_get_object(obj)); \
(iter.entry ? (iter.key = (char*)lh_entry_k(iter.entry), iter.val = (struct json_object*)lh_entry_v(iter.entry), iter.entry) : 0); \ (iter.entry ? (iter.key = (char *)lh_entry_k(iter.entry), \
iter.entry = iter.entry->next) iter.val = (struct json_object *)lh_entry_v(iter.entry), iter.entry) \
: 0); \
iter.entry = lh_entry_next(iter.entry))
/* Array type methods */ /* Array type methods */
/** Create a new empty json_object of type json_type_array /** Create a new empty json_object of type json_type_array
* with 32 slots allocated.
* If you know the array size you'll need ahead of time, use
* json_object_new_array_ext() instead.
* @see json_object_new_array_ext()
* @see json_object_array_shrink()
* @returns a json_object of type json_type_array * @returns a json_object of type json_type_array
*/ */
JSON_EXPORT struct json_object* json_object_new_array(void); JSON_EXPORT struct json_object *json_object_new_array(void);
/** Create a new empty json_object of type json_type_array
* with the desired number of slots allocated.
* @see json_object_array_shrink()
* @param initial_size the number of slots to allocate
* @returns a json_object of type json_type_array
*/
JSON_EXPORT struct json_object *json_object_new_array_ext(int initial_size);
/** Get the arraylist of a json_object of type json_type_array /** Get the arraylist of a json_object of type json_type_array
* @param obj the json_object instance * @param obj the json_object instance
* @returns an arraylist * @returns an arraylist
*/ */
JSON_EXPORT struct array_list* json_object_get_array(const struct json_object *obj); JSON_EXPORT struct array_list *json_object_get_array(const struct json_object *obj);
/** Get the length of a json_object of type json_type_array /** Get the length of a json_object of type json_type_array
* @param obj the json_object instance * @param obj the json_object instance
* @returns an int * @returns the length of the array
*/ */
JSON_EXPORT size_t json_object_array_length(const struct json_object *obj); JSON_EXPORT size_t json_object_array_length(const struct json_object *obj);
@@ -568,7 +573,8 @@ JSON_EXPORT size_t json_object_array_length(const struct json_object *obj);
* @param jso the json_object instance * @param jso the json_object instance
* @param sort_fn a sorting function * @param sort_fn a sorting function
*/ */
JSON_EXPORT void json_object_array_sort(struct json_object *jso, int(*sort_fn)(const void *, const void *)); JSON_EXPORT void json_object_array_sort(struct json_object *jso,
int (*sort_fn)(const void *, const void *));
/** Binary search a sorted array for a specified key object. /** Binary search a sorted array for a specified key object.
* *
@@ -584,10 +590,9 @@ JSON_EXPORT void json_object_array_sort(struct json_object *jso, int(*sort_fn)(c
* *
* @return the wanted json_object instance * @return the wanted json_object instance
*/ */
JSON_EXPORT struct json_object* json_object_array_bsearch( JSON_EXPORT struct json_object *
const struct json_object *key, json_object_array_bsearch(const struct json_object *key, const struct json_object *jso,
const struct json_object *jso, int (*sort_fn)(const void *, const void *));
int (*sort_fn)(const void *, const void *));
/** Add an element to the end of a json_object of type json_type_array /** Add an element to the end of a json_object of type json_type_array
* *
@@ -598,8 +603,7 @@ JSON_EXPORT struct json_object* json_object_array_bsearch(
* @param obj the json_object instance * @param obj the json_object instance
* @param val the json_object to be added * @param val the json_object to be added
*/ */
JSON_EXPORT int json_object_array_add(struct json_object *obj, JSON_EXPORT int json_object_array_add(struct json_object *obj, struct json_object *val);
struct json_object *val);
/** Insert or replace an element at a specified index in an array (a json_object of type json_type_array) /** Insert or replace an element at a specified index in an array (a json_object of type json_type_array)
* *
@@ -617,20 +621,47 @@ JSON_EXPORT int json_object_array_add(struct json_object *obj,
* @param val the json_object to be added * @param val the json_object to be added
*/ */
JSON_EXPORT int json_object_array_put_idx(struct json_object *obj, size_t idx, JSON_EXPORT int json_object_array_put_idx(struct json_object *obj, size_t idx,
struct json_object *val); struct json_object *val);
/** Get the element at specificed index of the array (a json_object of type json_type_array) /** Insert an element at a specified index in an array (a json_object of type json_type_array)
*
* The reference count will *not* be incremented. This is to make adding
* fields to objects in code more compact. If you want to retain a reference
* to an added object you must wrap the passed object with json_object_get
*
* The array size will be automatically be expanded to the size of the
* index if the index is larger than the current size.
* If the index is within the existing array limits, then the element will be
* inserted and all elements will be shifted. This is the only difference between
* this function and json_object_array_put_idx().
*
* @param obj the json_object instance
* @param idx the index to insert the element at
* @param val the json_object to be added
*/
JSON_EXPORT int json_object_array_insert_idx(struct json_object *obj, size_t idx,
struct json_object *val);
/** Get the element at specified index of array `obj` (which must be a json_object of type json_type_array)
*
* *No* reference counts will be changed, and ownership of the returned
* object remains with `obj`. See json_object_object_get() for additional
* implications of this behavior.
*
* Calling this with anything other than a json_type_array will trigger
* an assert.
*
* @param obj the json_object instance * @param obj the json_object instance
* @param idx the index to get the element at * @param idx the index to get the element at
* @returns the json_object at the specified index (or NULL) * @returns the json_object at the specified index (or NULL)
*/ */
JSON_EXPORT struct json_object* json_object_array_get_idx(const struct json_object *obj, JSON_EXPORT struct json_object *json_object_array_get_idx(const struct json_object *obj,
size_t idx); size_t idx);
/** Delete an elements from a specified index in an array (a json_object of type json_type_array) /** Delete an elements from a specified index in an array (a json_object of type json_type_array)
* *
* The reference count will be decremented for each of the deleted objects. If there * The reference count will be decremented for each of the deleted objects. If there
* are no more owners of an element that is being deleted, then the value is * are no more owners of an element that is being deleted, then the value is
* freed. Otherwise, the reference to the value will remain in memory. * freed. Otherwise, the reference to the value will remain in memory.
* *
* @param obj the json_object instance * @param obj the json_object instance
@@ -640,40 +671,48 @@ JSON_EXPORT struct json_object* json_object_array_get_idx(const struct json_obje
*/ */
JSON_EXPORT int json_object_array_del_idx(struct json_object *obj, size_t idx, size_t count); JSON_EXPORT int json_object_array_del_idx(struct json_object *obj, size_t idx, size_t count);
/**
* Shrink the internal memory allocation of the array to just
* enough to fit the number of elements in it, plus empty_slots.
*
* @param jso the json_object instance, must be json_type_array
* @param empty_slots the number of empty slots to leave allocated
*/
JSON_EXPORT int json_object_array_shrink(struct json_object *jso, int empty_slots);
/* json_bool type methods */ /* json_bool type methods */
/** Create a new empty json_object of type json_type_boolean /** Create a new empty json_object of type json_type_boolean
* @param b a json_bool TRUE or FALSE (1 or 0) * @param b a json_bool 1 or 0
* @returns a json_object of type json_type_boolean * @returns a json_object of type json_type_boolean
*/ */
JSON_EXPORT struct json_object* json_object_new_boolean(json_bool b); JSON_EXPORT struct json_object *json_object_new_boolean(json_bool b);
/** Get the json_bool value of a json_object /** Get the json_bool value of a json_object
* *
* The type is coerced to a json_bool if the passed object is not a json_bool. * The type is coerced to a json_bool if the passed object is not a json_bool.
* integer and double objects will return FALSE if there value is zero * integer and double objects will return 0 if there value is zero
* or TRUE otherwise. If the passed object is a string it will return * or 1 otherwise. If the passed object is a string it will return
* TRUE if it has a non zero length. If any other object type is passed * 1 if it has a non zero length.
* TRUE will be returned if the object is not NULL. * If any other object type is passed 0 will be returned, even non-empty
* json_type_array and json_type_object objects.
* *
* @param obj the json_object instance * @param obj the json_object instance
* @returns a json_bool * @returns a json_bool
*/ */
JSON_EXPORT json_bool json_object_get_boolean(const struct json_object *obj); JSON_EXPORT json_bool json_object_get_boolean(const struct json_object *obj);
/** Set the json_bool value of a json_object /** Set the json_bool value of a json_object
* *
* The type of obj is checked to be a json_type_boolean and 0 is returned * The type of obj is checked to be a json_type_boolean and 0 is returned
* if it is not without any further actions. If type of obj is json_type_boolean * if it is not without any further actions. If type of obj is json_type_boolean
* the obect value is chaned to new_value * the object value is changed to new_value
* *
* @param obj the json_object instance * @param obj the json_object instance
* @param new_value the value to be set * @param new_value the value to be set
* @returns 1 if value is set correctly, 0 otherwise * @returns 1 if value is set correctly, 0 otherwise
*/ */
JSON_EXPORT int json_object_set_boolean(struct json_object *obj,json_bool new_value); JSON_EXPORT int json_object_set_boolean(struct json_object *obj, json_bool new_value);
/* int type methods */ /* int type methods */
@@ -683,15 +722,19 @@ JSON_EXPORT int json_object_set_boolean(struct json_object *obj,json_bool new_va
* @param i the integer * @param i the integer
* @returns a json_object of type json_type_int * @returns a json_object of type json_type_int
*/ */
JSON_EXPORT struct json_object* json_object_new_int(int32_t i); JSON_EXPORT struct json_object *json_object_new_int(int32_t i);
/** Create a new empty json_object of type json_type_int /** Create a new empty json_object of type json_type_int
* @param i the integer * @param i the integer
* @returns a json_object of type json_type_int * @returns a json_object of type json_type_int
*/ */
JSON_EXPORT struct json_object* json_object_new_int64(int64_t i); JSON_EXPORT struct json_object *json_object_new_int64(int64_t i);
/** Create a new empty json_object of type json_type_uint
* @param i the integer
* @returns a json_object of type json_type_uint
*/
JSON_EXPORT struct json_object *json_object_new_uint64(uint64_t i);
/** Get the int value of a json_object /** Get the int value of a json_object
* *
@@ -710,16 +753,16 @@ JSON_EXPORT struct json_object* json_object_new_int64(int64_t i);
JSON_EXPORT int32_t json_object_get_int(const struct json_object *obj); JSON_EXPORT int32_t json_object_get_int(const struct json_object *obj);
/** Set the int value of a json_object /** Set the int value of a json_object
* *
* The type of obj is checked to be a json_type_int and 0 is returned * The type of obj is checked to be a json_type_int and 0 is returned
* if it is not without any further actions. If type of obj is json_type_int * if it is not without any further actions. If type of obj is json_type_int
* the obect value is changed to new_value * the object value is changed to new_value
* *
* @param obj the json_object instance * @param obj the json_object instance
* @param new_value the value to be set * @param new_value the value to be set
* @returns 1 if value is set correctly, 0 otherwise * @returns 1 if value is set correctly, 0 otherwise
*/ */
JSON_EXPORT int json_object_set_int(struct json_object *obj,int new_value); JSON_EXPORT int json_object_set_int(struct json_object *obj, int new_value);
/** Increment a json_type_int object by the given amount, which may be negative. /** Increment a json_type_int object by the given amount, which may be negative.
* *
@@ -733,11 +776,10 @@ JSON_EXPORT int json_object_set_int(struct json_object *obj,int new_value);
* *
* @param obj the json_object instance * @param obj the json_object instance
* @param val the value to add * @param val the value to add
* @returns 1 if the increment succeded, 0 otherwise * @returns 1 if the increment succeeded, 0 otherwise
*/ */
JSON_EXPORT int json_object_int_inc(struct json_object *obj, int64_t val); JSON_EXPORT int json_object_int_inc(struct json_object *obj, int64_t val);
/** Get the int value of a json_object /** Get the int value of a json_object
* *
* The type is coerced to a int64 if the passed object is not a int64. * The type is coerced to a int64 if the passed object is not a int64.
@@ -753,18 +795,44 @@ JSON_EXPORT int json_object_int_inc(struct json_object *obj, int64_t val);
*/ */
JSON_EXPORT int64_t json_object_get_int64(const struct json_object *obj); JSON_EXPORT int64_t json_object_get_int64(const struct json_object *obj);
/** Get the uint value of a json_object
*
* The type is coerced to a uint64 if the passed object is not a uint64.
* double objects will return their uint64 conversion. Strings will be
* parsed as an uint64. If no conversion exists then 0 is returned.
*
* NOTE: Set errno to 0 directly before a call to this function to determine
* whether or not conversion was successful (it does not clear the value for
* you).
*
* @param obj the json_object instance
* @returns an uint64
*/
JSON_EXPORT uint64_t json_object_get_uint64(const struct json_object *obj);
/** Set the int64_t value of a json_object /** Set the int64_t value of a json_object
* *
* The type of obj is checked to be a json_type_int and 0 is returned * The type of obj is checked to be a json_type_int and 0 is returned
* if it is not without any further actions. If type of obj is json_type_int * if it is not without any further actions. If type of obj is json_type_int
* the obect value is chaned to new_value * the object value is changed to new_value
* *
* @param obj the json_object instance * @param obj the json_object instance
* @param new_value the value to be set * @param new_value the value to be set
* @returns 1 if value is set correctly, 0 otherwise * @returns 1 if value is set correctly, 0 otherwise
*/ */
JSON_EXPORT int json_object_set_int64(struct json_object *obj,int64_t new_value); JSON_EXPORT int json_object_set_int64(struct json_object *obj, int64_t new_value);
/** Set the uint64_t value of a json_object
*
* The type of obj is checked to be a json_type_uint and 0 is returned
* if it is not without any further actions. If type of obj is json_type_uint
* the object value is changed to new_value
*
* @param obj the json_object instance
* @param new_value the value to be set
* @returns 1 if value is set correctly, 0 otherwise
*/
JSON_EXPORT int json_object_set_uint64(struct json_object *obj, uint64_t new_value);
/* double type methods */ /* double type methods */
@@ -775,7 +843,7 @@ JSON_EXPORT int json_object_set_int64(struct json_object *obj,int64_t new_value)
* @param d the double * @param d the double
* @returns a json_object of type json_type_double * @returns a json_object of type json_type_double
*/ */
JSON_EXPORT struct json_object* json_object_new_double(double d); JSON_EXPORT struct json_object *json_object_new_double(double d);
/** /**
* Create a new json_object of type json_type_double, using * Create a new json_object of type json_type_double, using
@@ -793,7 +861,8 @@ JSON_EXPORT struct json_object* json_object_new_double(double d);
* The userdata field is used to store the string representation, so it * The userdata field is used to store the string representation, so it
* can't be used for other data if this function is used. * can't be used for other data if this function is used.
* *
* An equivalent sequence of calls is: * A roughly equivalent sequence of calls, with the difference being that
* the serialization function won't be reset by json_object_set_double(), is:
* @code * @code
* jso = json_object_new_double(d); * jso = json_object_new_double(d);
* json_object_set_serializer(jso, json_object_userdata_to_json_string, * json_object_set_serializer(jso, json_object_userdata_to_json_string,
@@ -803,7 +872,7 @@ JSON_EXPORT struct json_object* json_object_new_double(double d);
* @param d the numeric value of the double. * @param d the numeric value of the double.
* @param ds the string representation of the double. This will be copied. * @param ds the string representation of the double. This will be copied.
*/ */
JSON_EXPORT struct json_object* json_object_new_double_s(double d, const char *ds); JSON_EXPORT struct json_object *json_object_new_double_s(double d, const char *ds);
/** /**
* Set a global or thread-local json-c option, depending on whether * Set a global or thread-local json-c option, depending on whether
@@ -817,9 +886,8 @@ JSON_EXPORT struct json_object* json_object_new_double_s(double d, const char *d
* *
* @return -1 on errors, 0 on success. * @return -1 on errors, 0 on success.
*/ */
int json_c_set_serialization_double_format(const char *double_format, int global_or_thread); JSON_EXPORT int json_c_set_serialization_double_format(const char *double_format,
int global_or_thread);
/** Serialize a json_object of type json_type_double to a string. /** Serialize a json_object of type json_type_double to a string.
* *
@@ -840,10 +908,8 @@ int json_c_set_serialization_double_format(const char *double_format, int global
* @param level Ignored. * @param level Ignored.
* @param flags Ignored. * @param flags Ignored.
*/ */
JSON_EXPORT int json_object_double_to_json_string(struct json_object* jso, JSON_EXPORT int json_object_double_to_json_string(struct json_object *jso, struct printbuf *pb,
struct printbuf *pb, int level, int flags);
int level,
int flags);
/** Get the double floating point value of a json_object /** Get the double floating point value of a json_object
* *
@@ -870,20 +936,20 @@ JSON_EXPORT int json_object_double_to_json_string(struct json_object* jso,
*/ */
JSON_EXPORT double json_object_get_double(const struct json_object *obj); JSON_EXPORT double json_object_get_double(const struct json_object *obj);
/** Set the double value of a json_object /** Set the double value of a json_object
* *
* The type of obj is checked to be a json_type_double and 0 is returned * The type of obj is checked to be a json_type_double and 0 is returned
* if it is not without any further actions. If type of obj is json_type_double * if it is not without any further actions. If type of obj is json_type_double
* the obect value is chaned to new_value * the object value is changed to new_value
*
* If the object was created with json_object_new_double_s(), the serialization
* function is reset to the default and the cached serialized value is cleared.
* *
* @param obj the json_object instance * @param obj the json_object instance
* @param new_value the value to be set * @param new_value the value to be set
* @returns 1 if value is set correctly, 0 otherwise * @returns 1 if value is set correctly, 0 otherwise
*/ */
JSON_EXPORT int json_object_set_double(struct json_object *obj,double new_value); JSON_EXPORT int json_object_set_double(struct json_object *obj, double new_value);
/* string type methods */ /* string type methods */
@@ -893,10 +959,21 @@ JSON_EXPORT int json_object_set_double(struct json_object *obj,double new_value)
* *
* @param s the string * @param s the string
* @returns a json_object of type json_type_string * @returns a json_object of type json_type_string
* @see json_object_new_string_len()
*/ */
JSON_EXPORT struct json_object* json_object_new_string(const char *s); JSON_EXPORT struct json_object *json_object_new_string(const char *s);
JSON_EXPORT struct json_object* json_object_new_string_len(const char *s, int len); /** Create a new empty json_object of type json_type_string and allocate
* len characters for the new string.
*
* A copy of the string is made and the memory is managed by the json_object
*
* @param s the string
* @param len max length of the new string
* @returns a json_object of type json_type_string
* @see json_object_new_string()
*/
JSON_EXPORT struct json_object *json_object_new_string_len(const char *s, const int len);
/** Get the string value of a json_object /** Get the string value of a json_object
* *
@@ -914,7 +991,7 @@ JSON_EXPORT struct json_object* json_object_new_string_len(const char *s, int le
* @param obj the json_object instance * @param obj the json_object instance
* @returns a string or NULL * @returns a string or NULL
*/ */
JSON_EXPORT const char* json_object_get_string(struct json_object *obj); JSON_EXPORT const char *json_object_get_string(struct json_object *obj);
/** Get the string length of a json_object /** Get the string length of a json_object
* *
@@ -926,25 +1003,30 @@ JSON_EXPORT const char* json_object_get_string(struct json_object *obj);
*/ */
JSON_EXPORT int json_object_get_string_len(const struct json_object *obj); JSON_EXPORT int json_object_get_string_len(const struct json_object *obj);
/** Set the string value of a json_object with zero terminated strings /** Set the string value of a json_object with zero terminated strings
* equivalent to json_object_set_string_len (obj, new_value, strlen(new_value)) * equivalent to json_object_set_string_len (obj, new_value, strlen(new_value))
* @returns 1 if value is set correctly, 0 otherwise * @returns 1 if value is set correctly, 0 otherwise
*/ */
JSON_EXPORT int json_object_set_string(json_object* obj, const char* new_value); JSON_EXPORT int json_object_set_string(json_object *obj, const char *new_value);
/** Set the string value of a json_object str /** Set the string value of a json_object str
* *
* The type of obj is checked to be a json_type_string and 0 is returned * The type of obj is checked to be a json_type_string and 0 is returned
* if it is not without any further actions. If type of obj is json_type_string * if it is not without any further actions. If type of obj is json_type_string
* the obect value is chaned to new_value * the object value is changed to new_value
* *
* @param obj the json_object instance * @param obj the json_object instance
* @param new_value the value to be set; Since string legth is given in len this need not be zero terminated * @param new_value the value to be set; Since string length is given in len this need not be zero terminated
* @param len the length of new_value * @param len the length of new_value
* @returns 1 if value is set correctly, 0 otherwise * @returns 1 if value is set correctly, 0 otherwise
*/ */
JSON_EXPORT int json_object_set_string_len(json_object* obj, const char* new_value, int len); JSON_EXPORT int json_object_set_string_len(json_object *obj, const char *new_value, int len);
/** This method exists only to provide a complementary function
* along the lines of the other json_object_new_* functions.
* It always returns NULL, and it is entirely acceptable to simply use NULL directly.
*/
JSON_EXPORT struct json_object *json_object_new_null(void);
/** Check if two json_object's are equal /** Check if two json_object's are equal
* *
@@ -961,10 +1043,9 @@ JSON_EXPORT int json_object_set_string_len(json_object* obj, const char* new_val
* *
* @param obj1 the first json_object instance * @param obj1 the first json_object instance
* @param obj2 the second json_object instance * @param obj2 the second json_object instance
* @returns whether both objects are equal or not * @returns 1 if both objects are equal, 0 otherwise
*/ */
JSON_EXPORT int json_object_equal(struct json_object *obj1, JSON_EXPORT int json_object_equal(struct json_object *obj1, struct json_object *obj2);
struct json_object *obj2);
/** /**
* Perform a shallow copy of src into *dst as part of an overall json_object_deep_copy(). * Perform a shallow copy of src into *dst as part of an overall json_object_deep_copy().
@@ -974,17 +1055,18 @@ JSON_EXPORT int json_object_equal(struct json_object *obj1,
* When shallow_copy is called *dst will be NULL, and must be non-NULL when it returns. * When shallow_copy is called *dst will be NULL, and must be non-NULL when it returns.
* src will never be NULL. * src will never be NULL.
* *
* If shallow_copy sets the serializer on an object, return 2 to indicate to * If shallow_copy sets the serializer on an object, return 2 to indicate to
* json_object_deep_copy that it should not attempt to use the standard userdata * json_object_deep_copy that it should not attempt to use the standard userdata
* copy function. * copy function.
* *
* @return On success 1 or 2, -1 on errors * @return On success 1 or 2, -1 on errors
*/ */
typedef int (json_c_shallow_copy_fn)(json_object *src, json_object *parent, const char *key, size_t index, json_object **dst); typedef int(json_c_shallow_copy_fn)(json_object *src, json_object *parent, const char *key,
size_t index, json_object **dst);
/** /**
* The default shallow copy implementation for use with json_object_deep_copy(). * The default shallow copy implementation for use with json_object_deep_copy().
* This simply calls the appropriate json_object_new_<type>() function and * This simply calls the appropriate json_object_new_<type>() function and
* copies over the serializer function (_to_json_string internal field of * copies over the serializer function (_to_json_string internal field of
* the json_object structure) but not any _userdata or _user_delete values. * the json_object structure) but not any _userdata or _user_delete values.
* *
@@ -994,7 +1076,7 @@ typedef int (json_c_shallow_copy_fn)(json_object *src, json_object *parent, cons
* *
* @return 1 on success, -1 on errors, but never 2. * @return 1 on success, -1 on errors, but never 2.
*/ */
json_c_shallow_copy_fn json_c_shallow_copy_default; JSON_EXPORT json_c_shallow_copy_fn json_c_shallow_copy_default;
/** /**
* Copy the contents of the JSON object. * Copy the contents of the JSON object.
@@ -1011,11 +1093,12 @@ json_c_shallow_copy_fn json_c_shallow_copy_default;
* when custom serializers are in use. See also * when custom serializers are in use. See also
* json_object set_serializer. * json_object set_serializer.
* *
* @returns 0 if the copy went well, -1 if an error occured during copy * @returns 0 if the copy went well, -1 if an error occurred during copy
* or if the destination pointer is non-NULL * or if the destination pointer is non-NULL
*/ */
JSON_EXPORT int json_object_deep_copy(struct json_object *src, struct json_object **dst, json_c_shallow_copy_fn *shallow_copy); JSON_EXPORT int json_object_deep_copy(struct json_object *src, struct json_object **dst,
json_c_shallow_copy_fn *shallow_copy);
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif

View File

@@ -9,6 +9,7 @@
* *
******************************************************************************* *******************************************************************************
*/ */
#include "config.h"
#include <stddef.h> #include <stddef.h>
@@ -53,111 +54,100 @@
/// Our current representation of the "end" iterator; /// Our current representation of the "end" iterator;
/// ///
/// @note May not always be NULL /// @note May not always be NULL
static const void* kObjectEndIterValue = NULL; static const void *kObjectEndIterValue = NULL;
/** /**
* **************************************************************************** * ****************************************************************************
*/ */
struct json_object_iterator struct json_object_iterator json_object_iter_begin(struct json_object *obj)
json_object_iter_begin(struct json_object* obj)
{ {
struct json_object_iterator iter; struct json_object_iterator iter;
struct lh_table* pTable; struct lh_table *pTable;
/// @note json_object_get_object will return NULL if passed NULL /// @note json_object_get_object will return NULL if passed NULL
/// or a non-json_type_object instance /// or a non-json_type_object instance
pTable = json_object_get_object(obj); pTable = json_object_get_object(obj);
JASSERT(NULL != pTable); JASSERT(NULL != pTable);
/// @note For a pair-less Object, head is NULL, which matches our /// @note For a pair-less Object, head is NULL, which matches our
/// definition of the "end" iterator /// definition of the "end" iterator
iter.opaque_ = pTable->head; iter.opaque_ = lh_table_head(pTable);
return iter; return iter;
} }
/** /**
* **************************************************************************** * ****************************************************************************
*/ */
struct json_object_iterator struct json_object_iterator json_object_iter_end(const struct json_object *obj)
json_object_iter_end(const struct json_object* obj)
{ {
struct json_object_iterator iter; struct json_object_iterator iter;
JASSERT(NULL != obj); JASSERT(NULL != obj);
JASSERT(json_object_is_type(obj, json_type_object)); JASSERT(json_object_is_type(obj, json_type_object));
iter.opaque_ = kObjectEndIterValue; iter.opaque_ = kObjectEndIterValue;
return iter; return iter;
} }
/** /**
* **************************************************************************** * ****************************************************************************
*/ */
void void json_object_iter_next(struct json_object_iterator *iter)
json_object_iter_next(struct json_object_iterator* iter)
{ {
JASSERT(NULL != iter); JASSERT(NULL != iter);
JASSERT(kObjectEndIterValue != iter->opaque_); JASSERT(kObjectEndIterValue != iter->opaque_);
iter->opaque_ = ((const struct lh_entry *)iter->opaque_)->next; iter->opaque_ = lh_entry_next(((const struct lh_entry *)iter->opaque_));
} }
/** /**
* **************************************************************************** * ****************************************************************************
*/ */
const char* const char *json_object_iter_peek_name(const struct json_object_iterator *iter)
json_object_iter_peek_name(const struct json_object_iterator* iter)
{ {
JASSERT(NULL != iter); JASSERT(NULL != iter);
JASSERT(kObjectEndIterValue != iter->opaque_); JASSERT(kObjectEndIterValue != iter->opaque_);
return (const char*)(((const struct lh_entry *)iter->opaque_)->k); return (const char *)(((const struct lh_entry *)iter->opaque_)->k);
} }
/** /**
* **************************************************************************** * ****************************************************************************
*/ */
struct json_object* struct json_object *json_object_iter_peek_value(const struct json_object_iterator *iter)
json_object_iter_peek_value(const struct json_object_iterator* iter)
{ {
JASSERT(NULL != iter); JASSERT(NULL != iter);
JASSERT(kObjectEndIterValue != iter->opaque_); JASSERT(kObjectEndIterValue != iter->opaque_);
return (struct json_object*)lh_entry_v((const struct lh_entry *)iter->opaque_); return (struct json_object *)lh_entry_v((const struct lh_entry *)iter->opaque_);
} }
/** /**
* **************************************************************************** * ****************************************************************************
*/ */
json_bool json_bool json_object_iter_equal(const struct json_object_iterator *iter1,
json_object_iter_equal(const struct json_object_iterator* iter1, const struct json_object_iterator *iter2)
const struct json_object_iterator* iter2)
{ {
JASSERT(NULL != iter1); JASSERT(NULL != iter1);
JASSERT(NULL != iter2); JASSERT(NULL != iter2);
return (iter1->opaque_ == iter2->opaque_); return (iter1->opaque_ == iter2->opaque_);
} }
/** /**
* **************************************************************************** * ****************************************************************************
*/ */
struct json_object_iterator struct json_object_iterator json_object_iter_init_default(void)
json_object_iter_init_default(void)
{ {
struct json_object_iterator iter; struct json_object_iterator iter;
/** /**
* @note Make this a negative, invalid value, such that * @note Make this a negative, invalid value, such that
* accidental access to it would likely be trapped by the * accidental access to it would likely be trapped by the
* hardware as an invalid address. * hardware as an invalid address.
*/ */
iter.opaque_ = NULL; iter.opaque_ = NULL;
return iter; return iter;
} }

View File

@@ -20,10 +20,10 @@
******************************************************************************* *******************************************************************************
*/ */
#ifndef JSON_OBJECT_ITERATOR_H #ifndef JSON_OBJECT_ITERATOR_H
#define JSON_OBJECT_ITERATOR_H #define JSON_OBJECT_ITERATOR_H
#include "json_types.h"
#include <stddef.h> #include <stddef.h>
#ifdef __cplusplus #ifdef __cplusplus
@@ -39,17 +39,16 @@ struct json_object_iter_info_;
* The opaque iterator that references a name/value pair within * The opaque iterator that references a name/value pair within
* a JSON Object instance or the "end" iterator value. * a JSON Object instance or the "end" iterator value.
*/ */
struct json_object_iterator { struct json_object_iterator
const void* opaque_; {
const void *opaque_;
}; };
/** /**
* forward declaration of json-c's JSON value instance structure * forward declaration of json-c's JSON value instance structure
*/ */
struct json_object; struct json_object;
/** /**
* Initializes an iterator structure to a "default" value that * Initializes an iterator structure to a "default" value that
* is convenient for initializing an iterator variable to a * is convenient for initializing an iterator variable to a
@@ -72,8 +71,7 @@ struct json_object;
* *
* @return json_object_iterator * @return json_object_iterator
*/ */
struct json_object_iterator JSON_EXPORT struct json_object_iterator json_object_iter_init_default(void);
json_object_iter_init_default(void);
/** Retrieves an iterator to the first pair of the JSON Object. /** Retrieves an iterator to the first pair of the JSON Object.
* *
@@ -106,8 +104,7 @@ json_object_iter_init_default(void);
* *
* @endcode * @endcode
*/ */
struct json_object_iterator JSON_EXPORT struct json_object_iterator json_object_iter_begin(struct json_object *obj);
json_object_iter_begin(struct json_object* obj);
/** Retrieves the iterator that represents the position beyond the /** Retrieves the iterator that represents the position beyond the
* last pair of the given JSON Object instance. * last pair of the given JSON Object instance.
@@ -137,8 +134,7 @@ json_object_iter_begin(struct json_object* obj);
* (i.e., NOT the last pair, but "beyond the last * (i.e., NOT the last pair, but "beyond the last
* pair" value) * pair" value)
*/ */
struct json_object_iterator JSON_EXPORT struct json_object_iterator json_object_iter_end(const struct json_object *obj);
json_object_iter_end(const struct json_object* obj);
/** Returns an iterator to the next pair, if any /** Returns an iterator to the next pair, if any
* *
@@ -155,9 +151,7 @@ json_object_iter_end(const struct json_object* obj);
* of json_object_iter_end() for the same JSON Object * of json_object_iter_end() for the same JSON Object
* instance. * instance.
*/ */
void JSON_EXPORT void json_object_iter_next(struct json_object_iterator *iter);
json_object_iter_next(struct json_object_iterator* iter);
/** Returns a const pointer to the name of the pair referenced /** Returns a const pointer to the name of the pair referenced
* by the given iterator. * by the given iterator.
@@ -174,9 +168,7 @@ json_object_iter_next(struct json_object_iterator* iter);
* deleted or modified, and MUST NOT be modified or * deleted or modified, and MUST NOT be modified or
* freed by the user. * freed by the user.
*/ */
const char* JSON_EXPORT const char *json_object_iter_peek_name(const struct json_object_iterator *iter);
json_object_iter_peek_name(const struct json_object_iterator* iter);
/** Returns a pointer to the json-c instance representing the /** Returns a pointer to the json-c instance representing the
* value of the referenced name/value pair, without altering * value of the referenced name/value pair, without altering
@@ -197,9 +189,8 @@ json_object_iter_peek_name(const struct json_object_iterator* iter);
* the JSON Null value as a NULL json_object instance * the JSON Null value as a NULL json_object instance
* pointer. * pointer.
*/ */
struct json_object* JSON_EXPORT struct json_object *
json_object_iter_peek_value(const struct json_object_iterator* iter); json_object_iter_peek_value(const struct json_object_iterator *iter);
/** Tests two iterators for equality. Typically used to test /** Tests two iterators for equality. Typically used to test
* for end of iteration by comparing an iterator to the * for end of iteration by comparing an iterator to the
@@ -227,14 +218,11 @@ json_object_iter_peek_value(const struct json_object_iterator* iter);
* reference the same name/value pair or are both at * reference the same name/value pair or are both at
* "end"); zero if they are not equal. * "end"); zero if they are not equal.
*/ */
json_bool JSON_EXPORT json_bool json_object_iter_equal(const struct json_object_iterator *iter1,
json_object_iter_equal(const struct json_object_iterator* iter1, const struct json_object_iterator *iter2);
const struct json_object_iterator* iter2);
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif
#endif /* JSON_OBJECT_ITERATOR_H */ #endif /* JSON_OBJECT_ITERATOR_H */

View File

@@ -20,41 +20,84 @@
extern "C" { extern "C" {
#endif #endif
#define LEN_DIRECT_STRING_DATA 32 /**< how many bytes are directly stored in json_object for strings? */ struct json_object;
#include "json_inttypes.h"
#include "json_types.h"
typedef void (json_object_private_delete_fn)(struct json_object *o); #ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif /* HAVE_UNISTD_H */
#ifdef _MSC_VER
#include <BaseTsd.h>
typedef SSIZE_T ssize_t;
#endif
/* json object int type, support extension*/
typedef enum json_object_int_type
{
json_object_int_type_int64,
json_object_int_type_uint64
} json_object_int_type;
struct json_object struct json_object
{ {
enum json_type o_type; enum json_type o_type;
json_object_private_delete_fn *_delete; uint32_t _ref_count;
json_object_to_json_string_fn *_to_json_string; json_object_to_json_string_fn *_to_json_string;
int _ref_count; struct printbuf *_pb;
struct printbuf *_pb; json_object_delete_fn *_user_delete;
union data { void *_userdata;
json_bool c_boolean; // Actually longer, always malloc'd as some more-specific type.
double c_double; // The rest of a struct json_object_${o_type} follows
int64_t c_int64; };
struct lh_table *c_object;
struct array_list *c_array; struct json_object_object
struct { {
union { struct json_object base;
/* optimize: if we have small strings, we can store them struct lh_table *c_object;
* directly. This saves considerable CPU cycles AND memory. };
*/ struct json_object_array
char *ptr; {
char data[LEN_DIRECT_STRING_DATA]; struct json_object base;
} str; struct array_list *c_array;
int len; };
} c_string;
} o; struct json_object_boolean
json_object_delete_fn *_user_delete; {
void *_userdata; struct json_object base;
json_bool c_boolean;
};
struct json_object_double
{
struct json_object base;
double c_double;
};
struct json_object_int
{
struct json_object base;
enum json_object_int_type cint_type;
union
{
int64_t c_int64;
uint64_t c_uint64;
} cint;
};
struct json_object_string
{
struct json_object base;
ssize_t len; // Signed b/c negative lengths indicate data is a pointer
// Consider adding an "alloc" field here, if json_object_set_string calls
// to expand the length of a string are common operations to perform.
union
{
char idata[1]; // Immediate data. Actually longer
char *pdata; // Only when len < 0
} c_string;
}; };
void _json_c_set_last_err(const char *err_fmt, ...); void _json_c_set_last_err(const char *err_fmt, ...);
extern const char *json_number_chars;
extern const char *json_hex_chars; extern const char *json_hex_chars;
#ifdef __cplusplus #ifdef __cplusplus

332
json_patch.c Normal file
View File

@@ -0,0 +1,332 @@
/*
* Copyright (c) 2021 Alexandru Ardelean.
* Copyright (c) 2023 Eric Hawicz
*
* This is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See COPYING for details.
*/
#include "config.h"
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include "json_patch.h"
#include "json_object_private.h"
#include "json_pointer_private.h"
#include <limits.h>
#ifndef SIZE_T_MAX
#if SIZEOF_SIZE_T == SIZEOF_INT
#define SIZE_T_MAX UINT_MAX
#elif SIZEOF_SIZE_T == SIZEOF_LONG
#define SIZE_T_MAX ULONG_MAX
#elif SIZEOF_SIZE_T == SIZEOF_LONG_LONG
#define SIZE_T_MAX ULLONG_MAX
#else
#error Unable to determine size of size_t
#endif
#endif
#define _set_err(_errval, _errmsg) do { \
patch_error->errno_code = (_errval); \
patch_error->errmsg = (_errmsg); \
errno = 0; /* To avoid confusion */ \
} while (0)
#define _set_err_from_ptrget(_errval, _fieldname) do { \
patch_error->errno_code = (_errval); \
patch_error->errmsg = (_errval) == ENOENT ? \
"Did not find element referenced by " _fieldname " field" : \
"Invalid " _fieldname " field"; \
errno = 0; /* To avoid confusion */ \
} while(0)
/**
* JavaScript Object Notation (JSON) Patch
* RFC 6902 - https://tools.ietf.org/html/rfc6902
*/
static int json_patch_apply_test(struct json_object **res,
struct json_object *patch_elem,
const char *path, struct json_patch_error *patch_error)
{
struct json_object *value1, *value2;
if (!json_object_object_get_ex(patch_elem, "value", &value1)) {
_set_err(EINVAL, "Patch object does not contain a 'value' field");
return -1;
}
if (json_pointer_get(*res, path, &value2))
{
_set_err_from_ptrget(errno, "path");
return -1;
}
if (!json_object_equal(value1, value2)) {
_set_err(ENOENT, "Value of element referenced by 'path' field did not match 'value' field");
return -1;
}
return 0;
}
static int __json_patch_apply_remove(struct json_pointer_get_result *jpres)
{
if (json_object_is_type(jpres->parent, json_type_array)) {
return json_object_array_del_idx(jpres->parent, jpres->index_in_parent, 1);
} else if (jpres->parent && jpres->key_in_parent) {
json_object_object_del(jpres->parent, jpres->key_in_parent);
return 0;
} else {
// We're removing the root object
(void)json_object_put(jpres->obj);
jpres->obj = NULL;
return 0;
}
}
static int json_patch_apply_remove(struct json_object **res, const char *path, struct json_patch_error *patch_error)
{
struct json_pointer_get_result jpres;
int rc;
if (json_pointer_get_internal(*res, path, &jpres))
{
_set_err_from_ptrget(errno, "path");
return -1;
}
rc = __json_patch_apply_remove(&jpres);
if (rc < 0)
_set_err(EINVAL, "Unable to remove path referenced by 'path' field");
// This means we removed and freed the root object, i.e. *res
if (jpres.parent == NULL)
*res = NULL;
return rc;
}
// callback for json_pointer_set_with_array_cb()
static int json_object_array_insert_idx_cb(struct json_object *parent, size_t idx,
struct json_object *value, void *priv)
{
int rc;
int *add = priv;
if (idx > json_object_array_length(parent))
{
// Note: will propagate back out through json_pointer_set_with_array_cb()
errno = EINVAL;
return -1;
}
if (*add)
rc = json_object_array_insert_idx(parent, idx, value);
else
rc = json_object_array_put_idx(parent, idx, value);
if (rc < 0)
errno = EINVAL;
return rc;
}
static int json_patch_apply_add_replace(struct json_object **res,
struct json_object *patch_elem,
const char *path, int add, struct json_patch_error *patch_error)
{
struct json_object *value;
int rc;
if (!json_object_object_get_ex(patch_elem, "value", &value)) {
_set_err(EINVAL, "Patch object does not contain a 'value' field");
return -1;
}
/* if this is a replace op, then we need to make sure it exists before replacing */
if (!add && json_pointer_get(*res, path, NULL)) {
_set_err_from_ptrget(errno, "path");
return -1;
}
rc = json_pointer_set_with_array_cb(res, path, json_object_get(value),
json_object_array_insert_idx_cb, &add);
if (rc)
{
_set_err(errno, "Failed to set value at path referenced by 'path' field");
json_object_put(value);
}
return rc;
}
// callback for json_pointer_set_with_array_cb()
static int json_object_array_move_cb(struct json_object *parent, size_t idx,
struct json_object *value, void *priv)
{
int rc;
struct json_pointer_get_result *from = priv;
size_t len = json_object_array_length(parent);
/**
* If it's the same array parent, it means that we removed
* and element from it, so the length is temporarily reduced
* by 1, which means that if we try to move an element to
* the last position, we need to check the current length + 1
*/
if (parent == from->parent)
len++;
if (idx > len)
{
// Note: will propagate back out through json_pointer_set_with_array_cb()
errno = EINVAL;
return -1;
}
rc = json_object_array_insert_idx(parent, idx, value);
if (rc < 0)
errno = EINVAL;
return rc;
}
static int json_patch_apply_move_copy(struct json_object **res,
struct json_object *patch_elem,
const char *path, int move, struct json_patch_error *patch_error)
{
json_pointer_array_set_cb array_set_cb;
struct json_pointer_get_result from;
struct json_object *jfrom;
const char *from_s;
size_t from_s_len;
int rc;
if (!json_object_object_get_ex(patch_elem, "from", &jfrom)) {
_set_err(EINVAL, "Patch does not contain a 'from' field");
return -1;
}
from_s = json_object_get_string(jfrom);
from_s_len = strlen(from_s);
if (strncmp(from_s, path, from_s_len) == 0) {
/**
* If lengths match, it's a noop, if they don't,
* then we're trying to move a parent under a child
* which is not allowed as per RFC 6902 section 4.4
* The "from" location MUST NOT be a proper prefix of the "path"
* location; i.e., a location cannot be moved into one of its children.
*/
if (from_s_len == strlen(path))
return 0;
_set_err(EINVAL, "Invalid attempt to move parent under a child");
return -1;
}
rc = json_pointer_get_internal(*res, from_s, &from);
if (rc)
{
_set_err_from_ptrget(errno, "from");
return rc;
}
// Note: it's impossible for json_pointer to find the root obj, due
// to the path check above, so from.parent is guaranteed non-NULL
json_object_get(from.obj);
if (!move) {
array_set_cb = json_object_array_insert_idx_cb;
} else {
rc = __json_patch_apply_remove(&from);
if (rc < 0) {
json_object_put(from.obj);
return rc;
}
array_set_cb = json_object_array_move_cb;
}
rc = json_pointer_set_with_array_cb(res, path, from.obj, array_set_cb, &from);
if (rc)
{
_set_err(errno, "Failed to set value at path referenced by 'path' field");
json_object_put(from.obj);
}
return rc;
}
int json_patch_apply(struct json_object *copy_from, struct json_object *patch,
struct json_object **base, struct json_patch_error *patch_error)
{
size_t ii;
int rc = 0;
struct json_patch_error placeholder;
if (!patch_error)
patch_error = &placeholder;
patch_error->patch_failure_idx = SIZE_T_MAX;
patch_error->errno_code = 0;
if (base == NULL||
(*base == NULL && copy_from == NULL) ||
(*base != NULL && copy_from != NULL))
{
_set_err(EFAULT, "Exactly one of *base or copy_from must be non-NULL");
return -1;
}
if (!json_object_is_type(patch, json_type_array)) {
_set_err(EFAULT, "Patch object is not of type json_type_array");
return -1;
}
if (copy_from != NULL)
{
if (json_object_deep_copy(copy_from, base, NULL) < 0)
{
_set_err(ENOMEM, "Unable to copy copy_from using json_object_deep_copy()");
return -1;
}
}
/* Go through all operations ; apply them on res */
for (ii = 0; ii < json_object_array_length(patch); ii++) {
struct json_object *jop, *jpath;
struct json_object *patch_elem = json_object_array_get_idx(patch, ii);
const char *op, *path;
patch_error->patch_failure_idx = ii;
if (!json_object_object_get_ex(patch_elem, "op", &jop)) {
_set_err(EINVAL, "Patch object does not contain 'op' field");
return -1;
}
op = json_object_get_string(jop);
if (!json_object_object_get_ex(patch_elem, "path", &jpath)) {
_set_err(EINVAL, "Patch object does not contain 'path' field");
return -1;
}
path = json_object_get_string(jpath); // Note: empty string is ok!
if (!strcmp(op, "test"))
rc = json_patch_apply_test(base, patch_elem, path, patch_error);
else if (!strcmp(op, "remove"))
rc = json_patch_apply_remove(base, path, patch_error);
else if (!strcmp(op, "add"))
rc = json_patch_apply_add_replace(base, patch_elem, path, 1, patch_error);
else if (!strcmp(op, "replace"))
rc = json_patch_apply_add_replace(base, patch_elem, path, 0, patch_error);
else if (!strcmp(op, "move"))
rc = json_patch_apply_move_copy(base, patch_elem, path, 1, patch_error);
else if (!strcmp(op, "copy"))
rc = json_patch_apply_move_copy(base, patch_elem, path, 0, patch_error);
else {
_set_err(EINVAL, "Patch object has invalid 'op' field");
return -1;
}
if (rc < 0)
break;
}
return rc;
}

80
json_patch.h Normal file
View File

@@ -0,0 +1,80 @@
/*
* Copyright (c) 2021 Alexadru Ardelean.
*
* This is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See COPYING for details.
*
*/
/**
* @file
* @brief JSON Patch (RFC 6902) implementation for manipulating JSON objects
*/
#ifndef _json_patch_h_
#define _json_patch_h_
#include "json_pointer.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* Details of an error that occurred during json_patch_apply()
*/
struct json_patch_error {
/**
* An errno value indicating what kind of error occurred.
* Possible values include:
* - ENOENT - A path referenced in the operation does not exist.
* - EINVAL - An invalid operation or with invalid path was attempted
* - ENOMEM - Unable to allocate memory
* - EFAULT - Invalid arguments were passed to json_patch_apply()
* (i.e. a C API error, vs. a data error like EINVAL)
*/
int errno_code;
/**
* The index into the patch array of the operation that failed,
* or SIZE_T_MAX for overall errors.
*/
size_t patch_failure_idx;
/**
* A human readable error message.
* Allocated from static storage, does not need to be freed.
*/
const char *errmsg;
};
/**
* Apply the JSON patch to the base object.
* The patch object must be formatted as per RFC 6902, i.e.
* a json_type_array containing patch operations.
* If the patch is not correctly formatted, an error will
* be returned.
*
* The json_object at *base will be modified in place.
* Exactly one of *base or copy_from must be non-NULL.
* If *base is NULL, a new copy of copy_from will allocated and populated
* using json_object_deep_copy(). In this case json_object_put() _must_ be
* used to free *base even if the overall patching operation fails.
*
* If anything fails during patching a negative value will be returned,
* and patch_error (if non-NULL) will be populated with error details.
*
* @param base a pointer to the JSON object which to patch
* @param patch the JSON object that describes the patch to be applied
* @param copy_from a JSON object to copy to *base
* @param patch_error optional, details about errors
*
* @return negative if an error (or not found), or 0 if patch completely applied
*/
JSON_EXPORT int json_patch_apply(struct json_object *copy_from, struct json_object *patch,
struct json_object **base, struct json_patch_error *patch_error);
#ifdef __cplusplus
}
#endif
#endif

View File

@@ -14,12 +14,16 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <ctype.h>
#include "json_object_private.h"
#include "json_pointer.h" #include "json_pointer.h"
#include "json_pointer_private.h"
#include "strdup_compat.h" #include "strdup_compat.h"
#include "vasprintf_compat.h" #include "vasprintf_compat.h"
/* Avoid ctype.h and locale overhead */
#define is_plain_digit(c) ((c) >= '0' && (c) <= '9')
/** /**
* JavaScript Object Notation (JSON) Pointer * JavaScript Object Notation (JSON) Pointer
* RFC 6901 - https://tools.ietf.org/html/rfc6901 * RFC 6901 - https://tools.ietf.org/html/rfc6901
@@ -27,10 +31,11 @@
static void string_replace_all_occurrences_with_char(char *s, const char *occur, char repl_char) static void string_replace_all_occurrences_with_char(char *s, const char *occur, char repl_char)
{ {
int slen = strlen(s); size_t slen = strlen(s);
int skip = strlen(occur) - 1; /* length of the occurence, minus the char we're replacing */ size_t skip = strlen(occur) - 1; /* length of the occurrence, minus the char we're replacing */
char *p = s; char *p = s;
while ((p = strstr(p, occur))) { while ((p = strstr(p, occur)))
{
*p = repl_char; *p = repl_char;
p++; p++;
slen -= skip; slen -= skip;
@@ -38,55 +43,61 @@ static void string_replace_all_occurrences_with_char(char *s, const char *occur,
} }
} }
static int is_valid_index(struct json_object *jo, const char *path, int32_t *idx) static int is_valid_index(const char *path, size_t *idx)
{ {
int i, len = strlen(path); size_t i, len = strlen(path);
/* this code-path optimizes a bit, for when we reference the 0-9 index range in a JSON array /* this code-path optimizes a bit, for when we reference the 0-9 index range
and because leading zeros not allowed */ * in a JSON array and because leading zeros not allowed
if (len == 1) { */
if (isdigit((int)path[0])) { if (len == 1)
{
if (is_plain_digit(path[0]))
{
*idx = (path[0] - '0'); *idx = (path[0] - '0');
goto check_oob; return 1;
} }
errno = EINVAL; errno = EINVAL;
return 0; return 0;
} }
/* leading zeros not allowed per RFC */ /* leading zeros not allowed per RFC */
if (path[0] == '0') { if (path[0] == '0')
{
errno = EINVAL; errno = EINVAL;
return 0; return 0;
} }
/* RFC states base-10 decimals */ /* RFC states base-10 decimals */
for (i = 0; i < len; i++) { for (i = 0; i < len; i++)
if (!isdigit((int)path[i])) { {
if (!is_plain_digit(path[i]))
{
errno = EINVAL; errno = EINVAL;
return 0; return 0;
} }
} }
*idx = strtol(path, NULL, 10); // We know it's all digits, so the only error case here is overflow,
if (*idx < 0) { // but ULLONG_MAX will be longer than any array length so that's ok.
errno = EINVAL; *idx = strtoull(path, NULL, 10);
return 0;
}
check_oob:
len = json_object_array_length(jo);
if (*idx >= len) {
errno = ENOENT;
return 0;
}
return 1; return 1;
} }
static int json_pointer_get_single_path(struct json_object *obj, char *path, struct json_object **value) static int json_pointer_get_single_path(struct json_object *obj, char *path,
struct json_object **value, size_t *idx)
{ {
if (json_object_is_type(obj, json_type_array)) { if (json_object_is_type(obj, json_type_array))
int32_t idx; {
if (!is_valid_index(obj, path, &idx)) if (!is_valid_index(path, idx))
return -1; return -1;
obj = json_object_array_get_idx(obj, idx); if (*idx >= json_object_array_length(obj))
if (obj) { {
errno = ENOENT;
return -1;
}
obj = json_object_array_get_idx(obj, *idx);
if (obj)
{
if (value) if (value)
*value = obj; *value = obj;
return 0; return 0;
@@ -100,7 +111,8 @@ static int json_pointer_get_single_path(struct json_object *obj, char *path, str
string_replace_all_occurrences_with_char(path, "~1", '/'); string_replace_all_occurrences_with_char(path, "~1", '/');
string_replace_all_occurrences_with_char(path, "~0", '~'); string_replace_all_occurrences_with_char(path, "~0", '~');
if (!json_object_object_get_ex(obj, path, value)) { if (!json_object_object_get_ex(obj, path, value))
{
errno = ENOENT; errno = ENOENT;
return -1; return -1;
} }
@@ -108,42 +120,51 @@ static int json_pointer_get_single_path(struct json_object *obj, char *path, str
return 0; return 0;
} }
static int json_pointer_set_single_path( static int json_object_array_put_idx_cb(struct json_object *parent, size_t idx,
struct json_object *parent, struct json_object *value, void *priv)
const char *path,
struct json_object *value)
{ {
if (json_object_is_type(parent, json_type_array)) { return json_object_array_put_idx(parent, idx, value);
int32_t idx; }
static int json_pointer_set_single_path(struct json_object *parent, const char *path,
struct json_object *value,
json_pointer_array_set_cb array_set_cb, void *priv)
{
if (json_object_is_type(parent, json_type_array))
{
size_t idx;
/* RFC (Chapter 4) states that '-' may be used to add new elements to an array */ /* RFC (Chapter 4) states that '-' may be used to add new elements to an array */
if (path[0] == '-' && path[1] == '\0') if (path[0] == '-' && path[1] == '\0')
return json_object_array_add(parent, value); return json_object_array_add(parent, value);
if (!is_valid_index(parent, path, &idx)) if (!is_valid_index(path, &idx))
return -1; return -1;
return json_object_array_put_idx(parent, idx, value); return array_set_cb(parent, idx, value, priv);
} }
/* path replacements should have been done in json_pointer_get_single_path(), /* path replacements should have been done in json_pointer_get_single_path(),
and we should still be good here */ * and we should still be good here
*/
if (json_object_is_type(parent, json_type_object)) if (json_object_is_type(parent, json_type_object))
return json_object_object_add(parent, path, value); return json_object_object_add(parent, path, value);
/* Getting here means that we tried to "dereference" a primitive JSON type (like string, int, bool). /* Getting here means that we tried to "dereference" a primitive JSON type
i.e. add a sub-object to it */ * (like string, int, bool).i.e. add a sub-object to it
*/
errno = ENOENT; errno = ENOENT;
return -1; return -1;
} }
static int json_pointer_get_recursive( static int json_pointer_result_get_recursive(struct json_object *obj, char *path,
struct json_object *obj, struct json_pointer_get_result *res)
char *path,
struct json_object **value)
{ {
struct json_object *parent_obj = obj;
size_t idx = 0;
char *endp; char *endp;
int rc; int rc;
/* All paths (on each recursion level must have a leading '/' */ /* All paths (on each recursion level must have a leading '/' */
if (path[0] != '/') { if (path[0] != '/')
{
errno = EINVAL; errno = EINVAL;
return -1; return -1;
} }
@@ -154,55 +175,104 @@ static int json_pointer_get_recursive(
*endp = '\0'; *endp = '\0';
/* If we err-ed here, return here */ /* If we err-ed here, return here */
if ((rc = json_pointer_get_single_path(obj, path, &obj))) if ((rc = json_pointer_get_single_path(obj, path, &obj, &idx)))
return rc; return rc;
if (endp) { if (endp)
*endp = '/'; /* Put the slash back, so that the sanity check passes on next recursion level */ {
return json_pointer_get_recursive(obj, endp, value); /* Put the slash back, so that the sanity check passes on next recursion level */
*endp = '/';
return json_pointer_result_get_recursive(obj, endp, res);
} }
/* We should be at the end of the recursion here */ /* We should be at the end of the recursion here */
if (value) if (res) {
*value = obj; res->parent = parent_obj;
res->obj = obj;
if (json_object_is_type(res->parent, json_type_array))
res->index_in_parent = idx;
else
res->key_in_parent = path;
}
return 0; return 0;
} }
int json_pointer_get(struct json_object *obj, const char *path, struct json_object **res) static int json_pointer_object_get_recursive(struct json_object *obj, char *path,
struct json_object **value)
{
struct json_pointer_get_result res;
int rc;
rc = json_pointer_result_get_recursive(obj, path, &res);
if (rc)
return rc;
if (value)
*value = res.obj;
return 0;
}
int json_pointer_get_internal(struct json_object *obj, const char *path,
struct json_pointer_get_result *res)
{ {
char *path_copy = NULL; char *path_copy = NULL;
int rc; int rc;
if (!obj || !path) { if (!obj || !path)
{
errno = EINVAL; errno = EINVAL;
return -1; return -1;
} }
if (path[0] == '\0') { if (path[0] == '\0')
if (res) {
*res = obj; res->parent = NULL;
res->obj = obj;
res->key_in_parent = NULL;
res->index_in_parent = UINT32_MAX;
return 0; return 0;
} }
/* pass a working copy to the recursive call */ /* pass a working copy to the recursive call */
if (!(path_copy = strdup(path))) { if (!(path_copy = strdup(path)))
{
errno = ENOMEM; errno = ENOMEM;
return -1; return -1;
} }
rc = json_pointer_get_recursive(obj, path_copy, res); rc = json_pointer_result_get_recursive(obj, path_copy, res);
/* re-map the path string to the const-path string */
if (rc == 0 && json_object_is_type(res->parent, json_type_object) && res->key_in_parent)
res->key_in_parent = path + (res->key_in_parent - path_copy);
free(path_copy); free(path_copy);
return rc; return rc;
} }
int json_pointer_get(struct json_object *obj, const char *path, struct json_object **res)
{
struct json_pointer_get_result jpres;
int rc;
rc = json_pointer_get_internal(obj, path, &jpres);
if (rc)
return rc;
if (res)
*res = jpres.obj;
return 0;
}
int json_pointer_getf(struct json_object *obj, struct json_object **res, const char *path_fmt, ...) int json_pointer_getf(struct json_object *obj, struct json_object **res, const char *path_fmt, ...)
{ {
char *path_copy = NULL; char *path_copy = NULL;
int rc = 0; int rc = 0;
va_list args; va_list args;
if (!obj || !path_fmt) { if (!obj || !path_fmt)
{
errno = EINVAL; errno = EINVAL;
return -1; return -1;
} }
@@ -214,65 +284,79 @@ int json_pointer_getf(struct json_object *obj, struct json_object **res, const c
if (rc < 0) if (rc < 0)
return rc; return rc;
if (path_copy[0] == '\0') { if (path_copy[0] == '\0')
{
if (res) if (res)
*res = obj; *res = obj;
goto out; goto out;
} }
rc = json_pointer_get_recursive(obj, path_copy, res); rc = json_pointer_object_get_recursive(obj, path_copy, res);
out: out:
free(path_copy); free(path_copy);
return rc; return rc;
} }
int json_pointer_set(struct json_object **obj, const char *path, struct json_object *value) int json_pointer_set_with_array_cb(struct json_object **obj, const char *path,
struct json_object *value,
json_pointer_array_set_cb array_set_cb, void *priv)
{ {
const char *endp; const char *endp;
char *path_copy = NULL; char *path_copy = NULL;
struct json_object *set = NULL; struct json_object *set = NULL;
int rc; int rc;
if (!obj || !path) { if (!obj || !path)
{
errno = EINVAL; errno = EINVAL;
return -1; return -1;
} }
if (path[0] == '\0') { if (path[0] == '\0')
{
json_object_put(*obj); json_object_put(*obj);
*obj = value; *obj = value;
return 0; return 0;
} }
if (path[0] != '/') { if (path[0] != '/')
{
errno = EINVAL; errno = EINVAL;
return -1; return -1;
} }
/* If there's only 1 level to set, stop here */ /* If there's only 1 level to set, stop here */
if ((endp = strrchr(path, '/')) == path) { if ((endp = strrchr(path, '/')) == path)
{
path++; path++;
return json_pointer_set_single_path(*obj, path, value); return json_pointer_set_single_path(*obj, path, value, array_set_cb, priv);
} }
/* pass a working copy to the recursive call */ /* pass a working copy to the recursive call */
if (!(path_copy = strdup(path))) { if (!(path_copy = strdup(path)))
{
errno = ENOMEM; errno = ENOMEM;
return -1; return -1;
} }
path_copy[endp - path] = '\0'; path_copy[endp - path] = '\0';
rc = json_pointer_get_recursive(*obj, path_copy, &set); rc = json_pointer_object_get_recursive(*obj, path_copy, &set);
free(path_copy); free(path_copy);
if (rc) if (rc)
return rc; return rc;
endp++; endp++;
return json_pointer_set_single_path(set, endp, value); return json_pointer_set_single_path(set, endp, value, array_set_cb, priv);
} }
int json_pointer_setf(struct json_object **obj, struct json_object *value, const char *path_fmt, ...) int json_pointer_set(struct json_object **obj, const char *path, struct json_object *value)
{
return json_pointer_set_with_array_cb(obj, path, value, json_object_array_put_idx_cb, NULL);
}
int json_pointer_setf(struct json_object **obj, struct json_object *value, const char *path_fmt,
...)
{ {
char *endp; char *endp;
char *path_copy = NULL; char *path_copy = NULL;
@@ -280,7 +364,8 @@ int json_pointer_setf(struct json_object **obj, struct json_object *value, const
va_list args; va_list args;
int rc = 0; int rc = 0;
if (!obj || !path_fmt) { if (!obj || !path_fmt)
{
errno = EINVAL; errno = EINVAL;
return -1; return -1;
} }
@@ -293,35 +378,38 @@ int json_pointer_setf(struct json_object **obj, struct json_object *value, const
if (rc < 0) if (rc < 0)
return rc; return rc;
if (path_copy[0] == '\0') { if (path_copy[0] == '\0')
{
json_object_put(*obj); json_object_put(*obj);
*obj = value; *obj = value;
goto out; goto out;
} }
if (path_copy[0] != '/') { if (path_copy[0] != '/')
{
errno = EINVAL; errno = EINVAL;
rc = -1; rc = -1;
goto out; goto out;
} }
/* If there's only 1 level to set, stop here */ /* If there's only 1 level to set, stop here */
if ((endp = strrchr(path_copy, '/')) == path_copy) { if ((endp = strrchr(path_copy, '/')) == path_copy)
{
set = *obj; set = *obj;
goto set_single_path; goto set_single_path;
} }
*endp = '\0'; *endp = '\0';
rc = json_pointer_get_recursive(*obj, path_copy, &set); rc = json_pointer_object_get_recursive(*obj, path_copy, &set);
if (rc) if (rc)
goto out; goto out;
set_single_path: set_single_path:
endp++; endp++;
rc = json_pointer_set_single_path(set, endp, value); rc = json_pointer_set_single_path(set, endp, value,
json_object_array_put_idx_cb, NULL);
out: out:
free(path_copy); free(path_copy);
return rc; return rc;
} }

View File

@@ -32,37 +32,36 @@ extern "C" {
* Internally, this is equivalent to doing a series of 'json_object_object_get()' * Internally, this is equivalent to doing a series of 'json_object_object_get()'
* and 'json_object_array_get_idx()' along the given 'path'. * and 'json_object_array_get_idx()' along the given 'path'.
* *
* Note that the 'path' string supports 'printf()' type arguments, so, whatever
* is added after the 'res' param will be treated as an argument for 'path'
* Example: json_pointer_get(obj, "/foo/%d/%s", &res, 0, bar)
* This means, that you need to escape '%' with '%%' (just like in printf())
*
* @param obj the json_object instance/tree from where to retrieve sub-objects * @param obj the json_object instance/tree from where to retrieve sub-objects
* @param path a (RFC6901) string notation for the sub-object to retrieve * @param path a (RFC6901) string notation for the sub-object to retrieve
* @param res a pointer where to store a reference to the json_object * @param res a pointer that stores a reference to the json_object
* associated with the given path * associated with the given path
* *
* @return negative if an error (or not found), or 0 if succeeded * @return negative if an error (or not found), or 0 if succeeded
*/ */
int json_pointer_get(struct json_object *obj, const char *path, struct json_object **res); JSON_EXPORT int json_pointer_get(struct json_object *obj, const char *path,
struct json_object **res);
/** /**
* This is a variant of 'json_pointer_get()' that supports printf() style arguments. * This is a variant of 'json_pointer_get()' that supports printf() style arguments.
* *
* Example: json_pointer_getf(obj, res, "/foo/%d/%s", 0, bak) * Variable arguments go after the 'path_fmt' parameter.
*
* Example: json_pointer_getf(obj, res, "/foo/%d/%s", 0, "bar")
* This also means that you need to escape '%' with '%%' (just like in printf()) * This also means that you need to escape '%' with '%%' (just like in printf())
* *
* Please take into consideration all recommended 'printf()' format security * Please take into consideration all recommended 'printf()' format security
* aspects when using this function. * aspects when using this function.
* *
* @param obj the json_object instance/tree to which to add a sub-object * @param obj the json_object instance/tree to which to add a sub-object
* @param res a pointer where to store a reference to the json_object * @param res a pointer that stores a reference to the json_object
* associated with the given path * associated with the given path
* @param path_fmt a printf() style format for the path * @param path_fmt a printf() style format for the path
* *
* @return negative if an error (or not found), or 0 if succeeded * @return negative if an error (or not found), or 0 if succeeded
*/ */
int json_pointer_getf(struct json_object *obj, struct json_object **res, const char *path_fmt, ...); JSON_EXPORT int json_pointer_getf(struct json_object *obj, struct json_object **res,
const char *path_fmt, ...);
/** /**
* Sets JSON object 'value' in the 'obj' tree at the location specified * Sets JSON object 'value' in the 'obj' tree at the location specified
@@ -82,23 +81,21 @@ int json_pointer_getf(struct json_object *obj, struct json_object **res, const c
* That also implies that 'json_pointer_set()' does not do any refcount incrementing. * That also implies that 'json_pointer_set()' does not do any refcount incrementing.
* (Just that single decrement that was mentioned above). * (Just that single decrement that was mentioned above).
* *
* Note that the 'path' string supports 'printf()' type arguments, so, whatever
* is added after the 'value' param will be treated as an argument for 'path'
* Example: json_pointer_set(obj, "/foo/%d/%s", value, 0, bak)
* This means, that you need to escape '%' with '%%' (just like in printf())
*
* @param obj the json_object instance/tree to which to add a sub-object * @param obj the json_object instance/tree to which to add a sub-object
* @param path a (RFC6901) string notation for the sub-object to set in the tree * @param path a (RFC6901) string notation for the sub-object to set in the tree
* @param value object to set at path * @param value object to set at path
* *
* @return negative if an error (or not found), or 0 if succeeded * @return negative if an error (or not found), or 0 if succeeded
*/ */
int json_pointer_set(struct json_object **obj, const char *path, struct json_object *value); JSON_EXPORT int json_pointer_set(struct json_object **obj, const char *path,
struct json_object *value);
/** /**
* This is a variant of 'json_pointer_set()' that supports printf() style arguments. * This is a variant of 'json_pointer_set()' that supports printf() style arguments.
* *
* Example: json_pointer_setf(obj, value, "/foo/%d/%s", 0, bak) * Variable arguments go after the 'path_fmt' parameter.
*
* Example: json_pointer_setf(obj, value, "/foo/%d/%s", 0, "bar")
* This also means that you need to escape '%' with '%%' (just like in printf()) * This also means that you need to escape '%' with '%%' (just like in printf())
* *
* Please take into consideration all recommended 'printf()' format security * Please take into consideration all recommended 'printf()' format security
@@ -110,8 +107,8 @@ int json_pointer_set(struct json_object **obj, const char *path, struct json_obj
* *
* @return negative if an error (or not found), or 0 if succeeded * @return negative if an error (or not found), or 0 if succeeded
*/ */
int json_pointer_setf(struct json_object **obj, struct json_object *value, const char *path_fmt, ...); JSON_EXPORT int json_pointer_setf(struct json_object **obj, struct json_object *value,
const char *path_fmt, ...);
#ifdef __cplusplus #ifdef __cplusplus
} }

43
json_pointer_private.h Normal file
View File

@@ -0,0 +1,43 @@
/*
* Copyright (c) 2023 Eric Hawicz
*
* This library is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See COPYING for details.
*/
/**
* @file
* @brief Do not use, json-c internal, may be changed or removed at any time.
*/
#ifndef _json_pointer_private_h_
#define _json_pointer_private_h_
#ifdef __cplusplus
extern "C" {
#endif
struct json_pointer_get_result {
struct json_object *parent;
struct json_object *obj;
// The key of the found object; only valid when parent is json_type_object
// Caution: re-uses tail end of the `path` argument to json_pointer_get_internal
const char *key_in_parent;
// the index of the found object; only valid when parent is json_type_array
uint32_t index_in_parent;
};
int json_pointer_get_internal(struct json_object *obj, const char *path,
struct json_pointer_get_result *res);
typedef int(*json_pointer_array_set_cb)(json_object *parent, size_t idx,
json_object *value, void *priv);
int json_pointer_set_with_array_cb(struct json_object **obj, const char *path,
struct json_object *value,
json_pointer_array_set_cb array_set_cb, void *priv);
#ifdef __cplusplus
}
#endif
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -16,80 +16,126 @@
#ifndef _json_tokener_h_ #ifndef _json_tokener_h_
#define _json_tokener_h_ #define _json_tokener_h_
#include <stddef.h>
#include "json_object.h" #include "json_object.h"
#include <stddef.h>
#ifdef __cplusplus #ifdef __cplusplus
extern "C" { extern "C" {
#endif #endif
enum json_tokener_error { enum json_tokener_error
json_tokener_success, {
json_tokener_continue, json_tokener_success,
json_tokener_error_depth, json_tokener_continue,
json_tokener_error_parse_eof, json_tokener_error_depth,
json_tokener_error_parse_unexpected, json_tokener_error_parse_eof,
json_tokener_error_parse_null, json_tokener_error_parse_unexpected,
json_tokener_error_parse_boolean, json_tokener_error_parse_null,
json_tokener_error_parse_number, json_tokener_error_parse_boolean,
json_tokener_error_parse_array, json_tokener_error_parse_number,
json_tokener_error_parse_object_key_name, json_tokener_error_parse_array,
json_tokener_error_parse_object_key_sep, json_tokener_error_parse_object_key_name,
json_tokener_error_parse_object_value_sep, json_tokener_error_parse_object_key_sep,
json_tokener_error_parse_string, json_tokener_error_parse_object_value_sep,
json_tokener_error_parse_comment, json_tokener_error_parse_string,
json_tokener_error_size json_tokener_error_parse_comment,
json_tokener_error_parse_utf8_string,
json_tokener_error_size, /* A string longer than INT32_MAX was passed as input */
json_tokener_error_memory /* Failed to allocate memory */
}; };
enum json_tokener_state { /**
json_tokener_state_eatws, * @deprecated Don't use this outside of json_tokener.c, it will be made private in a future release.
json_tokener_state_start, */
json_tokener_state_finish, enum json_tokener_state
json_tokener_state_null, {
json_tokener_state_comment_start, json_tokener_state_eatws,
json_tokener_state_comment, json_tokener_state_start,
json_tokener_state_comment_eol, json_tokener_state_finish,
json_tokener_state_comment_end, json_tokener_state_null,
json_tokener_state_string, json_tokener_state_comment_start,
json_tokener_state_string_escape, json_tokener_state_comment,
json_tokener_state_escape_unicode, json_tokener_state_comment_eol,
json_tokener_state_boolean, json_tokener_state_comment_end,
json_tokener_state_number, json_tokener_state_string,
json_tokener_state_array, json_tokener_state_string_escape,
json_tokener_state_array_add, json_tokener_state_escape_unicode,
json_tokener_state_array_sep, json_tokener_state_escape_unicode_need_escape,
json_tokener_state_object_field_start, json_tokener_state_escape_unicode_need_u,
json_tokener_state_object_field, json_tokener_state_boolean,
json_tokener_state_object_field_end, json_tokener_state_number,
json_tokener_state_object_value, json_tokener_state_array,
json_tokener_state_object_value_add, json_tokener_state_array_add,
json_tokener_state_object_sep, json_tokener_state_array_sep,
json_tokener_state_array_after_sep, json_tokener_state_object_field_start,
json_tokener_state_object_field_start_after_sep, json_tokener_state_object_field,
json_tokener_state_inf json_tokener_state_object_field_end,
json_tokener_state_object_value,
json_tokener_state_object_value_add,
json_tokener_state_object_sep,
json_tokener_state_array_after_sep,
json_tokener_state_object_field_start_after_sep,
json_tokener_state_inf
}; };
/**
* @deprecated Don't use this outside of json_tokener.c, it will be made private in a future release.
*/
struct json_tokener_srec struct json_tokener_srec
{ {
enum json_tokener_state state, saved_state; enum json_tokener_state state, saved_state;
struct json_object *obj; struct json_object *obj;
struct json_object *current; struct json_object *current;
char *obj_field_name; char *obj_field_name;
}; };
#define JSON_TOKENER_DEFAULT_DEPTH 32 #define JSON_TOKENER_DEFAULT_DEPTH 32
/**
* Internal state of the json parser.
* Do not access any fields of this structure directly.
* Its definition is published due to historical limitations
* in the json tokener API, and will be changed to be an opaque
* type in the future.
*/
struct json_tokener struct json_tokener
{ {
char *str; /**
struct printbuf *pb; * @deprecated Do not access any of these fields outside of json_tokener.c
int max_depth, depth, is_double, st_pos, char_offset; */
enum json_tokener_error err; char *str;
unsigned int ucs_char; struct printbuf *pb;
char quote_char; int max_depth, depth, is_double, st_pos;
struct json_tokener_srec *stack; /**
int flags; * @deprecated See json_tokener_get_parse_end() instead.
*/
int char_offset;
/**
* @deprecated See json_tokener_get_error() instead.
*/
enum json_tokener_error err;
unsigned int ucs_char, high_surrogate;
char quote_char;
struct json_tokener_srec *stack;
int flags;
}; };
/**
* Return the offset of the byte after the last byte parsed
* relative to the start of the most recent string passed in
* to json_tokener_parse_ex(). i.e. this is where parsing
* would start again if the input contains another JSON object
* after the currently parsed one.
*
* Note that when multiple parse calls are issued, this is *not* the
* total number of characters parsed.
*
* In the past this would have been accessed as tok->char_offset.
*
* See json_tokener_parse_ex() for an example of how to use this.
*/
JSON_EXPORT size_t json_tokener_get_parse_end(struct json_tokener *tok);
/** /**
* @deprecated Unused in json-c code * @deprecated Unused in json-c code
*/ */
@@ -101,11 +147,36 @@ typedef struct json_tokener json_tokener;
* restrictive from one release to the next, causing your * restrictive from one release to the next, causing your
* code to fail on previously working input. * code to fail on previously working input.
* *
* Note that setting this will also effectively disable parsing
* of multiple json objects in a single character stream
* (e.g. {"foo":123}{"bar":234}); if you want to allow that
* also set JSON_TOKENER_ALLOW_TRAILING_CHARS
*
* This flag is not set by default. * This flag is not set by default.
* *
* @see json_tokener_set_flags() * @see json_tokener_set_flags()
*/ */
#define JSON_TOKENER_STRICT 0x01 #define JSON_TOKENER_STRICT 0x01
/**
* Use with JSON_TOKENER_STRICT to allow trailing characters after the
* first parsed object.
*
* @see json_tokener_set_flags()
*/
#define JSON_TOKENER_ALLOW_TRAILING_CHARS 0x02
/**
* Cause json_tokener_parse_ex() to validate that input is UTF8.
* If this flag is specified and validation fails, then
* json_tokener_get_error(tok) will return
* json_tokener_error_parse_utf8_string
*
* This flag is not set by default.
*
* @see json_tokener_set_flags()
*/
#define JSON_TOKENER_VALIDATE_UTF8 0x10
/** /**
* Given an error previously returned by json_tokener_get_error(), * Given an error previously returned by json_tokener_get_error(),
@@ -113,7 +184,7 @@ typedef struct json_tokener json_tokener;
* *
* @return a generic error message is returned if an invalid error value is provided. * @return a generic error message is returned if an invalid error value is provided.
*/ */
const char *json_tokener_error_desc(enum json_tokener_error jerr); JSON_EXPORT const char *json_tokener_error_desc(enum json_tokener_error jerr);
/** /**
* Retrieve the error caused by the last call to json_tokener_parse_ex(), * Retrieve the error caused by the last call to json_tokener_parse_ex(),
@@ -122,16 +193,50 @@ const char *json_tokener_error_desc(enum json_tokener_error jerr);
* When parsing a JSON string in pieces, if the tokener is in the middle * When parsing a JSON string in pieces, if the tokener is in the middle
* of parsing this will return json_tokener_continue. * of parsing this will return json_tokener_continue.
* *
* See also json_tokener_error_desc(). * @see json_tokener_error_desc().
*/ */
JSON_EXPORT enum json_tokener_error json_tokener_get_error(struct json_tokener *tok); JSON_EXPORT enum json_tokener_error json_tokener_get_error(struct json_tokener *tok);
JSON_EXPORT struct json_tokener* json_tokener_new(void); /**
JSON_EXPORT struct json_tokener* json_tokener_new_ex(int depth); * Allocate a new json_tokener.
* When done using that to parse objects, free it with json_tokener_free().
* See json_tokener_parse_ex() for usage details.
*/
JSON_EXPORT struct json_tokener *json_tokener_new(void);
/**
* Allocate a new json_tokener with a custom max nesting depth.
* @see JSON_TOKENER_DEFAULT_DEPTH
*/
JSON_EXPORT struct json_tokener *json_tokener_new_ex(int depth);
/**
* Free a json_tokener previously allocated with json_tokener_new().
*/
JSON_EXPORT void json_tokener_free(struct json_tokener *tok); JSON_EXPORT void json_tokener_free(struct json_tokener *tok);
/**
* Reset the state of a json_tokener, to prepare to parse a
* brand new JSON object.
*/
JSON_EXPORT void json_tokener_reset(struct json_tokener *tok); JSON_EXPORT void json_tokener_reset(struct json_tokener *tok);
JSON_EXPORT struct json_object* json_tokener_parse(const char *str);
JSON_EXPORT struct json_object* json_tokener_parse_verbose(const char *str, enum json_tokener_error *error); /**
* Parse a json_object out of the string `str`.
*
* If you need more control over how the parsing occurs,
* see json_tokener_parse_ex().
*/
JSON_EXPORT struct json_object *json_tokener_parse(const char *str);
/**
* Parse a json_object out of the string `str`, but if it fails
* return the error in `*error`.
* @see json_tokener_parse()
* @see json_tokener_parse_ex()
*/
JSON_EXPORT struct json_object *json_tokener_parse_verbose(const char *str,
enum json_tokener_error *error);
/** /**
* Set flags that control how parsing will be done. * Set flags that control how parsing will be done.
@@ -151,26 +256,32 @@ JSON_EXPORT void json_tokener_set_flags(struct json_tokener *tok, int flags);
* *
* If json_tokener_parse_ex() returns NULL and the error is anything other than * If json_tokener_parse_ex() returns NULL and the error is anything other than
* json_tokener_continue, a fatal error has occurred and parsing must be * json_tokener_continue, a fatal error has occurred and parsing must be
* halted. Then, the tok object must not be reused until json_tokener_reset() is * halted. Then, the tok object must not be reused until json_tokener_reset()
* called. * is called.
* *
* When a valid JSON value is parsed, a non-NULL json_object will be * When a valid JSON value is parsed, a non-NULL json_object will be
* returned. Also, json_tokener_get_error() will return json_tokener_success. * returned, with a reference count of one which belongs to the caller. Also,
* Be sure to check the type with json_object_is_type() or * json_tokener_get_error() will return json_tokener_success. Be sure to check
* json_object_get_type() before using the object. * the type with json_object_is_type() or json_object_get_type() before using
* the object.
* *
* @b XXX this shouldn't use internal fields:
* Trailing characters after the parsed value do not automatically cause an * Trailing characters after the parsed value do not automatically cause an
* error. It is up to the caller to decide whether to treat this as an * error. It is up to the caller to decide whether to treat this as an
* error or to handle the additional characters, perhaps by parsing another * error or to handle the additional characters, perhaps by parsing another
* json value starting from that point. * json value starting from that point.
* *
* Extra characters can be detected by comparing the tok->char_offset against * If the caller knows that they are at the end of their input, the length
* passed MUST include the final '\0' character, so values with no inherent
* end (i.e. numbers) can be properly parsed, rather than just returning
* json_tokener_continue.
*
* Extra characters can be detected by comparing the value returned by
* json_tokener_get_parse_end() against
* the length of the last len parameter passed in. * the length of the last len parameter passed in.
* *
* The tokener does \b not maintain an internal buffer so the caller is * The tokener does \b not maintain an internal buffer so the caller is
* responsible for calling json_tokener_parse_ex with an appropriate str * responsible for a subsequent call to json_tokener_parse_ex with an
* parameter starting with the extra characters. * appropriate str parameter starting with the extra characters.
* *
* This interface is presently not 64-bit clean due to the int len argument * This interface is presently not 64-bit clean due to the int len argument
* so the function limits the maximum string size to INT32_MAX (2GB). * so the function limits the maximum string size to INT32_MAX (2GB).
@@ -186,6 +297,8 @@ enum json_tokener_error jerr;
do { do {
mystring = ... // get JSON string, e.g. read from file, etc... mystring = ... // get JSON string, e.g. read from file, etc...
stringlen = strlen(mystring); stringlen = strlen(mystring);
if (end_of_input)
stringlen++; // Include the '\0' if we know we're at the end of input
jobj = json_tokener_parse_ex(tok, mystring, stringlen); jobj = json_tokener_parse_ex(tok, mystring, stringlen);
} while ((jerr = json_tokener_get_error(tok)) == json_tokener_continue); } while ((jerr = json_tokener_get_error(tok)) == json_tokener_continue);
if (jerr != json_tokener_success) if (jerr != json_tokener_success)
@@ -193,7 +306,7 @@ if (jerr != json_tokener_success)
fprintf(stderr, "Error: %s\n", json_tokener_error_desc(jerr)); fprintf(stderr, "Error: %s\n", json_tokener_error_desc(jerr));
// Handle errors, as appropriate for your application. // Handle errors, as appropriate for your application.
} }
if (tok->char_offset < stringlen) // XXX shouldn't access internal fields if (json_tokener_get_parse_end(tok) < stringlen)
{ {
// Handle extra characters after parsed object as desired. // Handle extra characters after parsed object as desired.
// e.g. issue an error, parse another object from that point, etc... // e.g. issue an error, parse another object from that point, etc...
@@ -206,8 +319,8 @@ if (tok->char_offset < stringlen) // XXX shouldn't access internal fields
* @param str an string with any valid JSON expression, or portion of. This does not need to be null terminated. * @param str an string with any valid JSON expression, or portion of. This does not need to be null terminated.
* @param len the length of str * @param len the length of str
*/ */
JSON_EXPORT struct json_object* json_tokener_parse_ex(struct json_tokener *tok, JSON_EXPORT struct json_object *json_tokener_parse_ex(struct json_tokener *tok, const char *str,
const char *str, int len); int len);
#ifdef __cplusplus #ifdef __cplusplus
} }

78
json_types.h Normal file
View File

@@ -0,0 +1,78 @@
/*
* Copyright (c) 2020 Eric Hawicz
*
* This library is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See COPYING for details.
*/
#ifndef _json_types_h_
#define _json_types_h_
/**
* @file
* @brief Basic types used in a few places in json-c, but you should include "json_object.h" instead.
*/
#ifdef __cplusplus
extern "C" {
#endif
#ifndef JSON_EXPORT
#if defined(_MSC_VER) && defined(JSON_C_DLL)
#define JSON_EXPORT __declspec(dllexport)
#else
#define JSON_EXPORT extern
#endif
#endif
struct printbuf;
/**
* A structure to use with json_object_object_foreachC() loops.
* Contains key, val and entry members.
*/
struct json_object_iter
{
char *key;
struct json_object *val;
struct lh_entry *entry;
};
typedef struct json_object_iter json_object_iter;
typedef int json_bool;
/**
* @brief The core type for all type of JSON objects handled by json-c
*/
typedef struct json_object json_object;
/**
* Type of custom user delete functions. See json_object_set_serializer.
*/
typedef void(json_object_delete_fn)(struct json_object *jso, void *userdata);
/**
* Type of a custom serialization function. See json_object_set_serializer.
*/
typedef int(json_object_to_json_string_fn)(struct json_object *jso, struct printbuf *pb, int level,
int flags);
/* supported object types */
typedef enum json_type
{
/* If you change this, be sure to update json_type_to_name() too */
json_type_null,
json_type_boolean,
json_type_double,
json_type_int,
json_type_object,
json_type_array,
json_type_string
} json_type;
#ifdef __cplusplus
}
#endif
#endif

View File

@@ -14,13 +14,12 @@
#include "strerror_override.h" #include "strerror_override.h"
#include <limits.h>
#include <stdarg.h> #include <stdarg.h>
#include <stddef.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <stddef.h>
#include <limits.h>
#include <string.h> #include <string.h>
#include <ctype.h>
#ifdef HAVE_SYS_TYPES_H #ifdef HAVE_SYS_TYPES_H
#include <sys/types.h> #include <sys/types.h>
@@ -35,37 +34,33 @@
#endif /* HAVE_FCNTL_H */ #endif /* HAVE_FCNTL_H */
#ifdef HAVE_UNISTD_H #ifdef HAVE_UNISTD_H
# include <unistd.h> #include <unistd.h>
#endif /* HAVE_UNISTD_H */ #endif /* HAVE_UNISTD_H */
#ifdef WIN32 #ifdef _WIN32
# if MSC_VER < 1800 #define WIN32_LEAN_AND_MEAN
/* strtoll is available only since Visual Studio 2013 */ #include <io.h>
# define strtoll _strtoi64 #include <windows.h>
# endif #endif /* defined(_WIN32) */
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
# include <io.h>
#endif /* defined(WIN32) */
#if !defined(HAVE_OPEN) && defined(WIN32) #if !defined(HAVE_OPEN) && defined(_WIN32)
# define open _open #define open _open
#endif #endif
#include "snprintf_compat.h" #include "snprintf_compat.h"
#include "debug.h" #include "debug.h"
#include "printbuf.h"
#include "json_inttypes.h" #include "json_inttypes.h"
#include "json_object.h" #include "json_object.h"
#include "json_tokener.h" #include "json_tokener.h"
#include "json_util.h" #include "json_util.h"
#include "printbuf.h"
static int _json_object_to_fd(int fd, struct json_object *obj, int flags, const char *filename); static int _json_object_to_fd(int fd, struct json_object *obj, int flags, const char *filename);
static char _last_err[256] = ""; static char _last_err[256] = "";
const char *json_util_get_last_err() const char *json_util_get_last_err(void)
{ {
if (_last_err[0] == '\0') if (_last_err[0] == '\0')
return NULL; return NULL;
@@ -81,43 +76,84 @@ void _json_c_set_last_err(const char *err_fmt, ...)
va_end(ap); va_end(ap);
} }
struct json_object* json_object_from_fd(int fd) struct json_object *json_object_from_fd(int fd)
{ {
struct printbuf *pb; return json_object_from_fd_ex(fd, -1);
struct json_object *obj; }
char buf[JSON_FILE_BUF_SIZE]; struct json_object *json_object_from_fd_ex(int fd, int in_depth)
int ret; {
struct printbuf *pb;
struct json_object *obj;
char buf[JSON_FILE_BUF_SIZE];
ssize_t ret;
int depth = JSON_TOKENER_DEFAULT_DEPTH;
json_tokener *tok;
if(!(pb = printbuf_new())) { if (!(pb = printbuf_new()))
_json_c_set_last_err("json_object_from_file: printbuf_new failed\n"); {
return NULL; _json_c_set_last_err("json_object_from_fd_ex: printbuf_new failed\n");
} return NULL;
while((ret = read(fd, buf, JSON_FILE_BUF_SIZE)) > 0) { }
printbuf_memappend(pb, buf, ret);
} if (in_depth != -1)
if(ret < 0) { depth = in_depth;
_json_c_set_last_err("json_object_from_fd: error reading fd %d: %s\n", fd, strerror(errno)); tok = json_tokener_new_ex(depth);
printbuf_free(pb); if (!tok)
return NULL; {
} _json_c_set_last_err(
obj = json_tokener_parse(pb->buf); "json_object_from_fd_ex: unable to allocate json_tokener(depth=%d): %s\n",
printbuf_free(pb); depth, strerror(errno));
return obj; printbuf_free(pb);
return NULL;
}
while ((ret = read(fd, buf, sizeof(buf))) > 0)
{
if (printbuf_memappend(pb, buf, ret) < 0)
{
#if JSON_FILE_BUF_SIZE > INT_MAX
#error "Can't append more than INT_MAX bytes at a time"
#endif
_json_c_set_last_err(
"json_object_from_fd_ex: failed to printbuf_memappend after reading %d+%d bytes: %s", printbuf_length(pb), (int)ret, strerror(errno));
json_tokener_free(tok);
printbuf_free(pb);
return NULL;
}
}
if (ret < 0)
{
_json_c_set_last_err("json_object_from_fd_ex: error reading fd %d: %s\n", fd,
strerror(errno));
json_tokener_free(tok);
printbuf_free(pb);
return NULL;
}
obj = json_tokener_parse_ex(tok, pb->buf, printbuf_length(pb));
if (obj == NULL)
_json_c_set_last_err("json_tokener_parse_ex failed: %s\n",
json_tokener_error_desc(json_tokener_get_error(tok)));
json_tokener_free(tok);
printbuf_free(pb);
return obj;
} }
struct json_object* json_object_from_file(const char *filename) struct json_object *json_object_from_file(const char *filename)
{ {
struct json_object *obj; struct json_object *obj;
int fd; int fd;
if((fd = open(filename, O_RDONLY)) < 0) { if ((fd = open(filename, O_RDONLY)) < 0)
_json_c_set_last_err("json_object_from_file: error opening file %s: %s\n", {
filename, strerror(errno)); _json_c_set_last_err("json_object_from_file: error opening file %s: %s\n",
return NULL; filename, strerror(errno));
} return NULL;
obj = json_object_from_fd(fd); }
close(fd); obj = json_object_from_fd(fd);
return obj; close(fd);
return obj;
} }
/* extended "format and write to file" function */ /* extended "format and write to file" function */
@@ -127,14 +163,16 @@ int json_object_to_file_ext(const char *filename, struct json_object *obj, int f
int fd, ret; int fd, ret;
int saved_errno; int saved_errno;
if (!obj) { if (!obj)
_json_c_set_last_err("json_object_to_file: object is null\n"); {
_json_c_set_last_err("json_object_to_file_ext: object is null\n");
return -1; return -1;
} }
if ((fd = open(filename, O_WRONLY | O_TRUNC | O_CREAT, 0644)) < 0) { if ((fd = open(filename, O_WRONLY | O_TRUNC | O_CREAT, 0644)) < 0)
_json_c_set_last_err("json_object_to_file: error opening file %s: %s\n", {
filename, strerror(errno)); _json_c_set_last_err("json_object_to_file_ext: error opening file %s: %s\n",
filename, strerror(errno));
return -1; return -1;
} }
ret = _json_object_to_fd(fd, obj, flags, filename); ret = _json_object_to_fd(fd, obj, flags, filename);
@@ -146,7 +184,8 @@ int json_object_to_file_ext(const char *filename, struct json_object *obj, int f
int json_object_to_fd(int fd, struct json_object *obj, int flags) int json_object_to_fd(int fd, struct json_object *obj, int flags)
{ {
if (!obj) { if (!obj)
{
_json_c_set_last_err("json_object_to_fd: object is null\n"); _json_c_set_last_err("json_object_to_fd: object is null\n");
return -1; return -1;
} }
@@ -155,27 +194,30 @@ int json_object_to_fd(int fd, struct json_object *obj, int flags)
} }
static int _json_object_to_fd(int fd, struct json_object *obj, int flags, const char *filename) static int _json_object_to_fd(int fd, struct json_object *obj, int flags, const char *filename)
{ {
int ret; ssize_t ret;
const char *json_str; const char *json_str;
unsigned int wpos, wsize; size_t wpos, wsize;
filename = filename ? filename : "(fd)"; filename = filename ? filename : "(fd)";
if (!(json_str = json_object_to_json_string_ext(obj,flags))) { if (!(json_str = json_object_to_json_string_ext(obj, flags)))
{
return -1; return -1;
} }
wsize = (unsigned int)(strlen(json_str) & UINT_MAX); /* CAW: probably unnecessary, but the most 64bit safe */ wsize = strlen(json_str);
wpos = 0; wpos = 0;
while(wpos < wsize) { while (wpos < wsize)
if((ret = write(fd, json_str + wpos, wsize-wpos)) < 0) { {
_json_c_set_last_err("json_object_to_file: error writing file %s: %s\n", if ((ret = write(fd, json_str + wpos, wsize - wpos)) < 0)
filename, strerror(errno)); {
return -1; _json_c_set_last_err("json_object_to_fd: error writing file %s: %s\n",
filename, strerror(errno));
return -1;
} }
/* because of the above check for ret < 0, we can safely cast and add */ /* because of the above check for ret < 0, we can safely cast and add */
wpos += (unsigned int)ret; wpos += (size_t)ret;
} }
return 0; return 0;
@@ -185,14 +227,15 @@ static int _json_object_to_fd(int fd, struct json_object *obj, int flags, const
int json_object_to_file(const char *filename, struct json_object *obj) int json_object_to_file(const char *filename, struct json_object *obj)
{ {
return json_object_to_file_ext(filename, obj, JSON_C_TO_STRING_PLAIN); return json_object_to_file_ext(filename, obj, JSON_C_TO_STRING_PLAIN);
} }
// Deprecated json_parse_double function. See json_tokener_parse_double instead.
int json_parse_double(const char *buf, double *retval) int json_parse_double(const char *buf, double *retval)
{ {
char *end; char *end;
*retval = strtod(buf, &end); *retval = strtod(buf, &end);
return end == buf ? 1 : 0; return end == buf ? 1 : 0;
} }
int json_parse_int64(const char *buf, int64_t *retval) int json_parse_int64(const char *buf, int64_t *retval)
@@ -204,11 +247,38 @@ int json_parse_int64(const char *buf, int64_t *retval)
val = strtoll(buf, &end, 10); val = strtoll(buf, &end, 10);
if (end != buf) if (end != buf)
*retval = val; *retval = val;
return ((val == 0 && errno != 0) || (end == buf)) ? 1 : 0; if ((val == 0 && errno != 0) || (end == buf))
{
errno = EINVAL;
return 1;
}
return 0;
}
int json_parse_uint64(const char *buf, uint64_t *retval)
{
char *end = NULL;
uint64_t val;
errno = 0;
while (*buf == ' ')
buf++;
if (*buf == '-')
return 1; /* error: uint cannot be negative */
val = strtoull(buf, &end, 10);
if (end != buf)
*retval = val;
if ((val == 0 && errno != 0) || (end == buf))
{
errno = EINVAL;
return 1;
}
return 0;
} }
#ifndef HAVE_REALLOC #ifndef HAVE_REALLOC
void* rpl_realloc(void* p, size_t n) void *rpl_realloc(void *p, size_t n)
{ {
if (n == 0) if (n == 0)
n = 1; n = 1;
@@ -218,26 +288,28 @@ void* rpl_realloc(void* p, size_t n)
} }
#endif #endif
#define NELEM(a) (sizeof(a) / sizeof(a[0])) #define NELEM(a) (sizeof(a) / sizeof(a[0]))
static const char* json_type_name[] = { /* clang-format off */
/* If you change this, be sure to update the enum json_type definition too */ static const char *json_type_name[] = {
"null", /* If you change this, be sure to update the enum json_type definition too */
"boolean", "null",
"double", "boolean",
"int", "double",
"object", "int",
"array", "object",
"string", "array",
"string",
}; };
/* clang-format on */
const char *json_type_to_name(enum json_type o_type) const char *json_type_to_name(enum json_type o_type)
{ {
int o_type_int = (int)o_type; int o_type_int = (int)o_type;
if (o_type_int < 0 || o_type_int >= (int)NELEM(json_type_name)) if (o_type_int < 0 || o_type_int >= (int)NELEM(json_type_name))
{ {
_json_c_set_last_err("json_type_to_name: type %d is out of range [0,%d]\n", o_type, NELEM(json_type_name)); _json_c_set_last_err("json_type_to_name: type %d is out of range [0,%u]\n", o_type,
(unsigned)NELEM(json_type_name));
return NULL; return NULL;
} }
return json_type_name[o_type]; return json_type_name[o_type];
} }

View File

@@ -12,21 +12,20 @@
/** /**
* @file * @file
* @brief Miscllaneous utility functions and macros. * @brief Miscllaneous utility functions and macros.
*/ */
#ifndef _json_util_h_ #ifndef _json_util_h_
#define _json_util_h_ #define _json_util_h_
#include "json_object.h" #include "json_object.h"
#ifndef json_min #ifndef json_min
#define json_min(a,b) ((a) < (b) ? (a) : (b)) #define json_min(a, b) ((a) < (b) ? (a) : (b))
#endif #endif
#ifndef json_max #ifndef json_max
#define json_max(a,b) ((a) > (b) ? (a) : (b)) #define json_max(a, b) ((a) > (b) ? (a) : (b))
#endif #endif
#ifdef __cplusplus #ifdef __cplusplus
extern "C" { extern "C" {
#endif #endif
@@ -38,9 +37,9 @@ extern "C" {
* Read the full contents of the given file, then convert it to a * Read the full contents of the given file, then convert it to a
* json_object using json_tokener_parse(). * json_object using json_tokener_parse().
* *
* Returns -1 if something fails. See json_util_get_last_err() for details. * Returns NULL on failure. See json_util_get_last_err() for details.
*/ */
extern struct json_object* json_object_from_file(const char *filename); JSON_EXPORT struct json_object *json_object_from_file(const char *filename);
/** /**
* Create a JSON object from already opened file descriptor. * Create a JSON object from already opened file descriptor.
@@ -50,9 +49,21 @@ extern struct json_object* json_object_from_file(const char *filename);
* Note, that the fd must be readable at the actual position, i.e. * Note, that the fd must be readable at the actual position, i.e.
* use lseek(fd, 0, SEEK_SET) before. * use lseek(fd, 0, SEEK_SET) before.
* *
* Returns -1 if something fails. See json_util_get_last_err() for details. * The depth argument specifies the maximum object depth to pass to
* json_tokener_new_ex(). When depth == -1, JSON_TOKENER_DEFAULT_DEPTH
* is used instead.
*
* Returns NULL on failure. See json_util_get_last_err() for details.
*/ */
extern struct json_object* json_object_from_fd(int fd); JSON_EXPORT struct json_object *json_object_from_fd_ex(int fd, int depth);
/**
* Create a JSON object from an already opened file descriptor, using
* the default maximum object depth. (JSON_TOKENER_DEFAULT_DEPTH)
*
* See json_object_from_fd_ex() for details.
*/
JSON_EXPORT struct json_object *json_object_from_fd(int fd);
/** /**
* Equivalent to: * Equivalent to:
@@ -60,7 +71,7 @@ extern struct json_object* json_object_from_fd(int fd);
* *
* Returns -1 if something fails. See json_util_get_last_err() for details. * Returns -1 if something fails. See json_util_get_last_err() for details.
*/ */
extern int json_object_to_file(const char *filename, struct json_object *obj); JSON_EXPORT int json_object_to_file(const char *filename, struct json_object *obj);
/** /**
* Open and truncate the given file, creating it if necessary, then * Open and truncate the given file, creating it if necessary, then
@@ -68,7 +79,7 @@ extern int json_object_to_file(const char *filename, struct json_object *obj);
* *
* Returns -1 if something fails. See json_util_get_last_err() for details. * Returns -1 if something fails. See json_util_get_last_err() for details.
*/ */
extern int json_object_to_file_ext(const char *filename, struct json_object *obj, int flags); JSON_EXPORT int json_object_to_file_ext(const char *filename, struct json_object *obj, int flags);
/** /**
* Convert the json_object to a string and write it to the file descriptor. * Convert the json_object to a string and write it to the file descriptor.
@@ -80,24 +91,37 @@ extern int json_object_to_file_ext(const char *filename, struct json_object *obj
* @param flags flags to pass to json_object_to_json_string_ext() * @param flags flags to pass to json_object_to_json_string_ext()
* @return -1 if something fails. See json_util_get_last_err() for details. * @return -1 if something fails. See json_util_get_last_err() for details.
*/ */
extern int json_object_to_fd(int fd, struct json_object *obj, int flags); JSON_EXPORT int json_object_to_fd(int fd, struct json_object *obj, int flags);
/** /**
* Return the last error from various json-c functions, including: * Return the last error from various json-c functions, including:
* json_object_to_file{,_ext}, json_object_to_fd() or * json_object_to_file{,_ext}, json_object_to_fd() or
* json_object_from_{file,fd}, or NULL if there is none. * json_object_from_{file,fd}, or NULL if there is none.
*/ */
const char *json_util_get_last_err(void); JSON_EXPORT const char *json_util_get_last_err(void);
/**
extern int json_parse_int64(const char *buf, int64_t *retval); * A parsing helper for integer values. Returns 0 on success,
extern int json_parse_double(const char *buf, double *retval); * with the parsed value assigned to *retval. Overflow/underflow
* are NOT considered errors, but errno will be set to ERANGE,
* just like the strtol/strtoll functions do.
*/
JSON_EXPORT int json_parse_int64(const char *buf, int64_t *retval);
/**
* A parsing help for integer values, providing one extra bit of
* magnitude beyond json_parse_int64().
*/
JSON_EXPORT int json_parse_uint64(const char *buf, uint64_t *retval);
/**
* @deprecated
*/
JSON_EXPORT int json_parse_double(const char *buf, double *retval);
/** /**
* Return a string describing the type of the object. * Return a string describing the type of the object.
* e.g. "int", or "object", etc... * e.g. "int", or "object", etc...
*/ */
extern const char *json_type_to_name(enum json_type o_type); JSON_EXPORT const char *json_type_to_name(enum json_type o_type);
#ifdef __cplusplus #ifdef __cplusplus
} }

View File

@@ -13,45 +13,39 @@
#include "json_visit.h" #include "json_visit.h"
#include "linkhash.h" #include "linkhash.h"
static int _json_c_visit(json_object *jso, json_object *parent_jso, static int _json_c_visit(json_object *jso, json_object *parent_jso, const char *jso_key,
const char *jso_key, size_t *jso_index, size_t *jso_index, json_c_visit_userfunc *userfunc, void *userarg);
json_c_visit_userfunc *userfunc, void *userarg);
int json_c_visit(json_object *jso, int future_flags, int json_c_visit(json_object *jso, int future_flags, json_c_visit_userfunc *userfunc, void *userarg)
json_c_visit_userfunc *userfunc, void *userarg)
{ {
int ret = _json_c_visit(jso, NULL, NULL, NULL, userfunc, userarg); int ret = _json_c_visit(jso, NULL, NULL, NULL, userfunc, userarg);
switch(ret) switch (ret)
{ {
case JSON_C_VISIT_RETURN_CONTINUE: case JSON_C_VISIT_RETURN_CONTINUE:
case JSON_C_VISIT_RETURN_SKIP: case JSON_C_VISIT_RETURN_SKIP:
case JSON_C_VISIT_RETURN_POP: case JSON_C_VISIT_RETURN_POP:
case JSON_C_VISIT_RETURN_STOP: case JSON_C_VISIT_RETURN_STOP: return 0;
return 0; default: return JSON_C_VISIT_RETURN_ERROR;
default:
return JSON_C_VISIT_RETURN_ERROR;
} }
} }
static int _json_c_visit(json_object *jso, json_object *parent_jso, static int _json_c_visit(json_object *jso, json_object *parent_jso, const char *jso_key,
const char *jso_key, size_t *jso_index, size_t *jso_index, json_c_visit_userfunc *userfunc, void *userarg)
json_c_visit_userfunc *userfunc, void *userarg)
{ {
int userret = userfunc(jso, 0, parent_jso, jso_key, jso_index, userarg); int userret = userfunc(jso, 0, parent_jso, jso_key, jso_index, userarg);
switch(userret) switch (userret)
{ {
case JSON_C_VISIT_RETURN_CONTINUE: case JSON_C_VISIT_RETURN_CONTINUE: break;
break;
case JSON_C_VISIT_RETURN_SKIP: case JSON_C_VISIT_RETURN_SKIP:
case JSON_C_VISIT_RETURN_POP: case JSON_C_VISIT_RETURN_POP:
case JSON_C_VISIT_RETURN_STOP: case JSON_C_VISIT_RETURN_STOP:
case JSON_C_VISIT_RETURN_ERROR: case JSON_C_VISIT_RETURN_ERROR: return userret;
return userret;
default: default:
fprintf(stderr, "ERROR: invalid return value from json_c_visit userfunc: %d\n", userret); fprintf(stderr, "ERROR: invalid return value from json_c_visit userfunc: %d\n",
userret);
return JSON_C_VISIT_RETURN_ERROR; return JSON_C_VISIT_RETURN_ERROR;
} }
switch(json_object_get_type(jso)) switch (json_object_get_type(jso))
{ {
case json_type_null: case json_type_null:
case json_type_boolean: case json_type_boolean:
@@ -69,12 +63,13 @@ static int _json_c_visit(json_object *jso, json_object *parent_jso,
if (userret == JSON_C_VISIT_RETURN_POP) if (userret == JSON_C_VISIT_RETURN_POP)
break; break;
if (userret == JSON_C_VISIT_RETURN_STOP || if (userret == JSON_C_VISIT_RETURN_STOP ||
userret == JSON_C_VISIT_RETURN_ERROR) userret == JSON_C_VISIT_RETURN_ERROR)
return userret; return userret;
if (userret != JSON_C_VISIT_RETURN_CONTINUE && if (userret != JSON_C_VISIT_RETURN_CONTINUE &&
userret != JSON_C_VISIT_RETURN_SKIP) userret != JSON_C_VISIT_RETURN_SKIP)
{ {
fprintf(stderr, "INTERNAL ERROR: _json_c_visit returned %d\n", userret); fprintf(stderr, "INTERNAL ERROR: _json_c_visit returned %d\n",
userret);
return JSON_C_VISIT_RETURN_ERROR; return JSON_C_VISIT_RETURN_ERROR;
} }
} }
@@ -91,19 +86,21 @@ static int _json_c_visit(json_object *jso, json_object *parent_jso,
if (userret == JSON_C_VISIT_RETURN_POP) if (userret == JSON_C_VISIT_RETURN_POP)
break; break;
if (userret == JSON_C_VISIT_RETURN_STOP || if (userret == JSON_C_VISIT_RETURN_STOP ||
userret == JSON_C_VISIT_RETURN_ERROR) userret == JSON_C_VISIT_RETURN_ERROR)
return userret; return userret;
if (userret != JSON_C_VISIT_RETURN_CONTINUE && if (userret != JSON_C_VISIT_RETURN_CONTINUE &&
userret != JSON_C_VISIT_RETURN_SKIP) userret != JSON_C_VISIT_RETURN_SKIP)
{ {
fprintf(stderr, "INTERNAL ERROR: _json_c_visit returned %d\n", userret); fprintf(stderr, "INTERNAL ERROR: _json_c_visit returned %d\n",
userret);
return JSON_C_VISIT_RETURN_ERROR; return JSON_C_VISIT_RETURN_ERROR;
} }
} }
break; break;
} }
default: default:
fprintf(stderr, "INTERNAL ERROR: _json_c_visit found object of unknown type: %d\n", json_object_get_type(jso)); fprintf(stderr, "INTERNAL ERROR: _json_c_visit found object of unknown type: %d\n",
json_object_get_type(jso));
return JSON_C_VISIT_RETURN_ERROR; return JSON_C_VISIT_RETURN_ERROR;
} }
@@ -112,22 +109,20 @@ static int _json_c_visit(json_object *jso, json_object *parent_jso,
// Non-container types will have already returned before this point. // Non-container types will have already returned before this point.
userret = userfunc(jso, JSON_C_VISIT_SECOND, parent_jso, jso_key, jso_index, userarg); userret = userfunc(jso, JSON_C_VISIT_SECOND, parent_jso, jso_key, jso_index, userarg);
switch(userret) switch (userret)
{ {
case JSON_C_VISIT_RETURN_SKIP: case JSON_C_VISIT_RETURN_SKIP:
case JSON_C_VISIT_RETURN_POP: case JSON_C_VISIT_RETURN_POP:
// These are not really sensible during JSON_C_VISIT_SECOND, // These are not really sensible during JSON_C_VISIT_SECOND,
// but map them to JSON_C_VISIT_CONTINUE anyway. // but map them to JSON_C_VISIT_CONTINUE anyway.
// FALLTHROUGH // FALLTHROUGH
case JSON_C_VISIT_RETURN_CONTINUE: case JSON_C_VISIT_RETURN_CONTINUE: return JSON_C_VISIT_RETURN_CONTINUE;
return JSON_C_VISIT_RETURN_CONTINUE;
case JSON_C_VISIT_RETURN_STOP: case JSON_C_VISIT_RETURN_STOP:
case JSON_C_VISIT_RETURN_ERROR: case JSON_C_VISIT_RETURN_ERROR: return userret;
return userret;
default: default:
fprintf(stderr, "ERROR: invalid return value from json_c_visit userfunc: %d\n", userret); fprintf(stderr, "ERROR: invalid return value from json_c_visit userfunc: %d\n",
userret);
return JSON_C_VISIT_RETURN_ERROR; return JSON_C_VISIT_RETURN_ERROR;
} }
// NOTREACHED // NOTREACHED
} }

View File

@@ -8,9 +8,12 @@
*/ */
#include "json_object.h" #include "json_object.h"
typedef int (json_c_visit_userfunc)(json_object *jso, int flags, #ifdef __cplusplus
json_object *parent_jso, const char *jso_key, extern "C" {
size_t *jso_index, void *userarg); #endif
typedef int(json_c_visit_userfunc)(json_object *jso, int flags, json_object *parent_jso,
const char *jso_key, size_t *jso_index, void *userarg);
/** /**
* Visit each object in the JSON hierarchy starting at jso. * Visit each object in the JSON hierarchy starting at jso.
@@ -26,20 +29,20 @@ typedef int (json_c_visit_userfunc)(json_object *jso, int flags,
* userfunc must return one of the defined return values, to indicate * userfunc must return one of the defined return values, to indicate
* whether and how to continue visiting nodes, or one of various ways to stop. * whether and how to continue visiting nodes, or one of various ways to stop.
* *
* Returns 0 if nodes were visited successfully, even if some were * Returns 0 if nodes were visited successfully, even if some were
* intentionally skipped due to what userfunc returned. * intentionally skipped due to what userfunc returned.
* Returns <0 if an error occurred during iteration, including if * Returns <0 if an error occurred during iteration, including if
* userfunc returned JSON_C_VISIT_RETURN_ERROR. * userfunc returned JSON_C_VISIT_RETURN_ERROR.
*/ */
int json_c_visit(json_object *jso, int future_flags, JSON_EXPORT int json_c_visit(json_object *jso, int future_flags, json_c_visit_userfunc *userfunc,
json_c_visit_userfunc *userfunc, void *userarg); void *userarg);
/** /**
* Passed to json_c_visit_userfunc as one of the flags values to indicate * Passed to json_c_visit_userfunc as one of the flags values to indicate
* that this is the second time a container (array or object) is being * that this is the second time a container (array or object) is being
* called, after all of it's members have been iterated over. * called, after all of it's members have been iterated over.
*/ */
#define JSON_C_VISIT_SECOND 0x02 #define JSON_C_VISIT_SECOND 0x02
/** /**
* This json_c_visit_userfunc return value indicates that iteration * This json_c_visit_userfunc return value indicates that iteration
@@ -47,7 +50,6 @@ int json_c_visit(json_object *jso, int future_flags,
*/ */
#define JSON_C_VISIT_RETURN_CONTINUE 0 #define JSON_C_VISIT_RETURN_CONTINUE 0
/** /**
* This json_c_visit_userfunc return value indicates that iteration * This json_c_visit_userfunc return value indicates that iteration
* over the members of the current object should be skipped. * over the members of the current object should be skipped.
@@ -60,7 +62,7 @@ int json_c_visit(json_object *jso, int future_flags,
* This json_c_visit_userfunc return value indicates that iteration * This json_c_visit_userfunc return value indicates that iteration
* of the fields/elements of the <b>containing</b> object should stop * of the fields/elements of the <b>containing</b> object should stop
* and continue "popped up" a level of the object hierarchy. * and continue "popped up" a level of the object hierarchy.
* For example, returning this when handling arg will result in * For example, returning this when handling arg will result in
* arg3 and any other fields being skipped. The next call to userfunc * arg3 and any other fields being skipped. The next call to userfunc
* will be the JSON_C_VISIT_SECOND call on "foo", followed by a userfunc * will be the JSON_C_VISIT_SECOND call on "foo", followed by a userfunc
* call on "bar". * call on "bar".
@@ -92,4 +94,8 @@ int json_c_visit(json_object *jso, int future_flags,
*/ */
#define JSON_C_VISIT_RETURN_ERROR -1 #define JSON_C_VISIT_RETURN_ERROR -1
#ifdef __cplusplus
}
#endif
#endif /* _json_c_json_visit_h_ */ #endif /* _json_c_json_visit_h_ */

View File

@@ -7,13 +7,13 @@
#ifndef __warn_references #ifndef __warn_references
#if defined(__GNUC__) && defined (HAS_GNU_WARNING_LONG) #if defined(__GNUC__) && defined(HAS_GNU_WARNING_LONG)
#define __warn_references(sym,msg) \ #define __warn_references(sym, msg) \
__asm__(".section .gnu" #sym ",\n\t.ascii \"" msg "\"\n\t.text"); __asm__(".section .gnu" #sym ",\n\t.ascii \"" msg "\"\n\t.text");
#else #else
#define __warn_references(sym,msg) /* nothing */ #define __warn_references(sym, msg) /* nothing */
#endif #endif
#endif #endif

View File

@@ -12,55 +12,46 @@
#include "config.h" #include "config.h"
#include <stdio.h> #include <assert.h>
#include <string.h> #include <limits.h>
#include <stdlib.h>
#include <stdarg.h> #include <stdarg.h>
#include <stddef.h> #include <stddef.h>
#include <limits.h> #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef HAVE_ENDIAN_H #ifdef HAVE_ENDIAN_H
# include <endian.h> /* attempt to define endianness */ #include <endian.h> /* attempt to define endianness */
#endif #endif
#if defined(_MSC_VER) || defined(__MINGW32__) #if defined(_MSC_VER) || defined(__MINGW32__)
# define WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN
# include <windows.h> /* Get InterlockedCompareExchange */ #include <windows.h> /* Get InterlockedCompareExchange */
#endif #endif
#include "random_seed.h"
#include "linkhash.h" #include "linkhash.h"
#include "random_seed.h"
/* hash functions */ /* hash functions */
static unsigned long lh_char_hash(const void *k); static unsigned long lh_char_hash(const void *k);
static unsigned long lh_perllike_str_hash(const void *k); static unsigned long lh_perllike_str_hash(const void *k);
static lh_hash_fn *char_hash_fn = lh_char_hash; static lh_hash_fn *char_hash_fn = lh_char_hash;
int /* comparison functions */
json_global_set_string_hash(const int h) int lh_char_equal(const void *k1, const void *k2);
int lh_ptr_equal(const void *k1, const void *k2);
int json_global_set_string_hash(const int h)
{ {
switch(h) { switch (h)
case JSON_C_STR_HASH_DFLT: {
char_hash_fn = lh_char_hash; case JSON_C_STR_HASH_DFLT: char_hash_fn = lh_char_hash; break;
break; case JSON_C_STR_HASH_PERLLIKE: char_hash_fn = lh_perllike_str_hash; break;
case JSON_C_STR_HASH_PERLLIKE: default: return -1;
char_hash_fn = lh_perllike_str_hash;
break;
default:
return -1;
} }
return 0; return 0;
} }
void lh_abort(const char *msg, ...)
{
va_list ap;
va_start(ap, msg);
vprintf(msg, ap);
va_end(ap);
exit(1);
}
static unsigned long lh_ptr_hash(const void *k) static unsigned long lh_ptr_hash(const void *k)
{ {
/* CAW: refactored to be 64bit nice */ /* CAW: refactored to be 64bit nice */
@@ -74,9 +65,9 @@ int lh_ptr_equal(const void *k1, const void *k2)
/* /*
* hashlittle from lookup3.c, by Bob Jenkins, May 2006, Public Domain. * hashlittle from lookup3.c, by Bob Jenkins, May 2006, Public Domain.
* http://burtleburtle.net/bob/c/lookup3.c * https://burtleburtle.net/bob/c/lookup3.c
* minor modifications to make functions static so no symbols are exported * minor modifications to make functions static so no symbols are exported
* minor mofifications to compile with -Werror * minor modifications to compile with -Werror
*/ */
/* /*
@@ -90,7 +81,7 @@ if SELF_TEST is defined. You can use this free for any purpose. It's in
the public domain. It has no warranty. the public domain. It has no warranty.
You probably want to use hashlittle(). hashlittle() and hashbig() You probably want to use hashlittle(). hashlittle() and hashbig()
hash byte arrays. hashlittle() is is faster than hashbig() on hash byte arrays. hashlittle() is faster than hashbig() on
little-endian machines. Intel and AMD are little-endian machines. little-endian machines. Intel and AMD are little-endian machines.
On second thought, you probably want hashlittle2(), which is identical to On second thought, you probably want hashlittle2(), which is identical to
hashlittle() except it returns two 32-bit hashes for the price of one. hashlittle() except it returns two 32-bit hashes for the price of one.
@@ -119,25 +110,23 @@ on 1 byte), but shoehorning those bytes into integers efficiently is messy.
* My best guess at if you are big-endian or little-endian. This may * My best guess at if you are big-endian or little-endian. This may
* need adjustment. * need adjustment.
*/ */
#if (defined(__BYTE_ORDER) && defined(__LITTLE_ENDIAN) && \ #if (defined(__BYTE_ORDER) && defined(__LITTLE_ENDIAN) && __BYTE_ORDER == __LITTLE_ENDIAN) || \
__BYTE_ORDER == __LITTLE_ENDIAN) || \ (defined(i386) || defined(__i386__) || defined(__i486__) || defined(__i586__) || \
(defined(i386) || defined(__i386__) || defined(__i486__) || \ defined(__i686__) || defined(vax) || defined(MIPSEL))
defined(__i586__) || defined(__i686__) || defined(vax) || defined(MIPSEL)) #define HASH_LITTLE_ENDIAN 1
# define HASH_LITTLE_ENDIAN 1 #define HASH_BIG_ENDIAN 0
# define HASH_BIG_ENDIAN 0 #elif (defined(__BYTE_ORDER) && defined(__BIG_ENDIAN) && __BYTE_ORDER == __BIG_ENDIAN) || \
#elif (defined(__BYTE_ORDER) && defined(__BIG_ENDIAN) && \ (defined(sparc) || defined(POWERPC) || defined(mc68000) || defined(sel))
__BYTE_ORDER == __BIG_ENDIAN) || \ #define HASH_LITTLE_ENDIAN 0
(defined(sparc) || defined(POWERPC) || defined(mc68000) || defined(sel)) #define HASH_BIG_ENDIAN 1
# define HASH_LITTLE_ENDIAN 0
# define HASH_BIG_ENDIAN 1
#else #else
# define HASH_LITTLE_ENDIAN 0 #define HASH_LITTLE_ENDIAN 0
# define HASH_BIG_ENDIAN 0 #define HASH_BIG_ENDIAN 0
#endif #endif
#define hashsize(n) ((uint32_t)1<<(n)) #define hashsize(n) ((uint32_t)1 << (n))
#define hashmask(n) (hashsize(n)-1) #define hashmask(n) (hashsize(n) - 1)
#define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k)))) #define rot(x, k) (((x) << (k)) | ((x) >> (32 - (k))))
/* /*
------------------------------------------------------------------------------- -------------------------------------------------------------------------------
@@ -167,7 +156,7 @@ satisfy this are
14 9 3 7 17 3 14 9 3 7 17 3
Well, "9 15 3 18 27 15" didn't quite get 32 bits diffing Well, "9 15 3 18 27 15" didn't quite get 32 bits diffing
for "differ" defined as + with a one-bit base and a two-bit delta. I for "differ" defined as + with a one-bit base and a two-bit delta. I
used http://burtleburtle.net/bob/hash/avalanche.html to choose used https://burtleburtle.net/bob/hash/avalanche.html to choose
the operations, constants, and arrangements of the variables. the operations, constants, and arrangements of the variables.
This does not achieve avalanche. There are input bits of (a,b,c) This does not achieve avalanche. There are input bits of (a,b,c)
@@ -183,15 +172,17 @@ on, and rotates are much kinder to the top and bottom bits, so I used
rotates. rotates.
------------------------------------------------------------------------------- -------------------------------------------------------------------------------
*/ */
/* clang-format off */
#define mix(a,b,c) \ #define mix(a,b,c) \
{ \ { \
a -= c; a ^= rot(c, 4); c += b; \ a -= c; a ^= rot(c, 4); c += b; \
b -= a; b ^= rot(a, 6); a += c; \ b -= a; b ^= rot(a, 6); a += c; \
c -= b; c ^= rot(b, 8); b += a; \ c -= b; c ^= rot(b, 8); b += a; \
a -= c; a ^= rot(c,16); c += b; \ a -= c; a ^= rot(c,16); c += b; \
b -= a; b ^= rot(a,19); a += c; \ b -= a; b ^= rot(a,19); a += c; \
c -= b; c ^= rot(b, 4); b += a; \ c -= b; c ^= rot(b, 4); b += a; \
} }
/* clang-format on */
/* /*
------------------------------------------------------------------------------- -------------------------------------------------------------------------------
@@ -218,17 +209,18 @@ and these came close:
11 8 15 26 3 22 24 11 8 15 26 3 22 24
------------------------------------------------------------------------------- -------------------------------------------------------------------------------
*/ */
/* clang-format off */
#define final(a,b,c) \ #define final(a,b,c) \
{ \ { \
c ^= b; c -= rot(b,14); \ c ^= b; c -= rot(b,14); \
a ^= c; a -= rot(c,11); \ a ^= c; a -= rot(c,11); \
b ^= a; b -= rot(a,25); \ b ^= a; b -= rot(a,25); \
c ^= b; c -= rot(b,16); \ c ^= b; c -= rot(b,16); \
a ^= c; a -= rot(c,4); \ a ^= c; a -= rot(c,4); \
b ^= a; b -= rot(a,14); \ b ^= a; b -= rot(a,14); \
c ^= b; c -= rot(b,24); \ c ^= b; c -= rot(b,24); \
} }
/* clang-format on */
/* /*
------------------------------------------------------------------------------- -------------------------------------------------------------------------------
@@ -257,197 +249,208 @@ acceptable. Do NOT use for cryptographic purposes.
------------------------------------------------------------------------------- -------------------------------------------------------------------------------
*/ */
static uint32_t hashlittle( const void *key, size_t length, uint32_t initval) /* clang-format off */
static uint32_t hashlittle(const void *key, size_t length, uint32_t initval)
{ {
uint32_t a,b,c; /* internal state */ uint32_t a,b,c; /* internal state */
union { const void *ptr; size_t i; } u; /* needed for Mac Powerbook G4 */ union
{
const void *ptr;
size_t i;
} u; /* needed for Mac Powerbook G4 */
/* Set up the internal state */ /* Set up the internal state */
a = b = c = 0xdeadbeef + ((uint32_t)length) + initval; a = b = c = 0xdeadbeef + ((uint32_t)length) + initval;
u.ptr = key; u.ptr = key;
if (HASH_LITTLE_ENDIAN && ((u.i & 0x3) == 0)) { if (HASH_LITTLE_ENDIAN && ((u.i & 0x3) == 0)) {
const uint32_t *k = (const uint32_t *)key; /* read 32-bit chunks */ const uint32_t *k = (const uint32_t *)key; /* read 32-bit chunks */
/*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */ /*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */
while (length > 12) while (length > 12)
{ {
a += k[0]; a += k[0];
b += k[1]; b += k[1];
c += k[2]; c += k[2];
mix(a,b,c); mix(a,b,c);
length -= 12; length -= 12;
k += 3; k += 3;
} }
/*----------------------------- handle the last (probably partial) block */ /*----------------------------- handle the last (probably partial) block */
/* /*
* "k[2]&0xffffff" actually reads beyond the end of the string, but * "k[2]&0xffffff" actually reads beyond the end of the string, but
* then masks off the part it's not allowed to read. Because the * then masks off the part it's not allowed to read. Because the
* string is aligned, the masked-off tail is in the same word as the * string is aligned, the masked-off tail is in the same word as the
* rest of the string. Every machine with memory protection I've seen * rest of the string. Every machine with memory protection I've seen
* does it on word boundaries, so is OK with this. But VALGRIND will * does it on word boundaries, so is OK with this. But VALGRIND will
* still catch it and complain. The masking trick does make the hash * still catch it and complain. The masking trick does make the hash
* noticably faster for short strings (like English words). * noticeably faster for short strings (like English words).
* AddressSanitizer is similarly picky about overrunning * AddressSanitizer is similarly picky about overrunning
* the buffer. (http://clang.llvm.org/docs/AddressSanitizer.html * the buffer. (https://clang.llvm.org/docs/AddressSanitizer.html)
*/ */
#ifdef VALGRIND #ifdef VALGRIND
# define PRECISE_MEMORY_ACCESS 1 #define PRECISE_MEMORY_ACCESS 1
#elif defined(__SANITIZE_ADDRESS__) /* GCC's ASAN */ #elif defined(__SANITIZE_ADDRESS__) /* GCC's ASAN */
# define PRECISE_MEMORY_ACCESS 1 #define PRECISE_MEMORY_ACCESS 1
#elif defined(__has_feature) #elif defined(__has_feature)
# if __has_feature(address_sanitizer) /* Clang's ASAN */ #if __has_feature(address_sanitizer) /* Clang's ASAN */
# define PRECISE_MEMORY_ACCESS 1 #define PRECISE_MEMORY_ACCESS 1
# endif #endif
#endif #endif
#ifndef PRECISE_MEMORY_ACCESS #ifndef PRECISE_MEMORY_ACCESS
switch(length) switch(length)
{ {
case 12: c+=k[2]; b+=k[1]; a+=k[0]; break; case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
case 11: c+=k[2]&0xffffff; b+=k[1]; a+=k[0]; break; case 11: c+=k[2]&0xffffff; b+=k[1]; a+=k[0]; break;
case 10: c+=k[2]&0xffff; b+=k[1]; a+=k[0]; break; case 10: c+=k[2]&0xffff; b+=k[1]; a+=k[0]; break;
case 9 : c+=k[2]&0xff; b+=k[1]; a+=k[0]; break; case 9 : c+=k[2]&0xff; b+=k[1]; a+=k[0]; break;
case 8 : b+=k[1]; a+=k[0]; break; case 8 : b+=k[1]; a+=k[0]; break;
case 7 : b+=k[1]&0xffffff; a+=k[0]; break; case 7 : b+=k[1]&0xffffff; a+=k[0]; break;
case 6 : b+=k[1]&0xffff; a+=k[0]; break; case 6 : b+=k[1]&0xffff; a+=k[0]; break;
case 5 : b+=k[1]&0xff; a+=k[0]; break; case 5 : b+=k[1]&0xff; a+=k[0]; break;
case 4 : a+=k[0]; break; case 4 : a+=k[0]; break;
case 3 : a+=k[0]&0xffffff; break; case 3 : a+=k[0]&0xffffff; break;
case 2 : a+=k[0]&0xffff; break; case 2 : a+=k[0]&0xffff; break;
case 1 : a+=k[0]&0xff; break; case 1 : a+=k[0]&0xff; break;
case 0 : return c; /* zero length strings require no mixing */ case 0 : return c; /* zero length strings require no mixing */
} }
#else /* make valgrind happy */ #else /* make valgrind happy */
const uint8_t *k8 = (const uint8_t *)k; const uint8_t *k8 = (const uint8_t *)k;
switch(length) switch(length)
{ {
case 12: c+=k[2]; b+=k[1]; a+=k[0]; break; case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
case 11: c+=((uint32_t)k8[10])<<16; /* fall through */ case 11: c+=((uint32_t)k8[10])<<16; /* fall through */
case 10: c+=((uint32_t)k8[9])<<8; /* fall through */ case 10: c+=((uint32_t)k8[9])<<8; /* fall through */
case 9 : c+=k8[8]; /* fall through */ case 9 : c+=k8[8]; /* fall through */
case 8 : b+=k[1]; a+=k[0]; break; case 8 : b+=k[1]; a+=k[0]; break;
case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */ case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */
case 6 : b+=((uint32_t)k8[5])<<8; /* fall through */ case 6 : b+=((uint32_t)k8[5])<<8; /* fall through */
case 5 : b+=k8[4]; /* fall through */ case 5 : b+=k8[4]; /* fall through */
case 4 : a+=k[0]; break; case 4 : a+=k[0]; break;
case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */ case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */
case 2 : a+=((uint32_t)k8[1])<<8; /* fall through */ case 2 : a+=((uint32_t)k8[1])<<8; /* fall through */
case 1 : a+=k8[0]; break; case 1 : a+=k8[0]; break;
case 0 : return c; case 0 : return c;
} }
#endif /* !valgrind */ #endif /* !valgrind */
} else if (HASH_LITTLE_ENDIAN && ((u.i & 0x1) == 0)) { }
const uint16_t *k = (const uint16_t *)key; /* read 16-bit chunks */ else if (HASH_LITTLE_ENDIAN && ((u.i & 0x1) == 0))
const uint8_t *k8; {
const uint16_t *k = (const uint16_t *)key; /* read 16-bit chunks */
const uint8_t *k8;
/*--------------- all but last block: aligned reads and different mixing */ /*--------------- all but last block: aligned reads and different mixing */
while (length > 12) while (length > 12)
{ {
a += k[0] + (((uint32_t)k[1])<<16); a += k[0] + (((uint32_t)k[1])<<16);
b += k[2] + (((uint32_t)k[3])<<16); b += k[2] + (((uint32_t)k[3])<<16);
c += k[4] + (((uint32_t)k[5])<<16); c += k[4] + (((uint32_t)k[5])<<16);
mix(a,b,c); mix(a,b,c);
length -= 12; length -= 12;
k += 6; k += 6;
} }
/*----------------------------- handle the last (probably partial) block */ /*----------------------------- handle the last (probably partial) block */
k8 = (const uint8_t *)k; k8 = (const uint8_t *)k;
switch(length) switch(length)
{ {
case 12: c+=k[4]+(((uint32_t)k[5])<<16); case 12: c+=k[4]+(((uint32_t)k[5])<<16);
b+=k[2]+(((uint32_t)k[3])<<16); b+=k[2]+(((uint32_t)k[3])<<16);
a+=k[0]+(((uint32_t)k[1])<<16); a+=k[0]+(((uint32_t)k[1])<<16);
break; break;
case 11: c+=((uint32_t)k8[10])<<16; /* fall through */ case 11: c+=((uint32_t)k8[10])<<16; /* fall through */
case 10: c+=k[4]; case 10: c+=k[4];
b+=k[2]+(((uint32_t)k[3])<<16); b+=k[2]+(((uint32_t)k[3])<<16);
a+=k[0]+(((uint32_t)k[1])<<16); a+=k[0]+(((uint32_t)k[1])<<16);
break; break;
case 9 : c+=k8[8]; /* fall through */ case 9 : c+=k8[8]; /* fall through */
case 8 : b+=k[2]+(((uint32_t)k[3])<<16); case 8 : b+=k[2]+(((uint32_t)k[3])<<16);
a+=k[0]+(((uint32_t)k[1])<<16); a+=k[0]+(((uint32_t)k[1])<<16);
break; break;
case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */ case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */
case 6 : b+=k[2]; case 6 : b+=k[2];
a+=k[0]+(((uint32_t)k[1])<<16); a+=k[0]+(((uint32_t)k[1])<<16);
break; break;
case 5 : b+=k8[4]; /* fall through */ case 5 : b+=k8[4]; /* fall through */
case 4 : a+=k[0]+(((uint32_t)k[1])<<16); case 4 : a+=k[0]+(((uint32_t)k[1])<<16);
break; break;
case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */ case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */
case 2 : a+=k[0]; case 2 : a+=k[0];
break; break;
case 1 : a+=k8[0]; case 1 : a+=k8[0];
break; break;
case 0 : return c; /* zero length requires no mixing */ case 0 : return c; /* zero length requires no mixing */
} }
} else { /* need to read the key one byte at a time */ }
const uint8_t *k = (const uint8_t *)key; else
{
/* need to read the key one byte at a time */
const uint8_t *k = (const uint8_t *)key;
/*--------------- all but the last block: affect some 32 bits of (a,b,c) */ /*--------------- all but the last block: affect some 32 bits of (a,b,c) */
while (length > 12) while (length > 12)
{ {
a += k[0]; a += k[0];
a += ((uint32_t)k[1])<<8; a += ((uint32_t)k[1])<<8;
a += ((uint32_t)k[2])<<16; a += ((uint32_t)k[2])<<16;
a += ((uint32_t)k[3])<<24; a += ((uint32_t)k[3])<<24;
b += k[4]; b += k[4];
b += ((uint32_t)k[5])<<8; b += ((uint32_t)k[5])<<8;
b += ((uint32_t)k[6])<<16; b += ((uint32_t)k[6])<<16;
b += ((uint32_t)k[7])<<24; b += ((uint32_t)k[7])<<24;
c += k[8]; c += k[8];
c += ((uint32_t)k[9])<<8; c += ((uint32_t)k[9])<<8;
c += ((uint32_t)k[10])<<16; c += ((uint32_t)k[10])<<16;
c += ((uint32_t)k[11])<<24; c += ((uint32_t)k[11])<<24;
mix(a,b,c); mix(a,b,c);
length -= 12; length -= 12;
k += 12; k += 12;
} }
/*-------------------------------- last block: affect all 32 bits of (c) */ /*-------------------------------- last block: affect all 32 bits of (c) */
switch(length) /* all the case statements fall through */ switch(length) /* all the case statements fall through */
{ {
case 12: c+=((uint32_t)k[11])<<24; /* FALLTHRU */ case 12: c+=((uint32_t)k[11])<<24; /* FALLTHRU */
case 11: c+=((uint32_t)k[10])<<16; /* FALLTHRU */ case 11: c+=((uint32_t)k[10])<<16; /* FALLTHRU */
case 10: c+=((uint32_t)k[9])<<8; /* FALLTHRU */ case 10: c+=((uint32_t)k[9])<<8; /* FALLTHRU */
case 9 : c+=k[8]; /* FALLTHRU */ case 9 : c+=k[8]; /* FALLTHRU */
case 8 : b+=((uint32_t)k[7])<<24; /* FALLTHRU */ case 8 : b+=((uint32_t)k[7])<<24; /* FALLTHRU */
case 7 : b+=((uint32_t)k[6])<<16; /* FALLTHRU */ case 7 : b+=((uint32_t)k[6])<<16; /* FALLTHRU */
case 6 : b+=((uint32_t)k[5])<<8; /* FALLTHRU */ case 6 : b+=((uint32_t)k[5])<<8; /* FALLTHRU */
case 5 : b+=k[4]; /* FALLTHRU */ case 5 : b+=k[4]; /* FALLTHRU */
case 4 : a+=((uint32_t)k[3])<<24; /* FALLTHRU */ case 4 : a+=((uint32_t)k[3])<<24; /* FALLTHRU */
case 3 : a+=((uint32_t)k[2])<<16; /* FALLTHRU */ case 3 : a+=((uint32_t)k[2])<<16; /* FALLTHRU */
case 2 : a+=((uint32_t)k[1])<<8; /* FALLTHRU */ case 2 : a+=((uint32_t)k[1])<<8; /* FALLTHRU */
case 1 : a+=k[0]; case 1 : a+=k[0];
break; break;
case 0 : return c; case 0 : return c;
} }
} }
final(a,b,c); final(a,b,c);
return c; return c;
} }
/* clang-format on */
/* a simple hash function similiar to what perl does for strings. /* a simple hash function similar to what perl does for strings.
* for good results, the string should not be excessivly large. * for good results, the string should not be excessively large.
*/ */
static unsigned long lh_perllike_str_hash(const void *k) static unsigned long lh_perllike_str_hash(const void *k)
{ {
const char *rkey = (const char *)k; const char *rkey = (const char *)k;
unsigned hashval = 1; unsigned hashval = 1;
while (*rkey) while (*rkey)
hashval = hashval * 33 + *rkey++; hashval = hashval * 33 + *rkey++;
return hashval; return hashval;
} }
static unsigned long lh_char_hash(const void *k) static unsigned long lh_char_hash(const void *k)
@@ -459,10 +462,11 @@ static unsigned long lh_char_hash(const void *k)
#endif #endif
static volatile RANDOM_SEED_TYPE random_seed = -1; static volatile RANDOM_SEED_TYPE random_seed = -1;
if (random_seed == -1) { if (random_seed == -1)
{
RANDOM_SEED_TYPE seed; RANDOM_SEED_TYPE seed;
/* we can't use -1 as it is the unitialized sentinel */ /* we can't use -1 as it is the uninitialized sentinel */
while ((seed = json_c_get_random_seed()) == -1); while ((seed = json_c_get_random_seed()) == -1) {}
#if SIZEOF_INT == 8 && defined __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8 #if SIZEOF_INT == 8 && defined __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8
#define USE_SYNC_COMPARE_AND_SWAP 1 #define USE_SYNC_COMPARE_AND_SWAP 1
#endif #endif
@@ -477,34 +481,34 @@ static unsigned long lh_char_hash(const void *k)
#elif defined _MSC_VER || defined __MINGW32__ #elif defined _MSC_VER || defined __MINGW32__
InterlockedCompareExchange(&random_seed, seed, -1); InterlockedCompareExchange(&random_seed, seed, -1);
#else #else
//#warning "racy random seed initializtion if used by multiple threads" //#warning "racy random seed initialization if used by multiple threads"
random_seed = seed; /* potentially racy */ random_seed = seed; /* potentially racy */
#endif #endif
} }
return hashlittle((const char*)k, strlen((const char*)k), random_seed); return hashlittle((const char *)k, strlen((const char *)k), (uint32_t)random_seed);
} }
int lh_char_equal(const void *k1, const void *k2) int lh_char_equal(const void *k1, const void *k2)
{ {
return (strcmp((const char*)k1, (const char*)k2) == 0); return (strcmp((const char *)k1, (const char *)k2) == 0);
} }
struct lh_table* lh_table_new(int size, struct lh_table *lh_table_new(int size, lh_entry_free_fn *free_fn, lh_hash_fn *hash_fn,
lh_entry_free_fn *free_fn, lh_equal_fn *equal_fn)
lh_hash_fn *hash_fn,
lh_equal_fn *equal_fn)
{ {
int i; int i;
struct lh_table *t; struct lh_table *t;
t = (struct lh_table*)calloc(1, sizeof(struct lh_table)); /* Allocate space for elements to avoid divisions by zero. */
assert(size > 0);
t = (struct lh_table *)calloc(1, sizeof(struct lh_table));
if (!t) if (!t)
return NULL; return NULL;
t->count = 0; t->count = 0;
t->size = size; t->size = size;
t->table = (struct lh_entry*)calloc(size, sizeof(struct lh_entry)); t->table = (struct lh_entry *)calloc(size, sizeof(struct lh_entry));
if (!t->table) if (!t->table)
{ {
free(t); free(t);
@@ -513,18 +517,17 @@ struct lh_table* lh_table_new(int size,
t->free_fn = free_fn; t->free_fn = free_fn;
t->hash_fn = hash_fn; t->hash_fn = hash_fn;
t->equal_fn = equal_fn; t->equal_fn = equal_fn;
for(i = 0; i < size; i++) t->table[i].k = LH_EMPTY; for (i = 0; i < size; i++)
t->table[i].k = LH_EMPTY;
return t; return t;
} }
struct lh_table* lh_kchar_table_new(int size, struct lh_table *lh_kchar_table_new(int size, lh_entry_free_fn *free_fn)
lh_entry_free_fn *free_fn)
{ {
return lh_table_new(size, free_fn, char_hash_fn, lh_char_equal); return lh_table_new(size, free_fn, char_hash_fn, lh_char_equal);
} }
struct lh_table* lh_kptr_table_new(int size, struct lh_table *lh_kptr_table_new(int size, lh_entry_free_fn *free_fn)
lh_entry_free_fn *free_fn)
{ {
return lh_table_new(size, free_fn, lh_ptr_hash, lh_ptr_equal); return lh_table_new(size, free_fn, lh_ptr_hash, lh_ptr_equal);
} }
@@ -543,7 +546,7 @@ int lh_table_resize(struct lh_table *t, int new_size)
unsigned long h = lh_get_hash(new_t, ent->k); unsigned long h = lh_get_hash(new_t, ent->k);
unsigned int opts = 0; unsigned int opts = 0;
if (ent->k_is_constant) if (ent->k_is_constant)
opts = JSON_C_OBJECT_KEY_IS_CONSTANT; opts = JSON_C_OBJECT_ADD_CONSTANT_KEY;
if (lh_table_insert_w_hash(new_t, ent->k, ent->v, h, opts) != 0) if (lh_table_insert_w_hash(new_t, ent->k, ent->v, h, opts) != 0)
{ {
lh_table_free(new_t); lh_table_free(new_t);
@@ -563,39 +566,50 @@ int lh_table_resize(struct lh_table *t, int new_size)
void lh_table_free(struct lh_table *t) void lh_table_free(struct lh_table *t)
{ {
struct lh_entry *c; struct lh_entry *c;
if(t->free_fn) { if (t->free_fn)
for(c = t->head; c != NULL; c = c->next) {
for (c = t->head; c != NULL; c = c->next)
t->free_fn(c); t->free_fn(c);
} }
free(t->table); free(t->table);
free(t); free(t);
} }
int lh_table_insert_w_hash(struct lh_table *t, const void *k, const void *v, const unsigned long h,
int lh_table_insert_w_hash(struct lh_table *t, const void *k, const void *v, const unsigned long h, const unsigned opts) const unsigned opts)
{ {
unsigned long n; unsigned long n;
if (t->count >= t->size * LH_LOAD_FACTOR) if (t->count >= t->size * LH_LOAD_FACTOR)
if (lh_table_resize(t, t->size * 2) != 0) {
/* Avoid signed integer overflow with large tables. */
int new_size = (t->size > INT_MAX / 2) ? INT_MAX : (t->size * 2);
if (t->size == INT_MAX || lh_table_resize(t, new_size) != 0)
return -1; return -1;
}
n = h % t->size; n = h % t->size;
while( 1 ) { while (1)
if(t->table[n].k == LH_EMPTY || t->table[n].k == LH_FREED) break; {
if ((int)++n == t->size) n = 0; if (t->table[n].k == LH_EMPTY || t->table[n].k == LH_FREED)
break;
if ((int)++n == t->size)
n = 0;
} }
t->table[n].k = k; t->table[n].k = k;
t->table[n].k_is_constant = (opts & JSON_C_OBJECT_KEY_IS_CONSTANT); t->table[n].k_is_constant = (opts & JSON_C_OBJECT_ADD_CONSTANT_KEY);
t->table[n].v = v; t->table[n].v = v;
t->count++; t->count++;
if(t->head == NULL) { if (t->head == NULL)
{
t->head = t->tail = &t->table[n]; t->head = t->tail = &t->table[n];
t->table[n].next = t->table[n].prev = NULL; t->table[n].next = t->table[n].prev = NULL;
} else { }
else
{
t->tail->next = &t->table[n]; t->tail->next = &t->table[n];
t->table[n].prev = t->tail; t->table[n].prev = t->tail;
t->table[n].next = NULL; t->table[n].next = NULL;
@@ -609,66 +623,78 @@ int lh_table_insert(struct lh_table *t, const void *k, const void *v)
return lh_table_insert_w_hash(t, k, v, lh_get_hash(t, k), 0); return lh_table_insert_w_hash(t, k, v, lh_get_hash(t, k), 0);
} }
struct lh_entry *lh_table_lookup_entry_w_hash(struct lh_table *t, const void *k,
struct lh_entry* lh_table_lookup_entry_w_hash(struct lh_table *t, const void *k, const unsigned long h) const unsigned long h)
{ {
unsigned long n = h % t->size; unsigned long n = h % t->size;
int count = 0; int count = 0;
while( count < t->size ) { while (count < t->size)
if(t->table[n].k == LH_EMPTY) return NULL; {
if(t->table[n].k != LH_FREED && if (t->table[n].k == LH_EMPTY)
t->equal_fn(t->table[n].k, k)) return &t->table[n]; return NULL;
if ((int)++n == t->size) n = 0; if (t->table[n].k != LH_FREED && t->equal_fn(t->table[n].k, k))
return &t->table[n];
if ((int)++n == t->size)
n = 0;
count++; count++;
} }
return NULL; return NULL;
} }
struct lh_entry* lh_table_lookup_entry(struct lh_table *t, const void *k) struct lh_entry *lh_table_lookup_entry(struct lh_table *t, const void *k)
{ {
return lh_table_lookup_entry_w_hash(t, k, lh_get_hash(t, k)); return lh_table_lookup_entry_w_hash(t, k, lh_get_hash(t, k));
} }
const void* lh_table_lookup(struct lh_table *t, const void *k) json_bool lh_table_lookup_ex(struct lh_table *t, const void *k, void **v)
{
void *result;
lh_table_lookup_ex(t, k, &result);
return result;
}
json_bool lh_table_lookup_ex(struct lh_table* t, const void* k, void **v)
{ {
struct lh_entry *e = lh_table_lookup_entry(t, k); struct lh_entry *e = lh_table_lookup_entry(t, k);
if (e != NULL) { if (e != NULL)
if (v != NULL) *v = lh_entry_v(e); {
return TRUE; /* key found */ if (v != NULL)
*v = lh_entry_v(e);
return 1; /* key found */
} }
if (v != NULL) *v = NULL; if (v != NULL)
return FALSE; /* key not found */ *v = NULL;
return 0; /* key not found */
} }
int lh_table_delete_entry(struct lh_table *t, struct lh_entry *e) int lh_table_delete_entry(struct lh_table *t, struct lh_entry *e)
{ {
ptrdiff_t n = (ptrdiff_t)(e - t->table); /* CAW: fixed to be 64bit nice, still need the crazy negative case... */ /* CAW: fixed to be 64bit nice, still need the crazy negative case... */
ptrdiff_t n = (ptrdiff_t)(e - t->table);
/* CAW: this is bad, really bad, maybe stack goes other direction on this machine... */ /* CAW: this is bad, really bad, maybe stack goes other direction on this machine... */
if(n < 0) { return -2; } if (n < 0)
{
return -2;
}
if(t->table[n].k == LH_EMPTY || t->table[n].k == LH_FREED) return -1; if (t->table[n].k == LH_EMPTY || t->table[n].k == LH_FREED)
return -1;
t->count--; t->count--;
if(t->free_fn) t->free_fn(e); if (t->free_fn)
t->free_fn(e);
t->table[n].v = NULL; t->table[n].v = NULL;
t->table[n].k = LH_FREED; t->table[n].k = LH_FREED;
if(t->tail == &t->table[n] && t->head == &t->table[n]) { if (t->tail == &t->table[n] && t->head == &t->table[n])
{
t->head = t->tail = NULL; t->head = t->tail = NULL;
} else if (t->head == &t->table[n]) { }
else if (t->head == &t->table[n])
{
t->head->next->prev = NULL; t->head->next->prev = NULL;
t->head = t->head->next; t->head = t->head->next;
} else if (t->tail == &t->table[n]) { }
else if (t->tail == &t->table[n])
{
t->tail->prev->next = NULL; t->tail->prev->next = NULL;
t->tail = t->tail->prev; t->tail = t->tail->prev;
} else { }
else
{
t->table[n].prev->next = t->table[n].next; t->table[n].prev->next = t->table[n].next;
t->table[n].next->prev = t->table[n].prev; t->table[n].next->prev = t->table[n].prev;
} }
@@ -676,11 +702,11 @@ int lh_table_delete_entry(struct lh_table *t, struct lh_entry *e)
return 0; return 0;
} }
int lh_table_delete(struct lh_table *t, const void *k) int lh_table_delete(struct lh_table *t, const void *k)
{ {
struct lh_entry *e = lh_table_lookup_entry(t, k); struct lh_entry *e = lh_table_lookup_entry(t, k);
if(!e) return -1; if (!e)
return -1;
return lh_table_delete_entry(t, e); return lh_table_delete_entry(t, e);
} }

View File

@@ -16,8 +16,8 @@
* this is exposed by the json_object_get_object() function and within the * this is exposed by the json_object_get_object() function and within the
* json_object_iter type, it is not recommended for direct use. * json_object_iter type, it is not recommended for direct use.
*/ */
#ifndef _linkhash_h_ #ifndef _json_c_linkhash_h_
#define _linkhash_h_ #define _json_c_linkhash_h_
#include "json_object.h" #include "json_object.h"
@@ -40,12 +40,12 @@ extern "C" {
/** /**
* sentinel pointer value for empty slots * sentinel pointer value for empty slots
*/ */
#define LH_EMPTY (void*)-1 #define LH_EMPTY (void *)-1
/** /**
* sentinel pointer value for freed slots * sentinel pointer value for freed slots
*/ */
#define LH_FREED (void*)-2 #define LH_FREED (void *)-2
/** /**
* default string hash function * default string hash function
@@ -69,84 +69,103 @@ struct lh_entry;
/** /**
* callback function prototypes * callback function prototypes
*/ */
typedef void (lh_entry_free_fn) (struct lh_entry *e); typedef void(lh_entry_free_fn)(struct lh_entry *e);
/** /**
* callback function prototypes * callback function prototypes
*/ */
typedef unsigned long (lh_hash_fn) (const void *k); typedef unsigned long(lh_hash_fn)(const void *k);
/** /**
* callback function prototypes * callback function prototypes
*/ */
typedef int (lh_equal_fn) (const void *k1, const void *k2); typedef int(lh_equal_fn)(const void *k1, const void *k2);
/** /**
* An entry in the hash table * An entry in the hash table. Outside of linkhash.c, treat this as opaque.
*/ */
struct lh_entry { struct lh_entry
{
/** /**
* The key. Use lh_entry_k() instead of accessing this directly. * The key.
* @deprecated Use lh_entry_k() instead of accessing this directly.
*/ */
const void *k; const void *k;
/** /**
* A flag for users of linkhash to know whether or not they * A flag for users of linkhash to know whether or not they
* need to free k. * need to free k.
* @deprecated use lh_entry_k_is_constant() instead.
*/ */
int k_is_constant; int k_is_constant;
/** /**
* The value. Use lh_entry_v() instead of accessing this directly. * The value.
* @deprecated Use lh_entry_v() instead of accessing this directly.
*/ */
const void *v; const void *v;
/** /**
* The next entry * The next entry.
* @deprecated Use lh_entry_next() instead of accessing this directly.
*/ */
struct lh_entry *next; struct lh_entry *next;
/** /**
* The previous entry. * The previous entry.
* @deprecated Use lh_entry_prev() instead of accessing this directly.
*/ */
struct lh_entry *prev; struct lh_entry *prev;
}; };
/** /**
* The hash table structure. * The hash table structure. Outside of linkhash.c, treat this as opaque.
*/ */
struct lh_table { struct lh_table
{
/** /**
* Size of our hash. * Size of our hash.
* @deprecated do not use outside of linkhash.c
*/ */
int size; int size;
/** /**
* Numbers of entries. * Numbers of entries.
* @deprecated Use lh_table_length() instead.
*/ */
int count; int count;
/** /**
* The first entry. * The first entry.
* @deprecated Use lh_table_head() instead.
*/ */
struct lh_entry *head; struct lh_entry *head;
/** /**
* The last entry. * The last entry.
* @deprecated Do not use, may be removed in a future release.
*/ */
struct lh_entry *tail; struct lh_entry *tail;
/**
* Internal storage of the actual table of entries.
* @deprecated do not use outside of linkhash.c
*/
struct lh_entry *table; struct lh_entry *table;
/** /**
* A pointer onto the function responsible for freeing an entry. * A pointer to the function responsible for freeing an entry.
* @deprecated do not use outside of linkhash.c
*/ */
lh_entry_free_fn *free_fn; lh_entry_free_fn *free_fn;
/**
* @deprecated do not use outside of linkhash.c
*/
lh_hash_fn *hash_fn; lh_hash_fn *hash_fn;
/**
* @deprecated do not use outside of linkhash.c
*/
lh_equal_fn *equal_fn; lh_equal_fn *equal_fn;
}; };
typedef struct lh_table lh_table; typedef struct lh_table lh_table;
/** /**
* Convenience list iterator. * Convenience list iterator.
*/ */
#define lh_foreach(table, entry) \ #define lh_foreach(table, entry) for (entry = lh_table_head(table); entry; entry = lh_entry_next(entry))
for(entry = table->head; entry; entry = entry->next)
/** /**
* lh_foreach_safe allows calling of deletion routine while iterating. * lh_foreach_safe allows calling of deletion routine while iterating.
@@ -156,9 +175,7 @@ for(entry = table->head; entry; entry = entry->next)
* @param tmp a struct lh_entry * variable to hold a temporary pointer to the next element * @param tmp a struct lh_entry * variable to hold a temporary pointer to the next element
*/ */
#define lh_foreach_safe(table, entry, tmp) \ #define lh_foreach_safe(table, entry, tmp) \
for(entry = table->head; entry && ((tmp = entry->next) || 1); entry = tmp) for (entry = lh_table_head(table); entry && ((tmp = lh_entry_next(entry)) || 1); entry = tmp)
/** /**
* Create a new linkhash table. * Create a new linkhash table.
@@ -178,10 +195,8 @@ for(entry = table->head; entry && ((tmp = entry->next) || 1); entry = tmp)
* @return On success, a pointer to the new linkhash table is returned. * @return On success, a pointer to the new linkhash table is returned.
* On error, a null pointer is returned. * On error, a null pointer is returned.
*/ */
extern struct lh_table* lh_table_new(int size, extern struct lh_table *lh_table_new(int size, lh_entry_free_fn *free_fn, lh_hash_fn *hash_fn,
lh_entry_free_fn *free_fn, lh_equal_fn *equal_fn);
lh_hash_fn *hash_fn,
lh_equal_fn *equal_fn);
/** /**
* Convenience function to create a new linkhash table with char keys. * Convenience function to create a new linkhash table with char keys.
@@ -191,9 +206,7 @@ extern struct lh_table* lh_table_new(int size,
* @return On success, a pointer to the new linkhash table is returned. * @return On success, a pointer to the new linkhash table is returned.
* On error, a null pointer is returned. * On error, a null pointer is returned.
*/ */
extern struct lh_table* lh_kchar_table_new(int size, extern struct lh_table *lh_kchar_table_new(int size, lh_entry_free_fn *free_fn);
lh_entry_free_fn *free_fn);
/** /**
* Convenience function to create a new linkhash table with ptr keys. * Convenience function to create a new linkhash table with ptr keys.
@@ -203,9 +216,7 @@ extern struct lh_table* lh_kchar_table_new(int size,
* @return On success, a pointer to the new linkhash table is returned. * @return On success, a pointer to the new linkhash table is returned.
* On error, a null pointer is returned. * On error, a null pointer is returned.
*/ */
extern struct lh_table* lh_kptr_table_new(int size, extern struct lh_table *lh_kptr_table_new(int size, lh_entry_free_fn *free_fn);
lh_entry_free_fn *free_fn);
/** /**
* Free a linkhash table. * Free a linkhash table.
@@ -217,7 +228,6 @@ extern struct lh_table* lh_kptr_table_new(int size,
*/ */
extern void lh_table_free(struct lh_table *t); extern void lh_table_free(struct lh_table *t);
/** /**
* Insert a record into the table. * Insert a record into the table.
* *
@@ -230,7 +240,6 @@ extern void lh_table_free(struct lh_table *t);
*/ */
extern int lh_table_insert(struct lh_table *t, const void *k, const void *v); extern int lh_table_insert(struct lh_table *t, const void *k, const void *v);
/** /**
* Insert a record into the table using a precalculated key hash. * Insert a record into the table using a precalculated key hash.
* *
@@ -242,11 +251,11 @@ extern int lh_table_insert(struct lh_table *t, const void *k, const void *v);
* @param k a pointer to the key to insert. * @param k a pointer to the key to insert.
* @param v a pointer to the value to insert. * @param v a pointer to the value to insert.
* @param h hash value of the key to insert * @param h hash value of the key to insert
* @param opts if set to JSON_C_OBJECT_KEY_IS_CONSTANT, sets lh_entry.k_is_constant * @param opts if set to JSON_C_OBJECT_ADD_CONSTANT_KEY, sets lh_entry.k_is_constant
* so t's free function knows to avoid freeing the key. * so t's free function knows to avoid freeing the key.
*/ */
extern int lh_table_insert_w_hash(struct lh_table *t, const void *k, const void *v, const unsigned long h, const unsigned opts); extern int lh_table_insert_w_hash(struct lh_table *t, const void *k, const void *v,
const unsigned long h, const unsigned opts);
/** /**
* Lookup a record in the table. * Lookup a record in the table.
@@ -255,7 +264,7 @@ extern int lh_table_insert_w_hash(struct lh_table *t, const void *k, const void
* @param k a pointer to the key to lookup * @param k a pointer to the key to lookup
* @return a pointer to the record structure of the value or NULL if it does not exist. * @return a pointer to the record structure of the value or NULL if it does not exist.
*/ */
extern struct lh_entry* lh_table_lookup_entry(struct lh_table *t, const void *k); extern struct lh_entry *lh_table_lookup_entry(struct lh_table *t, const void *k);
/** /**
* Lookup a record in the table using a precalculated key hash. * Lookup a record in the table using a precalculated key hash.
@@ -269,17 +278,8 @@ extern struct lh_entry* lh_table_lookup_entry(struct lh_table *t, const void *k)
* @param h hash value of the key to lookup * @param h hash value of the key to lookup
* @return a pointer to the record structure of the value or NULL if it does not exist. * @return a pointer to the record structure of the value or NULL if it does not exist.
*/ */
extern struct lh_entry* lh_table_lookup_entry_w_hash(struct lh_table *t, const void *k, const unsigned long h); extern struct lh_entry *lh_table_lookup_entry_w_hash(struct lh_table *t, const void *k,
const unsigned long h);
/**
* Lookup a record into the table.
*
* @param t the table to lookup
* @param k a pointer to the key to lookup
* @return a pointer to the found value or NULL if it does not exist.
* @deprecated Use lh_table_lookup_ex() instead.
*/
THIS_FUNCTION_IS_DEPRECATED(extern const void* lh_table_lookup(struct lh_table *t, const void *k));
/** /**
* Lookup a record in the table. * Lookup a record in the table.
@@ -303,7 +303,6 @@ extern json_bool lh_table_lookup_ex(struct lh_table *t, const void *k, void **v)
*/ */
extern int lh_table_delete_entry(struct lh_table *t, struct lh_entry *e); extern int lh_table_delete_entry(struct lh_table *t, struct lh_entry *e);
/** /**
* Delete a record from the table. * Delete a record from the table.
* *
@@ -316,22 +315,10 @@ extern int lh_table_delete_entry(struct lh_table *t, struct lh_entry *e);
*/ */
extern int lh_table_delete(struct lh_table *t, const void *k); extern int lh_table_delete(struct lh_table *t, const void *k);
extern int lh_table_length(struct lh_table *t);
/** /**
* Prints a message to <code>stdout</code>, * Return the number of entries in the table.
* then exits the program with an exit code of <code>1</code>.
*
* @param msg Message format string, like for <code>printf</code>.
* @param ... Format args.
*
* @deprecated Since it is not a good idea to exit the entire program
* because of an internal library failure, json-c will no longer
* use this function internally.
* However, because its interface is public, it will remain part of
* the API on the off chance of legacy software using it externally.
*/ */
THIS_FUNCTION_IS_DEPRECATED(void lh_abort(const char *msg, ...)); extern int lh_table_length(struct lh_table *t);
/** /**
* Resizes the specified table. * Resizes the specified table.
@@ -344,21 +331,29 @@ THIS_FUNCTION_IS_DEPRECATED(void lh_abort(const char *msg, ...));
*/ */
int lh_table_resize(struct lh_table *t, int new_size); int lh_table_resize(struct lh_table *t, int new_size);
/** /**
* @deprecated Don't use this outside of linkhash.h: * @deprecated Don't use this outside of linkhash.h:
*/ */
#if !defined(_MSC_VER) || (_MSC_VER > 1800) #if (defined(AIX_CC) || (defined(_MSC_VER) && (_MSC_VER <= 1800)) )
/* VS2010 can't handle inline funcs, so skip it there */ /* VS2010 can't handle inline funcs, so skip it there */
#define _LH_INLINE inline
#else
#define _LH_INLINE #define _LH_INLINE
#else
#define _LH_INLINE inline
#endif #endif
/**
* Return the first entry in the lh_table.
* @see lh_entry_next()
*/
static _LH_INLINE struct lh_entry *lh_table_head(const lh_table *t)
{
return t->head;
}
/** /**
* Calculate the hash of a key for a given table. * Calculate the hash of a key for a given table.
* *
* This is an exension to support functions that need to calculate * This is an extension to support functions that need to calculate
* the hash several times and allows them to do it just once and then pass * the hash several times and allows them to do it just once and then pass
* in the hash to all utility functions. Depending on use case, this can be a * in the hash to all utility functions. Depending on use case, this can be a
* considerable performance improvement. * considerable performance improvement.
@@ -371,7 +366,6 @@ static _LH_INLINE unsigned long lh_get_hash(const struct lh_table *t, const void
return t->hash_fn(k); return t->hash_fn(k);
} }
#undef _LH_INLINE
/** /**
* @deprecated Don't use this outside of linkhash.h: * @deprecated Don't use this outside of linkhash.h:
@@ -387,9 +381,22 @@ static _LH_INLINE unsigned long lh_get_hash(const struct lh_table *t, const void
* *
* lh_entry.k is const to indicate and help ensure that linkhash itself doesn't modify * lh_entry.k is const to indicate and help ensure that linkhash itself doesn't modify
* it, but callers are allowed to do what they want with it. * it, but callers are allowed to do what they want with it.
* See also lh_entry.k_is_constant * @see lh_entry_k_is_constant()
*/ */
#define lh_entry_k(entry) _LH_UNCONST((entry)->k) static _LH_INLINE void *lh_entry_k(const struct lh_entry *e)
{
return _LH_UNCONST(e->k);
}
/**
* Returns 1 if the key for the given entry is constant, and thus
* does not need to be freed when the lh_entry is freed.
* @see lh_table_insert_w_hash()
*/
static _LH_INLINE int lh_entry_k_is_constant(const struct lh_entry *e)
{
return e->k_is_constant;
}
/** /**
* Return a non-const version of lh_entry.v. * Return a non-const version of lh_entry.v.
@@ -397,7 +404,41 @@ static _LH_INLINE unsigned long lh_get_hash(const struct lh_table *t, const void
* v is const to indicate and help ensure that linkhash itself doesn't modify * v is const to indicate and help ensure that linkhash itself doesn't modify
* it, but callers are allowed to do what they want with it. * it, but callers are allowed to do what they want with it.
*/ */
#define lh_entry_v(entry) _LH_UNCONST((entry)->v) static _LH_INLINE void *lh_entry_v(const struct lh_entry *e)
{
return _LH_UNCONST(e->v);
}
/**
* Change the value for an entry. The caller is responsible for freeing
* the previous value.
*/
static _LH_INLINE void lh_entry_set_val(struct lh_entry *e, void *newval)
{
e->v = newval;
}
/**
* Return the next element, or NULL if there is no next element.
* @see lh_table_head()
* @see lh_entry_prev()
*/
static _LH_INLINE struct lh_entry *lh_entry_next(const struct lh_entry *e)
{
return e->next;
}
/**
* Return the previous element, or NULL if there is no previous element.
* @see lh_table_head()
* @see lh_entry_next()
*/
static _LH_INLINE struct lh_entry *lh_entry_prev(const struct lh_entry *e)
{
return e->prev;
}
#undef _LH_INLINE
#ifdef __cplusplus #ifdef __cplusplus
} }

View File

@@ -9,17 +9,24 @@
/* Define isnan, isinf, infinity and nan on Windows/MSVC */ /* Define isnan, isinf, infinity and nan on Windows/MSVC */
#ifndef HAVE_DECL_ISNAN #ifndef HAVE_DECL_ISNAN
# ifdef HAVE_DECL__ISNAN #ifdef HAVE_DECL__ISNAN
#include <float.h> #include <float.h>
#define isnan(x) _isnan(x) #define isnan(x) _isnan(x)
# endif #else
/* On platforms like AIX and "IBM i" we need to provide our own isnan */
#define isnan(x) ((x) != (x))
#endif
#endif #endif
#ifndef HAVE_DECL_ISINF #ifndef HAVE_DECL_ISINF
# ifdef HAVE_DECL__FINITE #ifdef HAVE_DECL__FINITE
#include <float.h> #include <float.h>
#define isinf(x) (!_finite(x)) #define isinf(x) (!_finite(x))
# endif #else
#include <float.h>
/* On platforms like AIX and "IBM i" we need to provide our own isinf */
#define isinf(x) ((x) < -DBL_MAX || (x) > DBL_MAX)
#endif
#endif #endif
#ifndef HAVE_DECL_INFINITY #ifndef HAVE_DECL_INFINITY

View File

@@ -10,19 +10,21 @@
* *
* Copyright (c) 2008-2009 Yahoo! Inc. All rights reserved. * Copyright (c) 2008-2009 Yahoo! Inc. All rights reserved.
* The copyrights to the contents of this file are licensed under the MIT License * The copyrights to the contents of this file are licensed under the MIT License
* (http://www.opensource.org/licenses/mit-license.php) * (https://www.opensource.org/licenses/mit-license.php)
*/ */
#include "config.h" #include "config.h"
#include <errno.h>
#include <limits.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#ifdef HAVE_STDARG_H #ifdef HAVE_STDARG_H
# include <stdarg.h> #include <stdarg.h>
#else /* !HAVE_STDARG_H */ #else /* !HAVE_STDARG_H */
# error Not enough var arg support! #error Not enough var arg support!
#endif /* HAVE_STDARG_H */ #endif /* HAVE_STDARG_H */
#include "debug.h" #include "debug.h"
@@ -32,28 +34,31 @@
static int printbuf_extend(struct printbuf *p, int min_size); static int printbuf_extend(struct printbuf *p, int min_size);
struct printbuf* printbuf_new(void) struct printbuf *printbuf_new(void)
{ {
struct printbuf *p; struct printbuf *p;
p = (struct printbuf*)calloc(1, sizeof(struct printbuf)); p = (struct printbuf *)calloc(1, sizeof(struct printbuf));
if(!p) return NULL; if (!p)
p->size = 32; return NULL;
p->bpos = 0; p->size = 32;
if(!(p->buf = (char*)malloc(p->size))) { p->bpos = 0;
free(p); if (!(p->buf = (char *)malloc(p->size)))
return NULL; {
} free(p);
p->buf[0]= '\0'; return NULL;
return p; }
p->buf[0] = '\0';
return p;
} }
/** /**
* Extend the buffer p so it has a size of at least min_size. * Extend the buffer p so it has a size of at least min_size.
* *
* If the current size is large enough, nothing is changed. * If the current size is large enough, nothing is changed.
* *
* If extension failed, errno is set to indicate the error.
*
* Note: this does not check the available space! The caller * Note: this does not check the available space! The caller
* is responsible for performing those calculations. * is responsible for performing those calculations.
*/ */
@@ -64,16 +69,25 @@ static int printbuf_extend(struct printbuf *p, int min_size)
if (p->size >= min_size) if (p->size >= min_size)
return 0; return 0;
/* Prevent signed integer overflows with large buffers. */
new_size = p->size * 2; if (min_size > INT_MAX - 8)
if (new_size < min_size + 8) {
new_size = min_size + 8; errno = EFBIG;
return -1;
}
if (p->size > INT_MAX / 2)
new_size = min_size + 8;
else {
new_size = p->size * 2;
if (new_size < min_size + 8)
new_size = min_size + 8;
}
#ifdef PRINTBUF_DEBUG #ifdef PRINTBUF_DEBUG
MC_DEBUG("printbuf_memappend: realloc " MC_DEBUG("printbuf_extend: realloc "
"bpos=%d min_size=%d old_size=%d new_size=%d\n", "bpos=%d min_size=%d old_size=%d new_size=%d\n",
p->bpos, min_size, p->size, new_size); p->bpos, min_size, p->size, new_size);
#endif /* PRINTBUF_DEBUG */ #endif /* PRINTBUF_DEBUG */
if(!(t = (char*)realloc(p->buf, new_size))) if (!(t = (char *)realloc(p->buf, new_size)))
return -1; return -1;
p->size = new_size; p->size = new_size;
p->buf = t; p->buf = t;
@@ -82,14 +96,21 @@ static int printbuf_extend(struct printbuf *p, int min_size)
int printbuf_memappend(struct printbuf *p, const char *buf, int size) int printbuf_memappend(struct printbuf *p, const char *buf, int size)
{ {
if (p->size <= p->bpos + size + 1) { /* Prevent signed integer overflows with large buffers. */
if (printbuf_extend(p, p->bpos + size + 1) < 0) if (size < 0 || size > INT_MAX - p->bpos - 1)
return -1; {
} errno = EFBIG;
memcpy(p->buf + p->bpos, buf, size); return -1;
p->bpos += size; }
p->buf[p->bpos]= '\0'; if (p->size <= p->bpos + size + 1)
return size; {
if (printbuf_extend(p, p->bpos + size + 1) < 0)
return -1;
}
memcpy(p->buf + p->bpos, buf, size);
p->bpos += size;
p->buf[p->bpos] = '\0';
return size;
} }
int printbuf_memset(struct printbuf *pb, int offset, int charvalue, int len) int printbuf_memset(struct printbuf *pb, int offset, int charvalue, int len)
@@ -98,6 +119,12 @@ int printbuf_memset(struct printbuf *pb, int offset, int charvalue, int len)
if (offset == -1) if (offset == -1)
offset = pb->bpos; offset = pb->bpos;
/* Prevent signed integer overflows with large buffers. */
if (len < 0 || offset < -1 || len > INT_MAX - offset)
{
errno = EFBIG;
return -1;
}
size_needed = offset + len; size_needed = offset + len;
if (pb->size < size_needed) if (pb->size < size_needed)
{ {
@@ -105,6 +132,8 @@ int printbuf_memset(struct printbuf *pb, int offset, int charvalue, int len)
return -1; return -1;
} }
if (pb->bpos < offset)
memset(pb->buf + pb->bpos, '\0', offset - pb->bpos);
memset(pb->buf + offset, charvalue, len); memset(pb->buf + offset, charvalue, len);
if (pb->bpos < size_needed) if (pb->bpos < size_needed)
pb->bpos = size_needed; pb->bpos = size_needed;
@@ -114,42 +143,50 @@ int printbuf_memset(struct printbuf *pb, int offset, int charvalue, int len)
int sprintbuf(struct printbuf *p, const char *msg, ...) int sprintbuf(struct printbuf *p, const char *msg, ...)
{ {
va_list ap; va_list ap;
char *t; char *t;
int size; int size;
char buf[128]; char buf[128];
/* user stack buffer first */ /* use stack buffer first */
va_start(ap, msg); va_start(ap, msg);
size = vsnprintf(buf, 128, msg, ap); size = vsnprintf(buf, 128, msg, ap);
va_end(ap); va_end(ap);
/* if string is greater than stack buffer, then use dynamic string /* if string is greater than stack buffer, then use dynamic string
with vasprintf. Note: some implementation of vsnprintf return -1 * with vasprintf. Note: some implementations of vsnprintf return -1
if output is truncated whereas some return the number of bytes that * if output is truncated whereas some return the number of bytes that
would have been written - this code handles both cases. */ * would have been written - this code handles both cases.
if(size == -1 || size > 127) { */
va_start(ap, msg); if (size < 0 || size > 127)
if((size = vasprintf(&t, msg, ap)) < 0) { va_end(ap); return -1; } {
va_end(ap); va_start(ap, msg);
printbuf_memappend(p, t, size); if ((size = vasprintf(&t, msg, ap)) < 0)
free(t); {
return size; va_end(ap);
} else { return -1;
printbuf_memappend(p, buf, size); }
return size; va_end(ap);
} size = printbuf_memappend(p, t, size);
free(t);
}
else
{
size = printbuf_memappend(p, buf, size);
}
return size;
} }
void printbuf_reset(struct printbuf *p) void printbuf_reset(struct printbuf *p)
{ {
p->buf[0] = '\0'; p->buf[0] = '\0';
p->bpos = 0; p->bpos = 0;
} }
void printbuf_free(struct printbuf *p) void printbuf_free(struct printbuf *p)
{ {
if(p) { if (p)
free(p->buf); {
free(p); free(p->buf);
} free(p);
}
} }

View File

@@ -10,32 +10,40 @@
* *
* Copyright (c) 2008-2009 Yahoo! Inc. All rights reserved. * Copyright (c) 2008-2009 Yahoo! Inc. All rights reserved.
* The copyrights to the contents of this file are licensed under the MIT License * The copyrights to the contents of this file are licensed under the MIT License
* (http://www.opensource.org/licenses/mit-license.php) * (https://www.opensource.org/licenses/mit-license.php)
*/ */
/** /**
* @file * @file
* @brief Internal string buffer handing. Unless you're writing a * @brief Internal string buffer handling. Unless you're writing a
* json_object_to_json_string_fn implementation for use with * json_object_to_json_string_fn implementation for use with
* json_object_set_serializer() direct use of this is not * json_object_set_serializer() direct use of this is not
* recommended. * recommended.
*/ */
#ifndef _printbuf_h_ #ifndef _json_c_printbuf_h_
#define _printbuf_h_ #define _json_c_printbuf_h_
#ifndef JSON_EXPORT
#if defined(_MSC_VER) && defined(JSON_C_DLL)
#define JSON_EXPORT __declspec(dllexport)
#else
#define JSON_EXPORT extern
#endif
#endif
#ifdef __cplusplus #ifdef __cplusplus
extern "C" { extern "C" {
#endif #endif
struct printbuf { struct printbuf
char *buf; {
int bpos; char *buf;
int size; int bpos;
int size;
}; };
typedef struct printbuf printbuf; typedef struct printbuf printbuf;
extern struct printbuf* JSON_EXPORT struct printbuf *printbuf_new(void);
printbuf_new(void);
/* As an optimization, printbuf_memappend_fast() is defined as a macro /* As an optimization, printbuf_memappend_fast() is defined as a macro
* that handles copying data if the buffer is large enough; otherwise * that handles copying data if the buffer is large enough; otherwise
@@ -45,17 +53,22 @@ printbuf_new(void);
* Your code should not use printbuf_memappend() directly unless it * Your code should not use printbuf_memappend() directly unless it
* checks the return code. Use printbuf_memappend_fast() instead. * checks the return code. Use printbuf_memappend_fast() instead.
*/ */
extern int JSON_EXPORT int printbuf_memappend(struct printbuf *p, const char *buf, int size);
printbuf_memappend(struct printbuf *p, const char *buf, int size);
#define printbuf_memappend_fast(p, bufptr, bufsize) \ #define printbuf_memappend_fast(p, bufptr, bufsize) \
do { \ do \
if ((p->size - p->bpos) > bufsize) { \ { \
memcpy(p->buf + p->bpos, (bufptr), bufsize); \ if ((p->size - p->bpos) > bufsize) \
p->bpos += bufsize; \ { \
p->buf[p->bpos]= '\0'; \ memcpy(p->buf + p->bpos, (bufptr), bufsize); \
} else { printbuf_memappend(p, (bufptr), bufsize); } \ p->bpos += bufsize; \
} while (0) p->buf[p->bpos] = '\0'; \
} \
else \
{ \
printbuf_memappend(p, (bufptr), bufsize); \
} \
} while (0)
#define printbuf_length(p) ((p)->bpos) #define printbuf_length(p) ((p)->bpos)
@@ -79,7 +92,7 @@ do { \
* sprintbuf() * sprintbuf()
*/ */
#define printbuf_strappend(pb, str) \ #define printbuf_strappend(pb, str) \
printbuf_memappend ((pb), _printbuf_check_literal(str), sizeof(str) - 1) printbuf_memappend((pb), _printbuf_check_literal(str), sizeof(str) - 1)
/** /**
* Set len bytes of the buffer to charvalue, starting at offset offset. * Set len bytes of the buffer to charvalue, starting at offset offset.
@@ -89,8 +102,7 @@ do { \
* *
* If offset is -1, this starts at the end of the current data in the buffer. * If offset is -1, this starts at the end of the current data in the buffer.
*/ */
extern int JSON_EXPORT int printbuf_memset(struct printbuf *pb, int offset, int charvalue, int len);
printbuf_memset(struct printbuf *pb, int offset, int charvalue, int len);
/** /**
* Formatted print to printbuf. * Formatted print to printbuf.
@@ -106,14 +118,11 @@ printbuf_memset(struct printbuf *pb, int offset, int charvalue, int len);
* printbuf_memappend() * printbuf_memappend()
* printbuf_strappend() * printbuf_strappend()
*/ */
extern int JSON_EXPORT int sprintbuf(struct printbuf *p, const char *msg, ...);
sprintbuf(struct printbuf *p, const char *msg, ...);
extern void JSON_EXPORT void printbuf_reset(struct printbuf *p);
printbuf_reset(struct printbuf *p);
extern void JSON_EXPORT void printbuf_free(struct printbuf *p);
printbuf_free(struct printbuf *p);
#ifdef __cplusplus #ifdef __cplusplus
} }

View File

@@ -9,13 +9,26 @@
* *
*/ */
#include "random_seed.h"
#include "config.h"
#include "strerror_override.h" #include "strerror_override.h"
#include <stdio.h> #include <stdio.h>
#include "config.h" #include <stdlib.h>
#include "random_seed.h" #ifdef HAVE_BSD_STDLIB_H
#include <bsd/stdlib.h>
#endif
#define DEBUG_SEED(s) #define DEBUG_SEED(s)
#if defined(__APPLE__) || defined(__unix__) || defined(__linux__)
#define HAVE_DEV_RANDOM 1
#endif
#ifdef HAVE_ARC4RANDOM
#undef HAVE_GETRANDOM
#undef HAVE_DEV_RANDOM
#undef HAVE_CRYPTGENRANDOM
#endif
#if defined ENABLE_RDRAND #if defined ENABLE_RDRAND
@@ -26,20 +39,11 @@
static void do_cpuid(int regs[], int h) static void do_cpuid(int regs[], int h)
{ {
__asm__ __volatile__( /* clang-format off */
#if defined __x86_64__ __asm__ __volatile__("cpuid"
"pushq %%rbx;\n" : "=a"(regs[0]), "=b"(regs[1]), "=c"(regs[2]), "=d"(regs[3])
#else
"pushl %%ebx;\n"
#endif
"cpuid;\n"
#if defined __x86_64__
"popq %%rbx;\n"
#else
"popl %%ebx;\n"
#endif
: "=a"(regs[0]), [ebx] "=r"(regs[1]), "=c"(regs[2]), "=d"(regs[3])
: "a"(h)); : "a"(h));
/* clang-format on */
} }
#elif defined _MSC_VER #elif defined _MSC_VER
@@ -53,12 +57,51 @@ static void do_cpuid(int regs[], int h)
#if HAS_X86_CPUID #if HAS_X86_CPUID
static int has_rdrand() static int get_rdrand_seed(void);
/* Valid values are -1 (haven't tested), 0 (no), and 1 (yes). */
static int _has_rdrand = -1;
static int has_rdrand(void)
{ {
// CPUID.01H:ECX.RDRAND[bit 30] == 1 if (_has_rdrand != -1)
int regs[4]; {
do_cpuid(regs, 1); return _has_rdrand;
return (regs[2] & (1 << 30)) != 0; }
/* CPUID.01H:ECX.RDRAND[bit 30] == 1 */
int regs[4];
do_cpuid(regs, 1);
if (!(regs[2] & (1 << 30)))
{
_has_rdrand = 0;
return 0;
}
/*
* Some CPUs advertise RDRAND in CPUID, but return 0xFFFFFFFF
* unconditionally. To avoid locking up later, test RDRAND here. If over
* 3 trials RDRAND has returned the same value, declare it broken.
* Example CPUs are AMD Ryzen 3000 series
* and much older AMD APUs, such as the E1-1500
* https://github.com/systemd/systemd/issues/11810
* https://linuxreviews.org/RDRAND_stops_returning_random_values_on_older_AMD_CPUs_after_suspend
*/
_has_rdrand = 0;
int prev = get_rdrand_seed();
for (int i = 0; i < 3; i++)
{
int temp = get_rdrand_seed();
if (temp != prev)
{
_has_rdrand = 1;
break;
}
prev = temp;
}
return _has_rdrand;
} }
#endif #endif
@@ -69,17 +112,19 @@ static int has_rdrand()
#define HAVE_RDRAND 1 #define HAVE_RDRAND 1
static int get_rdrand_seed() static int get_rdrand_seed(void)
{ {
DEBUG_SEED("get_rdrand_seed"); DEBUG_SEED("get_rdrand_seed");
int _eax; int _eax;
// rdrand eax /* rdrand eax */
__asm__ __volatile__("1: .byte 0x0F\n" /* clang-format off */
" .byte 0xC7\n" __asm__ __volatile__("1: .byte 0x0F\n"
" .byte 0xF0\n" " .byte 0xC7\n"
" jnc 1b;\n" " .byte 0xF0\n"
: "=a" (_eax)); " jnc 1b;\n"
return _eax; : "=a" (_eax));
/* clang-format on */
return _eax;
} }
#endif #endif
@@ -91,12 +136,13 @@ static int get_rdrand_seed()
/* get_rdrand_seed - Visual Studio 2012 and above */ /* get_rdrand_seed - Visual Studio 2012 and above */
static int get_rdrand_seed() static int get_rdrand_seed(void)
{ {
DEBUG_SEED("get_rdrand_seed"); DEBUG_SEED("get_rdrand_seed");
int r; int r;
while (_rdrand32_step(&r) == 0); while (_rdrand32_step(&r) == 0)
return r; ;
return r;
} }
#elif defined _M_IX86 #elif defined _M_IX86
@@ -104,135 +150,208 @@ static int get_rdrand_seed()
/* get_rdrand_seed - Visual Studio 2010 and below - x86 only */ /* get_rdrand_seed - Visual Studio 2010 and below - x86 only */
static int get_rdrand_seed() /* clang-format off */
static int get_rdrand_seed(void)
{ {
DEBUG_SEED("get_rdrand_seed"); DEBUG_SEED("get_rdrand_seed");
int _eax; int _eax;
retry: retry:
// rdrand eax /* rdrand eax */
__asm _emit 0x0F __asm _emit 0xC7 __asm _emit 0xF0 __asm _emit 0x0F __asm _emit 0xC7 __asm _emit 0xF0
__asm jnc retry __asm jnc retry
__asm mov _eax, eax __asm mov _eax, eax
return _eax; return _eax;
} }
/* clang-format on */
#endif #endif
#endif #endif
#endif /* defined ENABLE_RDRAND */ #endif /* defined ENABLE_RDRAND */
#ifdef HAVE_GETRANDOM
/* has_dev_urandom */
#if defined (__APPLE__) || defined(__unix__) || defined(__linux__)
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h> #include <stdlib.h>
#include <sys/stat.h> #ifdef HAVE_SYS_RANDOM_H
#include <sys/random.h>
#endif
#define HAVE_DEV_RANDOM 1 static int get_getrandom_seed(int *seed)
static const char *dev_random_file = "/dev/urandom";
static int has_dev_urandom()
{ {
struct stat buf; DEBUG_SEED("get_getrandom_seed");
if (stat(dev_random_file, &buf)) {
return 0;
}
return ((buf.st_mode & S_IFCHR) != 0);
}
ssize_t ret;
do
{
ret = getrandom(seed, sizeof(*seed), GRND_NONBLOCK);
} while ((ret == -1) && (errno == EINTR));
if (ret == -1)
{
if (errno == ENOSYS) /* syscall not available in kernel */
return -1;
if (errno == EAGAIN) /* entropy not yet initialized */
return -1;
fprintf(stderr, "error from getrandom(): %s", strerror(errno));
return -1;
}
if (ret != sizeof(*seed))
return -1;
return 0;
}
#endif /* defined HAVE_GETRANDOM */
/* get_dev_random_seed */ /* get_dev_random_seed */
static int get_dev_random_seed() #ifdef HAVE_DEV_RANDOM
#include <fcntl.h>
#include <string.h>
#if HAVE_UNISTD_H
#include <unistd.h>
#endif /* HAVE_UNISTD_H */
#include <stdlib.h>
#include <sys/stat.h>
static const char *dev_random_file = "/dev/urandom";
static int get_dev_random_seed(int *seed)
{ {
DEBUG_SEED("get_dev_random_seed"); DEBUG_SEED("get_dev_random_seed");
int fd = open(dev_random_file, O_RDONLY); struct stat buf;
if (fd < 0) { if (stat(dev_random_file, &buf))
fprintf(stderr, "error opening %s: %s", dev_random_file, strerror(errno)); return -1;
exit(1); if ((buf.st_mode & S_IFCHR) == 0)
} return -1;
int r; /* coverity[toctou] */
ssize_t nread = read(fd, &r, sizeof(r)); int fd = open(dev_random_file, O_RDONLY);
if (nread != sizeof(r)) { if (fd < 0)
fprintf(stderr, "error short read %s: %s", dev_random_file, strerror(errno)); {
exit(1); fprintf(stderr, "error opening %s: %s", dev_random_file, strerror(errno));
} return -1;
}
close(fd); ssize_t nread = read(fd, seed, sizeof(*seed));
return r;
close(fd);
if (nread != sizeof(*seed))
{
fprintf(stderr, "error short read %s: %s", dev_random_file, strerror(errno));
return -1;
}
return 0;
} }
#endif #endif
/* get_cryptgenrandom_seed */ /* get_cryptgenrandom_seed */
#ifdef WIN32 #ifdef _WIN32
#define HAVE_CRYPTGENRANDOM 1 #define HAVE_CRYPTGENRANDOM 1
/* clang-format off */
#include <windows.h> #include <windows.h>
/* Caution: these blank lines must remain so clang-format doesn't reorder
includes to put windows.h after wincrypt.h */
#include <wincrypt.h> #include <wincrypt.h>
/* clang-format on */
#ifndef __GNUC__ #ifndef __GNUC__
#pragma comment(lib, "advapi32.lib") #pragma comment(lib, "advapi32.lib")
#endif #endif
static int get_cryptgenrandom_seed() static int get_cryptgenrandom_seed(int *seed)
{ {
HCRYPTPROV hProvider = 0; HCRYPTPROV hProvider = 0;
int r; DWORD dwFlags = CRYPT_VERIFYCONTEXT;
DEBUG_SEED("get_cryptgenrandom_seed"); DEBUG_SEED("get_cryptgenrandom_seed");
if (!CryptAcquireContextW(&hProvider, 0, 0, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) { /* WinNT 4 and Win98 do no support CRYPT_SILENT */
fprintf(stderr, "error CryptAcquireContextW"); if (LOBYTE(LOWORD(GetVersion())) > 4)
exit(1); dwFlags |= CRYPT_SILENT;
}
if (!CryptGenRandom(hProvider, sizeof(r), (BYTE*)&r)) { if (!CryptAcquireContextA(&hProvider, 0, 0, PROV_RSA_FULL, dwFlags))
fprintf(stderr, "error CryptGenRandom"); {
exit(1); fprintf(stderr, "error CryptAcquireContextA 0x%08lx", GetLastError());
} return -1;
}
else
{
BOOL ret = CryptGenRandom(hProvider, sizeof(*seed), (BYTE *)seed);
CryptReleaseContext(hProvider, 0);
if (!ret)
{
fprintf(stderr, "error CryptGenRandom 0x%08lx", GetLastError());
return -1;
}
}
CryptReleaseContext(hProvider, 0); return 0;
return r;
} }
#endif #endif
/* get_time_seed */ /* get_time_seed */
#ifndef HAVE_ARC4RANDOM
#include <time.h> #include <time.h>
static int get_time_seed() static int get_time_seed(void)
{ {
DEBUG_SEED("get_time_seed"); DEBUG_SEED("get_time_seed");
return (int)time(NULL) * 433494437; /* coverity[store_truncates_time_t] */
return (unsigned)time(NULL) * 433494437;
} }
#endif
/* json_c_get_random_seed */ /* json_c_get_random_seed */
int json_c_get_random_seed() int json_c_get_random_seed(void)
{ {
#if HAVE_RDRAND #ifdef OVERRIDE_GET_RANDOM_SEED
if (has_rdrand()) return get_rdrand_seed(); OVERRIDE_GET_RANDOM_SEED;
#endif #endif
#if HAVE_DEV_RANDOM #if defined HAVE_RDRAND && HAVE_RDRAND
if (has_dev_urandom()) return get_dev_random_seed(); if (has_rdrand())
return get_rdrand_seed();
#endif #endif
#if HAVE_CRYPTGENRANDOM #ifdef HAVE_ARC4RANDOM
return get_cryptgenrandom_seed(); /* arc4random never fails, so use it if it's available */
return arc4random();
#else
#ifdef HAVE_GETRANDOM
{
int seed = 0;
if (get_getrandom_seed(&seed) == 0)
return seed;
}
#endif #endif
return get_time_seed(); #if defined HAVE_DEV_RANDOM && HAVE_DEV_RANDOM
{
int seed = 0;
if (get_dev_random_seed(&seed) == 0)
return seed;
}
#endif
#if defined HAVE_CRYPTGENRANDOM && HAVE_CRYPTGENRANDOM
{
int seed = 0;
if (get_cryptgenrandom_seed(&seed) == 0)
return seed;
}
#endif
return get_time_seed();
#endif /* !HAVE_ARC4RANDOM */
} }

View File

@@ -20,7 +20,7 @@
extern "C" { extern "C" {
#endif #endif
extern int json_c_get_random_seed(); extern int json_c_get_random_seed(void);
#ifdef __cplusplus #ifdef __cplusplus
} }

View File

@@ -13,7 +13,7 @@
#include <stdarg.h> #include <stdarg.h>
#if !defined(HAVE_SNPRINTF) && defined(_MSC_VER) #if !defined(HAVE_SNPRINTF) && (defined(_MSC_VER) || defined(__MINGW32__))
static int json_c_vsnprintf(char *str, size_t size, const char *format, va_list ap) static int json_c_vsnprintf(char *str, size_t size, const char *format, va_list ap)
{ {
int ret; int ret;
@@ -35,7 +35,7 @@ static int json_c_snprintf(char *str, size_t size, const char *format, ...)
#define snprintf json_c_snprintf #define snprintf json_c_snprintf
#elif !defined(HAVE_SNPRINTF) /* !HAVE_SNPRINTF */ #elif !defined(HAVE_SNPRINTF) /* !HAVE_SNPRINTF */
# error Need vsnprintf! #error snprintf is required but was not found
#endif /* !HAVE_SNPRINTF && defined(WIN32) */ #endif /* !HAVE_SNPRINTF */
#endif /* __snprintf_compat_h */ #endif /* __snprintf_compat_h */

View File

@@ -7,10 +7,10 @@
*/ */
#if !defined(HAVE_STRDUP) && defined(_MSC_VER) #if !defined(HAVE_STRDUP) && defined(_MSC_VER)
/* MSC has the version as _strdup */ /* MSC has the version as _strdup */
# define strdup _strdup #define strdup _strdup
#elif !defined(HAVE_STRDUP) #elif !defined(HAVE_STRDUP)
# error You do not have strdup on your system. #error You do not have strdup on your system.
#endif /* HAVE_STRDUP */ #endif /* HAVE_STRDUP */
#endif #endif

View File

@@ -5,10 +5,12 @@
* Override strerror() to get consistent output across platforms. * Override strerror() to get consistent output across platforms.
*/ */
static struct { static struct
{
int errno_value; int errno_value;
const char *errno_str; const char *errno_str;
} errno_list[] = { } errno_list[] = {
/* clang-format off */
#define STRINGIFY(x) #x #define STRINGIFY(x) #x
#define ENTRY(x) {x, &STRINGIFY(undef_ ## x)[6]} #define ENTRY(x) {x, &STRINGIFY(undef_ ## x)[6]}
ENTRY(EPERM), ENTRY(EPERM),
@@ -18,7 +20,9 @@ static struct {
ENTRY(EIO), ENTRY(EIO),
ENTRY(ENXIO), ENTRY(ENXIO),
ENTRY(E2BIG), ENTRY(E2BIG),
#ifdef ENOEXEC
ENTRY(ENOEXEC), ENTRY(ENOEXEC),
#endif
ENTRY(EBADF), ENTRY(EBADF),
ENTRY(ECHILD), ENTRY(ECHILD),
ENTRY(EDEADLK), ENTRY(EDEADLK),
@@ -52,9 +56,11 @@ static struct {
ENTRY(EAGAIN), ENTRY(EAGAIN),
{ 0, (char *)0 } { 0, (char *)0 }
}; };
/* clang-format on */
// Enabled during tests // Enabled during tests
int _json_c_strerror_enable = 0; static int _json_c_strerror_enable = 0;
extern char *getenv(const char *name); // Avoid including stdlib.h
#define PREFIX "ERRNO=" #define PREFIX "ERRNO="
static char errno_buf[128] = PREFIX; static char errno_buf[128] = PREFIX;
@@ -65,6 +71,8 @@ char *_json_c_strerror(int errno_in)
int ii, jj; int ii, jj;
if (!_json_c_strerror_enable) if (!_json_c_strerror_enable)
_json_c_strerror_enable = (getenv("_JSON_C_STRERROR_ENABLE") == NULL) ? -1 : 1;
if (_json_c_strerror_enable == -1)
return strerror(errno_in); return strerror(errno_in);
// Avoid standard functions, so we don't need to include any // Avoid standard functions, so we don't need to include any
@@ -76,7 +84,8 @@ char *_json_c_strerror(int errno_in)
if (errno_list[ii].errno_value != errno_in) if (errno_list[ii].errno_value != errno_in)
continue; continue;
for (start_idx = sizeof(PREFIX) - 1, jj = 0; errno_str[jj] != '\0'; jj++, start_idx++) for (start_idx = sizeof(PREFIX) - 1, jj = 0; errno_str[jj] != '\0';
jj++, start_idx++)
{ {
errno_buf[start_idx] = errno_str[jj]; errno_buf[start_idx] = errno_str[jj];
} }
@@ -85,17 +94,17 @@ char *_json_c_strerror(int errno_in)
} }
// It's not one of the known errno values, return the numeric value. // It's not one of the known errno values, return the numeric value.
for (ii = 0; errno_in > 10; errno_in /= 10, ii++) for (ii = 0; errno_in >= 10; errno_in /= 10, ii++)
{ {
digbuf[ii] = "0123456789"[(errno_in % 10)]; digbuf[ii] = "0123456789"[(errno_in % 10)];
} }
digbuf[ii] = "0123456789"[(errno_in % 10)]; digbuf[ii] = "0123456789"[(errno_in % 10)];
// Reverse the digits // Reverse the digits
for (start_idx = sizeof(PREFIX) - 1 ; ii >= 0; ii--, start_idx++) for (start_idx = sizeof(PREFIX) - 1; ii >= 0; ii--, start_idx++)
{ {
errno_buf[start_idx] = digbuf[ii]; errno_buf[start_idx] = digbuf[ii];
} }
errno_buf[start_idx] = '\0';
return errno_buf; return errno_buf;
} }

View File

@@ -20,11 +20,11 @@ extern "C" {
JSON_EXPORT char *_json_c_strerror(int errno_in); JSON_EXPORT char *_json_c_strerror(int errno_in);
#ifndef STRERROR_OVERRIDE_IMPL #ifndef STRERROR_OVERRIDE_IMPL
#define strerror _json_c_strerror #define strerror _json_c_strerror
#endif #endif
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif
#endif /* _json_strerror_override_h_ */ #endif /* _json_strerror_override_h_ */

View File

@@ -1,12 +0,0 @@
#ifndef __json_strerror_override_private_h__
#define __json_strerror_override_private_h__
/**
* @file
* @brief Do not use, json-c internal, may be changed or removed at any time.
*/
/* Used by tests to get consistent output */
extern int _json_c_strerror_enable;
#endif

64
tests/CMakeLists.txt Normal file
View File

@@ -0,0 +1,64 @@
cmake_minimum_required(VERSION 3.9)
add_executable(test1Formatted test1.c parse_flags.c parse_flags.h)
target_compile_definitions(test1Formatted PRIVATE TEST_FORMATTED=1)
target_link_libraries(test1Formatted PRIVATE ${PROJECT_NAME})
add_executable(test2Formatted test2.c parse_flags.c parse_flags.h)
target_compile_definitions(test2Formatted PRIVATE TEST_FORMATTED=1)
target_link_libraries(test2Formatted PRIVATE ${PROJECT_NAME})
# https://cmake.org/cmake/help/v3.0/command/add_test.html
# https://pabloariasal.github.io/2018/02/19/its-time-to-do-cmake-right/
include_directories(PUBLIC ${CMAKE_SOURCE_DIR})
set(ALL_TEST_NAMES
test1
test2
test4
testReplaceExisting
test_cast
test_charcase
test_compare
test_deep_copy
test_double_serializer
test_float
test_int_add
test_int_get
test_locale
test_null
test_parse
test_parse_int64
test_printbuf
test_set_serializer
test_set_value
test_strerror
test_util_file
test_visit
test_object_iterator)
if (NOT DISABLE_JSON_POINTER)
set(ALL_TEST_NAMES ${ALL_TEST_NAMES} test_json_pointer)
if (NOT DISABLE_JSON_PATCH)
set(ALL_TEST_NAMES ${ALL_TEST_NAMES} test_json_patch)
endif()
endif()
foreach(TESTNAME ${ALL_TEST_NAMES})
add_executable(${TESTNAME} ${TESTNAME}.c)
add_test(NAME ${TESTNAME} COMMAND ${PROJECT_SOURCE_DIR}/tests/${TESTNAME}.test)
# XXX using the non-target_ versions of these doesn't work :(
target_include_directories(
${TESTNAME}
PUBLIC
${CMAKE_CURRENT_LIST_DIR}
)
target_link_libraries(
${TESTNAME}
PRIVATE
${PROJECT_NAME}
)
endforeach(TESTNAME)

View File

@@ -1,64 +0,0 @@
AM_CPPFLAGS = -I$(top_srcdir) -I$(top_srcdir)/tests
LDADD= $(LIBJSON_LA)
LIBJSON_LA=$(top_builddir)/libjson-c.la
TESTS=
TESTS+= test_util_file.test
TESTS+= test_float.test
TESTS+= test1.test
TESTS+= test2.test
TESTS+= test4.test
TESTS+= testReplaceExisting.test
TESTS+= test_parse_int64.test
TESTS+= test_deep_copy.test
TESTS+= test_null.test
TESTS+= test_cast.test
TESTS+= test_double_serializer.test
TESTS+= test_parse.test
TESTS+= test_locale.test
TESTS+= test_charcase.test
TESTS+= test_printbuf.test
TESTS+= test_set_serializer.test
TESTS+= test_compare.test
TESTS+= test_set_value.test
TESTS+= test_visit.test
TESTS+= test_json_pointer.test
TESTS+= test_int_add.test
check_PROGRAMS=
check_PROGRAMS += $(TESTS:.test=)
EXTRA_DIST=
EXTRA_DIST += $(TESTS)
EXTRA_DIST += $(TESTS:.test=.expected)
EXTRA_DIST += test-defs.sh
EXTRA_DIST += valid.json
# Note: handled by test1.test
check_PROGRAMS += test1Formatted
test1Formatted_SOURCES = test1.c parse_flags.c parse_flags.h
test1Formatted_CPPFLAGS = $(AM_CPPFLAGS) -DTEST_FORMATTED
EXTRA_DIST+= test1Formatted_plain.expected
EXTRA_DIST+= test1Formatted_pretty.expected
EXTRA_DIST+= test1Formatted_spaced.expected
# Note: handled by test2.test
check_PROGRAMS += test2Formatted
test2Formatted_SOURCES = test2.c parse_flags.c parse_flags.h
test2Formatted_CPPFLAGS = $(AM_CPPFLAGS) -DTEST_FORMATTED
EXTRA_DIST+= test2Formatted_plain.expected
EXTRA_DIST+= test2Formatted_pretty.expected
EXTRA_DIST+= test2Formatted_spaced.expected
test_util_file_SOURCES = test_util_file.c
testsubdir=testSubDir
TESTS_ENVIRONMENT = top_builddir=$(top_builddir)
distclean-local:
-rm -rf $(testsubdir)
-rm -f *.vg.out

View File

@@ -0,0 +1,233 @@
[
{
"comment": "4.1. add with missing object",
"doc": { "q": { "bar": 2 } },
"patch": [ {"op": "add", "path": "/a/b", "value": 1} ],
"error":
"path /a does not exist -- missing objects are not created recursively"
},
{
"comment": "A.1. Adding an Object Member",
"doc": {
"foo": "bar"
},
"patch": [
{ "op": "add", "path": "/baz", "value": "qux" }
],
"expected": {
"baz": "qux",
"foo": "bar"
}
},
{
"comment": "A.2. Adding an Array Element",
"doc": {
"foo": [ "bar", "baz" ]
},
"patch": [
{ "op": "add", "path": "/foo/1", "value": "qux" }
],
"expected": {
"foo": [ "bar", "qux", "baz" ]
}
},
{
"comment": "A.3. Removing an Object Member",
"doc": {
"baz": "qux",
"foo": "bar"
},
"patch": [
{ "op": "remove", "path": "/baz" }
],
"expected": {
"foo": "bar"
}
},
{
"comment": "A.4. Removing an Array Element",
"doc": {
"foo": [ "bar", "qux", "baz" ]
},
"patch": [
{ "op": "remove", "path": "/foo/1" }
],
"expected": {
"foo": [ "bar", "baz" ]
}
},
{
"comment": "A.5. Replacing a Value",
"doc": {
"baz": "qux",
"foo": "bar"
},
"patch": [
{ "op": "replace", "path": "/baz", "value": "boo" }
],
"expected": {
"baz": "boo",
"foo": "bar"
}
},
{
"comment": "A.6. Moving a Value",
"doc": {
"foo": {
"bar": "baz",
"waldo": "fred"
},
"qux": {
"corge": "grault"
}
},
"patch": [
{ "op": "move", "from": "/foo/waldo", "path": "/qux/thud" }
],
"expected": {
"foo": {
"bar": "baz"
},
"qux": {
"corge": "grault",
"thud": "fred"
}
}
},
{
"comment": "A.7. Moving an Array Element",
"doc": {
"foo": [ "all", "grass", "cows", "eat" ]
},
"patch": [
{ "op": "move", "from": "/foo/1", "path": "/foo/3" }
],
"expected": {
"foo": [ "all", "cows", "eat", "grass" ]
}
},
{
"comment": "A.8. Testing a Value: Success",
"doc": {
"baz": "qux",
"foo": [ "a", 2, "c" ]
},
"patch": [
{ "op": "test", "path": "/baz", "value": "qux" },
{ "op": "test", "path": "/foo/1", "value": 2 }
],
"expected": {
"baz": "qux",
"foo": [ "a", 2, "c" ]
}
},
{
"comment": "A.9. Testing a Value: Error",
"doc": {
"baz": "qux"
},
"patch": [
{ "op": "test", "path": "/baz", "value": "bar" }
],
"error": "string not equivalent"
},
{
"comment": "A.10. Adding a nested Member Object",
"doc": {
"foo": "bar"
},
"patch": [
{ "op": "add", "path": "/child", "value": { "grandchild": { } } }
],
"expected": {
"foo": "bar",
"child": {
"grandchild": {
}
}
}
},
{
"comment": "A.11. Ignoring Unrecognized Elements",
"doc": {
"foo":"bar"
},
"patch": [
{ "op": "add", "path": "/baz", "value": "qux", "xyz": 123 }
],
"expected": {
"foo":"bar",
"baz":"qux"
}
},
{
"comment": "A.12. Adding to a Non-existent Target",
"doc": {
"foo": "bar"
},
"patch": [
{ "op": "add", "path": "/baz/bat", "value": "qux" }
],
"error": "add to a non-existent target"
},
{
"comment": "A.13 Invalid JSON Patch Document",
"doc": {
"foo": "bar"
},
"patch": [
{ "op": "add", "path": "/baz", "value": "qux", "op": "remove" }
],
"error_wont_happen_in_jsonc": "operation has two 'op' members",
"error": "Did not find element referenced by path field"
},
{
"comment": "A.14. ~ Escape Ordering",
"doc": {
"/": 9,
"~1": 10
},
"patch": [{"op": "test", "path": "/~01", "value": 10}],
"expected": {
"/": 9,
"~1": 10
}
},
{
"comment": "A.15. Comparing Strings and Numbers",
"doc": {
"/": 9,
"~1": 10
},
"patch": [{"op": "test", "path": "/~01", "value": "10"}],
"error": "number is not equal to string"
},
{
"comment": "A.16. Adding an Array Value",
"doc": {
"foo": ["bar"]
},
"patch": [{ "op": "add", "path": "/foo/-", "value": ["abc", "def"] }],
"expected": {
"foo": ["bar", ["abc", "def"]]
}
}
]

540
tests/json_patch_tests.json Normal file
View File

@@ -0,0 +1,540 @@
[
{ "comment": "empty list, empty docs",
"doc": {},
"patch": [],
"expected": {} },
{ "comment": "empty patch list",
"doc": {"foo": 1},
"patch": [],
"expected": {"foo": 1} },
{ "comment": "rearrangements OK?",
"doc": {"foo": 1, "bar": 2},
"patch": [],
"expected": {"bar":2, "foo": 1} },
{ "comment": "rearrangements OK? How about one level down ... array",
"doc": [{"foo": 1, "bar": 2}],
"patch": [],
"expected": [{"bar":2, "foo": 1}] },
{ "comment": "rearrangements OK? How about one level down...",
"doc": {"foo":{"foo": 1, "bar": 2}},
"patch": [],
"expected": {"foo":{"bar":2, "foo": 1}} },
{ "comment": "add replaces any existing field",
"doc": {"foo": null},
"patch": [{"op": "add", "path": "/foo", "value":1}],
"expected": {"foo": 1} },
{ "comment": "toplevel array",
"doc": [],
"patch": [{"op": "add", "path": "/0", "value": "foo"}],
"expected": ["foo"] },
{ "comment": "toplevel array, no change",
"doc": ["foo"],
"patch": [],
"expected": ["foo"] },
{ "comment": "toplevel object, numeric string",
"doc": {},
"patch": [{"op": "add", "path": "/foo", "value": "1"}],
"expected": {"foo":"1"} },
{ "comment": "toplevel object, integer",
"doc": {},
"patch": [{"op": "add", "path": "/foo", "value": 1}],
"expected": {"foo":1} },
{ "comment": "Toplevel scalar values OK?",
"doc": "foo",
"patch": [{"op": "replace", "path": "", "value": "bar"}],
"expected": "bar"
},
{ "comment": "replace object document with array document?",
"doc": {},
"patch": [{"op": "add", "path": "", "value": []}],
"expected": [] },
{ "comment": "replace array document with object document?",
"doc": [],
"patch": [{"op": "add", "path": "", "value": {}}],
"expected": {} },
{ "comment": "append to root array document?",
"doc": [],
"patch": [{"op": "add", "path": "/-", "value": "hi"}],
"expected": ["hi"] },
{ "comment": "Add, / target",
"doc": {},
"patch": [ {"op": "add", "path": "/", "value":1 } ],
"expected": {"":1} },
{ "comment": "Add, /foo/ deep target (trailing slash)",
"doc": {"foo": {}},
"patch": [ {"op": "add", "path": "/foo/", "value":1 } ],
"expected": {"foo":{"": 1}} },
{ "comment": "Add composite value at top level",
"doc": {"foo": 1},
"patch": [{"op": "add", "path": "/bar", "value": [1, 2]}],
"expected": {"foo": 1, "bar": [1, 2]} },
{ "comment": "Add into composite value",
"doc": {"foo": 1, "baz": [{"qux": "hello"}]},
"patch": [{"op": "add", "path": "/baz/0/foo", "value": "world"}],
"expected": {"foo": 1, "baz": [{"qux": "hello", "foo": "world"}]} },
{ "doc": {"bar": [1, 2]},
"patch": [{"op": "add", "path": "/bar/8", "value": "5"}],
"error": "Out of bounds (upper)" },
{ "doc": {"bar": [1, 2]},
"patch": [{"op": "add", "path": "/bar/-1", "value": "5"}],
"error": "Out of bounds (lower)" },
{ "doc": {"foo": 1},
"patch": [{"op": "add", "path": "/bar", "value": true}],
"expected": {"foo": 1, "bar": true} },
{ "doc": {"foo": 1},
"patch": [{"op": "add", "path": "/bar", "value": false}],
"expected": {"foo": 1, "bar": false} },
{ "doc": {"foo": 1},
"patch": [{"op": "add", "path": "/bar", "value": null}],
"expected": {"foo": 1, "bar": null} },
{ "comment": "0 can be an array index or object element name",
"doc": {"foo": 1},
"patch": [{"op": "add", "path": "/0", "value": "bar"}],
"expected": {"foo": 1, "0": "bar" } },
{ "doc": ["foo"],
"patch": [{"op": "add", "path": "/1", "value": "bar"}],
"expected": ["foo", "bar"] },
{ "doc": ["foo", "sil"],
"patch": [{"op": "add", "path": "/1", "value": "bar"}],
"expected": ["foo", "bar", "sil"] },
{ "doc": ["foo", "sil"],
"patch": [{"op": "add", "path": "/0", "value": "bar"}],
"expected": ["bar", "foo", "sil"] },
{ "comment": "push item to array via last index + 1",
"doc": ["foo", "sil"],
"patch": [{"op":"add", "path": "/2", "value": "bar"}],
"expected": ["foo", "sil", "bar"] },
{ "comment": "add item to array at index > length should fail",
"doc": ["foo", "sil"],
"patch": [{"op":"add", "path": "/3", "value": "bar"}],
"error": "index is greater than number of items in array" },
{ "comment": "test against implementation-specific numeric parsing",
"doc": {"1e0": "foo"},
"patch": [{"op": "test", "path": "/1e0", "value": "foo"}],
"expected": {"1e0": "foo"} },
{ "comment": "test with bad number should fail",
"doc": ["foo", "bar"],
"patch": [{"op": "test", "path": "/1e0", "value": "bar"}],
"error": "test op shouldn't get array element 1" },
{ "doc": ["foo", "sil"],
"patch": [{"op": "add", "path": "/bar", "value": 42}],
"error": "Object operation on array target" },
{ "doc": ["foo", "sil"],
"patch": [{"op": "add", "path": "/1", "value": ["bar", "baz"]}],
"expected": ["foo", ["bar", "baz"], "sil"],
"comment": "value in array add not flattened" },
{ "doc": {"foo": 1, "bar": [1, 2, 3, 4]},
"patch": [{"op": "remove", "path": "/bar"}],
"expected": {"foo": 1} },
{ "doc": {"foo": 1, "baz": [{"qux": "hello"}]},
"patch": [{"op": "remove", "path": "/baz/0/qux"}],
"expected": {"foo": 1, "baz": [{}]} },
{ "doc": {"foo": 1, "baz": [{"qux": "hello"}]},
"patch": [{"op": "replace", "path": "/foo", "value": [1, 2, 3, 4]}],
"expected": {"foo": [1, 2, 3, 4], "baz": [{"qux": "hello"}]} },
{ "doc": {"foo": [1, 2, 3, 4], "baz": [{"qux": "hello"}]},
"patch": [{"op": "replace", "path": "/baz/0/qux", "value": "world"}],
"expected": {"foo": [1, 2, 3, 4], "baz": [{"qux": "world"}]} },
{ "doc": ["foo"],
"patch": [{"op": "replace", "path": "/0", "value": "bar"}],
"expected": ["bar"] },
{ "doc": [""],
"patch": [{"op": "replace", "path": "/0", "value": 0}],
"expected": [0] },
{ "doc": [""],
"patch": [{"op": "replace", "path": "/0", "value": true}],
"expected": [true] },
{ "doc": [""],
"patch": [{"op": "replace", "path": "/0", "value": false}],
"expected": [false] },
{ "doc": [""],
"patch": [{"op": "replace", "path": "/0", "value": null}],
"expected": [null] },
{ "doc": ["foo", "sil"],
"patch": [{"op": "replace", "path": "/1", "value": ["bar", "baz"]}],
"expected": ["foo", ["bar", "baz"]],
"comment": "value in array replace not flattened" },
{ "comment": "replace whole document",
"doc": {"foo": "bar"},
"patch": [{"op": "replace", "path": "", "value": {"baz": "qux"}}],
"expected": {"baz": "qux"} },
{ "comment": "add whole document, null",
"doc": {},
"Note1": "We can't pass null in to json_patch_apply, so start with _something_ and remove it",
"patch": [
{"op": "remove", "path": ""},
{"op": "add", "path": "", "value": {"baz": "qux"}}
],
"expected": {"baz": "qux"} },
{ "comment": "replace whole document, null",
"doc": {},
"Note1": "We can't pass null in to json_patch_apply, so start with _something_ and remove it",
"patch": [
{"op": "remove", "path": ""},
{"op": "replace", "path": "", "value": {"baz": "qux"}}
],
"error": "The spec says the target location must exist, so replacing a null document fails"
},
{ "comment": "remove whole document",
"doc": {"foo": "bar"},
"patch": [{"op": "remove", "path": ""}],
"expected": null },
{ "comment": "remove whole document",
"doc": {"foo": "bar"},
"patch": [{"op": "remove", "path": ""}],
"expected": null },
{ "comment": "remove whole document, array",
"doc": ["foo", "bar"],
"patch": [{"op": "remove", "path": ""}],
"expected": null },
{ "comment": "remove whole document, string",
"doc": "foo",
"patch": [{"op": "remove", "path": ""}],
"expected": null },
{ "comment": "remove whole document, null",
"doc": {},
"Note1": "We can't pass null in to json_patch_apply, so start with _something_ and remove it",
"patch": [
{"op": "remove", "path": ""},
{"op": "remove", "path": ""},
],
"error": "The spec says the target location must exist, so removing a null document fails"
},
{ "comment": "test replace with missing parent key should fail",
"doc": {"bar": "baz"},
"patch": [{"op": "replace", "path": "/foo/bar", "value": false}],
"error": "replace op should fail with missing parent key" },
{ "comment": "spurious patch properties",
"doc": {"foo": 1},
"patch": [{"op": "test", "path": "/foo", "value": 1, "spurious": 1}],
"expected": {"foo": 1} },
{ "doc": {"foo": null},
"patch": [{"op": "test", "path": "/foo", "value": null}],
"expected": {"foo": null},
"comment": "null value should be valid obj property" },
{ "doc": {"foo": null},
"patch": [{"op": "replace", "path": "/foo", "value": "truthy"}],
"expected": {"foo": "truthy"},
"comment": "null value should be valid obj property to be replaced with something truthy" },
{ "doc": {"foo": null},
"patch": [{"op": "move", "from": "/foo", "path": "/bar"}],
"expected": {"bar": null},
"comment": "null value should be valid obj property to be moved" },
{ "doc": {"foo": null},
"patch": [{"op": "copy", "from": "/foo", "path": "/bar"}],
"expected": {"foo": null, "bar": null},
"comment": "null value should be valid obj property to be copied" },
{ "doc": {"foo": null},
"patch": [{"op": "remove", "path": "/foo"}],
"expected": {},
"comment": "null value should be valid obj property to be removed" },
{ "doc": {"foo": "bar"},
"patch": [{"op": "replace", "path": "/foo", "value": null}],
"expected": {"foo": null},
"comment": "null value should still be valid obj property replace other value" },
{ "doc": {"foo": {"foo": 1, "bar": 2}},
"patch": [{"op": "test", "path": "/foo", "value": {"bar": 2, "foo": 1}}],
"expected": {"foo": {"foo": 1, "bar": 2}},
"comment": "test should pass despite rearrangement" },
{ "doc": {"foo": [{"foo": 1, "bar": 2}]},
"patch": [{"op": "test", "path": "/foo", "value": [{"bar": 2, "foo": 1}]}],
"expected": {"foo": [{"foo": 1, "bar": 2}]},
"comment": "test should pass despite (nested) rearrangement" },
{ "doc": {"foo": {"bar": [1, 2, 5, 4]}},
"patch": [{"op": "test", "path": "/foo", "value": {"bar": [1, 2, 5, 4]}}],
"expected": {"foo": {"bar": [1, 2, 5, 4]}},
"comment": "test should pass - no error" },
{ "doc": {"foo": {"bar": [1, 2, 5, 4]}},
"patch": [{"op": "test", "path": "/foo", "value": [1, 2]}],
"error": "test op should fail" },
{ "comment": "Test the whole document",
"doc": { "foo": 1 },
"patch": [{"op": "test", "path": "", "value": {"foo": 1}}],
"expected": { "foo": 1 } },
{ "comment": "Test the whole document, no match",
"doc": { "foo": 1 },
"patch": [{"op": "test", "path": "", "value": {"foo": 2}}],
"expected": { "foo": 1 },
"error": "Tested value does not match original doc" },
{ "comment": "Empty-string element",
"doc": { "": 1 },
"patch": [{"op": "test", "path": "/", "value": 1}],
"expected": { "": 1 } },
{ "doc": {
"foo": ["bar", "baz"],
"": 0,
"a/b": 1,
"c%d": 2,
"e^f": 3,
"g|h": 4,
"i\\j": 5,
"k\"l": 6,
" ": 7,
"m~n": 8
},
"patch": [{"op": "test", "path": "/foo", "value": ["bar", "baz"]},
{"op": "test", "path": "/foo/0", "value": "bar"},
{"op": "test", "path": "/", "value": 0},
{"op": "test", "path": "/a~1b", "value": 1},
{"op": "test", "path": "/c%d", "value": 2},
{"op": "test", "path": "/e^f", "value": 3},
{"op": "test", "path": "/g|h", "value": 4},
{"op": "test", "path": "/i\\j", "value": 5},
{"op": "test", "path": "/k\"l", "value": 6},
{"op": "test", "path": "/ ", "value": 7},
{"op": "test", "path": "/m~0n", "value": 8}],
"expected": {
"": 0,
" ": 7,
"a/b": 1,
"c%d": 2,
"e^f": 3,
"foo": [
"bar",
"baz"
],
"g|h": 4,
"i\\j": 5,
"k\"l": 6,
"m~n": 8
}
},
{ "comment": "Move to same location has no effect",
"doc": {"foo": 1},
"patch": [{"op": "move", "from": "/foo", "path": "/foo"}],
"expected": {"foo": 1} },
{ "doc": {"foo": 1, "baz": [{"qux": "hello"}]},
"patch": [{"op": "move", "from": "/foo", "path": "/bar"}],
"expected": {"baz": [{"qux": "hello"}], "bar": 1} },
{ "doc": {"baz": [{"qux": "hello"}], "bar": 1},
"patch": [{"op": "move", "from": "/baz/0/qux", "path": "/baz/1"}],
"expected": {"baz": [{}, "hello"], "bar": 1} },
{ "doc": {"baz": [{"qux": "hello"}], "bar": 1},
"patch": [{"op": "copy", "from": "/baz/0", "path": "/boo"}],
"expected": {"baz":[{"qux":"hello"}],"bar":1,"boo":{"qux":"hello"}} },
{ "comment": "replacing the root of the document is possible with add",
"doc": {"foo": "bar"},
"patch": [{"op": "add", "path": "", "value": {"baz": "qux"}}],
"expected": {"baz":"qux"}},
{ "comment": "Adding to \"/-\" adds to the end of the array",
"doc": [ 1, 2 ],
"patch": [ { "op": "add", "path": "/-", "value": { "foo": [ "bar", "baz" ] } } ],
"expected": [ 1, 2, { "foo": [ "bar", "baz" ] } ]},
{ "comment": "Adding to \"/-\" adds to the end of the array, even n levels down",
"doc": [ 1, 2, [ 3, [ 4, 5 ] ] ],
"patch": [ { "op": "add", "path": "/2/1/-", "value": { "foo": [ "bar", "baz" ] } } ],
"expected": [ 1, 2, [ 3, [ 4, 5, { "foo": [ "bar", "baz" ] } ] ] ]},
{ "comment": "test remove with bad number should fail",
"doc": {"foo": 1, "baz": [{"qux": "hello"}]},
"patch": [{"op": "remove", "path": "/baz/1e0/qux"}],
"error": "remove op shouldn't remove from array with bad number" },
{ "comment": "test remove on array",
"doc": [1, 2, 3, 4],
"patch": [{"op": "remove", "path": "/0"}],
"expected": [2, 3, 4] },
{ "comment": "test repeated removes",
"doc": [1, 2, 3, 4],
"patch": [{ "op": "remove", "path": "/1" },
{ "op": "remove", "path": "/2" }],
"expected": [1, 3] },
{ "comment": "test remove with bad index should fail",
"doc": [1, 2, 3, 4],
"patch": [{"op": "remove", "path": "/1e0"}],
"error": "remove op shouldn't remove from array with bad number" },
{ "comment": "test replace with bad number should fail",
"doc": [""],
"patch": [{"op": "replace", "path": "/1e0", "value": false}],
"error": "replace op shouldn't replace in array with bad number" },
{ "comment": "test copy with bad number should fail",
"doc": {"baz": [1,2,3], "bar": 1},
"patch": [{"op": "copy", "from": "/baz/1e0", "path": "/boo"}],
"error": "copy op shouldn't work with bad number" },
{ "comment": "test move with bad number should fail",
"doc": {"foo": 1, "baz": [1,2,3,4]},
"patch": [{"op": "move", "from": "/baz/1e0", "path": "/foo"}],
"error": "move op shouldn't work with bad number" },
{ "comment": "test add with bad number should fail",
"doc": ["foo", "sil"],
"patch": [{"op": "add", "path": "/1e0", "value": "bar"}],
"error": "add op shouldn't add to array with bad number" },
{ "comment": "missing 'path' parameter",
"doc": {},
"patch": [ { "op": "add", "value": "bar" } ],
"error": "missing 'path' parameter" },
{ "comment": "'path' parameter with null value",
"doc": {},
"patch": [ { "op": "add", "path": null, "value": "bar" } ],
"error": "null is not valid value for 'path'" },
{ "comment": "invalid JSON Pointer token",
"doc": {},
"patch": [ { "op": "add", "path": "foo", "value": "bar" } ],
"error": "JSON Pointer should start with a slash" },
{ "comment": "missing 'value' parameter to add",
"doc": [ 1 ],
"patch": [ { "op": "add", "path": "/-" } ],
"error": "missing 'value' parameter" },
{ "comment": "missing 'value' parameter to replace",
"doc": [ 1 ],
"patch": [ { "op": "replace", "path": "/0" } ],
"error": "missing 'value' parameter" },
{ "comment": "missing 'value' parameter to test",
"doc": [ null ],
"patch": [ { "op": "test", "path": "/0" } ],
"error": "missing 'value' parameter" },
{ "comment": "missing value parameter to test - where undef is falsy",
"doc": [ false ],
"patch": [ { "op": "test", "path": "/0" } ],
"error": "missing 'value' parameter" },
{ "comment": "missing from parameter to copy",
"doc": [ 1 ],
"patch": [ { "op": "copy", "path": "/-" } ],
"error": "missing 'from' parameter" },
{ "comment": "missing from location to copy",
"doc": { "foo": 1 },
"patch": [ { "op": "copy", "from": "/bar", "path": "/foo" } ],
"error": "missing 'from' location" },
{ "comment": "missing from parameter to move",
"doc": { "foo": 1 },
"patch": [ { "op": "move", "path": "" } ],
"error": "missing 'from' parameter" },
{ "comment": "missing from location to move",
"doc": { "foo": 1 },
"patch": [ { "op": "move", "from": "/bar", "path": "/foo" } ],
"error": "missing 'from' location" },
{ "comment": "duplicate ops, json-c parses this as op:move",
"doc": { "foo": "bar" },
"patch": [ { "op": "add", "path": "/baz", "value": "qux",
"op": "move", "from":"/foo" } ],
"error_wont_happen_in_jsonc": "patch has two 'op' members",
"expected": { "baz": "bar" }
},
{ "comment": "unrecognized op should fail",
"doc": {"foo": 1},
"patch": [{"op": "spam", "path": "/foo", "value": 1}],
"error": "Unrecognized op 'spam'" },
{ "comment": "test with bad array number that has leading zeros",
"doc": ["foo", "bar"],
"patch": [{"op": "test", "path": "/00", "value": "foo"}],
"error": "test op should reject the array value, it has leading zeros" },
{ "comment": "test with bad array number that has leading zeros",
"doc": ["foo", "bar"],
"patch": [{"op": "test", "path": "/01", "value": "bar"}],
"error": "test op should reject the array value, it has leading zeros" },
{ "comment": "Removing nonexistent field",
"doc": {"foo" : "bar"},
"patch": [{"op": "remove", "path": "/baz"}],
"error": "removing a nonexistent field should fail" },
{ "comment": "Removing deep nonexistent path",
"doc": {"foo" : "bar"},
"patch": [{"op": "remove", "path": "/missing1/missing2"}],
"error": "removing a nonexistent field should fail" },
{ "comment": "Removing nonexistent index",
"doc": ["foo", "bar"],
"patch": [{"op": "remove", "path": "/2"}],
"error": "removing a nonexistent index should fail" },
{ "comment": "Patch with different capitalisation than doc",
"doc": {"foo":"bar"},
"patch": [{"op": "add", "path": "/FOO", "value": "BAR"}],
"expected": {"foo": "bar", "FOO": "BAR"}
}
]

View File

@@ -1,3 +1,6 @@
#ifdef NDEBUG
#undef NDEBUG
#endif
#include "config.h" #include "config.h"
#include <stdio.h> #include <stdio.h>
@@ -7,18 +10,20 @@
#include "parse_flags.h" #include "parse_flags.h"
#if !defined(HAVE_STRCASECMP) && defined(_MSC_VER) #if !defined(HAVE_STRCASECMP) && defined(_MSC_VER)
# define strcasecmp _stricmp #define strcasecmp _stricmp
#elif !defined(HAVE_STRCASECMP) #elif !defined(HAVE_STRCASECMP)
# error You do not have strcasecmp on your system. #error You do not have strcasecmp on your system.
#endif /* HAVE_STRNCASECMP */ #endif /* HAVE_STRNCASECMP */
static struct { static struct
{
const char *arg; const char *arg;
int flag; int flag;
} format_args[] = { } format_args[] = {
{ "plain", JSON_C_TO_STRING_PLAIN }, {"plain", JSON_C_TO_STRING_PLAIN},
{ "spaced", JSON_C_TO_STRING_SPACED }, {"spaced", JSON_C_TO_STRING_SPACED},
{ "pretty", JSON_C_TO_STRING_PRETTY }, {"pretty", JSON_C_TO_STRING_PRETTY},
{"pretty_tab", JSON_C_TO_STRING_PRETTY_TAB},
}; };
#ifndef NELEM #ifndef NELEM
@@ -29,7 +34,7 @@ int parse_flags(int argc, char **argv)
{ {
int arg_idx; int arg_idx;
int sflags = 0; int sflags = 0;
for (arg_idx = 1; arg_idx < argc ; arg_idx++) for (arg_idx = 1; arg_idx < argc; arg_idx++)
{ {
int jj; int jj;
for (jj = 0; jj < (int)NELEM(format_args); jj++) for (jj = 0; jj < (int)NELEM(format_args); jj++)

View File

@@ -1,5 +1,10 @@
#!/bin/sh #!/bin/sh
if [ ! -z "$JSONC_TEST_TRACE" ] ; then
VERBOSE=1
set -x
set -v
fi
# Make sure srcdir is an absolute path. Supply the variable # Make sure srcdir is an absolute path. Supply the variable
# if it does not exist. We want to be able to run the tests # if it does not exist. We want to be able to run the tests
# stand-alone!! # stand-alone!!
@@ -85,7 +90,7 @@ run_output_test()
fi fi
TEST_COMMAND="$1" TEST_COMMAND="$1"
shift shift
if [ -z "${TEST_OUTPUT}" ] ; then if [ -z "${TEST_OUTPUT}" ] ; then
TEST_OUTPUT=${TEST_COMMAND} TEST_OUTPUT=${TEST_COMMAND}
fi fi

View File

@@ -1,19 +1,25 @@
#ifdef NDEBUG
#undef NDEBUG
#endif
#include <assert.h>
#include <limits.h>
#include <stddef.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <stddef.h>
#include <string.h> #include <string.h>
#include <assert.h>
#include "config.h"
#include "json.h" #include "json.h"
#include "parse_flags.h" #include "parse_flags.h"
static int sort_fn (const void *j1, const void *j2) static int sort_fn(const void *j1, const void *j2)
{ {
json_object * const *jso1, * const *jso2; json_object *const *jso1, *const *jso2;
int i1, i2; int i1, i2;
jso1 = (json_object* const*)j1; jso1 = (json_object *const *)j1;
jso2 = (json_object* const*)j2; jso2 = (json_object *const *)j2;
if (!*jso1 && !*jso2) if (!*jso1 && !*jso2)
return 0; return 0;
if (!*jso1) if (!*jso1)
@@ -38,7 +44,8 @@ static const char *to_json_string(json_object *obj, int flags)
copy = strdup(result); copy = strdup(result);
if (copy == NULL) if (copy == NULL)
printf("to_json_string: Allocation failed!\n"); printf("to_json_string: Allocation failed!\n");
else { else
{
result = json_object_to_json_string_ext(obj, flags); result = json_object_to_json_string_ext(obj, flags);
if (length != strlen(result)) if (length != strlen(result))
printf("to_json_string: Length mismatch!\n"); printf("to_json_string: Length mismatch!\n");
@@ -48,13 +55,13 @@ static const char *to_json_string(json_object *obj, int flags)
} }
return result; return result;
} }
#define json_object_to_json_string(obj) to_json_string(obj,sflags) #define json_object_to_json_string(obj) to_json_string(obj, sflags)
#else #else
/* no special define */ /* no special define */
#endif #endif
json_object *make_array(void); json_object *make_array(void);
json_object *make_array() json_object *make_array(void)
{ {
json_object *my_array; json_object *my_array;
@@ -70,7 +77,7 @@ json_object *make_array()
} }
void test_array_del_idx(void); void test_array_del_idx(void);
void test_array_del_idx() void test_array_del_idx(void)
{ {
int rc; int rc;
size_t ii; size_t ii;
@@ -84,7 +91,7 @@ void test_array_del_idx()
orig_array_len = json_object_array_length(my_array); orig_array_len = json_object_array_length(my_array);
printf("my_array=\n"); printf("my_array=\n");
for(ii = 0; ii < json_object_array_length(my_array); ii++) for (ii = 0; ii < json_object_array_length(my_array); ii++)
{ {
json_object *obj = json_object_array_get_idx(my_array, ii); json_object *obj = json_object_array_get_idx(my_array, ii);
printf("\t[%d]=%s\n", (int)ii, json_object_to_json_string(obj)); printf("\t[%d]=%s\n", (int)ii, json_object_to_json_string(obj));
@@ -94,38 +101,38 @@ void test_array_del_idx()
for (ii = 0; ii < orig_array_len; ii++) for (ii = 0; ii < orig_array_len; ii++)
{ {
rc = json_object_array_del_idx(my_array, 0, 1); rc = json_object_array_del_idx(my_array, 0, 1);
printf("after del_idx(0,1)=%d, my_array.to_string()=%s\n", printf("after del_idx(0,1)=%d, my_array.to_string()=%s\n", rc,
rc, json_object_to_json_string(my_array)); json_object_to_json_string(my_array));
} }
/* One more time, with the empty array: */ /* One more time, with the empty array: */
rc = json_object_array_del_idx(my_array, 0, 1); rc = json_object_array_del_idx(my_array, 0, 1);
printf("after del_idx(0,1)=%d, my_array.to_string()=%s\n", printf("after del_idx(0,1)=%d, my_array.to_string()=%s\n", rc,
rc, json_object_to_json_string(my_array)); json_object_to_json_string(my_array));
json_object_put(my_array); json_object_put(my_array);
/* Delete all array indexes at once */ /* Delete all array indexes at once */
my_array = make_array(); my_array = make_array();
rc = json_object_array_del_idx(my_array, 0, orig_array_len); rc = json_object_array_del_idx(my_array, 0, orig_array_len);
printf("after del_idx(0,%d)=%d, my_array.to_string()=%s\n", printf("after del_idx(0,%d)=%d, my_array.to_string()=%s\n", (int)orig_array_len, rc,
(int)orig_array_len, rc, json_object_to_json_string(my_array)); json_object_to_json_string(my_array));
json_object_put(my_array); json_object_put(my_array);
/* Delete *more* than all array indexes at once */ /* Delete *more* than all array indexes at once */
my_array = make_array(); my_array = make_array();
rc = json_object_array_del_idx(my_array, 0, orig_array_len + 1); rc = json_object_array_del_idx(my_array, 0, orig_array_len + 1);
printf("after del_idx(0,%d)=%d, my_array.to_string()=%s\n", printf("after del_idx(0,%d)=%d, my_array.to_string()=%s\n", (int)(orig_array_len + 1), rc,
(int)(orig_array_len + 1), rc, json_object_to_json_string(my_array)); json_object_to_json_string(my_array));
json_object_put(my_array); json_object_put(my_array);
/* Delete some array indexes, then add more */ /* Delete some array indexes, then add more */
my_array = make_array(); my_array = make_array();
rc = json_object_array_del_idx(my_array, 0, orig_array_len - 1); rc = json_object_array_del_idx(my_array, 0, orig_array_len - 1);
printf("after del_idx(0,%d)=%d, my_array.to_string()=%s\n", printf("after del_idx(0,%d)=%d, my_array.to_string()=%s\n", (int)(orig_array_len - 1), rc,
(int)(orig_array_len - 1), rc, json_object_to_json_string(my_array)); json_object_to_json_string(my_array));
json_object_array_add(my_array, json_object_new_string("s1")); json_object_array_add(my_array, json_object_new_string("s1"));
json_object_array_add(my_array, json_object_new_string("s2")); json_object_array_add(my_array, json_object_new_string("s2"));
json_object_array_add(my_array, json_object_new_string("s3")); json_object_array_add(my_array, json_object_new_string("s3"));
@@ -135,9 +142,92 @@ void test_array_del_idx()
json_object_put(my_array); json_object_put(my_array);
} }
void test_array_list_expand_internal(void);
void test_array_list_expand_internal(void)
{
int rc;
size_t ii;
size_t idx;
json_object *my_array;
#ifdef TEST_FORMATTED
int sflags = 0;
#endif
my_array = make_array();
printf("my_array=\n");
for (ii = 0; ii < json_object_array_length(my_array); ii++)
{
json_object *obj = json_object_array_get_idx(my_array, ii);
printf("\t[%d]=%s\n", (int)ii, json_object_to_json_string(obj));
}
printf("my_array.to_string()=%s\n", json_object_to_json_string(my_array));
/* Put iNdex < array->size, no expand. */
rc = json_object_array_put_idx(my_array, 5, json_object_new_int(6));
printf("put_idx(5,6)=%d\n", rc);
/* array->size < Put Index < array->size * 2 <= SIZE_T_MAX, the size = array->size * 2. */
idx = ARRAY_LIST_DEFAULT_SIZE * 2 - 1;
rc = json_object_array_put_idx(my_array, idx, json_object_new_int(0));
printf("put_idx(%d,0)=%d\n", (int)(idx), rc);
/* array->size * 2 < Put Index, the size = Put Index. */
idx = ARRAY_LIST_DEFAULT_SIZE * 2 * 2 + 1;
rc = json_object_array_put_idx(my_array, idx, json_object_new_int(0));
printf("put_idx(%d,0)=%d\n", (int)(idx), rc);
/* SIZE_T_MAX <= Put Index, it will fail and the size will no change. */
idx = SIZE_MAX; // SIZE_MAX = SIZE_T_MAX
json_object *tmp = json_object_new_int(10);
rc = json_object_array_put_idx(my_array, idx, tmp);
printf("put_idx(SIZE_T_MAX,0)=%d\n", rc);
if (rc == -1)
{
json_object_put(tmp);
}
json_object_put(my_array);
}
void test_array_insert_idx(void);
void test_array_insert_idx(void)
{
json_object *my_array;
struct json_object *jo1;
my_array = json_object_new_array();
json_object_array_add(my_array, json_object_new_int(1));
json_object_array_add(my_array, json_object_new_int(2));
json_object_array_add(my_array, json_object_new_int(5));
json_object_array_insert_idx(my_array, 2, json_object_new_int(4));
jo1 = json_tokener_parse("[1, 2, 4, 5]");
assert(1 == json_object_equal(my_array, jo1));
json_object_put(jo1);
json_object_array_insert_idx(my_array, 2, json_object_new_int(3));
jo1 = json_tokener_parse("[1, 2, 3, 4, 5]");
assert(1 == json_object_equal(my_array, jo1));
json_object_put(jo1);
json_object_array_insert_idx(my_array, 5, json_object_new_int(6));
jo1 = json_tokener_parse("[1, 2, 3, 4, 5, 6]");
assert(1 == json_object_equal(my_array, jo1));
json_object_put(jo1);
json_object_array_insert_idx(my_array, 7, json_object_new_int(8));
jo1 = json_tokener_parse("[1, 2, 3, 4, 5, 6, null, 8]");
assert(1 == json_object_equal(my_array, jo1));
json_object_put(jo1);
json_object_put(my_array);
}
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
json_object *my_string, *my_int, *my_object, *my_array; json_object *my_string, *my_int, *my_null, *my_object, *my_array;
size_t i; size_t i;
#ifdef TEST_FORMATTED #ifdef TEST_FORMATTED
int sflags = 0; int sflags = 0;
@@ -162,13 +252,15 @@ int main(int argc, char **argv)
my_string = json_object_new_string("/"); my_string = json_object_new_string("/");
printf("my_string=%s\n", json_object_get_string(my_string)); printf("my_string=%s\n", json_object_get_string(my_string));
printf("my_string.to_string()=%s\n", json_object_to_json_string(my_string)); printf("my_string.to_string()=%s\n", json_object_to_json_string(my_string));
printf("my_string.to_string(NOSLASHESCAPE)=%s\n", json_object_to_json_string_ext(my_string, JSON_C_TO_STRING_NOSLASHESCAPE)); printf("my_string.to_string(NOSLASHESCAPE)=%s\n",
json_object_to_json_string_ext(my_string, JSON_C_TO_STRING_NOSLASHESCAPE));
json_object_put(my_string); json_object_put(my_string);
my_string = json_object_new_string("/foo/bar/baz"); my_string = json_object_new_string("/foo/bar/baz");
printf("my_string=%s\n", json_object_get_string(my_string)); printf("my_string=%s\n", json_object_get_string(my_string));
printf("my_string.to_string()=%s\n", json_object_to_json_string(my_string)); printf("my_string.to_string()=%s\n", json_object_to_json_string(my_string));
printf("my_string.to_string(NOSLASHESCAPE)=%s\n", json_object_to_json_string_ext(my_string, JSON_C_TO_STRING_NOSLASHESCAPE)); printf("my_string.to_string(NOSLASHESCAPE)=%s\n",
json_object_to_json_string_ext(my_string, JSON_C_TO_STRING_NOSLASHESCAPE));
json_object_put(my_string); json_object_put(my_string);
my_string = json_object_new_string("foo"); my_string = json_object_new_string("foo");
@@ -179,13 +271,16 @@ int main(int argc, char **argv)
printf("my_int=%d\n", json_object_get_int(my_int)); printf("my_int=%d\n", json_object_get_int(my_int));
printf("my_int.to_string()=%s\n", json_object_to_json_string(my_int)); printf("my_int.to_string()=%s\n", json_object_to_json_string(my_int));
my_null = json_object_new_null();
printf("my_null.to_string()=%s\n", json_object_to_json_string(my_null));
my_array = json_object_new_array(); my_array = json_object_new_array();
json_object_array_add(my_array, json_object_new_int(1)); json_object_array_add(my_array, json_object_new_int(1));
json_object_array_add(my_array, json_object_new_int(2)); json_object_array_add(my_array, json_object_new_int(2));
json_object_array_add(my_array, json_object_new_int(3)); json_object_array_add(my_array, json_object_new_int(3));
json_object_array_put_idx(my_array, 4, json_object_new_int(5)); json_object_array_put_idx(my_array, 4, json_object_new_int(5));
printf("my_array=\n"); printf("my_array=\n");
for(i=0; i < json_object_array_length(my_array); i++) for (i = 0; i < json_object_array_length(my_array); i++)
{ {
json_object *obj = json_object_array_get_idx(my_array, i); json_object *obj = json_object_array_get_idx(my_array, i);
printf("\t[%d]=%s\n", (int)i, json_object_to_json_string(obj)); printf("\t[%d]=%s\n", (int)i, json_object_to_json_string(obj));
@@ -194,15 +289,18 @@ int main(int argc, char **argv)
json_object_put(my_array); json_object_put(my_array);
test_array_del_idx(); test_array_insert_idx();
my_array = json_object_new_array(); test_array_del_idx();
test_array_list_expand_internal();
my_array = json_object_new_array_ext(5);
json_object_array_add(my_array, json_object_new_int(3)); json_object_array_add(my_array, json_object_new_int(3));
json_object_array_add(my_array, json_object_new_int(1)); json_object_array_add(my_array, json_object_new_int(1));
json_object_array_add(my_array, json_object_new_int(2)); json_object_array_add(my_array, json_object_new_int(2));
json_object_array_put_idx(my_array, 4, json_object_new_int(0)); json_object_array_put_idx(my_array, 4, json_object_new_int(0));
printf("my_array=\n"); printf("my_array=\n");
for(i=0; i < json_object_array_length(my_array); i++) for (i = 0; i < json_object_array_length(my_array); i++)
{ {
json_object *obj = json_object_array_get_idx(my_array, i); json_object *obj = json_object_array_get_idx(my_array, i);
printf("\t[%d]=%s\n", (int)i, json_object_to_json_string(obj)); printf("\t[%d]=%s\n", (int)i, json_object_to_json_string(obj));
@@ -210,13 +308,19 @@ int main(int argc, char **argv)
printf("my_array.to_string()=%s\n", json_object_to_json_string(my_array)); printf("my_array.to_string()=%s\n", json_object_to_json_string(my_array));
json_object_array_sort(my_array, sort_fn); json_object_array_sort(my_array, sort_fn);
printf("my_array=\n"); printf("my_array=\n");
for(i=0; i < json_object_array_length(my_array); i++) for (i = 0; i < json_object_array_length(my_array); i++)
{ {
json_object *obj = json_object_array_get_idx(my_array, i); json_object *obj = json_object_array_get_idx(my_array, i);
printf("\t[%d]=%s\n", (int)i, json_object_to_json_string(obj)); printf("\t[%d]=%s\n", (int)i, json_object_to_json_string(obj));
} }
printf("my_array.to_string()=%s\n", json_object_to_json_string(my_array)); printf("my_array.to_string()=%s\n", json_object_to_json_string(my_array));
json_object *one = json_object_new_int(1);
json_object *result = json_object_array_bsearch(one, my_array, sort_fn);
printf("find json_object(1) in my_array successfully: %s\n",
json_object_to_json_string(result));
json_object_put(one);
my_object = json_object_new_object(); my_object = json_object_new_object();
int rc = json_object_object_add(my_object, "abc", my_object); int rc = json_object_object_add(my_object, "abc", my_object);
if (rc != -1) if (rc != -1)
@@ -245,10 +349,37 @@ int main(int argc, char **argv)
{ {
printf("\t%s: %s\n", key, json_object_to_json_string(val)); printf("\t%s: %s\n", key, json_object_to_json_string(val));
} }
json_object *empty_array = json_object_new_array();
json_object *empty_obj = json_object_new_object();
json_object_object_add(my_object, "empty_array", empty_array);
json_object_object_add(my_object, "empty_obj", empty_obj);
printf("my_object.to_string()=%s\n", json_object_to_json_string(my_object)); printf("my_object.to_string()=%s\n", json_object_to_json_string(my_object));
json_object_put(my_array);
my_array = json_object_new_array_ext(INT_MIN + 1);
if (my_array != NULL)
{
printf("ERROR: able to allocate an array of negative size!\n");
fflush(stdout);
json_object_put(my_array);
my_array = NULL;
}
#if SIZEOF_SIZE_T == SIZEOF_INT
my_array = json_object_new_array_ext(INT_MAX / 2 + 2);
if (my_array != NULL)
{
printf("ERROR: able to allocate an array of insufficient size!\n");
fflush(stdout);
json_object_put(my_array);
my_array = NULL;
}
#endif
json_object_put(my_string); json_object_put(my_string);
json_object_put(my_int); json_object_put(my_int);
json_object_put(my_null);
json_object_put(my_object); json_object_put(my_object);
json_object_put(my_array); json_object_put(my_array);

View File

@@ -12,6 +12,7 @@ my_string=foo
my_string.to_string()="foo" my_string.to_string()="foo"
my_int=9 my_int=9
my_int.to_string()=9 my_int.to_string()=9
my_null.to_string()=null
my_array= my_array=
[0]=1 [0]=1
[1]=2 [1]=2
@@ -40,6 +41,19 @@ after del_idx(0,7)=0, my_array.to_string()=[ ]
after del_idx(0,8)=-1, my_array.to_string()=[ 1, 2, 3, 4, 5, null, 7 ] after del_idx(0,8)=-1, my_array.to_string()=[ 1, 2, 3, 4, 5, null, 7 ]
after del_idx(0,6)=0, my_array.to_string()=[ 7 ] after del_idx(0,6)=0, my_array.to_string()=[ 7 ]
after adding more entries, my_array.to_string()=[ 7, "s1", "s2", "s3" ] after adding more entries, my_array.to_string()=[ 7, "s1", "s2", "s3" ]
my_array=
[0]=1
[1]=2
[2]=3
[3]=4
[4]=5
[5]=null
[6]=7
my_array.to_string()=[ 1, 2, 3, 4, 5, null, 7 ]
put_idx(5,6)=0
put_idx(63,0)=0
put_idx(129,0)=0
put_idx(SIZE_T_MAX,0)=-1
my_array= my_array=
[0]=3 [0]=3
[1]=1 [1]=1
@@ -54,10 +68,11 @@ my_array=
[3]=2 [3]=2
[4]=3 [4]=3
my_array.to_string()=[ null, 0, 1, 2, 3 ] my_array.to_string()=[ null, 0, 1, 2, 3 ]
find json_object(1) in my_array successfully: 1
baz_obj.to_string()="fark" baz_obj.to_string()="fark"
my_object= my_object=
abc: 12 abc: 12
foo: "bar" foo: "bar"
bool0: false bool0: false
bool1: true bool1: true
my_object.to_string()={ "abc": 12, "foo": "bar", "bool0": false, "bool1": true } my_object.to_string()={ "abc": 12, "foo": "bar", "bool0": false, "bool1": true, "empty_array": [ ], "empty_obj": { } }

View File

@@ -19,4 +19,20 @@ for flag in plain spaced pretty ; do
fi fi
done done
# Spaced and pretty JSON string
run_output_test -o test1Formatted_spaced_pretty \
test1Formatted spaced pretty
_err2=$?
if [ $_err -eq 0 ] ; then
_err=$_err2
fi
# Spaced and pretty JSON string using tabs
run_output_test -o test1Formatted_spaced_pretty_pretty_tab \
test1Formatted spaced pretty pretty_tab
_err2=$?
if [ $_err -eq 0 ] ; then
_err=$_err2
fi
exit $_err exit $_err

View File

@@ -12,6 +12,7 @@ my_string=foo
my_string.to_string()="foo" my_string.to_string()="foo"
my_int=9 my_int=9
my_int.to_string()=9 my_int.to_string()=9
my_null.to_string()=null
my_array= my_array=
[0]=1 [0]=1
[1]=2 [1]=2
@@ -40,6 +41,19 @@ after del_idx(0,7)=0, my_array.to_string()=[]
after del_idx(0,8)=-1, my_array.to_string()=[1,2,3,4,5,null,7] after del_idx(0,8)=-1, my_array.to_string()=[1,2,3,4,5,null,7]
after del_idx(0,6)=0, my_array.to_string()=[7] after del_idx(0,6)=0, my_array.to_string()=[7]
after adding more entries, my_array.to_string()=[7,"s1","s2","s3"] after adding more entries, my_array.to_string()=[7,"s1","s2","s3"]
my_array=
[0]=1
[1]=2
[2]=3
[3]=4
[4]=5
[5]=null
[6]=7
my_array.to_string()=[1,2,3,4,5,null,7]
put_idx(5,6)=0
put_idx(63,0)=0
put_idx(129,0)=0
put_idx(SIZE_T_MAX,0)=-1
my_array= my_array=
[0]=3 [0]=3
[1]=1 [1]=1
@@ -54,10 +68,11 @@ my_array=
[3]=2 [3]=2
[4]=3 [4]=3
my_array.to_string()=[null,0,1,2,3] my_array.to_string()=[null,0,1,2,3]
find json_object(1) in my_array successfully: 1
baz_obj.to_string()="fark" baz_obj.to_string()="fark"
my_object= my_object=
abc: 12 abc: 12
foo: "bar" foo: "bar"
bool0: false bool0: false
bool1: true bool1: true
my_object.to_string()={"abc":12,"foo":"bar","bool0":false,"bool1":true} my_object.to_string()={"abc":12,"foo":"bar","bool0":false,"bool1":true,"empty_array":[],"empty_obj":{}}

View File

@@ -12,6 +12,7 @@ my_string=foo
my_string.to_string()="foo" my_string.to_string()="foo"
my_int=9 my_int=9
my_int.to_string()=9 my_int.to_string()=9
my_null.to_string()=null
my_array= my_array=
[0]=1 [0]=1
[1]=2 [1]=2
@@ -46,6 +47,19 @@ after del_idx(0,7)=0, my_array.to_string()=[]
after del_idx(0,8)=-1, my_array.to_string()=[1,2,3,4,5,null,7] after del_idx(0,8)=-1, my_array.to_string()=[1,2,3,4,5,null,7]
after del_idx(0,6)=0, my_array.to_string()=[7] after del_idx(0,6)=0, my_array.to_string()=[7]
after adding more entries, my_array.to_string()=[7,"s1","s2","s3"] after adding more entries, my_array.to_string()=[7,"s1","s2","s3"]
my_array=
[0]=1
[1]=2
[2]=3
[3]=4
[4]=5
[5]=null
[6]=7
my_array.to_string()=[1,2,3,4,5,null,7]
put_idx(5,6)=0
put_idx(63,0)=0
put_idx(129,0)=0
put_idx(SIZE_T_MAX,0)=-1
my_array= my_array=
[0]=3 [0]=3
[1]=1 [1]=1
@@ -72,6 +86,7 @@ my_array.to_string()=[
2, 2,
3 3
] ]
find json_object(1) in my_array successfully: 1
baz_obj.to_string()="fark" baz_obj.to_string()="fark"
my_object= my_object=
abc: 12 abc: 12
@@ -82,5 +97,7 @@ my_object.to_string()={
"abc":12, "abc":12,
"foo":"bar", "foo":"bar",
"bool0":false, "bool0":false,
"bool1":true "bool1":true,
"empty_array":[],
"empty_obj":{}
} }

View File

@@ -12,6 +12,7 @@ my_string=foo
my_string.to_string()="foo" my_string.to_string()="foo"
my_int=9 my_int=9
my_int.to_string()=9 my_int.to_string()=9
my_null.to_string()=null
my_array= my_array=
[0]=1 [0]=1
[1]=2 [1]=2
@@ -40,6 +41,19 @@ after del_idx(0,7)=0, my_array.to_string()=[]
after del_idx(0,8)=-1, my_array.to_string()=[1,2,3,4,5,null,7] after del_idx(0,8)=-1, my_array.to_string()=[1,2,3,4,5,null,7]
after del_idx(0,6)=0, my_array.to_string()=[7] after del_idx(0,6)=0, my_array.to_string()=[7]
after adding more entries, my_array.to_string()=[7,"s1","s2","s3"] after adding more entries, my_array.to_string()=[7,"s1","s2","s3"]
my_array=
[0]=1
[1]=2
[2]=3
[3]=4
[4]=5
[5]=null
[6]=7
my_array.to_string()=[1,2,3,4,5,null,7]
put_idx(5,6)=0
put_idx(63,0)=0
put_idx(129,0)=0
put_idx(SIZE_T_MAX,0)=-1
my_array= my_array=
[0]=3 [0]=3
[1]=1 [1]=1
@@ -54,10 +68,11 @@ my_array=
[3]=2 [3]=2
[4]=3 [4]=3
my_array.to_string()=[ null, 0, 1, 2, 3 ] my_array.to_string()=[ null, 0, 1, 2, 3 ]
find json_object(1) in my_array successfully: 1
baz_obj.to_string()="fark" baz_obj.to_string()="fark"
my_object= my_object=
abc: 12 abc: 12
foo: "bar" foo: "bar"
bool0: false bool0: false
bool1: true bool1: true
my_object.to_string()={ "abc": 12, "foo": "bar", "bool0": false, "bool1": true } my_object.to_string()={ "abc": 12, "foo": "bar", "bool0": false, "bool1": true, "empty_array": [ ], "empty_obj": { } }

Some files were not shown because too many files have changed in this diff Show More