json-c-0.19/ 0000755 0001750 0001750 00000000000 15217751732 011336 5 ustar uerh uerh json-c-0.19/cmake/ 0000755 0001750 0001750 00000000000 15217751164 012415 5 ustar uerh uerh json-c-0.19/cmake/Config.cmake.in 0000644 0001750 0001750 00000000176 15217751164 015235 0 ustar uerh uerh @PACKAGE_INIT@
include("${CMAKE_CURRENT_LIST_DIR}/@PROJECT_NAME@-targets.cmake")
check_required_components("@PROJECT_NAME@")
json-c-0.19/cmake/json_config.h.in 0000644 0001750 0001750 00000000355 15217751164 015474 0 ustar uerh uerh /* Define to 1 if you have the header file. */
#cmakedefine JSON_C_HAVE_INTTYPES_H @JSON_C_HAVE_INTTYPES_H@
/* Define to 1 if you have the header file. */
#cmakedefine JSON_C_HAVE_STDINT_H @JSON_C_HAVE_STDINT_H@
json-c-0.19/cmake/config.h.in 0000644 0001750 0001750 00000015621 15217751164 014445 0 ustar uerh uerh
/* 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 header file. */
#cmakedefine HAVE_DLFCN_H
/* Define to 1 if you have the header file. */
#cmakedefine HAVE_ENDIAN_H
/* Define to 1 if you have the header file. */
#cmakedefine HAVE_FCNTL_H
/* Define to 1 if you have the header file. */
#cmakedefine HAVE_INTTYPES_H
/* Define to 1 if you have the header file. */
#cmakedefine HAVE_LIMITS_H
/* Define to 1 if you have the header file. */
#cmakedefine HAVE_LOCALE_H
/* Define to 1 if you have the header file. */
#cmakedefine HAVE_MEMORY_H
/* Define to 1 if you have the header file. */
#cmakedefine HAVE_STDARG_H
/* Define to 1 if you have the header file. */
#cmakedefine HAVE_STDINT_H
/* Define to 1 if you have the header file. */
#cmakedefine HAVE_STDLIB_H
/* Define to 1 if you have the header file. */
#cmakedefine HAVE_STRINGS_H
/* Define to 1 if you have the header file. */
#cmakedefine HAVE_STRING_H
/* Define to 1 if you have the header file. */
#cmakedefine HAVE_SYSLOG_H @HAVE_SYSLOG_H@
/* Define to 1 if you have the header file. */
#cmakedefine HAVE_SYS_CDEFS_H
/* Define to 1 if you have the header file. */
#cmakedefine HAVE_SYS_PARAM_H @HAVE_SYS_PARAM_H@
/* Define to 1 if you have the header file. */
#cmakedefine HAVE_SYS_RANDOM_H
/* Define to 1 if you have the header file. */
#cmakedefine HAVE_SYS_RESOURCE_H
/* Define to 1 if you have the header file. */
#cmakedefine HAVE_SYS_STAT_H
/* Define to 1 if you have the header file. */
#cmakedefine HAVE_SYS_TYPES_H @HAVE_SYS_TYPES_H@
/* Define to 1 if you have the header file. */
#cmakedefine HAVE_UNISTD_H @HAVE_UNISTD_H@
/* Define to 1 if you have the header file. */
#cmakedefine HAVE_XLOCALE_H
/* Define to 1 if you have the 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 you have the `duplocale' function. */
#cmakedefine HAVE_DUPLOCALE
/* 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 does not define. */
#cmakedefine size_t
json-c-0.19/README.md 0000644 0001750 0001750 00000034200 15217751164 012613 0 ustar uerh uerh \mainpage
json-c
========
1. [Overview and Build Status](#overview)
2. [Getting Help](#gettinghelp)
3. [Building on Unix](#buildunix)
* [Prerequisites](#installprereq)
* [Build commands](#buildcmds)
4. [CMake options](#CMake)
5. [Testing](#testing)
6. [Building with `vcpkg`](#buildvcpkg)
7. [Building for Android](#android)
8. [Building for Commodore Amiga or MorphOS](#amiga)
9. [Linking to libjson-c](#linking)
10. [Using json-c](#using)
JSON-C - A JSON implementation in C
-----------------------------------
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.
It aims to conform to [RFC 8259](https://www.rfc-editor.org/rfc/rfc8259).
Skip down to [Using json-c](#using)
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
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).
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) 
* [Travis Build](https://app.travis-ci.com/github/json-c/json-c) 
Test Status
* [Coveralls](https://coveralls.io/github/json-c/json-c?branch=master) [](https://coveralls.io/github/json-c/json-c?branch=master)
### Prerequisites:
- `gcc`, `clang`, or another C compiler
- `cmake>=2.8`, `>=3.16` recommended, `cmake=>3.1` for tests
To generate docs you'll also need:
- `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
```
### Build instructions:
`json-c` GitHub repo: https://github.com/json-c/json-c
```sh
$ git clone https://github.com/json-c/json-c.git
$ mkdir json-c-build
$ cd json-c-build
$ cmake ../json-c # See CMake section below for custom arguments
```
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
$ make
$ make test
$ make USE_VALGRIND=0 test # optionally skip using valgrind
$ sudo make install # it could be necessary to execute make install
```
### Generating documentation with Doxygen:
The library documentation can be generated directly from the source code using Doxygen tool:
```sh
# in build directory
make doc
google-chrome doc/html/index.html
```
CMake Options
--------------------
The json-c library is built with [CMake](https://cmake.org/cmake-tutorial/),
which can take a few options.
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.
Pass these options as `-D` on CMake's command-line.
```sh
# build a static library only
cmake -DBUILD_SHARED_LIBS=OFF ..
```
### Building with partial threading support
Although json-c does not support fully multi-threaded access to
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
json_object_get() and json_object_put().
Since this may have a performance impact, of at least 3x slower
according to https://stackoverflow.com/a/11609063, it is disabled by
default. You may turn it on by adjusting your cmake command with:
-DENABLE_THREADING=ON
Separately, the default hash function used for object field keys,
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
is always compiled in when the compare-and-swap operation is available.
### 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 |
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.
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.
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= \
-DENABLE_THREADING=true \
..
make install
```
Building for Commodore Amiga or MorphOS
----------------------
Building for Commodore Amiga is supported for both Motorola 68k (AmigaOS 3) and PowerPC (AmigaOS 4) architectures. MorphOS on compatible PowerPC hardware is also supported. You can set up a cross compiler locally, however it is much easier to use the already preconfigured Amiga development environment wtthin a Docker container.
Install Docker on your machine if you don't already have it. You can download Docker Desktop for Windows/macOS/Linux [here](https://www.docker.com/products/docker-desktop/).
### To build for Motorola 68k Amiga:
```
mkdir build
docker run --rm \
-v ${PWD}:/work \
-e USER=$( id -u ) -e GROUP=$( id -g ) \
-it sacredbanana/amiga-compiler:m68k-amigaos bash
cd build
cmake -DM68K_CRT=newlib ..
make
```
libjson-c.a will get created in the build directory.
You can change newlib to nix20, nix13, ixemul or clib2 if you would like to build the library suited for libnix or clib2 instead. Newlib is default.
### To build for PowerPC Amiga:
```
mkdir build
docker run --rm \
-v ${PWD}:/work \
-e USER=$( id -u ) -e GROUP=$( id -g ) \
-it sacredbanana/amiga-compiler:ppc-amigaos bash
cd build
cmake ..
make
```
libjson-c.a will get created in the build directory.
### To build for PowerPC MorphOS:
```
mkdir build
docker run --rm \
-v ${PWD}:/work \
-e USER=$( id -u ) -e GROUP=$( id -g ) \
-it sacredbanana/amiga-compiler:ppc-morphos bash
cd build
cmake -DNOIXEMUL=1 ..
make
```
If you are making an application that absolutely requires ixemul, then remove the `-DNOIXEMUL=1`.
libjson-c.a will get created in the build directory.
Linking to `libjson-c`
----------------------
If your system has `pkgconfig`,
then you can just add this to your `makefile`:
```make
CFLAGS += $(shell pkg-config --cflags json-c)
LDFLAGS += $(shell pkg-config --libs json-c)
```
Without `pkgconfig`, you might do something like this:
```make
JSON_C_DIR=/path/to/json_c/install
CFLAGS += -I$(JSON_C_DIR)/include/json-c
# Or to use lines like: #include
#CFLAGS += -I$(JSON_C_DIR)/include
LDFLAGS+= -L$(JSON_C_DIR)/lib -ljson-c
```
If your project uses cmake:
* 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 ..
```
Using json-c
------------
To use json-c you can either include json.h, or preferably, one of the
following more specific header files:
* json_object.h - Core types and methods.
* json_tokener.h - Methods for parsing and serializing json-c object trees.
* json_pointer.h - JSON Pointer (RFC 6901) implementation for retrieving
objects from a json-c object tree.
* 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_util.h - Miscellaneous utility functions.
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.
json-c-0.19/json_patch.h 0000644 0001750 0001750 00000004627 15217751164 013647 0 ustar uerh uerh /*
* 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
json-c-0.19/appveyor.yml 0000644 0001750 0001750 00000004477 15217751164 013741 0 ustar uerh uerh version: '{branch}.{build}'
image:
# b_toolset: v143
- Visual Studio 2022
# VS2015 also used for earlier VS builds
# aka os: Windows Server 2012 R2
- Visual Studio 2015
# aka os: Windows Server 2016
# b_toolset: v141
- Visual Studio 2017
# aka os: Windows Server 2019
# b_toolset: v142
- Visual Studio 2019
platform: x64
environment:
matrix:
- b_toolset: Windows7.1SDK
- b_toolset: v120
- b_toolset: v140
- b_toolset: v141
- b_toolset: v142
- b_toolset: v143
configuration:
- Debug
- Release
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
json-c-0.19/linkhash.h 0000644 0001750 0001750 00000031036 15217751164 013312 0 ustar uerh uerh /*
* $Id: linkhash.h,v 1.6 2006/01/30 23:07:57 mclark Exp $
*
* Copyright (c) 2004, 2005 Metaparadigm Pte. Ltd.
* Michael Clark
* Copyright (c) 2009 Hewlett-Packard Development Company, L.P.
*
* 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 Internal methods for working with json_type_object objects. Although
* this is exposed by the json_object_get_object() function and within the
* json_object_iter type, it is not recommended for direct use.
*/
#ifndef _json_c_linkhash_h_
#define _json_c_linkhash_h_
#include "json_object.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* golden prime used in hash functions
*/
#define LH_PRIME 0x9e370001UL
/**
* The fraction of filled hash buckets until an insert will cause the table
* to be resized.
* This can range from just above 0 up to 1.0.
*/
#define LH_LOAD_FACTOR 0.66
/**
* sentinel pointer value for empty slots
*/
#define LH_EMPTY (void *)-1
/**
* sentinel pointer value for freed slots
*/
#define LH_FREED (void *)-2
/**
* default string hash function
*/
#define JSON_C_STR_HASH_DFLT 0
/**
* perl-like string hash function
*/
#define JSON_C_STR_HASH_PERLLIKE 1
/**
* This function sets the hash function to be used for strings.
* Must be one of the JSON_C_STR_HASH_* values.
* @returns 0 - ok, -1 if parameter was invalid
*/
int json_global_set_string_hash(const int h);
struct lh_entry;
/**
* callback function prototypes
*/
typedef void(lh_entry_free_fn)(struct lh_entry *e);
/**
* callback function prototypes
*/
typedef unsigned long(lh_hash_fn)(const void *k);
/**
* callback function prototypes
*/
typedef int(lh_equal_fn)(const void *k1, const void *k2);
/**
* An entry in the hash table. Outside of linkhash.c, treat this as opaque.
*/
struct lh_entry
{
/**
* The key.
* @deprecated Use lh_entry_k() instead of accessing this directly.
*/
const void *k;
/**
* A flag for users of linkhash to know whether or not they
* need to free k.
* @deprecated use lh_entry_k_is_constant() instead.
*/
int k_is_constant;
/**
* The value.
* @deprecated Use lh_entry_v() instead of accessing this directly.
*/
const void *v;
/**
* The next entry.
* @deprecated Use lh_entry_next() instead of accessing this directly.
*/
struct lh_entry *next;
/**
* The previous entry.
* @deprecated Use lh_entry_prev() instead of accessing this directly.
*/
struct lh_entry *prev;
};
/**
* The hash table structure. Outside of linkhash.c, treat this as opaque.
*/
struct lh_table
{
/**
* Size of our hash.
* @deprecated do not use outside of linkhash.c
*/
int size;
/**
* Numbers of entries.
* @deprecated Use lh_table_length() instead.
*/
int count;
/**
* The first entry.
* @deprecated Use lh_table_head() instead.
*/
struct lh_entry *head;
/**
* The last entry.
* @deprecated Do not use, may be removed in a future release.
*/
struct lh_entry *tail;
/**
* Internal storage of the actual table of entries.
* @deprecated do not use outside of linkhash.c
*/
struct lh_entry *table;
/**
* A pointer to the function responsible for freeing an entry.
* @deprecated do not use outside of linkhash.c
*/
lh_entry_free_fn *free_fn;
/**
* @deprecated do not use outside of linkhash.c
*/
lh_hash_fn *hash_fn;
/**
* @deprecated do not use outside of linkhash.c
*/
lh_equal_fn *equal_fn;
};
typedef struct lh_table lh_table;
/**
* Convenience list iterator.
*/
#define lh_foreach(table, entry) for (entry = lh_table_head(table); entry; entry = lh_entry_next(entry))
/**
* lh_foreach_safe allows calling of deletion routine while iterating.
*
* @param table a struct lh_table * to iterate over
* @param entry a struct lh_entry * variable to hold each element
* @param tmp a struct lh_entry * variable to hold a temporary pointer to the next element
*/
#define lh_foreach_safe(table, entry, tmp) \
for (entry = lh_table_head(table); entry && ((tmp = lh_entry_next(entry)) || 1); entry = tmp)
/**
* Create a new linkhash table.
*
* @param size initial table size. The table is automatically resized
* although this incurs a performance penalty.
* @param free_fn callback function used to free memory for entries
* when lh_table_free or lh_table_delete is called.
* If NULL is provided, then memory for keys and values
* must be freed by the caller.
* @param hash_fn function used to hash keys. 2 standard ones are defined:
* lh_ptr_hash and lh_char_hash for hashing pointer values
* and C strings respectively.
* @param equal_fn comparison function to compare keys. 2 standard ones defined:
* lh_ptr_hash and lh_char_hash for comparing pointer values
* and C strings respectively.
* @return On success, a pointer to the new linkhash table is returned.
* On error, a null pointer is returned.
*/
extern struct lh_table *lh_table_new(int size, lh_entry_free_fn *free_fn, lh_hash_fn *hash_fn,
lh_equal_fn *equal_fn);
/**
* Convenience function to create a new linkhash table with char keys.
*
* @param size initial table size.
* @param free_fn callback function used to free memory for entries.
* @return On success, a pointer to the new linkhash table is returned.
* On error, a null pointer is returned.
*/
extern struct lh_table *lh_kchar_table_new(int size, lh_entry_free_fn *free_fn);
/**
* Convenience function to create a new linkhash table with ptr keys.
*
* @param size initial table size.
* @param free_fn callback function used to free memory for entries.
* @return On success, a pointer to the new linkhash table is returned.
* On error, a null pointer is returned.
*/
extern struct lh_table *lh_kptr_table_new(int size, lh_entry_free_fn *free_fn);
/**
* Free a linkhash table.
*
* If a lh_entry_free_fn callback free function was provided then it is
* called for all entries in the table.
*
* @param t table to free.
*/
extern void lh_table_free(struct lh_table *t);
/**
* Insert a record into the table.
*
* @param t the table to insert into.
* @param k a pointer to the key to insert.
* @param v a pointer to the value to insert.
*
* @return On success, 0 is returned.
* On error, a negative value is returned.
*/
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.
*
* The hash h, which should be calculated with lh_get_hash() on k, is provided by
* the caller, to allow for optimization when multiple operations with the same
* key are known to be needed.
*
* @param t the table to insert into.
* @param k a pointer to the key to insert.
* @param v a pointer to the value to insert.
* @param h hash value of the key to insert
* @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.
*/
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.
*
* @param t the table 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.
*/
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.
*
* The hash h, which should be calculated with lh_get_hash() on k, is provided by
* the caller, to allow for optimization when multiple operations with the same
* key are known to be needed.
*
* @param t the table to lookup
* @param k a pointer to 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.
*/
extern struct lh_entry *lh_table_lookup_entry_w_hash(struct lh_table *t, const void *k,
const unsigned long h);
/**
* Lookup a record in the table.
*
* @param t the table to lookup
* @param k a pointer to the key to lookup
* @param v a pointer to a where to store the found value (set to NULL if it doesn't exist).
* @return whether or not the key was found
*/
extern json_bool lh_table_lookup_ex(struct lh_table *t, const void *k, void **v);
/**
* Delete a record from the table.
*
* If a callback free function is provided then it is called for the
* for the item being deleted.
* @param t the table to delete from.
* @param e a pointer to the entry to delete.
* @return 0 if the item was deleted.
* @return -1 if it was not found.
*/
extern int lh_table_delete_entry(struct lh_table *t, struct lh_entry *e);
/**
* Delete all entries from the specified one to the tail of the list.
* Same as calling lh_table_delete_entry() on each of them.
*
* @param t the table to delete from.
* @param e a pointer to the first entry to delete.
* @return 0 if the item was deleted.
* @return -1 if it was not found.
*/
extern int lh_table_delete_entry_to_tail(struct lh_table *t, struct lh_entry *e);
/**
* Delete a record from the table.
*
* If a callback free function is provided then it is called for the
* for the item being deleted.
* @param t the table to delete from.
* @param k a pointer to the key to delete.
* @return 0 if the item was deleted.
* @return -1 if it was not found.
*/
extern int lh_table_delete(struct lh_table *t, const void *k);
/**
* Return the number of entries in the table.
*/
extern int lh_table_length(struct lh_table *t);
/**
* Resizes the specified table.
*
* @param t Pointer to table to resize.
* @param new_size New table size. Must be positive.
*
* @return On success, 0 is returned.
* On error, a negative value is returned.
*/
int lh_table_resize(struct lh_table *t, int new_size);
/**
* @deprecated Don't use this outside of linkhash.h:
*/
#if !defined (__STDC_VERSION__) || (__STDC_VERSION__ < 199901L)
/* C89 compilers like VS2010 can't handle inline funcs, so skip it there,
note: this also applies to -std=c89 in GCC! */
#define _LH_INLINE
#else
#define _LH_INLINE inline
#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.
*
* 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
* in the hash to all utility functions. Depending on use case, this can be a
* considerable performance improvement.
* @param t the table (used to obtain hash function)
* @param k a pointer to the key to lookup
* @return the key's hash
*/
static _LH_INLINE unsigned long lh_get_hash(const struct lh_table *t, const void *k)
{
return t->hash_fn(k);
}
/**
* @deprecated Don't use this outside of linkhash.h:
*/
#ifdef __UNCONST
#define _LH_UNCONST(a) __UNCONST(a)
#else
#define _LH_UNCONST(a) ((void *)(uintptr_t)(const void *)(a))
#endif
/**
* Return a non-const version of lh_entry.k.
*
* 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.
* @see lh_entry_k_is_constant()
*/
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.
*
* 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.
*/
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
}
#endif
#endif
json-c-0.19/libjson.c 0000644 0001750 0001750 00000001133 15217751164 013137 0 ustar uerh uerh
/* dummy source file for compatibility purposes */
#if defined(HAVE_CDEFS_H)
#include
#endif
#ifndef __warn_references
#if defined(__GNUC__) && defined(HAS_GNU_WARNING_LONG)
#define __warn_references(sym, msg) \
__asm__(".section .gnu" #sym ",\n\t.ascii \"" msg "\"\n\t.text");
#else
#define __warn_references(sym, msg) /* nothing */
#endif
#endif
#include "json_object.h"
__warn_references(json_object_get, "Warning: please link against libjson-c instead of libjson");
/* __asm__(".section .gnu.warning." __STRING(sym) \
" ; .ascii \"" msg "\" ; .text") */
json-c-0.19/bench/ 0000755 0001750 0001750 00000000000 15217751164 012414 5 ustar uerh uerh json-c-0.19/bench/README.bench.md 0000644 0001750 0001750 00000004476 15217751164 014764 0 ustar uerh uerh
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).
json-c-0.19/bench/jc-bench.sh 0000755 0001750 0001750 00000014647 15217751164 014440 0 ustar uerh uerh #!/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 < $_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
json-c-0.19/vasprintf_compat.h 0000644 0001750 0001750 00000002346 15217751164 015072 0 ustar uerh uerh #ifndef __vasprintf_compat_h
#define __vasprintf_compat_h
/**
* @file
* @brief Do not use, json-c internal, may be changed or removed at any time.
*/
#include "snprintf_compat.h"
#ifndef _WIN32
#include
#endif /* !defined(_WIN32) */
#include
#include
#if !defined(HAVE_VASPRINTF)
/* CAW: compliant version of vasprintf */
static int vasprintf(char **buf, const char *fmt, va_list ap)
{
#ifndef _WIN32
static char _T_emptybuffer = '\0';
va_list ap2;
#endif /* !defined(_WIN32) */
int chars;
char *b;
if (!buf)
{
return -1;
}
#ifdef _WIN32
chars = _vscprintf(fmt, ap);
#else /* !defined(_WIN32) */
/* CAW: RAWR! We have to hope to god here that vsnprintf doesn't overwrite
* our buffer like on some 64bit sun systems... but hey, it's time to move on
*/
va_copy(ap2, ap);
chars = vsnprintf(&_T_emptybuffer, 0, fmt, ap2);
va_end(ap2);
#endif /* defined(_WIN32) */
if (chars < 0 || (size_t)chars + 1 > SIZE_MAX / sizeof(char))
{
return -1;
}
b = (char *)malloc(sizeof(char) * ((size_t)chars + 1));
if (!b)
{
return -1;
}
if ((chars = vsprintf(b, fmt, ap)) < 0)
{
free(b);
}
else
{
*buf = b;
}
return chars;
}
#endif /* !HAVE_VASPRINTF */
#endif /* __vasprintf_compat_h */
json-c-0.19/CMakeLists.txt 0000644 0001750 0001750 00000057637 15217751654 014123 0 ustar uerh uerh # 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)
# JSON-C library is C only project.
# PROJECT_VERSION{,_MAJOR,_MINOR,_PATCH} set by project():
project(json-c LANGUAGES C VERSION 0.19)
# set default build type if not specified by user
if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE debug)
endif()
set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -O2")
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)
# 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 and macOS by calling freelocale" OFF)
option(BUILD_APPS "Default to building apps" ON)
# macOS (Darwin) has the same newlocale() bug as older FreeBSD versions:
# newlocale() does not free the locale object passed to it, causing memory leaks.
# See: https://github.com/json-c/json-c/issues/668
if(APPLE AND NOT NEWLOCALE_NEEDS_FREELOCALE)
message(STATUS "macOS detected: enabling NEWLOCALE_NEEDS_FREELOCALE to prevent memory leaks")
set(NEWLOCALE_NEEDS_FREELOCALE ON CACHE BOOL "macOS needs freelocale workaround" FORCE)
endif()
if (AMIGA)
set(DISABLE_THREAD_LOCAL_STORAGE ON)
set(ENABLE_THREADING OFF)
set(BUILD_SHARED_LIBS OFF)
set(BUILD_APPS OFF)
set(DISABLE_STATIC_FPIC ON)
if ($ENV{CROSS_PFX} STREQUAL "m68k-amigaos")
set(AMIGA_M68K ON)
set(BUILD_TESTING OFF)
if (${M68K_CRT} STREQUAL "newlib")
set(NEWLIB ON)
elseif(${M68K_CRT} STREQUAL "clib2")
set(CLIB2 ON)
elseif(${M68K_CRT} STREQUAL "ixemul")
set(IXEMUL ON)
elseif(${M68K_CRT} STREQUAL "nix20")
set(NIX20 ON)
elseif(${M68K_CRT} STREQUAL "nix13")
set(NIX13 ON)
else()
set(NEWLIB ON)
endif()
message(STATUS "Building for Motorola 68k AmigaOS using CRT: ${M68K_CRT}")
elseif ($ENV{CROSS_PFX} STREQUAL "ppc-amigaos")
set(AMIGA_PPC ON)
message(STATUS "Building for PowerPC AmigaOS")
elseif($ENV{CROSS_PFX} STREQUAL "ppc-morphos")
set(MORPHOS ON)
if (NOIXEMUL)
message(STATUS "Building for PowerPC MorphOS without ixemul")
set(DISABLE_WERROR ON)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -noixemul")
else()
message(STATUS "Building for PowerPC MorphOS with ixemul")
endif()
else()
message(FATAL_ERROR "Unsupported AmigaOS target")
endif()
else()
message(STATUS "Building for ${CMAKE_SYSTEM_NAME}")
endif()
if (UNIX OR MINGW OR CYGWIN OR AMIGA)
list(APPEND CMAKE_REQUIRED_DEFINITIONS -D_GNU_SOURCE)
endif()
if (BUILD_SHARED_LIBS)
add_definitions(-D JSON_C_DLL)
endif()
if (UNIX OR AMIGA)
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 ("${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(CLANG_CL TRUE)
else()
set(CLANG_CL FALSE)
endif()
endif()
if ((MSVC AND NOT (MSVC_VERSION LESS 1800)) OR MINGW OR CYGWIN OR UNIX OR AMIGA OR CLANG_CL)
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 OR AMIGA)
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)
if (NOT AMIGA_M68K)
check_symbol_exists(arc4random "stdlib.h" HAVE_ARC4RANDOM)
endif()
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)
if (NOT NIX20 AND NOT NIX13)
# libnix does not fully support this yet
check_symbol_exists(duplocale "locale.h" HAVE_DUPLOCALE)
endif()
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)
check_symbol_exists(setrlimit "sys/resource.h" HAVE_SETRLIMIT)
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")
if (CLANG_CL)
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()
if (AMIGA_M68K)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fbaserel")
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
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
# Note: config.h is _not_ included here
${PROJECT_BINARY_DIR}/json_config.h
${PROJECT_BINARY_DIR}/json.h
${PROJECT_SOURCE_DIR}/arraylist.h
${PROJECT_SOURCE_DIR}/debug.h
${PROJECT_SOURCE_DIR}/json_c_version.h
${PROJECT_SOURCE_DIR}/json_inttypes.h
${PROJECT_SOURCE_DIR}/json_object.h
${PROJECT_SOURCE_DIR}/json_object_iterator.h
${PROJECT_SOURCE_DIR}/json_tokener.h
${PROJECT_SOURCE_DIR}/json_types.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
${JSON_C_PUBLIC_HEADERS}
${PROJECT_SOURCE_DIR}/json_object_private.h
${PROJECT_SOURCE_DIR}/json_pointer_private.h
${PROJECT_SOURCE_DIR}/random_seed.h
${PROJECT_SOURCE_DIR}/strerror_override.h
${PROJECT_SOURCE_DIR}/math_compat.h
${PROJECT_SOURCE_DIR}/snprintf_compat.h
${PROJECT_SOURCE_DIR}/strdup_compat.h
${PROJECT_SOURCE_DIR}/vasprintf_compat.h
)
set(JSON_C_SOURCES
${PROJECT_SOURCE_DIR}/arraylist.c
${PROJECT_SOURCE_DIR}/debug.c
${PROJECT_SOURCE_DIR}/json_c_version.c
${PROJECT_SOURCE_DIR}/json_object.c
${PROJECT_SOURCE_DIR}/json_object_iterator.c
${PROJECT_SOURCE_DIR}/json_tokener.c
${PROJECT_SOURCE_DIR}/json_util.c
${PROJECT_SOURCE_DIR}/json_visit.c
${PROJECT_SOURCE_DIR}/linkhash.c
${PROJECT_SOURCE_DIR}/printbuf.c
${PROJECT_SOURCE_DIR}/random_seed.c
${PROJECT_SOURCE_DIR}/strerror_override.c
)
set(JSON_C_RESOURCES)
if (BUILD_SHARED_LIBS AND WIN32)
enable_language(RC)
set(JSON_C_RESOURCES ${JSON_C_RESOURCES} ${PROJECT_SOURCE_DIR}/libjson.rc)
endif()
if (NOT DISABLE_JSON_POINTER)
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_HEADERS}
${JSON_C_RESOURCES}
)
set_target_properties(${PROJECT_NAME} PROPERTIES
VERSION 5.5.0
SOVERSION 5)
list(APPEND CMAKE_TARGETS ${PROJECT_NAME})
# 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
$
$
)
target_link_libraries(${PROJECT_NAME} PUBLIC ${CMAKE_REQUIRED_LIBRARIES})
# Allow to build static and shared libraries at the same time
if (BUILD_STATIC_LIBS AND BUILD_SHARED_LIBS)
set(STATIC_LIB ${PROJECT_NAME}-static)
add_library(${STATIC_LIB} STATIC
${JSON_C_SOURCES}
${JSON_C_HEADERS}
)
target_include_directories(${PROJECT_NAME}-static
PUBLIC
$
$
)
target_link_libraries(${PROJECT_NAME}-static PUBLIC ${CMAKE_REQUIRED_LIBRARIES})
# rename the static library
if (NOT MSVC)
set_target_properties(${STATIC_LIB} PROPERTIES
OUTPUT_NAME ${PROJECT_NAME}
)
endif()
list(APPEND CMAKE_TARGETS ${STATIC_LIB})
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()
json-c-0.19/json_object_private.h 0000644 0001750 0001750 00000004400 15217751164 015535 0 ustar uerh uerh /*
* $Id: json_object_private.h,v 1.4 2006/01/26 02:16:28 mclark Exp $
*
* Copyright (c) 2004, 2005 Metaparadigm Pte. Ltd.
* Michael Clark
*
* 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_object_private_h_
#define _json_object_private_h_
#ifdef __cplusplus
extern "C" {
#endif
struct json_object;
#include "json_inttypes.h"
#include "json_types.h"
#ifdef HAVE_UNISTD_H
#include
#endif /* HAVE_UNISTD_H */
#if defined(_MSC_VER) && !defined(ssize_t)
#include
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
{
enum json_type o_type;
uint32_t _ref_count;
json_object_to_json_string_fn *_to_json_string;
struct printbuf *_pb;
json_object_delete_fn *_user_delete;
union {
void *_userdata;
void *_delete_parent; // Used during json_object_put
};
// Actually longer, always malloc'd as some more-specific type.
// The rest of a struct json_object_${o_type} follows
};
struct json_object_object
{
struct json_object base;
struct lh_table *c_object;
};
struct json_object_array
{
struct json_object base;
struct array_list *c_array;
};
struct json_object_boolean
{
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, ...);
extern const char *json_hex_chars;
#ifdef __cplusplus
}
#endif
#endif
json-c-0.19/json_pointer_private.h 0000644 0001750 0001750 00000003405 15217751164 015753 0 ustar uerh uerh /*
* 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);
// replaced by json_pointer_set_cb
// typedef int(*json_pointer_array_set_cb)(json_object *parent, size_t idx,
// json_object *value, void *priv);
typedef int(*json_pointer_set_cb)(json_object *parent, const char *key, size_t idx,
json_object *value, void *priv);
// replaced by json_pointer_set_with_cb
// 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);
int json_pointer_set_with_cb(struct json_object **obj, const char *path,
struct json_object *value,
json_pointer_set_cb set_cb, int cb_handles_obj, void *priv);
#ifdef __cplusplus
}
#endif
#endif
json-c-0.19/json_inttypes.h 0000644 0001750 0001750 00000001270 15217751164 014416 0 ustar uerh uerh
/**
* @file
* @brief Do not use, json-c internal, may be changed or removed at any time.
*/
#ifndef _json_inttypes_h_
#define _json_inttypes_h_
#include "json_config.h"
#ifdef JSON_C_HAVE_INTTYPES_H
/* inttypes.h includes stdint.h */
#include
#else
#ifdef JSON_C_HAVE_STDINT_H
#include
#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 SCNd64 "I64d"
#define PRIu64 "I64u"
#endif
#if defined(_MSC_VER) && !defined(ssize_t)
#include
typedef SSIZE_T ssize_t;
#endif
#endif
json-c-0.19/fuzz/ 0000755 0001750 0001750 00000000000 15217751164 012333 5 ustar uerh uerh json-c-0.19/fuzz/json_pointer_fuzzer.cc 0000644 0001750 0001750 00000002704 15217751164 016763 0 ustar uerh uerh #include
#include "json.h"
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
FuzzedDataProvider fdp(data, size);
struct json_tokener *tokener =
json_tokener_new_ex(fdp.ConsumeIntegralInRange(1, JSON_TOKENER_DEFAULT_DEPTH));
int flags = 0;
if (fdp.ConsumeBool()) {
flags |= JSON_TOKENER_VALIDATE_UTF8;
}
if (fdp.ConsumeBool()) {
flags |= JSON_TOKENER_ALLOW_TRAILING_CHARS;
}
if (fdp.ConsumeBool()) {
flags |= JSON_TOKENER_STRICT;
}
json_tokener_set_flags(tokener, flags);
std::string path = fdp.ConsumeRandomLengthString(5);
std::string sub_json_str = fdp.ConsumeRandomLengthString(10);
bool use_format_string = fdp.ConsumeBool();
std::string json_str = fdp.ConsumeRemainingBytesAsString();
struct json_object *jo1 = json_tokener_parse_ex(tokener, json_str.c_str(), json_str.size());
struct json_object *sub_json = json_tokener_parse(sub_json_str.c_str());
if (sub_json == NULL) {
sub_json = json_object_new_object();
}
struct json_object *jo2 = NULL;
if (use_format_string) {
json_pointer_getf(jo1, &jo2, "%s", path.c_str());
if (json_pointer_setf(&jo1, sub_json, "%s", path.c_str()))
{
json_object_put(sub_json);
}
} else {
json_pointer_get(jo1, path.c_str(), &jo2);
if (json_pointer_set(&jo1, path.c_str(), sub_json))
{
json_object_put(sub_json);
}
}
// Clean up the main JSON object
json_object_put(jo1);
json_tokener_free(tokener);
return 0;
}
json-c-0.19/fuzz/README.md 0000644 0001750 0001750 00000000342 15217751164 013611 0 ustar uerh uerh # 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.
json-c-0.19/fuzz/json_object_fuzzer.cc 0000644 0001750 0001750 00000002713 15217751164 016551 0 ustar uerh uerh #include
#include "json.h"
#include "json_visit.h"
// Function to test json_c_visit
static int emit_object(json_object *jso, int flags, json_object *parent_jso, const char *jso_key,
size_t *jso_index, void *userarg) {
return JSON_C_VISIT_RETURN_CONTINUE;
}
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
FuzzedDataProvider fdp(data, size);
json_object *jso = json_tokener_parse(fdp.ConsumeRandomLengthString(20).c_str());
json_object_get_boolean(jso);
json_object_get_double(jso);
json_object_get_int(jso);
json_object_get_int64(jso);
json_object_get_uint64(jso);
json_object_get_string(jso);
json_object_get_string_len(jso);
json_object_get_object(jso);
json_object_get_array(jso);
json_object_get_type(jso);
json_c_visit(jso, 0, emit_object, NULL);
json_object_set_int(jso, fdp.ConsumeIntegral());
json_object_set_int64(jso, fdp.ConsumeIntegral());
json_object_set_uint64(jso, fdp.ConsumeIntegral());
json_object_set_double(jso, fdp.ConsumeFloatingPoint());
json_object_set_string(jso, fdp.ConsumeRandomLengthString(10).c_str());
json_object_set_boolean(jso, fdp.ConsumeBool());
std::string str = fdp.ConsumeRandomLengthString(10);
json_object_set_string_len(jso, str.c_str(), str.size());
json_object *dst = NULL;
json_object_deep_copy(jso, &dst, json_c_shallow_copy_default);
json_object_put(dst);
json_object_put(jso);
return 0;
}
json-c-0.19/fuzz/json_array_fuzzer.dict 0000644 0001750 0001750 00000000163 15217751164 016754 0 ustar uerh uerh "{"
"}"
","
"["
"]"
","
":"
"e"
"e+"
"e-"
"E"
"E+"
"E-"
"\""
"null"
"1"
"1.234"
"3e4"
"NaN"
"Infinity"
"-Infinity"
json-c-0.19/fuzz/json_array_fuzzer.cc 0000644 0001750 0001750 00000002271 15217751164 016420 0 ustar uerh uerh #include
#include "json.h"
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
FuzzedDataProvider fdp(data, size);
json_object *my_array = json_object_new_array();
for (int i = 0; i < 3; ++i) {
json_object *jso = json_tokener_parse(fdp.ConsumeRandomLengthString(10).c_str());
if (jso == NULL) {
continue;
}
json_object_array_add(my_array, jso);
}
json_object_array_insert_idx(my_array, fdp.ConsumeIntegralInRange(0, 10),
json_object_new_int(fdp.ConsumeIntegral()));
json_object_array_get_idx(my_array, fdp.ConsumeIntegralInRange(0, 10));
json_object_array_put_idx(my_array, fdp.ConsumeIntegralInRange(0, 10),
json_object_new_int(fdp.ConsumeIntegral()));
json_object_array_del_idx(my_array, fdp.ConsumeIntegralInRange(0, 10),
fdp.ConsumeIntegralInRange(0, 10));
json_object_array_shrink(my_array, fdp.ConsumeIntegralInRange(0, 10));
json_object_array_sort(my_array, [](const void *a, const void *b) { return 0; });
json_object_array_length(my_array);
json_object_put(my_array);
return 0;
}
json-c-0.19/fuzz/tokener_parse_ex_fuzzer.cc 0000644 0001750 0001750 00000001145 15217751164 017605 0 ustar uerh uerh #include
#include
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
{
const char *data1 = reinterpret_cast(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;
}
json-c-0.19/fuzz/tokener_parse_ex_fuzzer.dict 0000644 0001750 0001750 00000000163 15217751164 020142 0 ustar uerh uerh "{"
"}"
","
"["
"]"
","
":"
"e"
"e+"
"e-"
"E"
"E+"
"E-"
"\""
"null"
"1"
"1.234"
"3e4"
"NaN"
"Infinity"
"-Infinity"
json-c-0.19/fuzz/json_pointer_fuzzer.dict 0000644 0001750 0001750 00000000163 15217751164 017316 0 ustar uerh uerh "{"
"}"
","
"["
"]"
","
":"
"e"
"e+"
"e-"
"E"
"E+"
"E-"
"\""
"null"
"1"
"1.234"
"3e4"
"NaN"
"Infinity"
"-Infinity"
json-c-0.19/fuzz/build.sh 0000755 0001750 0001750 00000003121 15217751164 013766 0 ustar uerh uerh #!/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
json-c-0.19/fuzz/json_object_fuzzer.dict 0000644 0001750 0001750 00000000163 15217751164 017104 0 ustar uerh uerh "{"
"}"
","
"["
"]"
","
":"
"e"
"e+"
"e-"
"E"
"E+"
"E-"
"\""
"null"
"1"
"1.234"
"3e4"
"NaN"
"Infinity"
"-Infinity"
json-c-0.19/json_pointer.c 0000644 0001750 0001750 00000024460 15217751164 014220 0 ustar uerh uerh /*
* Copyright (c) 2016 Alexandru Ardelean.
*
* 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 "strerror_override.h"
#include
#include
#include
#include
#include "json_object_private.h"
#include "json_pointer.h"
#include "json_pointer_private.h"
#include "strdup_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
* RFC 6901 - https://tools.ietf.org/html/rfc6901
*/
static void string_replace_all_occurrences_with_char(char *s, const char *occur, char repl_char)
{
size_t slen = strlen(s);
size_t skip = strlen(occur) - 1; /* length of the occurrence, minus the char we're replacing */
char *p = s;
while ((p = strstr(p, occur)))
{
*p = repl_char;
p++;
slen -= skip;
memmove(p, (p + skip), slen - (p - s) + 1); /* includes null char too */
}
}
static int is_valid_index(const char *path, size_t *idx)
{
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 and because leading zeros not allowed
*/
if (len == 1)
{
if (is_plain_digit(path[0]))
{
*idx = (path[0] - '0');
return 1;
}
errno = EINVAL;
return 0;
}
/* leading zeros not allowed per RFC */
if (path[0] == '0')
{
errno = EINVAL;
return 0;
}
/* RFC states base-10 decimals */
for (i = 0; i < len; i++)
{
if (!is_plain_digit(path[i]))
{
errno = EINVAL;
return 0;
}
}
// We know it's all digits, so the only error case here is overflow,
// but ULLONG_MAX will be longer than any array length so that's ok.
*idx = strtoull(path, NULL, 10);
return 1;
}
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 (!is_valid_index(path, idx))
return -1;
if (*idx >= json_object_array_length(obj))
{
errno = ENOENT;
return -1;
}
obj = json_object_array_get_idx(obj, *idx);
if (obj)
{
if (value)
*value = obj;
return 0;
}
/* Entry not found */
errno = ENOENT;
return -1;
}
/* RFC states that we first must eval all ~1 then all ~0 */
string_replace_all_occurrences_with_char(path, "~1", '/');
string_replace_all_occurrences_with_char(path, "~0", '~');
if (!json_object_object_get_ex(obj, path, value))
{
errno = ENOENT;
return -1;
}
return 0;
}
static int json_pointer_set_single_path(struct json_object *parent, const char *path,
struct json_object *value,
json_pointer_set_cb set_cb, int cb_handles_obj, 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 */
if (path[0] == '-' && path[1] == '\0')
return json_object_array_add(parent, value);
if (!is_valid_index(path, &idx))
return -1;
return set_cb(parent, NULL, idx, value, priv);
}
/* path replacements should have been done in json_pointer_get_single_path(),
* and we should still be good here
*/
if (json_object_is_type(parent, json_type_object))
{
if (cb_handles_obj)
{
return set_cb(parent, path, (size_t)-1, value, priv);
}
else
{
return json_object_object_add(parent, path, value);
}
}
/* Getting here means that we tried to "dereference" a primitive JSON type
* (like string, int, bool).i.e. add a sub-object to it
*/
errno = ENOENT;
return -1;
}
static int json_pointer_result_get_recursive(struct json_object *obj, char *path,
struct json_pointer_get_result *res)
{
struct json_object *parent_obj = obj;
size_t idx = 0;
char *endp;
int rc;
/* All paths (on each recursion level must have a leading '/' */
if (path[0] != '/')
{
errno = EINVAL;
return -1;
}
path++;
endp = strchr(path, '/');
if (endp)
*endp = '\0';
/* If we err-ed here, return here */
if ((rc = json_pointer_get_single_path(obj, path, &obj, &idx)))
return rc;
if (endp)
{
/* 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 */
if (res) {
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;
}
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;
int rc;
if (!obj || !path)
{
errno = EINVAL;
return -1;
}
if (path[0] == '\0')
{
res->parent = NULL;
res->obj = obj;
res->key_in_parent = NULL;
res->index_in_parent = UINT32_MAX;
return 0;
}
/* pass a working copy to the recursive call */
if (!(path_copy = strdup(path)))
{
errno = ENOMEM;
return -1;
}
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);
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, ...)
{
char *path_copy = NULL;
int rc = 0;
va_list args;
if (!obj || !path_fmt)
{
errno = EINVAL;
return -1;
}
va_start(args, path_fmt);
rc = vasprintf(&path_copy, path_fmt, args);
va_end(args);
if (rc < 0)
return rc;
if (path_copy[0] == '\0')
{
if (res)
*res = obj;
goto out;
}
rc = json_pointer_object_get_recursive(obj, path_copy, res);
out:
free(path_copy);
return rc;
}
int json_pointer_set_with_cb(struct json_object **obj, const char *path,
struct json_object *value,
json_pointer_set_cb set_cb, int cb_handles_obj, void *priv)
{
const char *endp;
char *path_copy = NULL;
struct json_object *set = NULL;
int rc;
if (!obj || !path)
{
errno = EINVAL;
return -1;
}
if (path[0] == '\0')
{
json_object_put(*obj);
*obj = value;
return 0;
}
if (path[0] != '/')
{
errno = EINVAL;
return -1;
}
/* If there's only 1 level to set, stop here */
if ((endp = strrchr(path, '/')) == path)
{
path++;
return json_pointer_set_single_path(*obj, path, value, set_cb, cb_handles_obj, priv);
}
/* pass a working copy to the recursive call */
if (!(path_copy = strdup(path)))
{
errno = ENOMEM;
return -1;
}
path_copy[endp - path] = '\0';
rc = json_pointer_object_get_recursive(*obj, path_copy, &set);
free(path_copy);
if (rc)
return rc;
endp++;
return json_pointer_set_single_path(set, endp, value, set_cb, cb_handles_obj, priv);
}
static int default_put_cb(struct json_object *parent, const char *key, size_t idx,
struct json_object *value, void *priv)
{
if (key == NULL)
return json_object_array_put_idx(parent, idx, value);
else
return json_object_object_add(parent, key, value);
}
int json_pointer_set(struct json_object **obj, const char *path, struct json_object *value)
{
return json_pointer_set_with_cb(obj, path, value, default_put_cb, 1, NULL);
}
int json_pointer_setf(struct json_object **obj, struct json_object *value, const char *path_fmt,
...)
{
char *endp;
char *path_copy = NULL;
struct json_object *set = NULL;
va_list args;
int rc = 0;
if (!obj || !path_fmt)
{
errno = EINVAL;
return -1;
}
/* pass a working copy to the recursive call */
va_start(args, path_fmt);
rc = vasprintf(&path_copy, path_fmt, args);
va_end(args);
if (rc < 0)
return rc;
if (path_copy[0] == '\0')
{
json_object_put(*obj);
*obj = value;
goto out;
}
if (path_copy[0] != '/')
{
errno = EINVAL;
rc = -1;
goto out;
}
/* If there's only 1 level to set, stop here */
if ((endp = strrchr(path_copy, '/')) == path_copy)
{
set = *obj;
goto set_single_path;
}
*endp = '\0';
rc = json_pointer_object_get_recursive(*obj, path_copy, &set);
if (rc)
goto out;
set_single_path:
endp++;
rc = json_pointer_set_single_path(set, endp, value, default_put_cb, 1, NULL);
out:
free(path_copy);
return rc;
}
int json_pointer_set_with_limit_index(struct json_object **obj, const char *path,
struct json_object *value, size_t limit_index)
{
// -1 means no limits
if (limit_index == (size_t)-1)
{
return json_pointer_set_with_cb(obj, path, value, default_put_cb, 1, NULL);
}
return json_pointer_set_with_cb(obj, path, value,
json_object_array_put_with_idx_limit_cb, 0, &limit_index);
}
/* safe callback for array index limit */
int json_object_array_put_with_idx_limit_cb(struct json_object *jso, const char *key, size_t idx,
struct json_object *jso_new, void *priv)
{
size_t max_idx;
if (key == NULL)
{
// array operation
// use priv as a size_t pointer to pass in the maximum allowed index.
// The priv is required context for this callback and must not be NULL.
if (!priv)
{
errno = EFAULT;
return -1;
}
max_idx = *(size_t*)priv;
// Check against a maximum to prevent excessive memory allocations.
// An extremely large index, even if it doesn't overflow size_t,
// will cause a huge memory allocation request via realloc,
// leading to an OOM.
if (idx > max_idx)
{
errno = EINVAL;
return -1;
}
return json_object_array_put_idx(jso, idx, jso_new);
}
else
{
// object operation
return json_object_object_add(jso, key, jso_new);
}
}
json-c-0.19/snprintf_compat.h 0000644 0001750 0001750 00000001715 15217751164 014720 0 ustar uerh uerh #ifndef __snprintf_compat_h
#define __snprintf_compat_h
/**
* @file
* @brief Do not use, json-c internal, may be changed or removed at any time.
*/
/*
* Microsoft's _vsnprintf and _snprint don't always terminate
* the string, so use wrappers that ensure that.
*/
#include
#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)
{
int ret;
ret = _vsnprintf(str, size, format, ap);
str[size - 1] = '\0';
return ret;
}
#define vsnprintf json_c_vsnprintf
static int json_c_snprintf(char *str, size_t size, const char *format, ...)
{
va_list ap;
int ret;
va_start(ap, format);
ret = json_c_vsnprintf(str, size, format, ap);
va_end(ap);
return ret;
}
#define snprintf json_c_snprintf
#elif !defined(HAVE_SNPRINTF) /* !HAVE_SNPRINTF */
#error snprintf is required but was not found
#endif /* !HAVE_SNPRINTF */
#endif /* __snprintf_compat_h */
json-c-0.19/Android.configure.mk 0000644 0001750 0001750 00000002715 15217751164 015233 0 ustar uerh uerh # This file is the top android makefile for all sub-modules.
#
# Suggested settings to build for Android:
#
# export PATH=$PATH:/opt/android-ndk/toolchains/arm-linux-androideabi-4.9/prebuilt/linux-x86_64/bin/
# export SYSROOT=/opt/android-ndk/platforms/android-9/arch-arm/usr/
# export LD=arm-linux-androideabi-ld
# export CC="arm-linux-androideabi-gcc --sysroot=/opt/android-ndk/platforms/android-9/arch-arm"
#
# Then run autogen.sh, configure and make.
#
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
json_c_TOP := $(LOCAL_PATH)
JSON_C_BUILT_SOURCES := Android.mk
JSON_C_BUILT_SOURCES := $(patsubst %, $(abspath $(json_c_TOP))/%, $(JSON_C_BUILT_SOURCES))
.PHONY: json-c-configure json-c-configure-real
json-c-configure-real:
echo $(JSON_C_BUILT_SOURCES)
cd $(json_c_TOP) ; \
$(abspath $(json_c_TOP))/autogen.sh && \
CC="$(CONFIGURE_CC)" \
CFLAGS="$(CONFIGURE_CFLAGS)" \
LD=$(TARGET_LD) \
LDFLAGS="$(CONFIGURE_LDFLAGS)" \
CPP=$(CONFIGURE_CPP) \
CPPFLAGS="$(CONFIGURE_CPPFLAGS)" \
PKG_CONFIG_LIBDIR=$(CONFIGURE_PKG_CONFIG_LIBDIR) \
PKG_CONFIG_TOP_BUILD_DIR=/ \
ac_cv_func_malloc_0_nonnull=yes \
ac_cv_func_realloc_0_nonnull=yes \
$(abspath $(json_c_TOP))/$(CONFIGURE) --host=$(CONFIGURE_HOST) \
--prefix=/system \
&& \
for file in $(JSON_C_BUILT_SOURCES); do \
rm -f $$file && \
make -C $$(dirname $$file) $$(basename $$file) ; \
done
json-c-configure: json-c-configure-real
PA_CONFIGURE_TARGETS += json-c-configure
-include $(json_c_TOP)/Android.mk
json-c-0.19/json_tokener.c 0000644 0001750 0001750 00000112451 15217751164 014205 0 ustar uerh uerh /*
* $Id: json_tokener.c,v 1.20 2006/07/25 03:24:50 mclark Exp $
*
* Copyright (c) 2004, 2005 Metaparadigm Pte. Ltd.
* Michael Clark
*
* This library is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See COPYING for details.
*
*
* Copyright (c) 2008-2009 Yahoo! Inc. All rights reserved.
* The copyrights to the contents of this file are licensed under the MIT License
* (https://www.opensource.org/licenses/mit-license.php)
*/
#include "config.h"
#include "math_compat.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include "debug.h"
#include "json_inttypes.h"
#include "json_object.h"
#include "json_object_private.h"
#include "json_tokener.h"
#include "json_util.h"
#include "printbuf.h"
#include "strdup_compat.h"
#ifdef HAVE_LOCALE_H
#include
#endif /* HAVE_LOCALE_H */
#ifdef HAVE_XLOCALE_H
#include
#endif
#ifdef HAVE_STRINGS_H
#include
#endif /* HAVE_STRINGS_H */
#define jt_hexdigit(x) (((x) <= '9') ? (x) - '0' : ((x)&7) + 9)
#if !HAVE_STRNCASECMP && defined(_WIN32)
/* MSC has the version as _strnicmp */
#define strncasecmp _strnicmp
#elif !HAVE_STRNCASECMP
#error You do not have strncasecmp on your system.
#endif /* HAVE_STRNCASECMP */
#if defined(_MSC_VER) && (_MSC_VER <= 1800)
/* VS2013 doesn't know about "inline" */
#define inline __inline
#elif defined(AIX_CC)
#define inline
#endif
/* The following helper functions are used to speed up parsing. They
* are faster than their ctype counterparts because they assume that
* the input is in ASCII and that the locale is set to "C". The
* compiler will also inline these functions, providing an additional
* speedup by saving on function calls.
*/
static inline int is_ws_char(char c)
{
return c == ' '
|| c == '\t'
|| c == '\n'
|| c == '\r';
}
static inline int is_hex_char(char c)
{
return (c >= '0' && c <= '9')
|| (c >= 'A' && c <= 'F')
|| (c >= 'a' && c <= 'f');
}
/* Use C99 NAN by default; if not available, nan("") should work too. */
#ifndef NAN
#define NAN nan("")
#endif /* !NAN */
static const char json_null_str[] = "null";
static const int json_null_str_len = sizeof(json_null_str) - 1;
static const char json_inf_str[] = "Infinity";
/* Swapped case "Infinity" to avoid need to call tolower() on input chars: */
static const char json_inf_str_invert[] = "iNFINITY";
static const unsigned int json_inf_str_len = sizeof(json_inf_str) - 1;
static const char json_nan_str[] = "NaN";
static const int json_nan_str_len = sizeof(json_nan_str) - 1;
static const char json_true_str[] = "true";
static const int json_true_str_len = sizeof(json_true_str) - 1;
static const char json_false_str[] = "false";
static const int json_false_str_len = sizeof(json_false_str) - 1;
/* clang-format off */
static const char *json_tokener_errors[] = {
"success",
"continue",
"nesting too deep",
"unexpected end of data",
"unexpected character",
"null expected",
"boolean expected",
"number expected",
"array value separator ',' expected",
"quoted object property name expected",
"object property name separator ':' expected",
"object value separator ',' expected",
"invalid string sequence",
"expected comment",
"invalid utf-8 string",
"buffer size overflow",
"out of memory"
};
/* clang-format on */
/**
* validete the utf-8 string in strict model.
* if not utf-8 format, return err.
*/
static json_bool json_tokener_validate_utf8(const char c, unsigned int *nBytes);
static int json_tokener_parse_double(const char *buf, int len, double *retval);
const char *json_tokener_error_desc(enum json_tokener_error jerr)
{
int jerr_int = (int)jerr;
if (jerr_int < 0 ||
jerr_int >= (int)(sizeof(json_tokener_errors) / sizeof(json_tokener_errors[0])))
return "Unknown error, "
"invalid json_tokener_error value passed to json_tokener_error_desc()";
return json_tokener_errors[jerr];
}
enum json_tokener_error json_tokener_get_error(struct json_tokener *tok)
{
return tok->err;
}
/* Stuff for decoding unicode sequences */
#define IS_HIGH_SURROGATE(uc) (((uc)&0xFFFFFC00) == 0xD800)
#define IS_LOW_SURROGATE(uc) (((uc)&0xFFFFFC00) == 0xDC00)
#define DECODE_SURROGATE_PAIR(hi, lo) ((((hi)&0x3FF) << 10) + ((lo)&0x3FF) + 0x10000)
static unsigned char utf8_replacement_char[3] = {0xEF, 0xBF, 0xBD};
struct json_tokener *json_tokener_new_ex(int depth)
{
struct json_tokener *tok;
if (depth < 1)
return NULL;
tok = (struct json_tokener *)calloc(1, sizeof(struct json_tokener));
if (!tok)
return NULL;
tok->stack = (struct json_tokener_srec *)calloc(depth, sizeof(struct json_tokener_srec));
if (!tok->stack)
{
free(tok);
return NULL;
}
tok->pb = printbuf_new();
if (!tok->pb)
{
free(tok->stack);
free(tok);
return NULL;
}
tok->max_depth = depth;
json_tokener_reset(tok);
return tok;
}
struct json_tokener *json_tokener_new(void)
{
return json_tokener_new_ex(JSON_TOKENER_DEFAULT_DEPTH);
}
void json_tokener_free(struct json_tokener *tok)
{
if (!tok)
return;
json_tokener_reset(tok);
if (tok->pb)
printbuf_free(tok->pb);
free(tok->stack);
free(tok);
}
static void json_tokener_reset_level(struct json_tokener *tok, int depth)
{
tok->stack[depth].state = json_tokener_state_eatws;
tok->stack[depth].saved_state = json_tokener_state_start;
json_object_put(tok->stack[depth].current);
tok->stack[depth].current = NULL;
free(tok->stack[depth].obj_field_name);
tok->stack[depth].obj_field_name = NULL;
}
void json_tokener_reset(struct json_tokener *tok)
{
int i;
if (!tok)
return;
for (i = tok->depth; i >= 0; i--)
json_tokener_reset_level(tok, i);
tok->depth = 0;
tok->err = json_tokener_success;
}
struct json_object *json_tokener_parse(const char *str)
{
enum json_tokener_error jerr_ignored;
struct json_object *obj;
obj = json_tokener_parse_verbose(str, &jerr_ignored);
return obj;
}
struct json_object *json_tokener_parse_verbose(const char *str, enum json_tokener_error *error)
{
struct json_tokener *tok;
struct json_object *obj;
tok = json_tokener_new();
if (!tok)
{
*error = json_tokener_error_memory;
return NULL;
}
obj = json_tokener_parse_ex(tok, str, -1);
*error = tok->err;
if (tok->err != json_tokener_success
#if 0
/* This would be a more sensible default, and cause parsing
* things like "null123" to fail when the caller can't know
* where the parsing left off, but starting to fail would
* be a notable behaviour change. Save for a 1.0 release.
*/
|| json_tokener_get_parse_end(tok) != strlen(str)
#endif
)
{
if (obj != NULL)
json_object_put(obj);
obj = NULL;
}
json_tokener_free(tok);
return obj;
}
#define state tok->stack[tok->depth].state
#define saved_state tok->stack[tok->depth].saved_state
#define current tok->stack[tok->depth].current
#define obj_field_name tok->stack[tok->depth].obj_field_name
/* Optimization:
* json_tokener_parse_ex() consumed a lot of CPU in its main loop,
* iterating character-by character. A large performance boost is
* achieved by using tighter loops to locally handle units such as
* comments and strings. Loops that handle an entire token within
* their scope also gather entire strings and pass them to
* printbuf_memappend() in a single call, rather than calling
* printbuf_memappend() one char at a time.
*
* PEEK_CHAR() and ADVANCE_CHAR() macros are used for code that is
* common to both the main loop and the tighter loops.
*/
/* PEEK_CHAR(dest, tok) macro:
* Peeks at the current char and stores it in dest.
* Returns 1 on success, sets tok->err and returns 0 if no more chars.
* Implicit inputs: str, len, nBytesp vars
*/
#define PEEK_CHAR(dest, tok) \
(((tok)->char_offset == len) \
? (((tok)->depth == 0 && state == json_tokener_state_eatws && \
saved_state == json_tokener_state_finish) \
? (((tok)->err = json_tokener_success), 0) \
: (((tok)->err = json_tokener_continue), 0)) \
: (((tok->flags & JSON_TOKENER_VALIDATE_UTF8) && \
(!json_tokener_validate_utf8(*str, nBytesp))) \
? ((tok->err = json_tokener_error_parse_utf8_string), 0) \
: (((dest) = *str), 1)))
/* ADVANCE_CHAR() macro:
* Increments str & tok->char_offset.
* For convenience of existing conditionals, returns the old value of c (0 on eof).
* Implicit inputs: c var
*/
#define ADVANCE_CHAR(str, tok) (++(str), ((tok)->char_offset)++, c)
/* printbuf_memappend_checked(p, s, l) macro:
* Add string s of length l to printbuffer p.
* If operation fails abort parse operation with memory error.
*/
#define printbuf_memappend_checked(p, s, l) \
do { \
if (printbuf_memappend((p), (s), (l)) < 0) \
{ \
tok->err = json_tokener_error_memory; \
goto out; \
} \
} while (0)
/* End optimization macro defs */
struct json_object *json_tokener_parse_ex(struct json_tokener *tok, const char *str, int len)
{
struct json_object *obj = NULL;
char c = '\1';
unsigned int nBytes = 0;
unsigned int *nBytesp = &nBytes;
#ifdef HAVE_USELOCALE
locale_t oldlocale = uselocale(NULL);
locale_t newloc;
#elif defined(HAVE_SETLOCALE)
char *oldlocale = NULL;
#endif
tok->char_offset = 0;
tok->err = json_tokener_success;
/* this interface is presently not 64-bit clean due to the int len argument
* and the internal printbuf interface that takes 32-bit int len arguments
* so the function limits the maximum string size to INT32_MAX (2GB).
* If the function is called with len == -1 then strlen is called to check
* the string length is less than INT32_MAX (2GB)
*/
if ((len < -1) || (len == -1 && strlen(str) > INT32_MAX))
{
tok->err = json_tokener_error_size;
return NULL;
}
#ifdef HAVE_USELOCALE
{
#ifdef HAVE_DUPLOCALE
locale_t duploc = duplocale(oldlocale);
if (duploc == NULL && errno == ENOMEM)
{
tok->err = json_tokener_error_memory;
return NULL;
}
newloc = newlocale(LC_NUMERIC_MASK, "C", duploc);
#else
newloc = newlocale(LC_NUMERIC_MASK, "C", oldlocale);
#endif
if (newloc == NULL)
{
tok->err = json_tokener_error_memory;
#ifdef HAVE_DUPLOCALE
freelocale(duploc);
#endif
return NULL;
}
#ifdef NEWLOCALE_NEEDS_FREELOCALE
#ifdef HAVE_DUPLOCALE
// Older versions of FreeBSD (<12.4) don't free the locale
// passed to newlocale(), so do it here
freelocale(duploc);
#endif
#endif
uselocale(newloc);
}
#elif defined(HAVE_SETLOCALE)
{
char *tmplocale;
tmplocale = setlocale(LC_NUMERIC, NULL);
if (tmplocale)
{
oldlocale = strdup(tmplocale);
if (oldlocale == NULL)
{
tok->err = json_tokener_error_memory;
return NULL;
}
}
setlocale(LC_NUMERIC, "C");
}
#endif
while (PEEK_CHAR(c, tok)) // Note: c might be '\0' !
{
redo_char:
switch (state)
{
case json_tokener_state_eatws:
/* Advance until we change state */
while (is_ws_char(c))
{
if ((!ADVANCE_CHAR(str, tok)) || (!PEEK_CHAR(c, tok)))
goto out;
}
if (c == '/' && !(tok->flags & JSON_TOKENER_STRICT))
{
printbuf_reset(tok->pb);
printbuf_memappend_checked(tok->pb, &c, 1);
state = json_tokener_state_comment_start;
}
else
{
state = saved_state;
goto redo_char;
}
break;
case json_tokener_state_start:
switch (c)
{
case '{':
state = json_tokener_state_eatws;
saved_state = json_tokener_state_object_field_start;
current = json_object_new_object();
if (current == NULL)
{
tok->err = json_tokener_error_memory;
goto out;
}
break;
case '[':
state = json_tokener_state_eatws;
saved_state = json_tokener_state_array;
current = json_object_new_array();
if (current == NULL)
{
tok->err = json_tokener_error_memory;
goto out;
}
break;
case 'I':
case 'i':
state = json_tokener_state_inf;
printbuf_reset(tok->pb);
tok->st_pos = 0;
goto redo_char;
case 'N':
case 'n':
state = json_tokener_state_null; // or NaN
printbuf_reset(tok->pb);
tok->st_pos = 0;
goto redo_char;
case '\'':
if (tok->flags & JSON_TOKENER_STRICT)
{
/* in STRICT mode only double-quote are allowed */
tok->err = json_tokener_error_parse_unexpected;
goto out;
}
/* FALLTHRU */
case '"':
state = json_tokener_state_string;
printbuf_reset(tok->pb);
tok->quote_char = c;
break;
case 'T':
case 't':
case 'F':
case 'f':
state = json_tokener_state_boolean;
printbuf_reset(tok->pb);
tok->st_pos = 0;
goto redo_char;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
state = json_tokener_state_number;
printbuf_reset(tok->pb);
tok->is_double = 0;
goto redo_char;
default: tok->err = json_tokener_error_parse_unexpected; goto out;
}
break;
case json_tokener_state_finish:
if (tok->depth == 0)
goto out;
obj = json_object_get(current);
json_tokener_reset_level(tok, tok->depth);
tok->depth--;
goto redo_char;
case json_tokener_state_inf: /* aka starts with 'i' (or 'I', or "-i", or "-I") */
{
/* If we were guaranteed to have len set, then we could (usually) handle
* the entire "Infinity" check in a single strncmp (strncasecmp), but
* since len might be -1 (i.e. "read until \0"), we need to check it
* a character at a time.
* Trying to handle it both ways would make this code considerably more
* complicated with likely little performance benefit.
*/
int is_negative = 0;
/* Note: tok->st_pos must be 0 when state is set to json_tokener_state_inf */
while (tok->st_pos < (int)json_inf_str_len)
{
char inf_char = *str;
if (inf_char != json_inf_str[tok->st_pos] &&
((tok->flags & JSON_TOKENER_STRICT) ||
inf_char != json_inf_str_invert[tok->st_pos])
)
{
tok->err = json_tokener_error_parse_unexpected;
goto out;
}
tok->st_pos++;
(void)ADVANCE_CHAR(str, tok);
if (!PEEK_CHAR(c, tok))
{
/* out of input chars, for now at least */
goto out;
}
}
/* We checked the full length of "Infinity", so create the object.
* When handling -Infinity, the number parsing code will have dropped
* the "-" into tok->pb for us, so check it now.
*/
if (printbuf_length(tok->pb) > 0 && *(tok->pb->buf) == '-')
{
is_negative = 1;
}
current = json_object_new_double(is_negative ? -INFINITY : INFINITY);
if (current == NULL)
{
tok->err = json_tokener_error_memory;
goto out;
}
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
goto redo_char;
}
break;
case json_tokener_state_null: /* aka starts with 'n' */
{
int size;
int size_nan;
printbuf_memappend_checked(tok->pb, &c, 1);
size = json_min(tok->st_pos + 1, json_null_str_len);
size_nan = json_min(tok->st_pos + 1, json_nan_str_len);
if ((!(tok->flags & JSON_TOKENER_STRICT) &&
strncasecmp(json_null_str, tok->pb->buf, size) == 0) ||
(strncmp(json_null_str, tok->pb->buf, size) == 0))
{
if (tok->st_pos == json_null_str_len)
{
current = NULL;
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
goto redo_char;
}
}
else if ((!(tok->flags & JSON_TOKENER_STRICT) &&
strncasecmp(json_nan_str, tok->pb->buf, size_nan) == 0) ||
(strncmp(json_nan_str, tok->pb->buf, size_nan) == 0))
{
if (tok->st_pos == json_nan_str_len)
{
current = json_object_new_double(NAN);
if (current == NULL)
{
tok->err = json_tokener_error_memory;
goto out;
}
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
goto redo_char;
}
}
else
{
tok->err = json_tokener_error_parse_null;
goto out;
}
tok->st_pos++;
}
break;
case json_tokener_state_comment_start:
if (c == '*')
{
state = json_tokener_state_comment;
}
else if (c == '/')
{
state = json_tokener_state_comment_eol;
}
else
{
tok->err = json_tokener_error_parse_comment;
goto out;
}
printbuf_memappend_checked(tok->pb, &c, 1);
break;
case json_tokener_state_comment:
{
/* Advance until we change state */
const char *case_start = str;
while (c != '*')
{
if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok))
{
printbuf_memappend_checked(tok->pb, case_start,
str - case_start);
goto out;
}
}
printbuf_memappend_checked(tok->pb, case_start, 1 + str - case_start);
state = json_tokener_state_comment_end;
}
break;
case json_tokener_state_comment_eol:
{
/* Advance until we change state */
const char *case_start = str;
while (c != '\n')
{
if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok))
{
printbuf_memappend_checked(tok->pb, case_start,
str - case_start);
goto out;
}
}
printbuf_memappend_checked(tok->pb, case_start, str - case_start);
MC_DEBUG("json_tokener_comment: %s\n", tok->pb->buf);
state = json_tokener_state_eatws;
}
break;
case json_tokener_state_comment_end:
printbuf_memappend_checked(tok->pb, &c, 1);
if (c == '/')
{
MC_DEBUG("json_tokener_comment: %s\n", tok->pb->buf);
state = json_tokener_state_eatws;
}
else
{
state = json_tokener_state_comment;
}
break;
case json_tokener_state_string:
{
/* Advance until we change state */
const char *case_start = str;
while (1)
{
if (c == tok->quote_char)
{
printbuf_memappend_checked(tok->pb, case_start,
str - case_start);
current =
json_object_new_string_len(tok->pb->buf, tok->pb->bpos);
if (current == NULL)
{
tok->err = json_tokener_error_memory;
goto out;
}
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
break;
}
else if (c == '\\')
{
printbuf_memappend_checked(tok->pb, case_start,
str - case_start);
saved_state = json_tokener_state_string;
state = json_tokener_state_string_escape;
break;
}
else if ((tok->flags & JSON_TOKENER_STRICT) && (unsigned char)c <= 0x1f)
{
// Disallow control characters in strict mode
tok->err = json_tokener_error_parse_string;
goto out;
}
if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok))
{
printbuf_memappend_checked(tok->pb, case_start,
str - case_start);
goto out;
}
}
}
break;
case json_tokener_state_string_escape:
switch (c)
{
case '"':
case '\\':
case '/':
printbuf_memappend_checked(tok->pb, &c, 1);
state = saved_state;
break;
case 'b':
case 'n':
case 'r':
case 't':
case 'f':
if (c == 'b')
printbuf_memappend_checked(tok->pb, "\b", 1);
else if (c == 'n')
printbuf_memappend_checked(tok->pb, "\n", 1);
else if (c == 'r')
printbuf_memappend_checked(tok->pb, "\r", 1);
else if (c == 't')
printbuf_memappend_checked(tok->pb, "\t", 1);
else if (c == 'f')
printbuf_memappend_checked(tok->pb, "\f", 1);
state = saved_state;
break;
case 'u':
tok->ucs_char = 0;
tok->st_pos = 0;
state = json_tokener_state_escape_unicode;
break;
default: tok->err = json_tokener_error_parse_string; goto out;
}
break;
// ===================================================
case json_tokener_state_escape_unicode:
{
/* Handle a 4-byte \uNNNN sequence, or two sequences if a surrogate pair */
while (1)
{
if (!c || !is_hex_char(c))
{
tok->err = json_tokener_error_parse_string;
goto out;
}
tok->ucs_char |=
((unsigned int)jt_hexdigit(c) << ((3 - tok->st_pos) * 4));
tok->st_pos++;
if (tok->st_pos >= 4)
break;
(void)ADVANCE_CHAR(str, tok);
if (!PEEK_CHAR(c, tok))
{
/*
* We're out of characters in the current call to
* json_tokener_parse(), but a subsequent call might
* provide us with more, so leave our current state
* as-is (including tok->high_surrogate) and return.
*/
goto out;
}
}
tok->st_pos = 0;
/* Now, we have a full \uNNNN sequence in tok->ucs_char */
/* If the *previous* sequence was a high surrogate ... */
if (tok->high_surrogate)
{
if (IS_LOW_SURROGATE(tok->ucs_char))
{
/* Recalculate the ucs_char, then fall thru to process normally */
tok->ucs_char = DECODE_SURROGATE_PAIR(tok->high_surrogate,
tok->ucs_char);
}
else
{
/* High surrogate was not followed by a low surrogate
* Replace the high and process the rest normally
*/
printbuf_memappend_checked(tok->pb,
(char *)utf8_replacement_char, 3);
}
tok->high_surrogate = 0;
}
if (tok->ucs_char < 0x80)
{
unsigned char unescaped_utf[1];
unescaped_utf[0] = tok->ucs_char;
printbuf_memappend_checked(tok->pb, (char *)unescaped_utf, 1);
}
else if (tok->ucs_char < 0x800)
{
unsigned char unescaped_utf[2];
unescaped_utf[0] = 0xc0 | (tok->ucs_char >> 6);
unescaped_utf[1] = 0x80 | (tok->ucs_char & 0x3f);
printbuf_memappend_checked(tok->pb, (char *)unescaped_utf, 2);
}
else if (IS_HIGH_SURROGATE(tok->ucs_char))
{
/*
* The next two characters should be \u, HOWEVER,
* we can't simply peek ahead here, because the
* characters we need might not be passed to us
* until a subsequent call to json_tokener_parse.
* Instead, transition through a couple of states.
* (now):
* _escape_unicode => _unicode_need_escape
* (see a '\\' char):
* _unicode_need_escape => _unicode_need_u
* (see a 'u' char):
* _unicode_need_u => _escape_unicode
* ...and we'll end up back around here.
*/
tok->high_surrogate = tok->ucs_char;
tok->ucs_char = 0;
state = json_tokener_state_escape_unicode_need_escape;
break;
}
else if (IS_LOW_SURROGATE(tok->ucs_char))
{
/* Got a low surrogate not preceded by a high */
printbuf_memappend_checked(tok->pb, (char *)utf8_replacement_char, 3);
}
else if (tok->ucs_char < 0x10000)
{
unsigned char unescaped_utf[3];
unescaped_utf[0] = 0xe0 | (tok->ucs_char >> 12);
unescaped_utf[1] = 0x80 | ((tok->ucs_char >> 6) & 0x3f);
unescaped_utf[2] = 0x80 | (tok->ucs_char & 0x3f);
printbuf_memappend_checked(tok->pb, (char *)unescaped_utf, 3);
}
else if (tok->ucs_char < 0x110000)
{
unsigned char unescaped_utf[4];
unescaped_utf[0] = 0xf0 | ((tok->ucs_char >> 18) & 0x07);
unescaped_utf[1] = 0x80 | ((tok->ucs_char >> 12) & 0x3f);
unescaped_utf[2] = 0x80 | ((tok->ucs_char >> 6) & 0x3f);
unescaped_utf[3] = 0x80 | (tok->ucs_char & 0x3f);
printbuf_memappend_checked(tok->pb, (char *)unescaped_utf, 4);
}
else
{
/* Don't know what we got--insert the replacement char */
printbuf_memappend_checked(tok->pb, (char *)utf8_replacement_char, 3);
}
state = saved_state; // i.e. _state_string or _state_object_field
}
break;
case json_tokener_state_escape_unicode_need_escape:
// We get here after processing a high_surrogate
// require a '\\' char
if (!c || c != '\\')
{
/* Got a high surrogate without another sequence following
* it. Put a replacement char in for the high surrogate
* and pop back up to _state_string or _state_object_field.
*/
printbuf_memappend_checked(tok->pb, (char *)utf8_replacement_char, 3);
tok->high_surrogate = 0;
tok->ucs_char = 0;
tok->st_pos = 0;
state = saved_state;
goto redo_char;
}
state = json_tokener_state_escape_unicode_need_u;
break;
case json_tokener_state_escape_unicode_need_u:
/* We already had a \ char, check that it's \u */
if (!c || c != 'u')
{
/* Got a high surrogate with some non-unicode escape
* sequence following it.
* Put a replacement char in for the high surrogate
* and handle the escape sequence normally.
*/
printbuf_memappend_checked(tok->pb, (char *)utf8_replacement_char, 3);
tok->high_surrogate = 0;
tok->ucs_char = 0;
tok->st_pos = 0;
state = json_tokener_state_string_escape;
goto redo_char;
}
state = json_tokener_state_escape_unicode;
break;
// ===================================================
case json_tokener_state_boolean:
{
int size1, size2;
printbuf_memappend_checked(tok->pb, &c, 1);
size1 = json_min(tok->st_pos + 1, json_true_str_len);
size2 = json_min(tok->st_pos + 1, json_false_str_len);
if ((!(tok->flags & JSON_TOKENER_STRICT) &&
strncasecmp(json_true_str, tok->pb->buf, size1) == 0) ||
(strncmp(json_true_str, tok->pb->buf, size1) == 0))
{
if (tok->st_pos == json_true_str_len)
{
current = json_object_new_boolean(1);
if (current == NULL)
{
tok->err = json_tokener_error_memory;
goto out;
}
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
goto redo_char;
}
}
else if ((!(tok->flags & JSON_TOKENER_STRICT) &&
strncasecmp(json_false_str, tok->pb->buf, size2) == 0) ||
(strncmp(json_false_str, tok->pb->buf, size2) == 0))
{
if (tok->st_pos == json_false_str_len)
{
current = json_object_new_boolean(0);
if (current == NULL)
{
tok->err = json_tokener_error_memory;
goto out;
}
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
goto redo_char;
}
}
else
{
tok->err = json_tokener_error_parse_boolean;
goto out;
}
tok->st_pos++;
}
break;
case json_tokener_state_number:
{
/* Advance until we change state */
const char *case_start = str;
int case_len = 0;
int is_exponent = 0;
int neg_sign_ok = 1;
int pos_sign_ok = 0;
if (printbuf_length(tok->pb) > 0)
{
/* We don't save all state from the previous incremental parse
so we need to re-generate it based on the saved string so far.
*/
char *e_loc = strchr(tok->pb->buf, 'e');
if (!e_loc)
e_loc = strchr(tok->pb->buf, 'E');
if (e_loc)
{
char *last_saved_char =
&tok->pb->buf[printbuf_length(tok->pb) - 1];
is_exponent = 1;
pos_sign_ok = neg_sign_ok = 1;
/* If the "e" isn't at the end, we can't start with a '-' */
if (e_loc != last_saved_char)
{
neg_sign_ok = 0;
pos_sign_ok = 0;
}
// else leave it set to 1, i.e. start of the new input
}
}
while (c && ((c >= '0' && c <= '9') ||
(!is_exponent && (c == 'e' || c == 'E')) ||
(neg_sign_ok && c == '-') || (pos_sign_ok && c == '+') ||
(!tok->is_double && c == '.')))
{
pos_sign_ok = neg_sign_ok = 0;
++case_len;
/* non-digit characters checks */
/* note: since the main loop condition to get here was
* an input starting with 0-9 or '-', we are
* protected from input starting with '.' or
* e/E.
*/
switch (c)
{
case '.':
tok->is_double = 1;
pos_sign_ok = 1;
neg_sign_ok = 1;
break;
case 'e': /* FALLTHRU */
case 'E':
is_exponent = 1;
tok->is_double = 1;
/* the exponent part can begin with a negative sign */
pos_sign_ok = neg_sign_ok = 1;
break;
default: break;
}
if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok))
{
printbuf_memappend_checked(tok->pb, case_start, case_len);
goto out;
}
}
/*
Now we know c isn't a valid number char, but check whether
it might have been intended to be, and return a potentially
more understandable error right away.
However, if we're at the top-level, use the number as-is
because c can be part of a new object to parse on the
next call to json_tokener_parse().
*/
if (tok->depth > 0 && c != ',' && c != ']' && c != '}' && c != '/' &&
c != 'I' && c != 'i' && !is_ws_char(c))
{
tok->err = json_tokener_error_parse_number;
goto out;
}
if (case_len > 0)
printbuf_memappend_checked(tok->pb, case_start, case_len);
// Check for -Infinity
if (tok->pb->buf[0] == '-' && case_len <= 1 && (c == 'i' || c == 'I'))
{
state = json_tokener_state_inf;
tok->st_pos = 0;
goto redo_char;
}
if (tok->is_double && !(tok->flags & JSON_TOKENER_STRICT))
{
/* Trim some chars off the end, to allow things
like "123e+" to parse ok. */
while (printbuf_length(tok->pb) > 1)
{
char last_char = tok->pb->buf[printbuf_length(tok->pb) - 1];
if (last_char != 'e' && last_char != 'E' &&
last_char != '-' && last_char != '+')
{
break;
}
tok->pb->buf[printbuf_length(tok->pb) - 1] = '\0';
printbuf_length(tok->pb)--;
}
}
}
{
int64_t num64;
uint64_t numuint64;
double numd;
if (!tok->is_double && tok->pb->buf[0] == '-' &&
json_parse_int64(tok->pb->buf, &num64) == 0)
{
if (errno == ERANGE && (tok->flags & JSON_TOKENER_STRICT))
{
tok->err = json_tokener_error_parse_number;
goto out;
}
current = json_object_new_int64(num64);
if (current == NULL)
{
tok->err = json_tokener_error_memory;
goto out;
}
}
else if (!tok->is_double && tok->pb->buf[0] != '-' &&
json_parse_uint64(tok->pb->buf, &numuint64) == 0)
{
if (errno == ERANGE && (tok->flags & JSON_TOKENER_STRICT))
{
tok->err = json_tokener_error_parse_number;
goto out;
}
if (numuint64 && tok->pb->buf[0] == '0' &&
(tok->flags & JSON_TOKENER_STRICT))
{
tok->err = json_tokener_error_parse_number;
goto out;
}
if (numuint64 <= INT64_MAX)
{
num64 = (uint64_t)numuint64;
current = json_object_new_int64(num64);
if (current == NULL)
{
tok->err = json_tokener_error_memory;
goto out;
}
}
else
{
current = json_object_new_uint64(numuint64);
if (current == NULL)
{
tok->err = json_tokener_error_memory;
goto out;
}
}
}
else if (tok->is_double &&
json_tokener_parse_double(
tok->pb->buf, printbuf_length(tok->pb), &numd) == 0)
{
current = json_object_new_double_s(numd, tok->pb->buf);
if (current == NULL)
{
tok->err = json_tokener_error_memory;
goto out;
}
}
else
{
tok->err = json_tokener_error_parse_number;
goto out;
}
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
goto redo_char;
}
break;
case json_tokener_state_array_after_sep:
case json_tokener_state_array:
if (c == ']')
{
// Minimize memory usage; assume parsed objs are unlikely to be changed
json_object_array_shrink(current, 0);
if (state == json_tokener_state_array_after_sep &&
(tok->flags & JSON_TOKENER_STRICT))
{
tok->err = json_tokener_error_parse_unexpected;
goto out;
}
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
}
else
{
if (tok->depth >= tok->max_depth - 1)
{
tok->err = json_tokener_error_depth;
goto out;
}
state = json_tokener_state_array_add;
tok->depth++;
json_tokener_reset_level(tok, tok->depth);
goto redo_char;
}
break;
case json_tokener_state_array_add:
if (json_object_array_add(current, obj) != 0)
{
tok->err = json_tokener_error_memory;
goto out;
}
saved_state = json_tokener_state_array_sep;
state = json_tokener_state_eatws;
goto redo_char;
case json_tokener_state_array_sep:
if (c == ']')
{
// Minimize memory usage; assume parsed objs are unlikely to be changed
json_object_array_shrink(current, 0);
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
}
else if (c == ',')
{
saved_state = json_tokener_state_array_after_sep;
state = json_tokener_state_eatws;
}
else
{
tok->err = json_tokener_error_parse_array;
goto out;
}
break;
case json_tokener_state_object_field_start:
case json_tokener_state_object_field_start_after_sep:
if (c == '}')
{
if (state == json_tokener_state_object_field_start_after_sep &&
(tok->flags & JSON_TOKENER_STRICT))
{
tok->err = json_tokener_error_parse_unexpected;
goto out;
}
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
}
else if (c == '"' || c == '\'')
{
tok->quote_char = c;
printbuf_reset(tok->pb);
state = json_tokener_state_object_field;
}
else
{
tok->err = json_tokener_error_parse_object_key_name;
goto out;
}
break;
case json_tokener_state_object_field:
{
/* Advance until we change state */
const char *case_start = str;
while (1)
{
if (c == tok->quote_char)
{
printbuf_memappend_checked(tok->pb, case_start,
str - case_start);
obj_field_name = strdup(tok->pb->buf);
if (obj_field_name == NULL)
{
tok->err = json_tokener_error_memory;
goto out;
}
saved_state = json_tokener_state_object_field_end;
state = json_tokener_state_eatws;
break;
}
else if (c == '\\')
{
printbuf_memappend_checked(tok->pb, case_start,
str - case_start);
saved_state = json_tokener_state_object_field;
state = json_tokener_state_string_escape;
break;
}
else if ((tok->flags & JSON_TOKENER_STRICT) && (unsigned char)c <= 0x1f)
{
// Disallow control characters in strict mode
tok->err = json_tokener_error_parse_string;
goto out;
}
if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok))
{
printbuf_memappend_checked(tok->pb, case_start,
str - case_start);
goto out;
}
}
}
break;
case json_tokener_state_object_field_end:
if (c == ':')
{
saved_state = json_tokener_state_object_value;
state = json_tokener_state_eatws;
}
else
{
tok->err = json_tokener_error_parse_object_key_sep;
goto out;
}
break;
case json_tokener_state_object_value:
if (tok->depth >= tok->max_depth - 1)
{
tok->err = json_tokener_error_depth;
goto out;
}
state = json_tokener_state_object_value_add;
tok->depth++;
json_tokener_reset_level(tok, tok->depth);
goto redo_char;
case json_tokener_state_object_value_add:
if (json_object_object_add(current, obj_field_name, obj) != 0)
{
tok->err = json_tokener_error_memory;
goto out;
}
free(obj_field_name);
obj_field_name = NULL;
saved_state = json_tokener_state_object_sep;
state = json_tokener_state_eatws;
goto redo_char;
case json_tokener_state_object_sep:
/* { */
if (c == '}')
{
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
}
else if (c == ',')
{
saved_state = json_tokener_state_object_field_start_after_sep;
state = json_tokener_state_eatws;
}
else
{
tok->err = json_tokener_error_parse_object_value_sep;
goto out;
}
break;
}
(void)ADVANCE_CHAR(str, tok);
if (!c) // This is the char *before* advancing
break;
} /* while(PEEK_CHAR) */
out:
if ((tok->flags & JSON_TOKENER_VALIDATE_UTF8) && (nBytes != 0))
{
tok->err = json_tokener_error_parse_utf8_string;
}
if (c && (state == json_tokener_state_finish) && (tok->depth == 0) &&
(tok->flags & (JSON_TOKENER_STRICT | JSON_TOKENER_ALLOW_TRAILING_CHARS)) ==
JSON_TOKENER_STRICT)
{
/* unexpected char after JSON data */
tok->err = json_tokener_error_parse_unexpected;
}
if (!c)
{
/* We hit an eof char (0) */
if (state != json_tokener_state_finish && saved_state != json_tokener_state_finish)
tok->err = json_tokener_error_parse_eof;
}
#ifdef HAVE_USELOCALE
uselocale(oldlocale);
freelocale(newloc);
#elif defined(HAVE_SETLOCALE)
setlocale(LC_NUMERIC, oldlocale);
free(oldlocale);
#endif
if (tok->err == json_tokener_success)
{
json_object *ret = json_object_get(current);
int ii;
/* Partially reset, so we parse additional objects on subsequent calls. */
for (ii = tok->depth; ii >= 0; ii--)
json_tokener_reset_level(tok, ii);
return ret;
}
MC_DEBUG("json_tokener_parse_ex: error %s at offset %d\n", json_tokener_errors[tok->err],
tok->char_offset);
return NULL;
}
static json_bool json_tokener_validate_utf8(const char c, unsigned int *nBytes)
{
unsigned char chr = c;
if (*nBytes == 0)
{
if (chr >= 0x80)
{
if ((chr & 0xe0) == 0xc0)
*nBytes = 1;
else if ((chr & 0xf0) == 0xe0)
*nBytes = 2;
else if ((chr & 0xf8) == 0xf0)
*nBytes = 3;
else
return 0;
}
}
else
{
if ((chr & 0xC0) != 0x80)
return 0;
(*nBytes)--;
}
return 1;
}
void json_tokener_set_flags(struct json_tokener *tok, int flags)
{
tok->flags = flags;
}
size_t json_tokener_get_parse_end(struct json_tokener *tok)
{
assert(tok->char_offset >= 0); /* Drop this line when char_offset becomes a size_t */
return (size_t)tok->char_offset;
}
static int json_tokener_parse_double(const char *buf, int len, double *retval)
{
char *end;
*retval = strtod(buf, &end);
if (buf + len == end)
return 0; // It worked
return 1;
}
json-c-0.19/issues_closed_for_0.18.md 0000644 0001750 0001750 00000011620 15217751164 016037 0 ustar uerh uerh This list was created with:
```
PREV=2023-08-12
NOW=2024-09-15
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.18.md
```
* [Issue #826](https://github.com/json-c/json-c/issues/826) - CMake: remove needless policy setting
* [Issue #827](https://github.com/json-c/json-c/issues/827) - Resolve build issue in tokener_parse_ex_fuzzer.c
* [Issue #828](https://github.com/json-c/json-c/issues/828) - Put arc4random check under DISABLE_EXTRA_LIBS=OFF in CMakeLists.txt.
* [Issue #829](https://github.com/json-c/json-c/issues/829) - Cannot build with clang-cl
* [Issue #830](https://github.com/json-c/json-c/issues/830) - I am looking whether this CVE - CVE-2021-32292 is impacted by json-c version v0.13.1or not ?
* [Issue #831](https://github.com/json-c/json-c/issues/831) - rename WIN32 to _WIN32
* [Issue #833](https://github.com/json-c/json-c/issues/833) - memory leak issue in 0.13
* [Issue #834](https://github.com/json-c/json-c/issues/834) - fix error des of 'error_memory'
* [Issue #835](https://github.com/json-c/json-c/issues/835) - fix error des of 'error_memory'
* [Issue #836](https://github.com/json-c/json-c/issues/836) - Null pointer dereference in tokener_parse_ex_fuzzer.cc
* [Issue #837](https://github.com/json-c/json-c/issues/837) - Add type checking for parsed objects in tokener_parse_ex_fuzzer
* [Issue #838](https://github.com/json-c/json-c/issues/838) - Cannot link properly using cmake
* [Issue #839](https://github.com/json-c/json-c/issues/839) - json_pointer.c: initialize idx
* [Issue #840](https://github.com/json-c/json-c/issues/840) - Memory leak when enable HAVE_SETLOCALE and HAVE_USELOCALE
* [Issue #841](https://github.com/json-c/json-c/issues/841) - Random crash in json_tokener_parse
* [Issue #842](https://github.com/json-c/json-c/issues/842) - Assignment bug in json_pointer.c
* [Issue #843](https://github.com/json-c/json-c/issues/843) - _WIN32 should be used, not WIN32 in source code ifdefs.
* [Issue #844](https://github.com/json-c/json-c/issues/844) - Doxygen: mis-wording in `json_object_put`
* [Issue #845](https://github.com/json-c/json-c/issues/845) - [CMP0153](https://cmake.org/cmake/help/latest/policy/CMP0153.html)
* [Issue #846](https://github.com/json-c/json-c/issues/846) - CMP0153
* [Issue #848](https://github.com/json-c/json-c/issues/848) - json_object_from_file caused calloc SIGSEGV
* [Issue #849](https://github.com/json-c/json-c/issues/849) - random_seed.c: add a Coverity Scan suppression
* [Issue #850](https://github.com/json-c/json-c/issues/850) - Missing return description
* [Issue #851](https://github.com/json-c/json-c/issues/851) - Allow NULL in json_object_new_string() and json_object_new_string_len()
* [Issue #852](https://github.com/json-c/json-c/issues/852) - docs: micro typo in json_object_put doc
* [Issue #853](https://github.com/json-c/json-c/issues/853) - json_tokener_parse_verbose does not set the error indicator when it fails to allocate the tokener
* [Issue #854](https://github.com/json-c/json-c/issues/854) - json_tokener_parse_verbose sets the error indicator to a wrong value when there is a memory allocation failure
* [Issue #856](https://github.com/json-c/json-c/issues/856) - Using libjson-c.so or compiling from source seg faults on json_tokener_parse_ex in alpine docker container
* [Issue #857](https://github.com/json-c/json-c/issues/857) - json_tokener_parse_verbose sets the error indicator to a wrong value when there is a memory allocation failure
* [Issue #858](https://github.com/json-c/json-c/issues/858) - json_tokener.h: json_tokener_parse_verbose: fix typo
* [Issue #859](https://github.com/json-c/json-c/issues/859) - Develop
* [Issue #860](https://github.com/json-c/json-c/issues/860) - Develop
* [Issue #861](https://github.com/json-c/json-c/issues/861) - Handle yet another out-of-memory condition.
* [Issue #862](https://github.com/json-c/json-c/issues/862) - Missing `json-c-targets.cmake` during build cmake build step
* [Issue #863](https://github.com/json-c/json-c/issues/863) - build ios simulator error
* [Issue #864](https://github.com/json-c/json-c/issues/864) - Build pkg-config for msvc as well
* [Issue #865](https://github.com/json-c/json-c/issues/865) - Assertion usage
* [Issue #866](https://github.com/json-c/json-c/issues/866) - Added github actions
* [Issue #868](https://github.com/json-c/json-c/issues/868) - I meet compile error in harmony
* [Issue #869](https://github.com/json-c/json-c/issues/869) - At a high level how are jsons parses? Are they terminated by the new line?
* [Issue #870](https://github.com/json-c/json-c/issues/870) - Non-Compliant features should be optional (and disabled)
json-c-0.19/meson_options.txt 0000644 0001750 0001750 00000002077 15217751164 015000 0 ustar uerh uerh
option('disable_bsymbolic', type: 'boolean', value: false, description: 'Avoid linking with -Bsymbolic-function')
option('disable_thread_local_storage', type: 'boolean', value: false, description: 'Disable Thread-Local Storage')
option('enable_rdrand', type: 'boolean', value: false, description: 'Enable RDRAND Hardware RNG')
option('enable_threading', type: 'boolean', value: false, description: 'Enable partial threading support')
option('override_get_random_seed', type: 'boolean', value: false, description: 'Override json_c_get_random_seed()')
option('disable_extra_libs', type: 'boolean', value: false, description: 'Avoid linking extra libraries like libbsd')
option('disable_json_pointer', type: 'boolean', value: false, description: 'Disable JSON pointer support')
option('disable_json_patch', type: 'boolean', value: false, description: 'Disable JSON patch support')
option('newlocale_needs_freelocale', type: 'boolean', value: false, description: 'FreeBSD workaround for newlocale')
option('build_apps', type: 'boolean', value: true, description: 'Build command-line apps')
json-c-0.19/json-c.pc.in 0000644 0001750 0001750 00000000404 15217751164 013455 0 ustar uerh uerh prefix=@prefix@
exec_prefix=@exec_prefix@
libdir=@libdir@
includedir=@includedir@
Name: json-c
Description: A JSON implementation in C
Version: @VERSION@
Requires:
Libs.private: @LIBS@
Libs: -L${libdir} -ljson-c
Cflags: -I${includedir} -I${includedir}/json-c
json-c-0.19/linkhash.c 0000644 0001750 0001750 00000052434 15217751164 013312 0 ustar uerh uerh /*
* $Id: linkhash.c,v 1.4 2006/01/26 02:16:28 mclark Exp $
*
* Copyright (c) 2004, 2005 Metaparadigm Pte. Ltd.
* Michael Clark
* Copyright (c) 2009 Hewlett-Packard Development Company, L.P.
*
* This library 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
#include
#include
#include
#include
#include
#include
#ifdef HAVE_ENDIAN_H
#include /* attempt to define endianness */
#endif
#if defined(_MSC_VER) || defined(__MINGW32__)
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include /* Get InterlockedCompareExchange */
#endif
#include "linkhash.h"
#include "random_seed.h"
/* hash functions */
static unsigned long lh_char_hash(const void *k);
static unsigned long lh_perllike_str_hash(const void *k);
static lh_hash_fn *char_hash_fn = lh_char_hash;
/* comparison functions */
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)
{
case JSON_C_STR_HASH_DFLT: char_hash_fn = lh_char_hash; break;
case JSON_C_STR_HASH_PERLLIKE: char_hash_fn = lh_perllike_str_hash; break;
default: return -1;
}
return 0;
}
static unsigned long lh_ptr_hash(const void *k)
{
/* CAW: refactored to be 64bit nice */
return (unsigned long)((((ptrdiff_t)k * LH_PRIME) >> 4) & ULONG_MAX);
}
int lh_ptr_equal(const void *k1, const void *k2)
{
return (k1 == k2);
}
/*
* hashlittle from lookup3.c, by Bob Jenkins, May 2006, Public Domain.
* https://burtleburtle.net/bob/c/lookup3.c
* minor modifications to make functions static so no symbols are exported
* minor modifications to compile with -Werror
*/
/*
-------------------------------------------------------------------------------
lookup3.c, by Bob Jenkins, May 2006, Public Domain.
These are functions for producing 32-bit hashes for hash table lookup.
hashword(), hashlittle(), hashlittle2(), hashbig(), mix(), and final()
are externally useful functions. Routines to test the hash are included
if SELF_TEST is defined. You can use this free for any purpose. It's in
the public domain. It has no warranty.
You probably want to use hashlittle(). hashlittle() and hashbig()
hash byte arrays. hashlittle() is faster than hashbig() on
little-endian machines. Intel and AMD are little-endian machines.
On second thought, you probably want hashlittle2(), which is identical to
hashlittle() except it returns two 32-bit hashes for the price of one.
You could implement hashbig2() if you wanted but I haven't bothered here.
If you want to find a hash of, say, exactly 7 integers, do
a = i1; b = i2; c = i3;
mix(a,b,c);
a += i4; b += i5; c += i6;
mix(a,b,c);
a += i7;
final(a,b,c);
then use c as the hash value. If you have a variable length array of
4-byte integers to hash, use hashword(). If you have a byte array (like
a character string), use hashlittle(). If you have several byte arrays, or
a mix of things, see the comments above hashlittle().
Why is this so big? I read 12 bytes at a time into 3 4-byte integers,
then mix those integers. This is fast (you can do a lot more thorough
mixing with 12*3 instructions on 3 integers than you can with 3 instructions
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
* need adjustment.
*/
#if (defined(__BYTE_ORDER) && defined(__LITTLE_ENDIAN) && __BYTE_ORDER == __LITTLE_ENDIAN) || \
(defined(i386) || defined(__i386__) || defined(__i486__) || defined(__i586__) || \
defined(__i686__) || defined(vax) || defined(MIPSEL))
#define HASH_LITTLE_ENDIAN 1
#define HASH_BIG_ENDIAN 0
#elif (defined(__BYTE_ORDER) && defined(__BIG_ENDIAN) && __BYTE_ORDER == __BIG_ENDIAN) || \
(defined(sparc) || defined(POWERPC) || defined(mc68000) || defined(sel))
#define HASH_LITTLE_ENDIAN 0
#define HASH_BIG_ENDIAN 1
#else
#define HASH_LITTLE_ENDIAN 0
#define HASH_BIG_ENDIAN 0
#endif
#define hashsize(n) ((uint32_t)1 << (n))
#define hashmask(n) (hashsize(n) - 1)
#define rot(x, k) (((x) << (k)) | ((x) >> (32 - (k))))
/*
-------------------------------------------------------------------------------
mix -- mix 3 32-bit values reversibly.
This is reversible, so any information in (a,b,c) before mix() is
still in (a,b,c) after mix().
If four pairs of (a,b,c) inputs are run through mix(), or through
mix() in reverse, there are at least 32 bits of the output that
are sometimes the same for one pair and different for another pair.
This was tested for:
* pairs that differed by one bit, by two bits, in any combination
of top bits of (a,b,c), or in any combination of bottom bits of
(a,b,c).
* "differ" is defined as +, -, ^, or ~^. For + and -, I transformed
the output delta to a Gray code (a^(a>>1)) so a string of 1's (as
is commonly produced by subtraction) look like a single 1-bit
difference.
* the base values were pseudorandom, all zero but one bit set, or
all zero plus a counter that starts at zero.
Some k values for my "a-=c; a^=rot(c,k); c+=b;" arrangement that
satisfy this are
4 6 8 16 19 4
9 15 3 18 27 15
14 9 3 7 17 3
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
used https://burtleburtle.net/bob/hash/avalanche.html to choose
the operations, constants, and arrangements of the variables.
This does not achieve avalanche. There are input bits of (a,b,c)
that fail to affect some output bits of (a,b,c), especially of a. The
most thoroughly mixed value is c, but it doesn't really even achieve
avalanche in c.
This allows some parallelism. Read-after-writes are good at doubling
the number of bits affected, so the goal of mixing pulls in the opposite
direction as the goal of parallelism. I did what I could. Rotates
seem to cost as much as shifts on every machine I could lay my hands
on, and rotates are much kinder to the top and bottom bits, so I used
rotates.
-------------------------------------------------------------------------------
*/
/* clang-format off */
#define mix(a,b,c) \
{ \
a -= c; a ^= rot(c, 4); c += b; \
b -= a; b ^= rot(a, 6); a += c; \
c -= b; c ^= rot(b, 8); b += a; \
a -= c; a ^= rot(c,16); c += b; \
b -= a; b ^= rot(a,19); a += c; \
c -= b; c ^= rot(b, 4); b += a; \
}
/* clang-format on */
/*
-------------------------------------------------------------------------------
final -- final mixing of 3 32-bit values (a,b,c) into c
Pairs of (a,b,c) values differing in only a few bits will usually
produce values of c that look totally different. This was tested for
* pairs that differed by one bit, by two bits, in any combination
of top bits of (a,b,c), or in any combination of bottom bits of
(a,b,c).
* "differ" is defined as +, -, ^, or ~^. For + and -, I transformed
the output delta to a Gray code (a^(a>>1)) so a string of 1's (as
is commonly produced by subtraction) look like a single 1-bit
difference.
* the base values were pseudorandom, all zero but one bit set, or
all zero plus a counter that starts at zero.
These constants passed:
14 11 25 16 4 14 24
12 14 25 16 4 14 24
and these came close:
4 8 15 26 3 22 24
10 8 15 26 3 22 24
11 8 15 26 3 22 24
-------------------------------------------------------------------------------
*/
/* clang-format off */
#define final(a,b,c) \
{ \
c ^= b; c -= rot(b,14); \
a ^= c; a -= rot(c,11); \
b ^= a; b -= rot(a,25); \
c ^= b; c -= rot(b,16); \
a ^= c; a -= rot(c,4); \
b ^= a; b -= rot(a,14); \
c ^= b; c -= rot(b,24); \
}
/* clang-format on */
/*
-------------------------------------------------------------------------------
hashlittle() -- hash a variable-length key into a 32-bit value
k : the key (the unaligned variable-length array of bytes)
length : the length of the key, counting by bytes
initval : can be any 4-byte value
Returns a 32-bit value. Every bit of the key affects every bit of
the return value. Two keys differing by one or two bits will have
totally different hash values.
The best hash table sizes are powers of 2. There is no need to do
mod a prime (mod is sooo slow!). If you need less than 32 bits,
use a bitmask. For example, if you need only 10 bits, do
h = (h & hashmask(10));
In which case, the hash table should have hashsize(10) elements.
If you are hashing n strings (uint8_t **)k, do it like this:
for (i=0, h=0; i 12)
{
a += k[0];
b += k[1];
c += k[2];
mix(a,b,c);
length -= 12;
k += 3;
}
/*----------------------------- handle the last (probably partial) block */
/*
* "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
* 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
* 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
* noticeably faster for short strings (like English words).
* AddressSanitizer is similarly picky about overrunning
* the buffer. (https://clang.llvm.org/docs/AddressSanitizer.html)
*/
#ifdef VALGRIND
#define PRECISE_MEMORY_ACCESS 1
#elif defined(__SANITIZE_ADDRESS__) /* GCC's ASAN */
#define PRECISE_MEMORY_ACCESS 1
#elif defined(__has_feature)
#if __has_feature(address_sanitizer) /* Clang's ASAN */
#define PRECISE_MEMORY_ACCESS 1
#endif
#endif
#ifndef PRECISE_MEMORY_ACCESS
switch(length)
{
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 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 8 : b+=k[1]; 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 5 : b+=k[1]&0xff; a+=k[0]; break;
case 4 : a+=k[0]; break;
case 3 : a+=k[0]&0xffffff; break;
case 2 : a+=k[0]&0xffff; break;
case 1 : a+=k[0]&0xff; break;
case 0 : return c; /* zero length strings require no mixing */
}
#else /* make valgrind happy */
const uint8_t *k8 = (const uint8_t *)k;
switch(length)
{
case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
case 11: c+=((uint32_t)k8[10])<<16; /* fall through */
case 10: c+=((uint32_t)k8[9])<<8; /* fall through */
case 9 : c+=k8[8]; /* fall through */
case 8 : b+=k[1]; a+=k[0]; break;
case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */
case 6 : b+=((uint32_t)k8[5])<<8; /* fall through */
case 5 : b+=k8[4]; /* fall through */
case 4 : a+=k[0]; break;
case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */
case 2 : a+=((uint32_t)k8[1])<<8; /* fall through */
case 1 : a+=k8[0]; break;
case 0 : return c;
}
#endif /* !valgrind */
}
else if (HASH_LITTLE_ENDIAN && ((u.i & 0x1) == 0))
{
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 */
while (length > 12)
{
a += k[0] + (((uint32_t)k[1])<<16);
b += k[2] + (((uint32_t)k[3])<<16);
c += k[4] + (((uint32_t)k[5])<<16);
mix(a,b,c);
length -= 12;
k += 6;
}
/*----------------------------- handle the last (probably partial) block */
k8 = (const uint8_t *)k;
switch(length)
{
case 12: c+=k[4]+(((uint32_t)k[5])<<16);
b+=k[2]+(((uint32_t)k[3])<<16);
a+=k[0]+(((uint32_t)k[1])<<16);
break;
case 11: c+=((uint32_t)k8[10])<<16; /* fall through */
case 10: c+=k[4];
b+=k[2]+(((uint32_t)k[3])<<16);
a+=k[0]+(((uint32_t)k[1])<<16);
break;
case 9 : c+=k8[8]; /* fall through */
case 8 : b+=k[2]+(((uint32_t)k[3])<<16);
a+=k[0]+(((uint32_t)k[1])<<16);
break;
case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */
case 6 : b+=k[2];
a+=k[0]+(((uint32_t)k[1])<<16);
break;
case 5 : b+=k8[4]; /* fall through */
case 4 : a+=k[0]+(((uint32_t)k[1])<<16);
break;
case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */
case 2 : a+=k[0];
break;
case 1 : a+=k8[0];
break;
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;
/*--------------- all but the last block: affect some 32 bits of (a,b,c) */
while (length > 12)
{
a += k[0];
a += ((uint32_t)k[1])<<8;
a += ((uint32_t)k[2])<<16;
a += ((uint32_t)k[3])<<24;
b += k[4];
b += ((uint32_t)k[5])<<8;
b += ((uint32_t)k[6])<<16;
b += ((uint32_t)k[7])<<24;
c += k[8];
c += ((uint32_t)k[9])<<8;
c += ((uint32_t)k[10])<<16;
c += ((uint32_t)k[11])<<24;
mix(a,b,c);
length -= 12;
k += 12;
}
/*-------------------------------- last block: affect all 32 bits of (c) */
switch(length) /* all the case statements fall through */
{
case 12: c+=((uint32_t)k[11])<<24; /* FALLTHRU */
case 11: c+=((uint32_t)k[10])<<16; /* FALLTHRU */
case 10: c+=((uint32_t)k[9])<<8; /* FALLTHRU */
case 9 : c+=k[8]; /* FALLTHRU */
case 8 : b+=((uint32_t)k[7])<<24; /* FALLTHRU */
case 7 : b+=((uint32_t)k[6])<<16; /* FALLTHRU */
case 6 : b+=((uint32_t)k[5])<<8; /* FALLTHRU */
case 5 : b+=k[4]; /* FALLTHRU */
case 4 : a+=((uint32_t)k[3])<<24; /* FALLTHRU */
case 3 : a+=((uint32_t)k[2])<<16; /* FALLTHRU */
case 2 : a+=((uint32_t)k[1])<<8; /* FALLTHRU */
case 1 : a+=k[0];
break;
case 0 : return c;
}
}
final(a,b,c);
return c;
}
/* clang-format on */
/* a simple hash function similar to what perl does for strings.
* for good results, the string should not be excessively large.
*/
static unsigned long lh_perllike_str_hash(const void *k)
{
const char *rkey = (const char *)k;
unsigned hashval = 1;
while (*rkey)
hashval = hashval * 33 + *rkey++;
return hashval;
}
static unsigned long lh_char_hash(const void *k)
{
#if defined _MSC_VER || defined __MINGW32__
#define RANDOM_SEED_TYPE LONG
#else
#define RANDOM_SEED_TYPE int
#endif
static volatile RANDOM_SEED_TYPE random_seed = -1;
if (random_seed == -1)
{
RANDOM_SEED_TYPE seed;
/* we can't use -1 as it is the uninitialized sentinel */
while ((seed = json_c_get_random_seed()) == -1) {}
#if SIZEOF_INT == 8 && defined __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8
#define USE_SYNC_COMPARE_AND_SWAP 1
#endif
#if SIZEOF_INT == 4 && defined __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4
#define USE_SYNC_COMPARE_AND_SWAP 1
#endif
#if SIZEOF_INT == 2 && defined __GCC_HAVE_SYNC_COMPARE_AND_SWAP_2
#define USE_SYNC_COMPARE_AND_SWAP 1
#endif
#if defined USE_SYNC_COMPARE_AND_SWAP
(void)__sync_val_compare_and_swap(&random_seed, -1, seed);
#elif defined _MSC_VER || defined __MINGW32__
InterlockedCompareExchange(&random_seed, seed, -1);
#else
//#warning "racy random seed initialization if used by multiple threads"
random_seed = seed; /* potentially racy */
#endif
}
return hashlittle((const char *)k, strlen((const char *)k), (uint32_t)random_seed);
}
int lh_char_equal(const void *k1, const void *k2)
{
return (strcmp((const char *)k1, (const char *)k2) == 0);
}
struct lh_table *lh_table_new(int size, lh_entry_free_fn *free_fn, lh_hash_fn *hash_fn,
lh_equal_fn *equal_fn)
{
int i;
struct lh_table *t;
/* Allocate space for elements to avoid divisions by zero. */
assert(size > 0);
t = (struct lh_table *)calloc(1, sizeof(struct lh_table));
if (!t)
return NULL;
t->count = 0;
t->size = size;
t->table = (struct lh_entry *)calloc(size, sizeof(struct lh_entry));
if (!t->table)
{
free(t);
return NULL;
}
t->free_fn = free_fn;
t->hash_fn = hash_fn;
t->equal_fn = equal_fn;
for (i = 0; i < size; i++)
t->table[i].k = LH_EMPTY;
return t;
}
struct lh_table *lh_kchar_table_new(int size, lh_entry_free_fn *free_fn)
{
return lh_table_new(size, free_fn, char_hash_fn, lh_char_equal);
}
struct lh_table *lh_kptr_table_new(int size, lh_entry_free_fn *free_fn)
{
return lh_table_new(size, free_fn, lh_ptr_hash, lh_ptr_equal);
}
int lh_table_resize(struct lh_table *t, int new_size)
{
struct lh_table *new_t;
struct lh_entry *ent;
new_t = lh_table_new(new_size, NULL, t->hash_fn, t->equal_fn);
if (new_t == NULL)
return -1;
for (ent = t->head; ent != NULL; ent = ent->next)
{
unsigned long h = lh_get_hash(new_t, ent->k);
unsigned int opts = 0;
if (ent->k_is_constant)
opts = JSON_C_OBJECT_ADD_CONSTANT_KEY;
if (lh_table_insert_w_hash(new_t, ent->k, ent->v, h, opts) != 0)
{
lh_table_free(new_t);
return -1;
}
}
free(t->table);
t->table = new_t->table;
t->size = new_size;
t->head = new_t->head;
t->tail = new_t->tail;
free(new_t);
return 0;
}
void lh_table_free(struct lh_table *t)
{
struct lh_entry *c;
if (t->free_fn)
{
for (c = t->head; c != NULL; c = c->next)
t->free_fn(c);
}
free(t->table);
free(t);
}
int lh_table_insert_w_hash(struct lh_table *t, const void *k, const void *v, const unsigned long h,
const unsigned opts)
{
unsigned long n;
if (t->count >= t->size * LH_LOAD_FACTOR)
{
/* 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;
}
n = h % t->size;
while (1)
{
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_is_constant = (opts & JSON_C_OBJECT_ADD_CONSTANT_KEY);
t->table[n].v = v;
t->count++;
if (t->head == NULL)
{
t->head = t->tail = &t->table[n];
t->table[n].next = t->table[n].prev = NULL;
}
else
{
t->tail->next = &t->table[n];
t->table[n].prev = t->tail;
t->table[n].next = NULL;
t->tail = &t->table[n];
}
return 0;
}
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);
}
struct lh_entry *lh_table_lookup_entry_w_hash(struct lh_table *t, const void *k,
const unsigned long h)
{
unsigned long n = h % t->size;
int count = 0;
while (count < t->size)
{
if (t->table[n].k == LH_EMPTY)
return NULL;
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++;
}
return NULL;
}
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));
}
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);
if (e != NULL)
{
if (v != NULL)
*v = lh_entry_v(e);
return 1; /* key found */
}
if (v != NULL)
*v = NULL;
return 0; /* key not found */
}
int lh_table_delete_entry(struct lh_table *t, struct lh_entry *e)
{
/* CAW: fixed to be 64bit nice, still need the crazy negative case... */
ptrdiff_t n = (ptrdiff_t)(e - t->table);
assert(n >= 0 && n < t->size);
/* CAW: this is bad, really bad, maybe stack goes other direction on this machine... */
if (n < 0)
{
return -2;
}
if (t->table[n].k == LH_EMPTY || t->table[n].k == LH_FREED)
return -1;
t->count--;
if (t->free_fn)
t->free_fn(e);
t->table[n].v = NULL;
t->table[n].k = LH_FREED;
if (t->tail == &t->table[n] && t->head == &t->table[n])
{
t->head = t->tail = NULL;
}
else if (t->head == &t->table[n])
{
t->head->next->prev = NULL;
t->head = t->head->next;
}
else if (t->tail == &t->table[n])
{
t->tail->prev->next = NULL;
t->tail = t->tail->prev;
}
else
{
t->table[n].prev->next = t->table[n].next;
t->table[n].next->prev = t->table[n].prev;
}
t->table[n].next = t->table[n].prev = NULL;
return 0;
}
int lh_table_delete_entry_to_tail(struct lh_table *t, struct lh_entry *first_entry)
{
struct lh_entry *del_entry = t->tail;
do
{
struct lh_entry *prev = del_entry->prev;
// Could probably micro-optimize this, but better to avoid code duplication for now
if (lh_table_delete_entry(t, del_entry) != 0)
return -1;
if (del_entry == first_entry)
break;
del_entry = prev;
} while (del_entry != NULL);
return 0;
}
int lh_table_delete(struct lh_table *t, const void *k)
{
struct lh_entry *e = lh_table_lookup_entry(t, k);
if (!e)
return -1;
return lh_table_delete_entry(t, e);
}
int lh_table_length(struct lh_table *t)
{
return t->count;
}
json-c-0.19/ChangeLog 0000644 0001750 0001750 00000077616 15217751164 013130 0 ustar uerh uerh
0.19 (up to commit 3c1cf2b, 2026-06-27)
========================================
Deprecated and removed features:
--------------------------------
* none
New features
------------
* Add support for Commodore Amiga and MorphOS
* Allow builds with CMake 4 - sync minimum version across all CMakeLists.txt files
* Update openssl command to work for newer versions of openssl.
* Add support for building json-c with meson
* Support MSVC in packages that use GNU Autoconf.
* Add VERSIONINFO to libjson-c.dll
* Make json_tokener_free(NULL) a no-op, to simplify cleanup paths.
* Explicitly handle NaN values when converting to int
* Set errno=RANGE in json_object_get_int/int64/uint64() when the source value can't be represented in the target type.
* Make json_parse a bit more useful by adding -u (validate UTF8) and -P (specify arbitrary tokener parse flags), and read from stdin if no filename is provided.
* Fix the apps/json_parse "-s" (strict) option so it actually does something, and default to non-strict.
Significant changes and bug fixes
---------------------------------
* Issue #867 - also disallow control characters in keys in JSON_TOKENER_STRICT mode
* Issue #875: cast to unsigned char so bytes above 0x7f aren't interpreted as negative, which was causing the strict-mode control characters check to incorrectly trigger.
* Issue #881: don't allow json_tokener_new_ex() with a depth < 1
* Fix linkhash breaking -std=c89
* Fixing Cmake build when using clang-cl, avoids errors about redefining existing symbols
* Fix AIX build failure - Add CMake detection for getopt.h
* Fix bug involving supplemental code points that look like high surrogates
* Fix runtime issue with test_util_file.c in Windows (add O_BINARY)
* Fix macro WIN32_LEAN_AND_MEAN redefined
* Issue #914: Fix Memory usage regression due to newlocale() on macOS
* Issue #916: Fix OOM via large array index in json_pointer_set
* Issue #923: Avoid stack recursion in json_object_put()
* Issue #927: CVE-2026-9146 - update json_object_iterator documentation
* Issue #929: CVE-2026-11322 - fix information disclosure bug in apps/json_parse (not installed by default)
* Issue #930: fix locale-dependent strtod in json_object_get_double
* Issue #931: deep copy values in json_patch copy op to avoid aliasing and cycles
0.18 (up to commit 6bfab90, 2024-09-15)
========================================
Deprecated and removed features:
--------------------------------
* Clean up pre-3.9 CMake support in CMakeLists.txt
New features
------------
* Build pkg-config for msvc as well
Significant changes and bug fixes
---------------------------------
* Critical fix for binary compatibility with 0.16: Move the
json_tokener_error_memory entry to the end of enum json_tokener_error.
* Issue #829: attempt to detect clang-cl.exe and pass MSVC-compatile command
line arguments.
* PR #831 - rename WIN32 to _WIN32
* PR #839 - Fix gcc 5 "may be used uninitialized" failure in json_pointer.c
* PR #849 - random_seed.c: add a Coverity Scan suppression
* Issue #854: Set error=json_tokener_error_memory in
json_tokener_parser_verbose() when allocating the tokener fails.
* Issue #857: fix a few places where json_tokener should have been returning
json_tokener_error_memory but wasn't.
* Handle yet another out-of-memory condition in json_tokener, duplocate can
return NULL.
* Various fixes in the fuzzers
* A few minor doc fixes
***
0.17 (up to commit 077661f, 2023-08-08)
========================================
Known Bugs
----------
* DO NOT USE THE 0.17 RELEASE: json_tokener_error_memory in misplaced in the
json_tokener_error enum, leading to binary compatibility issues.
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)
=================================
This release, being three and a half years after the 0.12 branch (f84d9c),
has quite a number of changes included. The following is a sampling of
the most significant ones.
Since the 0.12 release, 250 issues and pull requests have been closed.
See issues_closed_for_0.13.md for a complete list.
Deprecated and removed features:
--------------------------------
* 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()
* lh_abort() is deprecated. It will be removed.
Behavior changes:
-----------------
* Tighten the number parsing algorithm to raise errors instead of truncating
the results. For example 12.3.4 or 2015-01-15, which now return null.
See commit 99d8fc
* 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.
* Check for failure when allocating memory, returning NULL and errno=ENOMEM.
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)
New features:
-------------
* We're aiming to follow RFC 7159 now.
* Add a couple of additional option to json_object_to_json_string_ext:
JSON_C_TO_STRING_PRETTY_TAB
JSON_C_TO_STRING_NOSLASHESCAPE
* Add a json_object_object_add_ex() function to allow for performance
improvements when certain constraints are known to be true.
* Make serialization format of doubles configurable, in two different ways:
Call json_object_set_serializer with json_object_double_to_json_string and a custom
format on each double object, or
Call json_c_set_serialization_double_format() to set a global or thread-wide format.
* Add utility function for comparing json_objects - json_object_equal()
* Add a way to copy entire object trees: json_object_deep_copy()
* Add json_object_set_ function to modify the value of existing json_object's
without the need to recreate them. Also add a json_object_int_inc function to
adjust an int's value.
* Add support for JSON pointer, RFC 6901. See json_pointer.h
* Add a json_util_get_last_err() function to retrieve the string describing the
cause of errors, instead of printing to stderr.
* Add perllike hash function for strings, and json_global_set_string_hash() 8f8d03d
* Add a json_c_visit() function to provide a way to iterate over a tree of json-c objects.
Notable bug fixes and other improvements:
-----------------------------------------
* Make reference increment and decrement atomic to allow passing json objects between threads.
* Fix json_object_object_foreach to avoid uninitialized variable warnings.
* Improve performance by removing unneeded data items from hashtable code and reducing duplicate hash computation.
* Improve performance by storing small strings inside json_object
* Improve performance of json_object_to_json_string by removing variadic printf. commit 9ff0f49
* Issue #371: fix parsing of "-Infinity", and avoid needlessly copying the input when doing so.
* Fix stack buffer overflow in json_object_double_to_json_string_format() - commit 2c2deb87
* Fix various potential null ptr deref and int32 overflows
* Issue #332: fix a long-standing bug in array_list_put_idx() where it would attempt to free previously free'd entries due to not checking the current array length.
* Issue #195: use uselocale() instead of setlocale() in json_tokener to behave better in threaded environments.
* Issue #275: fix out of bounds read when handling unicode surrogate pairs.
* Ensure doubles that happen to be a whole number are emitted with ".0" - commit ca7a19
* PR#331: for Visual Studio, use a snprintf/vsnprintf wrapper that ensures the string is terminated.
* Fix double to int cast overflow in json_object_get_int64.
* Clamp double to int32 when narrowing in json_object_get_int.
* Use strtoll() to parse ints - instead of sscanf
* Miscellaneous smaller changes, including removing unused variables, fixing warning
about uninitialized variables adding const qualifiers, reformatting code, etc...
Build changes:
--------------
* Add Appveyor and Travis build support
* Switch to using CMake when building on Windows with Visual Studio.
A dynamic .dll is generated instead of a .lib
config.h is now generated, config.h.win32 should no longer be manually copied
* Add support for MacOS through CMake too.
* Enable silent build by default
* Link against libm when needed
* Add support for building with AddressSanitizer
* Add support for building with Clang
* Add a --enable-threading configure option, and only use the (slower) __sync_add_and_fetch()/__sync_sub_and_fetch() function when it is specified.
List of new functions added:
----------------------------
### json_object.h
* array_list_bsearch()
* array_list_del_idx()
* json_object_to_json_string_length()
* json_object_get_userdata()
* json_object_set_userdata()
* json_object_object_add_ex()
* json_object_array_bsearch()
* json_object_array_del_idx()
* json_object_set_boolean()
* json_object_set_int()
* json_object_int_inc()
* json_object_set_int64()
* json_c_set_serialization_double_format()
* json_object_double_to_json_string()
* json_object_set_double()
* json_object_set_string()
* json_object_set_string_len()
* json_object_equal()
* json_object_deep_copy()
### json_pointer.h
* json_pointer_get()
* json_pointer_getf()
* json_pointer_set()
* json_pointer_setf()
### json_util.h
* json_object_from_fd()
* json_object_to_fd()
* json_util_get_last_err()
### json_visit.h
* json_c_visit()
### linkhash.h
* json_global_set_string_hash()
* lh_table_resize()
### printbuf.h
* printbuf_strappend()
0.12.1
======
* Minimal changes to address compile issues.
0.12
====
* Address security issues:
* CVE-2013-6371: hash collision denial of service
* CVE-2013-6370: buffer overflow if size_t is larger than int
* Avoid potential overflow in json_object_get_double
* Eliminate the mc_abort() function and MC_ABORT macro.
* Make the json_tokener_errors array local. It has been deprecated for
a while, and json_tokener_error_desc() should be used instead.
* change the floating point output format to %.17g so values with
more than 6 digits show up in the output.
* Remove the old libjson.so name compatibility support. The library is
only created as libjson-c.so now and headers are only installed
into the ${prefix}/json-c directory.
* When supported by the linker, add the -Bsymbolic-functions flag.
* Various changes to fix the build on MSVC.
* Make strict mode more strict:
* number must not start with 0
* no single-quote strings
* no comments
* trailing char not allowed
* only allow lowercase literals
* Added a json_object_new_double_s() convenience function to allow
an exact string representation of a double to be specified when
creating the object and use it in json_tokener_parse_ex() so
a re-serialized object more exactly matches the input.
* Add support NaN and Infinity
0.11
====
* IMPORTANT: the name of the library has changed to libjson-c.so and
the header files are now in include/json-c.
The pkgconfig name has also changed from json to json-c.
You should change your build to use appropriate -I and -l options.
A compatibility shim is in place so builds using the old name will
continue to work, but that will be removed in the next release.
* Maximum recursion depth is now a runtime option.
json_tokener_new() is provided for compatibility.
json_tokener_new_ex(depth)
* Include json_object_iterator.h in the installed headers.
* Add support for building on Android.
* Rewrite json_object_object_add to replace just the value if the key already exists so keys remain valid.
* Make it safe to delete keys while iterating with the json_object_object_foreach macro.
* Add a json_set_serializer() function to allow the string output of a json_object to be customized.
* Make float parsing locale independent.
* Add a json_tokener_set_flags() function and a JSON_TOKENER_STRICT flag.
* Enable -Werror when building.
* speed improvements to parsing 64-bit integers on systems with working sscanf
* Add a json_object_object_length function.
* Fix a bug (buffer overrun) when expanding arrays to more than 64 entries.
0.10
====
* Add a json_object_to_json_string_ext() function to allow output to be
formatted in a more human readable form.
* Add json_object_object_get_ex(), a NULL-safe get object method, to be able
to distinguish between a key not present and the value being NULL.
* Add an alternative iterator implementation, see json_object_iterator.h
* Make json_object_iter public to enable external use of the
json_object_object_foreachC macro.
* Add a printbuf_memset() function to provide an efficient way to set and
append things like whitespace indentation.
* 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_objct_object_get().
* Rename boolean type to json_bool.
* Fix various compile issues for Visual Studio and MinGW.
* Allow json_tokener_parse_ex() to be re-used to parse multiple object.
Also, fix some parsing issues with capitalized hexadecimal numbers and
number in E notation.
* Add json_tokener_get_error() and json_tokener_error_desc() to better
encapsulate the process of retrieving errors while parsing.
* Various improvements to the documentation of many functions.
* Add new json_object_array_sort() function.
* Fix a bug in json_object_get_int(), which would incorrectly return 0
when called on a string type object.
Eric Haszlakiewicz
* Add a json_type_to_name() function.
Eric Haszlakiewicz
* Add a json_tokener_parse_verbose() function.
Jehiah Czebotar
* Improve support for null bytes within JSON strings.
Jehiah Czebotar
* Fix file descriptor leak if memory allocation fails in json_util
Zachary Blair, zack_blair at hotmail dot com
* Add int64 support. Two new functions json_object_net_int64 and
json_object_get_int64. Binary compatibility preserved.
Eric Haszlakiewicz, EHASZLA at transunion com
Rui Miguel Silva Seabra, rms at 1407 dot org
* Fix subtle bug in linkhash where lookup could hang after all slots
were filled then successively freed.
Spotted by Jean-Marc Naud, j dash m at newtraxtech dot com
* Make json_object_from_file take const char *filename
Spotted by Vikram Raj V, vsagar at attinteractive dot com
* Add handling of surrogate pairs (json_tokener.c, test4.c, Makefile.am)
Brent Miller, bdmiller at yahoo dash inc dot com
* Correction to comment describing printbuf_memappend in printbuf.h
Brent Miller, bdmiller at yahoo dash inc dot com
0.9
===
* Add README.html README-WIN32.html config.h.win32 to Makefile.am
Michael Clark,
* Add const qualifier to the json_tokener_parse functions
Eric Haszlakiewicz, EHASZLA at transunion dot com
* Rename min and max so we can never clash with C or C++ std library
Ian Atha, thatha at yahoo dash inc dot com
* Fix any noticeable spelling or grammar errors.
* Make sure every va_start has a va_end.
* Check all pointers for validity.
Erik Hovland, erik at hovland dot org
* Fix json_object_get_boolean to return false for empty string
Spotted by Vitaly Kruglikov, Vitaly dot Kruglikov at palm dot com
* optimizations to json_tokener_parse_ex(), printbuf_memappend()
Brent Miller, bdmiller at yahoo dash inc dot com
* Disable REFCOUNT_DEBUG by default in json_object.c
* 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 #ifdef __cplusplus guards to all of the headers
* Add typedefs for json_object, json_tokener, array_list, printbuf, lh_table
Michael Clark,
* Null pointer dereference fix. Fix json_object_get_boolean strlen test
to not return TRUE for zero length string. Remove redundant includes.
Erik Hovland, erik at hovland dot org
* Fixed warning reported by adding -Wstrict-prototypes
-Wold-style-definition to the compilatin flags.
Dotan Barak, dotanba at gmail dot com
* Add const correctness to public interfaces
Gerard Krol, g dot c dot krol at student dot tudelft dot nl
0.8
===
* Add va_end for every va_start
Dotan Barak, dotanba at gmail dot com
* Add macros to enable compiling out debug code
Geoffrey Young, geoff at modperlcookbook dot org
* Fix bug with use of capital E in numbers with exponents
Mateusz Loskot, mateusz at loskot dot net
* Add stddef.h include
* Patch allows for json-c compile with -Werror and not fail due to
-Wmissing-prototypes -Wstrict-prototypes -Wmissing-declarations
Geoffrey Young, geoff at modperlcookbook dot org
0.7
===
* Add escaping of backslash to json output
* Add escaping of forward slash on tokenizing and output
* Changes to internal tokenizer from using recursion to
using a depth state structure to allow incremental parsing
0.6
===
* Fix bug in escaping of control characters
Johan Björklund, johbjo09 at kth dot se
* Remove include "config.h" from headers (should only
be included from .c files)
Michael Clark
0.5
===
* Make headers C++ compatible by change *this to *obj
* Add ifdef C++ extern "C" to headers
* Use simpler definition of min and max in bits.h
Larry Lansing, llansing at fuzzynerd dot com
* Remove automake 1.6 requirement
* Move autogen commands into autogen.sh. Update README
* Remove error pointer special case for Windows
* Change license from LGPL to MIT
Michael Clark
0.4
===
* Fix additional error case in object parsing
* Add back sign reversal in nested object parse as error pointer
value is negative, while error value is positive.
Michael Clark
0.3
===
* fix pointer arithmetic bug for error pointer check in is_error() macro
* fix type passed to printbuf_memappend in json_tokener
* update autotools bootstrap instructions in README
Michael Clark
0.2
===
* printbuf.c - C. Watford (christopher.watford@gmail.com)
Added a Win32/Win64 compliant implementation of vasprintf
* debug.c - C. Watford (christopher.watford@gmail.com)
Removed usage of vsyslog on Win32/Win64 systems, needs to be handled
by a configure script
* json_object.c - C. Watford (christopher.watford@gmail.com)
Added scope operator to wrap usage of json_object_object_foreach, this
needs to be rethought to be more ANSI C friendly
* json_object.h - C. Watford (christopher.watford@gmail.com)
Added Microsoft C friendly version of json_object_object_foreach
* json_tokener.c - C. Watford (christopher.watford@gmail.com)
Added a Win32/Win64 compliant implementation of strndup
* json_util.c - C. Watford (christopher.watford@gmail.com)
Added cast and mask to suffice size_t v. unsigned int conversion
correctness
* json_tokener.c - sign reversal issue on error info for nested object parse
spotted by Johan Björklund (johbjo09 at kth.se)
* json_object.c - escape " in json_escape_str
* Change to automake and libtool to build shared and static library
Michael Clark
0.1
===
* initial release
json-c-0.19/debug.h 0000644 0001750 0001750 00000005217 15217751164 012601 0 ustar uerh uerh /*
* $Id: debug.h,v 1.5 2006/01/30 23:07:57 mclark Exp $
*
* Copyright (c) 2004, 2005 Metaparadigm Pte. Ltd.
* Michael Clark
* Copyright (c) 2009 Hewlett-Packard Development Company, L.P.
*
* 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_C_DEBUG_H_
#define _JSON_C_DEBUG_H_
#include
#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
JSON_EXPORT void mc_set_debug(int debug);
JSON_EXPORT int mc_get_debug(void);
JSON_EXPORT void mc_set_syslog(int syslog);
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
#define __STRING(x) #x
#endif
#ifndef PARSER_BROKEN_FIXED
#define JASSERT(cond) \
do \
{ \
} while (0)
#else
#define JASSERT(cond) \
do \
{ \
if (!(cond)) \
{ \
mc_error("cjson assert failure %s:%d : cond \"" __STRING(cond) "failed\n", \
__FILE__, __LINE__); \
*(int *)0 = 1; \
abort(); \
} \
} while (0)
#endif
#define MC_ERROR(x, ...) mc_error(x, ##__VA_ARGS__)
#ifdef MC_MAINTAINER_MODE
#define MC_SET_DEBUG(x) mc_set_debug(x)
#define MC_GET_DEBUG() mc_get_debug()
#define MC_SET_SYSLOG(x) mc_set_syslog(x)
#define MC_DEBUG(x, ...) mc_debug(x, ##__VA_ARGS__)
#define MC_INFO(x, ...) mc_info(x, ##__VA_ARGS__)
#else
#define MC_SET_DEBUG(x) \
if (0) \
mc_set_debug(x)
#define MC_GET_DEBUG() (0)
#define MC_SET_SYSLOG(x) \
if (0) \
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
#ifdef __cplusplus
}
#endif
#endif
json-c-0.19/json_patch.c 0000644 0001750 0001750 00000024004 15217751164 013631 0 ustar uerh uerh /*
* 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
#include
#include
#include "json_patch.h"
#include "json_object_private.h"
#include "json_pointer_private.h"
#include
#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_cb()
// key is ignored because this callback is only for arrays
static int json_object_array_insert_idx_cb(struct json_object *parent, const char *key, 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_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_cb(res, path, json_object_get(value),
json_object_array_insert_idx_cb, 0, &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_cb()
// key is ignored because this callback is only for arrays
static int json_object_array_move_cb(struct json_object *parent, const char *key, 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_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_set_cb array_set_cb;
struct json_pointer_get_result from;
struct json_object *jfrom;
struct json_object *value;
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
if (!move) {
/* RFC 6902 section 4.5: "copy" duplicates the value, it does
* not share it. Sharing the source via a reference (as a plain
* json_object_get() would) lets a later op insert the value
* beneath itself through a different pointer path, which the
* from/path string check above can't detect because both paths
* resolve to the same object, producing a reference cycle that
* loops forever on serialisation and breaks teardown. An
* independent deep copy can never alias an existing node. */
value = NULL;
if (from.obj != NULL &&
json_object_deep_copy(from.obj, &value, NULL) < 0) {
_set_err(ENOMEM, "Unable to copy value referenced by 'from' field");
return -1;
}
array_set_cb = json_object_array_insert_idx_cb;
} else {
json_object_get(from.obj);
value = from.obj;
rc = __json_patch_apply_remove(&from);
if (rc < 0) {
json_object_put(value);
return rc;
}
array_set_cb = json_object_array_move_cb;
}
rc = json_pointer_set_with_cb(res, path, value, array_set_cb, 0, &from);
if (rc)
{
_set_err(errno, "Failed to set value at path referenced by 'path' field");
json_object_put(value);
}
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;
}
json-c-0.19/json_config.h.in 0000644 0001750 0001750 00000000133 15217751164 014406 0 ustar uerh uerh
/* Define to 1 if you have the header file. */
#undef JSON_C_HAVE_INTTYPES_H
json-c-0.19/issues_closed_for_0.16.md 0000644 0001750 0001750 00000024130 15217751164 016035 0 ustar uerh uerh 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
json-c-0.19/abi-check.sh 0000755 0001750 0001750 00000002114 15217751164 013500 0 ustar uerh uerh #!/bin/sh
set -e
# The 0.17 release is broken
prev=0.18
release=0.19
# ... clone json-c, abi-compliance-checker, abi-dumper
if [ "$1" != "--skip-build" ] ; then
mkdir build
cd build
CFLAGS=-Og cmake -DCMAKE_INSTALL_PREFIX=~/json-c-installs/json-c-${release} ..
make && make test && make install
fi
# Assume the old version has already been built
cd ~/abi-compliance-checker
mkxml()
{
ver="$1"
if [ ! -e ../json-c-installs/json-c-${ver}/lib64 ] ; then
ln -s lib ../json-c-installs/json-c-${ver}/lib64
fi
cat < json-c-${ver}.xml
${ver}
../json-c-installs/json-c-${ver}/include/json-c
../json-c-installs/json-c-${ver}/lib64/libjson-c.so
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/..."
json-c-0.19/INSTALL 0000644 0001750 0001750 00000000056 15217751164 012367 0 ustar uerh uerh
See README.md for installation instructions.
json-c-0.19/arraylist.c 0000644 0001750 0001750 00000013102 15217751164 013510 0 ustar uerh uerh /*
* $Id: arraylist.c,v 1.4 2006/01/26 02:16:28 mclark Exp $
*
* Copyright (c) 2004, 2005 Metaparadigm Pte. Ltd.
* Michael Clark
*
* This library 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
#ifdef STDC_HEADERS
#include
#include
#endif /* STDC_HEADERS */
#if defined(HAVE_STRINGS_H) && !defined(_STRING_H) && !defined(__USE_BSD)
#include
#endif /* HAVE_STRINGS_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
#include "arraylist.h"
struct array_list *array_list_new(array_list_free_fn *free_fn)
{
return array_list_new2(free_fn, ARRAY_LIST_DEFAULT_SIZE);
}
struct array_list *array_list_new2(array_list_free_fn *free_fn, int initial_size)
{
struct array_list *arr;
if (initial_size < 0 || (size_t)initial_size >= SIZE_T_MAX / sizeof(void *))
return NULL;
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;
}
extern void array_list_free(struct array_list *arr)
{
size_t 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)
{
void *t;
size_t new_size;
if (max < arr->size)
return 0;
/* Avoid undefined behaviour on size_t overflow */
if (arr->size >= SIZE_T_MAX / 2)
new_size = max;
else
{
new_size = arr->size << 1;
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;
arr->array = (void **)t;
arr->size = new_size;
return 0;
}
int array_list_shrink(struct array_list *arr, size_t empty_slots)
{
void *t;
size_t new_size;
if (empty_slots >= SIZE_T_MAX / sizeof(void *) - arr->length)
return -1;
new_size = arr->length + empty_slots;
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 array_list_insert_idx(struct array_list *arr, size_t idx, void *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;
}
//static inline int _array_list_put_idx(struct array_list *arr, size_t idx, void *data)
int array_list_put_idx(struct array_list *arr, size_t idx, void *data)
{
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;
}
int array_list_set_idx(struct array_list *arr, size_t idx, void *data)
{
if (idx >= arr->length)
return -1;
arr->array[idx] = data;
return 0;
}
int array_list_add(struct array_list *arr, void *data)
{
/* Repeat some of array_list_put_idx() so we can skip several
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;
}
void array_list_sort(struct array_list *arr, int (*compar)(const void *, const void *))
{
qsort(arr->array, arr->length, sizeof(arr->array[0]), compar);
}
void *array_list_bsearch(const void **key, struct array_list *arr,
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;
/* Avoid overflow in calculation with large indices. */
if (idx > SIZE_T_MAX - count)
return -1;
stop = idx + count;
if (idx >= arr->length || stop > arr->length)
return -1;
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 *));
arr->length -= count;
return 0;
}
json-c-0.19/json_c_version.h 0000644 0001750 0001750 00000002530 15217751544 014530 0 ustar uerh uerh /*
* Copyright (c) 2012,2017 Eric Haszlakiewicz
*
* 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 Methods for retrieving the json-c version.
*/
#ifndef _json_c_version_h_
#define _json_c_version_h_
#ifdef __cplusplus
extern "C" {
#endif
#define JSON_C_MAJOR_VERSION 0
#define JSON_C_MINOR_VERSION 19
#define JSON_C_MICRO_VERSION 0
#define JSON_C_VERSION_NUM \
((JSON_C_MAJOR_VERSION << 16) | (JSON_C_MINOR_VERSION << 8) | JSON_C_MICRO_VERSION)
#define JSON_C_VERSION "0.19"
#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
* @return the version of the json-c library as a string
*/
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
* being the micro version, the next higher 8 bits being the minor version
* and the next higher 8 bits being the major version.
* For example, 7.12.99 would be 0x00070B63.
*
* @see JSON_C_VERSION_NUM
* @return the version of the json-c library as an int
*/
JSON_EXPORT int json_c_version_num(void); /* Returns JSON_C_VERSION_NUM */
#ifdef __cplusplus
}
#endif
#endif
json-c-0.19/json_object_iterator.h 0000644 0001750 0001750 00000022565 15217751164 015730 0 ustar uerh uerh /**
*******************************************************************************
* @file json_object_iterator.h
*
* Copyright (c) 2009-2012 Hewlett-Packard Development Company, L.P.
* Copyright (c) 2026 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.
*
* @brief An API for iterating over json_type_object objects,
* styled to be familiar to C++ programmers.
* Unlike json_object_object_foreach() and
* json_object_object_foreachC(), this avoids the need to expose
* json-c internals like lh_entry.
*
* API attributes:
* * Thread-safe: NO
* * Reentrant: NO
*
*******************************************************************************
*/
#ifndef JSON_OBJECT_ITERATOR_H
#define JSON_OBJECT_ITERATOR_H
#include "json_types.h"
#include
#ifdef __cplusplus
extern "C" {
#endif
/**
* The opaque iterator that references a name/value pair within
* a JSON Object instance or the "end" iterator value.
*/
struct json_object_iterator
{
const void *opaque_;
// These could be used to make an interator that fails "faster"
// in the face of certain changes to the underlying object, but
// would still be vulnerable to skipping entries.
// Changing this structure size is an ABI change
// const lh_table *table;
// size_t begin_size;
};
/**
* forward declaration of json-c's JSON value instance structure
*/
struct json_object;
/**
* Initializes an iterator structure to a "default" value that
* is convenient for initializing an iterator variable to a
* default state (e.g., initialization list in a class'
* constructor).
*
* @code
* struct json_object_iterator iter = json_object_iter_init_default();
* MyClass() : iter_(json_object_iter_init_default())
* @endcode
*
* @note The initialized value doesn't reference any specific
* pair, is considered an invalid iterator, and MUST NOT
* be passed to any json-c API that expects a valid
* iterator.
*
* @note User and internal code MUST NOT make any assumptions
* about and dependencies on the value of the "default"
* iterator value.
*
* @return json_object_iterator
*/
JSON_EXPORT struct json_object_iterator json_object_iter_init_default(void);
/** Retrieves an iterator to the first key/value pair of the JSON Object.
*
* @warning Any modification of the fields present on the object
* invalidates all iterators on that object, regardless of
* what key/value pair they are pointing to, other than the
* end iterator.
* Modifications include adding or removing any pair, even if
* set of keys appears unchanged after the modification.
* Modifying *values* is allowed, including replacing a value
* by calling json_object_add(), provided the key already exists.
* Attempting to use an invalidated iterator in any way, other
* than comparing it to the end iterator, is *undefined behavior*.
* Passing such an iterator to any of the the json_object_iterator
* functions is not even guaranteed to fail in any consistent way.
*
* @param obj JSON Object instance (MUST be of type json_object)
*
* @return json_object_iterator If the JSON Object has at
* least one pair, on return, the iterator refers
* to the first pair. If the JSON Object doesn't
* have any pairs, the returned iterator is
* equivalent to the "end" iterator for the same
* JSON Object instance.
*
* @code
* struct json_object_iterator it;
* struct json_object_iterator itEnd;
* struct json_object* obj;
*
* obj = json_tokener_parse("{'first':'george', 'age':100}");
* it = json_object_iter_begin(obj);
* itEnd = json_object_iter_end(obj);
*
* while (!json_object_iter_equal(&it, &itEnd)) {
* printf("%s\n",
* json_object_iter_peek_name(&it));
* json_object_iter_next(&it);
* }
*
* @endcode
*/
JSON_EXPORT struct json_object_iterator json_object_iter_begin(struct json_object *obj);
/** Retrieves the iterator that represents the position beyond the
* last pair of the given JSON Object instance.
*
* @warning Do NOT write code that assumes that the "end"
* iterator value is NULL, even if it is so in a
* particular instance of the implementation.
*
* @note The reason we do not (and MUST NOT) provide
* "json_object_iter_is_end(json_object_iterator* iter)"
* type of API is because it would limit the underlying
* representation of name/value containment (or force us
* to add additional, otherwise unnecessary, fields to
* the iterator structure). The "end" iterator and the
* equality test method, on the other hand, permit us to
* cleanly abstract pretty much any reasonable underlying
* representation without burdening the iterator
* structure with unnecessary data.
*
* @note For performance reasons, memorize the "end" iterator prior
* to any loop.
*
* @param obj JSON Object instance (MUST be of type json_object)
*
* @return json_object_iterator On return, the iterator refers
* to the "end" of the Object instance's pairs
* (i.e., NOT the last pair, but "beyond the last
* pair" value)
*/
JSON_EXPORT struct json_object_iterator json_object_iter_end(const struct json_object *obj);
/** Returns an iterator to the next pair, if any
*
* @warning Any modification of the fields of the object invalidates
* the iterator, see the warning on json_object_iter_begin()
* for details.
*
* @param iter [IN/OUT] Pointer to iterator that references a
* name/value pair; MUST be a valid, non-end iterator.
* WARNING: bad things will happen if invalid or "end"
* iterator is passed. Upon return will contain the
* reference to the next pair if there is one; if there
* are no more pairs, will contain the "end" iterator
* value, which may be compared against the return value
* of json_object_iter_end() for the same JSON Object
* instance.
*/
JSON_EXPORT void json_object_iter_next(struct json_object_iterator *iter);
/** Returns a const pointer to the name of the pair referenced
* by the given iterator.
*
* @param iter pointer to iterator that references a name/value
* pair; MUST be a valid, non-end iterator.
*
* @warning bad things will happen if an invalid or "end" iterator
* is passed. See the warning on json_object_iter_begin()
* for details.
*
* @return const char* Pointer to the name of the referenced
* name/value pair. The name memory belongs to the
* name/value pair, will be freed when the pair is
* deleted or modified, and MUST NOT be modified or
* freed by the user.
*/
JSON_EXPORT const char *json_object_iter_peek_name(const struct json_object_iterator *iter);
/** Returns a pointer to the json-c instance representing the
* value of the referenced name/value pair, without altering
* the instance's reference count.
*
* @param iter pointer to iterator that references a name/value
* pair; MUST be a valid, non-end iterator.
*
* @warning bad things will happen if an invalid or "end" iterator
* is passed. See the warning on json_object_iter_begin()
* for details.
*
* @return struct json_object* Pointer to the json-c value
* instance of the referenced name/value pair; the
* value's reference count is not changed by this
* function: if you plan to hold on to this json-c node,
* take a look at json_object_get() and
* json_object_put(). IMPORTANT: json-c API represents
* the JSON Null value as a NULL json_object instance
* pointer.
*/
JSON_EXPORT struct json_object *
json_object_iter_peek_value(const struct json_object_iterator *iter);
/** Tests two iterators for equality. Typically used to test
* for end of iteration by comparing an iterator to the
* corresponding "end" iterator (that was derived from the same
* JSON Object instance).
*
* @note The reason we do not (and MUST NOT) provide
* "json_object_iter_is_end(json_object_iterator* iter)"
* type of API is because it would limit the underlying
* representation of name/value containment (or force us
* to add additional, otherwise unnecessary, fields to
* the iterator structure). The equality test method, on
* the other hand, permits us to cleanly abstract pretty
* much any reasonable underlying representation.
*
* @param iter1 Pointer to first valid, non-NULL iterator
* @param iter2 POinter to second valid, non-NULL iterator
*
* @warning if a NULL iterator pointer or an uninitialized
* or invalid iterator, or iterators derived from
* different JSON Object instances are passed, bad things
* will happen!
*
* @return json_bool non-zero if iterators are equal (i.e., both
* reference the same name/value pair or are both at
* "end"); zero if they are not equal.
*/
JSON_EXPORT json_bool json_object_iter_equal(const struct json_object_iterator *iter1,
const struct json_object_iterator *iter2);
#ifdef __cplusplus
}
#endif
#endif /* JSON_OBJECT_ITERATOR_H */
json-c-0.19/.travis.yml 0000644 0001750 0001750 00000006224 15217751164 013452 0 ustar uerh uerh language: cpp
matrix:
include:
# ubuntu xenial 16.04
# gcc 5 is the default on xenial
- os: linux
dist: xenial
compiler: gcc
addons:
apt:
packages:
- valgrind
- cppcheck
- doxygen
- cmake
env: CHECK="true"
# ubuntu bionic 18.04
# gcc 7 is the default on bionic
- os: linux
dist: bionic
compiler: gcc
addons:
apt:
packages:
- valgrind
- cppcheck
- doxygen
- cmake
env: CHECK="true"
# 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"
# 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
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:
- 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_DIST" = "bionic" ]; then
sudo apt-get install -y valgrind cppcheck doxygen;
fi;
make distcheck;
if type cppcheck &> /dev/null ; then cppcheck --error-exitcode=1 --quiet *.h *.c tests/ ; fi;
fi
json-c-0.19/COPYING 0000644 0001750 0001750 00000004235 15217751164 012374 0 ustar uerh uerh
Copyright (c) 2009-2012 Eric Haszlakiewicz
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
----------------------------------------------------------------
Copyright (c) 2004, 2005 Metaparadigm Pte Ltd
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
json-c-0.19/json_object.c 0000644 0001750 0001750 00000155034 15217751164 014010 0 ustar uerh uerh /*
* Copyright (c) 2004, 2005 Metaparadigm Pte. Ltd.
* Michael Clark
* Copyright (c) 2009 Hewlett-Packard Development Company, L.P.
*
* This library 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 "strerror_override.h"
#include
#ifdef HAVE_LIMITS_H
#include
#endif
#include
#include
#include
#include
#include
#ifdef HAVE_LOCALE_H
#include
#endif /* HAVE_LOCALE_H */
#include "arraylist.h"
#include "debug.h"
#include "json_inttypes.h"
#include "json_object.h"
#include "json_object_private.h"
#include "json_util.h"
#include "linkhash.h"
#include "math_compat.h"
#include "printbuf.h"
#include "snprintf_compat.h"
#include "strdup_compat.h"
/* Avoid ctype.h and locale overhead */
#define is_plain_digit(c) ((c) >= '0' && (c) <= '9')
#if SIZEOF_LONG_LONG != SIZEOF_INT64_T
#error The long long type is not 64-bits
#endif
#ifndef SSIZE_T_MAX
#if SIZEOF_SSIZE_T == SIZEOF_INT
#define SSIZE_T_MAX INT_MAX
#elif SIZEOF_SSIZE_T == SIZEOF_LONG
#define SSIZE_T_MAX LONG_MAX
#elif SIZEOF_SSIZE_T == SIZEOF_LONG_LONG
#define SSIZE_T_MAX LLONG_MAX
#else
#error Unable to determine size of ssize_t
#endif
#endif
const char *json_number_chars = "0123456789.+-eE"; /* Unused, but part of public API, drop for 1.0 */
const char *json_hex_chars = "0123456789abcdefABCDEF";
static void json_object_generic_delete(struct json_object *jso);
#if defined(_MSC_VER) && (_MSC_VER <= 1800)
/* VS2013 doesn't know about "inline" */
#define inline __inline
#elif defined(AIX_CC)
#define inline
#endif
/* define colors */
#define ANSI_COLOR_RESET "\033[0m"
#define ANSI_COLOR_FG_GREEN "\033[0;32m"
#define ANSI_COLOR_FG_BLUE "\033[0;34m"
#define ANSI_COLOR_FG_MAGENTA "\033[0;35m"
/*
* Helper functions to more safely cast to a particular type of json_object
*/
static inline struct json_object_object *JC_OBJECT(struct json_object *jso)
{
return (void *)jso;
}
static inline const struct json_object_object *JC_OBJECT_C(const struct json_object *jso)
{
return (const void *)jso;
}
static inline struct json_object_array *JC_ARRAY(struct json_object *jso)
{
return (void *)jso;
}
static inline const struct json_object_array *JC_ARRAY_C(const struct json_object *jso)
{
return (const void *)jso;
}
static inline struct json_object_boolean *JC_BOOL(struct json_object *jso)
{
return (void *)jso;
}
static inline const struct json_object_boolean *JC_BOOL_C(const struct json_object *jso)
{
return (const void *)jso;
}
static inline struct json_object_double *JC_DOUBLE(struct json_object *jso)
{
return (void *)jso;
}
static inline const struct json_object_double *JC_DOUBLE_C(const struct json_object *jso)
{
return (const void *)jso;
}
static inline struct json_object_int *JC_INT(struct json_object *jso)
{
return (void *)jso;
}
static inline const struct json_object_int *JC_INT_C(const struct json_object *jso)
{
return (const void *)jso;
}
static inline struct json_object_string *JC_STRING(struct json_object *jso)
{
return (void *)jso;
}
static inline const struct json_object_string *JC_STRING_C(const struct json_object *jso)
{
return (const void *)jso;
}
#define JC_CONCAT(a, b) a##b
#define JC_CONCAT3(a, b, c) a##b##c
#define JSON_OBJECT_NEW(jtype) \
(struct JC_CONCAT(json_object_, jtype) *)json_object_new( \
JC_CONCAT(json_type_, jtype), sizeof(struct JC_CONCAT(json_object_, jtype)), \
&JC_CONCAT3(json_object_, jtype, _to_json_string))
static inline struct json_object *json_object_new(enum json_type o_type, size_t alloc_size,
json_object_to_json_string_fn *to_json_string);
static void json_object_object_delete(struct json_object *jso_base);
static void json_object_string_delete(struct json_object *jso);
static void json_object_array_delete(struct json_object *jso);
static json_object_to_json_string_fn json_object_object_to_json_string;
static json_object_to_json_string_fn json_object_boolean_to_json_string;
static json_object_to_json_string_fn json_object_double_to_json_string_default;
static json_object_to_json_string_fn json_object_int_to_json_string;
static json_object_to_json_string_fn json_object_string_to_json_string;
static json_object_to_json_string_fn json_object_array_to_json_string;
static json_object_to_json_string_fn _json_object_userdata_to_json_string;
#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
/**
* Abort and optionally print a message on standard error.
* This should be used rather than assert() for unconditional abortion
* (in particular for code paths which are never supposed to be run).
* */
JSON_NORETURN static void json_abort(const char *message);
/* helper for accessing the optimized string data component in json_object
*/
static inline char *get_string_component_mutable(struct json_object *jso)
{
if (JC_STRING_C(jso)->len < 0)
{
/* Due to json_object_set_string(), we might have a pointer */
return JC_STRING(jso)->c_string.pdata;
}
return JC_STRING(jso)->c_string.idata;
}
static inline const char *get_string_component(const struct json_object *jso)
{
return get_string_component_mutable((void *)(uintptr_t)(const void *)jso);
}
/* string escaping */
static int json_escape_str(struct printbuf *pb, const char *str, size_t len, int flags)
{
size_t pos = 0, start_offset = 0;
unsigned char c;
while (len)
{
--len;
c = str[pos];
switch (c)
{
case '\b':
case '\n':
case '\r':
case '\t':
case '\f':
case '"':
case '\\':
case '/':
if ((flags & JSON_C_TO_STRING_NOSLASHESCAPE) && c == '/')
{
pos++;
break;
}
if (pos > start_offset)
printbuf_memappend(pb, str + start_offset, pos - start_offset);
if (c == '\b')
printbuf_memappend(pb, "\\b", 2);
else if (c == '\n')
printbuf_memappend(pb, "\\n", 2);
else if (c == '\r')
printbuf_memappend(pb, "\\r", 2);
else if (c == '\t')
printbuf_memappend(pb, "\\t", 2);
else if (c == '\f')
printbuf_memappend(pb, "\\f", 2);
else if (c == '"')
printbuf_memappend(pb, "\\\"", 2);
else if (c == '\\')
printbuf_memappend(pb, "\\\\", 2);
else if (c == '/')
printbuf_memappend(pb, "\\/", 2);
start_offset = ++pos;
break;
default:
if (c < ' ')
{
char sbuf[7];
if (pos > start_offset)
printbuf_memappend(pb, str + start_offset,
pos - start_offset);
snprintf(sbuf, sizeof(sbuf), "\\u00%c%c", json_hex_chars[c >> 4],
json_hex_chars[c & 0xf]);
printbuf_memappend_fast(pb, sbuf, (int)sizeof(sbuf) - 1);
start_offset = ++pos;
}
else
pos++;
}
}
if (pos > start_offset)
printbuf_memappend(pb, str + start_offset, pos - start_offset);
return 0;
}
/* reference counting */
struct json_object *json_object_get(struct json_object *jso)
{
if (!jso)
return jso;
// Don't overflow the refcounter.
assert(jso->_ref_count < UINT32_MAX);
#if defined(HAVE_ATOMIC_BUILTINS) && defined(ENABLE_THREADING)
__sync_add_and_fetch(&jso->_ref_count, 1);
#else
++jso->_ref_count;
#endif
return jso;
}
/**
* Internal json_object_put function
* Returns 0 if we're done "freeing" the object, either because its memory
* was actually released, or we just needed to decrement the refcount.
* Returns 1 when the object is a non-empty container that still needs to be handled.
*/
static inline int _json_object_put_maybe_free(struct json_object *jso, int free_containers)
{
/* Avoid invalid free and crash explicitly instead of (silently)
* segfaulting.
*/
assert(jso->_ref_count > 0);
#if defined(HAVE_ATOMIC_BUILTINS) && defined(ENABLE_THREADING)
/* Note: this only allow the refcount to remain correct
* when multiple threads are adjusting it. It is still an error
* for a thread to decrement the refcount if it doesn't "own" it,
* as that can result in the thread that loses the race to 0
* operating on an already-freed object.
*/
if (__sync_sub_and_fetch(&jso->_ref_count, 1) > 0)
#else
if (--jso->_ref_count > 0)
#endif
{
return 0; // All done, caller doesn't need to do anything else
}
if (jso->_user_delete)
jso->_user_delete(jso, jso->_userdata);
switch (jso->o_type)
{
case json_type_object:
if (free_containers || lh_table_length(JC_OBJECT(jso)->c_object) == 0)
{
json_object_object_delete(jso);
break;
}
return 1;
case json_type_array:
// container objects are handled by the caller
if (free_containers || array_list_length(JC_ARRAY(jso)->c_array) == 0)
{
json_object_array_delete(jso);
break;
}
return 1;
case json_type_string:
json_object_string_delete(jso);
break;
default:
json_object_generic_delete(jso);
break;
}
return 0; // All done, caller doesn't need to do anything else
}
int json_object_put(struct json_object *jso)
{
if (!jso)
return 0;
if (_json_object_put_maybe_free(jso, 0) == 0)
return 0;
// else, it's a non-empty container object, handle it below
// Note: jso is now a "zombie" object, _ref_count == 0 but memory not yet released
/*
* Handle container objects with minimal stack usage.
* Perform depth-first iteration, decrementing ref counts on way down
* and freeing actual memory on the way up.
* Iterate backwards through each container so we can use the tail
* pointer/array length to know where to pick up upon popping up to
* the parent.
*/
while(jso != NULL)
{
size_t total_slots;
size_t slots_left;
struct lh_entry *cur_entry = NULL;
int retry_main_loop = 0;
if (jso->o_type == json_type_object)
{
total_slots = lh_table_length(JC_OBJECT(jso)->c_object);
cur_entry = JC_OBJECT(jso)->c_object->tail;
}
else
{
total_slots = array_list_length(JC_ARRAY(jso)->c_array);
}
slots_left = total_slots;
while (slots_left > 0)
{
size_t cur_slot = slots_left - 1;
json_object *child = NULL;
// First, clear the slot in the current jso object
// The slot itself will be freed when jso is freed, or
// if the child object in the slot is a container too and
// and we "recurse" into it.
switch (jso->o_type)
{
case json_type_object:
child = (json_object *)lh_entry_v(cur_entry);
// We're going to free child, so detach it from the entry
lh_entry_set_val(cur_entry, NULL);
break;
case json_type_array:
child = (struct json_object *)array_list_get_idx(JC_ARRAY(jso)->c_array, cur_slot);
// We're going to free child, so detach it from the entry
array_list_set_idx(JC_ARRAY(jso)->c_array, cur_slot, NULL);
break;
default:
assert(!"jso->o_type is not object or array");
break;
}
// Now, handle actually freeing the json_object in that slot
if (!child || _json_object_put_maybe_free(child, 0) == 0)
{
// child is either freed, or still referenced somewhere else
// leave it as-is and handle the previous slot
slots_left--;
if (jso->o_type == json_type_object)
cur_entry = cur_entry->prev;
continue;
}
// _ref_count == 0 now, and _user_delete has been called so we can re-use _userdata
child->_delete_parent = jso; // aka _userdata
child->_user_delete = NULL; // make sure it's not called again
// Clear the slot entries whose json_object have been freed so when we pop
// back up to this jso we can continue where we left off.
// Note: since we set each entry to NULL above, clearing the slot
// is a noop wrt releasing a json_object.
if (jso->o_type == json_type_object)
{
lh_table_delete_entry_to_tail(JC_OBJECT(jso)->c_object, cur_entry);
}
else // json_type_array
{
array_list_del_idx(JC_ARRAY(jso)->c_array, cur_slot, total_slots - cur_slot);
}
// Iterate down through the child, it will be freed once all
// of *its* children are freed
jso = child;
retry_main_loop = 1;
break;
}
if (retry_main_loop)
// Iterating down, don't free jso yet
continue;
// All slots are cleared, now pop back up to the parent
{
json_object *parent = jso->_delete_parent;
// jso is a child that's already been detached from its parent
// so we need to actually free it now
assert(jso->_ref_count == 0);
jso->_ref_count++; // We're the exclusive owner of jso, non-atomic add is ok.
assert(_json_object_put_maybe_free(jso, 1) == 0);
jso = parent;
// iteration will be reset at the top of the loop
}
}
return 1;
}
/* generic object construction and destruction parts */
static void json_object_generic_delete(struct json_object *jso)
{
printbuf_free(jso->_pb);
free(jso);
}
static inline struct json_object *json_object_new(enum json_type o_type, size_t alloc_size,
json_object_to_json_string_fn *to_json_string)
{
struct json_object *jso;
jso = (struct json_object *)malloc(alloc_size);
if (!jso)
return NULL;
jso->o_type = o_type;
jso->_ref_count = 1;
jso->_to_json_string = to_json_string;
jso->_pb = NULL;
jso->_user_delete = NULL;
jso->_userdata = NULL;
//jso->... // Type-specific fields must be set by caller
return jso;
}
/* type checking functions */
int json_object_is_type(const struct json_object *jso, enum json_type type)
{
if (!jso)
return (type == json_type_null);
return (jso->o_type == type);
}
enum json_type json_object_get_type(const struct json_object *jso)
{
if (!jso)
return json_type_null;
return jso->o_type;
}
void *json_object_get_userdata(json_object *jso)
{
return jso ? jso->_userdata : NULL;
}
void json_object_set_userdata(json_object *jso, void *userdata, json_object_delete_fn *user_delete)
{
// Can't return failure, so abort if we can't perform the operation.
assert(jso != NULL);
// First, clean up any previously existing user info
if (jso->_user_delete)
jso->_user_delete(jso, jso->_userdata);
jso->_userdata = userdata;
jso->_user_delete = user_delete;
}
/* set a custom conversion to string */
void json_object_set_serializer(json_object *jso, json_object_to_json_string_fn *to_string_func,
void *userdata, json_object_delete_fn *user_delete)
{
json_object_set_userdata(jso, userdata, user_delete);
if (to_string_func == NULL)
{
// Reset to the standard serialization function
switch (jso->o_type)
{
case json_type_null: jso->_to_json_string = NULL; break;
case json_type_boolean:
jso->_to_json_string = &json_object_boolean_to_json_string;
break;
case json_type_double:
jso->_to_json_string = &json_object_double_to_json_string_default;
break;
case json_type_int: jso->_to_json_string = &json_object_int_to_json_string; break;
case json_type_object:
jso->_to_json_string = &json_object_object_to_json_string;
break;
case json_type_array:
jso->_to_json_string = &json_object_array_to_json_string;
break;
case json_type_string:
jso->_to_json_string = &json_object_string_to_json_string;
break;
}
return;
}
jso->_to_json_string = to_string_func;
}
/* extended conversion to string */
const char *json_object_to_json_string_length(struct json_object *jso, int flags, size_t *length)
{
const char *r = NULL;
size_t s = 0;
if (!jso)
{
s = 4;
r = "null";
}
else if ((jso->_pb) || (jso->_pb = printbuf_new()))
{
printbuf_reset(jso->_pb);
if (jso->_to_json_string(jso, jso->_pb, 0, flags) >= 0)
{
s = (size_t)jso->_pb->bpos;
r = jso->_pb->buf;
}
}
if (length)
*length = s;
return r;
}
const char *json_object_to_json_string_ext(struct json_object *jso, int flags)
{
return json_object_to_json_string_length(jso, flags, NULL);
}
/* backwards-compatible conversion to string */
const char *json_object_to_json_string(struct json_object *jso)
{
return json_object_to_json_string_ext(jso, JSON_C_TO_STRING_SPACED);
}
static void indent(struct printbuf *pb, int level, int flags)
{
if (flags & JSON_C_TO_STRING_PRETTY)
{
if (flags & JSON_C_TO_STRING_PRETTY_TAB)
{
printbuf_memset(pb, -1, '\t', level);
}
else
{
printbuf_memset(pb, -1, ' ', level * 2);
}
}
}
/* json_object_object */
static int json_object_object_to_json_string(struct json_object *jso, struct printbuf *pb,
int level, int flags)
{
int had_children = 0;
struct json_object_iter iter;
printbuf_strappend(pb, "{" /*}*/);
json_object_object_foreachC(jso, iter)
{
if (had_children)
{
printbuf_strappend(pb, ",");
}
if (flags & JSON_C_TO_STRING_PRETTY)
printbuf_strappend(pb, "\n");
had_children = 1;
if (flags & JSON_C_TO_STRING_SPACED && !(flags & JSON_C_TO_STRING_PRETTY))
printbuf_strappend(pb, " ");
indent(pb, level + 1, flags);
if (flags & JSON_C_TO_STRING_COLOR)
printbuf_strappend(pb, ANSI_COLOR_FG_BLUE);
printbuf_strappend(pb, "\"");
json_escape_str(pb, iter.key, strlen(iter.key), flags);
printbuf_strappend(pb, "\"");
if (flags & JSON_C_TO_STRING_COLOR)
printbuf_strappend(pb, ANSI_COLOR_RESET);
if (flags & JSON_C_TO_STRING_SPACED)
printbuf_strappend(pb, ": ");
else
printbuf_strappend(pb, ":");
if (iter.val == NULL) {
if (flags & JSON_C_TO_STRING_COLOR)
printbuf_strappend(pb, ANSI_COLOR_FG_MAGENTA);
printbuf_strappend(pb, "null");
if (flags & JSON_C_TO_STRING_COLOR)
printbuf_strappend(pb, ANSI_COLOR_RESET);
} else if (iter.val->_to_json_string(iter.val, pb, level + 1, flags) < 0)
return -1;
}
if ((flags & JSON_C_TO_STRING_PRETTY) && had_children)
{
printbuf_strappend(pb, "\n");
indent(pb, level, flags);
}
if (flags & JSON_C_TO_STRING_SPACED && !(flags & JSON_C_TO_STRING_PRETTY))
return printbuf_strappend(pb, /*{*/ " }");
else
return printbuf_strappend(pb, /*{*/ "}");
}
static void json_object_lh_entry_free(struct lh_entry *ent)
{
struct json_object *jso = (struct json_object *)lh_entry_v(ent);
if (!lh_entry_k_is_constant(ent))
free(lh_entry_k(ent));
if (jso) // micro-opt, skip func call on null object
json_object_put(jso);
}
static void json_object_object_delete(struct json_object *jso_base)
{
lh_table_free(JC_OBJECT(jso_base)->c_object);
json_object_generic_delete(jso_base);
}
struct json_object *json_object_new_object(void)
{
struct json_object_object *jso = JSON_OBJECT_NEW(object);
if (!jso)
return NULL;
jso->c_object =
lh_kchar_table_new(JSON_OBJECT_DEF_HASH_ENTRIES, &json_object_lh_entry_free);
if (!jso->c_object)
{
json_object_generic_delete(&jso->base);
errno = ENOMEM;
return NULL;
}
return &jso->base;
}
struct lh_table *json_object_get_object(const struct json_object *jso)
{
if (!jso)
return NULL;
switch (jso->o_type)
{
case json_type_object: return JC_OBJECT_C(jso)->c_object;
default: return NULL;
}
}
int json_object_object_add_ex(struct json_object *jso, const char *const key,
struct json_object *const val, const unsigned opts)
{
struct json_object *existing_value = NULL;
struct lh_entry *existing_entry;
unsigned long hash;
assert(json_object_get_type(jso) == json_type_object);
// We lookup the entry and replace the value, rather than just deleting
// and re-adding it, so the existing key remains valid.
hash = lh_get_hash(JC_OBJECT(jso)->c_object, (const void *)key);
existing_entry =
(opts & JSON_C_OBJECT_ADD_KEY_IS_NEW)
? NULL
: lh_table_lookup_entry_w_hash(JC_OBJECT(jso)->c_object, (const void *)key, hash);
// The caller must avoid creating loops in the object tree, but do a
// quick check anyway to make sure we're not creating a trivial loop.
if (jso == val)
return -1;
if (!existing_entry)
{
const void *const k =
(opts & JSON_C_OBJECT_ADD_CONSTANT_KEY) ? (const void *)key : strdup(key);
if (k == NULL)
return -1;
return lh_table_insert_w_hash(JC_OBJECT(jso)->c_object, k, val, hash, opts);
}
existing_value = (json_object *)lh_entry_v(existing_entry);
if (existing_value)
json_object_put(existing_value);
lh_entry_set_val(existing_entry, val);
return 0;
}
int json_object_object_add(struct json_object *jso, const char *key, struct json_object *val)
{
return json_object_object_add_ex(jso, key, val, 0);
}
int json_object_object_length(const struct json_object *jso)
{
assert(json_object_get_type(jso) == json_type_object);
return lh_table_length(JC_OBJECT_C(jso)->c_object);
}
size_t json_c_object_sizeof(void)
{
return sizeof(struct json_object);
}
struct json_object *json_object_object_get(const struct json_object *jso, const char *key)
{
struct json_object *result = NULL;
json_object_object_get_ex(jso, key, &result);
return result;
}
json_bool json_object_object_get_ex(const struct json_object *jso, const char *key,
struct json_object **value)
{
if (value != NULL)
*value = NULL;
if (NULL == jso)
return 0;
switch (jso->o_type)
{
case json_type_object:
return lh_table_lookup_ex(JC_OBJECT_C(jso)->c_object, (const void *)key,
(void **)value);
default:
if (value != NULL)
*value = NULL;
return 0;
}
}
void json_object_object_del(struct json_object *jso, const char *key)
{
assert(json_object_get_type(jso) == json_type_object);
lh_table_delete(JC_OBJECT(jso)->c_object, key);
}
/* json_object_boolean */
static int json_object_boolean_to_json_string(struct json_object *jso, struct printbuf *pb,
int level, int flags)
{
int ret;
if (flags & JSON_C_TO_STRING_COLOR)
printbuf_strappend(pb, ANSI_COLOR_FG_MAGENTA);
if (JC_BOOL(jso)->c_boolean)
ret = printbuf_strappend(pb, "true");
else
ret = printbuf_strappend(pb, "false");
if (ret > -1 && flags & JSON_C_TO_STRING_COLOR)
return printbuf_strappend(pb, ANSI_COLOR_RESET);
return ret;
}
struct json_object *json_object_new_boolean(json_bool b)
{
struct json_object_boolean *jso = JSON_OBJECT_NEW(boolean);
if (!jso)
return NULL;
jso->c_boolean = b;
return &jso->base;
}
json_bool json_object_get_boolean(const struct json_object *jso)
{
if (!jso)
return 0;
switch (jso->o_type)
{
case json_type_boolean: return JC_BOOL_C(jso)->c_boolean;
case json_type_int:
switch (JC_INT_C(jso)->cint_type)
{
case json_object_int_type_int64: return (JC_INT_C(jso)->cint.c_int64 != 0);
case json_object_int_type_uint64: return (JC_INT_C(jso)->cint.c_uint64 != 0);
default: json_abort("invalid cint_type");
}
case json_type_double: return (JC_DOUBLE_C(jso)->c_double != 0);
case json_type_string: return (JC_STRING_C(jso)->len != 0);
default: return 0;
}
}
int json_object_set_boolean(struct json_object *jso, json_bool new_value)
{
if (!jso || jso->o_type != json_type_boolean)
return 0;
JC_BOOL(jso)->c_boolean = new_value;
return 1;
}
/* json_object_int */
static int json_object_int_to_json_string(struct json_object *jso, struct printbuf *pb, int level,
int flags)
{
/* room for 19 digits, the sign char, and a null term */
char sbuf[21];
if (JC_INT(jso)->cint_type == json_object_int_type_int64)
snprintf(sbuf, sizeof(sbuf), "%" PRId64, JC_INT(jso)->cint.c_int64);
else
snprintf(sbuf, sizeof(sbuf), "%" PRIu64, JC_INT(jso)->cint.c_uint64);
return printbuf_memappend(pb, sbuf, strlen(sbuf));
}
struct json_object *json_object_new_int(int32_t i)
{
return json_object_new_int64(i);
}
int32_t json_object_get_int(const struct json_object *jso)
{
int64_t cint64 = 0;
double cdouble;
enum json_type o_type;
errno = 0;
if (!jso)
return 0;
o_type = jso->o_type;
if (o_type == json_type_int)
{
const struct json_object_int *jsoint = JC_INT_C(jso);
if (jsoint->cint_type == json_object_int_type_int64)
{
cint64 = jsoint->cint.c_int64;
}
else
{
if (jsoint->cint.c_uint64 >= INT64_MAX)
cint64 = INT64_MAX;
else
cint64 = (int64_t)jsoint->cint.c_uint64;
}
}
else if (o_type == json_type_string)
{
/*
* Parse strings into 64-bit numbers, then use the
* 64-to-32-bit number handling below.
*/
if (json_parse_int64(get_string_component(jso), &cint64) != 0)
return 0; /* whoops, it didn't work. */
o_type = json_type_int;
}
switch (o_type)
{
case json_type_int:
/* Make sure we return the correct values for out of range numbers. */
if (cint64 < INT32_MIN)
{
errno = ERANGE;
return INT32_MIN;
}
if (cint64 > INT32_MAX)
{
errno = ERANGE;
return INT32_MAX;
}
return (int32_t)cint64;
case json_type_double:
cdouble = JC_DOUBLE_C(jso)->c_double;
if (cdouble < INT32_MIN)
{
errno = ERANGE;
return INT32_MIN;
}
if (cdouble > INT32_MAX)
{
errno = ERANGE;
return INT32_MAX;
}
if (isnan(cdouble))
{
errno = EINVAL;
return INT32_MIN;
}
return (int32_t)cdouble;
case json_type_boolean: return JC_BOOL_C(jso)->c_boolean;
default: return 0;
}
}
int json_object_set_int(struct json_object *jso, int new_value)
{
return json_object_set_int64(jso, (int64_t)new_value);
}
struct json_object *json_object_new_int64(int64_t i)
{
struct json_object_int *jso = JSON_OBJECT_NEW(int);
if (!jso)
return NULL;
jso->cint.c_int64 = i;
jso->cint_type = json_object_int_type_int64;
return &jso->base;
}
struct json_object *json_object_new_uint64(uint64_t i)
{
struct json_object_int *jso = JSON_OBJECT_NEW(int);
if (!jso)
return NULL;
jso->cint.c_uint64 = i;
jso->cint_type = json_object_int_type_uint64;
return &jso->base;
}
int64_t json_object_get_int64(const struct json_object *jso)
{
int64_t cint;
errno = 0;
if (!jso)
return 0;
switch (jso->o_type)
{
case json_type_int:
{
const struct json_object_int *jsoint = JC_INT_C(jso);
switch (jsoint->cint_type)
{
case json_object_int_type_int64: return jsoint->cint.c_int64;
case json_object_int_type_uint64:
if (jsoint->cint.c_uint64 > INT64_MAX)
{
errno = ERANGE;
return INT64_MAX;
}
return (int64_t)jsoint->cint.c_uint64;
default: json_abort("invalid cint_type");
}
}
case json_type_double:
// INT64_MAX can't be exactly represented as a double
// so cast to tell the compiler it's ok to round up.
if (JC_DOUBLE_C(jso)->c_double > (double)INT64_MAX)
{
errno = ERANGE;
return INT64_MAX;
}
if (JC_DOUBLE_C(jso)->c_double < (double)INT64_MIN)
{
errno = ERANGE;
return INT64_MIN;
}
if (isnan(JC_DOUBLE_C(jso)->c_double))
{
errno = EINVAL;
return INT64_MIN;
}
return (int64_t)JC_DOUBLE_C(jso)->c_double;
case json_type_boolean: return JC_BOOL_C(jso)->c_boolean;
case json_type_string:
if (json_parse_int64(get_string_component(jso), &cint) == 0)
return cint;
/* FALLTHRU */
default: return 0;
}
}
uint64_t json_object_get_uint64(const struct json_object *jso)
{
uint64_t cuint;
errno = 0;
if (!jso)
return 0;
switch (jso->o_type)
{
case json_type_int:
{
const struct json_object_int *jsoint = JC_INT_C(jso);
switch (jsoint->cint_type)
{
case json_object_int_type_int64:
if (jsoint->cint.c_int64 < 0)
{
errno = ERANGE;
return 0;
}
return (uint64_t)jsoint->cint.c_int64;
case json_object_int_type_uint64: return jsoint->cint.c_uint64;
default: json_abort("invalid cint_type");
}
}
case json_type_double:
// UINT64_MAX can't be exactly represented as a double
// so cast to tell the compiler it's ok to round up.
if (JC_DOUBLE_C(jso)->c_double > (double)UINT64_MAX)
{
errno = ERANGE;
return UINT64_MAX;
}
if (JC_DOUBLE_C(jso)->c_double < 0)
{
errno = ERANGE;
return 0;
}
if (isnan(JC_DOUBLE_C(jso)->c_double))
{
errno = EINVAL;
return 0;
}
return (uint64_t)JC_DOUBLE_C(jso)->c_double;
case json_type_boolean: return JC_BOOL_C(jso)->c_boolean;
case json_type_string:
if (json_parse_uint64(get_string_component(jso), &cuint) == 0)
return cuint;
/* FALLTHRU */
default: return 0;
}
}
int json_object_set_int64(struct json_object *jso, int64_t new_value)
{
if (!jso || jso->o_type != json_type_int)
return 0;
JC_INT(jso)->cint.c_int64 = new_value;
JC_INT(jso)->cint_type = json_object_int_type_int64;
return 1;
}
int json_object_set_uint64(struct json_object *jso, uint64_t new_value)
{
if (!jso || jso->o_type != json_type_int)
return 0;
JC_INT(jso)->cint.c_uint64 = new_value;
JC_INT(jso)->cint_type = json_object_int_type_uint64;
return 1;
}
int json_object_int_inc(struct json_object *jso, int64_t val)
{
struct json_object_int *jsoint;
if (!jso || jso->o_type != json_type_int)
return 0;
jsoint = JC_INT(jso);
switch (jsoint->cint_type)
{
case json_object_int_type_int64:
if (val > 0 && jsoint->cint.c_int64 > INT64_MAX - val)
{
jsoint->cint.c_uint64 = (uint64_t)jsoint->cint.c_int64 + (uint64_t)val;
jsoint->cint_type = json_object_int_type_uint64;
}
else if (val < 0 && jsoint->cint.c_int64 < INT64_MIN - val)
{
jsoint->cint.c_int64 = INT64_MIN;
}
else
{
jsoint->cint.c_int64 += val;
}
return 1;
case json_object_int_type_uint64:
if (val > 0 && jsoint->cint.c_uint64 > UINT64_MAX - (uint64_t)val)
{
jsoint->cint.c_uint64 = UINT64_MAX;
}
else if (val < 0 && jsoint->cint.c_uint64 < (uint64_t)(-val))
{
jsoint->cint.c_int64 = (int64_t)jsoint->cint.c_uint64 + val;
jsoint->cint_type = json_object_int_type_int64;
}
else if (val < 0 && jsoint->cint.c_uint64 >= (uint64_t)(-val))
{
jsoint->cint.c_uint64 -= (uint64_t)(-val);
}
else
{
jsoint->cint.c_uint64 += val;
}
return 1;
default: json_abort("invalid cint_type");
}
}
/* json_object_double */
#if defined(HAVE___THREAD)
// i.e. __thread or __declspec(thread)
static SPEC___THREAD char *tls_serialization_float_format = NULL;
#endif
static char *global_serialization_float_format = NULL;
int json_c_set_serialization_double_format(const char *double_format, int global_or_thread)
{
if (global_or_thread == JSON_C_OPTION_GLOBAL)
{
#if defined(HAVE___THREAD)
if (tls_serialization_float_format)
{
free(tls_serialization_float_format);
tls_serialization_float_format = NULL;
}
#endif
if (global_serialization_float_format)
free(global_serialization_float_format);
if (double_format)
{
char *p = strdup(double_format);
if (p == NULL)
{
_json_c_set_last_err("json_c_set_serialization_double_format: "
"out of memory\n");
return -1;
}
global_serialization_float_format = p;
}
else
{
global_serialization_float_format = NULL;
}
}
else if (global_or_thread == JSON_C_OPTION_THREAD)
{
#if defined(HAVE___THREAD)
if (tls_serialization_float_format)
{
free(tls_serialization_float_format);
tls_serialization_float_format = NULL;
}
if (double_format)
{
char *p = strdup(double_format);
if (p == NULL)
{
_json_c_set_last_err("json_c_set_serialization_double_format: "
"out of memory\n");
return -1;
}
tls_serialization_float_format = p;
}
else
{
tls_serialization_float_format = NULL;
}
#else
_json_c_set_last_err("json_c_set_serialization_double_format: not compiled "
"with __thread support\n");
return -1;
#endif
}
else
{
_json_c_set_last_err("json_c_set_serialization_double_format: invalid "
"global_or_thread value: %d\n", global_or_thread);
return -1;
}
return 0;
}
static int json_object_double_to_json_string_format(struct json_object *jso, struct printbuf *pb,
int level, int flags, const char *format)
{
struct json_object_double *jsodbl = JC_DOUBLE(jso);
char buf[128], *p, *q;
int size;
/* Although JSON RFC does not support
* NaN or Infinity as numeric values
* ECMA 262 section 9.8.1 defines
* how to handle these cases as strings
*/
if (isnan(jsodbl->c_double))
{
size = snprintf(buf, sizeof(buf), "NaN");
}
else if (isinf(jsodbl->c_double))
{
if (jsodbl->c_double > 0)
size = snprintf(buf, sizeof(buf), "Infinity");
else
size = snprintf(buf, sizeof(buf), "-Infinity");
}
else
{
const char *std_format = "%.17g";
int format_drops_decimals = 0;
int looks_numeric = 0;
if (!format)
{
#if defined(HAVE___THREAD)
if (tls_serialization_float_format)
format = tls_serialization_float_format;
else
#endif
if (global_serialization_float_format)
format = global_serialization_float_format;
else
format = std_format;
}
size = snprintf(buf, sizeof(buf), format, jsodbl->c_double);
if (size < 0)
return -1;
p = strchr(buf, ',');
if (p)
*p = '.';
else
p = strchr(buf, '.');
if (format == std_format || strstr(format, ".0f") == NULL)
format_drops_decimals = 1;
looks_numeric = /* Looks like *some* kind of number */
is_plain_digit(buf[0]) || (size > 1 && buf[0] == '-' && is_plain_digit(buf[1]));
if (size < (int)sizeof(buf) - 2 && looks_numeric && !p && /* Has no decimal point */
strchr(buf, 'e') == NULL && /* Not scientific notation */
format_drops_decimals)
{
// Ensure it looks like a float, even if snprintf didn't,
// unless a custom format is set to omit the decimal.
strcat(buf, ".0");
size += 2;
}
if (p && (flags & JSON_C_TO_STRING_NOZERO))
{
/* last useful digit, always keep 1 zero */
p++;
for (q = p; *q; q++)
{
if (*q != '0')
p = q;
}
/* drop trailing zeroes */
if (*p != 0)
*(++p) = 0;
size = p - buf;
}
}
// although unlikely, snprintf can fail
if (size < 0)
return -1;
if (size >= (int)sizeof(buf))
// The standard formats are guaranteed not to overrun the buffer,
// but if a custom one happens to do so, just silently truncate.
size = sizeof(buf) - 1;
printbuf_memappend(pb, buf, size);
return size;
}
static int json_object_double_to_json_string_default(struct json_object *jso, struct printbuf *pb,
int level, int flags)
{
return json_object_double_to_json_string_format(jso, pb, level, flags, NULL);
}
int json_object_double_to_json_string(struct json_object *jso, struct printbuf *pb, int level,
int flags)
{
return json_object_double_to_json_string_format(jso, pb, level, flags,
(const char *)jso->_userdata);
}
struct json_object *json_object_new_double(double d)
{
struct json_object_double *jso = JSON_OBJECT_NEW(double);
if (!jso)
return NULL;
jso->base._to_json_string = &json_object_double_to_json_string_default;
jso->c_double = d;
return &jso->base;
}
struct json_object *json_object_new_double_s(double d, const char *ds)
{
char *new_ds;
struct json_object *jso = json_object_new_double(d);
if (!jso)
return NULL;
new_ds = strdup(ds);
if (!new_ds)
{
json_object_generic_delete(jso);
errno = ENOMEM;
return NULL;
}
json_object_set_serializer(jso, _json_object_userdata_to_json_string, new_ds,
json_object_free_userdata);
return jso;
}
/*
* A wrapper around json_object_userdata_to_json_string() used only
* by json_object_new_double_s() just so json_object_set_double() can
* detect when it needs to reset the serializer to the default.
*/
static int _json_object_userdata_to_json_string(struct json_object *jso, struct printbuf *pb,
int level, int flags)
{
return json_object_userdata_to_json_string(jso, pb, level, flags);
}
int json_object_userdata_to_json_string(struct json_object *jso, struct printbuf *pb, int level,
int flags)
{
int userdata_len = strlen((const char *)jso->_userdata);
printbuf_memappend(pb, (const char *)jso->_userdata, userdata_len);
return userdata_len;
}
void json_object_free_userdata(struct json_object *jso, void *userdata)
{
free(userdata);
}
double json_object_get_double(const struct json_object *jso)
{
double cdouble;
char *errPtr = NULL;
if (!jso)
return 0.0;
switch (jso->o_type)
{
case json_type_double: return JC_DOUBLE_C(jso)->c_double;
case json_type_int:
switch (JC_INT_C(jso)->cint_type)
{
case json_object_int_type_int64: return JC_INT_C(jso)->cint.c_int64;
case json_object_int_type_uint64: return JC_INT_C(jso)->cint.c_uint64;
default: json_abort("invalid cint_type");
}
case json_type_boolean: return JC_BOOL_C(jso)->c_boolean;
case json_type_string:
{
const char *cstr = get_string_component(jso);
const char *parse = cstr;
char *radixconv = NULL;
#ifdef HAVE_LOCALE_H
/* A json_type_string holds the value with a '.' radix, as it
* appears in JSON, but strtod() honours the current locale. In a
* locale whose decimal point is not '.' the '.' is treated as a
* stray character, so e.g. "19.95" is read as 0. Parse a copy
* with the radix translated so the value comes back unchanged. */
const char *decimal_point = localeconv()->decimal_point;
if (decimal_point && decimal_point[0] != '.' && decimal_point[1] == '\0')
{
const char *dot = strchr(cstr, '.');
if (dot)
{
size_t slen = strlen(cstr);
radixconv = (char *)malloc(slen + 1);
if (radixconv == NULL)
{
errno = ENOMEM;
return 0.0;
}
memcpy(radixconv, cstr, slen + 1);
radixconv[dot - cstr] = decimal_point[0];
parse = radixconv;
}
}
#endif
errno = 0;
cdouble = strtod(parse, &errPtr);
/* if conversion stopped at the first character, return 0.0 */
if (errPtr == parse)
{
free(radixconv);
errno = EINVAL;
return 0.0;
}
/*
* Check that the conversion terminated on something sensible
*
* For example, { "pay" : 123AB } would parse as 123.
*/
if (*errPtr != '\0')
{
free(radixconv);
errno = EINVAL;
return 0.0;
}
/*
* If strtod encounters a string which would exceed the
* capacity of a double, it returns +/- HUGE_VAL and sets
* errno to ERANGE. But +/- HUGE_VAL is also a valid result
* from a conversion, so we need to check errno.
*
* Underflow also sets errno to ERANGE, but it returns 0 in
* that case, which is what we will return anyway.
*
* See CERT guideline ERR30-C
*/
if ((HUGE_VAL == cdouble || -HUGE_VAL == cdouble) && (ERANGE == errno))
cdouble = 0.0;
free(radixconv);
return cdouble;
}
default: errno = EINVAL; return 0.0;
}
}
int json_object_set_double(struct json_object *jso, double new_value)
{
if (!jso || jso->o_type != json_type_double)
return 0;
JC_DOUBLE(jso)->c_double = new_value;
if (jso->_to_json_string == &_json_object_userdata_to_json_string)
json_object_set_serializer(jso, NULL, NULL, NULL);
return 1;
}
/* json_object_string */
static int json_object_string_to_json_string(struct json_object *jso, struct printbuf *pb,
int level, int flags)
{
ssize_t len = JC_STRING(jso)->len;
if (flags & JSON_C_TO_STRING_COLOR)
printbuf_strappend(pb, ANSI_COLOR_FG_GREEN);
printbuf_strappend(pb, "\"");
json_escape_str(pb, get_string_component(jso), len < 0 ? -(ssize_t)len : len, flags);
printbuf_strappend(pb, "\"");
if (flags & JSON_C_TO_STRING_COLOR)
printbuf_strappend(pb, ANSI_COLOR_RESET);
return 0;
}
static void json_object_string_delete(struct json_object *jso)
{
if (JC_STRING(jso)->len < 0)
free(JC_STRING(jso)->c_string.pdata);
json_object_generic_delete(jso);
}
static struct json_object *_json_object_new_string(const char *s, const size_t len)
{
size_t objsize;
struct json_object_string *jso;
/*
* Structures Actual memory layout
* ------------------- --------------------
* [json_object_string [json_object_string
* [json_object] [json_object]
* ...other fields... ...other fields...
* c_string] len
* bytes
* of
* string
* data
* \0]
*/
if (len > (SSIZE_T_MAX - (sizeof(*jso) - sizeof(jso->c_string)) - 1))
return NULL;
objsize = (sizeof(*jso) - sizeof(jso->c_string)) + len + 1;
if (len < sizeof(void *))
// We need a minimum size to support json_object_set_string() mutability
// so we can stuff a pointer into pdata :(
objsize += sizeof(void *) - len;
jso = (struct json_object_string *)json_object_new(json_type_string, objsize,
&json_object_string_to_json_string);
if (!jso)
return NULL;
jso->len = len;
memcpy(jso->c_string.idata, s, len);
// Cast below needed for Clang UB sanitizer
((char *)jso->c_string.idata)[len] = '\0';
return &jso->base;
}
struct json_object *json_object_new_string(const char *s)
{
return _json_object_new_string(s, strlen(s));
}
struct json_object *json_object_new_string_len(const char *s, const int len)
{
return _json_object_new_string(s, len);
}
const char *json_object_get_string(struct json_object *jso)
{
if (!jso)
return NULL;
switch (jso->o_type)
{
case json_type_string: return get_string_component(jso);
default: return json_object_to_json_string(jso);
}
}
static inline ssize_t _json_object_get_string_len(const struct json_object_string *jso)
{
ssize_t len;
len = jso->len;
return (len < 0) ? -(ssize_t)len : len;
}
int json_object_get_string_len(const struct json_object *jso)
{
if (!jso)
return 0;
switch (jso->o_type)
{
case json_type_string: return _json_object_get_string_len(JC_STRING_C(jso));
default: return 0;
}
}
static int _json_object_set_string_len(json_object *jso, const char *s, size_t len)
{
char *dstbuf;
ssize_t curlen;
ssize_t newlen;
if (jso == NULL || jso->o_type != json_type_string)
return 0;
if (len >= INT_MAX - 1)
// jso->len is a signed ssize_t, so it can't hold the
// full size_t range. json_object_get_string_len returns
// length as int, cap length at INT_MAX.
return 0;
curlen = JC_STRING(jso)->len;
if (curlen < 0) {
if (len == 0) {
free(JC_STRING(jso)->c_string.pdata);
JC_STRING(jso)->len = curlen = 0;
} else {
curlen = -curlen;
}
}
newlen = len;
dstbuf = get_string_component_mutable(jso);
if ((ssize_t)len > curlen)
{
// We have no way to return the new ptr from realloc(jso, newlen)
// and we have no way of knowing whether there's extra room available
// so we need to stuff a pointer in to pdata :(
dstbuf = (char *)malloc(len + 1);
if (dstbuf == NULL)
return 0;
if (JC_STRING(jso)->len < 0)
free(JC_STRING(jso)->c_string.pdata);
JC_STRING(jso)->c_string.pdata = dstbuf;
newlen = -(ssize_t)len;
}
else if (JC_STRING(jso)->len < 0)
{
// We've got enough room in the separate allocated buffer,
// so use it as-is and continue to indicate that pdata is used.
newlen = -(ssize_t)len;
}
memcpy(dstbuf, (const void *)s, len);
dstbuf[len] = '\0';
JC_STRING(jso)->len = newlen;
return 1;
}
int json_object_set_string(json_object *jso, const char *s)
{
return _json_object_set_string_len(jso, s, strlen(s));
}
int json_object_set_string_len(json_object *jso, const char *s, int len)
{
return _json_object_set_string_len(jso, s, len);
}
/* json_object_array */
static int json_object_array_to_json_string(struct json_object *jso, struct printbuf *pb, int level,
int flags)
{
int had_children = 0;
size_t ii;
printbuf_strappend(pb, "[");
for (ii = 0; ii < json_object_array_length(jso); ii++)
{
struct json_object *val;
if (had_children)
{
printbuf_strappend(pb, ",");
}
if (flags & JSON_C_TO_STRING_PRETTY)
printbuf_strappend(pb, "\n");
had_children = 1;
if (flags & JSON_C_TO_STRING_SPACED && !(flags & JSON_C_TO_STRING_PRETTY))
printbuf_strappend(pb, " ");
indent(pb, level + 1, flags);
val = json_object_array_get_idx(jso, ii);
if (val == NULL) {
if (flags & JSON_C_TO_STRING_COLOR)
printbuf_strappend(pb, ANSI_COLOR_FG_MAGENTA);
printbuf_strappend(pb, "null");
if (flags & JSON_C_TO_STRING_COLOR)
printbuf_strappend(pb, ANSI_COLOR_RESET);
} else if (val->_to_json_string(val, pb, level + 1, flags) < 0)
return -1;
}
if ((flags & JSON_C_TO_STRING_PRETTY) && had_children)
{
printbuf_strappend(pb, "\n");
indent(pb, level, flags);
}
if (flags & JSON_C_TO_STRING_SPACED && !(flags & JSON_C_TO_STRING_PRETTY))
return printbuf_strappend(pb, " ]");
return printbuf_strappend(pb, "]");
}
static void json_object_array_entry_free(void *data)
{
struct json_object *jso = (struct json_object *)data;
if (jso) // micro-opt, skip func call on null object
json_object_put(jso);
}
static void json_object_array_delete(struct json_object *jso)
{
array_list_free(JC_ARRAY(jso)->c_array);
json_object_generic_delete(jso);
}
struct json_object *json_object_new_array(void)
{
return json_object_new_array_ext(ARRAY_LIST_DEFAULT_SIZE);
}
struct json_object *json_object_new_array_ext(int initial_size)
{
struct json_object_array *jso = JSON_OBJECT_NEW(array);
if (!jso)
return NULL;
jso->c_array = array_list_new2(&json_object_array_entry_free, initial_size);
if (jso->c_array == NULL)
{
free(jso);
return NULL;
}
return &jso->base;
}
struct array_list *json_object_get_array(const struct json_object *jso)
{
if (!jso)
return NULL;
switch (jso->o_type)
{
case json_type_array: return JC_ARRAY_C(jso)->c_array;
default: return NULL;
}
}
void json_object_array_sort(struct json_object *jso, int (*sort_fn)(const void *, const void *))
{
assert(json_object_get_type(jso) == json_type_array);
array_list_sort(JC_ARRAY(jso)->c_array, sort_fn);
}
struct json_object *json_object_array_bsearch(const struct json_object *key,
const struct json_object *jso,
int (*sort_fn)(const void *, const void *))
{
struct json_object **result;
assert(json_object_get_type(jso) == json_type_array);
result = (struct json_object **)array_list_bsearch((const void **)(void *)&key,
JC_ARRAY_C(jso)->c_array, sort_fn);
if (!result)
return NULL;
return *result;
}
size_t json_object_array_length(const struct json_object *jso)
{
assert(json_object_get_type(jso) == json_type_array);
return array_list_length(JC_ARRAY_C(jso)->c_array);
}
int json_object_array_add(struct json_object *jso, struct json_object *val)
{
assert(json_object_get_type(jso) == json_type_array);
return array_list_add(JC_ARRAY(jso)->c_array, val);
}
int json_object_array_insert_idx(struct json_object *jso, size_t idx, struct json_object *val)
{
assert(json_object_get_type(jso) == json_type_array);
return array_list_insert_idx(JC_ARRAY(jso)->c_array, idx, val);
}
int json_object_array_put_idx(struct json_object *jso, size_t idx, struct json_object *val)
{
assert(json_object_get_type(jso) == json_type_array);
return array_list_put_idx(JC_ARRAY(jso)->c_array, idx, val);
}
int json_object_array_del_idx(struct json_object *jso, size_t idx, size_t count)
{
assert(json_object_get_type(jso) == json_type_array);
return array_list_del_idx(JC_ARRAY(jso)->c_array, idx, count);
}
struct json_object *json_object_array_get_idx(const struct json_object *jso, size_t idx)
{
assert(json_object_get_type(jso) == json_type_array);
return (struct json_object *)array_list_get_idx(JC_ARRAY_C(jso)->c_array, idx);
}
static int json_array_equal(struct json_object *jso1, struct json_object *jso2)
{
size_t len, i;
len = json_object_array_length(jso1);
if (len != json_object_array_length(jso2))
return 0;
for (i = 0; i < len; i++)
{
if (!json_object_equal(json_object_array_get_idx(jso1, i),
json_object_array_get_idx(jso2, i)))
return 0;
}
return 1;
}
int json_object_array_shrink(struct json_object *jso, int empty_slots)
{
if (empty_slots < 0)
json_abort("json_object_array_shrink called with negative empty_slots");
return array_list_shrink(JC_ARRAY(jso)->c_array, empty_slots);
}
struct json_object *json_object_new_null(void)
{
return NULL;
}
static int json_object_all_values_equal(struct json_object *jso1, struct json_object *jso2)
{
struct json_object_iter iter;
struct json_object *sub;
assert(json_object_get_type(jso1) == json_type_object);
assert(json_object_get_type(jso2) == json_type_object);
/* Iterate over jso1 keys and see if they exist and are equal in jso2 */
json_object_object_foreachC(jso1, iter)
{
if (!lh_table_lookup_ex(JC_OBJECT(jso2)->c_object, (void *)iter.key,
(void **)(void *)&sub))
return 0;
if (!json_object_equal(iter.val, sub))
return 0;
}
/* Iterate over jso2 keys to see if any exist that are not in jso1 */
json_object_object_foreachC(jso2, iter)
{
if (!lh_table_lookup_ex(JC_OBJECT(jso1)->c_object, (void *)iter.key,
(void **)(void *)&sub))
return 0;
}
return 1;
}
int json_object_equal(struct json_object *jso1, struct json_object *jso2)
{
if (jso1 == jso2)
return 1;
if (!jso1 || !jso2)
return 0;
if (jso1->o_type != jso2->o_type)
return 0;
switch (jso1->o_type)
{
case json_type_boolean: return (JC_BOOL(jso1)->c_boolean == JC_BOOL(jso2)->c_boolean);
case json_type_double: return (JC_DOUBLE(jso1)->c_double == JC_DOUBLE(jso2)->c_double);
case json_type_int:
{
struct json_object_int *int1 = JC_INT(jso1);
struct json_object_int *int2 = JC_INT(jso2);
if (int1->cint_type == json_object_int_type_int64)
{
if (int2->cint_type == json_object_int_type_int64)
return (int1->cint.c_int64 == int2->cint.c_int64);
if (int1->cint.c_int64 < 0)
return 0;
return ((uint64_t)int1->cint.c_int64 == int2->cint.c_uint64);
}
// else jso1 is a uint64
if (int2->cint_type == json_object_int_type_uint64)
return (int1->cint.c_uint64 == int2->cint.c_uint64);
if (int2->cint.c_int64 < 0)
return 0;
return (int1->cint.c_uint64 == (uint64_t)int2->cint.c_int64);
}
case json_type_string:
{
return (_json_object_get_string_len(JC_STRING(jso1)) ==
_json_object_get_string_len(JC_STRING(jso2)) &&
memcmp(get_string_component(jso1), get_string_component(jso2),
_json_object_get_string_len(JC_STRING(jso1))) == 0);
}
case json_type_object: return json_object_all_values_equal(jso1, jso2);
case json_type_array: return json_array_equal(jso1, jso2);
case json_type_null: return 1;
};
return 0;
}
static int json_object_copy_serializer_data(struct json_object *src, struct json_object *dst)
{
if (!src->_userdata && !src->_user_delete)
return 0;
if (dst->_to_json_string == json_object_userdata_to_json_string ||
dst->_to_json_string == _json_object_userdata_to_json_string)
{
char *p;
assert(src->_userdata);
p = strdup(src->_userdata);
if (p == NULL)
{
_json_c_set_last_err("json_object_copy_serializer_data: out of memory\n");
return -1;
}
dst->_userdata = p;
}
// else if ... other supported serializers ...
else
{
_json_c_set_last_err(
"json_object_copy_serializer_data: unable to copy unknown serializer data: "
"%p\n", (void *)dst->_to_json_string);
return -1;
}
dst->_user_delete = src->_user_delete;
return 0;
}
/**
* The default shallow copy implementation. Simply creates a new object of the same
* type but does *not* copy over _userdata nor retain any custom serializer.
* If custom serializers are in use, json_object_deep_copy() must be passed a shallow copy
* implementation that is aware of how to copy them.
*
* This always returns -1 or 1. It will never return 2 since it does not copy the serializer.
*/
int json_c_shallow_copy_default(json_object *src, json_object *parent, const char *key,
size_t index, json_object **dst)
{
switch (src->o_type)
{
case json_type_boolean: *dst = json_object_new_boolean(JC_BOOL(src)->c_boolean); break;
case json_type_double: *dst = json_object_new_double(JC_DOUBLE(src)->c_double); break;
case json_type_int:
switch (JC_INT(src)->cint_type)
{
case json_object_int_type_int64:
*dst = json_object_new_int64(JC_INT(src)->cint.c_int64);
break;
case json_object_int_type_uint64:
*dst = json_object_new_uint64(JC_INT(src)->cint.c_uint64);
break;
default: json_abort("invalid cint_type");
}
break;
case json_type_string:
*dst = json_object_new_string_len(get_string_component(src),
_json_object_get_string_len(JC_STRING(src)));
break;
case json_type_object: *dst = json_object_new_object(); break;
case json_type_array: *dst = json_object_new_array(); break;
default: errno = EINVAL; return -1;
}
if (!*dst)
{
errno = ENOMEM;
return -1;
}
(*dst)->_to_json_string = src->_to_json_string;
// _userdata and _user_delete are copied later
return 1;
}
/*
* The actual guts of json_object_deep_copy(), with a few additional args
* needed so we can keep track of where we are within the object tree.
*
* Note: caller is responsible for freeing *dst if this fails and returns -1.
*/
static int json_object_deep_copy_recursive(struct json_object *src, struct json_object *parent,
const char *key_in_parent, size_t index_in_parent,
struct json_object **dst,
json_c_shallow_copy_fn *shallow_copy)
{
struct json_object_iter iter;
size_t src_array_len, ii;
int shallow_copy_rc = 0;
shallow_copy_rc = shallow_copy(src, parent, key_in_parent, index_in_parent, dst);
/* -1=error, 1=object created ok, 2=userdata set */
if (shallow_copy_rc < 1)
{
errno = EINVAL;
return -1;
}
assert(*dst != NULL);
switch (src->o_type)
{
case json_type_object:
json_object_object_foreachC(src, iter)
{
struct json_object *jso = NULL;
/* This handles the `json_type_null` case */
if (!iter.val)
jso = NULL;
else if (json_object_deep_copy_recursive(iter.val, src, iter.key, UINT_MAX,
&jso, shallow_copy) < 0)
{
json_object_put(jso);
return -1;
}
if (json_object_object_add(*dst, iter.key, jso) < 0)
{
json_object_put(jso);
return -1;
}
}
break;
case json_type_array:
src_array_len = json_object_array_length(src);
for (ii = 0; ii < src_array_len; ii++)
{
struct json_object *jso = NULL;
struct json_object *jso1 = json_object_array_get_idx(src, ii);
/* This handles the `json_type_null` case */
if (!jso1)
jso = NULL;
else if (json_object_deep_copy_recursive(jso1, src, NULL, ii, &jso,
shallow_copy) < 0)
{
json_object_put(jso);
return -1;
}
if (json_object_array_add(*dst, jso) < 0)
{
json_object_put(jso);
return -1;
}
}
break;
default:
break;
/* else, nothing to do, shallow_copy already did. */
}
if (shallow_copy_rc != 2)
return json_object_copy_serializer_data(src, *dst);
return 0;
}
int json_object_deep_copy(struct json_object *src, struct json_object **dst,
json_c_shallow_copy_fn *shallow_copy)
{
int rc;
/* Check if arguments are sane ; *dst must not point to a non-NULL object */
if (!src || !dst || *dst)
{
errno = EINVAL;
return -1;
}
if (shallow_copy == NULL)
shallow_copy = json_c_shallow_copy_default;
rc = json_object_deep_copy_recursive(src, NULL, NULL, UINT_MAX, dst, shallow_copy);
if (rc < 0)
{
json_object_put(*dst);
*dst = NULL;
}
return rc;
}
static void json_abort(const char *message)
{
if (message != NULL)
fprintf(stderr, "json-c aborts with error: %s\n", message);
abort();
}
json-c-0.19/json_object.h 0000644 0001750 0001750 00000130245 15217751164 014012 0 ustar uerh uerh /*
* $Id: json_object.h,v 1.12 2006/01/30 23:07:57 mclark Exp $
*
* Copyright (c) 2004, 2005 Metaparadigm Pte. Ltd.
* Michael Clark
* Copyright (c) 2009 Hewlett-Packard Development Company, L.P.
*
* 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 Core json-c API. Start here, or with json_tokener.h
*/
#ifndef _json_object_h_
#define _json_object_h_
#ifdef __GNUC__
#define JSON_C_CONST_FUNCTION(func) func __attribute__((const))
#else
#define JSON_C_CONST_FUNCTION(func) func
#endif
#include "json_inttypes.h"
#include "json_types.h"
#include "printbuf.h"
#include
#ifdef __cplusplus
extern "C" {
#endif
#define JSON_OBJECT_DEF_HASH_ENTRIES 16
/**
* A flag for the json_object_to_json_string_ext() and
* json_object_to_file_ext() functions which causes the output
* to have no extra whitespace or formatting applied.
*/
#define JSON_C_TO_STRING_PLAIN 0
/**
* A flag for the json_object_to_json_string_ext() and
* json_object_to_file_ext() functions which causes the output to have
* minimal whitespace inserted to make things slightly more readable.
*/
#define JSON_C_TO_STRING_SPACED (1 << 0)
/**
* A flag for the json_object_to_json_string_ext() and
* json_object_to_file_ext() functions which causes
* the output to be formatted.
*
* See the "Two Space Tab" option at https://jsonformatter.curiousconcept.com/
* for an example of the format.
*/
#define JSON_C_TO_STRING_PRETTY (1 << 1)
/**
* A flag for the json_object_to_json_string_ext() and
* json_object_to_file_ext() functions which causes
* the output to be formatted.
*
* Instead of a "Two Space Tab" this gives a single tab character.
*/
#define JSON_C_TO_STRING_PRETTY_TAB (1 << 3)
/**
* A flag to drop trailing zero for float values
*/
#define JSON_C_TO_STRING_NOZERO (1 << 2)
/**
* Don't escape forward slashes.
*/
#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
* causes the value to be added without a check if it already exists.
* Note: it is the responsibility of the caller to ensure that no
* key is added multiple times. If this is done, results are
* unpredictable. While this option is somewhat dangerous, it
* permits potentially large performance savings in code that
* knows for sure the key values are unique (e.g. because the
* code adds a well-known set of constant key values).
*/
#define JSON_C_OBJECT_ADD_KEY_IS_NEW (1 << 1)
/**
* A flag for the json_object_object_add_ex function which
* flags the key as being constant memory. This means that
* the key will NOT be copied via strdup(), resulting in a
* potentially huge performance win (malloc, strdup and
* free are usually performance hogs). It is acceptable to
* use this flag for keys in non-constant memory blocks if
* the caller ensure that the memory holding the key lives
* longer than the corresponding json object. However, this
* is somewhat dangerous and should only be done if really
* justified.
* The general use-case for this flag is cases where the
* key is given as a real constant value in the function
* call, e.g. as in
* json_object_object_add_ex(obj, "ip", json,
* JSON_C_OBJECT_ADD_CONSTANT_KEY);
*/
#define JSON_C_OBJECT_ADD_CONSTANT_KEY (1 << 2)
/**
* This flag is an alias to JSON_C_OBJECT_ADD_CONSTANT_KEY.
* Historically, this flag was used first and the new name
* JSON_C_OBJECT_ADD_CONSTANT_KEY was introduced for version
* 0.16.00 in order to have regular naming.
* 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
* current and future threads that have not set a thread-local value.
*
* @see json_c_set_serialization_double_format
*/
#define JSON_C_OPTION_GLOBAL (0)
/**
* Set a thread-local value of an option, overriding the global value.
* This will fail if json-c is not compiled with threading enabled, and
* with the __thread specifier (or equivalent) available.
*
* @see json_c_set_serialization_double_format
*/
#define JSON_C_OPTION_THREAD (1)
/* reference counting functions */
/**
* Increment the reference count of json_object, thereby taking ownership of it.
*
* 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
* @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);
/**
* 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
* 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
* @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);
/**
* Check if the json_object is of a given type
* @param obj the json_object instance
* @param type one of:
json_type_null (i.e. obj == NULL),
json_type_boolean,
json_type_double,
json_type_int,
json_type_object,
json_type_array,
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);
/**
* Get the type of the json_object. See also json_type_to_name() to turn this
* into a string suitable, for instance, for logging.
*
* @param obj the json_object instance
* @returns type being one of:
json_type_null (i.e. obj == NULL),
json_type_boolean,
json_type_double,
json_type_int,
json_type_object,
json_type_array,
json_type_string
*/
JSON_EXPORT enum json_type json_object_get_type(const struct json_object *obj);
/** Stringify object to json format.
* 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
* have to free it, later use of json_object_put() should be sufficient.
* If you can not ensure there's no concurrent access to *obj use
* strdup().
* @param obj the json_object instance
* @returns a string in JSON format
*/
JSON_EXPORT const char *json_object_to_json_string(struct json_object *obj);
/** Stringify object to json format
* @see json_object_to_json_string() for details on how to free string.
* @param obj the json_object instance
* @param flags formatting options, see JSON_C_TO_STRING_PRETTY and other constants
* @returns a string in JSON format
*/
JSON_EXPORT const char *json_object_to_json_string_ext(struct json_object *obj, int flags);
/** Stringify object to json format
* @see json_object_to_json_string() for details on how to free string.
* @param obj the json_object instance
* @param flags formatting options, see JSON_C_TO_STRING_PRETTY and other constants
* @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
*/
JSON_EXPORT const char *json_object_to_json_string_length(struct json_object *obj, int flags,
size_t *length);
/**
* Returns the userdata set by json_object_set_userdata() or
* json_object_set_serializer()
*
* @param jso the object to return the userdata for
*/
JSON_EXPORT void *json_object_get_userdata(json_object *jso);
/**
* Set an opaque userdata value for an object
*
* The userdata can be retrieved using json_object_get_userdata().
*
* If custom userdata is already set on this object, any existing user_delete
* function is called before the new one is set.
*
* The user_delete parameter is optional and may be passed as NULL, even if
* the userdata parameter is non-NULL. It will be called just before the
* json_object is deleted, after it's reference count goes to zero
* (see json_object_put()).
* If this is not provided, it is up to the caller to free the userdata at
* an appropriate time. (i.e. after the json_object is deleted)
*
* Note: Objects created by parsing strings may have custom serializers set
* which expect the userdata to contain specific data (due to use of
* json_object_new_double_s()). In this case, json_object_set_serialiser() with
* NULL as to_string_func should be used instead to set the userdata and reset
* the serializer to its default value.
*
* @param jso the object to set the userdata for
* @param userdata an optional opaque cookie
* @param user_delete an optional function from freeing userdata
*/
JSON_EXPORT void json_object_set_userdata(json_object *jso, void *userdata,
json_object_delete_fn *user_delete);
/**
* Set a custom serialization function to be used when this particular object
* is converted to a string by json_object_to_json_string.
*
* If custom userdata is already set on this object, any existing user_delete
* function is called before the new one is set.
*
* If to_string_func is NULL the default behaviour is reset (but the userdata
* and user_delete fields are still set).
*
* The userdata parameter is optional and may be passed as NULL. It can be used
* to provide additional data for to_string_func to use. This parameter may
* be NULL even if user_delete is non-NULL.
*
* The user_delete parameter is optional and may be passed as NULL, even if
* the userdata parameter is non-NULL. It will be called just before the
* json_object is deleted, after it's reference count goes to zero
* (see json_object_put()).
* If this is not provided, it is up to the caller to free the userdata at
* an appropriate time. (i.e. after the json_object is deleted)
*
* Note that the userdata is the same as set by json_object_set_userdata(), so
* care must be taken not to overwrite the value when both a custom serializer
* and json_object_set_userdata() are used.
*
* @param jso the object to customize
* @param to_string_func the custom serialization function
* @param userdata an optional opaque cookie
* @param user_delete an optional function from freeing userdata
*/
JSON_EXPORT void json_object_set_serializer(json_object *jso,
json_object_to_json_string_fn *to_string_func,
void *userdata, json_object_delete_fn *user_delete);
#ifdef __clang__
/*
* Clang doesn't pay attention to the parameters defined in the
* function typedefs used here, so turn off spurious doc warnings.
* {
*/
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdocumentation"
#endif
/**
* Simply call free on the userdata pointer.
* Can be used with json_object_set_serializer().
*
* @param jso unused
* @param userdata the pointer that is passed to free().
*/
JSON_EXPORT json_object_delete_fn json_object_free_userdata;
/**
* Copy the jso->_userdata string over to pb as-is.
* Can be used with json_object_set_serializer().
*
* @param jso The object whose _userdata is used.
* @param pb The destination buffer.
* @param level Ignored.
* @param flags Ignored.
*/
JSON_EXPORT json_object_to_json_string_fn json_object_userdata_to_json_string;
#ifdef __clang__
/* } */
#pragma clang diagnostic pop
#endif
/* object type methods */
/** Create a new empty object with a reference count of 1. The caller of
* this object initially has sole ownership. Remember, when using
* json_object_object_add or json_object_array_put_idx, ownership will
* transfer to the object/array. Call json_object_get if you want to maintain
* shared ownership or also add this object as a child of multiple objects or
* arrays. Any ownerships you acquired but did not transfer must be released
* through json_object_put.
*
* @returns a json_object of type json_type_object
*/
JSON_EXPORT struct json_object *json_object_new_object(void);
/** Get the hashtable of a json_object of type json_type_object
* @param obj the json_object instance
* @returns a linkhash
*/
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.
* @param obj the json_object whose length to return
*/
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
*
* The reference count of `val` will *not* be incremented, in effect
* transferring ownership that object to `obj`, and thus `val` will be
* freed when `obj` is. (i.e. through `json_object_put(obj)`)
*
* If you want to retain a reference to the added object, independent
* of the lifetime of obj, you must increment the refcount with
* `json_object_get(val)` (and later release it with json_object_put()).
*
* 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 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
*
* @return On success, 0 is returned.
* On error, a negative value is returned.
*/
JSON_EXPORT int json_object_object_add(struct json_object *obj, const char *key,
struct json_object *val);
/** Add an object field to a json_object of type json_type_object
*
* The semantics are identical to json_object_object_add, except that an
* additional flag fields gives you more control over some detail aspects
* of processing. See the description of JSON_C_OBJECT_ADD_* flags for more
* details.
*
* @param obj the json_object instance
* @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 opts process-modifying options. To specify multiple options, use
* (OPT1|OPT2)
*/
JSON_EXPORT int json_object_object_add_ex(struct json_object *obj, const char *const key,
struct json_object *const val, const unsigned opts);
/** Get the json_object associate with a given object field.
* Deprecated/discouraged: used json_object_object_get_ex instead.
*
* 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
* 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
* reference counts through the json_object_put/json_object_get methods unless
* you need to have the child (value) reference maintain a different lifetime
* than the owning parent (obj). Ownership of the returned value is retained
* by obj (do not do json_object_put unless you have done a json_object_get).
* If you delete the value from obj (json_object_object_del) and wish to access
* the returned reference afterwards, make sure you have first gotten shared
* ownership through json_object_get (& don't forget to do a json_object_put
* or transfer ownership to prevent a memory leak).
*
* @param obj the json_object instance
* @param key the object 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,
const char *key);
/** Get the json_object associated with a given object field.
*
* This returns true if the key is found, false in all other cases (including
* if obj isn't a json_type_object).
*
* *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
* you need to have the child (value) reference maintain a different lifetime
* than the owning parent (obj). Ownership of value is retained by obj.
*
* @param obj the json_object instance
* @param key the object field name
* @param value a pointer where to store a reference to the json_object
* associated with the given field name.
*
* It is safe to pass a NULL value.
* @returns 1 if the key exists, 0 otherwise
*/
JSON_EXPORT int json_object_object_get_ex(const struct json_object *obj, const char *key,
struct json_object **value);
/** Delete the given json_object field
*
* The reference count will be decremented for the deleted object. If there
* are no more owners of the value represented by this key, then the value is
* freed. Otherwise, the reference to the value will remain in memory.
*
* @param obj the json_object instance
* @param key the object field name
*/
JSON_EXPORT void json_object_object_del(struct json_object *obj, const char *key);
/**
* Iterate through all keys and values of an object.
*
* Adding keys to the object while iterating is NOT allowed.
*
* Deleting an existing key, or replacing an existing key with a
* new value IS allowed.
*
* @param obj the json_object instance
* @param key the local name for the char* key variable defined in the body
* @param val the local name for the json_object* object variable defined in
* the body
*/
#if defined(__GNUC__) && !defined(__STRICT_ANSI__) && (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L)
#define json_object_object_foreach(obj, key, val) \
char *key = NULL; \
struct json_object *val __attribute__((__unused__)) = NULL; \
for (struct lh_entry *entry##key = lh_table_head(json_object_get_object(obj)), \
*entry_next##key = NULL; \
({ \
if (entry##key) \
{ \
key = (char *)lh_entry_k(entry##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 */
#define json_object_object_foreach(obj, key, val) \
char *key = NULL; \
struct json_object *val = NULL; \
struct lh_entry *entry##key; \
struct lh_entry *entry_next##key = NULL; \
for (entry##key = lh_table_head(json_object_get_object(obj)); \
(entry##key ? (key = (char *)lh_entry_k(entry##key), \
val = (struct json_object *)lh_entry_v(entry##key), \
entry_next##key = lh_entry_next(entry##key), entry##key) \
: 0); \
entry##key = entry_next##key)
#endif /* defined(__GNUC__) && !defined(__STRICT_ANSI__) && (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) */
/** Iterate through all keys and values of an object (ANSI C Safe)
* @param obj the json_object instance
* @param iter the object iterator, use type json_object_iter
*/
#define json_object_object_foreachC(obj, iter) \
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 = lh_entry_next(iter.entry))
/* Array type methods */
/** 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
*/
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
* @param obj the json_object instance
* @returns an arraylist
*/
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
* @param obj the json_object instance
* @returns the length of the array
*/
JSON_EXPORT size_t json_object_array_length(const struct json_object *obj);
/** Sorts the elements of jso of type json_type_array
*
* Pointers to the json_object pointers will be passed as the two arguments
* to sort_fn
*
* @param jso the json_object instance
* @param sort_fn a sorting function
*/
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.
*
* It depends on your compare function what's sufficient as a key.
* Usually you create some dummy object with the parameter compared in
* it, to identify the right item you're actually looking for.
*
* @see json_object_array_sort() for hints on the compare function.
*
* @param key a dummy json_object with the right key
* @param jso the array object we're searching
* @param sort_fn the sort/compare function
*
* @return the wanted json_object instance
*/
JSON_EXPORT struct json_object *
json_object_array_bsearch(const struct json_object *key, const struct json_object *jso,
int (*sort_fn)(const void *, const void *));
/** Add an element to the end of 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
*
* @param obj the json_object instance
* @param val the json_object to be added
*/
JSON_EXPORT int json_object_array_add(struct json_object *obj, struct json_object *val);
/** Insert or replace 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 reference count of a replaced object will be decremented.
*
* The array size will be automatically be expanded to the size of the
* index if the index is larger than the current size.
*
* @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_put_idx(struct json_object *obj, size_t idx,
struct json_object *val);
/** 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 idx the index to get the element at
* @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,
size_t idx);
/** 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
* 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.
*
* @param obj the json_object instance
* @param idx the index to start deleting elements at
* @param count the number of elements to delete
* @returns 0 if the elements were successfully deleted
*/
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 */
/** Create a new empty json_object of type json_type_boolean
* @param b a json_bool 1 or 0
* @returns a json_object of type json_type_boolean
*/
JSON_EXPORT struct json_object *json_object_new_boolean(json_bool b);
/** 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.
* integer and double objects will return 0 if there value is zero
* or 1 otherwise. If the passed object is a string it will return
* 1 if it has a non zero length.
* 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
* @returns a json_bool
*/
JSON_EXPORT json_bool json_object_get_boolean(const struct json_object *obj);
/** 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
* if it is not without any further actions. If type of obj is json_type_boolean
* 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_boolean(struct json_object *obj, json_bool new_value);
/* int type methods */
/** Create a new empty json_object of type json_type_int
* Note that values are stored as 64-bit values internally.
* To ensure the full range is maintained, use json_object_new_int64 instead.
* @param i the integer
* @returns a json_object of type json_type_int
*/
JSON_EXPORT struct json_object *json_object_new_int(int32_t i);
/** Create a new empty json_object of type json_type_int
* @param i the integer
* @returns a json_object of type json_type_int
*/
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
*
* The type is coerced to a int if the passed object is not a int.
* double objects will return their integer conversion except for NaN values
* which return INT32_MIN and the errno is set to EINVAL.
* Strings will be parsed as an integer. If no conversion exists then 0 is
* returned and errno is set to EINVAL. null is equivalent to 0 (no error values
* set).
* Sets errno to ERANGE if the value exceeds the range of int.
*
* Note that integers are stored internally as 64-bit values.
* If the value of too big or too small to fit into 32-bit, INT32_MAX or
* INT32_MIN are returned, respectively.
*
* @param obj the json_object instance
* @returns an int
*/
JSON_EXPORT int32_t json_object_get_int(const struct json_object *obj);
/** Set the int value of a json_object
*
* 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
* 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_int(struct json_object *obj, int new_value);
/** Increment a json_type_int object by the given amount, which may be negative.
*
* If the type of obj is not json_type_int then 0 is returned with no further
* action taken.
* If the addition would result in a overflow, the object value
* is set to INT64_MAX.
* If the addition would result in a underflow, the object value
* is set to INT64_MIN.
* Neither overflow nor underflow affect the return value.
*
* @param obj the json_object instance
* @param val the value to add
* @returns 1 if the increment succeeded, 0 otherwise
*/
JSON_EXPORT int json_object_int_inc(struct json_object *obj, int64_t val);
/** Get the int value of a json_object
*
* The type is coerced to a int64 if the passed object is not a int64.
* double objects will return their int64 conversion except for NaN values
* which return INT64_MIN and the errno is set to EINVAL.
* Strings will be parsed as an int64. If no conversion exists then 0 is
* returned and errno is set to EINVAL. null is equivalent to 0 (no error values
* set).
* Sets errno to ERANGE if the value exceeds the range of int64.
*
* 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 int64
*/
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 except for NaN values
* which return 0 and the errno is set to EINVAL.
* Strings will be parsed as an uint64. If no conversion exists then 0 is
* returned and errno is set to EINVAL. null is equivalent to 0 (no error values
* set).
* Sets errno to ERANGE if the value exceeds the range of uint64.
*
* 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
*
* 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
* 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_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 */
/** Create a new empty json_object of type json_type_double
*
* @see json_object_double_to_json_string() for how to set a custom format string.
*
* @param d the double
* @returns a json_object of type json_type_double
*/
JSON_EXPORT struct json_object *json_object_new_double(double d);
/**
* Create a new json_object of type json_type_double, using
* the exact serialized representation of the value.
*
* This allows for numbers that would otherwise get displayed
* inefficiently (e.g. 12.3 => "12.300000000000001") to be
* serialized with the more convenient form.
*
* Notes:
*
* This is used by json_tokener_parse_ex() to allow for
* an exact re-serialization of a parsed object.
*
* The userdata field is used to store the string representation, so it
* can't be used for other data if this function is used.
*
* 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
* jso = json_object_new_double(d);
* json_object_set_serializer(jso, json_object_userdata_to_json_string,
* strdup(ds), json_object_free_userdata);
* @endcode
*
* @param d the numeric value of the double.
* @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);
/**
* Set a global or thread-local json-c option, depending on whether
* JSON_C_OPTION_GLOBAL or JSON_C_OPTION_THREAD is passed.
* Thread-local options default to undefined, and inherit from the global
* value, even if the global value is changed after the thread is created.
* Attempting to set thread-local options when threading is not compiled in
* will result in an error. Be sure to check the return value.
*
* double_format is a "%g" printf format, such as "%.20g"
*
* @return -1 on errors, 0 on success.
*/
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.
*
* This function isn't meant to be called directly. Instead, you can set a
* custom format string for the serialization of this double using the
* following call (where "%.17g" actually is the default):
*
* @code
* jso = json_object_new_double(d);
* json_object_set_serializer(jso, json_object_double_to_json_string,
* "%.17g", NULL);
* @endcode
*
* @see printf(3) man page for format strings
*
* @param jso The json_type_double object that is serialized.
* @param pb The destination buffer.
* @param level Ignored.
* @param flags Ignored.
*/
JSON_EXPORT int json_object_double_to_json_string(struct json_object *jso, struct printbuf *pb,
int level, int flags);
/** Get the double floating point value of a json_object
*
* The type is coerced to a double if the passed object is not a double.
* integer objects will return their double conversion. Strings will be
* parsed as a double. If no conversion exists then 0.0 is returned and
* errno is set to EINVAL. null is equivalent to 0 (no error values set)
*
* If the value is too big to fit in a double, then the value is set to
* the closest infinity with errno set to ERANGE. If strings cannot be
* converted to their double value, then EINVAL is set & NaN is returned.
*
* Arrays of length 0 are interpreted as 0 (with no error flags set).
* Arrays of length 1 are effectively cast to the equivalent object and
* converted using the above rules. All other arrays set the error to
* EINVAL & return NaN.
*
* 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 a double floating point number
*/
JSON_EXPORT double json_object_get_double(const struct json_object *obj);
/** Set the double value of a json_object
*
* 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
* 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 new_value the value to be set
* @returns 1 if value is set correctly, 0 otherwise
*/
JSON_EXPORT int json_object_set_double(struct json_object *obj, double new_value);
/* string type methods */
/** Create a new empty json_object of type json_type_string
*
* A copy of the string is made and the memory is managed by the json_object
*
* @param s the 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);
/** 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
*
* If the passed object is of type json_type_null (i.e. obj == NULL),
* NULL is returned.
*
* If the passed object of type json_type_string, the string contents
* are returned.
*
* Otherwise the JSON representation of the object is returned.
*
* The returned string memory is managed by the json_object and will
* be freed when the reference count of the json_object drops to zero.
*
* @param obj the json_object instance
* @returns a string or NULL
*/
JSON_EXPORT const char *json_object_get_string(struct json_object *obj);
/** Get the string length of a json_object
*
* If the passed object is not of type json_type_string then zero
* will be returned.
*
* @param obj the json_object instance
* @returns int
*/
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
* equivalent to json_object_set_string_len (obj, new_value, strlen(new_value))
* @returns 1 if value is set correctly, 0 otherwise
*/
JSON_EXPORT int json_object_set_string(json_object *obj, const char *new_value);
/** 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
* if it is not without any further actions. If type of obj is json_type_string
* the object value is changed to new_value
*
* @param obj the json_object instance
* @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
* @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);
/** 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
*
* If the passed objects are equal 1 will be returned.
* Equality is defined as follows:
* - json_objects of different types are never equal
* - json_objects of the same primitive type are equal if the
* c-representation of their value is equal
* - json-arrays are considered equal if all values at the same
* indices are equal (same order)
* - Complex json_objects are considered equal if all
* contained objects referenced by their key are equal,
* regardless their order.
*
* @param obj1 the first json_object instance
* @param obj2 the second json_object instance
* @returns 1 if both objects are equal, 0 otherwise
*/
JSON_EXPORT int json_object_equal(struct json_object *obj1, struct json_object *obj2);
/**
* Perform a shallow copy of src into *dst as part of an overall json_object_deep_copy().
*
* If src is part of a containing object or array, parent will be non-NULL,
* and key or index will be provided.
* When shallow_copy is called *dst will be NULL, and must be non-NULL when it returns.
* src will never be NULL.
*
* 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
* copy function.
*
* @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);
/**
* The default shallow copy implementation for use with json_object_deep_copy().
* This simply calls the appropriate json_object_new_() function and
* copies over the serializer function (_to_json_string internal field of
* the json_object structure) but not any _userdata or _user_delete values.
*
* If you're writing a custom shallow_copy function, perhaps because you're using
* your own custom serializer, you can call this first to create the new object
* before customizing it with json_object_set_serializer().
*
* @return 1 on success, -1 on errors, but never 2.
*/
JSON_EXPORT json_c_shallow_copy_fn json_c_shallow_copy_default;
/**
* Copy the contents of the JSON object.
* The destination object must be initialized to NULL,
* to make sure this function won't overwrite an existing JSON object.
*
* This does roughly the same thing as
* `json_tokener_parse(json_object_get_string(src))`.
*
* @param src source JSON object whose contents will be copied
* @param dst pointer to the destination object where the contents of `src`;
* make sure this pointer is initialized to NULL
* @param shallow_copy an optional function to copy individual objects, needed
* when custom serializers are in use. See also
* json_object set_serializer.
*
* @returns 0 if the copy went well, -1 if an error occurred during copy
* 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);
#ifdef __cplusplus
}
#endif
#endif
json-c-0.19/issues_closed_for_0.17.md 0000644 0001750 0001750 00000021737 15217751164 016050 0 ustar uerh uerh 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
json-c-0.19/.clang-format 0000644 0001750 0001750 00000003321 15217751164 013707 0 ustar uerh uerh 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
json-c-0.19/json_util.c 0000644 0001750 0001750 00000015433 15217751164 013515 0 ustar uerh uerh /*
* $Id: json_util.c,v 1.4 2006/01/30 23:07:57 mclark Exp $
*
* Copyright (c) 2004, 2005 Metaparadigm Pte. Ltd.
* Michael Clark
*
* This library 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"
#undef realloc
#include "strerror_override.h"
#include
#include
#include
#include
#include
#include
#ifdef HAVE_SYS_TYPES_H
#include
#endif /* HAVE_SYS_TYPES_H */
#ifdef HAVE_SYS_STAT_H
#include
#endif /* HAVE_SYS_STAT_H */
#ifdef HAVE_FCNTL_H
#include
#endif /* HAVE_FCNTL_H */
#ifdef HAVE_UNISTD_H
#include
#endif /* HAVE_UNISTD_H */
#ifdef _WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include
#include
#endif /* defined(_WIN32) */
#if !defined(HAVE_OPEN) && defined(_WIN32)
#define open _open
#endif
#include "snprintf_compat.h"
#include "debug.h"
#include "json_inttypes.h"
#include "json_object.h"
#include "json_tokener.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 char _last_err[256] = "";
const char *json_util_get_last_err(void)
{
if (_last_err[0] == '\0')
return NULL;
return _last_err;
}
void _json_c_set_last_err(const char *err_fmt, ...)
{
va_list ap;
va_start(ap, err_fmt);
// Ignore (attempted) overruns from snprintf
(void)vsnprintf(_last_err, sizeof(_last_err), err_fmt, ap);
va_end(ap);
}
struct json_object *json_object_from_fd(int fd)
{
return json_object_from_fd_ex(fd, -1);
}
struct json_object *json_object_from_fd_ex(int fd, int in_depth)
{
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()))
{
_json_c_set_last_err("json_object_from_fd_ex: printbuf_new failed\n");
return NULL;
}
if (in_depth != -1)
depth = in_depth;
tok = json_tokener_new_ex(depth);
if (!tok)
{
_json_c_set_last_err(
"json_object_from_fd_ex: unable to allocate json_tokener(depth=%d): %s\n",
depth, strerror(errno));
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 *obj;
int fd;
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));
return NULL;
}
obj = json_object_from_fd(fd);
close(fd);
return obj;
}
/* extended "format and write to file" function */
int json_object_to_file_ext(const char *filename, struct json_object *obj, int flags)
{
int fd, ret;
int saved_errno;
if (!obj)
{
_json_c_set_last_err("json_object_to_file_ext: object is null\n");
return -1;
}
if ((fd = open(filename, O_WRONLY | O_TRUNC | O_CREAT, 0644)) < 0)
{
_json_c_set_last_err("json_object_to_file_ext: error opening file %s: %s\n",
filename, strerror(errno));
return -1;
}
ret = _json_object_to_fd(fd, obj, flags, filename);
saved_errno = errno;
close(fd);
errno = saved_errno;
return ret;
}
int json_object_to_fd(int fd, struct json_object *obj, int flags)
{
if (!obj)
{
_json_c_set_last_err("json_object_to_fd: object is null\n");
return -1;
}
return _json_object_to_fd(fd, obj, flags, NULL);
}
static int _json_object_to_fd(int fd, struct json_object *obj, int flags, const char *filename)
{
ssize_t ret;
const char *json_str;
size_t wpos, wsize;
filename = filename ? filename : "(fd)";
if (!(json_str = json_object_to_json_string_ext(obj, flags)))
{
return -1;
}
wsize = strlen(json_str);
wpos = 0;
while (wpos < wsize)
{
if ((ret = write(fd, json_str + wpos, wsize - wpos)) < 0)
{
_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 */
wpos += (size_t)ret;
}
return 0;
}
// backwards compatible "format and write to file" function
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);
}
// Deprecated json_parse_double function. See json_tokener_parse_double instead.
int json_parse_double(const char *buf, double *retval)
{
char *end;
*retval = strtod(buf, &end);
return end == buf ? 1 : 0;
}
int json_parse_int64(const char *buf, int64_t *retval)
{
char *end = NULL;
int64_t val;
errno = 0;
val = strtoll(buf, &end, 10);
if (end != buf)
*retval = val;
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
void *rpl_realloc(void *p, size_t n)
{
if (n == 0)
n = 1;
if (p == 0)
return malloc(n);
return realloc(p, n);
}
#endif
#define NELEM(a) (sizeof(a) / sizeof(a[0]))
/* clang-format off */
static const char *json_type_name[] = {
/* If you change this, be sure to update the enum json_type definition too */
"null",
"boolean",
"double",
"int",
"object",
"array",
"string",
};
/* clang-format on */
const char *json_type_to_name(enum json_type o_type)
{
int o_type_int = (int)o_type;
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,%u]\n", o_type,
(unsigned)NELEM(json_type_name));
return NULL;
}
return json_type_name[o_type];
}
json-c-0.19/json_object_iterator.c 0000644 0001750 0001750 00000010742 15217751164 015715 0 ustar uerh uerh /**
*******************************************************************************
* @file json_object_iterator.c
*
* Copyright (c) 2009-2012 Hewlett-Packard Development Company, L.P.
*
* This library 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
#include "json.h"
#include "json_object_private.h"
#include "json_object_iterator.h"
/**
* How It Works
*
* For each JSON Object, json-c maintains a linked list of zero
* or more lh_entry (link-hash entry) structures inside the
* Object's link-hash table (lh_table).
*
* Each lh_entry structure on the JSON Object's linked list
* represents a single name/value pair. The "next" field of the
* last lh_entry in the list is set to NULL, which terminates
* the list.
*
* We represent a valid iterator that refers to an actual
* name/value pair via a pointer to the pair's lh_entry
* structure set as the iterator's opaque_ field.
*
* We follow json-c's current pair list representation by
* representing a valid "end" iterator (one that refers past the
* last pair) with a NULL value in the iterator's opaque_ field.
*
* A JSON Object without any pairs in it will have the "head"
* field of its lh_table structure set to NULL. For such an
* object, json_object_iter_begin will return an iterator with
* the opaque_ field set to NULL, which is equivalent to the
* "end" iterator.
*
* When iterating, we simply update the iterator's opaque_ field
* to point to the next lh_entry structure in the linked list.
* opaque_ will become NULL once we iterate past the last pair
* in the list, which makes the iterator equivalent to the "end"
* iterator.
*/
/// Our current representation of the "end" iterator;
///
/// @note May not always be NULL
static const void *kObjectEndIterValue = NULL;
/**
* ****************************************************************************
*/
struct json_object_iterator json_object_iter_begin(struct json_object *obj)
{
struct json_object_iterator iter;
struct lh_table *pTable;
/// @note json_object_get_object will return NULL if passed NULL
/// or a non-json_type_object instance
pTable = json_object_get_object(obj);
JASSERT(NULL != pTable);
/// @note For a pair-less Object, head is NULL, which matches our
/// definition of the "end" iterator
iter.opaque_ = lh_table_head(pTable);
return iter;
}
/**
* ****************************************************************************
*/
struct json_object_iterator json_object_iter_end(const struct json_object *obj)
{
struct json_object_iterator iter;
JASSERT(NULL != obj);
JASSERT(json_object_is_type(obj, json_type_object));
iter.opaque_ = kObjectEndIterValue;
return iter;
}
/**
* ****************************************************************************
*/
void json_object_iter_next(struct json_object_iterator *iter)
{
JASSERT(NULL != iter);
JASSERT(kObjectEndIterValue != iter->opaque_);
iter->opaque_ = lh_entry_next(((const struct lh_entry *)iter->opaque_));
}
/**
* ****************************************************************************
*/
const char *json_object_iter_peek_name(const struct json_object_iterator *iter)
{
JASSERT(NULL != iter);
JASSERT(kObjectEndIterValue != iter->opaque_);
return (const char *)(((const struct lh_entry *)iter->opaque_)->k);
}
/**
* ****************************************************************************
*/
struct json_object *json_object_iter_peek_value(const struct json_object_iterator *iter)
{
JASSERT(NULL != iter);
JASSERT(kObjectEndIterValue != iter->opaque_);
return (struct json_object *)lh_entry_v((const struct lh_entry *)iter->opaque_);
}
/**
* ****************************************************************************
*/
json_bool json_object_iter_equal(const struct json_object_iterator *iter1,
const struct json_object_iterator *iter2)
{
JASSERT(NULL != iter1);
JASSERT(NULL != iter2);
return (iter1->opaque_ == iter2->opaque_);
}
/**
* ****************************************************************************
*/
struct json_object_iterator json_object_iter_init_default(void)
{
struct json_object_iterator iter;
/**
* @note Make this a negative, invalid value, such that
* accidental access to it would likely be trapped by the
* hardware as an invalid address.
*/
iter.opaque_ = NULL;
return iter;
}
json-c-0.19/issues_closed_for_0.13.md 0000644 0001750 0001750 00000066175 15217751164 016051 0 ustar uerh uerh
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=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
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.13 release
(since commit f84d9c, the 0.12 branch point, 2014-04-10)
* [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__set(json_object *o, 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. \
json-c-0.19/json-c.sym 0000644 0001750 0001750 00000010640 15217751164 013261 0 ustar uerh uerh
/*
* 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_set_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_delete_entry_to_tail;
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;
JSONC_0.19 {
global:
json_pointer_set_with_limit_index;
json_pointer_set_with_cb;
json_object_array_put_with_idx_limit_cb;
} JSONC_0.18;
json-c-0.19/.github/ 0000755 0001750 0001750 00000000000 15217751164 012675 5 ustar uerh uerh json-c-0.19/.github/workflows/ 0000755 0001750 0001750 00000000000 15217751164 014732 5 ustar uerh uerh json-c-0.19/.github/workflows/meson.yml 0000644 0001750 0001750 00000015660 15217751164 016606 0 ustar uerh uerh name: meson
on: [push, pull_request]
concurrency:
group: ${{github.workflow}}-${{github.head_ref}}
cancel-in-progress: true
permissions:
contents: read
jobs:
Linux-GCC:
runs-on: ubuntu-22.04
strategy:
matrix:
cc: ['9', '13']
steps:
- uses: actions/checkout@v4
- uses: egor-tensin/setup-gcc@v1
with:
version: ${{matrix.cc}}
- name: Install packages
run: |
python3 -m pip install meson ninja
- name: Compile and Test
run: |
meson setup "${{github.workspace}}/build" -Dwarning_level=3 -Dbuildtype=debug
meson compile -C "${{github.workspace}}/build" --verbose
meson test -C "${{github.workspace}}/build" --verbose
Linux-Clang:
runs-on: ubuntu-22.04
strategy:
matrix:
cc: ['9', '22']
steps:
- uses: actions/checkout@v4
- uses: egor-tensin/setup-clang@v1
- name: Install packages
run: |
python3 -m pip install meson ninja
- name: Compile and Test
run: |
meson setup "${{github.workspace}}/build" -Dwarning_level=3 -Dbuildtype=debug
meson compile -C "${{github.workspace}}/build" --verbose
meson test -C "${{github.workspace}}/build" --verbose
VisualStudio:
runs-on: windows-latest
strategy:
matrix:
platform: ['x64', 'x86']
steps:
- uses: actions/checkout@v4
- name: Install packages
run: |
python -m pip install meson ninja
- uses: ilammy/msvc-dev-cmd@v1
with:
arch: ${{matrix.platform}}
- name: Compile and Test
env:
CFLAGS: '/analyze'
run: |
meson setup "${{github.workspace}}/build" --wrap-mode=forcefallback -Dwarning_level=3 -Dbuildtype=debug
meson compile -C "${{github.workspace}}/build" --verbose
meson test -C "${{github.workspace}}/build" --verbose
VisualStudio-clang-cl:
runs-on: windows-latest
steps:
- uses: actions/checkout@v4
- name: Install packages
run: |
python -m pip install meson ninja
- uses: ilammy/msvc-dev-cmd@v1
- name: Compile and Test
env:
CC: clang-cl
run: |
meson setup "${{github.workspace}}/build" -Dwarning_level=3 -Dbuildtype=debug
meson compile -C "${{github.workspace}}/build" --verbose
meson test -C "${{github.workspace}}/build" --verbose
MSYS2:
runs-on: windows-latest
strategy:
matrix:
platform: ['UCRT64', 'CLANG64']
defaults:
run:
shell: msys2 {0}
steps:
- uses: actions/checkout@v4
- uses: msys2/setup-msys2@v2
with:
msystem: ${{matrix.platform}}
pacboy: >-
cc:p
cmake:p
meson:p
ninja:p
pkgconf:p
- name: Compile and Test
run: |
meson setup "${{github.workspace}}/build" -Dwarning_level=3 -Dbuildtype=debug
meson compile -C "${{github.workspace}}/build" --verbose
meson test -C "${{github.workspace}}/build" --verbose
Cygwin:
runs-on: windows-latest
defaults:
run:
shell: msys2 {0}
steps:
- uses: actions/checkout@v4
- uses: msys2/setup-msys2@v2
with:
msystem: 'MSYS'
install: >-
gcc
meson
ninja
- name: Compile and Test
run: |
meson setup build -Dwarning_level=3 -Dcpp_std=gnu++20 -Dbuildtype=debug
meson compile -C build --verbose
meson test -C build --verbose
MacOS:
runs-on: macos-latest
steps:
- uses: actions/checkout@v4
- name: Install packages
run: |
brew install meson
- name: Compile and Test
run: |
meson setup "${{github.workspace}}/build" -Dwarning_level=3 -Dbuildtype=debug
meson compile -C "${{github.workspace}}/build" --verbose
meson test -C "${{github.workspace}}/build" --verbose
DragonflyBSD:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: vmactions/dragonflybsd-vm@v1
with:
prepare: |
pkg install -y ninja meson pkgconf
run: |
meson setup "${{github.workspace}}/build" -Dwarning_level=3 -Dbuildtype=debug
meson compile -C "${{github.workspace}}/build" --verbose
meson test -C "${{github.workspace}}/build" --verbose
FreeBSD:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: vmactions/freebsd-vm@v1
with:
prepare: |
pkg install -y ninja meson pkgconf
run: |
meson setup "${{github.workspace}}/build" -Dwarning_level=3 -Dbuildtype=debug
meson compile -C "${{github.workspace}}/build" --verbose
meson test -C "${{github.workspace}}/build" --verbose
NetBSD:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: vmactions/netbsd-vm@v1
with:
prepare: |
/usr/sbin/pkg_add meson pkgconf
run: |
meson setup "${{github.workspace}}/build" -Dwarning_level=3 -Dbuildtype=debug
meson compile -C "${{github.workspace}}/build" --verbose
meson test -C "${{github.workspace}}/build" --verbose
OmniOS:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: vmactions/omnios-vm@v1
with:
prepare: |
pkg install gcc14 meson-313 ninja pkg-config python-313
run: |
/usr/lib/python3.13/bin/meson setup "${{github.workspace}}/build" -Dwarning_level=3 -Dbuildtype=debug
/usr/lib/python3.13/bin/meson compile -C "${{github.workspace}}/build" --verbose
/usr/lib/python3.13/bin/meson test -C "${{github.workspace}}/build" --verbose
OpenBSD:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: vmactions/openbsd-vm@v1
with:
prepare: |
pkg_add ninja meson pkgconf
run: |
meson setup "${{github.workspace}}/build" -Dwarning_level=3 -Dbuildtype=debug
meson compile -C "${{github.workspace}}/build" --verbose
meson test -C "${{github.workspace}}/build" --verbose
Alpine:
runs-on: ubuntu-latest
strategy:
matrix:
platform: ['x86_64', 'x86', 'armhf', 'armv7', 'aarch64', 'ppc64le', 'riscv64', 's390x']
defaults:
run:
shell: alpine.sh {0}
steps:
- uses: actions/checkout@v4
- uses: jirutka/setup-alpine@v1
with:
branch: edge
arch: ${{matrix.platform}}
packages: >
build-base pkgconf meson samurai
- name: Compile and Test
run: |
meson setup "${{github.workspace}}/build" -Dwarning_level=3 -Dbuildtype=debug
meson compile -C "${{github.workspace}}/build" --verbose
meson test -C "${{github.workspace}}/build" --verbose
json-c-0.19/.github/ISSUE_TEMPLATE/ 0000755 0001750 0001750 00000000000 15217751164 015060 5 ustar uerh uerh json-c-0.19/.github/ISSUE_TEMPLATE/bug_report.md 0000644 0001750 0001750 00000001275 15217751164 017557 0 ustar uerh uerh ---
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
json-c-0.19/math_compat.h 0000644 0001750 0001750 00000001602 15217751164 014001 0 ustar uerh uerh #ifndef __math_compat_h
#define __math_compat_h
/**
* @file
* @brief Do not use, json-c internal, may be changed or removed at any time.
*/
/* Define isnan, isinf, infinity and nan on Windows/MSVC */
#ifndef HAVE_DECL_ISNAN
#ifdef HAVE_DECL__ISNAN
#include
#define isnan(x) _isnan(x)
#else
/* On platforms like AIX and "IBM i" we need to provide our own isnan */
#define isnan(x) ((x) != (x))
#endif
#endif
#ifndef HAVE_DECL_ISINF
#ifdef HAVE_DECL__FINITE
#include
#define isinf(x) (!_finite(x))
#else
#include
/* 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
#ifndef HAVE_DECL_INFINITY
#include
#define INFINITY (DBL_MAX + DBL_MAX)
#define HAVE_DECL_INFINITY
#endif
#ifndef HAVE_DECL_NAN
#define NAN (INFINITY - INFINITY)
#define HAVE_DECL_NAN
#endif
#endif
json-c-0.19/.gitignore 0000644 0001750 0001750 00000002367 15217751164 013335 0 ustar uerh uerh # Temp files
*~
*.swp
*.bak
*.backup
\#*
.\#*
*\#
*.sav
*.save
*.autosav
*.autosave
.DS_Store
# Tests
/tests/Makefile
/tests/test1
/tests/test1Formatted
/tests/test2
/tests/test2Formatted
/tests/test4
/tests/testReplaceExisting
/tests/testSubDir
/tests/test_cast
/tests/test_charcase
/tests/test_compare
/tests/test_deep_copy
/tests/test_double_serializer
/tests/test_float
/tests/test_int_add
/tests/test_int_get
/tests/test_json_pointer
/tests/test_locale
/tests/test_null
/tests/test_parse
/tests/test_parse_int64
/tests/test_printbuf
/tests/test_set_serializer
/tests/test_set_value
/tests/test_util_file
/tests/test_visit
/tests/*.vg.out
/tests/*.log
/tests/*.trs
# Generated folders
/build
/Debug
/Release
/*/Debug
/*/Release
# Archives
*.zip
*.tar.*
*.tgz
*.gz
*.bz2
*.xz
*.lz
*.lzma
*.7z
*.dll
*.deb
*.rpm
*.apk
*.exe
*.msi
*.dmg
*.ipa
# It's not good practice to build directly in the source tree
# but ignore cmake auto-generated files anyway:
/json_config.h
/json.h
/config.h
/json-c.pc
/Makefile
/CMakeCache.txt
/CMakeFiles
/CMakeDoxyfile.in
/*.cmake
/DartConfiguration.tcl
/tests/CMakeFiles/
/tests/*.cmake
/Testing/
# ...and build artifacts.
/doc/html
/libjson-c.a
/libjson-c.so
/libjson-c.so.*
# Benchmarking input and output
/bench/data
/bench/work
json-c-0.19/meson.build 0000644 0001750 0001750 00000017751 15217751164 013512 0 ustar uerh uerh
project('json-c', 'c', version: '0.18.99',
meson_version: '>=0.54.0',
license: 'MIT',
default_options: ['buildtype=release', 'warning_level=2'])
cc = meson.get_compiler('c')
# Configuration header generation
conf_data = configuration_data()
jconf_data = configuration_data()
conf_data.set('VERSION', meson.project_version())
has_std_lib = cc.has_header('stdlib.h')
has_std_arg = cc.has_header('stdarg.h')
has_string = cc.has_header('string.h')
has_float = cc.has_header('float.h')
if has_std_lib and has_std_arg and has_string and has_float
conf_data.set('STDC_HEADERS', 1, description : 'Define to 1 if you have the ANSI C header files.')
endif
bsd_dep = dependency('libbsd', required: false)
headers = {
'bsd/stdlib.h': bsd_dep,
'dlfcn.h': [],
'endian.h': [],
'fcntl.h': [],
'inttypes.h': [],
'limits.h': [],
'locale.h': [],
'memory.h': [],
'stdarg.h': [],
'stdint.h': [],
'stdlib.h': [],
'string.h': [],
'strings.h': [],
'syslog.h': [],
'sys/cdefs.h': [],
'sys/param.h': [],
'sys/random.h': [],
'sys/resource.h': [],
'sys/stat.h': [],
'sys/types.h': [],
'unistd.h': [],
'xlocale.h': [],
}
foreach h, d : headers
if cc.has_header(h, dependencies: d)
conf_data.set('HAVE_@0@'.format(h.underscorify().to_upper()), 1, description : 'Define to 1 if you have the <@0@> header file'.format(h))
endif
endforeach
if cc.has_header('inttypes.h')
conf_data.set('JSON_C_HAVE_INTTYPES_H', 1, description : 'Define to 1 if you have the header file.')
jconf_data.set('JSON_C_HAVE_INTTYPES_H', 1, description : 'Define to 1 if you have the header file.')
endif
if cc.has_header('stdint.h')
conf_data.set('JSON_C_HAVE_STDINT_H', 1, description : 'Define to 1 if you have the header file.')
jconf_data.set('JSON_C_HAVE_STDINT_H', 1, description : 'Define to 1 if you have the header file.')
endif
funcs = [
'open',
'realloc',
'setlocale',
'strdup',
'strerror',
'uselocale',
'duplocale',
'vsyslog',
'getrandom',
'getrusage',
'strtoll',
'strtoull',
'arc4random',
'vasprintf',
]
if conf_data.has('HAVE_STRINGS_H')
funcs += ['strcasecmp', 'strncasecmp']
endif
foreach f : funcs
if cc.has_function(f)
conf_data.set('HAVE_@0@'.format(f.to_upper()), 1, description : 'Define to 1 if you have the `@0@` function.'.format(f))
endif
endforeach
foreach f : ['snprintf', 'vsnprintf', 'vprintf']
if cc.has_header_symbol('stdio.h', f)
conf_data.set('HAVE_@0@'.format(f.to_upper()), 1, description : 'Define to 1 if you have the `@0@` function.'.format(f))
endif
endforeach
if not conf_data.has('HAVE_VPRINTF') and cc.has_function('_doprnt')
conf_data.set('HAVE_DOPRNT', 1, description : 'Define to 1 if you have _doprnt but not vprintf.')
endif
if conf_data.has('HAVE_STRTOLL')
conf_data.set('json_c_strtoll', 'strtoll')
elif cc.has_function('_strtoi64', prefix : '#include ')
conf_data.set('json_c_strtoll', '_strtoi64')
endif
if conf_data.has('HAVE_STRTOULL')
conf_data.set('json_c_strtoull', 'strtoull')
elif cc.has_function('_strtoui64', prefix : '#include ')
conf_data.set('json_c_strtoull', '_strtoui64')
endif
decls = {
'INFINITY': 'math.h',
'isinf': 'math.h',
'isnan': 'math.h',
'NAN': 'math.h',
'_finite': 'float.h',
'_isnan': 'float.h',
}
foreach d, h : decls
if cc.has_header_symbol(h, d)
conf_data.set('HAVE_DECL_@0@'.format(d.to_upper()), 1, description : 'Define to 1 if you have the declaration of `@0@`'.format(d))
endif
endforeach
check_thread = cc.compiles('__thread int x;', name: 'Check for __thread support')
if check_thread
conf_data.set('HAVE___THREAD', 1)
conf_data.set('SPEC___THREAD', '__thread')
elif cc.get_argument_syntax() == 'msvc'
conf_data.set('SPEC___THREAD', '__declspec(thread)')
endif
gnu_warning_section_support = cc.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; }
''', name: 'Check for GNU warning section support')
if gnu_warning_section_support
conf_data.set('HAS_GNU_WARNING_LONG', 1, description : 'Define to 1 if the compiler supports .gnu.warning sections.')
endif
atomic_builtin_support = cc.compiles('''
int main() {
int x = 0;
int i = __sync_add_and_fetch(&x, 1);
return x;
}
''',
name: 'Check for atomic builtins')
if atomic_builtin_support
conf_data.set('HAVE_ATOMIC_BUILTINS', 1, description : 'Define to 1 if the compiler supports atomic builtins.')
endif
if get_option('enable_rdrand')
conf_data.set('ENABLE_RDRAND', 1)
endif
if get_option('override_get_random_seed')
conf_data.set('OVERRIDE_GET_RANDOM_SEED', get_option('override_get_random_seed'))
endif
if get_option('enable_threading')
conf_data.set('ENABLE_THREADING', 1)
endif
if get_option('newlocale_needs_freelocale')
conf_data.set('NEWLOCALE_NEEDS_FREELOCALE', 1)
endif
conf_data.set('SIZEOF_INT', cc.sizeof('int'))
conf_data.set('SIZEOF_INT64_T', cc.sizeof('int64_t', prefix : '#include '))
conf_data.set('SIZEOF_LONG', cc.sizeof('long'))
conf_data.set('SIZEOF_LONG_LONG', cc.sizeof('long long'))
conf_data.set('SIZEOF_SIZE_T', cc.sizeof('size_t', prefix : '#include '))
if cc.get_argument_syntax() == 'msvc'
conf_data.set('SIZEOF_SSIZE_T', cc.sizeof('SSIZE_T', prefix : '#include \n#include '))
else
conf_data.set('SIZEOF_SSIZE_T', cc.sizeof('ssize_t', prefix : '#include '))
endif
conf_data.set('PACKAGE_VERSION', meson.project_version())
conf_data.set('PROJECT_NAME', meson.project_name())
configure_header = configure_file(
output: 'config.h',
configuration: conf_data
)
json_configure_header = configure_file(
output: 'json_config.h',
configuration: jconf_data
)
jhconf_data = configuration_data()
jhconf_data.set('JSON_H_JSON_PATCH',
get_option('disable_json_patch') ? '' : '#include "json_patch.h"'
)
jhconf_data.set('JSON_H_JSON_POINTER',
get_option('disable_json_pointer') ? '' : '#include "json_pointer.h"'
)
json_header = configure_file(
input: 'json.h.cmakein',
output: 'json.h',
configuration: jhconf_data
)
# Platform-specific flags
add_project_arguments('-D_GNU_SOURCE', language: 'c')
if host_machine.system() == 'windows'
add_project_arguments('-DWIN32', language: 'c')
endif
# Compiler flags
message('target is ' + host_machine.system())
if host_machine.system() == 'windows'
# Cover any compiler on Windows attempting to use MSVC's standard library
add_project_arguments('-D_CRT_NONSTDC_NO_DEPRECATE', '-D_CRT_SECURE_NO_WARNINGS', language: 'c')
endif
add_project_arguments(cc.get_supported_arguments('-Wno-unused-parameter'), language : 'c')
sym = cc.get_supported_link_arguments(
'-Wl,--version-script,@0@/json-c.sym'.format(
meson.current_source_dir(),
),
)
# Source files
sources = files(
'arraylist.c', 'debug.c', 'json_c_version.c', 'json_object.c',
'json_object_iterator.c', 'json_tokener.c', 'json_util.c',
'json_visit.c', 'linkhash.c', 'printbuf.c', 'random_seed.c',
'strerror_override.c'
)
if not get_option('disable_json_pointer')
sources += files('json_pointer.c')
if not get_option('disable_json_patch')
sources += files('json_patch.c')
endif
endif
# Include directories
inc = include_directories('.')
# Build library
libjson = library('json-c',
sources,
include_directories: inc,
dependencies: bsd_dep,
install: true,
link_args: sym,
version: '5.4.0',
soversion: '5',
)
jsonc_dep = declare_dependency(link_with: libjson, include_directories: inc)
meson.override_dependency('json-c', jsonc_dep)
# Install headers
install_headers(
'arraylist.h', 'debug.h', 'json_c_version.h', 'json_inttypes.h',
'json_object.h', 'json_object_iterator.h', 'json_tokener.h',
'json_types.h', 'json_util.h', 'json_visit.h', 'linkhash.h',
'printbuf.h', json_configure_header, json_header
)
# Optional apps
if get_option('build_apps') and host_machine.system() != 'windows'
subdir('apps')
endif
# Optional tests
if get_option('buildtype') == 'debug'
subdir('tests')
endif
json-c-0.19/doc/ 0000755 0001750 0001750 00000000000 15217751765 012111 5 ustar uerh uerh json-c-0.19/doc/fixup_markdown.sh 0000755 0001750 0001750 00000000360 15217751164 015475 0 ustar uerh uerh #!/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; } ' "$@"
json-c-0.19/doc/CMakeLists.txt 0000644 0001750 0001750 00000000721 15217751164 014642 0 ustar uerh uerh # 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)
json-c-0.19/doc/Doxyfile.in 0000644 0001750 0001750 00000311343 15217751164 014222 0 ustar uerh uerh # Doxyfile 1.8.8
# This file describes the settings to be used by the documentation system
# doxygen (www.doxygen.org) for a project.
#
# All text after a double hash (##) is considered a comment and is placed in
# front of the TAG it is preceding.
#
# All text after a single hash (#) is considered a comment and will be ignored.
# The format is:
# TAG = value [value, ...]
# For lists, items can also be appended using:
# TAG += value [value, ...]
# Values that contain spaces should be placed between quotes (\" \").
#---------------------------------------------------------------------------
# Project related configuration options
#---------------------------------------------------------------------------
# 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
# before the first occurrence of this tag. Doxygen uses libiconv (or the iconv
# built into libc) for the transcoding. See https://www.gnu.org/software/libiconv
# for the list of possible encodings.
# The default value is: UTF-8.
DOXYFILE_ENCODING = UTF-8
# The PROJECT_NAME tag is a single word (or a sequence of words surrounded by
# double-quotes, unless you are using Doxywizard) that should identify the
# project for which the documentation is generated. This name is used in the
# title of most generated pages and in a few other places.
# The default value is: My Project.
PROJECT_NAME = json-c
# The PROJECT_NUMBER tag can be used to enter a project or revision number. This
# could be handy for archiving the generated documentation or if some version
# control system is used.
PROJECT_NUMBER = @PROJECT_VERSION@
# 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
# quick idea about the purpose of the project. Keep the description short.
PROJECT_BRIEF =
# With the PROJECT_LOGO tag one can specify an logo or icon that is included in
# the documentation. The maximum height of the logo should not exceed 55 pixels
# and the maximum width should not exceed 200 pixels. Doxygen will copy the logo
# to the output directory.
PROJECT_LOGO =
# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path
# into which the generated documentation will be written. If a relative path is
# entered, it will be relative to the location where doxygen was started. If
# left blank the current directory will be used.
OUTPUT_DIRECTORY = @CMAKE_CURRENT_BINARY_DIR@
# 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
# will distribute the generated files over these directories. Enabling this
# option can be useful when feeding doxygen a huge amount of source files, where
# putting all generated files in the same directory would otherwise causes
# performance problems for the file system.
# The default value is: NO.
CREATE_SUBDIRS = NO
# If the ALLOW_UNICODE_NAMES tag is set to YES, doxygen will allow non-ASCII
# characters to appear in the names of generated files. If set to NO, non-ASCII
# characters will be escaped, for example _xE3_x81_x84 will be used for Unicode
# U+3044.
# The default value is: NO.
ALLOW_UNICODE_NAMES = NO
# The OUTPUT_LANGUAGE tag is used to specify the language in which all
# documentation generated by doxygen is written. Doxygen will use this
# information to generate all constant output in the proper language.
# Possible values are: Afrikaans, Arabic, Armenian, Brazilian, Catalan, Chinese,
# Chinese-Traditional, Croatian, Czech, Danish, Dutch, English (United States),
# Esperanto, Farsi (Persian), Finnish, French, German, Greek, Hungarian,
# Indonesian, Italian, Japanese, Japanese-en (Japanese with English messages),
# Korean, Korean-en (Korean with English messages), Latvian, Lithuanian,
# Macedonian, Norwegian, Persian (Farsi), Polish, Portuguese, Romanian, Russian,
# Serbian, Serbian-Cyrillic, Slovak, Slovene, Spanish, Swedish, Turkish,
# Ukrainian and Vietnamese.
# The default value is: English.
OUTPUT_LANGUAGE = English
# If the BRIEF_MEMBER_DESC tag is set to YES doxygen will include brief member
# descriptions after the members that are listed in the file and class
# documentation (similar to Javadoc). Set to NO to disable this.
# The default value is: YES.
BRIEF_MEMBER_DESC = YES
# If the REPEAT_BRIEF tag is set to YES doxygen will prepend the brief
# description of a member or function before the detailed description
#
# Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the
# brief descriptions will be completely suppressed.
# The default value is: YES.
REPEAT_BRIEF = YES
# This tag implements a quasi-intelligent brief description abbreviator that is
# used to form the text in various listings. Each string in this list, if found
# as the leading text of the brief description, will be stripped from the text
# and the result, after processing the whole list, is used as the annotated
# text. Otherwise, the brief description is used as-is. If left blank, the
# following values are used ($name is automatically replaced with the name of
# the entity):The $name class, The $name widget, The $name file, is, provides,
# specifies, contains, represents, a, an and the.
ABBREVIATE_BRIEF =
# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then
# doxygen will generate a detailed section even if there is only a brief
# description.
# The default value is: NO.
ALWAYS_DETAILED_SEC = NO
# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all
# inherited members of a class in the documentation of that class as if those
# members were ordinary class members. Constructors, destructors and assignment
# operators of the base classes will not be shown.
# The default value is: NO.
INLINE_INHERITED_MEMB = NO
# If the FULL_PATH_NAMES tag is set to YES doxygen will prepend the full path
# before files name in the file list and in the header files. If set to NO the
# shortest path that makes the file name unique will be used
# The default value is: YES.
FULL_PATH_NAMES = YES
# The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path.
# Stripping is only done if one of the specified strings matches the left-hand
# part of the path. The tag can be used to show relative paths in the file list.
# If left blank the directory from which doxygen is run is used as the path to
# strip.
#
# Note that you can specify absolute paths here, but also relative paths, which
# will be relative from the directory where doxygen is started.
# This tag requires that the tag FULL_PATH_NAMES is set to YES.
STRIP_FROM_PATH = @CMAKE_SOURCE_DIR@
# 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
# header file to include in order to use a class. If left blank only the name of
# the header file containing the class definition is used. Otherwise one should
# specify the list of include paths that are normally passed to the compiler
# using the -I flag.
STRIP_FROM_INC_PATH =
# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but
# less readable) file names. This can be useful is your file systems doesn't
# support long names like on DOS, Mac, or CD-ROM.
# The default value is: NO.
SHORT_NAMES = NO
# If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the
# first line (until the first dot) of a Javadoc-style comment as the brief
# description. If set to NO, the Javadoc-style will behave just like regular Qt-
# style comments (thus requiring an explicit @brief command for a brief
# description.)
# The default value is: NO.
JAVADOC_AUTOBRIEF = NO
# If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first
# line (until the first dot) of a Qt-style comment as the brief description. If
# set to NO, the Qt-style will behave just like regular Qt-style comments (thus
# requiring an explicit \brief command for a brief description.)
# The default value is: NO.
QT_AUTOBRIEF = NO
# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a
# multi-line C++ special comment block (i.e. a block of //! or /// comments) as
# a brief description. This used to be the default behavior. The new default is
# to treat a multi-line C++ comment block as a detailed description. Set this
# tag to YES if you prefer the old behavior instead.
#
# Note that setting this tag to YES also means that rational rose comments are
# not recognized any more.
# The default value is: NO.
MULTILINE_CPP_IS_BRIEF = NO
# If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the
# documentation from any documented member that it re-implements.
# The default value is: YES.
INHERIT_DOCS = YES
# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce a
# new page for each member. If set to NO, the documentation of a member will be
# part of the file/class/namespace that contains it.
# The default value is: NO.
SEPARATE_MEMBER_PAGES = NO
# The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen
# uses this value to replace tabs by spaces in code fragments.
# Minimum value: 1, maximum value: 16, default value: 4.
TAB_SIZE = 8
# This tag can be used to specify a number of aliases that act as commands in
# the documentation. An alias has the form:
# name=value
# For example adding
# "sideeffect=@par Side Effects:\n"
# will allow you to put the command \sideeffect (or @sideeffect) in the
# documentation, which will result in a user-defined paragraph with heading
# "Side Effects:". You can put \n's in the value part of an alias to insert
# newlines.
ALIASES =
# This tag can be used to specify a number of word-keyword mappings (TCL only).
# A mapping has the form "name=value". For example adding "class=itcl::class"
# will allow you to use the command class in the itcl::class meaning.
TCL_SUBST =
# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources
# only. Doxygen will then generate output that is more tailored for C. For
# instance, some of the names that are used will be different. The list of all
# members will be omitted, etc.
# The default value is: NO.
OPTIMIZE_OUTPUT_FOR_C = YES
# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or
# Python sources only. Doxygen will then generate output that is more tailored
# for that language. For instance, namespaces will be presented as packages,
# qualified scopes will look different, etc.
# The default value is: NO.
OPTIMIZE_OUTPUT_JAVA = NO
# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran
# sources. Doxygen will then generate output that is tailored for Fortran.
# The default value is: NO.
OPTIMIZE_FOR_FORTRAN = NO
# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL
# sources. Doxygen will then generate output that is tailored for VHDL.
# The default value is: NO.
OPTIMIZE_OUTPUT_VHDL = NO
# Doxygen selects the parser to use depending on the extension of the files it
# parses. With this tag you can assign which parser to use for a given
# extension. Doxygen has a built-in mapping, but you can override or extend it
# using this tag. The format is ext=language, where ext is a file extension, and
# language is one of the parsers supported by doxygen: IDL, Java, Javascript,
# C#, C, C++, D, PHP, Objective-C, Python, Fortran (fixed format Fortran:
# FortranFixed, free formatted Fortran: FortranFree, unknown formatted Fortran:
# Fortran. In the later case the parser tries to guess whether the code is fixed
# or free formatted code, this is the default for Fortran type files), VHDL. For
# instance to make doxygen treat .inc files as Fortran files (default is PHP),
# and .f files as C (default is Fortran), use: inc=Fortran f=C.
#
# Note For files without extension you can use no_extension as a placeholder.
#
# Note that for custom extensions you also need to set FILE_PATTERNS otherwise
# the files are not read by doxygen.
EXTENSION_MAPPING =
# If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments
# according to the Markdown format, which allows for more readable
# documentation. See https://daringfireball.net/projects/markdown/ for details.
# 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
# case of backward compatibilities issues.
# The default value is: YES.
MARKDOWN_SUPPORT = YES
# When enabled doxygen tries to link words that correspond to documented
# classes, or namespaces to their corresponding documentation. Such a link can
# be prevented in individual cases by by putting a % sign in front of the word
# or globally by setting AUTOLINK_SUPPORT to NO.
# The default value is: YES.
AUTOLINK_SUPPORT = YES
# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want
# to include (a tag file for) the STL sources as input, then you should set this
# tag to YES in order to let doxygen match functions declarations and
# definitions whose arguments contain STL classes (e.g. func(std::string);
# versus func(std::string) {}). This also make the inheritance and collaboration
# diagrams that involve STL classes more complete and accurate.
# The default value is: NO.
BUILTIN_STL_SUPPORT = NO
# If you use Microsoft's C++/CLI language, you should set this option to YES to
# enable parsing support.
# The default value is: NO.
CPP_CLI_SUPPORT = NO
# Set the SIP_SUPPORT tag to YES if your project consists of sip (see:
# 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
# of private inheritance when no explicit protection keyword is present.
# The default value is: NO.
SIP_SUPPORT = NO
# For Microsoft's IDL there are propget and propput attributes to indicate
# getter and setter methods for a property. Setting this option to YES will make
# doxygen to replace the get and set methods by a property in the documentation.
# This will only work if the methods are indeed getting or setting a simple
# type. If this is not the case, or you want to show the methods anyway, you
# should set this option to NO.
# The default value is: YES.
IDL_PROPERTY_SUPPORT = YES
# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC
# tag is set to YES, then doxygen will reuse the documentation of the first
# member in the group (if any) for the other members of the group. By default
# all members of a group must be documented explicitly.
# The default value is: NO.
DISTRIBUTE_GROUP_DOC = NO
# Set the SUBGROUPING tag to YES to allow class member groups of the same type
# (for instance a group of public functions) to be put as a subgroup of that
# type (e.g. under the Public Functions section). Set it to NO to prevent
# subgrouping. Alternatively, this can be done per class using the
# \nosubgrouping command.
# The default value is: YES.
SUBGROUPING = YES
# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions
# are shown inside the group in which they are included (e.g. using \ingroup)
# instead of on a separate page (for HTML and Man pages) or section (for LaTeX
# and RTF).
#
# Note that this feature does not work in combination with
# SEPARATE_MEMBER_PAGES.
# The default value is: NO.
INLINE_GROUPED_CLASSES = NO
# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions
# with only public data fields or simple typedef fields will be shown inline in
# the documentation of the scope in which they are defined (i.e. file,
# namespace, or group documentation), provided this scope is documented. If set
# to NO, structs, classes, and unions are shown on a separate page (for HTML and
# Man pages) or section (for LaTeX and RTF).
# The default value is: NO.
INLINE_SIMPLE_STRUCTS = NO
# When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or
# enum is documented as struct, union, or enum with the name of the typedef. So
# typedef struct TypeS {} TypeT, will appear in the documentation as a struct
# with name TypeT. When disabled the typedef will appear as a member of a file,
# namespace, or class. And the struct will be named TypeS. This can typically be
# useful for C code in case the coding convention dictates that all compound
# types are typedef'ed and only the typedef is referenced, never the tag name.
# The default value is: NO.
TYPEDEF_HIDES_STRUCT = NO
# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This
# cache is used to resolve symbols given their name and scope. Since this can be
# an expensive process and often the same symbol appears multiple times in the
# code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small
# doxygen will become slower. If the cache is too large, memory is wasted. The
# cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range
# is 0..9, the default is 0, corresponding to a cache size of 2^16=65536
# symbols. At the end of a run doxygen will report the cache usage and suggest
# the optimal cache size from a speed point of view.
# Minimum value: 0, maximum value: 9, default value: 0.
LOOKUP_CACHE_SIZE = 0
#---------------------------------------------------------------------------
# Build related configuration options
#---------------------------------------------------------------------------
# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in
# documentation are documented, even if no documentation was available. Private
# class members and static file members will be hidden unless the
# EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES.
# Note: This will also disable the warnings about undocumented members that are
# normally produced when WARNINGS is set to YES.
# The default value is: NO.
EXTRACT_ALL = YES
# If the EXTRACT_PRIVATE tag is set to YES all private members of a class will
# be included in the documentation.
# The default value is: NO.
EXTRACT_PRIVATE = NO
# If the EXTRACT_PACKAGE tag is set to YES all members with package or internal
# scope will be included in the documentation.
# The default value is: NO.
EXTRACT_PACKAGE = NO
# If the EXTRACT_STATIC tag is set to YES all static members of a file will be
# included in the documentation.
# The default value is: NO.
EXTRACT_STATIC = YES
# 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
# only classes defined in header files are included. Does not have any effect
# for Java sources.
# The default value is: YES.
EXTRACT_LOCAL_CLASSES = NO
# This flag is only useful for Objective-C code. When set to YES local methods,
# which are defined in the implementation section but not in the interface are
# included in the documentation. If set to NO only methods in the interface are
# included.
# The default value is: NO.
EXTRACT_LOCAL_METHODS = NO
# If this flag is set to YES, the members of anonymous namespaces will be
# extracted and appear in the documentation as a namespace called
# 'anonymous_namespace{file}', where file will be replaced with the base name of
# the file that contains the anonymous namespace. By default anonymous namespace
# are hidden.
# The default value is: NO.
EXTRACT_ANON_NSPACES = NO
# If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all
# undocumented members inside documented classes or files. If set to NO these
# members will be included in the various overviews, but no documentation
# section is generated. This option has no effect if EXTRACT_ALL is enabled.
# The default value is: NO.
HIDE_UNDOC_MEMBERS = NO
# If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all
# undocumented classes that are normally visible in the class hierarchy. If set
# to NO these classes will be included in the various overviews. This option has
# no effect if EXTRACT_ALL is enabled.
# The default value is: NO.
HIDE_UNDOC_CLASSES = NO
# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend
# (class|struct|union) declarations. If set to NO these declarations will be
# included in the documentation.
# The default value is: NO.
HIDE_FRIEND_COMPOUNDS = NO
# If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any
# documentation blocks found inside the body of a function. If set to NO these
# blocks will be appended to the function's detailed documentation block.
# The default value is: NO.
HIDE_IN_BODY_DOCS = NO
# The INTERNAL_DOCS tag determines if documentation that is typed after a
# \internal command is included. If the tag is set to NO then the documentation
# will be excluded. Set it to YES to include the internal documentation.
# The default value is: NO.
INTERNAL_DOCS = NO
# If the CASE_SENSE_NAMES tag is set to NO then doxygen will only generate file
# names in lower-case letters. If set to YES upper-case letters are also
# allowed. This is useful if you have classes or files whose names only differ
# in case and if your file system supports case sensitive file names. Windows
# and Mac users are advised to set this option to NO.
# The default value is: system dependent.
CASE_SENSE_NAMES = YES
# If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with
# their full class and namespace scopes in the documentation. If set to YES the
# scope will be hidden.
# The default value is: NO.
HIDE_SCOPE_NAMES = NO
# If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of
# the files that are included by a file in the documentation of that file.
# The default value is: YES.
SHOW_INCLUDE_FILES = NO
# If the SHOW_GROUPED_MEMB_INC tag is set to YES then Doxygen will add for each
# grouped member an include statement to the documentation, telling the reader
# which file to include in order to use the member.
# The default value is: NO.
SHOW_GROUPED_MEMB_INC = NO
# If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include
# files with double quotes in the documentation rather than with sharp brackets.
# The default value is: NO.
FORCE_LOCAL_INCLUDES = NO
# If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the
# documentation for inline members.
# The default value is: YES.
INLINE_INFO = YES
# If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the
# (detailed) documentation of file and class members alphabetically by member
# name. If set to NO the members will appear in declaration order.
# The default value is: YES.
SORT_MEMBER_DOCS = YES
# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief
# descriptions of file, namespace and class members alphabetically by member
# name. If set to NO the members will appear in declaration order. Note that
# this will also influence the order of the classes in the class list.
# The default value is: NO.
SORT_BRIEF_DOCS = NO
# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the
# (brief and detailed) documentation of class members so that constructors and
# destructors are listed first. If set to NO the constructors will appear in the
# respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS.
# Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief
# member documentation.
# Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting
# detailed member documentation.
# The default value is: NO.
SORT_MEMBERS_CTORS_1ST = NO
# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy
# of group names into alphabetical order. If set to NO the group names will
# appear in their defined order.
# The default value is: NO.
SORT_GROUP_NAMES = NO
# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by
# fully-qualified names, including namespaces. If set to NO, the class list will
# be sorted only by class name, not including the namespace part.
# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES.
# Note: This option applies only to the class list, not to the alphabetical
# list.
# The default value is: NO.
SORT_BY_SCOPE_NAME = NO
# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper
# type resolution of all parameters of a function it will reject a match between
# the prototype and the implementation of a member function even if there is
# only one candidate or it is obvious which candidate to choose by doing a
# simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still
# accept a match between prototype and implementation in such cases.
# The default value is: NO.
STRICT_PROTO_MATCHING = NO
# The GENERATE_TODOLIST tag can be used to enable ( YES) or disable ( NO) the
# todo list. This list is created by putting \todo commands in the
# documentation.
# The default value is: YES.
GENERATE_TODOLIST = YES
# The GENERATE_TESTLIST tag can be used to enable ( YES) or disable ( NO) the
# test list. This list is created by putting \test commands in the
# documentation.
# The default value is: YES.
GENERATE_TESTLIST = YES
# The GENERATE_BUGLIST tag can be used to enable ( YES) or disable ( NO) the bug
# list. This list is created by putting \bug commands in the documentation.
# The default value is: YES.
GENERATE_BUGLIST = YES
# The GENERATE_DEPRECATEDLIST tag can be used to enable ( YES) or disable ( NO)
# the deprecated list. This list is created by putting \deprecated commands in
# the documentation.
# The default value is: YES.
GENERATE_DEPRECATEDLIST= YES
# The ENABLED_SECTIONS tag can be used to enable conditional documentation
# sections, marked by \if ... \endif and \cond
# ... \endcond blocks.
ENABLED_SECTIONS =
# The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the
# initial value of a variable or macro / define can have for it to appear in the
# documentation. If the initializer consists of more lines than specified here
# it will be hidden. Use a value of 0 to hide initializers completely. The
# appearance of the value of individual variables and macros / defines can be
# controlled using \showinitializer or \hideinitializer command in the
# documentation regardless of this setting.
# Minimum value: 0, maximum value: 10000, default value: 30.
MAX_INITIALIZER_LINES = 30
# Set the SHOW_USED_FILES tag to NO to disable the list of files generated at
# the bottom of the documentation of classes and structs. If set to YES the list
# will mention the files that were used to generate the documentation.
# The default value is: YES.
SHOW_USED_FILES = YES
# Set the SHOW_FILES tag to NO to disable the generation of the Files page. This
# will remove the Files entry from the Quick Index and from the Folder Tree View
# (if specified).
# The default value is: YES.
SHOW_FILES = YES
# Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces
# page. This will remove the Namespaces entry from the Quick Index and from the
# Folder Tree View (if specified).
# The default value is: YES.
SHOW_NAMESPACES = YES
# The FILE_VERSION_FILTER tag can be used to specify a program or script that
# doxygen should invoke to get the current version for each file (typically from
# the version control system). Doxygen will invoke the program by executing (via
# popen()) the command command input-file, where command is the value of the
# FILE_VERSION_FILTER tag, and input-file is the name of an input file provided
# by doxygen. Whatever the program writes to standard output is used as the file
# version. For an example see the documentation.
FILE_VERSION_FILTER =
# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed
# by doxygen. The layout file controls the global structure of the generated
# output files in an output format independent way. To create the layout file
# that represents doxygen's defaults, run doxygen with the -l option. You can
# optionally specify a file name after the option, if omitted DoxygenLayout.xml
# will be used as the name of the layout file.
#
# Note that if you run doxygen from a directory containing a file called
# DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE
# tag is left empty.
LAYOUT_FILE =
# 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
# extension is automatically appended if omitted. This requires the bibtex tool
# 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
# 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.
CITE_BIB_FILES =
#---------------------------------------------------------------------------
# Configuration options related to warning and progress messages
#---------------------------------------------------------------------------
# The QUIET tag can be used to turn on/off the messages that are generated to
# standard output by doxygen. If QUIET is set to YES this implies that the
# messages are off.
# The default value is: NO.
QUIET = NO
# The WARNINGS tag can be used to turn on/off the warning messages that are
# generated to standard error ( stderr) by doxygen. If WARNINGS is set to YES
# this implies that the warnings are on.
#
# Tip: Turn warnings on while writing the documentation.
# The default value is: YES.
WARNINGS = YES
# If the WARN_IF_UNDOCUMENTED tag is set to YES, then doxygen will generate
# warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag
# will automatically be disabled.
# The default value is: YES.
WARN_IF_UNDOCUMENTED = YES
# If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for
# potential errors in the documentation, such as not documenting some parameters
# in a documented function, or documenting parameters that don't exist or using
# markup commands wrongly.
# The default value is: YES.
WARN_IF_DOC_ERROR = YES
# This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that
# are documented, but have no documentation for their parameters or return
# value. If set to NO doxygen will only warn about wrong or incomplete parameter
# documentation, but not about the absence of documentation.
# The default value is: NO.
WARN_NO_PARAMDOC = NO
# The WARN_FORMAT tag determines the format of the warning messages that doxygen
# can produce. The string should contain the $file, $line, and $text tags, which
# will be replaced by the file and line number from which the warning originated
# and the warning text. Optionally the format may contain $version, which will
# be replaced by the version of the file (if it could be obtained via
# FILE_VERSION_FILTER)
# The default value is: $file:$line: $text.
WARN_FORMAT = "$file:$line: $text"
# The WARN_LOGFILE tag can be used to specify a file to which warning and error
# messages should be written. If left blank the output is written to standard
# error (stderr).
WARN_LOGFILE =
#---------------------------------------------------------------------------
# Configuration options related to the input files
#---------------------------------------------------------------------------
# The INPUT tag is used to specify the files and/or directories that contain
# documented source files. You may enter file names like myfile.cpp or
# directories like /usr/src/myproject. Separate the files or directories with
# spaces.
# Note: If this tag is empty the current directory is searched.
INPUT = @CMAKE_SOURCE_DIR@ @CMAKE_BINARY_DIR@
# 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
# libiconv (or the iconv built into libc) for the transcoding. See the libiconv
# documentation (see: https://www.gnu.org/software/libiconv) for the list of
# possible encodings.
# The default value is: UTF-8.
INPUT_ENCODING = UTF-8
# If the value of the INPUT tag contains directories, you can use the
# FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and
# *.h) to filter out the source-files in the directories. If left blank the
# following patterns are tested:*.c, *.cc, *.cxx, *.cpp, *.c++, *.java, *.ii,
# *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h, *.hh, *.hxx, *.hpp,
# *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc, *.m, *.markdown,
# *.md, *.mm, *.dox, *.py, *.f90, *.f, *.for, *.tcl, *.vhd, *.vhdl, *.ucf,
# *.qsf, *.as and *.js.
FILE_PATTERNS = *.h \
*.md
# The RECURSIVE tag can be used to specify whether or not subdirectories should
# be searched for input files as well.
# The default value is: NO.
RECURSIVE = NO
# The EXCLUDE tag can be used to specify files and/or directories that should be
# excluded from the INPUT source files. This way you can easily exclude a
# subdirectory from a directory tree whose root is specified with the INPUT tag.
#
# Note that relative paths are relative to the directory from which doxygen is
# run.
EXCLUDE =
# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or
# directories that are symbolic links (a Unix file system feature) are excluded
# from the input.
# The default value is: NO.
EXCLUDE_SYMLINKS = NO
# If the value of the INPUT tag contains directories, you can use the
# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude
# certain files from those directories.
#
# 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_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
# (namespaces, classes, functions, etc.) that should be excluded from the
# output. The symbol name can be a fully qualified name, a word, or if the
# wildcard * is used, a substring. Examples: ANamespace, AClass,
# AClass::ANamespace, ANamespace::*Test
#
# Note that the wildcards are matched against the file with absolute path, so to
# exclude all test directories use the pattern */test/*
EXCLUDE_SYMBOLS = \
_json_c_* \
_LH_* \
_printbuf_* \
__STRING
# 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
# command).
EXAMPLE_PATH =
# If the value of the EXAMPLE_PATH tag contains directories, you can use the
# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and
# *.h) to filter out the source-files in the directories. If left blank all
# files are included.
EXAMPLE_PATTERNS =
# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be
# searched for input files to be used with the \include or \dontinclude commands
# irrespective of the value of the RECURSIVE tag.
# The default value is: NO.
EXAMPLE_RECURSIVE = NO
# The IMAGE_PATH tag can be used to specify one or more files or directories
# that contain images that are to be included in the documentation (see the
# \image command).
IMAGE_PATH =
# The INPUT_FILTER tag can be used to specify a program that doxygen should
# invoke to filter for each input file. Doxygen will invoke the filter program
# by executing (via popen()) the command:
#
#
#
# where is the value of the INPUT_FILTER tag, and is the
# name of an input file. Doxygen will then use the output that the filter
# program writes to standard output. If FILTER_PATTERNS is specified, this tag
# will be ignored.
#
# Note that the filter must not add or remove lines; it is applied before the
# code is scanned, but not when the output code is generated. If lines are added
# or removed, the anchors will not be placed correctly.
INPUT_FILTER = @CMAKE_CURRENT_SOURCE_DIR@/fixup_markdown.sh
# 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
# filter if there is a match. The filters are a list of the form: pattern=filter
# (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how
# filters are used. If the FILTER_PATTERNS tag is empty or if none of the
# patterns match the file name, INPUT_FILTER is applied.
FILTER_PATTERNS =
# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using
# INPUT_FILTER ) will also be used to filter the input files that are used for
# producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES).
# The default value is: NO.
FILTER_SOURCE_FILES = NO
# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file
# pattern. A pattern will override the setting for FILTER_PATTERN (if any) and
# it is also possible to disable source filtering for a specific pattern using
# *.ext= (so without naming a filter).
# This tag requires that the tag FILTER_SOURCE_FILES is set to YES.
FILTER_SOURCE_PATTERNS =
# If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that
# is part of the input, its contents will be placed on the main page
# (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.
USE_MDFILE_AS_MAINPAGE = README.md
#---------------------------------------------------------------------------
# Configuration options related to source browsing
#---------------------------------------------------------------------------
# If the SOURCE_BROWSER tag is set to YES then a list of source files will be
# generated. Documented entities will be cross-referenced with these sources.
#
# Note: To get rid of all source code in the generated output, make sure that
# also VERBATIM_HEADERS is set to NO.
# The default value is: NO.
SOURCE_BROWSER = NO
# Setting the INLINE_SOURCES tag to YES will include the body of functions,
# classes and enums directly into the documentation.
# The default value is: NO.
INLINE_SOURCES = NO
# Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any
# special comment blocks from generated source code fragments. Normal C, C++ and
# Fortran comments will always remain visible.
# The default value is: YES.
STRIP_CODE_COMMENTS = YES
# If the REFERENCED_BY_RELATION tag is set to YES then for each documented
# function all documented functions referencing it will be listed.
# The default value is: NO.
REFERENCED_BY_RELATION = YES
# If the REFERENCES_RELATION tag is set to YES then for each documented function
# all documented entities called/used by that function will be listed.
# The default value is: NO.
REFERENCES_RELATION = YES
# If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set
# to YES, then the hyperlinks from functions in REFERENCES_RELATION and
# REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will
# link to the documentation.
# The default value is: YES.
REFERENCES_LINK_SOURCE = YES
# If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the
# source code will show a tooltip with additional information such as prototype,
# brief description and links to the definition and documentation. Since this
# will make the HTML file larger and loading of large files a bit slower, you
# can opt to disable this feature.
# The default value is: YES.
# This tag requires that the tag SOURCE_BROWSER is set to YES.
SOURCE_TOOLTIPS = YES
# 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
# source browser. The htags tool is part of GNU's global source tagging system
# (see https://www.gnu.org/software/global/global.html). You will need version
# 4.8.6 or higher.
#
# To use it do the following:
# - Install the latest version of global
# - Enable SOURCE_BROWSER and USE_HTAGS in the config file
# - Make sure the INPUT points to the root of the source tree
# - Run doxygen as normal
#
# Doxygen will invoke htags (and that will in turn invoke gtags), so these
# tools must be available from the command line (i.e. in the search path).
#
# The result: instead of the source browser generated by doxygen, the links to
# source code will now point to the output of htags.
# The default value is: NO.
# This tag requires that the tag SOURCE_BROWSER is set to YES.
USE_HTAGS = NO
# If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a
# verbatim copy of the header file for each class for which an include is
# specified. Set to NO to disable this.
# See also: Section \class.
# The default value is: YES.
VERBATIM_HEADERS = NO
# If the CLANG_ASSISTED_PARSING tag is set to YES, then doxygen will use 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
# rich C++ code for which doxygen's built-in parser lacks the necessary type
# information.
# Note: The availability of this option depends on whether or not doxygen was
# compiled with the --with-libclang option.
# The default value is: NO.
#CLANG_ASSISTED_PARSING = NO
# If clang assisted parsing is enabled you can provide the compiler with command
# line options that you would normally use when invoking the compiler. Note that
# the include paths will already be set by doxygen for the files and directories
# specified with INPUT and INCLUDE_PATH.
# This tag requires that the tag CLANG_ASSISTED_PARSING is set to YES.
#CLANG_OPTIONS =
#---------------------------------------------------------------------------
# Configuration options related to the alphabetical class index
#---------------------------------------------------------------------------
# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all
# compounds will be generated. Enable this if the project contains a lot of
# classes, structs, unions or interfaces.
# The default value is: YES.
ALPHABETICAL_INDEX = NO
# The COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns in
# which the alphabetical index list will be split.
# Minimum value: 1, maximum value: 20, default value: 5.
# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.
COLS_IN_ALPHA_INDEX = 5
# In case all classes in a project start with a common prefix, all classes will
# be put under the same header in the alphabetical index. The IGNORE_PREFIX tag
# can be used to specify a prefix (or a list of prefixes) that should be ignored
# while generating the index headers.
# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.
IGNORE_PREFIX =
#---------------------------------------------------------------------------
# Configuration options related to the HTML output
#---------------------------------------------------------------------------
# If the GENERATE_HTML tag is set to YES doxygen will generate HTML output
# The default value is: YES.
GENERATE_HTML = YES
# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a
# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
# it.
# The default directory is: html.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_OUTPUT = html
# The HTML_FILE_EXTENSION tag can be used to specify the file extension for each
# generated HTML page (for example: .htm, .php, .asp).
# The default value is: .html.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_FILE_EXTENSION = .html
# The HTML_HEADER tag can be used to specify a user-defined HTML header file for
# each generated HTML page. If the tag is left blank doxygen will generate a
# standard header.
#
# To get valid HTML the header file that includes any scripts and style sheets
# that doxygen needs, which is dependent on the configuration options used (e.g.
# the setting GENERATE_TREEVIEW). It is highly recommended to start with a
# default header using
# doxygen -w html new_header.html new_footer.html new_stylesheet.css
# YourConfigFile
# and then modify the file new_header.html. See also section "Doxygen usage"
# for information on how to generate the default header that doxygen normally
# uses.
# Note: The header is subject to change so you typically have to regenerate the
# default header when upgrading to a newer version of doxygen. For a description
# of the possible markers and block names see the documentation.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_HEADER =
# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each
# generated HTML page. If the tag is left blank doxygen will generate a standard
# footer. See HTML_HEADER for more information on how to generate a default
# footer and what special commands can be used inside the footer. See also
# section "Doxygen usage" for information on how to generate the default footer
# that doxygen normally uses.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_FOOTER =
# The HTML_STYLESHEET tag can be used to specify a user-defined cascading style
# sheet that is used by each HTML page. It can be used to fine-tune the look of
# the HTML output. If left blank doxygen will generate a default style sheet.
# See also section "Doxygen usage" for information on how to generate the style
# sheet that doxygen normally uses.
# Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as
# it is more robust and this tag (HTML_STYLESHEET) will in the future become
# obsolete.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_STYLESHEET =
# The HTML_EXTRA_STYLESHEET tag can be used to specify additional user-defined
# cascading style sheets that are included after the standard style sheets
# 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
# standard style sheet and is therefore more robust against future updates.
# 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
# stylesheet in the list overrules the setting of the previous ones in the
# list). For an example see the documentation.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_EXTRA_STYLESHEET =
# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or
# other source files which should be copied to the HTML output directory. Note
# that these files will be copied to the base HTML output directory. Use the
# $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these
# files. In the HTML_STYLESHEET file, use the file name only. Also note that the
# files will be copied as-is; there are no commands or markers available.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_EXTRA_FILES =
# 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
# this color. Hue is specified as an angle on a colorwheel, see
# 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
# purple, and 360 is red again.
# Minimum value: 0, maximum value: 359, default value: 220.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_COLORSTYLE_HUE = 220
# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors
# in the HTML output. For a value of 0 the output will use grayscales only. A
# value of 255 will produce the most vivid colors.
# Minimum value: 0, maximum value: 255, default value: 100.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_COLORSTYLE_SAT = 100
# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the
# luminance component of the colors in the HTML output. Values below 100
# gradually make the output lighter, whereas values above 100 make the output
# darker. The value divided by 100 is the actual gamma applied, so 80 represents
# a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not
# change the gamma.
# Minimum value: 40, maximum value: 240, default value: 80.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_COLORSTYLE_GAMMA = 80
# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML
# page will contain the date and time when the page was generated. Setting this
# to NO can help when comparing the output of multiple runs.
# The default value is: YES.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_TIMESTAMP = YES
# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML
# documentation will contain sections that can be hidden and shown after the
# page has loaded.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_DYNAMIC_SECTIONS = NO
# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries
# shown in the various tree structured indices initially; the user can expand
# and collapse entries dynamically later on. Doxygen will expand the tree to
# such a level that at most the specified number of entries are visible (unless
# a fully collapsed tree already exceeds this amount). So setting the number of
# entries 1 will produce a full collapsed tree by default. 0 is a special value
# representing an infinite number of entries and will result in a full expanded
# tree by default.
# Minimum value: 0, maximum value: 9999, default value: 100.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_INDEX_NUM_ENTRIES = 100
# 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
# environment (see: https://developer.apple.com/tools/xcode/), introduced with
# 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
# that directory and running make install will install the docset in
# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at
# startup. See
# https://developer.apple.com/library/archive/featuredarticles/DoxygenXcode/
# for more information.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
GENERATE_DOCSET = NO
# This tag determines the name of the docset feed. A documentation feed provides
# an umbrella under which multiple documentation sets from a single provider
# (such as a company or product suite) can be grouped.
# The default value is: Doxygen generated docs.
# This tag requires that the tag GENERATE_DOCSET is set to YES.
DOCSET_FEEDNAME = "Doxygen generated docs"
# This tag specifies a string that should uniquely identify the documentation
# set bundle. This should be a reverse domain-name style string, e.g.
# com.mycompany.MyDocSet. Doxygen will append .docset to the name.
# The default value is: org.doxygen.Project.
# This tag requires that the tag GENERATE_DOCSET is set to YES.
DOCSET_BUNDLE_ID = org.doxygen.Project
# The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify
# the documentation publisher. This should be a reverse domain-name style
# string, e.g. com.mycompany.MyDocSet.documentation.
# The default value is: org.doxygen.Publisher.
# This tag requires that the tag GENERATE_DOCSET is set to YES.
DOCSET_PUBLISHER_ID = org.doxygen.Publisher
# The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher.
# The default value is: Publisher.
# This tag requires that the tag GENERATE_DOCSET is set to YES.
DOCSET_PUBLISHER_NAME = Publisher
# If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three
# additional HTML index files: index.hhp, index.hhc, and index.hhk. The
# index.hhp is a project file that can be read by Microsoft's HTML Help Workshop
# (see: http://www.microsoft.com/en-us/download/details.aspx?id=21138) on
# Windows.
#
# The HTML Help Workshop contains a compiler that can convert all HTML output
# generated by doxygen into a single compiled HTML file (.chm). Compiled HTML
# files are now used as the Windows 98 help format, and will replace the old
# Windows help format (.hlp) on all Windows platforms in the future. Compressed
# HTML files also contain an index, a table of contents, and you can search for
# words in the documentation. The HTML workshop also contains a viewer for
# compressed HTML files.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
GENERATE_HTMLHELP = NO
# The CHM_FILE tag can be used to specify the file name of the resulting .chm
# file. You can add a path in front of the file if the result should not be
# written to the html output directory.
# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
CHM_FILE =
# The HHC_LOCATION tag can be used to specify the location (absolute path
# including file name) of the HTML help compiler ( hhc.exe). If non-empty
# doxygen will try to run the HTML help compiler on the generated index.hhp.
# The file has to be specified with full path.
# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
HHC_LOCATION =
# The GENERATE_CHI flag controls if a separate .chi index file is generated (
# YES) or that it should be included in the master .chm file ( NO).
# The default value is: NO.
# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
GENERATE_CHI = NO
# The CHM_INDEX_ENCODING is used to encode HtmlHelp index ( hhk), content ( hhc)
# and project file content.
# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
CHM_INDEX_ENCODING =
# The BINARY_TOC flag controls whether a binary table of contents is generated (
# YES) or a normal table of contents ( NO) in the .chm file. Furthermore it
# enables the Previous and Next buttons.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
BINARY_TOC = NO
# The TOC_EXPAND flag can be set to YES to add extra items for group members to
# the table of contents of the HTML help documentation and to the tree view.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
TOC_EXPAND = NO
# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and
# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that
# can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help
# (.qch) of the generated HTML documentation.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
GENERATE_QHP = NO
# If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify
# the file name of the resulting .qch file. The path specified is relative to
# the HTML output folder.
# This tag requires that the tag GENERATE_QHP is set to YES.
QCH_FILE =
# The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help
# Project output. For more information please see Qt Help Project / Namespace
# (see: https://doc.qt.io/archives/qt-4.8/qthelpproject.html#namespace).
# The default value is: org.doxygen.Project.
# This tag requires that the tag GENERATE_QHP is set to YES.
QHP_NAMESPACE = org.doxygen.Project
# 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
# Folders (see:
# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#virtual-folders).
# The default value is: doc.
# This tag requires that the tag GENERATE_QHP is set to YES.
QHP_VIRTUAL_FOLDER = doc
# 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
# Filters (see:
# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom-filters).
# This tag requires that the tag GENERATE_QHP is set to YES.
QHP_CUST_FILTER_NAME =
# 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
# Filters (see:
# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom-filters).
# This tag requires that the tag GENERATE_QHP is set to YES.
QHP_CUST_FILTER_ATTRS =
# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this
# project's filter section matches. Qt Help Project / Filter Attributes (see:
# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#filter-attributes).
# This tag requires that the tag GENERATE_QHP is set to YES.
QHP_SECT_FILTER_ATTRS =
# The QHG_LOCATION tag can be used to specify the location of Qt's
# qhelpgenerator. If non-empty doxygen will try to run qhelpgenerator on the
# generated .qhp file.
# This tag requires that the tag GENERATE_QHP is set to YES.
QHG_LOCATION =
# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be
# generated, together with the HTML files, they form an Eclipse help plugin. To
# install this plugin and make it available under the help contents menu in
# Eclipse, the contents of the directory containing the HTML and XML files needs
# to be copied into the plugins directory of eclipse. The name of the directory
# within the plugins directory should be the same as the ECLIPSE_DOC_ID value.
# After copying Eclipse needs to be restarted before the help appears.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
GENERATE_ECLIPSEHELP = NO
# A unique identifier for the Eclipse help plugin. When installing the plugin
# the directory name containing the HTML and XML files should also have this
# name. Each documentation set should have its own identifier.
# The default value is: org.doxygen.Project.
# This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES.
ECLIPSE_DOC_ID = org.doxygen.Project
# If you want full control over the layout of the generated HTML pages it might
# be necessary to disable the index and replace it with your own. The
# DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top
# of each HTML page. A value of NO enables the index and the value YES disables
# it. Since the tabs in the index contain the same information as the navigation
# tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
DISABLE_INDEX = NO
# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index
# structure should be generated to display hierarchical information. If the tag
# value is set to YES, a side panel will be generated containing a tree-like
# index structure (just like the one that is generated for HTML Help). For this
# to work a browser that supports JavaScript, DHTML, CSS and frames is required
# (i.e. any modern browser). Windows users are probably better off using the
# HTML help feature. Via custom stylesheets (see HTML_EXTRA_STYLESHEET) one can
# further fine-tune the look of the index. As an example, the default style
# sheet generated by doxygen has an example that shows how to put an image at
# the root of the tree instead of the PROJECT_NAME. Since the tree basically has
# the same information as the tab index, you could consider setting
# DISABLE_INDEX to YES when enabling this option.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
GENERATE_TREEVIEW = NO
# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that
# doxygen will group on one line in the generated HTML documentation.
#
# Note that a value of 0 will completely suppress the enum values from appearing
# in the overview section.
# Minimum value: 0, maximum value: 20, default value: 4.
# This tag requires that the tag GENERATE_HTML is set to YES.
ENUM_VALUES_PER_LINE = 4
# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used
# to set the initial width (in pixels) of the frame in which the tree is shown.
# Minimum value: 0, maximum value: 1500, default value: 250.
# This tag requires that the tag GENERATE_HTML is set to YES.
TREEVIEW_WIDTH = 250
# When the EXT_LINKS_IN_WINDOW option is set to YES doxygen will open links to
# external symbols imported via tag files in a separate window.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
EXT_LINKS_IN_WINDOW = NO
# Use this tag to change the font size of LaTeX formulas included as images in
# the HTML documentation. When you change the font size after a successful
# doxygen run you need to manually remove any form_*.png images from the HTML
# output directory to force them to be regenerated.
# Minimum value: 8, maximum value: 50, default value: 10.
# This tag requires that the tag GENERATE_HTML is set to YES.
FORMULA_FONTSIZE = 10
# Use the FORMULA_TRANPARENT tag to determine whether or not the images
# generated for formulas are transparent PNGs. Transparent PNGs are not
# supported properly for IE 6.0, but are supported on all modern browsers.
#
# Note that when changing this option you need to delete any form_*.png files in
# the HTML output directory before the changes have effect.
# The default value is: YES.
# This tag requires that the tag GENERATE_HTML is set to YES.
FORMULA_TRANSPARENT = YES
# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see
# 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
# 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
# to it using the MATHJAX_RELPATH option.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
USE_MATHJAX = NO
# When MathJax is enabled you can set the default output format to be used for
# the MathJax output. See the MathJax site (see:
# https://docs.mathjax.org/en/latest/output/) for more details.
# Possible values are: HTML-CSS (which is slower, but has the best
# compatibility), NativeMML (i.e. MathML) and SVG.
# The default value is: HTML-CSS.
# This tag requires that the tag USE_MATHJAX is set to YES.
MATHJAX_FORMAT = HTML-CSS
# When MathJax is enabled you need to specify the location relative to the HTML
# output directory using the MATHJAX_RELPATH option. The destination directory
# should contain the MathJax.js script. For instance, if the mathjax directory
# is located at the same level as the HTML output directory, then
# MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax
# 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 from https://www.mathjax.org before deployment.
# The default value is: https://cdn.mathjax.org/mathjax/latest.
# This tag requires that the tag USE_MATHJAX is set to YES.
MATHJAX_RELPATH = https://cdn.mathjax.org/mathjax/latest
# The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax
# extension names that should be enabled during MathJax rendering. For example
# MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols
# This tag requires that the tag USE_MATHJAX is set to YES.
MATHJAX_EXTENSIONS =
# 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
# (see: https://docs.mathjax.org/en/latest/output/) for more details. For an
# example see the documentation.
# This tag requires that the tag USE_MATHJAX is set to YES.
MATHJAX_CODEFILE =
# When the SEARCHENGINE tag is enabled doxygen will generate a search box for
# the HTML output. The underlying search engine uses javascript and DHTML and
# should work on any modern browser. Note that when using HTML help
# (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET)
# there is already a search function so this one should typically be disabled.
# For large projects the javascript based search engine can be slow, then
# enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to
# search using the keyboard; to jump to the search box use + S
# (what the is depends on the OS and browser, but it is typically
# , /