summaryrefslogtreecommitdiff
path: root/zephyr/firmware_builder.py
blob: d481487afac0871690ceea26d95997ee079664d1 (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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
#!/usr/bin/env python3.8
# -*- coding: utf-8 -*-
# Copyright 2021 The ChromiumOS Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Build and test all of the Zephyr boards.

This is the entry point for the custom firmware builder workflow recipe.
"""

import argparse
import multiprocessing
import pathlib
import re
import shlex
import subprocess
import sys

from google.protobuf import json_format  # pylint: disable=import-error
import zmake.project

from chromite.api.gen_sdk.chromite.api import firmware_pb2


DEFAULT_BUNDLE_DIRECTORY = "/tmp/artifact_bundles"
DEFAULT_BUNDLE_METADATA_FILE = "/tmp/artifact_bundle_metadata"

# Boards that we want to track the coverage of our own files specifically.
SPECIAL_BOARDS = [
    "herobrine",
    "krabby",
    "nivviks",
    "skyrim",
    "kingler",
    "rex",
    "geralt",
]

BINARY_SIZE_REGIONS = [
    "RO_FLASH",
    "RO_RAM",
    "RO_ROM",
    "RW_FLASH",
    "RW_RAM",
    "RW_ROM",
]


def log_cmd(cmd, env=None):
    """Log subprocess command."""
    if env is not None:
        print("env", end=" ")
        [  # pylint:disable=expression-not-assigned
            print(key + "=" + shlex.quote(str(value)), end=" ")
            for key, value in env.items()
        ]
    print(" ".join(shlex.quote(str(x)) for x in cmd))
    sys.stdout.flush()


def build(opts):
    """Builds all Zephyr firmware targets"""
    metric_list = firmware_pb2.FwBuildMetricList()

    zephyr_dir = pathlib.Path(__file__).parent.resolve()
    platform_ec = zephyr_dir.parent
    subprocess.run(
        [platform_ec / "util" / "check_clang_format.py"],
        check=True,
        cwd=platform_ec,
        stdin=subprocess.DEVNULL,
    )

    # Start with a clean build environment
    cmd = ["make", "clobber"]
    log_cmd(cmd)
    subprocess.run(cmd, cwd=platform_ec, check=True, stdin=subprocess.DEVNULL)

    cmd = ["zmake", "-D", "build", "-a"]
    if opts.code_coverage:
        cmd.append("--coverage")
    log_cmd(cmd)
    subprocess.run(cmd, cwd=zephyr_dir, check=True, stdin=subprocess.DEVNULL)
    if not opts.code_coverage:
        for project in zmake.project.find_projects(zephyr_dir).values():
            if project.config.is_test:
                continue
            build_dir = (
                platform_ec / "build" / "zephyr" / project.config.project_name
            )
            metric = metric_list.value.add()
            metric.target_name = project.config.project_name
            metric.platform_name = project.config.zephyr_board
            for (variant, _) in project.iter_builds():
                build_log = build_dir / f"build-{variant}" / "build.log"
                parse_buildlog(
                    build_log,
                    metric,
                    variant.upper(),
                    metric.target_name in SPECIAL_BOARDS,
                )
    with open(opts.metrics, "w") as file:
        file.write(json_format.MessageToJson(metric_list))


UNITS = {
    "B": 1,
    "KB": 1024,
    "MB": 1024 * 1024,
    "GB": 1024 * 1024 * 1024,
}


def parse_buildlog(filename, metric, variant, track_on_gerrit):
    """Parse the build.log generated by zmake to find the size of the image."""
    with open(filename, "r") as infile:
        # Skip over all lines until the memory report is found
        while True:
            line = infile.readline()
            if not line:
                return
            if line.startswith("Memory region"):
                break

        for line in infile.readlines():
            # Skip any lines that are not part of the report
            if not line.startswith(" "):
                continue
            parts = line.split()
            fw_section = metric.fw_section.add()
            fw_section.region = variant + "_" + parts[0][:-1]
            fw_section.used = int(parts[1]) * UNITS[parts[2]]
            fw_section.total = int(parts[3]) * UNITS[parts[4]]
            if track_on_gerrit and fw_section.region in BINARY_SIZE_REGIONS:
                fw_section.track_on_gerrit = True
            else:
                fw_section.track_on_gerrit = False


def bundle(opts):
    """Bundle the artifacts for either firmware or code coverage."""
    if opts.code_coverage:
        bundle_coverage(opts)
    else:
        bundle_firmware(opts)


def get_bundle_dir(opts):
    """Get the directory for the bundle from opts or use the default.

    Also create the directory if it doesn't exist.
    """
    if opts.output_dir:
        bundle_dir = opts.output_dir
    else:
        bundle_dir = DEFAULT_BUNDLE_DIRECTORY
    bundle_dir = pathlib.Path(bundle_dir)
    if not bundle_dir.is_dir():
        bundle_dir.mkdir()
    return bundle_dir


def write_metadata(opts, info):
    """Write the metadata about the bundle."""
    bundle_metadata_file = (
        opts.metadata if opts.metadata else DEFAULT_BUNDLE_METADATA_FILE
    )
    with open(bundle_metadata_file, "w") as file:
        file.write(json_format.MessageToJson(info))


def bundle_coverage(opts):
    """Bundles the artifacts from code coverage into its own tarball."""
    info = firmware_pb2.FirmwareArtifactInfo()
    info.bcs_version_info.version_string = opts.bcs_version
    bundle_dir = get_bundle_dir(opts)
    zephyr_dir = pathlib.Path(__file__).parent.resolve()
    platform_ec = zephyr_dir.parent
    build_dir = platform_ec / "build" / "zephyr"
    tarball_name = "coverage.tbz2"
    tarball_path = bundle_dir / tarball_name
    cmd = ["tar", "cvfj", tarball_path, "lcov.info"]
    log_cmd(cmd)
    subprocess.run(cmd, cwd=build_dir, check=True, stdin=subprocess.DEVNULL)
    meta = info.objects.add()
    meta.file_name = tarball_name
    meta.lcov_info.type = (
        firmware_pb2.FirmwareArtifactInfo.LcovTarballInfo.LcovType.LCOV
    )
    (bundle_dir / "html").mkdir(exist_ok=True)
    cmd = ["mv", "lcov_rpt"]
    for board in SPECIAL_BOARDS:
        cmd.append(board + "_rpt")
    cmd.append(bundle_dir / "html/")
    log_cmd(cmd)
    subprocess.run(cmd, cwd=build_dir, check=True, stdin=subprocess.DEVNULL)
    meta = info.objects.add()
    meta.file_name = "html"
    meta.coverage_html.SetInParent()

    write_metadata(opts, info)


def bundle_firmware(opts):
    """Bundles the artifacts from each target into its own tarball."""
    info = firmware_pb2.FirmwareArtifactInfo()
    info.bcs_version_info.version_string = opts.bcs_version
    bundle_dir = get_bundle_dir(opts)
    zephyr_dir = pathlib.Path(__file__).parent.resolve()
    platform_ec = zephyr_dir.parent
    for project in zmake.project.find_projects(zephyr_dir).values():
        if project.config.is_test:
            continue
        build_dir = (
            platform_ec / "build" / "zephyr" / project.config.project_name
        )
        artifacts_dir = build_dir / "output"
        tarball_name = f"{project.config.project_name}.firmware.tbz2"
        tarball_path = bundle_dir.joinpath(tarball_name)
        cmd = ["tar", "cvfj", tarball_path, "."]
        log_cmd(cmd)
        subprocess.run(
            cmd, cwd=artifacts_dir, check=True, stdin=subprocess.DEVNULL
        )
        meta = info.objects.add()
        meta.file_name = tarball_name
        meta.tarball_info.type = (
            firmware_pb2.FirmwareArtifactInfo.TarballInfo.FirmwareType.EC
        )
        # TODO(kmshelton): Populate the rest of metadata contents as it
        # gets defined in infra/proto/src/chromite/api/firmware.proto.

    write_metadata(opts, info)


def test(opts):
    """Runs all of the unit tests for Zephyr firmware"""
    metrics = firmware_pb2.FwTestMetricList()

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

    # Run tests from Makefile.cq because make knows how to run things
    # in parallel.
    cmd = ["make", "-f", "Makefile.cq", f"-j{opts.cpus}", "test"]
    if opts.code_coverage:
        cmd.append("COVERAGE=1")
    if SPECIAL_BOARDS:
        cmd.append(f"SPECIAL_BOARDS={' '.join(SPECIAL_BOARDS)}")
    log_cmd(cmd)
    subprocess.run(
        cmd,
        check=True,
        cwd=zephyr_dir,
        stdin=subprocess.DEVNULL,
    )

    # Twister-based tests
    platform_ec = zephyr_dir.parent
    twister_out_dir = platform_ec / "twister-out-llvm"
    twister_out_dir_gcc = platform_ec / "twister-out-host"

    if opts.code_coverage:
        build_dir = platform_ec / "build" / "zephyr"
        _extract_lcov_summary(
            "EC_ZEPHYR_TESTS", metrics, twister_out_dir / "coverage.info"
        )
        _extract_lcov_summary(
            "EC_ZEPHYR_TESTS_GCC",
            metrics,
            twister_out_dir_gcc / "coverage.info",
        )
        _extract_lcov_summary(
            "EC_LEGACY_TESTS", metrics, platform_ec / "build/coverage/lcov.info"
        )
        _extract_lcov_summary(
            "ALL_TESTS", metrics, build_dir / "all_tests.info"
        )
        _extract_lcov_summary(
            "EC_ZEPHYR_MERGED", metrics, build_dir / "zephyr_merged.info"
        )
        _extract_lcov_summary("ALL_MERGED", metrics, build_dir / "lcov.info")
        _extract_lcov_summary(
            "ALL_FILTERED", metrics, build_dir / "lcov_no_tests.info"
        )

        for board in SPECIAL_BOARDS:
            _extract_lcov_summary(
                f"BOARD_{board}".upper(),
                metrics,
                build_dir / (board + "_final.info"),
            )

    with open(opts.metrics, "w") as file:
        file.write(json_format.MessageToJson(metrics))  # type: ignore


COVERAGE_RE = re.compile(
    r"lines\.*: *([0-9\.]+)% \(([0-9]+) of ([0-9]+) lines\)"
)


def _extract_lcov_summary(name, metrics, filename):
    zephyr_dir = pathlib.Path(__file__).parent.resolve()
    cmd = [
        "/usr/bin/lcov",
        "--summary",
        filename,
    ]
    log_cmd(cmd)
    output = subprocess.run(
        cmd,
        cwd=zephyr_dir,
        check=True,
        stdout=subprocess.PIPE,
        universal_newlines=True,
        stdin=subprocess.DEVNULL,
    ).stdout
    re_match = COVERAGE_RE.search(output)
    if re_match:
        metric = metrics.value.add()
        metric.name = name
        metric.coverage_percent = float(re_match.group(1))
        metric.covered_lines = int(re_match.group(2))
        metric.total_lines = int(re_match.group(3))


def main(args):
    """Builds and tests all of the Zephyr targets and reports build metrics"""
    opts = parse_args(args)

    if not hasattr(opts, "func"):
        print("Must select a valid sub command!")
        return -1

    # Run selected sub command function
    opts.func(opts)
    return 0


def parse_args(args):
    """Parse command line args."""
    parser = argparse.ArgumentParser(description=__doc__)

    parser.add_argument(
        "--cpus",
        default=multiprocessing.cpu_count(),
        help="The number of cores to use.",
    )

    parser.add_argument(
        "--metrics",
        dest="metrics",
        required=True,
        help="File to write the json-encoded MetricsList proto message.",
    )

    parser.add_argument(
        "--metadata",
        required=False,
        help=(
            "Full pathname for the file in which to write build artifact "
            "metadata."
        ),
    )

    parser.add_argument(
        "--output-dir",
        required=False,
        help=(
            "Full pathname for the directory in which to bundle build "
            "artifacts."
        ),
    )

    parser.add_argument(
        "--code-coverage",
        required=False,
        action="store_true",
        help="Build host-based unit tests for code coverage.",
    )

    parser.add_argument(
        "--bcs-version",
        dest="bcs_version",
        default="",
        required=False,
        # TODO(b/180008931): make this required=True.
        help="BCS version to include in metadata.",
    )

    # Would make this required=True, but not available until 3.7
    sub_cmds = parser.add_subparsers()

    build_cmd = sub_cmds.add_parser("build", help="Builds all firmware targets")
    build_cmd.set_defaults(func=build)

    build_cmd = sub_cmds.add_parser(
        "bundle",
        help="Creates a tarball containing build "
        "artifacts from all firmware targets",
    )
    build_cmd.set_defaults(func=bundle)

    test_cmd = sub_cmds.add_parser("test", help="Runs all firmware unit tests")
    test_cmd.set_defaults(func=test)

    return parser.parse_args(args)


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))