summaryrefslogtreecommitdiff
path: root/FreeRTOS/Test/CBMC/proofs/run-cbmc-proofs.py
blob: f95de775ba29e64fb71e2c9e7ce67e176a08e81f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
#!/usr/bin/env python3
#
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You may not
# use this file except in compliance with the License. A copy of the License is
# located at
#
#     http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is distributed on
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
# or implied. See the License for the specific language governing permissions
# and limitations under the License.


import argparse
import logging
import math
import os
import pathlib
import subprocess
import sys


DESCRIPTION = "Configure and run all CBMC proofs in parallel"
# Keep this 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 "FreeRTOS";

        for proof in $(find . -name cbmc-batch.yaml); do
            pushd $(dirname ${proof});
            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 --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`.
"""


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": ["--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": "FreeRTOS",
            "help": "Project name for report. Default: %(default)s",
    }, {
            "flags": ["--verbose"],
            "action": "store_true",
            "help": "verbose output",
    }]:
        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 print_counter(counter):
    print(
        "\rConfiguring CBMC proofs: "
        "{complete:{width}} / {total:{width}}".format(
            **counter), end="", file=sys.stderr)


def get_proof_dirs(proof_root, proof_list):
    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 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 "cbmc-batch.yaml" in fyles:
            yield pathlib.Path(root)

    if proofs_remaining:
        logging.error(
            "The following proofs were not found: %s",
            ", ".join(proofs_remaining))
        sys.exit(1)


def run_cmd(cmd, **args):
    if "shell" in args and args["shell"]:
        if not isinstance(cmd, str):
            raise UserWarning("Command must be a string if shell=True")
        str_cmd = cmd
    else:
        if not isinstance(cmd, list):
            raise UserWarning("Command passed to run_cmd must be a list")
        str_cmd = " ".join(cmd)

    logging.info("Command: %s", str_cmd)

    proc = subprocess.run(cmd, **args)

    if proc.returncode:
        logging.error("Command failed: %s", str_cmd)

    return proc


def run_build(jobs):
    cmd = ["litani", "run-build"]
    if jobs:
        cmd.extend(["-j", str(jobs)])
    run_cmd(cmd, check=True)


def add_proof_jobs(proof_directory, proof_root):
    proof_directory = pathlib.Path(proof_directory)
    harnesses = [
        f for f in os.listdir(proof_directory) if f.endswith("_harness.c")]
    if not len(harnesses) == 1:
        logging.error(
            "Found %d harnesses in directory '%s'", len(harnesses),
            proof_directory)
        return False

    # Neither the harness name nor the proof directory is unique enough,
    # due to proof configurations. Use the relative path instead.
    proof_name = str(proof_directory.relative_to(proof_root))

    goto_binary = str(
        (proof_directory / ("%s.goto" % harnesses[0][:-2])).resolve())

    # Build goto-binary

    run_cmd([
        "litani", "add-job",
        "--command", "make -B veryclean goto",
        "--outputs", goto_binary,
        "--pipeline-name", proof_name,
        "--ci-stage", "build",
        "--cwd", str(proof_directory),
        "--description", ("%s: building goto-binary" % proof_name),
    ], check=True)

    # Run 3 CBMC tasks

    cbmc_out = str(proof_directory / "cbmc.txt")
    run_cmd([
        "litani", "add-job",
        "--command", "make cbmc",
        "--inputs", goto_binary,
        "--outputs", cbmc_out,
        "--pipeline-name", proof_name,
        "--ci-stage", "test",
        "--tags", "stats-group:safety check",
        # Make returns 2 if the underlying command exited abnormally
        "--ignore-returns", "2",
        "--cwd", str(proof_directory),
        "--description", ("%s: running safety checks" % proof_name),
    ], check=True)

    property_out = str(proof_directory / "property.xml")
    run_cmd([
        "litani", "add-job",
        "--command", "make property",
        "--inputs", goto_binary,
        "--outputs", property_out,
        "--pipeline-name", proof_name,
        "--ci-stage", "test",
        "--cwd", str(proof_directory),
        "--description", ("%s: printing properties" % proof_name),
    ], check=True)

    coverage_out = str(proof_directory / "coverage.xml")
    run_cmd([
        "litani", "add-job",
        "--command", "make coverage",
        "--inputs", goto_binary,
        "--outputs", coverage_out,
        "--pipeline-name", proof_name,
        "--ci-stage", "test",
        "--cwd", str(proof_directory),
        "--tags", "stats-group:coverage computation",
        "--description", ("%s: computing coverage" % proof_name),
    ], check=True)

    # Check whether the CBMC proof actually passed. More details in the
    # Makefile rule for check-cbmc-result.
    run_cmd([
        "litani", "add-job",
        "--command", "make check-cbmc-result",
        "--inputs", cbmc_out,
        "--pipeline-name", proof_name,
        "--ci-stage", "report",
        "--cwd", str(proof_directory),
        "--description", ("%s: checking CBMC result" % proof_name),
    ], check=True)

    # Generate report
    run_cmd([
        "litani", "add-job",
        "--command", "make report",
        "--inputs", cbmc_out, property_out, coverage_out,
        "--outputs", str(proof_directory / "html"),
        "--pipeline-name", proof_name,
        "--ci-stage", "report",
        "--cwd", str(proof_directory),
        "--tags", "stats-group:report generation",
        "--description", ("%s: generating report" % proof_name),
    ], check=True)

    return True


def configure_proof_dirs(proof_dirs, proof_root, counter):
    for proof_dir in proof_dirs:
        print_counter(counter)

        success = add_proof_jobs(proof_dir, proof_root)

        counter["pass" if success else "fail"].append(proof_dir)
        counter["complete"] += 1


def main():
    args = get_args()
    set_up_logging(args.verbose)

    proof_root = pathlib.Path(__file__).resolve().parent

    run_cmd(["./prepare.py"], check=True, cwd=str(proof_root))
    if not args.no_standalone:
        run_cmd(
            ["litani", "init", "--project", args.project_name], check=True)

    proof_dirs = list(get_proof_dirs(proof_root, args.proofs))
    if not proof_dirs:
        logging.error("No proof directories found")
        sys.exit(1)

    counter = {
        "pass": [],
        "fail": [],
        "complete": 0,
        "total": len(proof_dirs),
        "width": int(math.log10(len(proof_dirs))) + 1
    }

    configure_proof_dirs(proof_dirs, proof_root, counter)

    print_counter(counter)
    print("", file=sys.stderr)

    if counter["fail"]:
        logging.error(
            "Failed to configure the following proofs:\n%s", "\n".join(
                [str(f) for f in counter["fail"]]))

    if not args.no_standalone:
        run_build(args.parallel_jobs)


if __name__ == "__main__":
    main()