[修改] 增加freeRTOS

1. 版本FreeRTOSv202212.01,命名为kernel;
This commit is contained in:
2023-05-06 16:43:01 +00:00
commit a345df017b
20944 changed files with 11094377 additions and 0 deletions

View File

@ -0,0 +1,63 @@
# Contributing Guidelines
Thank you for your interest in contributing to our project. Whether it's a bug report, new feature, correction, or additional
documentation, we greatly value feedback and contributions from our community.
Please read through this document before submitting any issues or pull requests to ensure we have all the necessary
information to effectively respond to your bug report or contribution.
## Reporting Bugs/Feature Requests
We welcome you to use the GitHub issue tracker to report bugs or suggest features.
When filing an issue, please check [existing open](https://github.com/FreeRTOS/coreJSON/issues), or [recently closed](https://github.com/FreeRTOS/coreJSON/issues?q=is%3Aissue+is%3Aclosed), issues to make sure somebody else hasn't already
reported the issue. Please try to include as much information as you can. Details like these are incredibly useful:
* A reproducible test case or series of steps
* The version of our code being used
* Any modifications you've made relevant to the bug
* Anything unusual about your environment or deployment
## Contributing via Pull Requests
Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that:
1. You are working against the latest source on the *main* branch.
1. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already.
1. You open an issue to discuss any significant work - we would hate for your time to be wasted.
To send us a pull request, please:
1. Fork the repository.
1. Modify the source; please focus on the specific change you are contributing. If you also reformat all the code, it will be hard for us to focus on your change.
1. Ensure that your contributions conform to the [style guide](https://docs.aws.amazon.com/embedded-csdk/202011.00/lib-ref/docs/doxygen/output/html/guide_developer_styleguide.html).
1. Format your code with uncrustify, using the config available in [FreeRTOS/CI-CD-Github-Actions](https://github.com/FreeRTOS/CI-CD-Github-Actions/blob/main/formatting/uncrustify.cfg).
1. Ensure local tests pass.
1. Commit to your fork using clear commit messages.
1. Send us a pull request, answering any default questions in the pull request interface.
1. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation.
GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and
[creating a pull request](https://help.github.com/articles/creating-a-pull-request/).
## Finding contributions to work on
Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels ((enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any ['help wanted'](https://github.com/FreeRTOS/coreJSON/labels?q=help+wanted) issues is a great place to start.
## Code of Conduct
This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct).
For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact
opensource-codeofconduct@amazon.com with any additional questions or comments.
## Security issue notifications
If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](https://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue.
## Licensing
See the [LICENSE](../LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution.
We may ask you to sign a [Contributor License Agreement (CLA)](https://en.wikipedia.org/wiki/Contributor_License_Agreement) for larger changes.

View File

@ -0,0 +1,9 @@
{
"lib_name" : "coreJSON",
"src": [
"source/core_json.c"
],
"include": [
"source/include"
]
}

View File

@ -0,0 +1,116 @@
name: CI Checks
on:
push:
branches: ["**"]
pull_request:
branches: [main]
workflow_dispatch:
jobs:
unittest:
runs-on: ubuntu-latest
steps:
- name: Clone This Repo
uses: actions/checkout@v2
- name: Build
run: |
sudo apt-get install -y lcov sed
cmake -S test -B build/ \
-G "Unix Makefiles" \
-DCMAKE_BUILD_TYPE=Debug \
-DBUILD_CLONE_SUBMODULES=ON \
-DCMAKE_C_FLAGS='--coverage -Wall -Wextra -Werror'
make -C build/ all
- name: Test
run: |
cd build/
ctest -E system --output-on-failure
cd ..
- name: Run Coverage
run: |
make -C build/ coverage
declare -a EXCLUDE=("\*test\*" "\*CMakeCCompilerId\*" "\*mocks\*" "\*source\*")
echo ${EXCLUDE[@]} | xargs lcov --rc lcov_branch_coverage=1 -r build/coverage.info -o build/coverage.info
lcov --rc lcov_branch_coverage=1 --list build/coverage.info
- name: Check Coverage
uses: FreeRTOS/CI-CD-Github-Actions/coverage-cop@main
with:
path: ./build/coverage.info
complexity:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Check complexity
uses: FreeRTOS/CI-CD-Github-Actions/complexity@main
with:
path: ./
doxygen:
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v2
- name: Run doxygen build
uses: FreeRTOS/CI-CD-Github-Actions/doxygen@main
with:
path: ./
spell-check:
runs-on: ubuntu-latest
steps:
- name: Clone This Repo
uses: actions/checkout@v2
- name: Run spellings check
uses: FreeRTOS/CI-CD-Github-Actions/spellings@main
with:
path: ./
formatting:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Check formatting
uses: FreeRTOS/CI-CD-Github-Actions/formatting@main
with:
path: ./
git-secrets:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Checkout awslabs/git-secrets
uses: actions/checkout@v2
with:
repository: awslabs/git-secrets
ref: master
path: git-secrets
- name: Install git-secrets
run: cd git-secrets && sudo make install && cd ..
- name: Run git-secrets
run: |
git-secrets --register-aws
git-secrets --scan
custom-standard-c-headers:
runs-on: ubuntu-latest
steps:
- name: Clone This Repo
uses: actions/checkout@v2
- name: Build
run: |
mkdir -p override-include
cp source/include/stdbool.readme override-include/stdbool.h
cp source/include/stdint.readme override-include/stdint.h
cmake -S test -B build/ \
-G "Unix Makefiles" \
-DBUILD_CLONE_SUBMODULES=ON \
-DCMAKE_C_FLAGS='-Wall -Wextra -I../override-include'
make -C build/ coverity_analysis
memory_statistics:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
submodules: 'recursive'
- name: Install Python3
uses: actions/setup-python@v2
with:
python-version: '3.7.10'
- name: Measure sizes
uses: FreeRTOS/CI-CD-Github-Actions/memory_statistics@main
with:
config: .github/memory_statistics_config.json
check_against: docs/doxygen/include/size_table.md

View File

@ -0,0 +1,11 @@
name: Doxygen Generation
on:
push:
branches: [main]
workflow_dispatch:
jobs:
doxygen-generation:
runs-on: ubuntu-latest
steps:
- name: Doxygen generation
uses: FreeRTOS/CI-CD-Github-Actions/doxygen-generation@main

View File

@ -0,0 +1,139 @@
name: Release automation
on:
workflow_dispatch:
inputs:
commit_id:
description: 'Commit ID to tag and create a release for'
required: true
version_number:
description: 'Release Version Number (Eg, v1.0.0)'
required: true
jobs:
tag-commit:
name: Tag commit
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v2
with:
ref: ${{ github.event.inputs.commit_id }}
- name: Configure git identity
run: |
git config --global user.name ${{ github.actor }}
git config --global user.email ${{ github.actor }}@users.noreply.github.com
- name: create a new branch that references commit id
run: git checkout -b ${{ github.event.inputs.version_number }} ${{ github.event.inputs.commit_id }}
- name: Generate SBOM
uses: FreeRTOS/CI-CD-Github-Actions/sbom-generator@main
with:
repo_path: ./
source_path: ./source
- name: commit SBOM file
run: |
git add .
git commit -m 'Update SBOM'
git push -u origin ${{ github.event.inputs.version_number }}
- name: Tag Commit and Push to remote
run: |
git tag ${{ github.event.inputs.version_number }} -a -m "coreJSON Library ${{ github.event.inputs.version_number }}"
git push origin --tags
- name: Verify tag on remote
run: |
git tag -d ${{ github.event.inputs.version_number }}
git remote update
git checkout tags/${{ github.event.inputs.version_number }}
git diff ${{ github.event.inputs.commit_id }} tags/${{ github.event.inputs.version_number }}
create-zip:
needs: tag-commit
name: Create ZIP and verify package for release asset.
runs-on: ubuntu-latest
steps:
- name: Install ZIP tools
run: sudo apt-get install zip unzip
- name: Checkout code
uses: actions/checkout@v2
with:
ref: ${{ github.event.inputs.commit_id }}
path: coreJSON
submodules: recursive
- name: Checkout disabled submodules
run: |
cd coreJSON
git submodule update --init --checkout --recursive
- name: Create ZIP
run: |
zip -r coreJSON-${{ github.event.inputs.version_number }}.zip coreJSON -x "*.git*"
ls ./
- name: Validate created ZIP
run: |
mkdir zip-check
mv coreJSON-${{ github.event.inputs.version_number }}.zip zip-check
cd zip-check
unzip coreJSON-${{ github.event.inputs.version_number }}.zip -d coreJSON-${{ github.event.inputs.version_number }}
ls coreJSON-${{ github.event.inputs.version_number }}
diff -r -x "*.git*" coreJSON-${{ github.event.inputs.version_number }}/coreJSON/ ../coreJSON/
cd ../
- name: Build
run: |
cd zip-check/coreJSON-${{ github.event.inputs.version_number }}/coreJSON
sudo apt-get install -y lcov
cmake -S test -B build/ \
-G "Unix Makefiles" \
-DCMAKE_BUILD_TYPE=Debug \
-DBUILD_CLONE_SUBMODULES=ON \
-DCMAKE_C_FLAGS='--coverage -Wall -Wextra -Werror'
make -C build/ all
- name: Test
run: |
cd zip-check/coreJSON-${{ github.event.inputs.version_number }}/coreJSON/build/
ctest -E system --output-on-failure
cd ..
- name: Create artifact of ZIP
uses: actions/upload-artifact@v2
with:
name: coreJSON-${{ github.event.inputs.version_number }}.zip
path: zip-check/coreJSON-${{ github.event.inputs.version_number }}.zip
deploy-doxygen:
needs: tag-commit
name: Deploy doxygen documentation
runs-on: ubuntu-latest
steps:
- name: Doxygen generation
uses: FreeRTOS/CI-CD-Github-Actions/doxygen-generation@main
with:
ref: ${{ github.event.inputs.version_number }}
add_release: "true"
create-release:
needs:
- create-zip
- deploy-doxygen
name: Create Release and Upload Release Asset
runs-on: ubuntu-latest
steps:
- name: Create Release
id: create_release
uses: actions/create-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tag_name: ${{ github.event.inputs.version_number }}
release_name: ${{ github.event.inputs.version_number }}
body: Release ${{ github.event.inputs.version_number }} of the coreJSON Library.
draft: false
prerelease: false
- name: Download ZIP artifact
uses: actions/download-artifact@v2
with:
name: coreJSON-${{ github.event.inputs.version_number }}.zip
- name: Upload Release Asset
id: upload-release-asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: ./coreJSON-${{ github.event.inputs.version_number }}.zip
asset_name: coreJSON-${{ github.event.inputs.version_number }}.zip
asset_content_type: application/zip

View File

@ -0,0 +1,13 @@
# Ignore documentation output.
**/docs/**/output/*
# Ignore CMake build directory.
build/
# Ignore build artifacts
*.o
# Ignore code coverage artifacts
*.gcda
*.gcno
*.gcov

View File

@ -0,0 +1,4 @@
[submodule "test/unit-test/Unity"]
path = test/unit-test/Unity
url = https://github.com/ThrowTheSwitch/Unity
update = none

View File

@ -0,0 +1,25 @@
path_classifiers:
library:
- exclude: /
extraction:
cpp:
index:
build_command:
- export 'CFLAGS=-Iinclude -ansi -Wall -Wextra -Wpedantic -Werror'
- make -C source core_json.o
csharp:
after_prepare:
- false
go:
after_prepare:
- false
java:
after_prepare:
- false
javascript:
after_prepare:
- false
python:
after_prepare:
- false

View File

@ -0,0 +1,38 @@
# Change Log for coreJSON Library
## v3.2.0 (October 2022)
- [#121](https://github.com/FreeRTOS/coreJSON/pull/121) MISRA C:2012 compliance updates.
- [#119](https://github.com/FreeRTOS/coreJSON/pull/119) Update CBMC Starter Kit.
- [#115](https://github.com/FreeRTOS/coreJSON/pull/115) Fix JSON validation for mismatched brackets.
- [#109](https://github.com/FreeRTOS/coreJSON/pull/109) Remove non-ASCII characters
## v3.1.0 (November 2021)
- [#106](https://github.com/FreeRTOS/coreJSON/pull/106) Update doxygen version for documentation.
## v3.0.2 (July 2021)
- [#100](https://github.com/FreeRTOS/coreJSON/pull/100) Fix overflow in skipOneHexEscape().
- [#95](https://github.com/FreeRTOS/coreJSON/pull/95) Eliminate warnings when base char type is unsigned.
- [#93](https://github.com/FreeRTOS/coreJSON/pull/93) Wrap query key separator macro with ifndef.
## v3.0.1 (February 2021)
- [#86](https://github.com/FreeRTOS/coreJSON/pull/86) Fix MISRA 9.1 violation.
- [#84](https://github.com/FreeRTOS/coreJSON/pull/84), [#82](https://github.com/FreeRTOS/coreJSON/pull/82) and [#80](https://github.com/FreeRTOS/coreJSON/pull/80) Documentation updates and fixes.
## v3.0.0 (December 2020)
- [#74](https://github.com/FreeRTOS/coreJSON/pull/74) Add `JSON_Iterate` function to iterate over items in a JSON collection.
- [#74](https://github.com/FreeRTOS/coreJSON/pull/74) Add `JSONInvalid` enum with the value 0 to `JSONTypes_t`. This change is not backwards compatible.
## v2.0.0 (November 2020)
### Updates
- [#53](https://github.com/FreeRTOS/coreJSON/pull/53) Update the `JSON_Search` function to support searching JSON arrays. This change is not backwards compatible.
### Other
- [#35](https://github.com/FreeRTOS/coreJSON/pull/35), [#36](https://github.com/FreeRTOS/coreJSON/pull/36), [#39](https://github.com/FreeRTOS/coreJSON/pull/39), [#51](https://github.com/FreeRTOS/coreJSON/pull/51), [#52](https://github.com/FreeRTOS/coreJSON/pull/52), [#54](https://github.com/FreeRTOS/coreJSON/pull/54) Minor documentation updates.
- [#40](https://github.com/FreeRTOS/coreJSON/pull/40) Build the unit tests with Unity instead of CMock.
- [#44](https://github.com/FreeRTOS/coreJSON/pull/44) Add 100% branch coverage to the unit tests.
- [#46](https://github.com/FreeRTOS/coreJSON/pull/46), [#49](https://github.com/FreeRTOS/coreJSON/pull/49) Fix warnings in the source code.
## v1.0.0 (September 2020)
This is the first release of the coreJSON library, a parser that strictly enforces the [ECMA-404 JSON standard](https://www.json.org/json-en.html) and is suitable for low memory footprint embedded devices.

View File

@ -0,0 +1,19 @@
MIT License
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.

View File

@ -0,0 +1,31 @@
# MISRA Compliance
The coreJSON library files conform to the [MISRA C:2012](https://www.misra.org.uk)
guidelines, with some noted exceptions. Compliance is checked with Coverity static analysis.
The specific deviations, suppressed inline, are listed below.
Additionally, [MISRA configuration file](https://github.com/FreeRTOS/coreJSON/blob/main/tools/coverity/misra.config) contains the project wide deviations.
### Suppressed with Coverity Comments
To find the violation references in the source files run grep on the source code
with ( Assuming rule 11.3 violation; with justification in point 1 ):
```
grep 'MISRA Ref 11.3.1' . -rI
```
#### Rule 11.3
_Ref 11.3.1_
- MISRA C-2012 Rule 11.3 prohibits casting a pointer to a different type.
This instance is a false positive, as the rule permits the
addition of a const type qualifier.
#### Rule 14.3
_Ref 14.3.1_
- MISRA C-2012 Rule 14.3 False positive as the static analysis tool believes
i can never be larger than SIZE_MAX - HEX_ESCAPE_LENGTH. This can be proven as
a bug by setting i to be 18446744073709551615UL at initial assignment, then require
start != NULL before assigning the vaue of i to start. This creates a case
where i should be large enough to hit the else statement, but the tool still flags
this as invariant.

View File

@ -0,0 +1,136 @@
## coreJSON Library
This repository contains the coreJSON library, a parser that strictly enforces the ECMA-404 JSON standard and is suitable for low memory footprint embedded devices. The coreJSON library is distributed under the [MIT Open Source License](LICENSE).
This library has gone through code quality checks including verification that no function has a [GNU Complexity](https://www.gnu.org/software/complexity/manual/complexity.html) score over 8, and checks against deviations from mandatory rules in the [MISRA coding standard](https://www.misra.org.uk). Deviations from the MISRA C:2012 guidelines are documented under [MISRA Deviations](MISRA.md). This library has also undergone both static code analysis from [Coverity static analysis](https://scan.coverity.com/), and validation of memory safety through the [CBMC automated reasoning tool](https://www.cprover.org/cbmc/).
See memory requirements for this library [here](./docs/doxygen/include/size_table.md).
**coreJSON v3.2.0 [source code](https://github.com/FreeRTOS/coreJSON/tree/v3.2.0/source) is part of the [FreeRTOS 202210.00 LTS](https://github.com/FreeRTOS/FreeRTOS-LTS/tree/202210.00-LTS) release.**
**coreJSON v3.0.0 [source code](https://github.com/FreeRTOS/coreJSON/tree/v3.0.0/source) is part of the [FreeRTOS 202012.00 LTS](https://github.com/FreeRTOS/FreeRTOS-LTS/tree/202012.00-LTS) release.**
## Reference example
```c
#include <stdio.h>
#include "core_json.h"
int main()
{
// Variables used in this example.
JSONStatus_t result;
char buffer[] = "{\"foo\":\"abc\",\"bar\":{\"foo\":\"xyz\"}}";
size_t bufferLength = sizeof( buffer ) - 1;
char queryKey[] = "bar.foo";
size_t queryKeyLength = sizeof( queryKey ) - 1;
char * value;
size_t valueLength;
// Calling JSON_Validate() is not necessary if the document is guaranteed to be valid.
result = JSON_Validate( buffer, bufferLength );
if( result == JSONSuccess )
{
result = JSON_Search( buffer, bufferLength, queryKey, queryKeyLength,
&value, &valueLength );
}
if( result == JSONSuccess )
{
// The pointer "value" will point to a location in the "buffer".
char save = value[ valueLength ];
// After saving the character, set it to a null byte for printing.
value[ valueLength ] = '\0';
// "Found: bar.foo -> xyz" will be printed.
printf( "Found: %s -> %s\n", queryKey, value );
// Restore the original character.
value[ valueLength ] = save;
}
return 0;
}
```
A search may descend through nested objects when the `queryKey` contains matching key strings joined by a separator, `.`. In the example above, `bar` has the value `{"foo":"xyz"}`. Therefore, a search for query key `bar.foo` would output `xyz`.
## Building coreJSON
A compiler that supports **C90 or later** such as *gcc* is required to build the library.
Additionally, the library uses 2 header files introduced in ISO C99, `stdbool.h` and `stdint.h`. For compilers that do not provide this header file, the [source/include](source/include) directory contains [stdbool.readme](source/include/stdbool.readme) and [stdint.readme](source/include/stdint.readme), which can be renamed to `stdbool.h` and `stdint.h` respectively.
For instance, if the example above is copied to a file named `example.c`, *gcc* can be used like so:
```bash
gcc -I source/include example.c source/core_json.c -o example
./example
```
*gcc* can also produce an output file to be linked:
```bash
gcc -I source/include -c source/core_json.c
```
## Documentation
### Existing documentation
For pre-generated documentation, please see the documentation linked in the locations below:
| Location |
| :-: |
| [AWS IoT Device SDK for Embedded C](https://github.com/aws/aws-iot-device-sdk-embedded-C#releases-and-documentation) |
| [FreeRTOS.org](https://freertos.org/Documentation/api-ref/coreJSON/docs/doxygen/output/html/index.html) |
Note that the latest included version of the coreJSON library may differ across repositories.
### Generating documentation
The Doxygen references were created using Doxygen version 1.9.2. To generate the
Doxygen pages, please run the following command from the root of this repository:
```shell
doxygen docs/doxygen/config.doxyfile
```
## Building unit tests
### Checkout Unity Submodule
By default, the submodules in this repository are configured with `update=none` in [.gitmodules](.gitmodules), to avoid increasing clone time and disk space usage of other repositories (like [amazon-freertos](https://github.com/aws/amazon-freertos) that submodules this repository).
To build unit tests, the submodule dependency of Unity is required. Use the following command to clone the submodule:
```
git submodule update --checkout --init --recursive test/unit-test/Unity
```
### Platform Prerequisites
- For running unit tests
- C90 compiler like gcc
- CMake 3.13.0 or later
- Ruby 2.0.0 or later is additionally required for the Unity test framework (that we use).
- For running the coverage target, gcov is additionally required.
### Steps to build Unit Tests
1. Go to the root directory of this repository. (Make sure that the **Unity** submodule is cloned as described [above](#checkout-unity-submodule).)
1. Create build directory: `mkdir build && cd build`
1. Run *cmake* while inside build directory: `cmake -S ../test`
1. Run this command to build the library and unit tests: `make all`
1. The generated test executables will be present in `build/bin/tests` folder.
1. Run `ctest` to execute all tests and view the test run summary.
## CBMC
To learn more about CBMC and proofs specifically, review the training material [here](https://model-checking.github.io/cbmc-training).
The `test/cbmc/proofs` directory contains CBMC proofs.
In order to run these proofs you will need to install CBMC and other tools by following the instructions [here](https://model-checking.github.io/cbmc-training/installation.html).
## Contributing
See [CONTRIBUTING.md](./.github/CONTRIBUTING.md) for information on contributing.

View File

@ -0,0 +1,5 @@
## Reporting a Vulnerability
If you discover a potential security issue in this project, we ask that you notify AWS/Amazon Security
via our [vulnerability reporting page](https://aws.amazon.com/security/vulnerability-reporting/) or directly via email to aws-security@amazon.com.
Please do **not** create a public github issue.

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,20 @@
<table>
<tr>
<td colspan="3"><center><b>Code Size of coreJSON (example generated with GCC for ARM Cortex-M)</b></center></td>
</tr>
<tr>
<td><b>File</b></td>
<td><b><center>With -O1 Optimization</center></b></td>
<td><b><center>With -Os Optimization</center></b></td>
</tr>
<tr>
<td>core_json.c</td>
<td><center>2.9K</center></td>
<td><center>2.4K</center></td>
</tr>
<tr>
<td><b>Total estimates</b></td>
<td><b><center>2.9K</center></b></td>
<td><b><center>2.4K</center></b></td>
</tr>
</table>

View File

@ -0,0 +1,228 @@
<doxygenlayout version="1.0">
<!-- Generated by doxygen 1.8.20 -->
<!-- Navigation index tabs for HTML output -->
<navindex>
<tab type="mainpage" visible="yes" title=""/>
<tab type="pages" visible="yes" title="" intro=""/>
<!-- Hide the default "Data Structures" tab and use the "Modules" tab for data
structures. This allows internal data structures to be hidden. -->
<tab type="modules" visible="yes" title="Data types and Constants" intro="This library defines the following data types and constants."/>
<tab type="namespaces" visible="yes" title="">
<tab type="namespacelist" visible="yes" title="" intro=""/>
<tab type="namespacemembers" visible="yes" title="" intro=""/>
</tab>
<tab type="interfaces" visible="no" title="">
<tab type="interfacelist" visible="no" title="" intro=""/>
<tab type="interfaceindex" visible="no" title=""/>
<tab type="interfacehierarchy" visible="yes" title="" intro=""/>
</tab>
<tab type="classes" visible="no" title="">
<tab type="classlist" visible="no" title="" intro=""/>
<tab type="classindex" visible="no" title=""/>
<tab type="hierarchy" visible="no" title="" intro=""/>
<tab type="classmembers" visible="no" title="" intro=""/>
</tab>
<tab type="structs" visible="no" title="">
<tab type="structlist" visible="no" title="" intro=""/>
<tab type="structindex" visible="no" title=""/>
</tab>
<tab type="exceptions" visible="no" title="">
<tab type="exceptionlist" visible="no" title="" intro=""/>
<tab type="exceptionindex" visible="no" title=""/>
<tab type="exceptionhierarchy" visible="yes" title="" intro=""/>
</tab>
<tab type="files" visible="no" title="">
<tab type="filelist" visible="yes" title="Files" intro="The following files are associated with this library."/>
<tab type="globals" visible="no" title="" intro=""/>
</tab>
<tab type="examples" visible="yes" title="" intro=""/>
</navindex>
<!-- Layout definition for a class page -->
<class>
<briefdescription visible="yes"/>
<includes visible="$SHOW_INCLUDE_FILES"/>
<inheritancegraph visible="$CLASS_GRAPH"/>
<collaborationgraph visible="$COLLABORATION_GRAPH"/>
<memberdecl>
<nestedclasses visible="yes" title=""/>
<publictypes title=""/>
<services title=""/>
<interfaces title=""/>
<publicslots title=""/>
<signals title=""/>
<publicmethods title=""/>
<publicstaticmethods title=""/>
<publicattributes title=""/>
<publicstaticattributes title=""/>
<protectedtypes title=""/>
<protectedslots title=""/>
<protectedmethods title=""/>
<protectedstaticmethods title=""/>
<protectedattributes title=""/>
<protectedstaticattributes title=""/>
<packagetypes title=""/>
<packagemethods title=""/>
<packagestaticmethods title=""/>
<packageattributes title=""/>
<packagestaticattributes title=""/>
<properties title=""/>
<events title=""/>
<privatetypes title=""/>
<privateslots title=""/>
<privatemethods title=""/>
<privatestaticmethods title=""/>
<privateattributes title=""/>
<privatestaticattributes title=""/>
<friends title=""/>
<related title="" subtitle=""/>
<membergroups visible="yes"/>
</memberdecl>
<detaileddescription title=""/>
<memberdef>
<inlineclasses title=""/>
<typedefs title=""/>
<enums title=""/>
<services title=""/>
<interfaces title=""/>
<constructors title=""/>
<functions title=""/>
<related title=""/>
<variables title=""/>
<properties title=""/>
<events title=""/>
</memberdef>
<allmemberslink visible="yes"/>
<usedfiles visible="$SHOW_USED_FILES"/>
<authorsection visible="yes"/>
</class>
<!-- Layout definition for a namespace page -->
<namespace>
<briefdescription visible="yes"/>
<memberdecl>
<nestednamespaces visible="yes" title=""/>
<constantgroups visible="yes" title=""/>
<interfaces visible="yes" title=""/>
<classes visible="yes" title=""/>
<structs visible="yes" title=""/>
<exceptions visible="yes" title=""/>
<typedefs title=""/>
<sequences title=""/>
<dictionaries title=""/>
<enums title=""/>
<functions title=""/>
<variables title=""/>
<membergroups visible="yes"/>
</memberdecl>
<detaileddescription title=""/>
<memberdef>
<inlineclasses title=""/>
<typedefs title=""/>
<sequences title=""/>
<dictionaries title=""/>
<enums title=""/>
<functions title=""/>
<variables title=""/>
</memberdef>
<authorsection visible="yes"/>
</namespace>
<!-- Layout definition for a file page -->
<file>
<briefdescription visible="yes"/>
<includes visible="$SHOW_INCLUDE_FILES"/>
<includegraph visible="$INCLUDE_GRAPH"/>
<includedbygraph visible="$INCLUDED_BY_GRAPH"/>
<sourcelink visible="yes"/>
<memberdecl>
<interfaces visible="yes" title=""/>
<classes visible="yes" title=""/>
<structs visible="yes" title=""/>
<exceptions visible="yes" title=""/>
<namespaces visible="yes" title=""/>
<constantgroups visible="yes" title=""/>
<defines title=""/>
<typedefs title=""/>
<sequences title=""/>
<dictionaries title=""/>
<enums title=""/>
<functions title=""/>
<variables title=""/>
<membergroups visible="yes"/>
</memberdecl>
<detaileddescription title=""/>
<memberdef>
<inlineclasses title=""/>
<defines title=""/>
<typedefs title=""/>
<sequences title=""/>
<dictionaries title=""/>
<enums title=""/>
<functions title=""/>
<variables title=""/>
</memberdef>
<authorsection/>
</file>
<!-- Layout definition for a group page -->
<group>
<briefdescription visible="yes"/>
<groupgraph visible="$GROUP_GRAPHS"/>
<memberdecl>
<nestedgroups visible="yes" title=""/>
<dirs visible="yes" title=""/>
<files visible="yes" title=""/>
<namespaces visible="yes" title=""/>
<classes visible="yes" title=""/>
<defines title=""/>
<typedefs title=""/>
<sequences title=""/>
<dictionaries title=""/>
<enums title=""/>
<enumvalues title=""/>
<functions title=""/>
<variables title=""/>
<signals title=""/>
<publicslots title=""/>
<protectedslots title=""/>
<privateslots title=""/>
<events title=""/>
<properties title=""/>
<friends title=""/>
<membergroups visible="yes"/>
</memberdecl>
<detaileddescription title=""/>
<memberdef>
<pagedocs/>
<inlineclasses title=""/>
<defines title=""/>
<typedefs title=""/>
<sequences title=""/>
<dictionaries title=""/>
<enums title=""/>
<enumvalues title=""/>
<functions title=""/>
<variables title=""/>
<signals title=""/>
<publicslots title=""/>
<protectedslots title=""/>
<privateslots title=""/>
<events title=""/>
<properties title=""/>
<friends title=""/>
</memberdef>
<authorsection visible="yes"/>
</group>
<!-- Layout definition for a directory page -->
<directory>
<briefdescription visible="yes"/>
<directorygraph visible="yes"/>
<memberdecl>
<dirs visible="yes"/>
<files visible="yes"/>
</memberdecl>
<detaileddescription title=""/>
</directory>
</doxygenlayout>

View File

@ -0,0 +1,79 @@
/**
@mainpage Overview
@anchor json
@brief coreJSON Library
<p>
A parser that supports key lookups while also strictly enforcing the ECMA-404 JSON standard.
The library is written in C and designed to be compliant with ISO C90 and MISRA C. It has proven safe memory use
and no heap allocation, making it suitable for IoT microcontrollers, but also fully portable to other platforms.
</p>
@section json_memory_requirements Memory Requirements
@brief Memory requirements of the JSON library.
@include{doc} size_table.md
@section json_design Design
@brief JSON Library Design
<h3>Memory Usage</h3>
<p>
All functions in the JSON library operate only on the buffers provided and use only
local variables on the stack. In order to support static-only usage, we made a
trade-off to re-parse as necessary so that we would not need to keep state.
</p>
<h3>Parsing Strictness</h3>
<p>
Input validation is necessary for strong security posture. As such, the parser
strictly enforces the ECMA-404 JSON standard. Additionally, JSON documents are
checked for illegal UTF-8 sequences, and strings have unicode hex escapes validated.
</p>
<h3>Compliance & Coverage</h3>
<p>
The JSON library is designed to be compliant with ISO C90 and MISRA C:2012.
All functions are written to have minimal complexity. Unit tests and CBMC proofs
are written to cover every path of execution and achieve 100% branch coverage.
</p>
*/
/**
@page json_functions Functions
@brief Primary functions of the JSON library:<br><br>
@subpage json_validate_function <br>
@subpage json_search_function <br>
@subpage json_searcht_function <br>
@subpage json_searchconst_function <br>
@subpage json_iterate_function <br>
@page json_validate_function JSON_Validate
@snippet core_json.h declare_json_validate
@copydoc JSON_Validate
@page json_search_function JSON_Search
@snippet core_json.h declare_json_search
@copydoc JSON_Search
@page json_searcht_function JSON_SearchT
@snippet core_json.h declare_json_searcht
@copydoc JSON_SearchT
@page json_searchconst_function JSON_SearchConst
@snippet core_json.h declare_json_searchconst
@copydoc JSON_SearchConst
@page json_iterate_function JSON_Iterate
@snippet core_json.h declare_json_iterate
@copydoc JSON_Iterate
*/
<!-- We do not use doxygen ALIASes here because there have been issues in the past versions with "^^" newlines within the alias definition. -->
/**
@defgroup json_enum_types Enumerated Types
@brief Enumerated types of the JSON library
@defgroup json_struct_types Struct Types
@brief Struct types of the JSON library
*/

View File

@ -0,0 +1,132 @@
/*
* Stylesheet for Doxygen HTML output.
*
* This file defines styles for custom elements in the header/footer and
* overrides some of the default Doxygen styles.
*
* Styles in this file do not affect the treeview sidebar.
*/
/* Set the margins to place a small amount of whitespace on the left and right
* side of the page. */
div.contents {
margin-left:4em;
margin-right:4em;
}
/* Justify text in paragraphs. */
p {
text-align: justify;
}
/* Style of section headings. */
h1 {
border-bottom: 1px solid #879ECB;
color: #354C7B;
font-size: 160%;
font-weight: normal;
padding-bottom: 4px;
padding-top: 8px;
}
/* Style of subsection headings. */
h2:not(.memtitle):not(.groupheader) {
font-size: 125%;
margin-bottom: 0px;
margin-top: 16px;
padding: 0px;
}
/* Style of paragraphs immediately after subsection headings. */
h2 + p {
margin: 0px;
padding: 0px;
}
/* Style of subsection headings. */
h3 {
font-size: 100%;
margin-bottom: 0px;
margin-left: 2em;
margin-right: 2em;
}
/* Style of paragraphs immediately after subsubsection headings. */
h3 + p {
margin-top: 0px;
margin-left: 2em;
margin-right: 2em;
}
/* Style of the prefix "AWS IoT Device SDK C" that appears in the header. */
#csdkprefix {
color: #757575;
}
/* Style of the "Return to main page" link that appears in the header. */
#returntomain {
padding: 0.5em;
}
/* Style of the dividers on Configuration Settings pages. */
div.configpagedivider {
margin-left: 0px !important;
margin-right: 0px !important;
margin-top: 20px !important;
}
/* Style of configuration setting names. */
dl.section.user ~ h1 {
border-bottom: none;
color: #000000;
font-family: monospace, fixed;
font-size: 16px;
margin-bottom: 0px;
margin-left: 2em;
margin-top: 1.5em;
}
/* Style of paragraphs on a configuration settings page. */
dl.section.user ~ * {
margin-bottom: 10px;
margin-left: 4em;
margin-right: 4em;
margin-top: 0px;
}
/* Hide the configuration setting marker. */
dl.section.user {
display: none;
}
/* Overrides for code fragments and lines. */
div.fragment {
background: #ffffff;
border: none;
padding: 5px;
}
div.line {
color: #3a3a3a;
}
/* Overrides for code syntax highlighting colors. */
span.comment {
color: #008000;
}
span.keyword, span.keywordtype, span.keywordflow {
color: #0000ff;
}
span.preprocessor {
color: #50015a;
}
span.stringliteral, span.charliteral {
color: #800c0c;
}
a.code, a.code:visited, a.line, a.line:visited {
color: #496194;
}

View File

@ -0,0 +1,14 @@
# This file is to add source files and include directories
# into variables so that it can be reused from different repositories
# in their Cmake based build system by including this file.
#
# Files specific to the repository such as test runner, platform tests
# are not added to the variables.
# JSON library source files.
set( JSON_SOURCES
${CMAKE_CURRENT_LIST_DIR}/source/core_json.c )
# JSON library Public Include directories.
set( JSON_INCLUDE_PUBLIC_DIRS
${CMAKE_CURRENT_LIST_DIR}/source/include )

View File

@ -0,0 +1,124 @@
abc
api
ascii
bf
bmp
br
buf
bufferlength
cbmc
colspan
com
cond
const
copydoc
corejson
coverity
dbff
dc
defgroup
df
dfff
ecma
ef
endcode
endcond
endif
enum
enums
fb
fc
fd
fe
ff
ffff
freertos
foo
gcc
github
html
https
ifndef
inc
ingroup
int
iot
iso
json
jsonarray
jsonbadparameter
jsonfalse
jsonillegaldocument
jsoninvalid
jsonmaxdepthexceeded
jsonnotfound
jsonnull
jsonnullparameter
jsonnumber
jsonobject
jsonpartial
jsonstatus
jsonstring
jsonsuccess
jsontrue
jsontype
keylength
len
longjmp
mainpage
md
microcontrollers
min
misra
mit
msb
multibyte
nb
nextkeyvaluepair
noninfringement
nul
os
outkey
outkeylength
outlength
outpair
outtype
outvalue
outvaluelength
param
printf
queryindex
querylength
requirelowsurrogate
rm
sizeof
skipanyliteral
skiparrayscalars
skipcollection
skipdecimals
skipdigits
skipescape
skipexponent
skipgeneric
skiphexescape
skipnumber
skipobjectscalars
skipspace
skipspaceandcomma
skipstring
skiputf
spdx
stderr
struct
sublicense
td
toolchain
tr
uint
unescaped
unicode
unwindings
utf
valuelength
xxxxxx
xyz

View File

@ -0,0 +1,5 @@
name : "coreJSON"
version: "v3.2.0"
description: |
"A parser strictly enforcing the ECMA-404 JSON standard, suitable for microcontrollers. \n"
license: "MIT"

View File

@ -0,0 +1,29 @@
SPDXVersion: SPDX-2.2
DataLicense: CC0-1.0
SPDXID: SPDXRef-DOCUMENT
DocumentName: coreJSON
DocumentNamespace: https://github.com/FreeRTOS/coreJSON/blob/v3.2.0/sbom.spdx
Creator: Amazon Web Services
Created: 2022-10-14T17:08:25Z
CreatorComment: NOASSERTION
DocumentComment: NOASSERTION
PackageName: coreJSON
SPDXID: SPDXRef-Package-coreJSON
PackageVersion: v3.2.0
PackageDownloadLocation: https://github.com/FreeRTOS/coreJSON/tree/v3.2.0
PackageLicenseConcluded: MIT
FilesAnalyzed: True
PackageVerificationCode: e44bfeaf26625bf3d3a217c1c9a18088b4e48434
PackageCopyrightText: NOASSERTION
PackageSummary: NOASSERTION
PackageDescription: "A parser strictly enforcing the ECMA-404 JSON standard, suitable for microcontrollers. \n"
FileName: ./core_json.c
SPDXID: SPDXRef-File-core_json.c
FileChecksum: SHA1: 983dee552b240890c992ddf634c3e87061eaff60
LicenseConcluded: MIT
FileCopyrightText: NOASSERTION
FileComment: NOASSERTION

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,339 @@
/*
* coreJSON v3.2.0
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* 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.
*/
/**
* @file core_json.h
* @brief Include this header file to use coreJSON in your application.
*/
#ifndef CORE_JSON_H_
#define CORE_JSON_H_
#include <stdbool.h>
#include <stddef.h>
/* *INDENT-OFF* */
#ifdef __cplusplus
extern "C" {
#endif
/* *INDENT-ON* */
/**
* @ingroup json_enum_types
* @brief Return codes from coreJSON library functions.
*/
typedef enum
{
JSONPartial = 0, /**< @brief JSON document is valid so far but incomplete. */
JSONSuccess, /**< @brief JSON document is valid and complete. */
JSONIllegalDocument, /**< @brief JSON document is invalid or malformed. */
JSONMaxDepthExceeded, /**< @brief JSON document has nesting that exceeds JSON_MAX_DEPTH. */
JSONNotFound, /**< @brief Query key could not be found in the JSON document. */
JSONNullParameter, /**< @brief Pointer parameter passed to a function is NULL. */
JSONBadParameter /**< @brief Query key is empty, or any subpart is empty, or max is 0. */
} JSONStatus_t;
/**
* @brief Parse a buffer to determine if it contains a valid JSON document.
*
* @param[in] buf The buffer to parse.
* @param[in] max The size of the buffer.
*
* @note The maximum nesting depth may be specified by defining the macro
* JSON_MAX_DEPTH. The default is 32 of sizeof(char).
*
* @note By default, a valid JSON document may contain a single element
* (e.g., string, boolean, number). To require that a valid document
* contain an object or array, define JSON_VALIDATE_COLLECTIONS_ONLY.
*
* @return #JSONSuccess if the buffer contents are valid JSON;
* #JSONNullParameter if buf is NULL;
* #JSONBadParameter if max is 0;
* #JSONIllegalDocument if the buffer contents are NOT valid JSON;
* #JSONMaxDepthExceeded if object and array nesting exceeds a threshold;
* #JSONPartial if the buffer contents are potentially valid but incomplete.
*
* <b>Example</b>
* @code{c}
* // Variables used in this example.
* JSONStatus_t result;
* char buffer[] = "{\"foo\":\"abc\",\"bar\":{\"foo\":\"xyz\"}}";
* size_t bufferLength = sizeof( buffer ) - 1;
*
* result = JSON_Validate( buffer, bufferLength );
*
* // JSON document is valid.
* assert( result == JSONSuccess );
* @endcode
*/
/* @[declare_json_validate] */
JSONStatus_t JSON_Validate( const char * buf,
size_t max );
/* @[declare_json_validate] */
/**
* @brief Find a key or array index in a JSON document and output the
* pointer @p outValue to its value.
*
* Any value may also be an object or an array to a maximum depth. A search
* may descend through nested objects or arrays when the query contains matching
* key strings or array indexes joined by a separator.
*
* For example, if the provided buffer contains <code>{"foo":"abc","bar":{"foo":"xyz"}}</code>,
* then a search for 'foo' would output <code>abc</code>, 'bar' would output
* <code>{"foo":"xyz"}</code>, and a search for 'bar.foo' would output
* <code>xyz</code>.
*
* If the provided buffer contains <code>[123,456,{"foo":"abc","bar":[88,99]}]</code>,
* then a search for '[1]' would output <code>456</code>, '[2].foo' would output
* <code>abc</code>, and '[2].bar[0]' would output <code>88</code>.
*
* On success, the pointer @p outValue points to a location in buf. No null
* termination is done for the value. For valid JSON it is safe to place
* a null character at the end of the value, so long as the character
* replaced is put back before running another search.
*
* @param[in] buf The buffer to search.
* @param[in] max size of the buffer.
* @param[in] query The object keys and array indexes to search for.
* @param[in] queryLength Length of the key.
* @param[out] outValue A pointer to receive the address of the value found.
* @param[out] outValueLength A pointer to receive the length of the value found.
*
* @note The maximum nesting depth may be specified by defining the macro
* JSON_MAX_DEPTH. The default is 32 of sizeof(char).
*
* @note JSON_Search() performs validation, but stops upon finding a matching
* key and its value. To validate the entire JSON document, use JSON_Validate().
*
* @return #JSONSuccess if the query is matched and the value output;
* #JSONNullParameter if any pointer parameters are NULL;
* #JSONBadParameter if the query is empty, or the portion after a separator is empty,
* or max is 0, or an index is too large to convert to a signed 32-bit integer;
* #JSONNotFound if the query has no match.
*
* <b>Example</b>
* @code{c}
* // Variables used in this example.
* JSONStatus_t result;
* char buffer[] = "{\"foo\":\"abc\",\"bar\":{\"foo\":\"xyz\"}}";
* size_t bufferLength = sizeof( buffer ) - 1;
* char query[] = "bar.foo";
* size_t queryLength = sizeof( query ) - 1;
* char * value;
* size_t valueLength;
*
* // Calling JSON_Validate() is not necessary if the document is guaranteed to be valid.
* result = JSON_Validate( buffer, bufferLength );
*
* if( result == JSONSuccess )
* {
* result = JSON_Search( buffer, bufferLength, query, queryLength,
* &value, &valueLength );
* }
*
* if( result == JSONSuccess )
* {
* // The pointer "value" will point to a location in the "buffer".
* char save = value[ valueLength ];
* // After saving the character, set it to a null byte for printing.
* value[ valueLength ] = '\0';
* // "Found: bar.foo -> xyz" will be printed.
* printf( "Found: %s -> %s\n", query, value );
* // Restore the original character.
* value[ valueLength ] = save;
* }
* @endcode
*
* @note The maximum index value is ~2 billion ( 2^31 - 9 ).
*/
/* @[declare_json_search] */
#define JSON_Search( buf, max, query, queryLength, outValue, outValueLength ) \
JSON_SearchT( buf, max, query, queryLength, outValue, outValueLength, NULL )
/* @[declare_json_search] */
/**
* @brief The largest value usable as an array index in a query
* for JSON_Search(), ~2 billion.
*/
#define MAX_INDEX_VALUE ( 0x7FFFFFF7 ) /* 2^31 - 9 */
/**
* @ingroup json_enum_types
* @brief Value types from the JSON standard.
*/
typedef enum
{
JSONInvalid = 0, /**< @brief Not a valid JSON type. */
JSONString, /**< @brief A quote delimited sequence of Unicode characters. */
JSONNumber, /**< @brief A rational number. */
JSONTrue, /**< @brief The literal value true. */
JSONFalse, /**< @brief The literal value false. */
JSONNull, /**< @brief The literal value null. */
JSONObject, /**< @brief A collection of zero or more key-value pairs. */
JSONArray /**< @brief A collection of zero or more values. */
} JSONTypes_t;
/**
* @brief Same as JSON_Search(), but also outputs a type for the value found
*
* See @ref JSON_Search for documentation of common behavior.
*
* @param[in] buf The buffer to search.
* @param[in] max size of the buffer.
* @param[in] query The object keys and array indexes to search for.
* @param[in] queryLength Length of the key.
* @param[out] outValue A pointer to receive the address of the value found.
* @param[out] outValueLength A pointer to receive the length of the value found.
* @param[out] outType An enum indicating the JSON-specific type of the value.
*/
/* @[declare_json_searcht] */
JSONStatus_t JSON_SearchT( char * buf,
size_t max,
const char * query,
size_t queryLength,
char ** outValue,
size_t * outValueLength,
JSONTypes_t * outType );
/* @[declare_json_searcht] */
/**
* @brief Same as JSON_SearchT(), but with const qualified buf and outValue arguments.
*
* See @ref JSON_Search for documentation of common behavior.
*
* @param[in] buf The buffer to search.
* @param[in] max size of the buffer.
* @param[in] query The object keys and array indexes to search for.
* @param[in] queryLength Length of the key.
* @param[out] outValue A pointer to receive the address of the value found.
* @param[out] outValueLength A pointer to receive the length of the value found.
* @param[out] outType An enum indicating the JSON-specific type of the value.
*/
/* @[declare_json_searchconst] */
JSONStatus_t JSON_SearchConst( const char * buf,
size_t max,
const char * query,
size_t queryLength,
const char ** outValue,
size_t * outValueLength,
JSONTypes_t * outType );
/* @[declare_json_searchconst] */
/**
* @ingroup json_struct_types
* @brief Structure to represent a key-value pair.
*/
typedef struct
{
const char * key; /**< @brief Pointer to the code point sequence for key. */
size_t keyLength; /**< @brief Length of the code point sequence for key. */
const char * value; /**< @brief Pointer to the code point sequence for value. */
size_t valueLength; /**< @brief Length of the code point sequence for value. */
JSONTypes_t jsonType; /**< @brief JSON-specific type of the value. */
} JSONPair_t;
/**
* @brief Output the next key-value pair or value from a collection.
*
* This function may be used in a loop to output each key-value pair from an object,
* or each value from an array. For the first invocation, the integers pointed to by
* start and next should be initialized to 0. These will be updated by the function.
* If another key-value pair or value is present, the output structure is populated
* and #JSONSuccess is returned; otherwise the structure is unchanged and #JSONNotFound
* is returned.
*
* @param[in] buf The buffer to search.
* @param[in] max size of the buffer.
* @param[in,out] start The index at which the collection begins.
* @param[in,out] next The index at which to seek the next value.
* @param[out] outPair A pointer to receive the next key-value pair.
*
* @note This function expects a valid JSON document; run JSON_Validate() first.
*
* @note For an object, the outPair structure will reference a key and its value.
* For an array, only the value will be referenced (i.e., outPair.key will be NULL).
*
* @return #JSONSuccess if a value is output;
* #JSONIllegalDocument if the buffer does not contain a collection;
* #JSONNotFound if there are no further values in the collection.
*
* <b>Example</b>
* @code{c}
* // Variables used in this example.
* static char * json_types[] =
* {
* "invalid",
* "string",
* "number",
* "true",
* "false",
* "null",
* "object",
* "array"
* };
*
* void show( const char * json,
* size_t length )
* {
* size_t start = 0, next = 0;
* JSONPair_t pair = { 0 };
* JSONStatus_t result;
*
* result = JSON_Validate( json, length );
* if( result == JSONSuccess )
* {
* result = JSON_Iterate( json, length, &start, &next, &pair );
* }
*
* while( result == JSONSuccess )
* {
* if( pair.key != NULL )
* {
* printf( "key: %.*s\t", ( int ) pair.keyLength, pair.key );
* }
*
* printf( "value: (%s) %.*s\n", json_types[ pair.jsonType ],
* ( int ) pair.valueLength, pair.value );
*
* result = JSON_Iterate( json, length, &start, &next, &pair );
* }
* }
* @endcode
*/
/* @[declare_json_iterate] */
JSONStatus_t JSON_Iterate( const char * buf,
size_t max,
size_t * start,
size_t * next,
JSONPair_t * outPair );
/* @[declare_json_iterate] */
/* *INDENT-OFF* */
#ifdef __cplusplus
}
#endif
/* *INDENT-ON* */
#endif /* ifndef CORE_JSON_H_ */

View File

@ -0,0 +1,30 @@
#ifndef _STDBOOL_H
#define _STDBOOL_H
/*******************************************************************************
* This file contains the definitions specified in stdbool.h. It is provided to
* allow the library to be built using compilers that do not provide their own
* stdbool.h defintion.
*
* To use this file:
*
* 1) Copy this file into a directory that is in your compiler's include path.
* The directory must be part of the include path for system header files,
* for example passed using gcc's "-I" or "-isystem" options.
*
* 2) Rename the copied file stdbool.h.
*
*/
#ifndef __cplusplus
/* _Bool was introduced in C99. */
#define bool int
#define false 0
#define true 1
#endif
#define __bool_true_false_are_defined 1
#endif /* _STDBOOL_H */

View File

@ -0,0 +1,41 @@
#ifndef _STDINT_H
#define _STDINT_H
/*******************************************************************************
* THIS IS NOT A FULL stdint.h IMPLEMENTATION - It only contains the definitions
* necessary to build the library code. It is provided to allow the library to
* be built using compilers that do not provide their own stdint.h definition.
*
* To use this file:
*
* 1) Copy this file into a directory that is in your compiler's include path.
* The directory must be part of the include path for system header file,
* for example passed using gcc's "-I" or "-isystem" options.
*
* 2) Rename the copied file stdint.h.
*
*/
typedef signed char int8_t;
typedef unsigned char uint8_t;
typedef short int16_t;
typedef unsigned short uint16_t;
typedef long int32_t;
typedef unsigned long uint32_t;
typedef long long int64_t;
typedef unsigned long long uint64_t;
#define INT8_MAX ( ( signed char ) 127 )
#define UINT8_MAX ( ( unsigned char ) 255 )
#define INT16_MAX ( ( short ) 32767 )
#define UINT16_MAX ( ( unsigned short ) 65535 )
#define INT32_MAX 2147483647L
#define UINT32_MAX 4294967295UL
#define INT64_MAX 9223372036854775807LL
#define UINT64_MAX 18446744073709551615ULL
#ifndef SIZE_MAX
#define SIZE_MAX ( ( size_t ) -1 )
#endif
#endif /* _STDINT_H */

View File

@ -0,0 +1,86 @@
cmake_minimum_required( VERSION 3.13.0 )
project( "CoreJSON unit test"
VERSION 1.0.0
LANGUAGES C )
# Allow the project to be organized into folders.
set_property( GLOBAL PROPERTY USE_FOLDERS ON )
# Use C90.
set( CMAKE_C_STANDARD 90 )
set( CMAKE_C_STANDARD_REQUIRED ON )
# Do not allow in-source build.
if( ${PROJECT_SOURCE_DIR} STREQUAL ${PROJECT_BINARY_DIR} )
message( FATAL_ERROR "In-source build is not allowed. Please build in a separate directory, such as ${PROJECT_SOURCE_DIR}/build." )
endif()
# Set global path variables.
get_filename_component(__MODULE_ROOT_DIR "${CMAKE_CURRENT_LIST_DIR}/.." ABSOLUTE)
set( MODULE_ROOT_DIR ${__MODULE_ROOT_DIR} CACHE INTERNAL "coreJSON source root." )
set( UNIT_TEST_DIR ${MODULE_ROOT_DIR}/test/unit-test CACHE INTERNAL "coreJSON unit test directory." )
set( UNITY_DIR ${UNIT_TEST_DIR}/Unity CACHE INTERNAL "Unity library source directory." )
# Configure options to always show in CMake GUI.
option( BUILD_CLONE_SUBMODULES
"Set this to ON to automatically clone any required Git submodules. When OFF, submodules must be manually cloned."
OFF )
# Set output directories.
set( CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin )
set( CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib )
set( CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib )
# ================================ Coverity Analysis Configuration =================================
# Include filepaths for source and include.
include( ${MODULE_ROOT_DIR}/jsonFilePaths.cmake )
# Target for Coverity analysis that builds the library.
add_library( coverity_analysis
${JSON_SOURCES} )
# JSON public include path.
target_include_directories( coverity_analysis PUBLIC ${JSON_INCLUDE_PUBLIC_DIRS} )
# When building the coverity analysis target we disable debug
target_compile_options(coverity_analysis PUBLIC -DNDEBUG )
# ==================================== Test Configuration ========================================
# Include Unity build configuration.
include( unit-test/unity_build.cmake )
# Check if the Unity source directory exists, and if not present, clone the submodule
# if BUILD_CLONE_SUBMODULES configuration is enabled.
if( NOT EXISTS ${UNITY_DIR}/src )
# Attempt to clone Unity.
if( ${BUILD_CLONE_SUBMODULES} )
clone_unity()
else()
message( FATAL_ERROR "The required submodule Unity does not exist. Either clone it manually, or set BUILD_CLONE_SUBMODULES to 1 to automatically clone it during build." )
endif()
endif()
# Add unit test and coverage configuration.
# Use CTest utility for managing test runs. This has to be added BEFORE
# defining test targets with add_test()
enable_testing()
# Add build targets for Unity and Unit, required for unit testing.
add_unity_targets()
# Add function to enable Unity based tests and coverage.
include( ${MODULE_ROOT_DIR}/tools/unity/create_test.cmake )
# Include build configuration for unit tests.
add_subdirectory( unit-test )
# ==================================== Coverage Analysis configuration ============================
# Add a target for running coverage on tests.
add_custom_target( coverage
COMMAND ${CMAKE_COMMAND} -DUNITY_DIR=${UNITY_DIR}
-P ${MODULE_ROOT_DIR}/tools/unity/coverage.cmake
DEPENDS unity core_json_utest
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
)

View File

@ -0,0 +1,22 @@
# Emitted when running CBMC proofs
proofs/**/logs
proofs/**/gotos
proofs/**/report
proofs/**/html
proofs/**/core_json.c
proofs/output
# Emitted by CBMC Viewer
TAGS-*
# Emitted by Arpa
arpa_cmake/
arpa-validation-logs/
Makefile.arpa
# Emitted by litani
.ninja_deps
.ninja_log
.litani_cache_dir
__pycache__/

View File

@ -0,0 +1,6 @@
CBMC proof include files
========================
This directory contains include files written for CBMC proof. It is
common to write some code to model aspects of the system under test,
and the header files for this code go here.

View File

@ -0,0 +1,111 @@
/*
* coreJSON v3.2.0
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* 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.
*/
#ifndef CORE_JSON_ANNEX_H_
#define CORE_JSON_ANNEX_H_
#include <stdint.h>
#include "core_json.h"
#define isBool( x ) ( ( x == true ) || ( x == false ) )
/* parameter check fail values for JSON API functions */
#define parameterEnum( x ) ( ( x == JSONNullParameter ) || ( x == JSONBadParameter ) )
/* These 3 enums represent all the ways skipCollection() can fail. */
#define skipCollectionFailEnum( x ) \
( ( x == JSONPartial ) || ( x == JSONIllegalDocument ) || ( x == JSONMaxDepthExceeded ) )
/* All possible return values for skipCollection() */
#define skipCollectionEnum( x ) ( skipCollectionFailEnum( x ) || ( x == JSONSuccess ) )
/* All possible return values for JSON_Validate() */
#define jsonValidateEnum( x ) ( skipCollectionEnum( x ) || parameterEnum( x ) )
/* All possible return values for JSON_Search() */
#define jsonSearchEnum( x ) ( jsonValidateEnum( x ) || ( x == JSONNotFound ) )
/* All possible return values for JSON_Iterate() */
#define jsonIterateEnum( x ) \
( parameterEnum( x ) || ( x == JSONIllegalDocument ) || \
( x == JSONNotFound ) || ( x == JSONSuccess ) )
/* All possible type values output from JSON_SearchT() */
#define jsonTypesEnum( x ) \
( ( x == JSONString ) || \
( x == JSONNumber ) || \
( x == JSONTrue ) || \
( x == JSONFalse ) || \
( x == JSONNull ) || \
( x == JSONObject ) || \
( x == JSONArray ) )
/*
* These are declarations for the (normally) static functions from core_json.c.
* Please see core_json.c for documentation.
*/
void skipSpace( const char * buf,
size_t * start,
size_t max );
bool skipUTF8( const char * buf,
size_t * start,
size_t max );
bool skipEscape( const char * buf,
size_t * start,
size_t max );
bool skipString( const char * buf,
size_t * start,
size_t max );
bool skipAnyLiteral( const char * buf,
size_t * start,
size_t max );
bool skipDigits( const char * buf,
size_t * start,
size_t max,
int32_t * outValue );
bool skipNumber( const char * buf,
size_t * start,
size_t max );
bool skipSpaceAndComma( const char * buf,
size_t * start,
size_t max );
bool skipAnyScalar( const char * buf,
size_t * start,
size_t max );
JSONStatus_t skipCollection( const char * buf,
size_t * start,
size_t max );
#endif /* ifndef CORE_JSON_ANNEX_H_ */

View File

@ -0,0 +1,51 @@
/*
* coreJSON v3.2.0
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* 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.
*/
#ifndef SKIPGENERIC_H_
#define SKIPGENERIC_H_
#include <stddef.h>
#include "core_json_annex.h"
/**
* @brief Advance buffer index beyond some minimum value.
*
* This function models the behavior of most of the skip* functions
* from core_json.c.
*
* @param[in] buf The buffer to parse.
* @param[in,out] start The index at which to begin.
* @param[in] max The size of the buffer.
* @param[in] min The smallest size required for a true result.
*
* @return true or false, nondeterministically
* if true, the index in start will increment by at least min
* but will not exceed max.
*/
bool skipGeneric( const char * buf,
size_t * start,
size_t max,
size_t min );
#endif /* ifndef SKIPGENERIC_H_ */

View File

@ -0,0 +1,81 @@
/*
* coreJSON v3.2.0
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* 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.
*/
/**
* @file JSON_Iterate_harness.c
* @brief Implements the proof harness for the JSON_Iterate function.
*/
#include <stdlib.h>
#include "core_json_annex.h"
void harness()
{
char * buf;
size_t max;
size_t * start, * next;
JSONPair_t * pair;
JSONStatus_t ret;
/* max is the buffer length which must not exceed unwindings. */
__CPROVER_assume( max < CBMC_MAX_BUFSIZE );
buf = malloc( max );
start = malloc( sizeof( *start ) );
next = malloc( sizeof( *next ) );
pair = malloc( sizeof( *pair ) );
if( pair != NULL )
{
JSONPair_t tmp = { 0 };
*pair = tmp;
}
ret = JSON_Iterate( buf,
max,
start,
next,
pair );
__CPROVER_assert( jsonIterateEnum( ret ), "The return value is a JSONStatus_t." );
if( ret == JSONSuccess )
{
if( pair->key != NULL )
{
__CPROVER_assert( ( pair->key > buf ) &&
( ( pair->key + pair->keyLength ) < ( buf + max ) ),
"The output key is a sequence of characters within buf." );
__CPROVER_assert( ( pair->key + pair->keyLength ) < pair->value,
"The output value occurs after the key." );
}
__CPROVER_assert( ( pair->value > buf ) &&
( ( pair->value + pair->valueLength ) <= ( buf + max ) ),
"The output value is a sequence of characters within buf." );
__CPROVER_assert( jsonTypesEnum( pair->jsonType ), "The value type is a JSONTypes_t." );
}
}

View File

@ -0,0 +1,27 @@
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
HARNESS_FILE=JSON_Iterate_harness
PROOF_UID=JSON_Iterate
# These values were experimentally chosen to provide 100% coverage
# without tripping unwinding assertions and without exhausting memory.
CBMC_MAX_BUFSIZE=7
UNWINDSET += nextValue.0:$(CBMC_MAX_BUFSIZE)
UNWINDSET += nextKeyValuePair.0:$(CBMC_MAX_BUFSIZE)
PROOF_SOURCES += $(PROOF_STUB)/skipGeneric.c
PROOF_SOURCES += $(PROOF_STUB)/skipAnyScalar.c
PROOF_SOURCES += $(PROOF_STUB)/skipCollection.c
PROOF_SOURCES += $(PROOF_STUB)/skipDigits.c
PROOF_SOURCES += $(PROOF_STUB)/skipSpace.c
PROOF_SOURCES += $(PROOF_STUB)/skipSpaceAndComma.c
PROOF_SOURCES += $(PROOF_STUB)/skipString.c
include ../Makefile-json.common
# Substitution command to pass to sed for patching core_json.c. The
# characters " and # must be escaped with backslash.
CORE_JSON_SED_EXPR = 1s/^/\#include \"core_json_annex.h\" /; s/^static //; s/(bool|void|JSONStatus_t) skip(AnyScalar|Collection|Digits|Space|SpaceAndComma|String)\b/&_/

View File

@ -0,0 +1,23 @@
JSON_Iterate proof
==============
This directory contains a memory safety proof for JSON_Iterate.
The proof runs in a few seconds. It provides complete coverage of:
* JSON_Iterate()
* iterate()
For this proof, the following functions are replaced with mocks.
These functions have separate proofs.
* skipAnyScalar()
* skipCollection()
* skipDigits()
* skipSpace()
* skipSpaceAndComma()
* skipString()
To run the proof.
* Add cbmc, goto-cc, goto-instrument, goto-analyzer, and cbmc-viewer
to your path.
* Run "make".
* Open html/index.html in a web browser.

View File

@ -0,0 +1 @@
# This file marks this directory as containing a CBMC proof.

View File

@ -0,0 +1,7 @@
{ "expected-missing-functions":
[
],
"proof-name": "JSON_Iterate",
"proof-root": "test/cbmc/proofs"
}

View File

@ -0,0 +1,78 @@
/*
* coreJSON v3.2.0
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* 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.
*/
/**
* @file JSON_Search_harness.c
* @brief Implements the proof harness for the JSON_Search function.
*/
#include <stdlib.h>
#include "core_json_annex.h"
void harness()
{
char * buf = NULL;
size_t max;
char * query = NULL;
size_t queryLength;
char * outValue;
size_t outValueLength;
JSONStatus_t ret;
JSONTypes_t outType;
/* max is the buffer length which must not exceed unwindings. */
__CPROVER_assume( max < CBMC_MAX_BUFSIZE );
if( nondet_bool() )
{
buf = malloc( max );
}
/* queryLength is the buffer length of the query which must not exceed unwindings. */
__CPROVER_assume( queryLength < CBMC_MAX_QUERYKEYLENGTH );
if( nondet_bool() )
{
query = malloc( queryLength );
}
ret = JSON_SearchT( buf,
max,
query,
queryLength,
( nondet_bool() ? &outValue : NULL ),
( nondet_bool() ? &outValueLength : NULL ),
( nondet_bool() ? &outType : NULL ) );
__CPROVER_assert( jsonSearchEnum( ret ), "The return value is a JSONStatus_t." );
if( ret == JSONSuccess )
{
__CPROVER_assert( ( outValue >= buf ) &&
( ( outValue + outValueLength ) <= ( buf + max ) ),
"The output value is a sequence of characters within buf." );
__CPROVER_assert( jsonTypesEnum( ret ), "The value type is a JSONTypes_t." );
}
}

View File

@ -0,0 +1,35 @@
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
HARNESS_FILE=JSON_Search_harness
PROOF_UID=JSON_Search
# These values were experimentally chosen to provide 100% coverage
# without tripping unwinding assertions and without exhausting memory.
CBMC_MAX_BUFSIZE=7
CBMC_MAX_QUERYKEYLENGTH=6
REMOVE_FUNCTION_BODY += strnEq
UNWINDSET += JSON_SearchT.0:$(CBMC_MAX_QUERYKEYLENGTH)
UNWINDSET += JSON_SearchT.1:$(CBMC_MAX_QUERYKEYLENGTH)
UNWINDSET += arraySearch.0:$(CBMC_MAX_BUFSIZE)
UNWINDSET += multiSearch.0:$(CBMC_MAX_BUFSIZE)
UNWINDSET += nextValue.0:$(CBMC_MAX_BUFSIZE)
UNWINDSET += nextKeyValuePair.0:$(CBMC_MAX_BUFSIZE)
UNWINDSET += objectSearch.0:$(CBMC_MAX_BUFSIZE)
UNWINDSET += skipQueryPart.0:$(CBMC_MAX_QUERYKEYLENGTH)
PROOF_SOURCES += $(PROOF_STUB)/skipGeneric.c
PROOF_SOURCES += $(PROOF_STUB)/skipAnyScalar.c
PROOF_SOURCES += $(PROOF_STUB)/skipCollection.c
PROOF_SOURCES += $(PROOF_STUB)/skipDigits.c
PROOF_SOURCES += $(PROOF_STUB)/skipSpace.c
PROOF_SOURCES += $(PROOF_STUB)/skipSpaceAndComma.c
PROOF_SOURCES += $(PROOF_STUB)/skipString.c
include ../Makefile-json.common
# Substitution command to pass to sed for patching core_json.c. The
# characters " and # must be escaped with backslash.
CORE_JSON_SED_EXPR = 1s/^/\#include \"core_json_annex.h\" /; s/^static //; s/(bool|void|JSONStatus_t) skip(AnyScalar|Collection|Digits|Space|SpaceAndComma|String)\b/&_/

View File

@ -0,0 +1,30 @@
JSON_Search proof
==============
This directory contains a memory safety proof for JSON_Search and JSON_SearchT.
The proof runs in 15 minutes on a t3.medium. It provides complete coverage of:
* JSON_Search()
* JSON_SearchT()
* JSON_SearchTc()
* arraySearch()
* multiSearch()
* nextKeyValuePair()
* nextValue()
* objectSearch()
* skipQueryPart()
For this proof, the following functions are replaced with mocks.
These functions have separate proofs.
* skipAnyScalar()
* skipCollection()
* skipDigits()
* skipSpace()
* skipSpaceAndComma()
* skipString()
To run the proof.
* Add cbmc, goto-cc, goto-instrument, goto-analyzer, and cbmc-viewer
to your path.
* Run "make".
* Open html/index.html in a web browser.

View File

@ -0,0 +1 @@
# This file marks this directory as containing a CBMC proof.

View File

@ -0,0 +1,7 @@
{ "expected-missing-functions":
[
"strnEq"
],
"proof-name": "JSON_Search",
"proof-root": "test/cbmc/proofs"
}

View File

@ -0,0 +1,50 @@
/*
* coreJSON v3.2.0
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* 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.
*/
/**
* @file JSON_Validate_harness.c
* @brief Implements the proof harness for the JSON_Validate function.
*/
#include <stdlib.h>
#include "core_json_annex.h"
void harness()
{
char * buf = NULL;
size_t max;
JSONStatus_t ret;
/* max is the buffer length which must not exceed unwindings. */
__CPROVER_assume( max < CBMC_MAX_BUFSIZE );
if( nondet_bool() )
{
buf = malloc( max );
}
ret = JSON_Validate( buf, max );
__CPROVER_assert( jsonValidateEnum( ret ), "The return value is a subset of JSONStatus_t." );
}

View File

@ -0,0 +1,24 @@
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
HARNESS_FILE=JSON_Validate_harness
PROOF_UID=JSON_Validate
# This value was experimentally chosen to provide 100% coverage
# without tripping unwinding assertions and without exhausting memory.
CBMC_MAX_BUFSIZE=14
UNWINDSET += JSON_Validate.0:$(CBMC_MAX_BUFSIZE)
PROOF_SOURCES += $(PROOF_STUB)/skipGeneric.c
PROOF_SOURCES += $(PROOF_STUB)/skipAnyLiteral.c
PROOF_SOURCES += $(PROOF_STUB)/skipCollection.c
PROOF_SOURCES += $(PROOF_STUB)/skipNumber.c
PROOF_SOURCES += $(PROOF_STUB)/skipSpace.c
PROOF_SOURCES += $(PROOF_STUB)/skipString.c
include ../Makefile-json.common
# Substitution command to pass to sed for patching core_json.c. The
# characters " and # must be escaped with backslash.
CORE_JSON_SED_EXPR = 1s/^/\#include \"core_json_annex.h\" /; s/^static //; s/(bool|JSONStatus_t|void) skip(AnyLiteral|Collection|Number|Space|String)\b/&_/

View File

@ -0,0 +1,21 @@
JSON_Validate proof
==============
This directory contains a memory safety proof for JSON_Validate.
The proof runs in a few seconds and provides complete coverage of:
* JSON_Validate()
* skipAnyScalar()
For this proof, the following functions are replaced with mocks.
These functions have separate proofs.
* skipAnyLiteral()
* skipCollection()
* skipNumber()
* skipString()
To run the proof.
* Add cbmc, goto-cc, goto-instrument, goto-analyzer, and cbmc-viewer
to your path.
* Run "make".
* Open html/index.html in a web browser.

View File

@ -0,0 +1 @@
# This file marks this directory as containing a CBMC proof.

View File

@ -0,0 +1,7 @@
{ "expected-missing-functions":
[
],
"proof-name": "JSON_Validate",
"proof-root": "test/cbmc/proofs"
}

View File

@ -0,0 +1,24 @@
SHELL := /bin/bash
DIRS := skipSpace skipSpaceAndComma skipEscape skipAnyLiteral skipUTF8
DIRS += skipNumber skipString skipCollection JSON_Validate JSON_Search
DIRS += JSON_Iterate
PROOF_COMMANDS := cbmc goto-cc goto-instrument goto-analyzer cbmc-viewer
SHELL_COMMANDS := mawk sed w3m
# run all the proofs in ascending dependency order
# and show a summary page for each
all: precheck clean
for d in $(DIRS); do \
echo -n $$d; \
time make -C $$d 2>&1 | mawk -W interactive 'NR % 30 == 0 {printf "."}'; echo; \
w3m -cols 120 -dump $$d/html/index.html | sed 's/^/ /'; \
done
clean:
for d in $(DIRS); do make -C $$d cleanclean >/dev/null 2>&1; done
precheck:
@hash $(PROOF_COMMANDS) $(SHELL_COMMANDS)
.PHONY: all clean precheck

View File

@ -0,0 +1,22 @@
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
HARNESS_ENTRY=harness
DEFINES += -DCBMC_MAX_BUFSIZE=$(CBMC_MAX_BUFSIZE)
ifdef CBMC_MAX_QUERYKEYLENGTH
DEFINES += -DCBMC_MAX_QUERYKEYLENGTH=$(CBMC_MAX_QUERYKEYLENGTH)
endif
INCLUDES += -I$(CBMC_ROOT)/include
PROOF_SOURCES += $(PROOFDIR)/$(HARNESS_FILE).c
PROJECT_SOURCES += $(PROOFDIR)/core_json.c
CHECKFLAGS += --pointer-primitive-check
include ../Makefile.common
cleanclean: veryclean
-$(RM) $(PROOFDIR)/core_json.c

View File

@ -0,0 +1,42 @@
# -*- mode: makefile -*-
# The first line sets the emacs major mode to Makefile
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
################################################################
# Use this file to give project-specific definitions of the command
# line arguments to pass to CBMC tools like goto-cc to build the goto
# binaries and cbmc to do the property and coverage checking.
#
# Use this file to override most default definitions of variables in
# Makefile.common.
################################################################
# Flags to pass to goto-cc for compilation (typically those passed to gcc -c)
# COMPILE_FLAGS =
COMPILE_FLAGS += -ansi
PROJECT_NAME = "FreeRTOS coreJSON"
LITANI ?= litani
# Flags to pass to goto-cc for linking (typically those passed to gcc)
# LINK_FLAGS =
# Preprocessor include paths -I...
# Consider adding
# INCLUDES += -I$(CBMC_ROOT)/include
# You will want to decide what order that comes in relative to the other
# include directories in your project.
#
# INCLUDES =
INCLUDES += -I$(SRCDIR)/source/include
# Preprocessor definitions -D...
# DEFINES =
# Path to arpa executable
# ARPA =
# Flags to pass to cmake for building the project
# ARPA_CMAKE_FLAGS =

View File

@ -0,0 +1,25 @@
# -*- mode: makefile -*-
# The first line sets the emacs major mode to Makefile
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
################################################################
# Use this file to give project-specific targets, including targets
# that may depend on targets defined in Makefile.common.
################################################################
# Each proof requires core_json.c to be patched (using sed) and dumped into the
# proof directory. The exact sed invocation differs for each proof. So each
# proof must set the CORE_JSON_SED_EXPR variable, which this rule uses as the
# argument to sed.
$(PROOFDIR)/core_json.c: $(SRCDIR)/source/core_json.c
$(LITANI) add-job \
--command \
"sed -E '$(CORE_JSON_SED_EXPR)' $^" \
--inputs $^ \
--outputs $@ \
--stdout-file $@ \
--ci-stage build \
--pipeline-name "$(PROOF_UID)" \
--description "$(PROOF_UID): patching core_json.c"

View File

@ -0,0 +1,11 @@
# -*- mode: makefile -*-
# The first line sets the emacs major mode to Makefile
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
################################################################
# Use this file to define project-specific targets and definitions for
# unit testing or continuous integration that may depend on targets
# defined in Makefile.common
################################################################

View File

@ -0,0 +1 @@
SRCDIR ?= $(abspath $(PROOF_ROOT)/../../..)

View File

@ -0,0 +1,999 @@
# -*- mode: makefile -*-
# The first line sets the emacs major mode to Makefile
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
CBMC_STARTER_KIT_VERSION = CBMC starter kit 2.5
################################################################
# The CBMC Starter Kit depends on the files Makefile.common and
# run-cbmc-proofs.py. They are installed by the setup script
# cbmc-starter-kit-setup and updated to the latest version by the
# update script cbmc-starter-kit-update. For more information about
# the starter kit and these files and these scripts, see
# https://model-checking.github.io/cbmc-starter-kit
#
# Makefile.common implements what we consider to be some best
# practices for using cbmc for software verification.
#
# Section I gives default values for a large number of Makefile
# variables that control
# * how your code is built (include paths, etc),
# * what program transformations are applied to your code (loop
# unwinding, etc), and
# * what properties cbmc checks for in your code (memory safety, etc).
#
# These variables are defined below with definitions of the form
# VARIABLE ?= DEFAULT_VALUE
# meaning VARIABLE is set to DEFAULT_VALUE if VARIABLE has not already
# been given a value.
#
# For your project, you can override these default values with
# project-specific definitions in Makefile-project-defines.
#
# For any individual proof, you can override these default values and
# project-specific values with proof-specific definitions in the
# Makefile for your proof.
#
# The definitions in the proof Makefile override definitions in the
# project Makefile-project-defines which override definitions in this
# Makefile.common.
#
# Section II uses the values defined in Section I to build your code, run
# your proof, and build a report of your results. You should not need
# to modify or override anything in Section II, but you may want to
# read it to understand how the values defined in Section I control
# things.
#
# To use Makefile.common, set variables as described above as needed,
# and then for each proof,
#
# * Create a subdirectory <DIR>.
# * Write a proof harness (a function) with the name <HARNESS_ENTRY>
# in a file with the name <DIR>/<HARNESS_FILE>.c
# * Write a makefile with the name <DIR>/Makefile that looks
# something like
#
# HARNESS_FILE=<HARNESS_FILE>
# HARNESS_ENTRY=<HARNESS_ENTRY>
# PROOF_UID=<PROOF_UID>
#
# PROJECT_SOURCES += $(SRCDIR)/libraries/api_1.c
# PROJECT_SOURCES += $(SRCDIR)/libraries/api_2.c
#
# PROOF_SOURCES += $(PROOFDIR)/harness.c
# PROOF_SOURCES += $(SRCDIR)/cbmc/proofs/stub_a.c
# PROOF_SOURCES += $(SRCDIR)/cbmc/proofs/stub_b.c
#
# UNWINDSET += foo.0:3
# UNWINDSET += bar.1:6
#
# REMOVE_FUNCTION_BODY += api_stub_a
# REMOVE_FUNCTION_BODY += api_stub_b
#
# DEFINES = -DDEBUG=0
#
# include ../Makefile.common
#
# * Change directory to <DIR> and run make
#
# The proof setup script cbmc-starter-kit-setup-proof from the CBMC
# Starter Kit will do most of this for, creating a directory and
# writing a basic Makefile and proof harness into it that you can edit
# as described above.
#
# Warning: If you get results that are hard to explain, consider
# running "make clean" or "make veryclean" before "make" if you get
# results that are hard to explain. Dependency handling in this
# Makefile.common may not be perfect.
SHELL=/bin/bash
default: report
################################################################
################################################################
## Section I: This section gives common variable definitions.
##
## Override these definitions in Makefile-project-defines or
## your proof Makefile.
##
## Remember that Makefile.common and Makefile-project-defines are
## included into the proof Makefile in your proof directory, so all
## relative pathnames defined there should be relative to your proof
## directory.
################################################################
# Define the layout of the source tree and the proof subtree
#
# Generally speaking,
#
# SRCDIR = the root of the repository
# CBMC_ROOT = /srcdir/cbmc
# PROOF_ROOT = /srcdir/cbmc/proofs
# PROOF_SOURCE = /srcdir/cbmc/sources
# PROOF_INCLUDE = /srcdir/cbmc/include
# PROOF_STUB = /srcdir/cbmc/stubs
# PROOFDIR = the directory containing the Makefile for your proof
#
# The path /srcdir/cbmc used in the example above is determined by the
# setup script cbmc-starter-kit-setup. Projects usually create a cbmc
# directory somewhere in the source tree, and run the setup script in
# that directory. The value of CBMC_ROOT becomes the absolute path to
# that directory.
#
# The location of that cbmc directory in the source tree affects the
# definition of SRCDIR, which is defined in terms of the relative path
# from a proof directory to the repository root. The definition is
# usually determined by the setup script cbmc-starter-kit-setup and
# written to Makefile-template-defines, but you can override it for a
# project in Makefile-project-defines and for a specific proof in the
# Makefile for the proof.
# Absolute path to the directory containing this Makefile.common
# See https://ftp.gnu.org/old-gnu/Manuals/make-3.80/html_node/make_17.html
#
# Note: We compute the absolute paths to the makefiles in MAKEFILE_LIST
# before we filter the list of makefiles for %/Makefile.common.
# Otherwise an invocation of the form "make -f Makefile.common" will set
# MAKEFILE_LIST to "Makefile.common" which will fail to match the
# pattern %/Makefile.common.
#
MAKEFILE_PATHS = $(foreach makefile,$(MAKEFILE_LIST),$(abspath $(makefile)))
PROOF_ROOT = $(dir $(filter %/Makefile.common,$(MAKEFILE_PATHS)))
CBMC_ROOT = $(shell dirname $(PROOF_ROOT))
PROOF_SOURCE = $(CBMC_ROOT)/sources
PROOF_INCLUDE = $(CBMC_ROOT)/include
PROOF_STUB = $(CBMC_ROOT)/stubs
# Project-specific definitions to override default definitions below
# * Makefile-project-defines will never be overwritten
# * Makefile-template-defines may be overwritten when the starter
# kit is updated
sinclude $(PROOF_ROOT)/Makefile-project-defines
sinclude $(PROOF_ROOT)/Makefile-template-defines
# SRCDIR is the path to the root of the source tree
# This is a default definition that is frequently overridden in
# another Makefile, see the discussion of SRCDIR above.
SRCDIR ?= $(abspath ../..)
# PROOFDIR is the path to the directory containing the proof harness
PROOFDIR ?= $(abspath .)
################################################################
# Define how to run CBMC
# Do property checking with the external SAT solver given by
# EXTERNAL_SAT_SOLVER. Do coverage checking with the default solver,
# since coverage checking requires the use of an incremental solver.
# The EXTERNAL_SAT_SOLVER variable is typically set (if it is at all)
# as an environment variable or as a makefile variable in
# Makefile-project-defines.
#
# For a particular proof, if the default solver is faster, do property
# checking with the default solver by including this definition in the
# proof Makefile:
# USE_EXTERNAL_SAT_SOLVER =
#
ifneq ($(strip $(EXTERNAL_SAT_SOLVER)),)
USE_EXTERNAL_SAT_SOLVER ?= --external-sat-solver $(EXTERNAL_SAT_SOLVER)
endif
CHECKFLAGS += $(USE_EXTERNAL_SAT_SOLVER)
# Job pools
# For version of Litani that are new enough (where `litani print-capabilities`
# prints "pools"), proofs for which `EXPENSIVE = true` is set can be added to a
# "job pool" that restricts how many expensive proofs are run at a time. All
# other proofs will be built in parallel as usual.
#
# In more detail: all compilation, instrumentation, and report jobs are run with
# full parallelism as usual, even for expensive proofs. The CBMC jobs for
# non-expensive proofs are also run in parallel. The only difference is that the
# CBMC safety checks and coverage checks for expensive proofs are run with a
# restricted parallelism level. At any one time, only N of these jobs are run at
# once, amongst all the proofs.
#
# To configure N, Litani needs to be initialized with a pool called "expensive".
# For example, to only run two CBMC safety/coverage jobs at a time from amongst
# all the proofs, you would initialize litani like
# litani init --pools expensive:2
# The run-cbmc-proofs.py script takes care of this initialization through the
# --expensive-jobs-parallelism flag.
#
# To enable this feature, set
# the ENABLE_POOLS variable when running Make, like
# `make ENABLE_POOLS=true report`
# The run-cbmc-proofs.py script takes care of this through the
# --restrict-expensive-jobs flag.
ifeq ($(strip $(ENABLE_POOLS)),)
POOL =
else ifeq ($(strip $(EXPENSIVE)),)
POOL =
else
POOL = --pool expensive
endif
# Similar to the pool feature above. If Litani is new enough, enable
# profiling CBMC's memory use.
ifeq ($(strip $(ENABLE_MEMORY_PROFILING)),)
MEMORY_PROFILING =
else
MEMORY_PROFILING = --profile-memory
endif
# Property checking flags
#
# Each variable below controls a specific property checking flag
# within CBMC. If desired, a property flag can be disabled within
# a particular proof by nulling the corresponding variable. For
# instance, the following line:
#
# CHECK_FLAG_POINTER_CHECK =
#
# would disable the --pointer-check CBMC flag within:
# * an entire project when added to Makefile-project-defines
# * a specific proof when added to the harness Makefile
CBMC_FLAG_MALLOC_MAY_FAIL ?= --malloc-may-fail
CBMC_FLAG_MALLOC_FAIL_NULL ?= --malloc-fail-null
CBMC_FLAG_BOUNDS_CHECK ?= --bounds-check
CBMC_FLAG_CONVERSION_CHECK ?= --conversion-check
CBMC_FLAG_DIV_BY_ZERO_CHECK ?= --div-by-zero-check
CBMC_FLAG_FLOAT_OVERFLOW_CHECK ?= --float-overflow-check
CBMC_FLAG_NAN_CHECK ?= --nan-check
CBMC_FLAG_POINTER_CHECK ?= --pointer-check
CBMC_FLAG_POINTER_OVERFLOW_CHECK ?= --pointer-overflow-check
CBMC_FLAG_POINTER_PRIMITIVE_CHECK ?= --pointer-primitive-check
CBMC_FLAG_SIGNED_OVERFLOW_CHECK ?= --signed-overflow-check
CBMC_FLAG_UNDEFINED_SHIFT_CHECK ?= --undefined-shift-check
CBMC_FLAG_UNSIGNED_OVERFLOW_CHECK ?= --unsigned-overflow-check
CBMC_FLAG_UNWINDING_ASSERTIONS ?= --unwinding-assertions
CBMC_FLAG_UNWIND ?= --unwind 1
CBMC_FLAG_FLUSH ?= --flush
# CBMC flags used for property checking and coverage checking
CBMCFLAGS += $(CBMC_FLAG_UNWIND) $(CBMC_UNWINDSET) $(CBMC_FLAG_FLUSH)
# CBMC flags used for property checking
CHECKFLAGS += $(CBMC_FLAG_MALLOC_MAY_FAIL)
CHECKFLAGS += $(CBMC_FLAG_MALLOC_FAIL_NULL)
CHECKFLAGS += $(CBMC_FLAG_BOUNDS_CHECK)
CHECKFLAGS += $(CBMC_FLAG_CONVERSION_CHECK)
CHECKFLAGS += $(CBMC_FLAG_DIV_BY_ZERO_CHECK)
CHECKFLAGS += $(CBMC_FLAG_FLOAT_OVERFLOW_CHECK)
CHECKFLAGS += $(CBMC_FLAG_NAN_CHECK)
CHECKFLAGS += $(CBMC_FLAG_POINTER_CHECK)
CHECKFLAGS += $(CBMC_FLAG_POINTER_OVERFLOW_CHECK)
CHECKFLAGS += $(CBMC_FLAG_POINTER_PRIMITIVE_CHECK)
CHECKFLAGS += $(CBMC_FLAG_SIGNED_OVERFLOW_CHECK)
CHECKFLAGS += $(CBMC_FLAG_UNDEFINED_SHIFT_CHECK)
CHECKFLAGS += $(CBMC_FLAG_UNSIGNED_OVERFLOW_CHECK)
CHECKFLAGS += $(CBMC_FLAG_UNWINDING_ASSERTIONS)
# CBMC flags used for coverage checking
COVERFLAGS += $(CBMC_FLAG_MALLOC_MAY_FAIL)
COVERFLAGS += $(CBMC_FLAG_MALLOC_FAIL_NULL)
# Additional CBMC flag to CBMC control verbosity.
#
# Meaningful values are
# 0 none
# 1 only errors
# 2 + warnings
# 4 + results
# 6 + status/phase information
# 8 + statistical information
# 9 + progress information
# 10 + debug info
#
# Uncomment the following line or set in Makefile-project-defines
# CBMC_VERBOSITY ?= --verbosity 4
# Additional CBMC flag to control how CBMC treats static variables.
#
# NONDET_STATIC is a list of flags of the form --nondet-static
# and --nondet-static-exclude VAR. The --nondet-static flag causes
# CBMC to initialize static variables with unconstrained value
# (ignoring initializers and default zero-initialization). The
# --nondet-static-exclude VAR excludes VAR for the variables
# initialized with unconstrained values.
NONDET_STATIC ?=
# Flags to pass to goto-cc for compilation and linking
COMPILE_FLAGS ?= -Wall
LINK_FLAGS ?= -Wall
EXPORT_FILE_LOCAL_SYMBOLS ?= --export-file-local-symbols
# Preprocessor include paths -I...
INCLUDES ?=
# Preprocessor definitions -D...
DEFINES ?=
# CBMC object model
#
# CBMC_OBJECT_BITS is the number of bits in a pointer CBMC uses for
# the id of the object to which a pointer is pointing. CBMC uses 8
# bits for the object id by default. The remaining bits in the pointer
# are used for offset into the object. This limits the size of the
# objects that CBMC can model. This Makefile defines this bound on
# object size to be CBMC_MAX_OBJECT_SIZE. You are likely to get
# unexpected results if you try to malloc an object larger than this
# bound.
CBMC_OBJECT_BITS ?= 8
# CBMC loop unwinding (Normally set in the proof Makefile)
#
# UNWINDSET is a list of pairs of the form foo.1:4 meaning that
# CBMC should unwind loop 1 in function foo no more than 4 times.
# For historical reasons, the number 4 is one more than the number
# of times CBMC actually unwinds the loop.
UNWINDSET ?=
# CBMC early loop unwinding (Normally set in the proof Makefile)
#
# Most users can ignore this variable.
#
# This variable exists to support the use of loop and function
# contracts, two features under development for CBMC. Checking the
# assigns clause for function contracts and loop invariants currently
# assumes loop-free bodies for loops and functions with contracts
# (possibly after replacing nested loops with their own loop
# contracts). To satisfy this requirement, it may be necessary to
# unwind some loops before the function contract and loop invariant
# transformations are applied to the goto program. This variable
# EARLY_UNWINDSET is identical to UNWINDSET, and we assume that the
# loops mentioned in EARLY_UNWINDSET and UNWINDSET are disjoint.
EARLY_UNWINDSET ?=
# CBMC function removal (Normally set set in the proof Makefile)
#
# REMOVE_FUNCTION_BODY is a list of function names. CBMC will "undefine"
# the function, and CBMC will treat the function as having no side effects
# and returning an unconstrained value of the appropriate return type.
# The list should include the names of functions being stubbed out.
REMOVE_FUNCTION_BODY ?=
# CBMC function pointer restriction (Normally set in the proof Makefile)
#
# RESTRICT_FUNCTION_POINTER is a list of function pointer restriction
# instructions of the form:
#
# <fun_id>.function_pointer_call.<N>/<fun_id>[,<fun_id>]*
#
# The function pointer call number <N> in the specified function gets
# rewritten to a case switch over a finite list of functions.
# If some possible target functions are omitted from the list a counter
# example trace will be found by CBMC, i.e. the transformation is sound.
# If the target functions are file-local symbols, then mangled names must
# be used.
RESTRICT_FUNCTION_POINTER ?=
# The project source files (Normally set set in the proof Makefile)
#
# PROJECT_SOURCES is the list of project source files to compile,
# including the source file defining the function under test.
PROJECT_SOURCES ?=
# The proof source files (Normally set in the proof Makefile)
#
# PROOF_SOURCES is the list of proof source files to compile, including
# the proof harness, and including any function stubs being used.
PROOF_SOURCES ?=
# The number of seconds that CBMC should be allowed to run for before
# being forcefully terminated. Currently, this is set to be less than
# the time limit for a CodeBuild job, which is eight hours. If a proof
# run takes longer than the time limit of the CI environment, the
# environment will halt the proof run without updating the Litani
# report, making the proof run appear to "hang".
CBMC_TIMEOUT ?= 21600
# Proof writers could add function contracts in their source code.
# These contracts are ignored by default, but may be enabled in two distinct
# contexts using the following two variables:
# 1. To check whether one or more function contracts are sound with respect to
# the function implementation, CHECK_FUNCTION_CONTRACTS should be a list of
# function names.
# 2. To replace calls to certain functions with their correspondent function
# contracts, USE_FUNCTION_CONTRACTS should be a list of function names.
# One must check separately whether a function contract is sound before
# replacing it in calling contexts.
CHECK_FUNCTION_CONTRACTS ?=
CBMC_CHECK_FUNCTION_CONTRACTS := $(patsubst %,--enforce-contract %, $(CHECK_FUNCTION_CONTRACTS))
USE_FUNCTION_CONTRACTS ?=
CBMC_USE_FUNCTION_CONTRACTS := $(patsubst %,--replace-call-with-contract %, $(USE_FUNCTION_CONTRACTS))
# Similarly, proof writers could also add loop contracts in their source code
# to obtain unbounded correctness proofs. Unlike function contracts, loop
# contracts are not reusable and thus are checked and used simultaneously.
# These contracts are also ignored by default, but may be enabled by setting
# the APPLY_LOOP_CONTRACTS variable to 1.
APPLY_LOOP_CONTRACTS ?= 0
ifeq ($(APPLY_LOOP_CONTRACTS),1)
CBMC_APPLY_LOOP_CONTRACTS ?= --apply-loop-contracts
endif
# Silence makefile output (eg, long litani commands) unless VERBOSE is set.
ifndef VERBOSE
MAKEFLAGS := $(MAKEFLAGS) -s
endif
################################################################
################################################################
## Section II: This section defines the process of running a proof
##
## There should be no reason to edit anything below this line.
################################################################
# Paths
CBMC ?= cbmc
GOTO_ANALYZER ?= goto-analyzer
GOTO_CC ?= goto-cc
GOTO_INSTRUMENT ?= goto-instrument
CRANGLER ?= crangler
VIEWER ?= cbmc-viewer
MAKE_SOURCE ?= make-source
VIEWER2 ?= cbmc-viewer
CMAKE ?= cmake
GOTODIR ?= $(PROOFDIR)/gotos
LOGDIR ?= $(PROOFDIR)/logs
PROJECT ?= project
PROOF ?= proof
HARNESS_GOTO ?= $(GOTODIR)/$(HARNESS_FILE)
PROJECT_GOTO ?= $(GOTODIR)/$(PROJECT)
PROOF_GOTO ?= $(GOTODIR)/$(PROOF)
################################################################
# Useful macros for values that are hard to reference
SPACE :=$() $()
COMMA :=,
################################################################
# Set C compiler defines
CBMCFLAGS += --object-bits $(CBMC_OBJECT_BITS)
COMPILE_FLAGS += --object-bits $(CBMC_OBJECT_BITS)
DEFINES += -DCBMC=1
DEFINES += -DCBMC_OBJECT_BITS=$(CBMC_OBJECT_BITS)
DEFINES += -DCBMC_MAX_OBJECT_SIZE="(SIZE_MAX>>(CBMC_OBJECT_BITS+1))"
# CI currently assumes cbmc invocation has at most one --unwindset
ifdef UNWINDSET
ifneq ($(strip $(UNWINDSET)),"")
CBMC_UNWINDSET := --unwindset $(subst $(SPACE),$(COMMA),$(strip $(UNWINDSET)))
endif
endif
ifdef EARLY_UNWINDSET
ifneq ($(strip $(EARLY_UNWINDSET)),"")
CBMC_EARLY_UNWINDSET := --unwindset $(subst $(SPACE),$(COMMA),$(strip $(EARLY_UNWINDSET)))
endif
endif
CBMC_REMOVE_FUNCTION_BODY := $(patsubst %,--remove-function-body %, $(REMOVE_FUNCTION_BODY))
CBMC_RESTRICT_FUNCTION_POINTER := $(patsubst %,--restrict-function-pointer %, $(RESTRICT_FUNCTION_POINTER))
################################################################
# Targets for rewriting source files with crangler
# Construct crangler configuration files
#
# REWRITTEN_SOURCES is a list of crangler output files source.i.
# This target assumes that for each source.i
# * source.i_SOURCE is the path to a source file,
# * source.i_FUNCTIONS is a list of functions (may be empty)
# * source.i_OBJECTS is a list of variables (may be empty)
# This target constructs the crangler configuration file source.i.json
# of the form
# {
# "sources": [ "/proj/code.c" ],
# "includes": [ "/proj/include" ],
# "defines": [ "VAR=1" ],
# "functions": [ {"function_name": ["remove static"]} ],
# "objects": [ {"variable_name": ["remove static"]} ],
# "output": "source.i"
# }
# to remove the static attribute from function_name and variable_name
# in the source file source.c and write the result to source.i.
#
# This target assumes that filenames include no spaces and that
# the INCLUDES and DEFINES variables include no spaces after -I
# and -D. For example, use "-DVAR=1" and not "-D VAR=1".
#
# Define *_SOURCE, *_FUNCTIONS, and *_OBJECTS in the proof Makefile.
# The string source.i is usually an absolute path $(PROOFDIR)/code.i
# to a file in the proof directory that contains the proof Makefile.
# The proof Makefile usually includes the definitions
# $(PROOFDIR)/code.i_SOURCE = /proj/code.c
# $(PROOFDIR)/code.i_FUNCTIONS = function_name
# $(PROOFDIR)/code.i_OBJECTS = variable_name
# Because these definitions refer to PROOFDIR that is defined in this
# Makefile.common, these definitions must appear after the inclusion
# of Makefile.common in the proof Makefile.
#
$(foreach rs,$(REWRITTEN_SOURCES),$(eval $(rs).json: $($(rs)_SOURCE)))
$(foreach rs,$(REWRITTEN_SOURCES),$(rs).json):
echo '{'\
'"sources": ['\
'"$($(@:.json=)_SOURCE)"'\
'],'\
'"includes": ['\
'$(subst $(SPACE),$(COMMA),$(patsubst -I%,"%",$(strip $(INCLUDES))))' \
'],'\
'"defines": ['\
'$(subst $(SPACE),$(COMMA),$(patsubst -D%,"%",$(subst ",\",$(strip $(DEFINES)))))' \
'],'\
'"functions": ['\
'{'\
'$(subst ~, ,$(subst $(SPACE),$(COMMA),$(patsubst %,"%":["remove~static"],$($(@:.json=)_FUNCTIONS))))' \
'}'\
'],'\
'"objects": ['\
'{'\
'$(subst ~, ,$(subst $(SPACE),$(COMMA),$(patsubst %,"%":["remove~static"],$($(@:.json=)_OBJECTS))))' \
'}'\
'],'\
'"output": "$(@:.json=)"'\
'}' > $@
# Rewrite source files with crangler
#
$(foreach rs,$(REWRITTEN_SOURCES),$(eval $(rs): $(rs).json))
$(REWRITTEN_SOURCES):
$(LITANI) add-job \
--command \
'$(CRANGLER) $@.json' \
--inputs $($@_SOURCE) \
--outputs $@ \
--stdout-file $(LOGDIR)/crangler-$(subst /,_,$(subst .,_,$@))-log.txt \
--interleave-stdout-stderr \
--pipeline-name "$(PROOF_UID)" \
--ci-stage build \
--description "$(PROOF_UID): removing static"
################################################################
# Build targets that make the relevant .goto files
# Compile project sources
$(PROJECT_GOTO)1.goto: $(PROJECT_SOURCES) $(REWRITTEN_SOURCES)
$(LITANI) add-job \
--command \
'$(GOTO_CC) $(CBMC_VERBOSITY) $(COMPILE_FLAGS) $(EXPORT_FILE_LOCAL_SYMBOLS) $(INCLUDES) $(DEFINES) $^ -o $@' \
--inputs $^ \
--outputs $@ \
--stdout-file $(LOGDIR)/project_sources-log.txt \
--pipeline-name "$(PROOF_UID)" \
--ci-stage build \
--description "$(PROOF_UID): building project binary"
# Compile proof sources
$(PROOF_GOTO)1.goto: $(PROOF_SOURCES)
$(LITANI) add-job \
--command \
'$(GOTO_CC) $(CBMC_VERBOSITY) $(COMPILE_FLAGS) $(EXPORT_FILE_LOCAL_SYMBOLS) $(INCLUDES) $(DEFINES) $^ -o $@' \
--inputs $^ \
--outputs $@ \
--stdout-file $(LOGDIR)/proof_sources-log.txt \
--pipeline-name "$(PROOF_UID)" \
--ci-stage build \
--description "$(PROOF_UID): building proof binary"
# Remove function bodies from project sources
$(PROJECT_GOTO)2.goto: $(PROJECT_GOTO)1.goto
$(LITANI) add-job \
--command \
'$(GOTO_INSTRUMENT) $(CBMC_VERBOSITY) $(CBMC_REMOVE_FUNCTION_BODY) $^ $@' \
--inputs $^ \
--outputs $@ \
--stdout-file $(LOGDIR)/remove_function_body-log.txt \
--pipeline-name "$(PROOF_UID)" \
--ci-stage build \
--description "$(PROOF_UID): removing function bodies from project sources"
# Link project and proof sources into the proof harness
$(HARNESS_GOTO)1.goto: $(PROOF_GOTO)1.goto $(PROJECT_GOTO)2.goto
$(LITANI) add-job \
--command '$(GOTO_CC) $(CBMC_VERBOSITY) --function $(HARNESS_ENTRY) $^ $(LINK_FLAGS) -o $@' \
--inputs $^ \
--outputs $@ \
--stdout-file $(LOGDIR)/link_proof_project-log.txt \
--pipeline-name "$(PROOF_UID)" \
--ci-stage build \
--description "$(PROOF_UID): linking project to proof"
# Restrict function pointers
$(HARNESS_GOTO)2.goto: $(HARNESS_GOTO)1.goto
$(LITANI) add-job \
--command \
'$(GOTO_INSTRUMENT) $(CBMC_VERBOSITY) $(CBMC_RESTRICT_FUNCTION_POINTER) $^ $@' \
--inputs $^ \
--outputs $@ \
--stdout-file $(LOGDIR)/restrict_function_pointer-log.txt \
--pipeline-name "$(PROOF_UID)" \
--ci-stage build \
--description "$(PROOF_UID): restricting function pointers in project sources"
# Fill static variable with unconstrained values
$(HARNESS_GOTO)3.goto: $(HARNESS_GOTO)2.goto
$(LITANI) add-job \
--command \
'$(GOTO_INSTRUMENT) $(CBMC_VERBOSITY) $(NONDET_STATIC) $^ $@' \
--inputs $^ \
--outputs $@ \
--stdout-file $(LOGDIR)/nondet_static-log.txt \
--pipeline-name "$(PROOF_UID)" \
--ci-stage build \
--description "$(PROOF_UID): setting static variables to nondet"
# Omit unused functions (sharpens coverage calculations)
$(HARNESS_GOTO)4.goto: $(HARNESS_GOTO)3.goto
$(LITANI) add-job \
--command \
'$(GOTO_INSTRUMENT) $(CBMC_VERBOSITY) --drop-unused-functions $^ $@' \
--inputs $^ \
--outputs $@ \
--stdout-file $(LOGDIR)/drop_unused_functions-log.txt \
--pipeline-name "$(PROOF_UID)" \
--ci-stage build \
--description "$(PROOF_UID): dropping unused functions"
# Omit initialization of unused global variables (reduces problem size)
$(HARNESS_GOTO)5.goto: $(HARNESS_GOTO)4.goto
$(LITANI) add-job \
--command \
'$(GOTO_INSTRUMENT) $(CBMC_VERBOSITY) --slice-global-inits $^ $@' \
--inputs $^ \
--outputs $@ \
--stdout-file $(LOGDIR)/slice_global_inits-log.txt \
--pipeline-name "$(PROOF_UID)" \
--ci-stage build \
--description "$(PROOF_UID): slicing global initializations"
# Replace function calls with function contracts
# This must be done before enforcing function contracts,
# since contract enforcement inlines all function calls.
$(HARNESS_GOTO)6.goto: $(HARNESS_GOTO)5.goto
$(LITANI) add-job \
--command \
'$(GOTO_INSTRUMENT) $(CBMC_VERBOSITY) $(CBMC_USE_FUNCTION_CONTRACTS) $^ $@' \
--inputs $^ \
--outputs $@ \
--stdout-file $(LOGDIR)/use_function_contracts-log.txt \
--pipeline-name "$(PROOF_UID)" \
--ci-stage build \
--description "$(PROOF_UID): replacing function calls with function contracts"
# Unwind loops for loop and function contracts
$(HARNESS_GOTO)7.goto: $(HARNESS_GOTO)6.goto
$(LITANI) add-job \
--command \
'$(GOTO_INSTRUMENT) $(CBMC_VERBOSITY) $(CBMC_EARLY_UNWINDSET) $(CBMC_FLAG_UNWINDING_ASSERTIONS) $^ $@' \
--inputs $^ \
--outputs $@ \
--stdout-file $(LOGDIR)/unwind_loops-log.txt \
--pipeline-name "$(PROOF_UID)" \
--ci-stage build \
--description "$(PROOF_UID): unwinding loops"
# Apply loop contracts
$(HARNESS_GOTO)8.goto: $(HARNESS_GOTO)7.goto
$(LITANI) add-job \
--command \
'$(GOTO_INSTRUMENT) $(CBMC_VERBOSITY) $(CBMC_APPLY_LOOP_CONTRACTS) $^ $@' \
--inputs $^ \
--outputs $@ \
--stdout-file $(LOGDIR)/apply_loop_contracts-log.txt \
--pipeline-name "$(PROOF_UID)" \
--ci-stage build \
--description "$(PROOF_UID): applying loop contracts"
# Check function contracts
$(HARNESS_GOTO)9.goto: $(HARNESS_GOTO)8.goto
$(LITANI) add-job \
--command \
'$(GOTO_INSTRUMENT) $(CBMC_VERBOSITY) $(CBMC_CHECK_FUNCTION_CONTRACTS) $^ $@' \
--inputs $^ \
--outputs $@ \
--stdout-file $(LOGDIR)/check_function_contracts-log.txt \
--pipeline-name "$(PROOF_UID)" \
--ci-stage build \
--description "$(PROOF_UID): checking function contracts"
# Final name for proof harness
$(HARNESS_GOTO).goto: $(HARNESS_GOTO)9.goto
$(LITANI) add-job \
--command 'cp $< $@' \
--inputs $^ \
--outputs $@ \
--pipeline-name "$(PROOF_UID)" \
--ci-stage build \
--description "$(PROOF_UID): copying final goto-binary"
################################################################
# Targets to run the analysis commands
$(LOGDIR)/result.txt: $(HARNESS_GOTO).goto
$(LITANI) add-job \
$(POOL) \
--command \
'$(CBMC) $(CBMC_VERBOSITY) $(CBMCFLAGS) $(CBMC_FLAG_UNWINDING_ASSERTIONS) $(CHECKFLAGS) --trace $<' \
--inputs $^ \
--outputs $@ \
--ci-stage test \
--stdout-file $@ \
$(MEMORY_PROFILING) \
--ignore-returns 10 \
--timeout $(CBMC_TIMEOUT) \
--pipeline-name "$(PROOF_UID)" \
--tags "stats-group:safety checks" \
--stderr-file $(LOGDIR)/result-err-log.txt \
--description "$(PROOF_UID): checking safety properties"
$(LOGDIR)/result.xml: $(HARNESS_GOTO).goto
$(LITANI) add-job \
$(POOL) \
--command \
'$(CBMC) $(CBMC_VERBOSITY) $(CBMCFLAGS) $(CBMC_FLAG_UNWINDING_ASSERTIONS) $(CHECKFLAGS) --trace --xml-ui $<' \
--inputs $^ \
--outputs $@ \
--ci-stage test \
--stdout-file $@ \
$(MEMORY_PROFILING) \
--ignore-returns 10 \
--timeout $(CBMC_TIMEOUT) \
--pipeline-name "$(PROOF_UID)" \
--tags "stats-group:safety checks" \
--stderr-file $(LOGDIR)/result-err-log.txt \
--description "$(PROOF_UID): checking safety properties"
$(LOGDIR)/property.xml: $(HARNESS_GOTO).goto
$(LITANI) add-job \
--command \
'$(CBMC) $(CBMC_VERBOSITY) $(CBMCFLAGS) $(CBMC_FLAG_UNWINDING_ASSERTIONS) $(CHECKFLAGS) --show-properties --xml-ui $<' \
--inputs $^ \
--outputs $@ \
--ci-stage test \
--stdout-file $@ \
--ignore-returns 10 \
--pipeline-name "$(PROOF_UID)" \
--stderr-file $(LOGDIR)/property-err-log.txt \
--description "$(PROOF_UID): printing safety properties"
$(LOGDIR)/coverage.xml: $(HARNESS_GOTO).goto
$(LITANI) add-job \
$(POOL) \
--command \
'$(CBMC) $(CBMC_VERBOSITY) $(CBMCFLAGS) $(COVERFLAGS) --cover location --xml-ui $<' \
--inputs $^ \
--outputs $@ \
--ci-stage test \
--stdout-file $@ \
$(MEMORY_PROFILING) \
--ignore-returns 10 \
--timeout $(CBMC_TIMEOUT) \
--pipeline-name "$(PROOF_UID)" \
--tags "stats-group:coverage computation" \
--stderr-file $(LOGDIR)/coverage-err-log.txt \
--description "$(PROOF_UID): calculating coverage"
define VIEWER_CMD
$(VIEWER) \
--result $(LOGDIR)/result.txt \
--block $(LOGDIR)/coverage.xml \
--property $(LOGDIR)/property.xml \
--srcdir $(SRCDIR) \
--goto $(HARNESS_GOTO).goto \
--htmldir $(PROOFDIR)/html
endef
export VIEWER_CMD
$(PROOFDIR)/html: $(LOGDIR)/result.txt $(LOGDIR)/property.xml $(LOGDIR)/coverage.xml
$(LITANI) add-job \
--command "$$VIEWER_CMD" \
--inputs $^ \
--outputs $(PROOFDIR)/html \
--pipeline-name "$(PROOF_UID)" \
--ci-stage report \
--stdout-file $(LOGDIR)/viewer-log.txt \
--description "$(PROOF_UID): generating report"
# Caution: run make-source before running property and coverage checking
# The current make-source script removes the goto binary
$(LOGDIR)/source.json:
mkdir -p $(dir $@)
$(RM) -r $(GOTODIR)
$(MAKE_SOURCE) --srcdir $(SRCDIR) --wkdir $(PROOFDIR) > $@
$(RM) -r $(GOTODIR)
define VIEWER2_CMD
$(VIEWER2) \
--result $(LOGDIR)/result.xml \
--coverage $(LOGDIR)/coverage.xml \
--property $(LOGDIR)/property.xml \
--srcdir $(SRCDIR) \
--goto $(HARNESS_GOTO).goto \
--reportdir $(PROOFDIR)/report \
--config $(PROOFDIR)/cbmc-viewer.json
endef
export VIEWER2_CMD
# Omit logs/source.json from report generation until make-sources
# works correctly with Makefiles that invoke the compiler with
# mutliple source files at once.
$(PROOFDIR)/report: $(LOGDIR)/result.xml $(LOGDIR)/property.xml $(LOGDIR)/coverage.xml
$(LITANI) add-job \
--command "$$VIEWER2_CMD" \
--inputs $^ \
--outputs $(PROOFDIR)/report \
--pipeline-name "$(PROOF_UID)" \
--stdout-file $(LOGDIR)/viewer-log.txt \
--ci-stage report \
--description "$(PROOF_UID): generating report"
litani-path:
@echo $(LITANI)
# ##############################################################
# Phony Rules
#
# These rules provide a convenient way to run a single proof up to a
# certain stage. Users can browse into a proof directory and run
# "make -Bj 3 report" to generate a report for just that proof, or
# "make goto" to build the goto binary. Under the hood, this runs litani
# for just that proof.
_goto: $(HARNESS_GOTO).goto
goto:
@ echo Running 'litani init'
$(LITANI) init --project $(PROJECT_NAME)
@ echo Running 'litani add-job'
$(MAKE) -B _goto
@ echo Running 'litani build'
$(LITANI) run-build
_result: $(LOGDIR)/result.txt
result:
@ echo Running 'litani init'
$(LITANI) init --project $(PROJECT_NAME)
@ echo Running 'litani add-job'
$(MAKE) -B _result
@ echo Running 'litani build'
$(LITANI) run-build
_property: $(LOGDIR)/property.xml
property:
@ echo Running 'litani init'
$(LITANI) init --project $(PROJECT_NAME)
@ echo Running 'litani add-job'
$(MAKE) -B _property
@ echo Running 'litani build'
$(LITANI) run-build
_coverage: $(LOGDIR)/coverage.xml
coverage:
@ echo Running 'litani init'
$(LITANI) init --project $(PROJECT_NAME)
@ echo Running 'litani add-job'
$(MAKE) -B _coverage
@ echo Running 'litani build'
$(LITANI) run-build
# Choose the invocation of cbmc-viewer depending on which version of
# cbmc-viewer is installed. The --version flag is not implemented in
# version 1 --- it is an "unrecognized argument" --- but it is
# implemented in version 2.
_report1: $(PROOFDIR)/html
_report2: $(PROOFDIR)/report
_report:
(cbmc-viewer --version 2>&1 | grep "unrecognized argument" > /dev/null) && \
$(MAKE) -B _report1 || $(MAKE) -B _report2
report report1 report2:
@ echo Running 'litani init'
$(LITANI) init --project $(PROJECT_NAME)
@ echo Running 'litani add-job'
$(MAKE) -B _report
@ echo Running 'litani build'
$(LITANI) run-build
################################################################
# Targets to clean up after ourselves
clean:
-$(RM) $(DEPENDENT_GOTOS)
-$(RM) TAGS*
-$(RM) *~ \#*
-$(RM) $(REWRITTEN_SOURCES) $(foreach rs,$(REWRITTEN_SOURCES),$(rs).json)
veryclean: clean
-$(RM) -r html report
-$(RM) -r $(LOGDIR) $(GOTODIR)
.PHONY: \
_coverage \
_goto \
_property \
_report \
_report2 \
_result \
clean \
coverage \
goto \
litani-path \
property \
report \
report2 \
result \
setup_dependencies \
testdeps \
veryclean \
#
################################################################
# Rule for generating cbmc-batch.yaml, used by the CI at
# https://github.com/awslabs/aws-batch-cbmc/
JOB_OS ?= ubuntu16
JOB_MEMORY ?= 32000
# Proofs that are expected to fail should set EXPECTED to
# "FAILED" in their Makefile. Values other than SUCCESSFUL
# or FAILED will cause a CI error.
EXPECTED ?= SUCCESSFUL
define yaml_encode_options
"$(shell echo $(1) | sed 's/ ,/ /g' | sed 's/ /;/g')"
endef
CI_FLAGS = $(CBMCFLAGS) $(CHECKFLAGS) $(COVERFLAGS)
cbmc-batch.yaml:
@$(RM) $@
@echo 'build_memory: $(JOB_MEMORY)' > $@
@echo 'cbmcflags: $(strip $(call yaml_encode_options,$(CI_FLAGS)))' >> $@
@echo 'coverage_memory: $(JOB_MEMORY)' >> $@
@echo 'expected: $(EXPECTED)' >> $@
@echo 'goto: $(HARNESS_GOTO).goto' >> $@
@echo 'jobos: $(JOB_OS)' >> $@
@echo 'property_memory: $(JOB_MEMORY)' >> $@
@echo 'report_memory: $(JOB_MEMORY)' >> $@
.PHONY: cbmc-batch.yaml
################################################################
# Run "make echo-proof-uid" to print the proof ID of a proof. This can be
# used by scripts to ensure that every proof has an ID, that there are
# no duplicates, etc.
.PHONY: echo-proof-uid
echo-proof-uid:
@echo $(PROOF_UID)
.PHONY: echo-project-name
echo-project-name:
@echo $(PROJECT_NAME)
################################################################
# Project-specific targets requiring values defined above
sinclude $(PROOF_ROOT)/Makefile-project-targets
# CI-specific targets to drive cbmc in CI
sinclude $(PROOF_ROOT)/Makefile-project-testing
################################################################

View File

@ -0,0 +1,27 @@
CBMC proofs
===========
This directory contains the CBMC proofs. Each proof is in its own
directory.
This directory includes four Makefiles.
One Makefile describes the basic workflow for building and running proofs:
* Makefile.common:
* make: builds the goto binary, does the cbmc property checking
and coverage checking, and builds the final report.
* make goto: builds the goto binary
* make result: does cbmc property checking
* make coverage: does cbmc coverage checking
* make report: builds the final report
Three included Makefiles describe project-specific settings and can override
definitions in Makefile.common:
* Makefile-project-defines: definitions like compiler flags
required to build the goto binaries, and definitions to override
definitions in Makefile.common.
* Makefile-project-targets: other make targets needed for the project
* Makefile-project-testing: other definitions and targets needed for
unit testing or continuous integration.

View File

@ -0,0 +1,92 @@
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
import json
import logging
def _get_max_length_per_column_list(data):
ret = [len(item) + 1 for item in data[0]]
for row in data[1:]:
for idx, item in enumerate(row):
ret[idx] = max(ret[idx], len(item) + 1)
return ret
def _get_table_header_separator(max_length_per_column_list):
line_sep = ""
for max_length_of_word_in_col in max_length_per_column_list:
line_sep += "|" + "-" * (max_length_of_word_in_col + 1)
line_sep += "|\n"
return line_sep
def _get_entries(max_length_per_column_list, row_data):
entries = []
for row in row_data:
entry = ""
for idx, word in enumerate(row):
max_length_of_word_in_col = max_length_per_column_list[idx]
space_formatted_word = (max_length_of_word_in_col - len(word)) * " "
entry += "| " + word + space_formatted_word
entry += "|\n"
entries.append(entry)
return entries
def _get_rendered_table(data):
table = []
max_length_per_column_list = _get_max_length_per_column_list(data)
entries = _get_entries(max_length_per_column_list, data)
for idx, entry in enumerate(entries):
if idx == 1:
line_sep = _get_table_header_separator(max_length_per_column_list)
table.append(line_sep)
table.append(entry)
table.append("\n")
return "".join(table)
def _get_status_and_proof_summaries(run_dict):
"""Parse a dict representing a Litani run and create lists summarizing the
proof results.
Parameters
----------
run_dict
A dictionary representing a Litani run.
Returns
-------
A list of 2 lists.
The first sub-list maps a status to the number of proofs with that status.
The second sub-list maps each proof to its status.
"""
count_statuses = {}
proofs = [["Proof", "Status"]]
for proof_pipeline in run_dict["pipelines"]:
status_pretty_name = proof_pipeline["status"].title().replace("_", " ")
try:
count_statuses[status_pretty_name] += 1
except KeyError:
count_statuses[status_pretty_name] = 1
proof = proof_pipeline["name"]
proofs.append([proof, status_pretty_name])
statuses = [["Status", "Count"]]
for status, count in count_statuses.items():
statuses.append([status, str(count)])
return [statuses, proofs]
def print_proof_results(out_file):
"""
Print 2 strings that summarize the proof results.
When printing, each string will render as a GitHub flavored Markdown table.
"""
try:
with open(out_file, encoding='utf-8') as run_json:
run_dict = json.load(run_json)
for summary in _get_status_and_proof_summaries(run_dict):
print(_get_rendered_table(summary))
except Exception as ex: # pylint: disable=broad-except
logging.critical("Could not print results. Exception: %s", str(ex))

View File

@ -0,0 +1,414 @@
#!/usr/bin/env python3
#
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
import argparse
import asyncio
import json
import logging
import math
import os
import pathlib
import re
import subprocess
import sys
import tempfile
from lib.summarize import print_proof_results
DESCRIPTION = "Configure and run all CBMC proofs in parallel"
# Keep the epilog hard-wrapped at 70 characters, as it gets printed
# verbatim in the terminal. 70 characters stops here --------------> |
EPILOG = """
This tool automates the process of running `make report` in each of
the CBMC proof directories. The tool calculates the dependency graph
of all tasks needed to build, run, and report on all the proofs, and
executes these tasks in parallel.
The tool is roughly equivalent to doing this:
litani init --project "my-cool-project";
find . -name cbmc-proof.txt | while read -r proof; do
pushd $(dirname ${proof});
# The `make _report` rule adds a single proof to litani
# without running it
make _report;
popd;
done
litani run-build;
except that it is much faster and provides some convenience options.
The CBMC CI runs this script with no arguments to build and run all
proofs in parallel. The value of "my-cool-project" is taken from the
PROJECT_NAME variable in Makefile-project-defines.
The --no-standalone argument omits the `litani init` and `litani
run-build`; use it when you want to add additional proof jobs, not
just the CBMC ones. In that case, you would run `litani init`
yourself; then run `run-cbmc-proofs --no-standalone`; add any
additional jobs that you want to execute with `litani add-job`; and
finally run `litani run-build`.
The litani dashboard will be written under the `output` directory; the
cbmc-viewer reports remain in the `$PROOF_DIR/report` directory. The
HTML dashboard from the latest Litani run will always be symlinked to
`output/latest/html/index.html`, so you can keep that page open in
your browser and reload the page whenever you re-run this script.
"""
# 70 characters stops here ----------------------------------------> |
def get_project_name():
cmd = [
"make",
"--no-print-directory",
"-f", "Makefile.common",
"echo-project-name",
]
logging.debug(" ".join(cmd))
proc = subprocess.run(cmd, universal_newlines=True, stdout=subprocess.PIPE, check=False)
if proc.returncode:
logging.critical("could not run make to determine project name")
sys.exit(1)
if not proc.stdout.strip():
logging.warning(
"project name has not been set; using generic name instead. "
"Set the PROJECT_NAME value in Makefile-project-defines to "
"remove this warning")
return "<PROJECT NAME HERE>"
return proc.stdout.strip()
def get_args():
pars = argparse.ArgumentParser(
description=DESCRIPTION, epilog=EPILOG,
formatter_class=argparse.RawDescriptionHelpFormatter)
for arg in [{
"flags": ["-j", "--parallel-jobs"],
"type": int,
"metavar": "N",
"help": "run at most N proof jobs in parallel",
}, {
"flags": ["--fail-on-proof-failure"],
"action": "store_true",
"help": "exit with return code `10' if any proof failed"
" (default: exit 0)",
}, {
"flags": ["--no-standalone"],
"action": "store_true",
"help": "only configure proofs: do not initialize nor run",
}, {
"flags": ["-p", "--proofs"],
"nargs": "+",
"metavar": "DIR",
"help": "only run proof in directory DIR (can pass more than one)",
}, {
"flags": ["--project-name"],
"metavar": "NAME",
"default": get_project_name(),
"help": "project name for report. Default: %(default)s",
}, {
"flags": ["--marker-file"],
"metavar": "FILE",
"default": "cbmc-proof.txt",
"help": (
"name of file that marks proof directories. Default: "
"%(default)s"),
}, {
"flags": ["--no-memory-profile"],
"action": "store_true",
"help": "disable memory profiling, even if Litani supports it"
}, {
"flags": ["--no-expensive-limit"],
"action": "store_true",
"help": "do not limit parallelism of 'EXPENSIVE' jobs",
}, {
"flags": ["--expensive-jobs-parallelism"],
"metavar": "N",
"default": 1,
"type": int,
"help": (
"how many proof jobs marked 'EXPENSIVE' to run in parallel. "
"Default: %(default)s"),
}, {
"flags": ["--verbose"],
"action": "store_true",
"help": "verbose output",
}, {
"flags": ["--debug"],
"action": "store_true",
"help": "debug output",
}, {
"flags": ["--summarize"],
"action": "store_true",
"help": "summarize proof results with two tables on stdout",
}, {
"flags": ["--version"],
"action": "version",
"version": "CBMC starter kit 2.5",
"help": "display version and exit"
}]:
flags = arg.pop("flags")
pars.add_argument(*flags, **arg)
return pars.parse_args()
def set_up_logging(verbose):
if verbose:
level = logging.DEBUG
else:
level = logging.WARNING
logging.basicConfig(
format="run-cbmc-proofs: %(message)s", level=level)
def task_pool_size():
ret = os.cpu_count()
if ret is None or ret < 3:
return 1
return ret - 2
def print_counter(counter):
# pylint: disable=consider-using-f-string
print("\rConfiguring CBMC proofs: "
"{complete:{width}} / {total:{width}}".format(**counter), end="", file=sys.stderr)
def get_proof_dirs(proof_root, proof_list, marker_file):
if proof_list is not None:
proofs_remaining = list(proof_list)
else:
proofs_remaining = []
for root, _, fyles in os.walk(proof_root):
proof_name = str(pathlib.Path(root).name)
if root != str(proof_root) and ".litani_cache_dir" in fyles:
pathlib.Path(f"{root}/.litani_cache_dir").unlink()
if proof_list and proof_name not in proof_list:
continue
if proof_list and proof_name in proofs_remaining:
proofs_remaining.remove(proof_name)
if marker_file in fyles:
yield root
if proofs_remaining:
logging.critical(
"The following proofs were not found: %s",
", ".join(proofs_remaining))
sys.exit(1)
def run_build(litani, jobs, fail_on_proof_failure, summarize):
cmd = [str(litani), "run-build"]
if jobs:
cmd.extend(["-j", str(jobs)])
if fail_on_proof_failure:
cmd.append("--fail-on-pipeline-failure")
if summarize:
out_file = pathlib.Path(tempfile.gettempdir(), "run.json").resolve()
cmd.extend(["--out-file", str(out_file)])
logging.debug(" ".join(cmd))
proc = subprocess.run(cmd, check=False)
if proc.returncode and not fail_on_proof_failure:
logging.critical("Failed to run litani run-build")
sys.exit(1)
if summarize:
print_proof_results(out_file)
out_file.unlink()
if proc.returncode:
logging.error("One or more proofs failed")
sys.exit(10)
def get_litani_path(proof_root):
cmd = [
"make",
"--no-print-directory",
f"PROOF_ROOT={proof_root}",
"-f", "Makefile.common",
"litani-path",
]
logging.debug(" ".join(cmd))
proc = subprocess.run(cmd, universal_newlines=True, stdout=subprocess.PIPE, check=False)
if proc.returncode:
logging.critical("Could not determine path to litani")
sys.exit(1)
return proc.stdout.strip()
def get_litani_capabilities(litani_path):
cmd = [litani_path, "print-capabilities"]
proc = subprocess.run(
cmd, text=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, check=False)
if proc.returncode:
return []
try:
return json.loads(proc.stdout)
except RuntimeError:
logging.warning("Could not load litani capabilities: '%s'", proc.stdout)
return []
def check_uid_uniqueness(proof_dir, proof_uids):
with (pathlib.Path(proof_dir) / "Makefile").open() as handle:
for line in handle:
match = re.match(r"^PROOF_UID\s*=\s*(?P<uid>\w+)", line)
if not match:
continue
if match["uid"] not in proof_uids:
proof_uids[match["uid"]] = proof_dir
return
logging.critical(
"The Makefile in directory '%s' should have a different "
"PROOF_UID than the Makefile in directory '%s'",
proof_dir, proof_uids[match["uid"]])
sys.exit(1)
logging.critical(
"The Makefile in directory '%s' should contain a line like", proof_dir)
logging.critical("PROOF_UID = ...")
logging.critical("with a unique identifier for the proof.")
sys.exit(1)
def should_enable_memory_profiling(litani_caps, args):
if args.no_memory_profile:
return False
return "memory_profile" in litani_caps
def should_enable_pools(litani_caps, args):
if args.no_expensive_limit:
return False
return "pools" in litani_caps
async def configure_proof_dirs( # pylint: disable=too-many-arguments
queue, counter, proof_uids, enable_pools, enable_memory_profiling, debug):
while True:
print_counter(counter)
path = str(await queue.get())
check_uid_uniqueness(path, proof_uids)
pools = ["ENABLE_POOLS=true"] if enable_pools else []
profiling = [
"ENABLE_MEMORY_PROFILING=true"] if enable_memory_profiling else []
# Allow interactive tasks to preempt proof configuration
proc = await asyncio.create_subprocess_exec(
"nice", "-n", "15", "make", *pools,
*profiling, "-B", "_report", "" if debug else "--quiet", cwd=path,
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
stdout, stderr = await proc.communicate()
logging.debug("returncode: %s", str(proc.returncode))
logging.debug("stdout:")
for line in stdout.decode().splitlines():
logging.debug(line)
logging.debug("stderr:")
for line in stderr.decode().splitlines():
logging.debug(line)
counter["fail" if proc.returncode else "pass"].append(path)
counter["complete"] += 1
print_counter(counter)
queue.task_done()
async def main(): # pylint: disable=too-many-locals
args = get_args()
set_up_logging(args.verbose)
proof_root = pathlib.Path(os.getcwd())
litani = get_litani_path(proof_root)
litani_caps = get_litani_capabilities(litani)
enable_pools = should_enable_pools(litani_caps, args)
init_pools = [
"--pools", f"expensive:{args.expensive_jobs_parallelism}"
] if enable_pools else []
if not args.no_standalone:
cmd = [
str(litani), "init", *init_pools, "--project", args.project_name,
"--no-print-out-dir",
]
if "output_directory_flags" in litani_caps:
out_prefix = proof_root / "output"
out_symlink = out_prefix / "latest"
out_index = out_symlink / "html" / "index.html"
cmd.extend([
"--output-prefix", str(out_prefix),
"--output-symlink", str(out_symlink),
])
print(
"\nFor your convenience, the output of this run will be symbolically linked to ",
out_index, "\n")
logging.debug(" ".join(cmd))
proc = subprocess.run(cmd, check=False)
if proc.returncode:
logging.critical("Failed to run litani init")
sys.exit(1)
proof_dirs = list(get_proof_dirs(
proof_root, args.proofs, args.marker_file))
if not proof_dirs:
logging.critical("No proof directories found")
sys.exit(1)
proof_queue = asyncio.Queue()
for proof_dir in proof_dirs:
proof_queue.put_nowait(proof_dir)
counter = {
"pass": [],
"fail": [],
"complete": 0,
"total": len(proof_dirs),
"width": int(math.log10(len(proof_dirs))) + 1
}
proof_uids = {}
tasks = []
enable_memory_profiling = should_enable_memory_profiling(litani_caps, args)
for _ in range(task_pool_size()):
task = asyncio.create_task(configure_proof_dirs(
proof_queue, counter, proof_uids, enable_pools,
enable_memory_profiling, args.debug))
tasks.append(task)
await proof_queue.join()
print_counter(counter)
print("", file=sys.stderr)
if counter["fail"]:
logging.critical(
"Failed to configure the following proofs:\n%s", "\n".join(
[str(f) for f in counter["fail"]]))
sys.exit(1)
if not args.no_standalone:
run_build(litani, args.parallel_jobs, args.fail_on_proof_failure, args.summarize)
if __name__ == "__main__":
asyncio.run(main())

View File

@ -0,0 +1,19 @@
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
HARNESS_FILE=skipAnyLiteral_harness
PROOF_UID=skipAnyLiteral
# This value was experimentally chosen to provide 100% coverage
# without tripping unwinding assertions and without exhausting memory.
CBMC_MAX_BUFSIZE=6
UNWINDSET += skipAnyLiteral.0:$(CBMC_MAX_BUFSIZE)
UNWINDSET += skipLiteral.0:$(CBMC_MAX_BUFSIZE)
UNWINDSET += strnEq.0:$(CBMC_MAX_BUFSIZE)
include ../Makefile-json.common
# Substitution command to pass to sed for patching core_json.c. The
# characters " and # must be escaped with backslash.
CORE_JSON_SED_EXPR = s/^static //

View File

@ -0,0 +1,16 @@
skipAnyLiteral proof
==============
This directory contains a memory safety proof for skipAnyLiteral.
This function requires non-NULL arguments and a buffer with length > 0.
The proof runs in a few seconds and provides complete coverage of:
* skipAnyLiteral()
* skipLiteral()
* strnEq()
To run the proof.
* Add cbmc, goto-cc, goto-instrument, goto-analyzer, and cbmc-viewer
to your path.
* Run "make".
* Open html/index.html in a web browser.

View File

@ -0,0 +1 @@
# This file marks this directory as containing a CBMC proof.

View File

@ -0,0 +1,7 @@
{ "expected-missing-functions":
[
],
"proof-name": "skipAnyLiteral",
"proof-root": "test/cbmc/proofs"
}

View File

@ -0,0 +1,58 @@
/*
* coreJSON v3.2.0
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* 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.
*/
/**
* @file skipAnyLiteral_harness.c
* @brief Implements the proof harness for the skipAnyLiteral function.
*/
#include <stdlib.h>
#include "core_json_annex.h"
void harness()
{
char * buf;
size_t start, max;
bool ret;
/* max is the buffer length which must be nonzero for non-API functions. */
__CPROVER_assume( max > 0 );
/* max is the buffer length which must not exceed unwindings. */
__CPROVER_assume( max < CBMC_MAX_BUFSIZE );
/* buf must not be NULL */
buf = malloc( max );
__CPROVER_assume( buf != NULL );
ret = skipAnyLiteral( buf, &start, max );
__CPROVER_assert( isBool( ret ), "A bool value is returned." );
if( ret == true )
{
__CPROVER_assert( start <= max,
"The buffer start index does not exceed the buffer length." );
}
}

View File

@ -0,0 +1,29 @@
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
HARNESS_FILE=skipCollection_harness
PROOF_UID=skipCollection
# This value was experimentally chosen to provide 100% coverage
# without tripping unwinding assertions and without exhausting memory.
CBMC_MAX_BUFSIZE=8
DEFINES += -DJSON_MAX_DEPTH="( $(CBMC_MAX_BUFSIZE) - 2 )"
REMOVE_FUNCTION_BODY += strnEq
UNWINDSET += skipCollection.0:$(CBMC_MAX_BUFSIZE)
UNWINDSET += skipArrayScalars.0:$(CBMC_MAX_BUFSIZE)
UNWINDSET += skipObjectScalars.0:$(CBMC_MAX_BUFSIZE)
PROOF_SOURCES += $(PROOF_STUB)/skipGeneric.c
PROOF_SOURCES += $(PROOF_STUB)/skipAnyLiteral.c
PROOF_SOURCES += $(PROOF_STUB)/skipNumber.c
PROOF_SOURCES += $(PROOF_STUB)/skipSpace.c
PROOF_SOURCES += $(PROOF_STUB)/skipSpaceAndComma.c
PROOF_SOURCES += $(PROOF_STUB)/skipString.c
include ../Makefile-json.common
# Substitution command to pass to sed for patching core_json.c. The
# characters " and # must be escaped with backslash.
CORE_JSON_SED_EXPR = 1s/^/\#include \"core_json_annex.h\" /; s/^static //; s/(bool|void) skip(AnyLiteral|Number|Space|SpaceAndComma|String)\b/&_/

View File

@ -0,0 +1,26 @@
skipCollection proof
==============
This directory contains a memory safety proof for skipCollection.
This function requires non-NULL arguments and a buffer with length > 0.
The proof runs in 5 minutes on a t3.medium. It provides complete coverage of:
* skipAnyScalar()
* skipArrayScalars()
* skipCollection()
* skipObjectScalars()
* skipScalars()
For this proof, the following functions are replaced with mocks.
These functions have separate proofs.
* skipAnyLiteral()
* skipNumber()
* skipSpace()
* skipSpaceAndComma()
* skipString()
To run the proof.
* Add cbmc, goto-cc, goto-instrument, goto-analyzer, and cbmc-viewer
to your path.
* Run "make".
* Open html/index.html in a web browser.

View File

@ -0,0 +1 @@
# This file marks this directory as containing a CBMC proof.

View File

@ -0,0 +1,7 @@
{ "expected-missing-functions":
[
],
"proof-name": "skipCollection",
"proof-root": "test/cbmc/proofs"
}

View File

@ -0,0 +1,58 @@
/*
* coreJSON v3.2.0
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* 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.
*/
/**
* @file skipCollection_harness.c
* @brief Implements the proof harness for the skipCollection function.
*/
#include <stdlib.h>
#include "core_json_annex.h"
void harness()
{
char * buf;
size_t start, max;
JSONStatus_t ret;
/* max is the buffer length which must be nonzero for non-API functions. */
__CPROVER_assume( max > 0 );
/* max is the buffer length which must not exceed unwindings. */
__CPROVER_assume( max < CBMC_MAX_BUFSIZE );
/* buf must not be NULL */
buf = malloc( max );
__CPROVER_assume( buf != NULL );
ret = skipCollection( buf, &start, max );
__CPROVER_assert( skipCollectionEnum( ret ), "The return value is a subset of JSONStatus_t." );
if( ret == JSONSuccess )
{
__CPROVER_assert( start <= max,
"The buffer start index does not exceed the buffer length." );
}
}

View File

@ -0,0 +1,19 @@
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
HARNESS_FILE=skipEscape_harness
PROOF_UID=skipEscape
# This value was experimentally chosen to provide 100% coverage
# without tripping unwinding assertions and without exhausting memory.
CBMC_MAX_BUFSIZE=14
UNWINDSET += skipEscape.0:$(CBMC_MAX_BUFSIZE)
UNWINDSET += skipHexEscape.0:$(CBMC_MAX_BUFSIZE)
UNWINDSET += skipOneHexEscape.0:$(CBMC_MAX_BUFSIZE)
include ../Makefile-json.common
# Substitution command to pass to sed for patching core_json.c. The
# characters " and # must be escaped with backslash.
CORE_JSON_SED_EXPR = s/^static //

View File

@ -0,0 +1,17 @@
skipEscape proof
==============
This directory contains a memory safety proof for skipEscape.
This function requires non-NULL arguments and a buffer with length > 0.
The proof runs in a few seconds and provides complete coverage of:
* hexToInt()
* skipEscape()
* skipHexEscape()
* skipOneHexEscape()
To run the proof.
* Add cbmc, goto-cc, goto-instrument, goto-analyzer, and cbmc-viewer
to your path.
* Run "make".
* Open html/index.html in a web browser.

View File

@ -0,0 +1 @@
# This file marks this directory as containing a CBMC proof.

View File

@ -0,0 +1,7 @@
{ "expected-missing-functions":
[
],
"proof-name": "skipEscape",
"proof-root": "test/cbmc/proofs"
}

View File

@ -0,0 +1,58 @@
/*
* coreJSON v3.2.0
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* 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.
*/
/**
* @file skipEscape_harness.c
* @brief Implements the proof harness for the skipEscape function.
*/
#include <stdlib.h>
#include "core_json_annex.h"
void harness()
{
char * buf;
size_t start, max;
bool ret;
/* max is the buffer length which must be nonzero for non-API functions. */
__CPROVER_assume( max > 0 );
/* max is the buffer length which must not exceed unwindings. */
__CPROVER_assume( max < CBMC_MAX_BUFSIZE );
/* buf must not be NULL */
buf = malloc( max );
__CPROVER_assume( buf != NULL );
ret = skipEscape( buf, &start, max );
__CPROVER_assert( isBool( ret ), "A bool value is returned." );
if( ret == true )
{
__CPROVER_assert( start <= max,
"The buffer start index does not exceed the buffer length." );
}
}

View File

@ -0,0 +1,20 @@
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
HARNESS_FILE=skipNumber_harness
PROOF_UID=skipNumber
# This value was experimentally chosen to provide 100% coverage
# without tripping unwinding assertions and without exhausting memory.
CBMC_MAX_BUFSIZE=12
UNWINDSET += skipDecimals.0:$(CBMC_MAX_BUFSIZE)
UNWINDSET += skipDigits.0:$(CBMC_MAX_BUFSIZE)
UNWINDSET += skipExponent.0:$(CBMC_MAX_BUFSIZE)
UNWINDSET += skipNumber.0:$(CBMC_MAX_BUFSIZE)
include ../Makefile-json.common
# Substitution command to pass to sed for patching core_json.c. The
# characters " and # must be escaped with backslash.
CORE_JSON_SED_EXPR = s/^static //

View File

@ -0,0 +1,20 @@
skipNumber proof
==============
This directory contains a memory safety proof for skipNumber.
This function requires non-NULL arguments and a buffer with length > 0.
The proof runs in a few seconds and provides complete coverage of:
* skipDecimals()
* skipDigits()
* skipExponent()
* skipNumber()
The function hexToInt() is partially covered in this proof, but is
fully covered in the skipEscape proof.
To run the proof.
* Add cbmc, goto-cc, goto-instrument, goto-analyzer, and cbmc-viewer
to your path.
* Run "make".
* Open html/index.html in a web browser.

View File

@ -0,0 +1 @@
# This file marks this directory as containing a CBMC proof.

View File

@ -0,0 +1,7 @@
{ "expected-missing-functions":
[
],
"proof-name": "skipNumber",
"proof-root": "test/cbmc/proofs"
}

View File

@ -0,0 +1,72 @@
/*
* coreJSON v3.2.0
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* 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.
*/
/**
* @file skipNumber_harness.c
* @brief Implements the proof harness for the skipNumber function.
*/
#include <stdlib.h>
#include "core_json_annex.h"
void harness()
{
char * buf;
size_t start, max;
bool ret;
int32_t * outValue;
/* max is the buffer length which must be nonzero for non-API functions. */
__CPROVER_assume( max > 0 );
/* max is the buffer length which must not exceed unwindings. */
__CPROVER_assume( max < CBMC_MAX_BUFSIZE );
/* buf must not be NULL */
buf = malloc( max );
__CPROVER_assume( buf != NULL );
ret = skipNumber( buf, &start, max );
__CPROVER_assert( isBool( ret ), "A bool value is returned." );
if( ret == true )
{
__CPROVER_assert( start <= max,
"The buffer start index does not exceed the buffer length." );
}
/* outValue may be NULL */
outValue = malloc( sizeof( *outValue ) );
ret = skipDigits( buf, &start, max, outValue );
__CPROVER_assert( isBool( ret ), "A bool value is returned." );
if( ( ret == true ) && ( outValue != NULL ) )
{
__CPROVER_assert( ( ( *outValue == -1 ) || ( ( *outValue >= 0 ) && ( *outValue <= MAX_INDEX_VALUE ) ) ),
"The converted integer is within the permitted range or is -1." );
}
}

View File

@ -0,0 +1,17 @@
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
HARNESS_FILE=skipSpace_harness
PROOF_UID=skipSpace
# This value was experimentally chosen to provide 100% coverage
# without tripping unwinding assertions and without exhausting memory.
CBMC_MAX_BUFSIZE=10
UNWINDSET += skipSpace.0:$(CBMC_MAX_BUFSIZE)
include ../Makefile-json.common
# Substitution command to pass to sed for patching core_json.c. The
# characters " and # must be escaped with backslash.
CORE_JSON_SED_EXPR = s/^static //

View File

@ -0,0 +1,14 @@
skipSpace proof
==============
This directory contains a memory safety proof for skipSpace.
This function requires non-NULL arguments and a buffer with length > 0.
The proof runs in a few seconds and provides complete coverage of
skipSpace().
To run the proof.
* Add cbmc, goto-cc, goto-instrument, goto-analyzer, and cbmc-viewer
to your path.
* Run "make".
* Open html/index.html in a web browser.

View File

@ -0,0 +1 @@
# This file marks this directory as containing a CBMC proof.

View File

@ -0,0 +1,7 @@
{ "expected-missing-functions":
[
],
"proof-name": "skipSpace",
"proof-root": "test/cbmc/proofs"
}

View File

@ -0,0 +1,55 @@
/*
* coreJSON v3.2.0
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* 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.
*/
/**
* @file skipSpace_harness.c
* @brief Implements the proof harness for the skipSpace function.
*/
#include <stdlib.h>
#include "core_json_annex.h"
void harness()
{
char * buf;
size_t start, saveStart = start, max;
/* max is the buffer length which must be nonzero for non-API functions. */
__CPROVER_assume( max > 0 );
/* max is the buffer length which must not exceed unwindings. */
__CPROVER_assume( max < CBMC_MAX_BUFSIZE );
/* buf must not be NULL */
buf = malloc( max );
__CPROVER_assume( buf != NULL );
skipSpace( buf, &start, max );
if( saveStart != start )
{
__CPROVER_assert( start <= max,
"The buffer start index does not exceed the buffer length." );
}
}

View File

@ -0,0 +1,18 @@
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
HARNESS_FILE=skipSpaceAndComma_harness
PROOF_UID=skipSpaceAndComma
# This value was experimentally chosen to provide 100% coverage
# without tripping unwinding assertions and without exhausting memory.
CBMC_MAX_BUFSIZE=10
UNWINDSET += skipSpace.0:$(CBMC_MAX_BUFSIZE)
UNWINDSET += skipSpaceAndComma.0:$(CBMC_MAX_BUFSIZE)
include ../Makefile-json.common
# Substitution command to pass to sed for patching core_json.c. The
# characters " and # must be escaped with backslash.
CORE_JSON_SED_EXPR = s/^static //

View File

@ -0,0 +1,14 @@
skipSpaceAndComma proof
==============
This directory contains a memory safety proof for skipSpaceAndComma.
This function requires non-NULL arguments and a buffer with length > 0.
The proof runs in a few seconds and provides complete coverage of
skipSpaceAndComma().
To run the proof.
* Add cbmc, goto-cc, goto-instrument, goto-analyzer, and cbmc-viewer
to your path.
* Run "make".
* Open html/index.html in a web browser.

View File

@ -0,0 +1 @@
# This file marks this directory as containing a CBMC proof.

View File

@ -0,0 +1,7 @@
{ "expected-missing-functions":
[
],
"proof-name": "skipSpaceAndComma",
"proof-root": "test/cbmc/proofs"
}

View File

@ -0,0 +1,58 @@
/*
* coreJSON v3.2.0
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* 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.
*/
/**
* @file skipSpaceAndComma_harness.c
* @brief Implements the proof harness for the skipSpaceAndComma function.
*/
#include <stdlib.h>
#include "core_json_annex.h"
void harness()
{
char * buf;
size_t start, max;
bool ret;
/* max is the buffer length which must be nonzero for non-API functions. */
__CPROVER_assume( max > 0 );
/* max is the buffer length which must not exceed unwindings. */
__CPROVER_assume( max < CBMC_MAX_BUFSIZE );
/* buf must not be NULL */
buf = malloc( max );
__CPROVER_assume( buf != NULL );
ret = skipSpaceAndComma( buf, &start, max );
__CPROVER_assert( isBool( ret ), "A bool value is returned." );
if( ret == true )
{
__CPROVER_assert( start <= max,
"The buffer start index does not exceed the buffer length." );
}
}

View File

@ -0,0 +1,21 @@
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
HARNESS_FILE=skipString_harness
PROOF_UID=skipString
# This value was experimentally chosen to provide 100% coverage
# without tripping unwinding assertions and without exhausting memory.
CBMC_MAX_BUFSIZE=14
UNWINDSET += skipString.0:$(CBMC_MAX_BUFSIZE)
PROOF_SOURCES += $(PROOF_STUB)/skipGeneric.c
PROOF_SOURCES += $(PROOF_STUB)/skipEscape.c
PROOF_SOURCES += $(PROOF_STUB)/skipUTF8.c
include ../Makefile-json.common
# Substitution command to pass to sed for patching core_json.c. The
# characters " and # must be escaped with backslash.
CORE_JSON_SED_EXPR = 1s/^/\#include \"core_json_annex.h\" /; s/^static //; s/bool skip(Escape|UTF8)\b/&_/

View File

@ -0,0 +1,17 @@
skipString proof
==============
This directory contains a memory safety proof for skipString.
This function requires non-NULL arguments and a buffer with length > 0.
The proof runs in a few seconds and provides complete coverage of
skipString().
For this proof, skipEscape() and skipUTF8() are replaced with mocks.
These functions have separate proofs.
To run the proof.
* Add cbmc, goto-cc, goto-instrument, goto-analyzer, and cbmc-viewer
to your path.
* Run "make".
* Open html/index.html in a web browser.

View File

@ -0,0 +1 @@
# This file marks this directory as containing a CBMC proof.

View File

@ -0,0 +1,7 @@
{ "expected-missing-functions":
[
],
"proof-name": "skipString",
"proof-root": "test/cbmc/proofs"
}

View File

@ -0,0 +1,58 @@
/*
* coreJSON v3.2.0
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* 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.
*/
/**
* @file skipString_harness.c
* @brief Implements the proof harness for the skipString function.
*/
#include <stdlib.h>
#include "core_json_annex.h"
void harness()
{
char * buf;
size_t start, max;
bool ret;
/* max is the buffer length which must be nonzero for non-API functions. */
__CPROVER_assume( max > 0 );
/* max is the buffer length which must not exceed unwindings. */
__CPROVER_assume( max < CBMC_MAX_BUFSIZE );
/* buf must not be NULL */
buf = malloc( max );
__CPROVER_assume( buf != NULL );
ret = skipString( buf, &start, max );
__CPROVER_assert( isBool( ret ), "A bool value is returned." );
if( ret == true )
{
__CPROVER_assert( start <= max,
"The buffer start index does not exceed the buffer length." );
}
}

View File

@ -0,0 +1,19 @@
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
HARNESS_FILE=skipUTF8_harness
PROOF_UID=skipUTF8
# This value was experimentally chosen to provide 100% coverage
# without tripping unwinding assertions and without exhausting memory.
CBMC_MAX_BUFSIZE=10
UNWINDSET += countHighBits.0:9
UNWINDSET += skipUTF8.0:$(CBMC_MAX_BUFSIZE)
UNWINDSET += skipUTF8MultiByte.0:$(CBMC_MAX_BUFSIZE)
include ../Makefile-json.common
# Substitution command to pass to sed for patching core_json.c. The
# characters " and # must be escaped with backslash.
CORE_JSON_SED_EXPR = s/^static //

View File

@ -0,0 +1,17 @@
skipUTF8 proof
==============
This directory contains a memory safety proof for skipUTF8.
This function requires non-NULL arguments and a buffer with length > 0.
The proof runs in a few seconds and provides complete coverage of:
* countHighBits()
* shortestUTF8()
* skipUTF8()
* skipUTF8MultiByte()
To run the proof.
* Add cbmc, goto-cc, goto-instrument, goto-analyzer, and cbmc-viewer
to your path.
* Run "make".
* Open html/index.html in a web browser.

View File

@ -0,0 +1 @@
# This file marks this directory as containing a CBMC proof.

View File

@ -0,0 +1,7 @@
{ "expected-missing-functions":
[
],
"proof-name": "skipUTF8",
"proof-root": "test/cbmc/proofs"
}

View File

@ -0,0 +1,58 @@
/*
* coreJSON v3.2.0
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* 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.
*/
/**
* @file skipUTF8_harness.c
* @brief Implements the proof harness for the skipUTF8 function.
*/
#include <stdlib.h>
#include "core_json_annex.h"
void harness()
{
char * buf;
size_t start, max;
bool ret;
/* max is the buffer length which must be nonzero for non-API functions. */
__CPROVER_assume( max > 0 );
/* max is the buffer length which must not exceed unwindings. */
__CPROVER_assume( max < CBMC_MAX_BUFSIZE );
/* buf must not be NULL */
buf = malloc( max );
__CPROVER_assume( buf != NULL );
ret = skipUTF8( buf, &start, max );
__CPROVER_assert( isBool( ret ), "A bool value is returned." );
if( ret == true )
{
__CPROVER_assert( start <= max,
"The buffer start index does not exceed the buffer length." );
}
}

View File

@ -0,0 +1,6 @@
CBMC proof source code
======================
This directory contains source code written for CBMC proofs. It is
common to write some code to model aspects of the system under test,
and this code goes here.

View File

@ -0,0 +1,6 @@
CBMC proof stubs
======================
This directory contains the stubs written for CBMC proofs. It is
common to stub out functionality like network send and receive methods
when writing a CBMC proof, and the code for these stubs goes here.

View File

@ -0,0 +1,38 @@
/*
* coreJSON v3.2.0
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* 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.
*/
#include "skipGeneric.h"
/*
* This function is a replacement for the function of the same name from core_json.c.
* Please see core_json.c for documentation.
*/
bool skipAnyLiteral( const char * buf,
size_t * start,
size_t max )
{
/* min argument is 4 for the shortest literal, e.g., true or null. */
return skipGeneric( buf, start, max, 4 );
}

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