Skip to contentSkip to conversation

Introduce an extensible static analyzer

RFC In review Alberto Faria 8 participants 26 messages Jul 29, 2022 – Oct 15, 2022

Subsystems (3)
lore
Share & tools
lore
#0 lore raw

v2 cover Introduce an extensible static analyzer

This series introduces a static analyzer for QEMU. It consists of a single static-analyzer.py script that relies on libclang's Python bindings, and provides a common framework on which arbitrary static analysis checks can be developed and run against QEMU's code base.

Summary of the series:

- Patch 1 adds the base static analyzer, along with a simple check that finds static functions whose return value is never used, and patch 2 fixes many occurrences of this.

- Patch 3 introduces support for output-comparison check tests, and adds some tests to the abovementioned check.

- Patch 4 makes the analyzer skip checks on a translation unit when it hasn't been modified since the last time those checks passed.

- Patch 5 adds a check to ensure that non-coroutine_fn functions don't perform direct calls to coroutine_fn functions, and patch 6 fixes some violations of this rule.

- Patch 7 adds a check to ensure that operations on coroutine_fn pointers make sense, like assignment and indirect calls, and patch 8 fixes some problems detected by the check. (Implementing this check properly is complicated, since AFAICT annotation attributes cannot be applied directly to types. This part still needs a lot of work.)

- Patch 9 introduces a no_coroutine_fn marker for functions that should not be called from coroutines, makes generated_co_wrapper evaluate to no_coroutine_fn, and adds a check enforcing this rule. Patch 10 fixes some violations that it finds.

The current primary motivation for this work is enforcing rules around block layer coroutines, which is why most of the series focuses on that. However, the static analyzer is intended to be sufficiently generic to satisfy other present and future QEMU static analysis needs.

Performance isn't great, but with some more optimization, the analyzer should be fast enough to be used iteratively during development, given that it avoids reanalyzing unmodified translation units, and that users can restrict the set of translation units under consideration. It should also be fast enough to run in CI (?).

Consider a small QEMU configuration and build (all commands were run on the same 12-thread laptop):

    $ cd build && time ../configure --target-list=x86_64-softmmu && cd ..
    [...]
    real    0m17.232s
    user    0m13.261s
    sys     0m3.895s
    $ time make -C build -j $(nproc) all
    [...]
    real    2m39.029s
    user    14m49.370s
    sys     1m57.364s
    $ time make -C build -j $(nproc) check
    [...]
    real    2m46.349s
    user    6m4.718s
    sys     4m15.660s

We can run the static analyzer against all translation units enabled in this configuration:

    $ time ./static-analyzer.py build
    util/qemu-coroutine.c:122:23: non-coroutine_fn function calls coroutine_fn qemu_coroutine_self()
    io/channel.c:152:17: non-coroutine_fn function calls coroutine_fn qio_channel_yield()
    [...]
    Analyzed 1649 translation units in 520.3 seconds.
    real    8m42.342s
    user    95m51.759s
    sys     0m21.576s

You will need libclang's Python bindings to run this. Try dnf install python3-clang or apt install python3-clang.

It takes around 1 to 2 seconds for the analyzer to load the compilation database, determine which translation units to analyze, etc. The durations reported by the analyzer itself don't include those steps, which is why they differ from what time reports.

We can also analyze only some of the translation units:

    $ time ./static-analyzer.py build block
    block/raw-format.c:420:12: non-coroutine_fn function calls coroutine_fn bdrv_co_ioctl()
    block/blkverify.c:266:12: non-coroutine_fn function calls coroutine_fn bdrv_co_flush()
    [...]
    Analyzed 21 translation units (58 other were up-to-date) in 5.8 seconds.
    real    0m7.031s
    user    0m40.951s
    sys     0m1.299s

Since the previous command had already analyzed all translation units, only the ones that had problems were reanalyzed.

Now skipping all the actual checks, but still parsing and building the AST for each translation unit, and adding --force to reanalyze all translation units:

    $ time ./static-analyzer.py build --force --skip-checks
    Analyzed 1649 translation units in 41.2 seconds.
    real    0m42.296s
    user    7m14.256s
    sys     0m15.803s

And now running a single check:

    $ time ./static-analyzer.py build --force --check return-value-never-used
    Analyzed 1649 translation units in 157.6 seconds.
    real    2m38.759s
    user    29m28.930s
    sys     0m17.968s

TODO:
- Run in GitLab CI (?).
- Finish the "coroutine_fn" check.
- Add check tests where missing.
- Avoid redundant AST traversals while keeping checks modular.
- More optimization.

v2:
- Fix parsing of compilation database commands.
- Reorganize checks and split them into separate modules.
- Make "return-value-never-used" ignore __attribute__((unused)) funcs.
- Add a visitor() abstraction wrapping clang_visitChildren() that is faster than using Cursor.get_children() with recursion.
- Add support for implementing tests for checks, and add some tests to "return-value-never-used".
- Use dependency information provided by Ninja to skip checks on translation units that haven't been modified since they last passed those checks.
- Ignore translation units from git submodules.
- And more.

Alberto Faria (10):
Add an extensible static analyzer
Drop unused static function return values
static-analyzer: Support adding tests to checks
static-analyzer: Avoid reanalyzing unmodified translation units
static-analyzer: Enforce coroutine_fn restrictions for direct calls Fix some direct calls from non-coroutine_fn to coroutine_fn
static-analyzer: Enforce coroutine_fn restrictions on function
pointers
Fix some bad coroutine_fn indirect calls and pointer assignments
block: Add no_coroutine_fn marker
Fix some calls from coroutine_fn to no_coroutine_fn

 accel/kvm/kvm-all.c                        |  12 +-
 accel/tcg/plugin-gen.c                     |   9 +-
 accel/tcg/translate-all.c                  |   9 +-
 audio/audio.c                              |   5 +-
 block.c                                    |   2 +-
 block/backup.c                             |   2 +-
 block/block-copy.c                         |   4 +-
 block/commit.c                             |   2 +-
 block/dirty-bitmap.c                       |   6 +-
 block/file-posix.c                         |   6 +-
 block/io.c                                 |  52 +-
 block/mirror.c                             |   4 +-
 block/monitor/block-hmp-cmds.c             |   2 +-
 block/nvme.c                               |   3 +-
 block/parallels.c                          |  28 +-
 block/qcow.c                               |  10 +-
 block/qcow2-bitmap.c                       |   6 +-
 block/qcow2-snapshot.c                     |   6 +-
 block/qcow2.c                              |  38 +-
 block/qcow2.h                              |  14 +-
 block/qed-table.c                          |   2 +-
 block/qed.c                                |  14 +-
 block/quorum.c                             |   7 +-
 block/ssh.c                                |   6 +-
 block/throttle-groups.c                    |   3 +-
 block/vdi.c                                |  17 +-
 block/vhdx.c                               |   8 +-
 block/vmdk.c                               |  11 +-
 block/vpc.c                                |   4 +-
 block/vvfat.c                              |  11 +-
 blockdev.c                                 |   2 +-
 chardev/char-ringbuf.c                     |   4 +-
 contrib/ivshmem-server/main.c              |   4 +-
 contrib/vhost-user-blk/vhost-user-blk.c    |   5 +-
 dump/dump.c                                |   4 +-
 fsdev/virtfs-proxy-helper.c                |   3 +-
 gdbstub.c                                  |  18 +-
 hw/audio/intel-hda.c                       |   7 +-
 hw/audio/pcspk.c                           |   7 +-
 hw/char/virtio-serial-bus.c                |  14 +-
 hw/display/cirrus_vga.c                    |   5 +-
 hw/hyperv/vmbus.c                          |  10 +-
 hw/i386/intel_iommu.c                      |  28 +-
 hw/i386/pc_q35.c                           |   5 +-
 hw/ide/pci.c                               |   4 +-
 hw/net/rtl8139.c                           |   3 +-
 hw/net/virtio-net.c                        |   6 +-
 hw/net/vmxnet3.c                           |   3 +-
 hw/nvme/ctrl.c                             |  17 +-
 hw/nvram/fw_cfg.c                          |   3 +-
 hw/scsi/megasas.c                          |   6 +-
 hw/scsi/mptconfig.c                        |   7 +-
 hw/scsi/mptsas.c                           |  14 +-
 hw/scsi/scsi-bus.c                         |   6 +-
 hw/usb/dev-audio.c                         |  13 +-
 hw/usb/hcd-ehci.c                          |   6 +-
 hw/usb/hcd-ohci.c                          |   4 +-
 hw/usb/hcd-xhci.c                          |  56 +-
 hw/vfio/common.c                           |  21 +-
 hw/virtio/vhost-vdpa.c                     |   3 +-
 hw/virtio/vhost.c                          |  11 +-
 hw/virtio/virtio-iommu.c                   |   4 +-
 hw/virtio/virtio-mem.c                     |   9 +-
 include/block/block-common.h               |   2 +-
 include/block/block-hmp-cmds.h             |   2 +-
 include/block/block-io.h                   |   5 +-
 include/block/block_int-common.h           |  12 +-
 include/qemu/coroutine.h                   |  43 +-
 io/channel-command.c                       |  10 +-
 migration/migration.c                      |  12 +-
 net/dump.c                                 |  16 +-
 net/vhost-vdpa.c                           |   8 +-
 qemu-img.c                                 |   6 +-
 qga/commands-posix-ssh.c                   |  10 +-
 softmmu/physmem.c                          |  18 +-
 softmmu/qtest.c                            |   5 +-
 static-analyzer.py                         | 801 +++++++++++++++++++++
 static_analyzer/__init__.py                | 348 +++++++++
 static_analyzer/coroutine_fn.py            | 280 +++++++
 static_analyzer/no_coroutine_fn.py         | 111 +++
 static_analyzer/return_value_never_used.py | 220 ++++++
 subprojects/libvduse/libvduse.c            |  12 +-
 subprojects/libvhost-user/libvhost-user.c  |  24 +-
 target/i386/host-cpu.c                     |   3 +-
 target/i386/kvm/kvm.c                      |  19 +-
 tcg/optimize.c                             |   3 +-
 tests/qtest/libqos/malloc.c                |   5 +-
 tests/qtest/libqos/qgraph.c                |   3 +-
 tests/qtest/test-x86-cpuid-compat.c        |   8 +-
 tests/qtest/virtio-9p-test.c               |   6 +-
 tests/unit/test-aio-multithread.c          |   5 +-
 tests/vhost-user-bridge.c                  |  19 +-
 ui/vnc.c                                   |  23 +-
 util/aio-posix.c                           |   7 +-
 util/uri.c                                 |  18 +-
 95 files changed, 2160 insertions(+), 519 deletions(-)
 create mode 100755 static-analyzer.py
 create mode 100644 static_analyzer/__init__.py
 create mode 100644 static_analyzer/coroutine_fn.py
 create mode 100644 static_analyzer/no_coroutine_fn.py
 create mode 100644 static_analyzer/return_value_never_used.py
Signature · 1 line
2.37.1
#1 lore raw

RFC v2 1/10 Add an extensible static analyzer

Add a static-analyzer.py script that uses libclang's Python bindings to provide a common framework on which arbitrary static analysis checks can be developed and run against QEMU's code base.

As an example, a simple "return-value-never-used" check is included that verifies that the return value of static, non-void functions is used by at least one caller.

---
 static-analyzer.py                         | 486 +++++++++++++++++++++
 static_analyzer/__init__.py                | 242 ++++++++++
 static_analyzer/return_value_never_used.py | 117 +++++
 3 files changed, 845 insertions(+)
 create mode 100755 static-analyzer.py
 create mode 100644 static_analyzer/__init__.py
 create mode 100644 static_analyzer/return_value_never_used.py
static-analyzer.py new file +486 -0
new file mode 100755
index 0000000000..3ade422dbf
@@ -0,0 +1,486 @@
+#!/usr/bin/env python3
+# ---------------------------------------------------------------------------- #
+
+from configparser import ConfigParser
+from contextlib import contextmanager
+from dataclasses import dataclass
+import json
+import os
+import os.path
+import shlex
+import subprocess
+import sys
+import re
+from argparse import ArgumentParser, Namespace, RawDescriptionHelpFormatter
+from multiprocessing import Pool
+from pathlib import Path
+import textwrap
+import time
+from typing import (
+    Iterable,
+    Iterator,
+    List,
+    Mapping,
+    NoReturn,
+    Sequence,
+    Union,
+)
+
+import clang.cindex  # type: ignore
+
+from static_analyzer import CHECKS, CheckContext
+
+# ---------------------------------------------------------------------------- #
+# Usage
+
+
+def parse_args() -> Namespace:
+
+    available_checks = "\n".join(
+        f"  {name}   {' '.join((CHECKS[name].__doc__ or '').split())}"
+        for name in sorted(CHECKS)
+    )
+
+    parser = ArgumentParser(
+        allow_abbrev=False,
+        formatter_class=RawDescriptionHelpFormatter,
+        description=textwrap.dedent(
+            """
+            Checks are best-effort, but should never report false positives.
+
+            This only considers translation units enabled under the given QEMU
+            build configuration. Note that a single .c file may give rise to
+            several translation units.
+
+            You should build QEMU before running this, since some translation
+            units depend on files that are generated during the build. If you
+            don't, you'll get errors, but should never get false negatives.
+            """
+        ),
+        epilog=textwrap.dedent(
+            f"""
+            available checks:
+            {available_checks}
+
+            exit codes:
+            0  No problems found.
+            1  Internal failure.
+            2  Bad usage.
+            3  Problems found in one or more translation units.
+            """
+        ),
+    )
+
+    parser.add_argument(
+        "build_dir",
+        type=Path,
+        help="Path to the build directory.",
+    )
+
+    parser.add_argument(
+        "translation_units",
+        type=Path,
+        nargs="*",
+        help=(
+            "Analyze only translation units whose root source file matches or"
+            " is under one of the given paths."
+        ),
+    )
+
+    # add regular options
+
+    parser.add_argument(
+        "-c",
+        "--check",
+        metavar="CHECK",
+        dest="check_names",
+        choices=sorted(CHECKS),
+        action="append",
+        help=(
+            "Enable the given check. Can be given multiple times. If not given,"
+            " all checks are enabled."
+        ),
+    )
+
+    parser.add_argument(
+        "-j",
+        "--jobs",
+        dest="threads",
+        type=int,
+        default=os.cpu_count() or 1,
+        help=(
+            f"Number of threads to employ. Defaults to {os.cpu_count() or 1} on"
+            f" this machine."
+        ),
+    )
+
+    # add development options
+
+    dev_options = parser.add_argument_group("development options")
+
+    dev_options.add_argument(
+        "--profile",
+        metavar="SORT_KEY",
+        help=(
+            "Profile execution. Forces single-threaded execution. The argument"
+            " specifies how to sort the results; see"
+            " https://docs.python.org/3/library/profile.html#pstats.Stats.sort_stats"
+        ),
+    )
+
+    dev_options.add_argument(
+        "--skip-checks",
+        action="store_true",
+        help="Do everything except actually running the checks.",
+    )
+
+    # parse arguments
+
+    args = parser.parse_args()
+    args.check_names = sorted(set(args.check_names or CHECKS))
+
+    return args
+
+
+# ---------------------------------------------------------------------------- #
+# Main
+
+
+def main() -> int:
+
+    args = parse_args()
+
+    if args.profile:
+
+        import cProfile
+        import pstats
+
+        profile = cProfile.Profile()
+
+        try:
+            return profile.runcall(lambda: analyze(args))
+        finally:
+            stats = pstats.Stats(profile, stream=sys.stderr)
+            stats.strip_dirs()
+            stats.sort_stats(args.profile)
+            stats.print_stats()
+
+    else:
+
+        return analyze(args)
+
+
+def analyze(args: Namespace) -> int:
+
+    tr_units = get_translation_units(args)
+
+    # analyze translation units
+
+    start_time = time.monotonic()
+    results: List[bool] = []
+
+    if len(tr_units) == 1:
+        progress_suffix = " of 1 translation unit...\033[0m\r"
+    else:
+        progress_suffix = f" of {len(tr_units)} translation units...\033[0m\r"
+
+    def print_progress() -> None:
+        print(f"\033[0;34mAnalyzed {len(results)}" + progress_suffix, end="")
+
+    print_progress()
+
+    def collect_results(results_iter: Iterable[bool]) -> None:
+        if sys.stdout.isatty():
+            for r in results_iter:
+                results.append(r)
+                print_progress()
+        else:
+            for r in results_iter:
+                results.append(r)
+
+    if tr_units:
+
+        if args.threads == 1:
+
+            collect_results(map(analyze_translation_unit, tr_units))
+
+        else:
+
+            # Mimic Python's default pool.map() chunk size, but limit it to
+            # 5 to avoid very big chunks when analyzing thousands of
+            # translation units.
+            chunk_size = min(5, -(-len(tr_units) // (args.threads * 4)))
+
+            with Pool(processes=args.threads) as pool:
+                collect_results(
+                    pool.imap_unordered(
+                        analyze_translation_unit, tr_units, chunk_size
+                    )
+                )
+
+    end_time = time.monotonic()
+
+    # print summary
+
+    if len(tr_units) == 1:
+        message = "Analyzed 1 translation unit"
+    else:
+        message = f"Analyzed {len(tr_units)} translation units"
+
+    message += f" in {end_time - start_time:.1f} seconds."
+
+    print(f"\033[0;34m{message}\033[0m")
+
+    # exit
+
+    return 0 if all(results) else 3
+
+
+# ---------------------------------------------------------------------------- #
+# Translation units
+
+
+@dataclass
+class TranslationUnit:
+    absolute_path: str
+    build_working_dir: str
+    build_command: str
+    system_include_paths: Sequence[str]
+    check_names: Sequence[str]
+
+
+def get_translation_units(args: Namespace) -> Sequence["TranslationUnit"]:
+    """Return a list of translation units to be analyzed."""
+
+    system_include_paths = get_clang_system_include_paths()
+    compile_commands = load_compilation_database(args.build_dir)
+
+    # get all translation units
+
+    tr_units: Iterable[TranslationUnit] = (
+        TranslationUnit(
+            absolute_path=str(Path(cmd["directory"], cmd["file"]).resolve()),
+            build_working_dir=cmd["directory"],
+            build_command=cmd["command"],
+            system_include_paths=system_include_paths,
+            check_names=args.check_names,
+        )
+        for cmd in compile_commands
+    )
+
+    # ignore translation units from git submodules
+
+    repo_root = (args.build_dir / "Makefile").resolve(strict=True).parent
+    module_file = repo_root / ".gitmodules"
+    assert module_file.exists()
+
+    modules = ConfigParser()
+    modules.read(module_file)
+
+    disallowed_prefixes = [
+        # ensure path is slash-terminated
+        os.path.join(repo_root, section["path"], "")
+        for section in modules.values()
+        if "path" in section
+    ]
+
+    tr_units = (
+        ctx
+        for ctx in tr_units
+        if all(
+            not ctx.absolute_path.startswith(prefix)
+            for prefix in disallowed_prefixes
+        )
+    )
+
+    # filter translation units by command line arguments
+
+    if args.translation_units:
+
+        allowed_prefixes = [
+            # ensure path exists and is slash-terminated (even if it is a file)
+            os.path.join(path.resolve(strict=True), "")
+            for path in args.translation_units
+        ]
+
+        tr_units = (
+            ctx
+            for ctx in tr_units
+            if any(
+                (ctx.absolute_path + "/").startswith(prefix)
+                for prefix in allowed_prefixes
+            )
+        )
+
+    # ensure that at least one translation unit is selected
+
+    tr_unit_list = list(tr_units)
+
+    if not tr_unit_list:
+        fatal("No translation units to analyze")
+
+    # disable all checks if --skip-checks was given
+
+    if args.skip_checks:
+        for context in tr_unit_list:
+            context.check_names = []
+
+    return tr_unit_list
+
+
+def get_clang_system_include_paths() -> Sequence[str]:
+
+    # libclang does not automatically include clang's standard system include
+    # paths, so we ask clang what they are and include them ourselves.
+
+    result = subprocess.run(
+        ["clang", "-E", "-", "-v"],
+        stdin=subprocess.DEVNULL,
+        stdout=subprocess.DEVNULL,
+        stderr=subprocess.PIPE,
+        universal_newlines=True,  # decode output using default encoding
+        check=True,
+    )
+
+    # Module `re` does not support repeated group captures.
+    pattern = (
+        r"#include <...> search starts here:\n"
+        r"((?: \S*\n)+)"
+        r"End of search list."
+    )
+
+    match = re.search(pattern, result.stderr, re.MULTILINE)
+    assert match is not None
+
+    return [line[1:] for line in match.group(1).splitlines()]
+
+
+def load_compilation_database(build_dir: Path) -> Sequence[Mapping[str, str]]:
+
+    # clang.cindex.CompilationDatabase.getCompileCommands() apparently produces
+    # entries for files not listed in compile_commands.json in a best-effort
+    # manner, which we don't want, so we parse the JSON ourselves instead.
+
+    path = build_dir / "compile_commands.json"
+
+    try:
+        with path.open("r") as f:
+            return json.load(f)
+    except FileNotFoundError:
+        fatal(f"{path} does not exist")
+
+
+# ---------------------------------------------------------------------------- #
+# Analysis
+
+
+def analyze_translation_unit(tr_unit: TranslationUnit) -> bool:
+
+    check_context = get_check_context(tr_unit)
+
+    try:
+        for name in tr_unit.check_names:
+            CHECKS[name](check_context)
+    except Exception as e:
+        raise RuntimeError(f"Error analyzing {check_context._rel_path}") from e
+
+    return not check_context._problems_found
+
+
+def get_check_context(tr_unit: TranslationUnit) -> CheckContext:
+
+    # relative to script's original working directory
+    rel_path = os.path.relpath(tr_unit.absolute_path)
+
+    # load translation unit
+
+    command = shlex.split(tr_unit.build_command)
+
+    adjusted_command = [
+        # keep the original compilation command name
+        command[0],
+        # ignore unknown GCC warning options
+        "-Wno-unknown-warning-option",
+        # keep all other arguments but the last, which is the file name
+        *command[1:-1],
+        # add clang system include paths
+        *(
+            arg
+            for path in tr_unit.system_include_paths
+            for arg in ("-isystem", path)
+        ),
+        # replace relative path to get absolute location information
+        tr_unit.absolute_path,
+    ]
+
+    # clang can warn about things that GCC doesn't
+    if "-Werror" in adjusted_command:
+        adjusted_command.remove("-Werror")
+
+    # We change directory for options like -I to work, but have to change back
+    # to have correct relative paths in messages.
+    with cwd(tr_unit.build_working_dir):
+
+        try:
+            tu = clang.cindex.TranslationUnit.from_source(
+                filename=None, args=adjusted_command
+            )
+        except clang.cindex.TranslationUnitLoadError as e:
+            raise RuntimeError(f"Failed to load {rel_path}") from e
+
+    if sys.stdout.isatty():
+        # add padding to fully overwrite progress message
+        printer = lambda s: print(s.ljust(50))
+    else:
+        printer = print
+
+    check_context = CheckContext(
+        translation_unit=tu,
+        translation_unit_path=tr_unit.absolute_path,
+        _rel_path=rel_path,
+        _build_working_dir=Path(tr_unit.build_working_dir),
+        _problems_found=False,
+        _printer=printer,
+    )
+
+    # check for error/fatal diagnostics
+
+    for diag in tu.diagnostics:
+        if diag.severity >= clang.cindex.Diagnostic.Error:
+            check_context._problems_found = True
+            location = check_context.format_location(diag)
+            check_context._printer(
+                f"\033[0;33m{location}: {diag.spelling}; this may lead to false"
+                f" positives and negatives\033[0m"
+            )
+
+    return check_context
+
+
+# ---------------------------------------------------------------------------- #
+# Utilities
+
+
+@contextmanager
+def cwd(path: Union[str, Path]) -> Iterator[None]:
+
+    original_cwd = os.getcwd()
+    os.chdir(path)
+
+    try:
+        yield
+    finally:
+        os.chdir(original_cwd)
+
+
+def fatal(message: str) -> NoReturn:
+    print(f"\033[0;31mERROR: {message}\033[0m")
+    sys.exit(1)
+
+
+# ---------------------------------------------------------------------------- #
+
+if __name__ == "__main__":
+    sys.exit(main())
+
+# ---------------------------------------------------------------------------- #
static_analyzer/__init__.py new file +242 -0

242 lines not on this page · raw message

static_analyzer/return_value_never_used.py new file +117 -0

117 lines not on this page · raw message

Signature · 1 line
2.37.1
#2 lore raw

RFC v2 2/10 Drop unused static function return values

In reply to Alberto Faria

Make non-void static functions whose return values are ignored by all callers return void instead.

These functions were found by static-analyzer.py.

Not all occurrences of this problem were fixed.

---
 accel/kvm/kvm-all.c                       | 12 ++---
 accel/tcg/plugin-gen.c                    |  9 ++--
 accel/tcg/translate-all.c                 |  9 ++--
 audio/audio.c                             |  5 +-
 block/block-copy.c                        |  4 +-
 block/file-posix.c                        |  6 +--
 block/io.c                                | 30 +++++-------
 block/qcow2-bitmap.c                      |  6 +--
 block/quorum.c                            |  5 +-
 block/vpc.c                               |  4 +-
 block/vvfat.c                             | 11 ++---
 chardev/char-ringbuf.c                    |  4 +-
 contrib/ivshmem-server/main.c             |  4 +-
 contrib/vhost-user-blk/vhost-user-blk.c   |  5 +-
 dump/dump.c                               |  4 +-
 fsdev/virtfs-proxy-helper.c               |  3 +-
 gdbstub.c                                 | 18 +++-----
 hw/audio/intel-hda.c                      |  7 ++-
 hw/audio/pcspk.c                          |  7 +--
 hw/char/virtio-serial-bus.c               | 14 +++---
 hw/display/cirrus_vga.c                   |  5 +-
 hw/hyperv/vmbus.c                         | 10 ++--
 hw/i386/intel_iommu.c                     | 28 ++++++------
 hw/i386/pc_q35.c                          |  5 +-
 hw/ide/pci.c                              |  4 +-
 hw/net/rtl8139.c                          |  3 +-
 hw/net/virtio-net.c                       |  6 +--
 hw/net/vmxnet3.c                          |  3 +-
 hw/nvme/ctrl.c                            | 17 ++-----
 hw/nvram/fw_cfg.c                         |  3 +-
 hw/scsi/megasas.c                         |  6 +--
 hw/scsi/mptconfig.c                       |  7 +--
 hw/scsi/mptsas.c                          | 14 ++----
 hw/scsi/scsi-bus.c                        |  6 +--
 hw/usb/dev-audio.c                        | 13 +++---
 hw/usb/hcd-ehci.c                         |  6 +--
 hw/usb/hcd-ohci.c                         |  4 +-
 hw/usb/hcd-xhci.c                         | 56 +++++++++++------------
 hw/vfio/common.c                          | 21 +++++----
 hw/virtio/vhost-vdpa.c                    |  3 +-
 hw/virtio/vhost.c                         | 11 ++---
 hw/virtio/virtio-iommu.c                  |  4 +-
 hw/virtio/virtio-mem.c                    |  9 ++--
 io/channel-command.c                      | 10 ++--
 migration/migration.c                     | 12 ++---
 net/dump.c                                | 16 +++----
 net/vhost-vdpa.c                          |  8 ++--
 qemu-img.c                                |  6 +--
 qga/commands-posix-ssh.c                  | 10 ++--
 softmmu/physmem.c                         | 18 ++++----
 softmmu/qtest.c                           |  5 +-
 subprojects/libvduse/libvduse.c           | 12 ++---
 subprojects/libvhost-user/libvhost-user.c | 24 ++++------
 target/i386/host-cpu.c                    |  3 +-
 target/i386/kvm/kvm.c                     | 19 ++++----
 tcg/optimize.c                            |  3 +-
 tests/qtest/libqos/malloc.c               |  5 +-
 tests/qtest/libqos/qgraph.c               |  3 +-
 tests/qtest/test-x86-cpuid-compat.c       |  8 ++--
 tests/qtest/virtio-9p-test.c              |  6 +--
 tests/unit/test-aio-multithread.c         |  5 +-
 tests/vhost-user-bridge.c                 | 19 +++-----
 ui/vnc.c                                  | 23 ++++------
 util/aio-posix.c                          |  7 +--
 util/uri.c                                | 18 +++-----
 65 files changed, 248 insertions(+), 403 deletions(-)
accel/kvm/kvm-all.c +3 -9
index f165074e99..748e9d6a2a 100644
@@ -759,7 +759,7 @@ static uint32_t kvm_dirty_ring_reap_one(KVMState *s, CPUState *cpu)
 }
 
 /* Must be with slots_lock held */
-static uint64_t kvm_dirty_ring_reap_locked(KVMState *s, CPUState* cpu)
+static void kvm_dirty_ring_reap_locked(KVMState *s, CPUState* cpu)
 {
     int ret;
     uint64_t total = 0;
@@ -785,18 +785,14 @@ static uint64_t kvm_dirty_ring_reap_locked(KVMState *s, CPUState* cpu)
     if (total) {
         trace_kvm_dirty_ring_reap(total, stamp / 1000);
     }
-
-    return total;
 }
 
 /*
  * Currently for simplicity, we must hold BQL before calling this.  We can
  * consider to drop the BQL if we're clear with all the race conditions.
  */
-static uint64_t kvm_dirty_ring_reap(KVMState *s, CPUState *cpu)
+static void kvm_dirty_ring_reap(KVMState *s, CPUState *cpu)
 {
-    uint64_t total;
-
     /*
      * We need to lock all kvm slots for all address spaces here,
      * because:
@@ -813,10 +809,8 @@ static uint64_t kvm_dirty_ring_reap(KVMState *s, CPUState *cpu)
      *     reset below.
      */
     kvm_slots_lock();
-    total = kvm_dirty_ring_reap_locked(s, cpu);
+    kvm_dirty_ring_reap_locked(s, cpu);
     kvm_slots_unlock();
-
-    return total;
 }
 
 static void do_kvm_cpu_synchronize_kick(CPUState *cpu, run_on_cpu_data arg)
accel/tcg/plugin-gen.c +3 -6
index 3d0b101e34..ca84f1f1f8 100644
@@ -239,21 +239,18 @@ static TCGOp *find_op(TCGOp *op, TCGOpcode opc)
     return NULL;
 }
 
-static TCGOp *rm_ops_range(TCGOp *begin, TCGOp *end)
+static void rm_ops_range(TCGOp *begin, TCGOp *end)
 {
-    TCGOp *ret = QTAILQ_NEXT(end, link);
-
     QTAILQ_REMOVE_SEVERAL(&tcg_ctx->ops, begin, end, link);
-    return ret;
 }
 
 /* remove all ops until (and including) plugin_cb_end */
-static TCGOp *rm_ops(TCGOp *op)
+static void rm_ops(TCGOp *op)
 {
     TCGOp *end_op = find_op(op, INDEX_op_plugin_cb_end);
 
     tcg_debug_assert(end_op);
-    return rm_ops_range(op, end_op);
+    rm_ops_range(op, end_op);
 }
 
 static TCGOp *copy_op_nocheck(TCGOp **begin_op, TCGOp *op)
accel/tcg/translate-all.c +4 -5
index ef62a199c7..0c93c3143d 100644
@@ -329,8 +329,8 @@ static int encode_search(TranslationBlock *tb, uint8_t *block)
  * When reset_icount is true, current TB will be interrupted and
  * icount should be recalculated.
  */
-static int cpu_restore_state_from_tb(CPUState *cpu, TranslationBlock *tb,
-                                     uintptr_t searched_pc, bool reset_icount)
+static void cpu_restore_state_from_tb(CPUState *cpu, TranslationBlock *tb,
+                                      uintptr_t searched_pc, bool reset_icount)
 {
     target_ulong data[TARGET_INSN_START_WORDS] = { tb->pc };
     uintptr_t host_pc = (uintptr_t)tb->tc.ptr;
@@ -345,7 +345,7 @@ static int cpu_restore_state_from_tb(CPUState *cpu, TranslationBlock *tb,
     searched_pc -= GETPC_ADJ;
 
     if (searched_pc < host_pc) {
-        return -1;
+        return;
     }
 
     /* Reconstruct the stored insn data while looking for the point at
@@ -359,7 +359,7 @@ static int cpu_restore_state_from_tb(CPUState *cpu, TranslationBlock *tb,
             goto found;
         }
     }
-    return -1;
+    return;
 
  found:
     if (reset_icount && (tb_cflags(tb) & CF_USE_ICOUNT)) {
@@ -375,7 +375,6 @@ static int cpu_restore_state_from_tb(CPUState *cpu, TranslationBlock *tb,
                 prof->restore_time + profile_getclock() - ti);
     qatomic_set(&prof->restore_count, prof->restore_count + 1);
 #endif
-    return 0;
 }
 
 bool cpu_restore_state(CPUState *cpu, uintptr_t host_pc, bool will_exit)
audio/audio.c +2 -3
index a02f3ce5c6..79022b2325 100644
@@ -478,7 +478,7 @@ static void audio_detach_capture (HWVoiceOut *hw)
     }
 }
 
-static int audio_attach_capture (HWVoiceOut *hw)
+static void audio_attach_capture(HWVoiceOut *hw)
 {
     AudioState *s = hw->s;
     CaptureVoiceOut *cap;
@@ -504,7 +504,7 @@ static int audio_attach_capture (HWVoiceOut *hw)
         if (!sw->rate) {
             dolog ("Could not start rate conversion for `%s'\n", SW_NAME (sw));
             g_free (sw);
-            return -1;
+            return;
         }
         QLIST_INSERT_HEAD (&hw_cap->sw_head, sw, entries);
         QLIST_INSERT_HEAD (&hw->cap_head, sc, entries);
@@ -518,7 +518,6 @@ static int audio_attach_capture (HWVoiceOut *hw)
             audio_capture_maybe_changed (cap, 1);
         }
     }
-    return 0;
 }
 
 /*
block/block-copy.c +1 -3
index bb947afdda..20a1b425d5 100644
@@ -820,7 +820,7 @@ void block_copy_kick(BlockCopyCallState *call_state)
  * it means that some I/O operation failed in context of _this_ block_copy call,
  * not some parallel operation.
  */
-static int coroutine_fn block_copy_common(BlockCopyCallState *call_state)
+static void coroutine_fn block_copy_common(BlockCopyCallState *call_state)
 {
     int ret;
     BlockCopyState *s = call_state->s;
@@ -879,8 +879,6 @@ static int coroutine_fn block_copy_common(BlockCopyCallState *call_state)
     qemu_co_mutex_lock(&s->lock);
     QLIST_REMOVE(call_state, list);
     qemu_co_mutex_unlock(&s->lock);
-
-    return ret;
 }
 
 static void coroutine_fn block_copy_async_co_entry(void *opaque)
block/file-posix.c +1 -5
index 48cd096624..a4641da7f9 100644
@@ -1895,7 +1895,7 @@ static int handle_aiocb_discard(void *opaque)
  * Returns: 0 on success, -errno on failure. Since this is an optimization,
  * caller may ignore failures.
  */
-static int allocate_first_block(int fd, size_t max_size)
+static void allocate_first_block(int fd, size_t max_size)
 {
     size_t write_size = (max_size < MAX_BLOCKSIZE)
         ? BDRV_SECTOR_SIZE
@@ -1903,7 +1903,6 @@ static int allocate_first_block(int fd, size_t max_size)
     size_t max_align = MAX(MAX_BLOCKSIZE, qemu_real_host_page_size());
     void *buf;
     ssize_t n;
-    int ret;
 
     buf = qemu_memalign(max_align, write_size);
     memset(buf, 0, write_size);
@@ -1912,10 +1911,7 @@ static int allocate_first_block(int fd, size_t max_size)
         n = pwrite(fd, buf, write_size, 0);
     } while (n == -1 && errno == EINTR);
 
-    ret = (n == -1) ? -errno : 0;
-
     qemu_vfree(buf);
-    return ret;
 }
 
 static int handle_aiocb_truncate(void *opaque)
block/io.c +12 -18
index 0a8cbefe86..853ed44289 100644
@@ -934,20 +934,16 @@ void bdrv_dec_in_flight(BlockDriverState *bs)
     bdrv_wakeup(bs);
 }
 
-static bool coroutine_fn bdrv_wait_serialising_requests(BdrvTrackedRequest *self)
+static void coroutine_fn
+bdrv_wait_serialising_requests(BdrvTrackedRequest *self)
 {
     BlockDriverState *bs = self->bs;
-    bool waited = false;
 
-    if (!qatomic_read(&bs->serialising_in_flight)) {
-        return false;
+    if (qatomic_read(&bs->serialising_in_flight)) {
+        qemu_co_mutex_lock(&bs->reqs_lock);
+        bdrv_wait_serialising_requests_locked(self);
+        qemu_co_mutex_unlock(&bs->reqs_lock);
     }
-
-    qemu_co_mutex_lock(&bs->reqs_lock);
-    waited = bdrv_wait_serialising_requests_locked(self);
-    qemu_co_mutex_unlock(&bs->reqs_lock);
-
-    return waited;
 }
 
 bool coroutine_fn bdrv_make_request_serialising(BdrvTrackedRequest *req,
@@ -1644,10 +1640,10 @@ static bool bdrv_init_padding(BlockDriverState *bs,
     return true;
 }
 
-static int bdrv_padding_rmw_read(BdrvChild *child,
-                                 BdrvTrackedRequest *req,
-                                 BdrvRequestPadding *pad,
-                                 bool zero_middle)
+static void bdrv_padding_rmw_read(BdrvChild *child,
+                                  BdrvTrackedRequest *req,
+                                  BdrvRequestPadding *pad,
+                                  bool zero_middle)
 {
     QEMUIOVector local_qiov;
     BlockDriverState *bs = child->bs;
@@ -1670,7 +1666,7 @@ static int bdrv_padding_rmw_read(BdrvChild *child,
         ret = bdrv_aligned_preadv(child, req, req->overlap_offset, bytes,
                                   align, &local_qiov, 0, 0);
         if (ret < 0) {
-            return ret;
+            return;
         }
         if (pad->head) {
             bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_HEAD);
@@ -1693,7 +1689,7 @@ static int bdrv_padding_rmw_read(BdrvChild *child,
                 req->overlap_offset + req->overlap_bytes - align,
                 align, align, &local_qiov, 0, 0);
         if (ret < 0) {
-            return ret;
+            return;
         }
         bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL);
     }
@@ -1702,8 +1698,6 @@ zero_mem:
     if (zero_middle) {
         memset(pad->buf + pad->head, 0, pad->buf_len - pad->head - pad->tail);
     }
-
-    return 0;
 }
 
 static void bdrv_padding_destroy(BdrvRequestPadding *pad)
block/qcow2-bitmap.c +2 -4
index e98bafe0f4..14e55cefac 100644
@@ -257,14 +257,14 @@ fail:
     return ret;
 }
 
-static int free_bitmap_clusters(BlockDriverState *bs, Qcow2BitmapTable *tb)
+static void free_bitmap_clusters(BlockDriverState *bs, Qcow2BitmapTable *tb)
 {
     int ret;
     uint64_t *bitmap_table;
 
     ret = bitmap_table_load(bs, tb, &bitmap_table);
     if (ret < 0) {
-        return ret;
+        return;
     }
 
     clear_bitmap_table(bs, bitmap_table, tb->size);
@@ -274,8 +274,6 @@ static int free_bitmap_clusters(BlockDriverState *bs, Qcow2BitmapTable *tb)
 
     tb->offset = 0;
     tb->size = 0;
-
-    return 0;
 }
 
 /* load_bitmap_data
block/quorum.c +1 -4
index f33f30d36b..9c0fbd79be 100644
@@ -293,7 +293,7 @@ static void quorum_rewrite_entry(void *opaque)
     }
 }
 
-static bool quorum_rewrite_bad_versions(QuorumAIOCB *acb,
+static void quorum_rewrite_bad_versions(QuorumAIOCB *acb,
                                         QuorumVoteValue *value)
 {
     QuorumVoteVersion *version;
@@ -331,9 +331,6 @@ static bool quorum_rewrite_bad_versions(QuorumAIOCB *acb,
             qemu_coroutine_enter(co);
         }
     }
-
-    /* return true if any rewrite is done else false */
-    return count;
 }
 
 static void quorum_count_vote(QuorumVotes *votes,
block/vpc.c +1 -3
index 4f49ef207f..03d65505d1 100644
@@ -782,7 +782,7 @@ static int coroutine_fn vpc_co_block_status(BlockDriverState *bs,
  * the hardware EIDE and ATA-2 limit of 16 heads (max disk size of 127 GB)
  * and instead allow up to 255 heads.
  */
-static int calculate_geometry(int64_t total_sectors, uint16_t *cyls,
+static void calculate_geometry(int64_t total_sectors, uint16_t *cyls,
     uint8_t *heads, uint8_t *secs_per_cyl)
 {
     uint32_t cyls_times_heads;
@@ -816,8 +816,6 @@ static int calculate_geometry(int64_t total_sectors, uint16_t *cyls,
     }
 
     *cyls = cyls_times_heads / *heads;
-
-    return 0;
 }
 
 static int create_dynamic_disk(BlockBackend *blk, VHDFooter *footer,
block/vvfat.c +5 -6
index d6dd919683..6c4c66eff7 100644
@@ -154,9 +154,9 @@ static inline int array_remove_slice(array_t* array,int index, int count)
     return 0;
 }
 
-static int array_remove(array_t* array,int index)
+static void array_remove(array_t* array,int index)
 {
-    return array_remove_slice(array, index, 1);
+    array_remove_slice(array, index, 1);
 }
 
 /* return the index for a given member */
@@ -2968,13 +2968,12 @@ DLOG(checkpoint());
     return 0;
 }
 
-static int try_commit(BDRVVVFATState* s)
+static void try_commit(BDRVVVFATState* s)
 {
     vvfat_close_current_file(s);
 DLOG(checkpoint());
-    if(!is_consistent(s))
-        return -1;
-    return do_commit(s);
+    if (is_consistent(s))
+        do_commit(s);
 }
 
 static int vvfat_write(BlockDriverState *bs, int64_t sector_num,
chardev/char-ringbuf.c +1 -3
index d40d21d3cf..335d75e824 100644
@@ -71,7 +71,7 @@ static int ringbuf_chr_write(Chardev *chr, const uint8_t *buf, int len)
     return len;
 }
 
-static int ringbuf_chr_read(Chardev *chr, uint8_t *buf, int len)
+static void ringbuf_chr_read(Chardev *chr, uint8_t *buf, int len)
 {
     RingBufChardev *d = RINGBUF_CHARDEV(chr);
     int i;
@@ -81,8 +81,6 @@ static int ringbuf_chr_read(Chardev *chr, uint8_t *buf, int len)
         buf[i] = d->cbuf[d->cons++ & (d->size - 1)];
     }
     qemu_mutex_unlock(&chr->chr_write_lock);
-
-    return i;
 }
 
 static void char_ringbuf_finalize(Object *obj)
contrib/ivshmem-server/main.c +1 -3
index 224dbeb547..67a0d7a497 100644
@@ -143,7 +143,7 @@ ivshmem_server_parse_args(IvshmemServerArgs *args, int argc, char *argv[])
 
 /* wait for events on listening server unix socket and connected client
  * sockets */
-static int
+static void
 ivshmem_server_poll_events(IvshmemServer *server)
 {
     fd_set fds;
@@ -174,8 +174,6 @@ ivshmem_server_poll_events(IvshmemServer *server)
             break;
         }
     }
-
-    return ret;
 }
 
 static void
contrib/vhost-user-blk/vhost-user-blk.c +2 -3
index 9cb78ca1d0..e4df9a074c 100644
@@ -66,8 +66,8 @@ static size_t vub_iov_size(const struct iovec *iov,
     return len;
 }
 
-static size_t vub_iov_to_buf(const struct iovec *iov,
-                             const unsigned int iov_cnt, void *buf)
+static void vub_iov_to_buf(const struct iovec *iov,
+                           const unsigned int iov_cnt, void *buf)
 {
     size_t len;
     unsigned int i;
@@ -77,7 +77,6 @@ static size_t vub_iov_to_buf(const struct iovec *iov,
         memcpy(buf + len,  iov[i].iov_base, iov[i].iov_len);
         len += iov[i].iov_len;
     }
-    return len;
 }
 
 static void vub_panic_cb(VuDev *vu_dev, const char *buf)
dump/dump.c +1 -3
index 4d9658ffa2..5080ecf574 100644
@@ -92,7 +92,7 @@ uint64_t cpu_to_dump64(DumpState *s, uint64_t val)
     return val;
 }
 
-static int dump_cleanup(DumpState *s)
+static void dump_cleanup(DumpState *s)
 {
     guest_phys_blocks_free(&s->guest_phys_blocks);
     memory_mapping_list_free(&s->list);
@@ -109,8 +109,6 @@ static int dump_cleanup(DumpState *s)
         }
     }
     migrate_del_blocker(dump_migration_blocker);
-
-    return 0;
 }
 
 static int fd_write_vmcore(const void *buf, size_t size, void *opaque)
fsdev/virtfs-proxy-helper.c +1 -2
index 2dde27922f..b91f730120 100644
@@ -829,7 +829,7 @@ static int process_reply(int sock, int type,
     return 0;
 }
 
-static int process_requests(int sock)
+static void process_requests(int sock)
 {
     int flags;
     int size = 0;
@@ -1016,7 +1016,6 @@ static int process_requests(int sock)
 err_out:
     g_free(in_iovec.iov_base);
     g_free(out_iovec.iov_base);
-    return -1;
 }
 
 int main(int argc, char **argv)
gdbstub.c +6 -12
index cf869b10e3..f73461848c 100644
@@ -506,10 +506,9 @@ static inline void gdb_continue(void)
  * Resume execution, per CPU actions. For user-mode emulation it's
  * equivalent to gdb_continue.
  */
-static int gdb_continue_partial(char *newstates)
+static void gdb_continue_partial(char *newstates)
 {
     CPUState *cpu;
-    int res = 0;
 #ifdef CONFIG_USER_ONLY
     /*
      * This is not exactly accurate, but it's an improvement compared to the
@@ -535,7 +534,7 @@ static int gdb_continue_partial(char *newstates)
         }
 
         if (vm_prepare_start(step_requested)) {
-            return 0;
+            return;
         }
 
         CPU_FOREACH(cpu) {
@@ -555,7 +554,6 @@ static int gdb_continue_partial(char *newstates)
                 flag = 1;
                 break;
             default:
-                res = -1;
                 break;
             }
         }
@@ -564,7 +562,6 @@ static int gdb_continue_partial(char *newstates)
         qemu_clock_enable(QEMU_CLOCK_VIRTUAL, true);
     }
 #endif
-    return res;
 }
 
 static void put_buffer(const uint8_t *buf, int len)
@@ -665,8 +662,7 @@ static void hexdump(const char *buf, int len,
     }
 }
 
-/* return -1 if error, 0 if OK */
-static int put_packet_binary(const char *buf, int len, bool dump)
+static void put_packet_binary(const char *buf, int len, bool dump)
 {
     int csum, i;
     uint8_t footer[3];
@@ -696,22 +692,20 @@ static int put_packet_binary(const char *buf, int len, bool dump)
 #ifdef CONFIG_USER_ONLY
         i = get_char();
         if (i < 0)
-            return -1;
+            return;
         if (i == '+')
             break;
 #else
         break;
 #endif
     }
-    return 0;
 }
 
-/* return -1 if error, 0 if OK */
-static int put_packet(const char *buf)
+static void put_packet(const char *buf)
 {
     trace_gdbstub_io_reply(buf);
 
-    return put_packet_binary(buf, strlen(buf), false);
+    put_packet_binary(buf, strlen(buf), false);
 }
 
 static void put_strbuf(void)
hw/audio/intel-hda.c +3 -4
index f38117057b..19284c5c9d 100644
@@ -283,7 +283,7 @@ static void intel_hda_update_irq(IntelHDAState *d)
     }
 }
 
-static int intel_hda_send_command(IntelHDAState *d, uint32_t verb)
+static void intel_hda_send_command(IntelHDAState *d, uint32_t verb)
 {
     uint32_t cad, nid, data;
     HDACodecDevice *codec;
@@ -293,7 +293,7 @@ static int intel_hda_send_command(IntelHDAState *d, uint32_t verb)
     if (verb & (1 << 27)) {
         /* indirect node addressing, not specified in HDA 1.0 */
         dprint(d, 1, "%s: indirect node addressing (guest bug?)\n", __func__);
-        return -1;
+        return;
     }
     nid = (verb >> 20) & 0x7f;
     data = verb & 0xfffff;
@@ -301,11 +301,10 @@ static int intel_hda_send_command(IntelHDAState *d, uint32_t verb)
     codec = hda_codec_find(&d->codecs, cad);
     if (codec == NULL) {
         dprint(d, 1, "%s: addressed non-existing codec\n", __func__);
-        return -1;
+        return;
     }
     cdc = HDA_CODEC_DEVICE_GET_CLASS(codec);
     cdc->command(codec, nid, data);
-    return 0;
 }
 
 static void intel_hda_corb_run(IntelHDAState *d)
hw/audio/pcspk.c +2 -5
index daf92a4ce1..027c04a88e 100644
@@ -114,13 +114,13 @@ static void pcspk_callback(void *opaque, int free)
     }
 }
 
-static int pcspk_audio_init(PCSpkState *s)
+static void pcspk_audio_init(PCSpkState *s)
 {
     struct audsettings as = {PCSPK_SAMPLE_RATE, 1, AUDIO_FORMAT_U8, 0};
 
     if (s->voice) {
         /* already initialized */
-        return 0;
+        return;
     }
 
     AUD_register_card(s_spk, &s->card);
@@ -128,10 +128,7 @@ static int pcspk_audio_init(PCSpkState *s)
     s->voice = AUD_open_out(&s->card, s->voice, s_spk, s, pcspk_callback, &as);
     if (!s->voice) {
         AUD_log(s_spk, "Could not open voice\n");
-        return -1;
     }
-
-    return 0;
 }
 
 static uint64_t pcspk_io_read(void *opaque, hwaddr addr,
hw/char/virtio-serial-bus.c +6 -8
index 7d4601cb5d..5196b8d5ea 100644
@@ -221,19 +221,19 @@ static void flush_queued_data(VirtIOSerialPort *port)
     do_flush_queued_data(port, port->ovq, VIRTIO_DEVICE(port->vser));
 }
 
-static size_t send_control_msg(VirtIOSerial *vser, void *buf, size_t len)
+static void send_control_msg(VirtIOSerial *vser, void *buf, size_t len)
 {
     VirtQueueElement *elem;
     VirtQueue *vq;
 
     vq = vser->c_ivq;
     if (!virtio_queue_ready(vq)) {
-        return 0;
+        return;
     }
 
     elem = virtqueue_pop(vq, sizeof(VirtQueueElement));
     if (!elem) {
-        return 0;
+        return;
     }
 
     /* TODO: detect a buffer that's too short, set NEEDS_RESET */
@@ -242,12 +242,10 @@ static size_t send_control_msg(VirtIOSerial *vser, void *buf, size_t len)
     virtqueue_push(vq, elem, len);
     virtio_notify(VIRTIO_DEVICE(vser), vq);
     g_free(elem);
-
-    return len;
 }
 
-static size_t send_control_event(VirtIOSerial *vser, uint32_t port_id,
-                                 uint16_t event, uint16_t value)
+static void send_control_event(VirtIOSerial *vser, uint32_t port_id,
+                               uint16_t event, uint16_t value)
 {
     VirtIODevice *vdev = VIRTIO_DEVICE(vser);
     struct virtio_console_control cpkt;
@@ -257,7 +255,7 @@ static size_t send_control_event(VirtIOSerial *vser, uint32_t port_id,
     virtio_stw_p(vdev, &cpkt.value, value);
 
     trace_virtio_serial_send_control_event(port_id, event, value);
-    return send_control_msg(vser, &cpkt, sizeof(cpkt));
+    send_control_msg(vser, &cpkt, sizeof(cpkt));
 }
 
 /* Functions for use inside qemu to open and read from/write to ports */
hw/display/cirrus_vga.c +2 -3
index 3bb6a58698..f8e7e2d077 100644
@@ -696,12 +696,12 @@ static int cirrus_bitblt_common_patterncopy(CirrusVGAState *s)
 
 /* fill */
 
-static int cirrus_bitblt_solidfill(CirrusVGAState *s, int blt_rop)
+static void cirrus_bitblt_solidfill(CirrusVGAState *s, int blt_rop)
 {
     cirrus_fill_t rop_func;
 
     if (blit_is_unsafe(s, true)) {
-        return 0;
+        return;
     }
     rop_func = cirrus_fill[rop_to_index[blt_rop]][s->cirrus_blt_pixelwidth - 1];
     rop_func(s, s->cirrus_blt_dstaddr,
@@ -711,7 +711,6 @@ static int cirrus_bitblt_solidfill(CirrusVGAState *s, int blt_rop)
 			     s->cirrus_blt_dstpitch, s->cirrus_blt_width,
 			     s->cirrus_blt_height);
     cirrus_bitblt_reset(s);
-    return 1;
 }
 
 /***************************************
hw/hyperv/vmbus.c +4 -6
index 30bc04e1c4..c18e4942e3 100644
@@ -728,9 +728,8 @@ bool vmbus_channel_is_open(VMBusChannel *chan)
  * flag (more recent guests) or setting a bit in the interrupt page and firing
  * the VMBus SINT (older guests).
  */
-static int vmbus_channel_notify_guest(VMBusChannel *chan)
+static void vmbus_channel_notify_guest(VMBusChannel *chan)
 {
-    int res = 0;
     unsigned long *int_map, mask;
     unsigned idx;
     hwaddr addr = chan->vmbus->int_page_gpa;
@@ -739,25 +738,24 @@ static int vmbus_channel_notify_guest(VMBusChannel *chan)
     trace_vmbus_channel_notify_guest(chan->id);
 
     if (!addr) {
-        return hyperv_set_event_flag(chan->notify_route, chan->id);
+        hyperv_set_event_flag(chan->notify_route, chan->id);
+        return;
     }
 
     int_map = cpu_physical_memory_map(addr, &len, 1);
     if (len != TARGET_PAGE_SIZE / 2) {
-        res = -ENXIO;
         goto unmap;
     }
 
     idx = BIT_WORD(chan->id);
     mask = BIT_MASK(chan->id);
     if ((qatomic_fetch_or(&int_map[idx], mask) & mask) != mask) {
-        res = hyperv_sint_route_set_sint(chan->notify_route);
+        hyperv_sint_route_set_sint(chan->notify_route);
         dirty = len;
     }
 
 unmap:
     cpu_physical_memory_unmap(int_map, len, 1, dirty);
-    return res;
 }
 
 #define VMBUS_PKT_TRAILER      sizeof(uint64_t)
hw/i386/intel_iommu.c +13 -15
index 2162394e08..970ba19593 100644
@@ -146,12 +146,11 @@ static void vtd_set_quad_raw(IntelIOMMUState *s, hwaddr addr, uint64_t val)
     stq_le_p(&s->csr[addr], val);
 }
 
-static uint32_t vtd_set_clear_mask_long(IntelIOMMUState *s, hwaddr addr,
-                                        uint32_t clear, uint32_t mask)
+static void vtd_set_clear_mask_long(IntelIOMMUState *s, hwaddr addr,
+                                    uint32_t clear, uint32_t mask)
 {
     uint32_t new_val = (ldl_le_p(&s->csr[addr]) & ~clear) | mask;
     stl_le_p(&s->csr[addr], new_val);
-    return new_val;
 }
 
 static uint64_t vtd_set_clear_mask_quad(IntelIOMMUState *s, hwaddr addr,
@@ -1312,15 +1311,15 @@ next:
  * @end: IOVA range end address (start <= addr < end)
  * @info: page walking information struct
  */
-static int vtd_page_walk(IntelIOMMUState *s, VTDContextEntry *ce,
-                         uint64_t start, uint64_t end,
-                         vtd_page_walk_info *info)
+static void vtd_page_walk(IntelIOMMUState *s, VTDContextEntry *ce,
+                          uint64_t start, uint64_t end,
+                          vtd_page_walk_info *info)
 {
     dma_addr_t addr = vtd_get_iova_pgtbl_base(s, ce);
     uint32_t level = vtd_get_iova_level(s, ce);
 
     if (!vtd_iova_range_check(s, start, ce, info->aw)) {
-        return -VTD_FR_ADDR_BEYOND_MGAW;
+        return;
     }
 
     if (!vtd_iova_range_check(s, end, ce, info->aw)) {
@@ -1328,7 +1327,7 @@ static int vtd_page_walk(IntelIOMMUState *s, VTDContextEntry *ce,
         end = vtd_iova_limit(s, ce, info->aw);
     }
 
-    return vtd_page_walk_level(addr, start, end, level, true, true, info);
+    vtd_page_walk_level(addr, start, end, level, true, true, info);
 }
 
 static int vtd_root_entry_rsvd_bits_check(IntelIOMMUState *s,
@@ -1488,7 +1487,7 @@ static uint16_t vtd_get_domain_id(IntelIOMMUState *s,
     return VTD_CONTEXT_ENTRY_DID(ce->hi);
 }
 
-static int vtd_sync_shadow_page_table_range(VTDAddressSpace *vtd_as,
+static void vtd_sync_shadow_page_table_range(VTDAddressSpace *vtd_as,
                                             VTDContextEntry *ce,
                                             hwaddr addr, hwaddr size)
 {
@@ -1502,17 +1501,17 @@ static int vtd_sync_shadow_page_table_range(VTDAddressSpace *vtd_as,
         .domain_id = vtd_get_domain_id(s, ce),
     };
 
-    return vtd_page_walk(s, ce, addr, addr + size, &info);
+    vtd_page_walk(s, ce, addr, addr + size, &info);
 }
 
-static int vtd_sync_shadow_page_table(VTDAddressSpace *vtd_as)
+static void vtd_sync_shadow_page_table(VTDAddressSpace *vtd_as)
 {
     int ret;
     VTDContextEntry ce;
     IOMMUNotifier *n;
 
     if (!(vtd_as->iommu.iommu_notify_flags & IOMMU_NOTIFIER_IOTLB_EVENTS)) {
-        return 0;
+        return;
     }
 
     ret = vtd_dev_to_context_entry(vtd_as->iommu_state,
@@ -1532,12 +1531,11 @@ static int vtd_sync_shadow_page_table(VTDAddressSpace *vtd_as)
             IOMMU_NOTIFIER_FOREACH(n, &vtd_as->iommu) {
                 vtd_address_space_unmap(vtd_as, n);
             }
-            ret = 0;
         }
-        return ret;
+        return;
     }
 
-    return vtd_sync_shadow_page_table_range(vtd_as, &ce, 0, UINT64_MAX);
+    vtd_sync_shadow_page_table_range(vtd_as, &ce, 0, UINT64_MAX);
 }
 
 /*
hw/i386/pc_q35.c +2 -3
index 3a35193ff7..aa7f9d778a 100644
@@ -76,7 +76,7 @@ static const struct ehci_companions ich9_1a[] = {
     { .name = "ich9-usb-uhci6", .func = 2, .port = 4 },
 };
 
-static int ehci_create_ich9_with_companions(PCIBus *bus, int slot)
+static void ehci_create_ich9_with_companions(PCIBus *bus, int slot)
 {
     const struct ehci_companions *comp;
     PCIDevice *ehci, *uhci;
@@ -94,7 +94,7 @@ static int ehci_create_ich9_with_companions(PCIBus *bus, int slot)
         comp = ich9_1a;
         break;
     default:
-        return -1;
+        return;
     }
 
     ehci = pci_new_multifunction(PCI_DEVFN(slot, 7), true, name);
@@ -108,7 +108,6 @@ static int ehci_create_ich9_with_companions(PCIBus *bus, int slot)
         qdev_prop_set_uint32(&uhci->qdev, "firstport", comp[i].port);
         pci_realize_and_unref(uhci, bus, &error_fatal);
     }
-    return 0;
 }
 
 /* PC hardware initialisation */
hw/ide/pci.c +1 -3
index 84ba733548..7d45923113 100644
@@ -381,7 +381,7 @@ static int ide_bmdma_pre_save(void *opaque)
 /* This function accesses bm->bus->error_status which is loaded only after
  * BMDMA itself. This is why the function is called from ide_pci_post_load
  * instead of being registered with VMState where it would run too early. */
-static int ide_bmdma_post_load(void *opaque, int version_id)
+static void ide_bmdma_post_load(void *opaque, int version_id)
 {
     BMDMAState *bm = opaque;
     uint8_t abused_bits = BM_MIGRATION_COMPAT_STATUS_BITS;
@@ -395,8 +395,6 @@ static int ide_bmdma_post_load(void *opaque, int version_id)
         bm->bus->retry_nsector = bm->migration_retry_nsector;
         bm->bus->retry_unit = bm->migration_retry_unit;
     }
-
-    return 0;
 }
 
 static const VMStateDescription vmstate_bmdma_current = {
hw/net/rtl8139.c +1 -2
index 6b65823b4b..e5511ec5ce 100644
@@ -86,9 +86,8 @@
 #  define DPRINTF(fmt, ...) \
     do { fprintf(stderr, "RTL8139: " fmt, ## __VA_ARGS__); } while (0)
 #else
-static inline G_GNUC_PRINTF(1, 2) int DPRINTF(const char *fmt, ...)
+static inline G_GNUC_PRINTF(1, 2) void DPRINTF(const char *fmt, ...)
 {
-    return 0;
 }
 #endif
 
hw/net/virtio-net.c +3 -3
index dd0d056fde..392ac7eb3a 100644
@@ -1218,14 +1218,14 @@ static void virtio_net_detach_epbf_rss(VirtIONet *n)
     virtio_net_attach_ebpf_to_backend(n->nic, -1);
 }
 
-static bool virtio_net_load_ebpf(VirtIONet *n)
+static void virtio_net_load_ebpf(VirtIONet *n)
 {
     if (!virtio_net_attach_ebpf_to_backend(n->nic, -1)) {
         /* backend does't support steering ebpf */
-        return false;
+        return;
     }
 
-    return ebpf_rss_load(&n->ebpf_rss);
+    ebpf_rss_load(&n->ebpf_rss);
 }
 
 static void virtio_net_unload_ebpf(VirtIONet *n)
hw/net/vmxnet3.c +1 -2
index 0b7acf7f89..078cf77ae3 100644
@@ -609,7 +609,7 @@ vmxnet3_pop_next_tx_descr(VMXNET3State *s,
     return false;
 }
 
-static bool
+static void
 vmxnet3_send_packet(VMXNET3State *s, uint32_t qidx)
 {
     Vmxnet3PktStatus status = VMXNET3_PKT_STATUS_OK;
@@ -630,7 +630,6 @@ vmxnet3_send_packet(VMXNET3State *s, uint32_t qidx)
 
 func_exit:
     vmxnet3_on_tx_done_update_stats(s, qidx, status);
-    return (status == VMXNET3_PKT_STATUS_OK);
 }
 
 static void vmxnet3_process_tx_queue(VMXNET3State *s, int qidx)
hw/nvme/ctrl.c +5 -12
index 533ad14e7a..686c580026 100644
@@ -1815,7 +1815,7 @@ static uint16_t nvme_zrm_close(NvmeNamespace *ns, NvmeZone *zone)
     }
 }
 
-static uint16_t nvme_zrm_reset(NvmeNamespace *ns, NvmeZone *zone)
+static void nvme_zrm_reset(NvmeNamespace *ns, NvmeZone *zone)
 {
     switch (nvme_get_zone_state(zone)) {
     case NVME_ZONE_STATE_EXPLICITLY_OPEN:
@@ -1837,11 +1837,8 @@ static uint16_t nvme_zrm_reset(NvmeNamespace *ns, NvmeZone *zone)
         zone->d.wp = zone->w_ptr;
         nvme_assign_zone_state(ns, zone, NVME_ZONE_STATE_EMPTY);
         /* fallthrough */
-    case NVME_ZONE_STATE_EMPTY:
-        return NVME_SUCCESS;
-
     default:
-        return NVME_ZONE_INVAL_TRANSITION;
+        break;
     }
 }
 
@@ -7319,16 +7316,14 @@ static void nvme_init_sriov(NvmeCtrl *n, PCIDevice *pci_dev, uint16_t offset)
                               PCI_BASE_ADDRESS_MEM_TYPE_64, bar_size);
 }
 
-static int nvme_add_pm_capability(PCIDevice *pci_dev, uint8_t offset)
+static void nvme_add_pm_capability(PCIDevice *pci_dev, uint8_t offset)
 {
     Error *err = NULL;
-    int ret;
 
-    ret = pci_add_capability(pci_dev, PCI_CAP_ID_PM, offset,
-                             PCI_PM_SIZEOF, &err);
+    pci_add_capability(pci_dev, PCI_CAP_ID_PM, offset, PCI_PM_SIZEOF, &err);
     if (err) {
         error_report_err(err);
-        return ret;
+        return;
     }
 
     pci_set_word(pci_dev->config + offset + PCI_PM_PMC,
@@ -7337,8 +7332,6 @@ static int nvme_add_pm_capability(PCIDevice *pci_dev, uint8_t offset)
                  PCI_PM_CTRL_NO_SOFT_RESET);
     pci_set_word(pci_dev->wmask + offset + PCI_PM_CTRL,
                  PCI_PM_CTRL_STATE_MASK);
-
-    return 0;
 }
 
 static int nvme_init_pci(NvmeCtrl *n, PCIDevice *pci_dev, Error **errp)
hw/nvram/fw_cfg.c +1 -2
index d605f3f45a..fb8e06538b 100644
@@ -265,7 +265,7 @@ static inline uint32_t fw_cfg_max_entry(const FWCfgState *s)
     return FW_CFG_FILE_FIRST + fw_cfg_file_slots(s);
 }
 
-static int fw_cfg_select(FWCfgState *s, uint16_t key)
+static void fw_cfg_select(FWCfgState *s, uint16_t key)
 {
     int arch, ret;
     FWCfgEntry *e;
@@ -286,7 +286,6 @@ static int fw_cfg_select(FWCfgState *s, uint16_t key)
     }
 
     trace_fw_cfg_select(s, key, trace_key_name(key), ret);
-    return ret;
 }
 
 static uint64_t fw_cfg_data_read(void *opaque, hwaddr addr, unsigned size)
hw/scsi/megasas.c +2 -4
index d5dfb412ba..32a0b489b9 100644
@@ -325,7 +325,7 @@ unmap:
 /*
  * passthrough sense and io sense are at the same offset
  */
-static int megasas_build_sense(MegasasCmd *cmd, uint8_t *sense_ptr,
+static void megasas_build_sense(MegasasCmd *cmd, uint8_t *sense_ptr,
     uint8_t sense_len)
 {
     PCIDevice *pcid = PCI_DEVICE(cmd->state);
@@ -346,7 +346,6 @@ static int megasas_build_sense(MegasasCmd *cmd, uint8_t *sense_ptr,
         pci_dma_write(pcid, pa, sense_ptr, sense_len);
         cmd->frame->header.sense_len = sense_len;
     }
-    return sense_len;
 }
 
 static void megasas_write_sense(MegasasCmd *cmd, SCSISense sense)
@@ -376,7 +375,7 @@ static void megasas_copy_sense(MegasasCmd *cmd)
 /*
  * Format an INQUIRY CDB
  */
-static int megasas_setup_inquiry(uint8_t *cdb, int pg, int len)
+static void megasas_setup_inquiry(uint8_t *cdb, int pg, int len)
 {
     memset(cdb, 0, 6);
     cdb[0] = INQUIRY;
@@ -385,7 +384,6 @@ static int megasas_setup_inquiry(uint8_t *cdb, int pg, int len)
         cdb[2] = pg;
     }
     stw_be_p(&cdb[3], len);
-    return len;
 }
 
 /*
hw/scsi/mptconfig.c +2 -5
index 19d01f39fa..195fcdad26 100644
@@ -127,16 +127,13 @@ static size_t vpack(uint8_t **p_data, const char *fmt, va_list ap1)
     return vfill(data, size, fmt, ap1);
 }
 
-static size_t fill(uint8_t *data, size_t size, const char *fmt, ...)
+static void fill(uint8_t *data, size_t size, const char *fmt, ...)
 {
     va_list ap;
-    size_t ret;
 
     va_start(ap, fmt);
-    ret = vfill(data, size, fmt, ap);
+    vfill(data, size, fmt, ap);
     va_end(ap);
-
-    return ret;
 }
 
 /* Functions to build the page header and fill in the length, always used
hw/scsi/mptsas.c +5 -9
index 706cf0df3a..78325ef797 100644
@@ -287,9 +287,9 @@ static int mptsas_scsi_device_find(MPTSASState *s, int bus, int target,
     return 0;
 }
 
-static int mptsas_process_scsi_io_request(MPTSASState *s,
-                                          MPIMsgSCSIIORequest *scsi_io,
-                                          hwaddr addr)
+static void mptsas_process_scsi_io_request(MPTSASState *s,
+                                           MPIMsgSCSIIORequest *scsi_io,
+                                           hwaddr addr)
 {
     MPTSASRequest *req;
     MPIMsgSCSIIOReply reply;
@@ -352,7 +352,7 @@ static int mptsas_process_scsi_io_request(MPTSASState *s,
     if (scsi_req_enqueue(req->sreq)) {
         scsi_req_continue(req->sreq);
     }
-    return 0;
+    return;
 
 overrun:
     trace_mptsas_scsi_overflow(s, scsi_io->MsgContext, req->sreq->cmd.xfer,
@@ -374,8 +374,6 @@ bad:
 
     mptsas_fix_scsi_io_reply_endianness(&reply);
     mptsas_reply(s, (MPIDefaultReply *)&reply);
-
-    return 0;
 }
 
 typedef struct {
@@ -944,7 +942,7 @@ disable:
     s->diagnostic_idx = 0;
 }
 
-static int mptsas_hard_reset(MPTSASState *s)
+static void mptsas_hard_reset(MPTSASState *s)
 {
     mptsas_soft_reset(s);
 
@@ -955,8 +953,6 @@ static int mptsas_hard_reset(MPTSASState *s)
     s->reply_frame_size = 0;
     s->max_devices = MPTSAS_NUM_PORTS;
     s->max_buses = 1;
-
-    return 0;
 }
 
 static void mptsas_interrupt_status_write(MPTSASState *s)
hw/scsi/scsi-bus.c +2 -4
index b2e2bc3c96..c4b89bc48c 100644
@@ -20,7 +20,7 @@
 static char *scsibus_get_dev_path(DeviceState *dev);
 static char *scsibus_get_fw_dev_path(DeviceState *dev);
 static void scsi_req_dequeue(SCSIRequest *req);
-static uint8_t *scsi_target_alloc_buf(SCSIRequest *req, size_t len);
+static void scsi_target_alloc_buf(SCSIRequest *req, size_t len);
 static void scsi_target_free_buf(SCSIRequest *req);
 
 static int next_scsi_bus;
@@ -649,14 +649,12 @@ static uint8_t *scsi_target_get_buf(SCSIRequest *req)
     return r->buf;
 }
 
-static uint8_t *scsi_target_alloc_buf(SCSIRequest *req, size_t len)
+static void scsi_target_alloc_buf(SCSIRequest *req, size_t len)
 {
     SCSITargetReq *r = DO_UPCAST(SCSITargetReq, req, req);
 
     r->buf = g_malloc(len);
     r->buf_len = len;
-
-    return r->buf;
 }
 
 static void scsi_target_free_buf(SCSIRequest *req)
hw/usb/dev-audio.c +6 -7
index 8748c1ba04..610fbbf8c9 100644
@@ -600,15 +600,16 @@ static void streambuf_fini(struct streambuf *buf)
     buf->data = NULL;
 }
 
-static int streambuf_put(struct streambuf *buf, USBPacket *p, uint32_t channels)
+static void streambuf_put(struct streambuf *buf, USBPacket *p,
+                          uint32_t channels)
 {
     int64_t free = buf->size - (buf->prod - buf->cons);
 
     if (free < USBAUDIO_PACKET_SIZE(channels)) {
-        return 0;
+        return;
     }
     if (p->iov.size != USBAUDIO_PACKET_SIZE(channels)) {
-        return 0;
+        return;
     }
 
     /* can happen if prod overflows */
@@ -616,7 +617,6 @@ static int streambuf_put(struct streambuf *buf, USBPacket *p, uint32_t channels)
     usb_packet_copy(p, buf->data + (buf->prod % buf->size),
                     USBAUDIO_PACKET_SIZE(channels));
     buf->prod += USBAUDIO_PACKET_SIZE(channels);
-    return USBAUDIO_PACKET_SIZE(channels);
 }
 
 static uint8_t *streambuf_get(struct streambuf *buf, size_t *len)
@@ -681,7 +681,7 @@ static void output_callback(void *opaque, int avail)
     }
 }
 
-static int usb_audio_set_output_altset(USBAudioState *s, int altset)
+static void usb_audio_set_output_altset(USBAudioState *s, int altset)
 {
     switch (altset) {
     case ALTSET_OFF:
@@ -697,14 +697,13 @@ static int usb_audio_set_output_altset(USBAudioState *s, int altset)
         AUD_set_active_out(s->out.voice, true);
         break;
     default:
-        return -1;
+        return;
     }
 
     if (s->debug) {
         fprintf(stderr, "usb-audio: set interface %d\n", altset);
     }
     s->out.altset = altset;
-    return 0;
 }
 
 /*
hw/usb/hcd-ehci.c +2 -4
index d4da8dcb8d..8e3766e579 100644
@@ -392,7 +392,7 @@ static inline int get_dwords(EHCIState *ehci, uint32_t addr,
 }
 
 /* Put an array of dwords in to main memory */
-static inline int put_dwords(EHCIState *ehci, uint32_t addr,
+static inline void put_dwords(EHCIState *ehci, uint32_t addr,
                              uint32_t *buf, int num)
 {
     int i;
@@ -401,7 +401,7 @@ static inline int put_dwords(EHCIState *ehci, uint32_t addr,
         ehci_raise_irq(ehci, USBSTS_HSE);
         ehci->usbcmd &= ~USBCMD_RUNSTOP;
         trace_usb_ehci_dma_error();
-        return -1;
+        return;
     }
 
     for (i = 0; i < num; i++, buf++, addr += sizeof(*buf)) {
@@ -409,8 +409,6 @@ static inline int put_dwords(EHCIState *ehci, uint32_t addr,
         dma_memory_write(ehci->as, addr, &tmp, sizeof(tmp),
                          MEMTXATTRS_UNSPECIFIED);
     }
-
-    return num;
 }
 
 static int ehci_get_pid(EHCIqtd *qtd)
hw/usb/hcd-ohci.c +1 -3
index 895b29fb86..1eaba710f1 100644
@@ -1226,7 +1226,7 @@ static void ohci_frame_boundary(void *opaque)
 /* Start sending SOF tokens across the USB bus, lists are processed in
  * next frame
  */
-static int ohci_bus_start(OHCIState *ohci)
+static void ohci_bus_start(OHCIState *ohci)
 {
     trace_usb_ohci_start(ohci->name);
 
@@ -1237,8 +1237,6 @@ static int ohci_bus_start(OHCIState *ohci)
 
     ohci->sof_time = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
     ohci_eof_timer(ohci);
-
-    return 1;
 }
 
 /* Stop sending SOF tokens on the bus */
hw/usb/hcd-xhci.c +26 -30

188 lines not on this page · raw message

hw/vfio/common.c +11 -10
index ace9562a9b..3f823bbe42 100644
@@ -1390,8 +1390,8 @@ static int vfio_ram_discard_get_dirty_bitmap(MemoryRegionSection *section,
     return vfio_get_dirty_bitmap(vrdl->container, iova, size, ram_addr);
 }
 
-static int vfio_sync_ram_discard_listener_dirty_bitmap(VFIOContainer *container,
-                                                   MemoryRegionSection *section)
+static void vfio_sync_ram_discard_listener_dirty_bitmap(
+    VFIOContainer *container, MemoryRegionSection *section)
 {
     RamDiscardManager *rdm = memory_region_get_ram_discard_manager(section->mr);
     VFIORamDiscardListener *vrdl = NULL;
@@ -1412,13 +1412,13 @@ static int vfio_sync_ram_discard_listener_dirty_bitmap(VFIOContainer *container,
      * We only want/can synchronize the bitmap for actually mapped parts -
      * which correspond to populated parts. Replay all populated parts.
      */
-    return ram_discard_manager_replay_populated(rdm, section,
-                                              vfio_ram_discard_get_dirty_bitmap,
-                                                &vrdl);
+    ram_discard_manager_replay_populated(rdm, section,
+                                         vfio_ram_discard_get_dirty_bitmap,
+                                         &vrdl);
 }
 
-static int vfio_sync_dirty_bitmap(VFIOContainer *container,
-                                  MemoryRegionSection *section)
+static void vfio_sync_dirty_bitmap(VFIOContainer *container,
+                                   MemoryRegionSection *section)
 {
     ram_addr_t ram_addr;
 
@@ -1447,15 +1447,16 @@ static int vfio_sync_dirty_bitmap(VFIOContainer *container,
                 break;
             }
         }
-        return 0;
+        return;
     } else if (memory_region_has_ram_discard_manager(section->mr)) {
-        return vfio_sync_ram_discard_listener_dirty_bitmap(container, section);
+        vfio_sync_ram_discard_listener_dirty_bitmap(container, section);
+        return;
     }
 
     ram_addr = memory_region_get_ram_addr(section->mr) +
                section->offset_within_region;
 
-    return vfio_get_dirty_bitmap(container,
+    vfio_get_dirty_bitmap(container,
                    REAL_HOST_PAGE_ALIGN(section->offset_within_address_space),
                    int128_get64(section->size), ram_addr);
 }
hw/virtio/vhost-vdpa.c +1 -2
index 3ff9ce3501..9321d5f7c5 100644
@@ -730,7 +730,7 @@ static int vhost_vdpa_get_vq_index(struct vhost_dev *dev, int idx)
     return idx;
 }
 
-static int vhost_vdpa_set_vring_ready(struct vhost_dev *dev)
+static void vhost_vdpa_set_vring_ready(struct vhost_dev *dev)
 {
     int i;
     trace_vhost_vdpa_set_vring_ready(dev);
@@ -741,7 +741,6 @@ static int vhost_vdpa_set_vring_ready(struct vhost_dev *dev)
         };
         vhost_vdpa_call(dev, VHOST_VDPA_SET_VRING_ENABLE, &state);
     }
-    return 0;
 }
 
 static void vhost_vdpa_dump_config(struct vhost_dev *dev, const uint8_t *config,
hw/virtio/vhost.c +5 -6
index 0827d631c0..f305f5988d 100644
@@ -106,17 +106,17 @@ static void vhost_dev_sync_region(struct vhost_dev *dev,
     }
 }
 
-static int vhost_sync_dirty_bitmap(struct vhost_dev *dev,
-                                   MemoryRegionSection *section,
-                                   hwaddr first,
-                                   hwaddr last)
+static void vhost_sync_dirty_bitmap(struct vhost_dev *dev,
+                                    MemoryRegionSection *section,
+                                    hwaddr first,
+                                    hwaddr last)
 {
     int i;
     hwaddr start_addr;
     hwaddr end_addr;
 
     if (!dev->log_enabled || !dev->started) {
-        return 0;
+        return;
     }
     start_addr = section->offset_within_address_space;
     end_addr = range_get_last(start_addr, int128_get64(section->size));
@@ -140,7 +140,6 @@ static int vhost_sync_dirty_bitmap(struct vhost_dev *dev,
         vhost_dev_sync_region(dev, section, start_addr, end_addr, vq->used_phys,
                               range_get_last(vq->used_phys, vq->used_size));
     }
-    return 0;
 }
 
 static void vhost_log_sync(MemoryListener *listener,
hw/virtio/virtio-iommu.c +1 -3
index 62e07ec2e4..03dd3a623e 100644
@@ -98,7 +98,7 @@ unlock:
 }
 
 /* Return whether the device is using IOMMU translation. */
-static bool virtio_iommu_switch_address_space(IOMMUDevice *sdev)
+static void virtio_iommu_switch_address_space(IOMMUDevice *sdev)
 {
     bool use_remapping;
 
@@ -119,8 +119,6 @@ static bool virtio_iommu_switch_address_space(IOMMUDevice *sdev)
         memory_region_set_enabled(MEMORY_REGION(&sdev->iommu_mr), false);
         memory_region_set_enabled(&sdev->bypass_mr, true);
     }
-
-    return use_remapping;
 }
 
 static void virtio_iommu_switch_address_space_all(VirtIOIOMMU *s)
hw/virtio/virtio-mem.c +4 -5
index 30d03e987a..413212cafe 100644
@@ -258,10 +258,10 @@ static int virtio_mem_for_each_plugged_section(const VirtIOMEM *vmem,
     return ret;
 }
 
-static int virtio_mem_for_each_unplugged_section(const VirtIOMEM *vmem,
-                                                 MemoryRegionSection *s,
-                                                 void *arg,
-                                                 virtio_mem_section_cb cb)
+static void virtio_mem_for_each_unplugged_section(const VirtIOMEM *vmem,
+                                                  MemoryRegionSection *s,
+                                                  void *arg,
+                                                  virtio_mem_section_cb cb)
 {
     unsigned long first_bit, last_bit;
     uint64_t offset, size;
@@ -287,7 +287,6 @@ static int virtio_mem_for_each_unplugged_section(const VirtIOMEM *vmem,
         first_bit = find_next_zero_bit(vmem->bitmap, vmem->bitmap_size,
                                        last_bit + 2);
     }
-    return ret;
 }
 
 static int virtio_mem_notify_populate_cb(MemoryRegionSection *s, void *arg)
io/channel-command.c +4 -6
index 9f2f4a1793..59f3c144f6 100644
@@ -172,8 +172,8 @@ qio_channel_command_new_spawn(const char *const argv[],
 #endif /* WIN32 */
 
 #ifndef WIN32
-static int qio_channel_command_abort(QIOChannelCommand *ioc,
-                                     Error **errp)
+static void qio_channel_command_abort(QIOChannelCommand *ioc,
+                                      Error **errp)
 {
     pid_t ret;
     int status;
@@ -193,7 +193,7 @@ static int qio_channel_command_abort(QIOChannelCommand *ioc,
             error_setg_errno(errp, errno,
                              "Cannot wait on pid %llu",
                              (unsigned long long)ioc->pid);
-            return -1;
+            return;
         }
     } else if (ret == 0) {
         if (step == 0) {
@@ -204,14 +204,12 @@ static int qio_channel_command_abort(QIOChannelCommand *ioc,
             error_setg(errp,
                        "Process %llu refused to die",
                        (unsigned long long)ioc->pid);
-            return -1;
+            return;
         }
         step++;
         usleep(10 * 1000);
         goto rewait;
     }
-
-    return 0;
 }
 #endif /* ! WIN32 */
 
migration/migration.c +5 -7
index e03f698a3c..4698080f96 100644
@@ -175,7 +175,7 @@ static MigrationIncomingState *current_incoming;
 
 static GSList *migration_blockers;
 
-static bool migration_object_check(MigrationState *ms, Error **errp);
+static void migration_object_check(MigrationState *ms, Error **errp);
 static int migration_maybe_pause(MigrationState *s,
                                  int *current_active_state,
                                  int new_state);
@@ -4485,15 +4485,15 @@ static void migration_instance_init(Object *obj)
  * Return true if check pass, false otherwise. Error will be put
  * inside errp if provided.
  */
-static bool migration_object_check(MigrationState *ms, Error **errp)
+static void migration_object_check(MigrationState *ms, Error **errp)
 {
     MigrationCapabilityStatusList *head = NULL;
     /* Assuming all off */
-    bool cap_list[MIGRATION_CAPABILITY__MAX] = { 0 }, ret;
+    bool cap_list[MIGRATION_CAPABILITY__MAX] = { 0 };
     int i;
 
     if (!migrate_params_check(&ms->parameters, errp)) {
-        return false;
+        return;
     }
 
     for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
@@ -4502,12 +4502,10 @@ static bool migration_object_check(MigrationState *ms, Error **errp)
         }
     }
 
-    ret = migrate_caps_check(cap_list, head, errp);
+    migrate_caps_check(cap_list, head, errp);
 
     /* It works with head == NULL */
     qapi_free_MigrationCapabilityStatusList(head);
-
-    return ret;
 }
 
 static const TypeInfo migration_type = {
net/dump.c +6 -10
index 6a63b15359..6fde1501a9 100644
@@ -61,7 +61,7 @@ struct pcap_sf_pkthdr {
     uint32_t len;
 };
 
-static ssize_t dump_receive_iov(DumpState *s, const struct iovec *iov, int cnt)
+static void dump_receive_iov(DumpState *s, const struct iovec *iov, int cnt)
 {
     struct pcap_sf_pkthdr hdr;
     int64_t ts;
@@ -71,7 +71,7 @@ static ssize_t dump_receive_iov(DumpState *s, const struct iovec *iov, int cnt)
 
     /* Early return in case of previous error. */
     if (s->fd < 0) {
-        return size;
+        return;
     }
 
     ts = qemu_clock_get_us(QEMU_CLOCK_VIRTUAL);
@@ -91,8 +91,6 @@ static ssize_t dump_receive_iov(DumpState *s, const struct iovec *iov, int cnt)
         close(s->fd);
         s->fd = -1;
     }
-
-    return size;
 }
 
 static void dump_cleanup(DumpState *s)
@@ -101,8 +99,8 @@ static void dump_cleanup(DumpState *s)
     s->fd = -1;
 }
 
-static int net_dump_state_init(DumpState *s, const char *filename,
-                               int len, Error **errp)
+static void net_dump_state_init(DumpState *s, const char *filename,
+                                int len, Error **errp)
 {
     struct pcap_file_hdr hdr;
     struct tm tm;
@@ -111,7 +109,7 @@ static int net_dump_state_init(DumpState *s, const char *filename,
     fd = open(filename, O_CREAT | O_TRUNC | O_WRONLY | O_BINARY, 0644);
     if (fd < 0) {
         error_setg_errno(errp, errno, "net dump: can't open %s", filename);
-        return -1;
+        return;
     }
 
     hdr.magic = PCAP_MAGIC;
@@ -125,7 +123,7 @@ static int net_dump_state_init(DumpState *s, const char *filename,
     if (write(fd, &hdr, sizeof(hdr)) < sizeof(hdr)) {
         error_setg_errno(errp, errno, "net dump write error");
         close(fd);
-        return -1;
+        return;
     }
 
     s->fd = fd;
@@ -133,8 +131,6 @@ static int net_dump_state_init(DumpState *s, const char *filename,
 
     qemu_get_timedate(&tm, 0);
     s->start_ts = mktime(&tm);
-
-    return 0;
 }
 
 #define TYPE_FILTER_DUMP "filter-dump"
net/vhost-vdpa.c +3 -5
index 6abad276a6..11e4f64a31 100644
@@ -506,12 +506,10 @@ static NetClientState *net_vhost_vdpa_init(NetClientState *peer,
     return nc;
 }
 
-static int vhost_vdpa_get_iova_range(int fd,
-                                     struct vhost_vdpa_iova_range *iova_range)
+static void vhost_vdpa_get_iova_range(int fd,
+                                      struct vhost_vdpa_iova_range *iova_range)
 {
-    int ret = ioctl(fd, VHOST_VDPA_GET_IOVA_RANGE, iova_range);
-
-    return ret < 0 ? -errno : 0;
+    ioctl(fd, VHOST_VDPA_GET_IOVA_RANGE, iova_range);
 }
 
 static int vhost_vdpa_get_features(int fd, uint64_t *features, Error **errp)
qemu-img.c +2 -4
index 7d4b33b3da..d90ad1d298 100644
@@ -289,16 +289,14 @@ static QemuOptsList qemu_source_opts = {
     },
 };
 
-static int G_GNUC_PRINTF(2, 3) qprintf(bool quiet, const char *fmt, ...)
+static void G_GNUC_PRINTF(2, 3) qprintf(bool quiet, const char *fmt, ...)
 {
-    int ret = 0;
     if (!quiet) {
         va_list args;
         va_start(args, fmt);
-        ret = vprintf(fmt, args);
+        vprintf(fmt, args);
         va_end(args);
     }
-    return ret;
 }
 
 
qga/commands-posix-ssh.c +4 -6
index f3a580b8cc..ddabc33502 100644
@@ -111,7 +111,7 @@ check_openssh_pub_keys(strList *keys, size_t *nkeys, Error **errp)
     return true;
 }
 
-static bool
+static void
 write_authkeys(const char *path, const GStrv keys,
                const struct passwd *p, Error **errp)
 {
@@ -121,22 +121,20 @@ write_authkeys(const char *path, const GStrv keys,
     contents = g_strjoinv("\n", keys);
     if (!g_file_set_contents(path, contents, -1, &err)) {
         error_setg(errp, "failed to write to '%s': %s", path, err->message);
-        return false;
+        return;
     }
 
     if (chown(path, p->pw_uid, p->pw_gid) == -1) {
         error_setg(errp, "failed to set ownership of directory '%s': %s",
                    path, g_strerror(errno));
-        return false;
+        return;
     }
 
     if (chmod(path, 0600) == -1) {
         error_setg(errp, "failed to set permissions of '%s': %s",
                    path, g_strerror(errno));
-        return false;
+        return;
     }
-
-    return true;
 }
 
 static GStrv
softmmu/physmem.c +8 -10
index dc3c3e5f2e..ef7d724a77 100644
@@ -1158,8 +1158,8 @@ hwaddr memory_region_section_get_iotlb(CPUState *cpu,
     return section - d->map.sections;
 }
 
-static int subpage_register(subpage_t *mmio, uint32_t start, uint32_t end,
-                            uint16_t section);
+static void subpage_register(subpage_t *mmio, uint32_t start, uint32_t end,
+                             uint16_t section);
 static subpage_t *subpage_init(FlatView *fv, hwaddr base);
 
 static uint16_t phys_section_add(PhysPageMap *map,
@@ -1823,14 +1823,14 @@ size_t qemu_ram_pagesize_largest(void)
     return largest;
 }
 
-static int memory_try_enable_merging(void *addr, size_t len)
+static void memory_try_enable_merging(void *addr, size_t len)
 {
     if (!machine_mem_merge(current_machine)) {
         /* disabled by the user */
-        return 0;
+        return;
     }
 
-    return qemu_madvise(addr, len, QEMU_MADV_MERGEABLE);
+    qemu_madvise(addr, len, QEMU_MADV_MERGEABLE);
 }
 
 /*
@@ -2526,13 +2526,13 @@ static const MemoryRegionOps subpage_ops = {
     .endianness = DEVICE_NATIVE_ENDIAN,
 };
 
-static int subpage_register(subpage_t *mmio, uint32_t start, uint32_t end,
-                            uint16_t section)
+static void subpage_register(subpage_t *mmio, uint32_t start, uint32_t end,
+                             uint16_t section)
 {
     int idx, eidx;
 
     if (start >= TARGET_PAGE_SIZE || end >= TARGET_PAGE_SIZE)
-        return -1;
+        return;
     idx = SUBPAGE_IDX(start);
     eidx = SUBPAGE_IDX(end);
 #if defined(DEBUG_SUBPAGE)
@@ -2542,8 +2542,6 @@ static int subpage_register(subpage_t *mmio, uint32_t start, uint32_t end,
     for (; idx <= eidx; idx++) {
         mmio->sub_section[idx] = section;
     }
-
-    return 0;
 }
 
 static subpage_t *subpage_init(FlatView *fv, hwaddr base)
softmmu/qtest.c +2 -3
index f8acef2628..d0c1c72292 100644
@@ -875,7 +875,7 @@ void qtest_server_init(const char *qtest_chrdev, const char *qtest_log, Error **
     object_unref(qtest);
 }
 
-static bool qtest_server_start(QTest *q, Error **errp)
+static void qtest_server_start(QTest *q, Error **errp)
 {
     Chardev *chr = q->chr;
     const char *qtest_log = q->log;
@@ -889,7 +889,7 @@ static bool qtest_server_start(QTest *q, Error **errp)
     }
 
     if (!qemu_chr_fe_init(&q->qtest_chr, chr, errp)) {
-        return false;
+        return;
     }
     qemu_chr_fe_set_handlers(&q->qtest_chr, qtest_can_read, qtest_read,
                              qtest_event, NULL, &q->qtest_chr, NULL, true);
@@ -901,7 +901,6 @@ static bool qtest_server_start(QTest *q, Error **errp)
         qtest_server_set_send_handler(qtest_server_char_be_send, &q->qtest_chr);
     }
     qtest = q;
-    return true;
 }
 
 void qtest_server_set_send_handler(void (*send)(void*, const char*),
subprojects/libvduse/libvduse.c +3 -9
index 9a2bcec282..a61552758c 100644
@@ -278,33 +278,27 @@ static int vduse_queue_check_inflights(VduseVirtq *vq)
     return 0;
 }
 
-static int vduse_queue_inflight_get(VduseVirtq *vq, int desc_idx)
+static void vduse_queue_inflight_get(VduseVirtq *vq, int desc_idx)
 {
     vq->log->inflight.desc[desc_idx].counter = vq->counter++;
 
     barrier();
 
     vq->log->inflight.desc[desc_idx].inflight = 1;
-
-    return 0;
 }
 
-static int vduse_queue_inflight_pre_put(VduseVirtq *vq, int desc_idx)
+static void vduse_queue_inflight_pre_put(VduseVirtq *vq, int desc_idx)
 {
     vq->log->inflight.last_batch_head = desc_idx;
-
-    return 0;
 }
 
-static int vduse_queue_inflight_post_put(VduseVirtq *vq, int desc_idx)
+static void vduse_queue_inflight_post_put(VduseVirtq *vq, int desc_idx)
 {
     vq->log->inflight.desc[desc_idx].inflight = 0;
 
     barrier();
 
     vq->log->inflight.used_idx = vq->used_idx;
-
-    return 0;
 }
 
 static void vduse_iova_remove_region(VduseDev *dev, uint64_t start,
subprojects/libvhost-user/libvhost-user.c +9 -15
index ffed4729a3..f3cea908b5 100644
@@ -2632,48 +2632,44 @@ vu_queue_map_desc(VuDev *dev, VuVirtq *vq, unsigned int idx, size_t sz)
     return elem;
 }
 
-static int
+static void
 vu_queue_inflight_get(VuDev *dev, VuVirtq *vq, int desc_idx)
 {
     if (!vu_has_protocol_feature(dev, VHOST_USER_PROTOCOL_F_INFLIGHT_SHMFD)) {
-        return 0;
+        return;
     }
 
     if (unlikely(!vq->inflight)) {
-        return -1;
+        return;
     }
 
     vq->inflight->desc[desc_idx].counter = vq->counter++;
     vq->inflight->desc[desc_idx].inflight = 1;
-
-    return 0;
 }
 
-static int
+static void
 vu_queue_inflight_pre_put(VuDev *dev, VuVirtq *vq, int desc_idx)
 {
     if (!vu_has_protocol_feature(dev, VHOST_USER_PROTOCOL_F_INFLIGHT_SHMFD)) {
-        return 0;
+        return;
     }
 
     if (unlikely(!vq->inflight)) {
-        return -1;
+        return;
     }
 
     vq->inflight->last_batch_head = desc_idx;
-
-    return 0;
 }
 
-static int
+static void
 vu_queue_inflight_post_put(VuDev *dev, VuVirtq *vq, int desc_idx)
 {
     if (!vu_has_protocol_feature(dev, VHOST_USER_PROTOCOL_F_INFLIGHT_SHMFD)) {
-        return 0;
+        return;
     }
 
     if (unlikely(!vq->inflight)) {
-        return -1;
+        return;
     }
 
     barrier();
@@ -2683,8 +2679,6 @@ vu_queue_inflight_post_put(VuDev *dev, VuVirtq *vq, int desc_idx)
     barrier();
 
     vq->inflight->used_idx = vq->used_idx;
-
-    return 0;
 }
 
 void *
target/i386/host-cpu.c +1 -2
index 10f8aba86e..4866a24858 100644
@@ -114,7 +114,7 @@ bool host_cpu_realizefn(CPUState *cs, Error **errp)
  * The function does NOT add a null terminator to the string
  * automatically.
  */
-static int host_cpu_fill_model_id(char *str)
+static void host_cpu_fill_model_id(char *str)
 {
     uint32_t eax = 0, ebx = 0, ecx = 0, edx = 0;
     int i;
@@ -126,7 +126,6 @@ static int host_cpu_fill_model_id(char *str)
         memcpy(str + i * 16 +  8, &ecx, 4);
         memcpy(str + i * 16 + 12, &edx, 4);
     }
-    return 0;
 }
 
 void host_cpu_vendor_fms(char *vendor, int *family, int *model, int *stepping)
target/i386/kvm/kvm.c +8 -11
index f148a6d52f..a2504f1a8b 100644
@@ -208,7 +208,7 @@ bool kvm_hv_vpindex_settable(void)
     return hv_vpindex_settable;
 }
 
-static int kvm_get_tsc(CPUState *cs)
+static void kvm_get_tsc(CPUState *cs)
 {
     X86CPU *cpu = X86_CPU(cs);
     CPUX86State *env = &cpu->env;
@@ -216,18 +216,17 @@ static int kvm_get_tsc(CPUState *cs)
     int ret;
 
     if (env->tsc_valid) {
-        return 0;
+        return;
     }
 
     env->tsc_valid = !runstate_is_running();
 
     ret = kvm_get_one_msr(cpu, MSR_IA32_TSC, &value);
     if (ret < 0) {
-        return ret;
+        return;
     }
 
     env->tsc = value;
-    return 0;
 }
 
 static inline void do_kvm_synchronize_tsc(CPUState *cpu, run_on_cpu_data arg)
@@ -2212,16 +2211,16 @@ void kvm_arch_do_init_vcpu(X86CPU *cpu)
     }
 }
 
-static int kvm_get_supported_feature_msrs(KVMState *s)
+static void kvm_get_supported_feature_msrs(KVMState *s)
 {
     int ret = 0;
 
     if (kvm_feature_msrs != NULL) {
-        return 0;
+        return;
     }
 
     if (!kvm_check_extension(s, KVM_CAP_GET_MSR_FEATURES)) {
-        return 0;
+        return;
     }
 
     struct kvm_msr_list msr_list;
@@ -2231,7 +2230,7 @@ static int kvm_get_supported_feature_msrs(KVMState *s)
     if (ret < 0 && ret != -E2BIG) {
         error_report("Fetch KVM feature MSR list failed: %s",
             strerror(-ret));
-        return ret;
+        return;
     }
 
     assert(msr_list.nmsrs > 0);
@@ -2247,10 +2246,8 @@ static int kvm_get_supported_feature_msrs(KVMState *s)
             strerror(-ret));
         g_free(kvm_feature_msrs);
         kvm_feature_msrs = NULL;
-        return ret;
+        return;
     }
-
-    return 0;
 }
 
 static int kvm_get_supported_msrs(KVMState *s)
tcg/optimize.c +1 -2
index ae081ab29c..b04b2b79a6 100644
@@ -1200,7 +1200,7 @@ static bool fold_bswap(OptContext *ctx, TCGOp *op)
     return fold_masks(ctx, op);
 }
 
-static bool fold_call(OptContext *ctx, TCGOp *op)
+static void fold_call(OptContext *ctx, TCGOp *op)
 {
     TCGContext *s = ctx->tcg;
     int nb_oargs = TCGOP_CALLO(op);
@@ -1229,7 +1229,6 @@ static bool fold_call(OptContext *ctx, TCGOp *op)
 
     /* Stop optimizing MB across calls. */
     ctx->prev_mb = NULL;
-    return true;
 }
 
 static bool fold_count_zeros(OptContext *ctx, TCGOp *op)
tests/qtest/libqos/malloc.c +2 -3
index f0c8f950c8..816e8dfa9c 100644
@@ -52,7 +52,7 @@ static MemBlock *mlist_find_space(MemList *head, uint64_t size)
     return NULL;
 }
 
-static MemBlock *mlist_sort_insert(MemList *head, MemBlock *insr)
+static void mlist_sort_insert(MemList *head, MemBlock *insr)
 {
     MemBlock *node;
     g_assert(head && insr);
@@ -60,12 +60,11 @@ static MemBlock *mlist_sort_insert(MemList *head, MemBlock *insr)
     QTAILQ_FOREACH(node, head, MLIST_ENTNAME) {
         if (insr->addr < node->addr) {
             QTAILQ_INSERT_BEFORE(node, insr, MLIST_ENTNAME);
-            return insr;
+            return;
         }
     }
 
     QTAILQ_INSERT_TAIL(head, insr, MLIST_ENTNAME);
-    return insr;
 }
 
 static inline uint64_t mlist_boundary(MemBlock *node)
tests/qtest/libqos/qgraph.c +1 -2
index 0a2dddfafa..a270ffea00 100644
@@ -349,7 +349,7 @@ static QOSStackElement *qos_tos(void)
 }
 
 /* qos_pop(): pops an element from the tos, setting it unvisited*/
-static QOSStackElement *qos_pop(void)
+static void qos_pop(void)
 {
     if (qos_node_tos == 0) {
         g_printerr("QOSStack: empty stack, cannot pop");
@@ -358,7 +358,6 @@ static QOSStackElement *qos_pop(void)
     QOSStackElement *e = qos_tos();
     e->node->visited = false;
     qos_node_tos--;
-    return e;
 }
 
 /**
tests/qtest/test-x86-cpuid-compat.c +3 -5
index b39c9055b3..cde4416a31 100644
@@ -149,10 +149,9 @@ static void test_feature_flag(const void *data)
  * either "feature-words" or "filtered-features", when running QEMU
  * using cmdline
  */
-static FeatureTestArgs *add_feature_test(const char *name, const char *cmdline,
-                                         uint32_t eax, uint32_t ecx,
-                                         const char *reg, int bitnr,
-                                         bool expected_value)
+static void add_feature_test(const char *name, const char *cmdline,
+                             uint32_t eax, uint32_t ecx, const char *reg,
+                             int bitnr, bool expected_value)
 {
     FeatureTestArgs *args = g_new0(FeatureTestArgs, 1);
     args->cmdline = cmdline;
@@ -162,7 +161,6 @@ static FeatureTestArgs *add_feature_test(const char *name, const char *cmdline,
     args->bitnr = bitnr;
     args->expected_value = expected_value;
     qtest_add_data_func(name, args, test_feature_flag);
-    return args;
 }
 
 static void test_plus_minus_subprocess(void)
tests/qtest/virtio-9p-test.c +2 -4
index 25305a4cf7..0762d3664c 100644
@@ -1319,8 +1319,8 @@ static void do_mkdir(QVirtio9P *v9p, const char *path, const char *cname)
 }
 
 /* create a regular file with Tlcreate and return file's fid */
-static uint32_t do_lcreate(QVirtio9P *v9p, const char *path,
-                           const char *cname)
+static void do_lcreate(QVirtio9P *v9p, const char *path,
+                       const char *cname)
 {
     g_autofree char *name = g_strdup(cname);
     uint32_t fid;
@@ -1331,8 +1331,6 @@ static uint32_t do_lcreate(QVirtio9P *v9p, const char *path,
     req = v9fs_tlcreate(v9p, fid, name, 0, 0750, 0, 0);
     v9fs_req_wait_for_reply(req, NULL);
     v9fs_rlcreate(req, NULL, NULL);
-
-    return fid;
 }
 
 /* create symlink named @a clink in directory @a path pointing to @a to */
tests/unit/test-aio-multithread.c +2 -3
index a555cc8835..02a778f5ea 100644
@@ -114,14 +114,14 @@ static int count_retry;
 static int count_here;
 static int count_other;
 
-static bool schedule_next(int n)
+static void schedule_next(int n)
 {
     Coroutine *co;
 
     co = qatomic_xchg(&to_schedule[n], NULL);
     if (!co) {
         qatomic_inc(&count_retry);
-        return false;
+        return;
     }
 
     if (n == id) {
@@ -131,7 +131,6 @@ static bool schedule_next(int n)
     }
 
     aio_co_schedule(ctx[n], co);
-    return true;
 }
 
 static void finish_cb(void *opaque)
tests/vhost-user-bridge.c +7 -12
index 9b1dab2f28..89784f2791 100644
@@ -85,22 +85,21 @@ vubr_die(const char *s)
     exit(1);
 }
 
-static int
+static void
 dispatcher_init(Dispatcher *dispr)
 {
     FD_ZERO(&dispr->fdset);
     dispr->max_sock = -1;
-    return 0;
 }
 
-static int
+static void
 dispatcher_add(Dispatcher *dispr, int sock, void *ctx, CallbackFunc cb)
 {
     if (sock >= FD_SETSIZE) {
         fprintf(stderr,
                 "Error: Failed to add new event. sock %d should be less than %d\n",
                 sock, FD_SETSIZE);
-        return -1;
+        return;
     }
 
     dispr->events[sock].ctx = ctx;
@@ -112,26 +111,24 @@ dispatcher_add(Dispatcher *dispr, int sock, void *ctx, CallbackFunc cb)
     }
     DPRINT("Added sock %d for watching. max_sock: %d\n",
            sock, dispr->max_sock);
-    return 0;
 }
 
-static int
+static void
 dispatcher_remove(Dispatcher *dispr, int sock)
 {
     if (sock >= FD_SETSIZE) {
         fprintf(stderr,
                 "Error: Failed to remove event. sock %d should be less than %d\n",
                 sock, FD_SETSIZE);
-        return -1;
+        return;
     }
 
     FD_CLR(sock, &dispr->fdset);
     DPRINT("Sock %d removed from dispatcher watch.\n", sock);
-    return 0;
 }
 
 /* timeout in us */
-static int
+static void
 dispatcher_wait(Dispatcher *dispr, uint32_t timeout)
 {
     struct timeval tv;
@@ -149,7 +146,7 @@ dispatcher_wait(Dispatcher *dispr, uint32_t timeout)
 
     /* Timeout */
     if (rc == 0) {
-        return 0;
+        return;
     }
 
     /* Now call callback for every ready socket. */
@@ -165,8 +162,6 @@ dispatcher_wait(Dispatcher *dispr, uint32_t timeout)
             e->callback(sock, e->ctx);
         }
     }
-
-    return 0;
 }
 
 static void
ui/vnc.c +8 -15
index 6a05d06147..03c9d10423 100644
@@ -68,7 +68,7 @@ static const struct timeval VNC_REFRESH_LOSSY = { 2, 0 };
 static QTAILQ_HEAD(, VncDisplay) vnc_displays =
     QTAILQ_HEAD_INITIALIZER(vnc_displays);
 
-static int vnc_cursor_define(VncState *vs);
+static void vnc_cursor_define(VncState *vs);
 static void vnc_update_throttle_offset(VncState *vs);
 
 static void vnc_set_share_mode(VncState *vs, VncShareMode mode)
@@ -996,13 +996,13 @@ static void vnc_mouse_set(DisplayChangeListener *dcl,
     /* can we ask the client(s) to move the pointer ??? */
 }
 
-static int vnc_cursor_define(VncState *vs)
+static void vnc_cursor_define(VncState *vs)
 {
     QEMUCursor *c = vs->vd->cursor;
     int isize;
 
     if (!vs->vd->cursor) {
-        return -1;
+        return;
     }
 
     if (vnc_has_feature(vs, VNC_FEATURE_ALPHA_CURSOR)) {
@@ -1015,9 +1015,7 @@ static int vnc_cursor_define(VncState *vs)
         vnc_write_s32(vs, VNC_ENCODING_RAW);
         vnc_write(vs, c->data, c->width * c->height * 4);
         vnc_unlock_output(vs);
-        return 0;
-    }
-    if (vnc_has_feature(vs, VNC_FEATURE_RICH_CURSOR)) {
+    } else if (vnc_has_feature(vs, VNC_FEATURE_RICH_CURSOR)) {
         vnc_lock_output(vs);
         vnc_write_u8(vs,  VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
         vnc_write_u8(vs,  0);  /*  padding     */
@@ -1028,9 +1026,7 @@ static int vnc_cursor_define(VncState *vs)
         vnc_write_pixels_generic(vs, c->data, isize);
         vnc_write(vs, vs->vd->cursor_mask, vs->vd->cursor_msize);
         vnc_unlock_output(vs);
-        return 0;
     }
-    return -1;
 }
 
 static void vnc_dpy_cursor_define(DisplayChangeListener *dcl,
@@ -1438,11 +1434,10 @@ size_t vnc_client_write_buf(VncState *vs, const uint8_t *data, size_t datalen)
  * as possible without blocking. If all buffered data is written,
  * will switch the FD poll() handler back to read monitoring.
  *
- * Returns the number of bytes written, which may be less than
- * the buffered output data if the socket would block.  Returns
- * 0 on I/O error, and disconnects the client socket.
+ * May write less than the buffered output data if the socket would
+ * block. On I/O error, disconnects the client socket.
  */
-static size_t vnc_client_write_plain(VncState *vs)
+static void vnc_client_write_plain(VncState *vs)
 {
     size_t offset;
     size_t ret;
@@ -1462,7 +1457,7 @@ static size_t vnc_client_write_plain(VncState *vs)
 #endif /* CONFIG_VNC_SASL */
         ret = vnc_client_write_buf(vs, vs->output.buffer, vs->output.offset);
     if (!ret)
-        return 0;
+        return;
 
     if (ret >= vs->force_update_offset) {
         if (vs->force_update_offset != 0) {
@@ -1487,8 +1482,6 @@ static size_t vnc_client_write_plain(VncState *vs)
             vs->ioc, G_IO_IN | G_IO_HUP | G_IO_ERR,
             vnc_client_io, vs, NULL);
     }
-
-    return ret;
 }
 
 
util/aio-posix.c +2 -5
index 731f3826c0..bedaf2efae 100644
@@ -403,16 +403,13 @@ static bool aio_dispatch_ready_handlers(AioContext *ctx,
 }
 
 /* Slower than aio_dispatch_ready_handlers() but only used via glib */
-static bool aio_dispatch_handlers(AioContext *ctx)
+static void aio_dispatch_handlers(AioContext *ctx)
 {
     AioHandler *node, *tmp;
-    bool progress = false;
 
     QLIST_FOREACH_SAFE_RCU(node, &ctx->aio_handlers, node, tmp) {
-        progress = aio_dispatch_handler(ctx, node) || progress;
+        aio_dispatch_handler(ctx, node);
     }
-
-    return progress;
 }
 
 void aio_dispatch(AioContext *ctx)
util/uri.c +6 -12
index ff72c6005f..7078cff857 100644
@@ -1364,15 +1364,13 @@ void uri_free(URI *uri)
  * Section 5.2, steps 6.c through 6.g.
  *
  * Normalization occurs directly on the string, no new allocation is done
- *
- * Returns 0 or an error code
  */
-static int normalize_uri_path(char *path)
+static void normalize_uri_path(char *path)
 {
     char *cur, *out;
 
     if (path == NULL) {
-        return -1;
+        return;
     }
 
     /* Skip all initial "/" chars.  We want to get to the beginning of the
@@ -1383,7 +1381,7 @@ static int normalize_uri_path(char *path)
         ++cur;
     }
     if (cur[0] == '\0') {
-        return 0;
+        return;
     }
 
     /* Keep everything we've seen so far.  */
@@ -1437,7 +1435,7 @@ done_cd:
         ++cur;
     }
     if (cur[0] == '\0') {
-        return 0;
+        return;
     }
 
     /*
@@ -1558,8 +1556,6 @@ done_cd:
             out[0] = 0;
         }
     }
-
-    return 0;
 }
 
 static int is_hex(char c)
@@ -2213,8 +2209,8 @@ struct QueryParams *query_params_new(int init_alloc)
 /* Ensure there is space to store at least one more parameter
  * at the end of the set.
  */
-static int query_params_append(struct QueryParams *ps, const char *name,
-                               const char *value)
+static void query_params_append(struct QueryParams *ps, const char *name,
+                                const char *value)
 {
     if (ps->n >= ps->alloc) {
         ps->p = g_renew(QueryParam, ps->p, ps->alloc * 2);
@@ -2225,8 +2221,6 @@ static int query_params_append(struct QueryParams *ps, const char *name,
     ps->p[ps->n].value = g_strdup(value);
     ps->p[ps->n].ignore = 0;
     ps->n++;
-
-    return 0;
 }
 
 void query_params_free(struct QueryParams *ps)
Signature · 1 line
2.37.1
#3 lore raw

Re: [RFC v2 02/10] Drop unused static function return values

Quoted 8 lines · * Alberto Faria ([email protected]) wrote:

Make non-void static functions whose return values are ignored by all callers return void instead.

These functions were found by static-analyzer.py.

Not all occurrences of this problem were fixed.

<snip>

Quoted 14 lines
migration/migration.c +1 -1
index e03f698a3c..4698080f96 100644
@@ -175,7 +175,7 @@ static MigrationIncomingState *current_incoming;
 
 static GSList *migration_blockers;
 
-static bool migration_object_check(MigrationState *ms, Error **errp);
+static void migration_object_check(MigrationState *ms, Error **errp);
 static int migration_maybe_pause(MigrationState *s,
                                  int *current_active_state,
                                  int new_state);

migration/migration.c static void migration_instance_init(Object *obj) · line 4489

Quoted 6 lines
migration/migration.c +1 -1
@@ -4485,15 +4485,15 @@ static void migration_instance_init(Object *obj)
  * Return true if check pass, false otherwise. Error will be put
  * inside errp if provided.
  */
-static bool migration_object_check(MigrationState *ms, Error **errp)
+static void migration_object_check(MigrationState *ms, Error **errp)
 {

I'm not sure if this is a good change.
Where we have a function that returns an error via an Error ** it's normal practice for us to return a bool to say whether it generated an error.

Now, in our case we only call it with error_fatal:

    migration_object_check(current_migration, &error_fatal);

so the bool isn't used/checked.

So I'm a bit conflicted:

a) Using error_fatal is the easiest way to handle this function
b) Things taking Error ** normally do return a flag value
c) But it's not used in this case.

Hmm.

Dave

Quoted 24 lines
migration/migration.c +3 -5
     MigrationCapabilityStatusList *head = NULL;
     /* Assuming all off */
-    bool cap_list[MIGRATION_CAPABILITY__MAX] = { 0 }, ret;
+    bool cap_list[MIGRATION_CAPABILITY__MAX] = { 0 };
     int i;
 
     if (!migrate_params_check(&ms->parameters, errp)) {
-        return false;
+        return;
     }
 
     for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
@@ -4502,12 +4502,10 @@ static bool migration_object_check(MigrationState *ms, Error **errp)
         }
     }
 
-    ret = migrate_caps_check(cap_list, head, errp);
+    migrate_caps_check(cap_list, head, errp);
 
     /* It works with head == NULL */
     qapi_free_MigrationCapabilityStatusList(head);
-
-    return ret;
 }
Signature · 1 line
Dr. David Alan Gilbert / [email protected] / Manchester, UK
#4 lore raw

Re: [RFC v2 02/10] Drop unused static function return values

Quoted 45 lines · Dr. David Alan Gilbert
Quoted 8 lines · * Alberto Faria ([email protected]) wrote:

Make non-void static functions whose return values are ignored by all callers return void instead.

These functions were found by static-analyzer.py.

Not all occurrences of this problem were fixed.

<snip>

Quoted 14 lines
migration/migration.c +1 -1
index e03f698a3c..4698080f96 100644
@@ -175,7 +175,7 @@ static MigrationIncomingState *current_incoming;
 
 static GSList *migration_blockers;
 
-static bool migration_object_check(MigrationState *ms, Error **errp);
+static void migration_object_check(MigrationState *ms, Error **errp);
 static int migration_maybe_pause(MigrationState *s,
                                  int *current_active_state,
                                  int new_state);

migration/migration.c static void migration_instance_init(Object *obj) · line 4489

Quoted 6 lines
migration/migration.c +1 -1
@@ -4485,15 +4485,15 @@ static void migration_instance_init(Object *obj)
  * Return true if check pass, false otherwise. Error will be put
  * inside errp if provided.
  */
-static bool migration_object_check(MigrationState *ms, Error **errp)
+static void migration_object_check(MigrationState *ms, Error **errp)
 {

I'm not sure if this is a good change.
Where we have a function that returns an error via an Error ** it's normal practice for us to return a bool to say whether it generated an error.

Now, in our case we only call it with error_fatal:

    migration_object_check(current_migration, &error_fatal);

so the bool isn't used/checked.

Quoted 7 lines

So I'm a bit conflicted:

a) Using error_fatal is the easiest way to handle this function
b) Things taking Error ** normally do return a flag value
c) But it's not used in this case.

Hmm.

I guess this generalizes to the bigger question of whether a global "return-value-never-used" check makes sense and brings value. Maybe there are too many cases where it would be preferable to keep the return value for consistency? Maybe they're not that many and could be tagged with __attribute__((unused))?

But in this particular case, perhaps we could drop the Error **errp parameter and directly pass &error_fatal to migrate_params_check() and migrate_caps_check().

Alberto

#5 lore raw

Re: [RFC v2 02/10] Drop unused static function return values

Quoted 61 lines · Alberto Faria
Quoted 45 lines · Dr. David Alan Gilbert
Quoted 8 lines · * Alberto Faria ([email protected]) wrote:

Make non-void static functions whose return values are ignored by all callers return void instead.

These functions were found by static-analyzer.py.

Not all occurrences of this problem were fixed.

<snip>

Quoted 14 lines
migration/migration.c +1 -1
index e03f698a3c..4698080f96 100644
@@ -175,7 +175,7 @@ static MigrationIncomingState *current_incoming;
 
 static GSList *migration_blockers;
 
-static bool migration_object_check(MigrationState *ms, Error **errp);
+static void migration_object_check(MigrationState *ms, Error **errp);
 static int migration_maybe_pause(MigrationState *s,
                                  int *current_active_state,
                                  int new_state);

migration/migration.c static void migration_instance_init(Object *obj) · line 4489

Quoted 6 lines
migration/migration.c +1 -1
@@ -4485,15 +4485,15 @@ static void migration_instance_init(Object *obj)
  * Return true if check pass, false otherwise. Error will be put
  * inside errp if provided.
  */
-static bool migration_object_check(MigrationState *ms, Error **errp)
+static void migration_object_check(MigrationState *ms, Error **errp)
 {

I'm not sure if this is a good change.
Where we have a function that returns an error via an Error ** it's normal practice for us to return a bool to say whether it generated an error.

Now, in our case we only call it with error_fatal:

    migration_object_check(current_migration, &error_fatal);

so the bool isn't used/checked.

Quoted 7 lines

So I'm a bit conflicted:

a) Using error_fatal is the easiest way to handle this function
b) Things taking Error ** normally do return a flag value
c) But it's not used in this case.

Hmm.

I guess this generalizes to the bigger question of whether a global "return-value-never-used" check makes sense and brings value. Maybe there are too many cases where it would be preferable to keep the return value for consistency? Maybe they're not that many and could be tagged with __attribute__((unused))?

Quoted 3 lines

But in this particular case, perhaps we could drop the Error **errp parameter and directly pass &error_fatal to migrate_params_check() and migrate_caps_check().

If it helps to think about this, Coverity checks for consistency. Across the whole code base, is the return value of a function used or ignored consistently. You will see Coverity errors like:

      Error: CHECKED_RETURN (CWE-252): [#def37]
      libnbd-1.12.5/fuse/operations.c:180: check_return: Calling "nbd_poll" without checking return value (as is done elsewhere 5 out of 6 times).
      libnbd-1.12.5/examples/aio-connect-read.c:96: example_checked: Example 1: "nbd_poll(nbd, -1)" has its value checked in "nbd_poll(nbd, -1) == -1".
      libnbd-1.12.5/examples/aio-connect-read.c:128: example_checked: Example 2: "nbd_poll(nbd, -1)" has its value checked in "nbd_poll(nbd, -1) == -1".
      libnbd-1.12.5/examples/strict-structured-reads.c:246: example_checked: Example 3: "nbd_poll(nbd, -1)" has its value checked in "nbd_poll(nbd, -1) == -1".
      libnbd-1.12.5/ocaml/nbd-c.c:2599: example_assign: Example 4: Assigning: "r" = return value from "nbd_poll(h, timeout)".
      libnbd-1.12.5/ocaml/nbd-c.c:2602: example_checked: Example 4 (cont.): "r" has its value checked in "r == -1".
      libnbd-1.12.5/python/methods.c:2806: example_assign: Example 5: Assigning: "ret" = return value from "nbd_poll(h, timeout)".
      libnbd-1.12.5/python/methods.c:2808: example_checked: Example 5 (cont.): "ret" has its value checked in "ret == -1".
      #  178|       /* Dispatch work while there are commands in flight. */
      #  179|       while (thread->in_flight > 0)
      #  180|->       nbd_poll (h, -1);
      #  181|     }
      #  182|

What it's saying is that in this code base, nbd_poll's return value was checked by the caller 5 out of 6 times, but ignored here. (This turned out to be a real bug which we fixed).

It seems like the check implemented in your patch is: If the return value is used 0 times anywhere in the code base, change the return value to 'void'. Coverity would not flag this.

Maybe a consistent use check is better?

Rich.

Signature · 4 lines
Richard Jones, Virtualization Group, Red Hat http://people.redhat.com/~rjones
Read my programming and virtualization blog: http://rwmj.wordpress.com
libguestfs lets you edit virtual machines.  Supports shell scripting,
bindings from many languages.  http://libguestfs.org
#6 lore raw

Re: [RFC v2 02/10] Drop unused static function return values

Quoted 74 lines · Richard W.M. Jones
Quoted 61 lines · Alberto Faria
Quoted 45 lines · Dr. David Alan Gilbert
Quoted 8 lines · * Alberto Faria ([email protected]) wrote:

Make non-void static functions whose return values are ignored by all callers return void instead.

These functions were found by static-analyzer.py.

Not all occurrences of this problem were fixed.

<snip>

Quoted 14 lines
migration/migration.c +1 -1
index e03f698a3c..4698080f96 100644
@@ -175,7 +175,7 @@ static MigrationIncomingState *current_incoming;
 
 static GSList *migration_blockers;
 
-static bool migration_object_check(MigrationState *ms, Error **errp);
+static void migration_object_check(MigrationState *ms, Error **errp);
 static int migration_maybe_pause(MigrationState *s,
                                  int *current_active_state,
                                  int new_state);

migration/migration.c static void migration_instance_init(Object *obj) · line 4489

Quoted 6 lines
migration/migration.c +1 -1
@@ -4485,15 +4485,15 @@ static void migration_instance_init(Object *obj)
  * Return true if check pass, false otherwise. Error will be put
  * inside errp if provided.
  */
-static bool migration_object_check(MigrationState *ms, Error **errp)
+static void migration_object_check(MigrationState *ms, Error **errp)
 {

I'm not sure if this is a good change.
Where we have a function that returns an error via an Error ** it's normal practice for us to return a bool to say whether it generated an error.

Now, in our case we only call it with error_fatal:

    migration_object_check(current_migration, &error_fatal);

so the bool isn't used/checked.

Quoted 7 lines

So I'm a bit conflicted:

a) Using error_fatal is the easiest way to handle this function
b) Things taking Error ** normally do return a flag value
c) But it's not used in this case.

Hmm.

I guess this generalizes to the bigger question of whether a global "return-value-never-used" check makes sense and brings value. Maybe there are too many cases where it would be preferable to keep the return value for consistency? Maybe they're not that many and could be tagged with __attribute__((unused))?

Quoted 3 lines

But in this particular case, perhaps we could drop the Error **errp parameter and directly pass &error_fatal to migrate_params_check() and migrate_caps_check().

If it helps to think about this, Coverity checks for consistency. Across the whole code base, is the return value of a function used or ignored consistently. You will see Coverity errors like:

What it's saying is that in this code base, nbd_poll's return value was checked by the caller 5 out of 6 times, but ignored here. (This turned out to be a real bug which we fixed).

Quoted 5 lines

It seems like the check implemented in your patch is: If the return value is used 0 times anywhere in the code base, change the return value to 'void'. Coverity would not flag this.

Maybe a consistent use check is better?

Inconsistent return value checking is designed-in behaviour for QEMU's current Error handling coding pattern with error_abort/fatal.

If we wanted to make it consistent we would need to require that all methods with 'Error **errp' are tagged 'attribute(unused)' and then provide

  # define ignore_value(x) \
     (__extension__ ({ __typeof__ (x) __x = (x); (void) __x; }))

Such that if you want to use error_abort/error_fatal, you need to explicitly discard the return value eg

   ignore_value(some_method(&error_abort));

If I was starting QEMU fresh, I think like the attribute(unused) anntation and explicit discard, but to retrofit it now would require updated about 3000 current callers which pass &error_abort and &error_fatal.

On the flipside I am willing to bet that doing this work would identify existing bugs where we don't pass error_abort/fatal and also fail to check for failure. So there would be potential payback for the vast churn

With regards,
Daniel

Signature · 3 lines
|: https://berrange.com      -o-    https://www.flickr.com/photos/dberrange :|
|: https://libvirt.org         -o-            https://fstop138.berrange.com :|
|: https://entangle-photo.org    -o-    https://www.instagram.com/dberrange :|
#7 lore raw

Re: [RFC v2 02/10] Drop unused static function return values

Quoted 2 lines · Daniel P. Berrangé

Inconsistent return value checking is designed-in behaviour for QEMU's current Error handling coding pattern with error_abort/fatal.

Yes; I habitually mark as false-positive Coverity reports about missing error checks where it has not noticed that the error handling is done via the errp pointer.

Quoted 17 lines

If we wanted to make it consistent we would need to require that all methods with 'Error **errp' are tagged 'attribute(unused)' and then provide

  # define ignore_value(x) \
     (__extension__ ({ __typeof__ (x) __x = (x); (void) __x; }))

Such that if you want to use error_abort/error_fatal, you need to explicitly discard the return value eg

   ignore_value(some_method(&error_abort));

If I was starting QEMU fresh, I think like the attribute(unused) anntation and explicit discard, but to retrofit it now would require updated about 3000 current callers which pass &error_abort and &error_fatal.

Quoted 4 lines

On the flipside I am willing to bet that doing this work would identify existing bugs where we don't pass error_abort/fatal and also fail to check for failure. So there would be potential payback for the vast churn

Yes, if somebody wanted to take on the task of making this stuff consistent I have no objection there. (I would be inclined to suggest that this might involve a design where we consistently report and check for the error in exactly one way, not in two parallel ways.)

-- PMM

#8 lore raw

Re: [RFC v2 02/10] Drop unused static function return values

Quoted 7 lines · Peter Maydell
Quoted 2 lines · Daniel P. Berrangé

Inconsistent return value checking is designed-in behaviour for QEMU's current Error handling coding pattern with error_abort/fatal.

Yes; I habitually mark as false-positive Coverity reports about missing error checks where it has not noticed that the error handling is done via the errp pointer.

Presumably the advantage of having a qemu-specific static analyser is it'll be able to ignore certain cases, eg. spotting if error_abort is a parameter and allowing (requiring even?) the return value to be ignored.

Coverity allows custom models too, but obviously that's all proprietary software.

Rich.

Signature · 5 lines
Richard Jones, Virtualization Group, Red Hat http://people.redhat.com/~rjones
Read my programming and virtualization blog: http://rwmj.wordpress.com
Fedora Windows cross-compiler. Compile Windows programs, test, and
build Windows installers. Over 100 libraries supported.
http://fedoraproject.org/wiki/MinGW
#9 lore raw

Re: [RFC v2 02/10] Drop unused static function return values

In reply to Richard W.M. Jones
Quoted 23 lines · Richard W.M. Jones

If it helps to think about this, Coverity checks for consistency. Across the whole code base, is the return value of a function used or ignored consistently. You will see Coverity errors like:

      Error: CHECKED_RETURN (CWE-252): [#def37]
      libnbd-1.12.5/fuse/operations.c:180: check_return: Calling "nbd_poll" without checking return value (as is done elsewhere 5 out of 6 times).
      libnbd-1.12.5/examples/aio-connect-read.c:96: example_checked: Example 1: "nbd_poll(nbd, -1)" has its value checked in "nbd_poll(nbd, -1) == -1".
      libnbd-1.12.5/examples/aio-connect-read.c:128: example_checked: Example 2: "nbd_poll(nbd, -1)" has its value checked in "nbd_poll(nbd, -1) == -1".
      libnbd-1.12.5/examples/strict-structured-reads.c:246: example_checked: Example 3: "nbd_poll(nbd, -1)" has its value checked in "nbd_poll(nbd, -1) == -1".
      libnbd-1.12.5/ocaml/nbd-c.c:2599: example_assign: Example 4: Assigning: "r" = return value from "nbd_poll(h, timeout)".
      libnbd-1.12.5/ocaml/nbd-c.c:2602: example_checked: Example 4 (cont.): "r" has its value checked in "r == -1".
      libnbd-1.12.5/python/methods.c:2806: example_assign: Example 5: Assigning: "ret" = return value from "nbd_poll(h, timeout)".
      libnbd-1.12.5/python/methods.c:2808: example_checked: Example 5 (cont.): "ret" has its value checked in "ret == -1".
      #  178|       /* Dispatch work while there are commands in flight. */
      #  179|       while (thread->in_flight > 0)
      #  180|->       nbd_poll (h, -1);
      #  181|     }
      #  182|

What it's saying is that in this code base, nbd_poll's return value was checked by the caller 5 out of 6 times, but ignored here. (This turned out to be a real bug which we fixed).

Quoted 5 lines

It seems like the check implemented in your patch is: If the return value is used 0 times anywhere in the code base, change the return value to 'void'. Coverity would not flag this.

Maybe a consistent use check is better?

Note that the analyzer is currently limited to analyzing a single translation unit at a time, so we would only be able to implement a consistent use check for static functions (this is why the current "return-value-never-used" check only applies to static functions).

It may be worthwhile exploring cross-translation unit analysis, although it may be difficult to accomplish while also avoiding reanalyzing the entire tree every time a single translation unit is modified.

Alberto

#10 lore raw

Re: [RFC v2 02/10] Drop unused static function return values

In reply to Dr. David Alan Gilbert
Quoted 42 lines · Dr. David Alan Gilbert
Quoted 8 lines · * Alberto Faria ([email protected]) wrote:

Make non-void static functions whose return values are ignored by all callers return void instead.

These functions were found by static-analyzer.py.

Not all occurrences of this problem were fixed.

<snip>

Quoted 14 lines
migration/migration.c +1 -1
index e03f698a3c..4698080f96 100644
@@ -175,7 +175,7 @@ static MigrationIncomingState *current_incoming;
 
 static GSList *migration_blockers;
 
-static bool migration_object_check(MigrationState *ms, Error **errp);
+static void migration_object_check(MigrationState *ms, Error **errp);
 static int migration_maybe_pause(MigrationState *s,
                                  int *current_active_state,
                                  int new_state);

migration/migration.c static void migration_instance_init(Object *obj) · line 4489

Quoted 6 lines
migration/migration.c +1 -1
@@ -4485,15 +4485,15 @@ static void migration_instance_init(Object *obj)
  * Return true if check pass, false otherwise. Error will be put
  * inside errp if provided.
  */
-static bool migration_object_check(MigrationState *ms, Error **errp)
+static void migration_object_check(MigrationState *ms, Error **errp)
 {

I'm not sure if this is a good change.
Where we have a function that returns an error via an Error ** it's normal practice for us to return a bool to say whether it generated an error.

Now, in our case we only call it with error_fatal:

    migration_object_check(current_migration, &error_fatal);
Quoted 7 lines

so the bool isn't used/checked.

So I'm a bit conflicted:

a) Using error_fatal is the easiest way to handle this function
b) Things taking Error ** normally do return a flag value
c) But it's not used in this case.

Yep, migration_object_check is following our recommended design pattern for error reporting. It is valid to either check the return value, or pass error_fatal / error_abort.

The fact that no /current/ callers happen to check the return value is not a reason to make it 'void'.

With regards,
Daniel

Signature · 3 lines
|: https://berrange.com      -o-    https://www.flickr.com/photos/dberrange :|
|: https://libvirt.org         -o-            https://fstop138.berrange.com :|
|: https://entangle-photo.org    -o-    https://www.instagram.com/dberrange :|
#11 lore raw

Re: [RFC v2 02/10] Drop unused static function return values

In reply to Alberto Faria
Quoted 11 lines · Alberto Faria

Make non-void static functions whose return values are ignored by all callers return void instead.

These functions were found by static-analyzer.py.

Not all occurrences of this problem were fixed.

 65 files changed, 248 insertions(+), 403 deletions(-)

The problem with a patch like this is that it rolls up into a single patch changes to the API of many functions in multiple subsystems across the whole codebase. Some of those changes might be right; some might be wrong. No single person is going to be in a position to review the whole lot, and a +248-403 patch email makes it very unwieldy to try to discuss.

If you want to propose some of these I think you need to:
* split it out so that you're only suggesting changes in one subsystem at a time
* look at the places you are suggesting changes, to see if the correct answer is actually "add the missing error check in the caller(s)"
* not change places that are following standard API patterns like "return bool and have an Error** argument"

thanks
-- PMM

#12 lore raw

Re: [RFC v2 02/10] Drop unused static function return values

Quoted 7 lines · Peter Maydell

The problem with a patch like this is that it rolls up into a single patch changes to the API of many functions in multiple subsystems across the whole codebase. Some of those changes might be right; some might be wrong. No single person is going to be in a position to review the whole lot, and a +248-403 patch email makes it very unwieldy to try to discuss.

Quoted 8 lines

If you want to propose some of these I think you need to:
* split it out so that you're only suggesting changes in one subsystem at a time
* look at the places you are suggesting changes, to see if the correct answer is actually "add the missing error check in the caller(s)"
* not change places that are following standard API patterns like "return bool and have an Error** argument"

Sounds good. For now, I'll limit the changes to a few representative cases e.g. in the block layer, since this patch is mostly intended as a demonstration of the type of issue that the check catches. Once there is agreement on the semantics for the check, I'll probably send a separate tree-wide series with per-subsystem patches.

Thanks,
Alberto

#13 lore raw

RFC v2 3/10 static-analyzer: Support adding tests to checks

In reply to Alberto Faria

Introduce an add_check_tests() method to add output-comparison tests to checks, and add some tests to the "return-value-never-used" check.

---
 static-analyzer.py                         | 133 ++++++++++++++++++++-
 static_analyzer/__init__.py                |  39 +++++-
 static_analyzer/return_value_never_used.py | 103 ++++++++++++++++
 3 files changed, 267 insertions(+), 8 deletions(-)
static-analyzer.py +127 -6
index 3ade422dbf..16e331000d 100755
@@ -11,17 +11,26 @@
 import subprocess
 import sys
 import re
-from argparse import ArgumentParser, Namespace, RawDescriptionHelpFormatter
+from argparse import (
+    Action,
+    ArgumentParser,
+    Namespace,
+    RawDescriptionHelpFormatter,
+)
 from multiprocessing import Pool
 from pathlib import Path
+from tempfile import TemporaryDirectory
 import textwrap
 import time
+from traceback import print_exc
 from typing import (
+    Callable,
     Iterable,
     Iterator,
     List,
     Mapping,
     NoReturn,
+    Optional,
     Sequence,
     Union,
 )
@@ -37,7 +46,7 @@
 def parse_args() -> Namespace:
 
     available_checks = "\n".join(
-        f"  {name}   {' '.join((CHECKS[name].__doc__ or '').split())}"
+        f"  {name}   {' '.join((CHECKS[name].checker.__doc__ or '').split())}"
         for name in sorted(CHECKS)
     )
 
@@ -134,14 +143,37 @@ def parse_args() -> Namespace:
         help="Do everything except actually running the checks.",
     )
 
+    dev_options.add_argument(
+        "--test",
+        action=TestAction,
+        nargs=0,
+        help="Run tests for all checks and exit.",
+    )
+
     # parse arguments
 
-    args = parser.parse_args()
+    try:
+        args = parser.parse_args()
+    except TestSentinelError:
+        # --test was specified
+        if len(sys.argv) > 2:
+            parser.error("--test must be given alone")
+        return Namespace(test=True)
+
     args.check_names = sorted(set(args.check_names or CHECKS))
 
     return args
 
 
+class TestAction(Action):
+    def __call__(self, parser, namespace, values, option_string=None):
+        raise TestSentinelError
+
+
+class TestSentinelError(Exception):
+    pass
+
+
 # ---------------------------------------------------------------------------- #
 # Main
 
@@ -150,7 +182,11 @@ def main() -> int:
 
     args = parse_args()
 
-    if args.profile:
+    if args.test:
+
+        return test()
+
+    elif args.profile:
 
         import cProfile
         import pstats
@@ -170,6 +206,18 @@ def main() -> int:
         return analyze(args)
 
 
+def test() -> int:
+
+    for (check_name, check) in CHECKS.items():
+        for group in check.test_groups:
+            for input in group.inputs:
+                run_test(
+                    check_name, group.location, input, group.expected_output
+                )
+
+    return 0
+
+
 def analyze(args: Namespace) -> int:
 
     tr_units = get_translation_units(args)
@@ -247,6 +295,7 @@ class TranslationUnit:
     build_command: str
     system_include_paths: Sequence[str]
     check_names: Sequence[str]
+    custom_printer: Optional[Callable[[str], None]]
 
 
 def get_translation_units(args: Namespace) -> Sequence["TranslationUnit"]:
@@ -264,6 +313,7 @@ def get_translation_units(args: Namespace) -> Sequence["TranslationUnit"]:
             build_command=cmd["command"],
             system_include_paths=system_include_paths,
             check_names=args.check_names,
+            custom_printer=None,
         )
         for cmd in compile_commands
     )
@@ -380,7 +430,7 @@ def analyze_translation_unit(tr_unit: TranslationUnit) -> bool:
 
     try:
         for name in tr_unit.check_names:
-            CHECKS[name](check_context)
+            CHECKS[name].checker(check_context)
     except Exception as e:
         raise RuntimeError(f"Error analyzing {check_context._rel_path}") from e
 
@@ -428,7 +478,9 @@ def get_check_context(tr_unit: TranslationUnit) -> CheckContext:
         except clang.cindex.TranslationUnitLoadError as e:
             raise RuntimeError(f"Failed to load {rel_path}") from e
 
-    if sys.stdout.isatty():
+    if tr_unit.custom_printer is not None:
+        printer = tr_unit.custom_printer
+    elif sys.stdout.isatty():
         # add padding to fully overwrite progress message
         printer = lambda s: print(s.ljust(50))
     else:
@@ -457,6 +509,75 @@ def get_check_context(tr_unit: TranslationUnit) -> CheckContext:
     return check_context
 
 
+# ---------------------------------------------------------------------------- #
+# Tests
+
+
+def run_test(
+    check_name: str, location: str, input: str, expected_output: str
+) -> None:
+
+    with TemporaryDirectory() as temp_dir:
+
+        os.chdir(temp_dir)
+
+        input_path = Path(temp_dir) / "file.c"
+        input_path.write_text(input)
+
+        actual_output_list = []
+
+        tu_context = TranslationUnit(
+            absolute_path=str(input_path),
+            build_working_dir=str(input_path.parent),
+            build_command=f"cc {shlex.quote(str(input_path))}",
+            system_include_paths=[],
+            check_names=[check_name],
+            custom_printer=lambda s: actual_output_list.append(s + "\n"),
+        )
+
+        check_context = get_check_context(tu_context)
+
+        # analyze translation unit
+
+        try:
+
+            for name in tu_context.check_names:
+                CHECKS[name].checker(check_context)
+
+        except Exception:
+
+            print(
+                f"\033[0;31mTest defined at {location} raised an"
+                f" exception.\033[0m"
+            )
+            print(f"\033[0;31mInput:\033[0m")
+            print(input, end="")
+            print(f"\033[0;31mExpected output:\033[0m")
+            print(expected_output, end="")
+            print(f"\033[0;31mException:\033[0m")
+            print_exc(file=sys.stdout)
+            print(f"\033[0;31mAST:\033[0m")
+            check_context.print_tree(check_context.translation_unit.cursor)
+
+            sys.exit(1)
+
+        actual_output = "".join(actual_output_list)
+
+        if actual_output != expected_output:
+
+            print(f"\033[0;33mTest defined at {location} failed.\033[0m")
+            print(f"\033[0;33mInput:\033[0m")
+            print(input, end="")
+            print(f"\033[0;33mExpected output:\033[0m")
+            print(expected_output, end="")
+            print(f"\033[0;33mActual output:\033[0m")
+            print(actual_output, end="")
+            print(f"\033[0;33mAST:\033[0m")
+            check_context.print_tree(check_context.translation_unit.cursor)
+
+            sys.exit(3)
+
+
 # ---------------------------------------------------------------------------- #
 # Utilities
 
static_analyzer/__init__.py +37 -2
index e6ca48d714..36028724b1 100644
@@ -3,16 +3,20 @@
 from ctypes import CFUNCTYPE, c_int, py_object
 from dataclasses import dataclass
 from enum import Enum
+import inspect
 import os
 import os.path
 from pathlib import Path
 from importlib import import_module
+import textwrap
 from typing import (
     Any,
     Callable,
     Dict,
+    Iterable,
     List,
     Optional,
+    Sequence,
     Union,
 )
 
@@ -218,18 +222,49 @@ def print_tree(
 
 Checker = Callable[[CheckContext], None]
 
-CHECKS: Dict[str, Checker] = {}
+
+class CheckTestGroup:
+
+    inputs: Sequence[str]
+    expected_output: str
+
+    location: str
+
+    def __init__(self, inputs: Iterable[str], expected_output: str) -> None:
+        def reformat_string(s: str) -> str:
+            return "".join(
+                line + "\n" for line in textwrap.dedent(s).strip().splitlines()
+            )
+
+        self.inputs = [reformat_string(input) for input in inputs]
+        self.expected_output = reformat_string(expected_output)
+
+        caller = inspect.stack()[1]
+        self.location = f"{os.path.relpath(caller.filename)}:{caller.lineno}"
+
+
+@dataclass
+class Check:
+    checker: Checker
+    test_groups: List[CheckTestGroup]
+
+
+CHECKS: Dict[str, Check] = {}
 
 
 def check(name: str) -> Callable[[Checker], Checker]:
     def decorator(checker: Checker) -> Checker:
         assert name not in CHECKS
-        CHECKS[name] = checker
+        CHECKS[name] = Check(checker=checker, test_groups=[])
         return checker
 
     return decorator
 
 
+def add_check_tests(check_name: str, *groups: CheckTestGroup) -> None:
+    CHECKS[check_name].test_groups.extend(groups)
+
+
 # ---------------------------------------------------------------------------- #
 # Import all checks
 
static_analyzer/return_value_never_used.py +103 -0

113 lines not on this page · raw message

Signature · 1 line
2.37.1
#14 lore raw

RFC v2 4/10 static-analyzer: Avoid reanalyzing unmodified translation units

In reply to Alberto Faria

For each translation unit, run each check only if any of the translation unit's files has been modified since the last time the check ran and passed without reporting problems.

---
 static-analyzer.py | 240 ++++++++++++++++++++++++++++++++++++++++-----
 1 file changed, 217 insertions(+), 23 deletions(-)
static-analyzer.py +217 -23
index 16e331000d..140760a93e 100755
@@ -25,6 +25,8 @@
 from traceback import print_exc
 from typing import (
     Callable,
+    Dict,
+    FrozenSet,
     Iterable,
     Iterator,
     List,
@@ -32,6 +34,7 @@
     NoReturn,
     Optional,
     Sequence,
+    Tuple,
     Union,
 )
 
@@ -61,9 +64,19 @@ def parse_args() -> Namespace:
             build configuration. Note that a single .c file may give rise to
             several translation units.
 
+            For each translation unit, each check is run only if any its files
+            has been modified since the last time the check ran and passed
+            without reporting problems.
+
             You should build QEMU before running this, since some translation
             units depend on files that are generated during the build. If you
             don't, you'll get errors, but should never get false negatives.
+            Also, translation units that haven't been built will always be
+            reanalyzed, even they haven't been modified, because we cant't know
+            what their dependencies are until they are built. (TODO: This is
+            rather annoying since `make all` does not actually build every
+            translation unit. Should this script trigger an actual full build
+            somehow as a first step?)
             """
         ),
         epilog=textwrap.dedent(
@@ -111,6 +124,16 @@ def parse_args() -> Namespace:
         ),
     )
 
+    parser.add_argument(
+        "-f",
+        "--force",
+        action="store_true",
+        help=(
+            "Analyze translation units even if they haven't been modified since"
+            " the last analysis."
+        ),
+    )
+
     parser.add_argument(
         "-j",
         "--jobs",
@@ -220,12 +243,17 @@ def test() -> int:
 
 def analyze(args: Namespace) -> int:
 
-    tr_units = get_translation_units(args)
+    analysis_timestamp = time.time()
+
+    # load log and get translation units
+
+    log = AnalysisLog.load(args.build_dir)
+    (tr_units, num_up_to_date_tr_units) = get_translation_units(args, log)
 
     # analyze translation units
 
     start_time = time.monotonic()
-    results: List[bool] = []
+    results: List[AnalysisResults] = []
 
     if len(tr_units) == 1:
         progress_suffix = " of 1 translation unit...\033[0m\r"
@@ -237,7 +265,7 @@ def print_progress() -> None:
 
     print_progress()
 
-    def collect_results(results_iter: Iterable[bool]) -> None:
+    def collect_results(results_iter: Iterable[AnalysisResults]) -> None:
         if sys.stdout.isatty():
             for r in results_iter:
                 results.append(r)
@@ -246,27 +274,41 @@ def collect_results(results_iter: Iterable[bool]) -> None:
             for r in results_iter:
                 results.append(r)
 
-    if tr_units:
+    try:
 
-        if args.threads == 1:
+        if tr_units:
 
-            collect_results(map(analyze_translation_unit, tr_units))
+            if args.threads == 1:
 
-        else:
+                collect_results(map(analyze_translation_unit, tr_units))
 
-            # Mimic Python's default pool.map() chunk size, but limit it to
-            # 5 to avoid very big chunks when analyzing thousands of
-            # translation units.
-            chunk_size = min(5, -(-len(tr_units) // (args.threads * 4)))
+            else:
 
-            with Pool(processes=args.threads) as pool:
-                collect_results(
-                    pool.imap_unordered(
-                        analyze_translation_unit, tr_units, chunk_size
+                # Mimic Python's default pool.map() chunk size, but limit it to
+                # 5 to avoid very big chunks when analyzing thousands of
+                # translation units.
+                chunk_size = min(5, -(-len(tr_units) // (args.threads * 4)))
+
+                with Pool(processes=args.threads) as pool:
+                    collect_results(
+                        pool.imap_unordered(
+                            analyze_translation_unit, tr_units, chunk_size
+                        )
                     )
-                )
 
-    end_time = time.monotonic()
+        end_time = time.monotonic()
+
+    finally:
+
+        # update analysis timestamps for passed checks for each translation unit
+        # (even if the static analyzer failed or was interrupted)
+
+        for r in results:
+            log.set_last_analysis_time(
+                r.tr_unit_object_file, r.passed_check_names, analysis_timestamp
+            )
+
+        log.save()
 
     # print summary
 
@@ -275,13 +317,18 @@ def collect_results(results_iter: Iterable[bool]) -> None:
     else:
         message = f"Analyzed {len(tr_units)} translation units"
 
+    if num_up_to_date_tr_units == 1:
+        message += " (1 other was up-to-date)"
+    elif num_up_to_date_tr_units > 1:
+        message += f" ({num_up_to_date_tr_units} other were up-to-date)"
+
     message += f" in {end_time - start_time:.1f} seconds."
 
     print(f"\033[0;34m{message}\033[0m")
 
     # exit
 
-    return 0 if all(results) else 3
+    return 0 if all(not r.problems_found for r in results) else 3
 
 
 # ---------------------------------------------------------------------------- #
@@ -293,13 +340,17 @@ class TranslationUnit:
     absolute_path: str
     build_working_dir: str
     build_command: str
+    object_file: str
     system_include_paths: Sequence[str]
     check_names: Sequence[str]
     custom_printer: Optional[Callable[[str], None]]
 
 
-def get_translation_units(args: Namespace) -> Sequence["TranslationUnit"]:
-    """Return a list of translation units to be analyzed."""
+def get_translation_units(
+    args: Namespace, log: "AnalysisLog"
+) -> Tuple[Sequence["TranslationUnit"], int]:
+    """Return a list of translation units to be analyzed, and the number of
+    translation units that were skipped because all checks are up to date."""
 
     system_include_paths = get_clang_system_include_paths()
     compile_commands = load_compilation_database(args.build_dir)
@@ -311,6 +362,7 @@ def get_translation_units(args: Namespace) -> Sequence["TranslationUnit"]:
             absolute_path=str(Path(cmd["directory"], cmd["file"]).resolve()),
             build_working_dir=cmd["directory"],
             build_command=cmd["command"],
+            object_file=cmd["output"],
             system_include_paths=system_include_paths,
             check_names=args.check_names,
             custom_printer=None,
@@ -365,17 +417,25 @@ def get_translation_units(args: Namespace) -> Sequence["TranslationUnit"]:
     # ensure that at least one translation unit is selected
 
     tr_unit_list = list(tr_units)
+    num_selected_tr_units = len(tr_unit_list)
 
     if not tr_unit_list:
         fatal("No translation units to analyze")
 
+    # skip translation units that don't need reanalyzing
+
+    if not args.force:
+        log.drop_up_to_date_checks(tr_unit_list)
+
+    num_up_to_date_tr_units = num_selected_tr_units - len(tr_unit_list)
+
     # disable all checks if --skip-checks was given
 
     if args.skip_checks:
         for context in tr_unit_list:
             context.check_names = []
 
-    return tr_unit_list
+    return (tr_unit_list, num_up_to_date_tr_units)
 
 
 def get_clang_system_include_paths() -> Sequence[str]:
@@ -420,21 +480,154 @@ def load_compilation_database(build_dir: Path) -> Sequence[Mapping[str, str]]:
         fatal(f"{path} does not exist")
 
 
+# ---------------------------------------------------------------------------- #
+# Analysis log
+
+
+@dataclass
+class AnalysisLog:
+
+    build_dir: Path
+    deps_by_object_file: Mapping[str, FrozenSet[str]]
+    last_analysis: Dict[str, Dict[str, float]]
+
+    @classmethod
+    def load(cls, build_dir: Path) -> "AnalysisLog":
+
+        # get dependencies
+
+        result = subprocess.run(
+            ["ninja", "-C", str(build_dir), "-t", "deps"],
+            stdin=subprocess.DEVNULL,
+            stdout=subprocess.PIPE,
+            stderr=subprocess.DEVNULL,
+            universal_newlines=True,  # decode output using default encoding
+            check=True,
+        )
+
+        deps: Dict[str, FrozenSet[str]] = {}
+
+        for group in result.stdout.split("\n\n"):
+            if group:
+                [first_line, *other_lines] = group.splitlines()
+                target = first_line[: first_line.index(":")]
+                deps[target] = frozenset(dep[4:] for dep in other_lines)
+
+        # load log
+
+        try:
+            with (build_dir / "static-analyzer-log.json").open("r") as f:
+                last_analysis: Dict[str, Dict[str, float]] = json.load(f)
+        except FileNotFoundError:
+            last_analysis = {}
+
+        return AnalysisLog(
+            build_dir=build_dir,
+            deps_by_object_file=deps,
+            last_analysis=last_analysis,
+        )
+
+    def drop_up_to_date_checks(self, tr_units: List[TranslationUnit]) -> None:
+        """For each translation unit, removes checks from
+        `TranslationUnit.check_names` that are are up-to-date.
+
+        If a `TranslationUnit` ends up with no checks, it is removed from the
+        list.
+        """
+
+        # deps are output relative to build dir
+        with cwd(self.build_dir):
+
+            def f(tr_unit: TranslationUnit) -> bool:
+                tr_unit.check_names = self._outdated_checks(
+                    tr_unit.object_file, tr_unit.check_names
+                )
+                return bool(tr_unit.check_names)
+
+            tr_units[:] = list(filter(f, tr_units))
+
+    def _outdated_checks(
+        self,
+        tr_unit_object_file: str,
+        candidate_check_names: Sequence[str],
+    ) -> Sequence[str]:
+        """Working directory must be `self.build_dir`."""
+
+        deps = self.deps_by_object_file.get(tr_unit_object_file)
+
+        if deps is None:
+            # This happens when the translation unit hasn't been built. In this
+            # case, we cannot know what its dependencies are, and thus whether
+            # they have been modified, so we must play safe and run all checks.
+            return candidate_check_names
+
+        latest_dep_mtime = max(map(os.path.getmtime, deps), default=0.0)
+
+        d = self.last_analysis.get(tr_unit_object_file, {})
+
+        return [
+            check
+            for check in candidate_check_names
+            if latest_dep_mtime >= d.get(check, 0.0)
+        ]
+
+    def set_last_analysis_time(
+        self,
+        tr_unit_object_file: str,
+        check_names: Iterable[str],
+        time: float,
+    ) -> None:
+
+        d = self.last_analysis.setdefault(tr_unit_object_file, {})
+
+        for check_name in check_names:
+            d[check_name] = time
+
+    def save(self) -> None:
+
+        with (self.build_dir / "static-analyzer-log.json").open("w") as f:
+            json.dump(self.last_analysis, f, indent=2)
+
+
 # ---------------------------------------------------------------------------- #
 # Analysis
 
 
-def analyze_translation_unit(tr_unit: TranslationUnit) -> bool:
+@dataclass
+class AnalysisResults:
+    tr_unit_object_file: str
+    passed_check_names: Sequence[str]
+    problems_found: bool
+
+
+def analyze_translation_unit(tr_unit: TranslationUnit) -> AnalysisResults:
 
     check_context = get_check_context(tr_unit)
 
+    had_diagnostics = check_context._problems_found
+    problems_found = check_context._problems_found
+    passed_check_names: List[str] = []
+
     try:
+
         for name in tr_unit.check_names:
+
+            check_context._problems_found = False
             CHECKS[name].checker(check_context)
+
+            if not had_diagnostics and not check_context._problems_found:
+                passed_check_names.append(name)
+            else:
+                problems_found = True
+
     except Exception as e:
         raise RuntimeError(f"Error analyzing {check_context._rel_path}") from e
 
-    return not check_context._problems_found
+    return AnalysisResults(
+        tr_unit_object_file=tr_unit.object_file,
+        passed_check_names=passed_check_names,
+        problems_found=problems_found,
+    )
 
 
 def get_check_context(tr_unit: TranslationUnit) -> CheckContext:
@@ -530,6 +723,7 @@ def run_test(
             absolute_path=str(input_path),
             build_working_dir=str(input_path.parent),
             build_command=f"cc {shlex.quote(str(input_path))}",
+            object_file="file.o",
             system_include_paths=[],
             check_names=[check_name],
             custom_printer=lambda s: actual_output_list.append(s + "\n"),
Signature · 1 line
2.37.1
#15 lore raw

RFC v2 5/10 static-analyzer: Enforce coroutine_fn restrictions for direct calls

In reply to Alberto Faria

Add a "coroutine_fn" check to static-analyzer.py that ensures that non-coroutine_fn functions don't perform direct calls to coroutine_fn functions.

For the few cases where this must happen, introduce an __allow_coroutine_fn_call() macro that wraps offending calls and overrides the static analyzer.

---
 include/qemu/coroutine.h        |  13 +++
 static_analyzer/__init__.py     |  46 ++++++++-
 static_analyzer/coroutine_fn.py | 173 ++++++++++++++++++++++++++++++++
 3 files changed, 231 insertions(+), 1 deletion(-)
 create mode 100644 static_analyzer/coroutine_fn.py
include/qemu/coroutine.h +13 -0
index 08c5bb3c76..40a4037525 100644
@@ -42,7 +42,20 @@
  *       ....
  *   }
  */
+#ifdef __clang__
+#define coroutine_fn __attribute__((__annotate__("coroutine_fn")))
+#else
 #define coroutine_fn
+#endif
+
+/**
+ * This can wrap a call to a coroutine_fn from a non-coroutine_fn function and
+ * suppress the static analyzer's complaints.
+ *
+ * You don't want to use this.
+ */
+#define __allow_coroutine_fn_call(call) \
+    ((void)"__allow_coroutine_fn_call", call)
 
 typedef struct Coroutine Coroutine;
 
static_analyzer/__init__.py +45 -1

59 lines not on this page · raw message

static_analyzer/coroutine_fn.py new file +173 -0

173 lines not on this page · raw message

Signature · 1 line
2.37.1
#16 lore raw

RFC v2 6/10 Fix some direct calls from non-coroutine_fn to coroutine_fn

In reply to Alberto Faria

In some cases we need to use a different function, in others we need to make the caller a coroutine_fn, and in others still we need to wrap calls to coroutines in __allow_coroutine_fn_call().

Also fix coroutine_fn annotation disagreements between several declarations of the same function.

These problems were found by static-analyzer.py.

Not all occurrences of these problems were fixed.

---
 block.c                        |  2 +-
 block/dirty-bitmap.c           |  6 ++++--
 block/io.c                     | 18 +++++++++++-------
 block/monitor/block-hmp-cmds.c |  2 +-
 block/nvme.c                   |  3 ++-
 block/qcow2.c                  | 14 +++++++-------
 block/qcow2.h                  | 14 +++++++-------
 block/qed.c                    |  2 +-
 block/quorum.c                 |  2 +-
 block/ssh.c                    |  6 +++---
 block/throttle-groups.c        |  3 ++-
 include/block/block-hmp-cmds.h |  2 +-
 include/block/block-io.h       |  5 +++--
 include/qemu/coroutine.h       | 18 ++++++++++--------
 14 files changed, 54 insertions(+), 43 deletions(-)
block.c +1 -1
index bc85f46eed..9f3814cbaa 100644
@@ -561,7 +561,7 @@ int bdrv_create(BlockDriver *drv, const char* filename,
 
     if (qemu_in_coroutine()) {
         /* Fast-path if already in coroutine context */
-        bdrv_create_co_entry(&cco);
+        __allow_coroutine_fn_call(bdrv_create_co_entry(&cco));
     } else {
         co = qemu_coroutine_create(bdrv_create_co_entry, &cco);
         qemu_coroutine_enter(co);
block/dirty-bitmap.c +4 -2
index bf3dc0512a..ccf46c0b1f 100644
@@ -419,7 +419,8 @@ int bdrv_remove_persistent_dirty_bitmap(BlockDriverState *bs, const char *name,
                                         Error **errp)
 {
     if (qemu_in_coroutine()) {
-        return bdrv_co_remove_persistent_dirty_bitmap(bs, name, errp);
+        return __allow_coroutine_fn_call(
+            bdrv_co_remove_persistent_dirty_bitmap(bs, name, errp));
     } else {
         Coroutine *co;
         BdrvRemovePersistentDirtyBitmapCo s = {
@@ -495,7 +496,8 @@ bool bdrv_can_store_new_dirty_bitmap(BlockDriverState *bs, const char *name,
 {
     IO_CODE();
     if (qemu_in_coroutine()) {
-        return bdrv_co_can_store_new_dirty_bitmap(bs, name, granularity, errp);
+        return __allow_coroutine_fn_call(
+            bdrv_co_can_store_new_dirty_bitmap(bs, name, granularity, errp));
     } else {
         Coroutine *co;
         BdrvCanStoreNewDirtyBitmapCo s = {
block/io.c +11 -7
index 853ed44289..c2ed14cedb 100644
@@ -449,8 +449,9 @@ static void bdrv_do_drained_begin(BlockDriverState *bs, bool recursive,
     BdrvChild *child, *next;
 
     if (qemu_in_coroutine()) {
-        bdrv_co_yield_to_drain(bs, true, recursive, parent, ignore_bds_parents,
-                               poll, NULL);
+        __allow_coroutine_fn_call(
+            bdrv_co_yield_to_drain(bs, true, recursive, parent,
+                                   ignore_bds_parents, poll, NULL));
         return;
     }
 
@@ -516,8 +517,10 @@ static void bdrv_do_drained_end(BlockDriverState *bs, bool recursive,
     assert(drained_end_counter != NULL);
 
     if (qemu_in_coroutine()) {
-        bdrv_co_yield_to_drain(bs, false, recursive, parent, ignore_bds_parents,
-                               false, drained_end_counter);
+        __allow_coroutine_fn_call(
+            bdrv_co_yield_to_drain(bs, false, recursive, parent,
+                                   ignore_bds_parents, false,
+                                   drained_end_counter));
         return;
     }
     assert(bs->quiesce_counter > 0);
@@ -643,7 +646,8 @@ void bdrv_drain_all_begin(void)
     GLOBAL_STATE_CODE();
 
     if (qemu_in_coroutine()) {
-        bdrv_co_yield_to_drain(NULL, true, false, NULL, true, true, NULL);
+        __allow_coroutine_fn_call(
+            bdrv_co_yield_to_drain(NULL, true, false, NULL, true, true, NULL));
         return;
     }
 
@@ -2742,8 +2746,8 @@ int coroutine_fn bdrv_co_is_zero_fast(BlockDriverState *bs, int64_t offset,
     return (pnum == bytes) && (ret & BDRV_BLOCK_ZERO);
 }
 
-int coroutine_fn bdrv_is_allocated(BlockDriverState *bs, int64_t offset,
-                                   int64_t bytes, int64_t *pnum)
+int bdrv_is_allocated(BlockDriverState *bs, int64_t offset, int64_t bytes,
+                      int64_t *pnum)
 {
     int ret;
     int64_t dummy;
block/monitor/block-hmp-cmds.c +1 -1
index bfb3c043a0..b5ba9281f0 100644
@@ -489,7 +489,7 @@ void hmp_nbd_server_stop(Monitor *mon, const QDict *qdict)
     hmp_handle_error(mon, err);
 }
 
-void hmp_block_resize(Monitor *mon, const QDict *qdict)
+void coroutine_fn hmp_block_resize(Monitor *mon, const QDict *qdict)
 {
     const char *device = qdict_get_str(qdict, "device");
     int64_t size = qdict_get_int(qdict, "size");
block/nvme.c +2 -1
index 01fb28aa63..c645f87142 100644
@@ -306,7 +306,8 @@ static NVMeRequest *nvme_get_free_req(NVMeQueuePair *q)
     while (q->free_req_head == -1) {
         if (qemu_in_coroutine()) {
             trace_nvme_free_req_queue_wait(q->s, q->index);
-            qemu_co_queue_wait(&q->free_req_queue, &q->lock);
+            __allow_coroutine_fn_call(
+                qemu_co_queue_wait(&q->free_req_queue, &q->lock));
         } else {
             qemu_mutex_unlock(&q->lock);
             return NULL;
block/qcow2.c +7 -7
index c6c6692fb7..d3dad0142e 100644
@@ -1905,7 +1905,7 @@ static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
 
     if (qemu_in_coroutine()) {
         /* From bdrv_co_create.  */
-        qcow2_open_entry(&qoc);
+        __allow_coroutine_fn_call(qcow2_open_entry(&qoc));
     } else {
         assert(qemu_get_current_aio_context() == qemu_get_aio_context());
         qemu_coroutine_enter(qemu_coroutine_create(qcow2_open_entry, &qoc));
@@ -5226,7 +5226,7 @@ static int qcow2_has_zero_init(BlockDriverState *bs)
     bool preallocated;
 
     if (qemu_in_coroutine()) {
-        qemu_co_mutex_lock(&s->lock);
+        __allow_coroutine_fn_call(qemu_co_mutex_lock(&s->lock));
     }
     /*
      * Check preallocation status: Preallocated images have all L2
@@ -5235,7 +5235,7 @@ static int qcow2_has_zero_init(BlockDriverState *bs)
      */
     preallocated = s->l1_size > 0 && s->l1_table[0] != 0;
     if (qemu_in_coroutine()) {
-        qemu_co_mutex_unlock(&s->lock);
+        __allow_coroutine_fn_call(qemu_co_mutex_unlock(&s->lock));
     }
 
     if (!preallocated) {
@@ -5274,8 +5274,8 @@ static int64_t qcow2_check_vmstate_request(BlockDriverState *bs,
     return pos;
 }
 
-static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
-                              int64_t pos)
+static coroutine_fn int qcow2_save_vmstate(BlockDriverState *bs,
+                                           QEMUIOVector *qiov, int64_t pos)
 {
     int64_t offset = qcow2_check_vmstate_request(bs, qiov, pos);
     if (offset < 0) {
@@ -5286,8 +5286,8 @@ static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
     return bs->drv->bdrv_co_pwritev_part(bs, offset, qiov->size, qiov, 0, 0);
 }
 
-static int qcow2_load_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
-                              int64_t pos)
+static coroutine_fn int qcow2_load_vmstate(BlockDriverState *bs,
+                                           QEMUIOVector *qiov, int64_t pos)
 {
     int64_t offset = qcow2_check_vmstate_request(bs, qiov, pos);
     if (offset < 0) {
block/qcow2.h +7 -7
index ba436a8d0d..e68d127d8e 100644
@@ -990,13 +990,13 @@ int qcow2_truncate_bitmaps_check(BlockDriverState *bs, Error **errp);
 bool qcow2_store_persistent_dirty_bitmaps(BlockDriverState *bs,
                                           bool release_stored, Error **errp);
 int qcow2_reopen_bitmaps_ro(BlockDriverState *bs, Error **errp);
-bool qcow2_co_can_store_new_dirty_bitmap(BlockDriverState *bs,
-                                         const char *name,
-                                         uint32_t granularity,
-                                         Error **errp);
-int qcow2_co_remove_persistent_dirty_bitmap(BlockDriverState *bs,
-                                            const char *name,
-                                            Error **errp);
+bool coroutine_fn qcow2_co_can_store_new_dirty_bitmap(BlockDriverState *bs,
+                                                      const char *name,
+                                                      uint32_t granularity,
+                                                      Error **errp);
+int coroutine_fn qcow2_co_remove_persistent_dirty_bitmap(BlockDriverState *bs,
+                                                         const char *name,
+                                                         Error **errp);
 bool qcow2_supports_persistent_dirty_bitmap(BlockDriverState *bs);
 uint64_t qcow2_get_persistent_dirty_bitmap_size(BlockDriverState *bs,
                                                 uint32_t cluster_size);
block/qed.c +1 -1
index 40943e679b..9114cde42f 100644
@@ -563,7 +563,7 @@ static int bdrv_qed_open(BlockDriverState *bs, QDict *options, int flags,
 
     bdrv_qed_init_state(bs);
     if (qemu_in_coroutine()) {
-        bdrv_qed_open_entry(&qoc);
+        __allow_coroutine_fn_call(bdrv_qed_open_entry(&qoc));
     } else {
         assert(qemu_get_current_aio_context() == qemu_get_aio_context());
         qemu_coroutine_enter(qemu_coroutine_create(bdrv_qed_open_entry, &qoc));
block/quorum.c +1 -1
index 9c0fbd79be..3a13bf1b1f 100644
@@ -233,7 +233,7 @@ static bool quorum_has_too_much_io_failed(QuorumAIOCB *acb)
     return false;
 }
 
-static int read_fifo_child(QuorumAIOCB *acb);
+static int coroutine_fn read_fifo_child(QuorumAIOCB *acb);
 
 static void quorum_copy_qiov(QEMUIOVector *dest, QEMUIOVector *source)
 {
block/ssh.c +3 -3
index a2dc646536..ceb4f4c5bc 100644
@@ -1129,9 +1129,9 @@ static coroutine_fn int ssh_co_readv(BlockDriverState *bs,
     return ret;
 }
 
-static int ssh_write(BDRVSSHState *s, BlockDriverState *bs,
-                     int64_t offset, size_t size,
-                     QEMUIOVector *qiov)
+static coroutine_fn int ssh_write(BDRVSSHState *s, BlockDriverState *bs,
+                                  int64_t offset, size_t size,
+                                  QEMUIOVector *qiov)
 {
     ssize_t r;
     size_t written;
block/throttle-groups.c +2 -1
index fb203c3ced..e9a14b6f2e 100644
@@ -337,7 +337,8 @@ static void schedule_next_request(ThrottleGroupMember *tgm, bool is_write)
     if (!must_wait) {
         /* Give preference to requests from the current tgm */
         if (qemu_in_coroutine() &&
-            throttle_group_co_restart_queue(tgm, is_write)) {
+            __allow_coroutine_fn_call(
+                throttle_group_co_restart_queue(tgm, is_write))) {
             token = tgm;
         } else {
             ThrottleTimers *tt = &token->throttle_timers;
include/block/block-hmp-cmds.h +1 -1
index 50ce0247c3..ba0593c440 100644
@@ -38,7 +38,7 @@ void hmp_nbd_server_add(Monitor *mon, const QDict *qdict);
 void hmp_nbd_server_remove(Monitor *mon, const QDict *qdict);
 void hmp_nbd_server_stop(Monitor *mon, const QDict *qdict);
 
-void hmp_block_resize(Monitor *mon, const QDict *qdict);
+void coroutine_fn hmp_block_resize(Monitor *mon, const QDict *qdict);
 void hmp_block_stream(Monitor *mon, const QDict *qdict);
 void hmp_block_passwd(Monitor *mon, const QDict *qdict);
 void hmp_block_set_io_throttle(Monitor *mon, const QDict *qdict);
include/block/block-io.h +3 -2
index fd25ffa9be..f4b183f3de 100644
@@ -83,12 +83,13 @@ void bdrv_aio_cancel(BlockAIOCB *acb);
 void bdrv_aio_cancel_async(BlockAIOCB *acb);
 
 /* sg packet commands */
-int bdrv_co_ioctl(BlockDriverState *bs, int req, void *buf);
+int coroutine_fn bdrv_co_ioctl(BlockDriverState *bs, int req, void *buf);
 
 /* Ensure contents are flushed to disk.  */
 int coroutine_fn bdrv_co_flush(BlockDriverState *bs);
 
-int bdrv_co_pdiscard(BdrvChild *child, int64_t offset, int64_t bytes);
+int coroutine_fn bdrv_co_pdiscard(BdrvChild *child, int64_t offset,
+                                  int64_t bytes);
 bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs);
 int bdrv_block_status(BlockDriverState *bs, int64_t offset,
                       int64_t bytes, int64_t *pnum, int64_t *map,
include/qemu/coroutine.h +10 -8
index 40a4037525..26445b3176 100644
@@ -289,7 +289,7 @@ void qemu_co_rwlock_init(CoRwlock *lock);
  * of a parallel writer, control is transferred to the caller of the current
  * coroutine.
  */
-void qemu_co_rwlock_rdlock(CoRwlock *lock);
+void coroutine_fn qemu_co_rwlock_rdlock(CoRwlock *lock);
 
 /**
  * Write Locks the CoRwlock from a reader.  This is a bit more efficient than
@@ -298,7 +298,7 @@ void qemu_co_rwlock_rdlock(CoRwlock *lock);
  * to the caller of the current coroutine; another writer might run while
  * @qemu_co_rwlock_upgrade blocks.
  */
-void qemu_co_rwlock_upgrade(CoRwlock *lock);
+void coroutine_fn qemu_co_rwlock_upgrade(CoRwlock *lock);
 
 /**
  * Downgrades a write-side critical section to a reader.  Downgrading with
@@ -306,20 +306,20 @@ void qemu_co_rwlock_upgrade(CoRwlock *lock);
  * followed by @qemu_co_rwlock_rdlock.  This makes it more efficient, but
  * may also sometimes be necessary for correctness.
  */
-void qemu_co_rwlock_downgrade(CoRwlock *lock);
+void coroutine_fn qemu_co_rwlock_downgrade(CoRwlock *lock);
 
 /**
  * Write Locks the mutex. If the lock cannot be taken immediately because
  * of a parallel reader, control is transferred to the caller of the current
  * coroutine.
  */
-void qemu_co_rwlock_wrlock(CoRwlock *lock);
+void coroutine_fn qemu_co_rwlock_wrlock(CoRwlock *lock);
 
 /**
  * Unlocks the read/write lock and schedules the next coroutine that was
  * waiting for this lock to be run.
  */
-void qemu_co_rwlock_unlock(CoRwlock *lock);
+void coroutine_fn qemu_co_rwlock_unlock(CoRwlock *lock);
 
 typedef struct QemuCoSleep {
     Coroutine *to_wake;
@@ -391,8 +391,9 @@ void qemu_coroutine_dec_pool_size(unsigned int additional_pool_size);
  * The same interface as qemu_sendv_recvv(), with added yielding.
  * XXX should mark these as coroutine_fn
  */
-ssize_t qemu_co_sendv_recvv(int sockfd, struct iovec *iov, unsigned iov_cnt,
-                            size_t offset, size_t bytes, bool do_send);
+ssize_t coroutine_fn qemu_co_sendv_recvv(int sockfd, struct iovec *iov,
+                                         unsigned iov_cnt, size_t offset,
+                                         size_t bytes, bool do_send);
 #define qemu_co_recvv(sockfd, iov, iov_cnt, offset, bytes) \
   qemu_co_sendv_recvv(sockfd, iov, iov_cnt, offset, bytes, false)
 #define qemu_co_sendv(sockfd, iov, iov_cnt, offset, bytes) \
@@ -401,7 +402,8 @@ ssize_t qemu_co_sendv_recvv(int sockfd, struct iovec *iov, unsigned iov_cnt,
 /**
  * The same as above, but with just a single buffer
  */
-ssize_t qemu_co_send_recv(int sockfd, void *buf, size_t bytes, bool do_send);
+ssize_t coroutine_fn qemu_co_send_recv(int sockfd, void *buf, size_t bytes,
+                                       bool do_send);
 #define qemu_co_recv(sockfd, buf, bytes) \
   qemu_co_send_recv(sockfd, buf, bytes, false)
 #define qemu_co_send(sockfd, buf, bytes) \
Signature · 1 line
2.37.1
#17 lore raw

RFC v2 7/10 static-analyzer: Enforce coroutine_fn restrictions on function pointers

In reply to Alberto Faria

Extend static-analyzer.py's "coroutine_fn" check to enforce coroutine_fn restrictions on function pointer operations.

Invalid operations include assigning a coroutine_fn value to a non-coroutine_fn function pointer, and invoking a coroutine_fn function pointer from a non-coroutine_fn function.

---
 static_analyzer/__init__.py     |  27 ++++++++
 static_analyzer/coroutine_fn.py | 115 ++++++++++++++++++++++++++++++--
 2 files changed, 138 insertions(+), 4 deletions(-)
static_analyzer/__init__.py +27 -0
index 5abdbd21a3..90992d3500 100644
@@ -24,6 +24,8 @@
     Cursor,
     CursorKind,
     SourceLocation,
+    SourceRange,
+    TokenGroup,
     TranslationUnit,
     TypeKind,
     conf,
@@ -117,6 +119,31 @@ def actual_visitor(node: Cursor, parent: Cursor, client_data: None) -> int:
 # Node predicates
 
 
+def is_binary_operator(node: Cursor, operator: str) -> bool:
+    return (
+        node.kind == CursorKind.BINARY_OPERATOR
+        and get_binary_operator_spelling(node) == operator
+    )
+
+
+def get_binary_operator_spelling(node: Cursor) -> Optional[str]:
+
+    assert node.kind == CursorKind.BINARY_OPERATOR
+
+    [left, right] = node.get_children()
+
+    op_range = SourceRange.from_locations(left.extent.end, right.extent.start)
+
+    tokens = list(TokenGroup.get_tokens(node.translation_unit, op_range))
+    if not tokens:
+        # Can occur when left and right children extents overlap due to
+        # misparsing.
+        return None
+
+    [op_token, *_] = tokens
+    return op_token.spelling
+
+
 def might_have_attribute(node: Cursor, attr: Union[CursorKind, str]) -> bool:
     """
     Check whether any of `node`'s children are an attribute of the given kind,
static_analyzer/coroutine_fn.py +111 -4

145 lines not on this page · raw message

Signature · 1 line
2.37.1
#18 lore raw

RFC v2 8/10 Fix some bad coroutine_fn indirect calls and pointer assignments

In reply to Alberto Faria

These problems were found by static-analyzer.py.

Not all occurrences of these problems were fixed.

---
 block/backup.c                   |  2 +-
 include/block/block_int-common.h | 12 +++++-------
 2 files changed, 6 insertions(+), 8 deletions(-)
block/backup.c +1 -1
index b2b649e305..6a9ad97a53 100644
@@ -309,7 +309,7 @@ static void coroutine_fn backup_pause(Job *job)
     }
 }
 
-static void coroutine_fn backup_set_speed(BlockJob *job, int64_t speed)
+static void backup_set_speed(BlockJob *job, int64_t speed)
 {
     BackupBlockJob *s = container_of(job, BackupBlockJob, common);
 
include/block/block_int-common.h +5 -7
index 8947abab76..16c45d1262 100644
@@ -731,13 +731,11 @@ struct BlockDriver {
     void coroutine_fn (*bdrv_co_drain_end)(BlockDriverState *bs);
 
     bool (*bdrv_supports_persistent_dirty_bitmap)(BlockDriverState *bs);
-    bool (*bdrv_co_can_store_new_dirty_bitmap)(BlockDriverState *bs,
-                                               const char *name,
-                                               uint32_t granularity,
-                                               Error **errp);
-    int (*bdrv_co_remove_persistent_dirty_bitmap)(BlockDriverState *bs,
-                                                  const char *name,
-                                                  Error **errp);
+    bool coroutine_fn (*bdrv_co_can_store_new_dirty_bitmap)(
+        BlockDriverState *bs, const char *name, uint32_t granularity,
+        Error **errp);
+    int coroutine_fn (*bdrv_co_remove_persistent_dirty_bitmap)(
+        BlockDriverState *bs, const char *name, Error **errp);
 };
 
 static inline bool block_driver_can_compress(BlockDriver *drv)
Signature · 1 line
2.37.1
#19 lore raw

RFC v2 9/10 block: Add no_coroutine_fn marker

In reply to Alberto Faria

When applied to a function, it advertises that it should not be called from coroutine_fn functions.

Make generated_co_wrapper evaluate to no_coroutine_fn, as coroutine_fn functions should instead directly call the coroutine_fn that backs the generated_co_wrapper.

Add a "no_coroutine_fn" check to static-analyzer.py that enforces no_coroutine_fn rules.

---
 include/block/block-common.h       |   2 +-
 include/qemu/coroutine.h           |  12 ++++
 static_analyzer/no_coroutine_fn.py | 111 +++++++++++++++++++++++++++++
 3 files changed, 124 insertions(+), 1 deletion(-)
 create mode 100644 static_analyzer/no_coroutine_fn.py
include/block/block-common.h +1 -1
index fdb7306e78..4b60c8c6f2 100644
@@ -42,7 +42,7 @@
  *
  * Read more in docs/devel/block-coroutine-wrapper.rst
  */
-#define generated_co_wrapper
+#define generated_co_wrapper no_coroutine_fn
 
 /* block.c */
 typedef struct BlockDriver BlockDriver;
include/qemu/coroutine.h +12 -0
index 26445b3176..c61dd2d3f7 100644
@@ -48,6 +48,18 @@
 #define coroutine_fn
 #endif
 
+/**
+ * Mark a function that should never be called from a coroutine context
+ *
+ * This typically means that there is an analogous, coroutine_fn function that
+ * should be used instead.
+ */
+#ifdef __clang__
+#define no_coroutine_fn __attribute__((__annotate__("no_coroutine_fn")))
+#else
+#define no_coroutine_fn
+#endif
+
 /**
  * This can wrap a call to a coroutine_fn from a non-coroutine_fn function and
  * suppress the static analyzer's complaints.
static_analyzer/no_coroutine_fn.py new file +111 -0

111 lines not on this page · raw message

Signature · 1 line
2.37.1
#20 lore raw

RFC v2 10/10 Fix some calls from coroutine_fn to no_coroutine_fn

In reply to Alberto Faria

These calls were found by static-analyzer.py.

Not all occurrences of this problem were fixed.

---
 block/commit.c         |  2 +-
 block/io.c             |  4 ++--
 block/mirror.c         |  4 ++--
 block/parallels.c      | 28 ++++++++++++++--------------
 block/qcow.c           | 10 +++++-----
 block/qcow2-snapshot.c |  6 +++---
 block/qcow2.c          | 24 ++++++++++++------------
 block/qed-table.c      |  2 +-
 block/qed.c            | 12 ++++++------
 block/vdi.c            | 17 +++++++++--------
 block/vhdx.c           |  8 ++++----
 block/vmdk.c           | 11 ++++++-----
 blockdev.c             |  2 +-
 13 files changed, 66 insertions(+), 64 deletions(-)
block/commit.c +1 -1
index 38571510cb..945945de05 100644
@@ -135,7 +135,7 @@ static int coroutine_fn commit_run(Job *job, Error **errp)
     }
 
     if (base_len < len) {
-        ret = blk_truncate(s->base, len, false, PREALLOC_MODE_OFF, 0, NULL);
+        ret = blk_co_truncate(s->base, len, false, PREALLOC_MODE_OFF, 0, NULL);
         if (ret) {
             return ret;
         }
block/io.c +2 -2
index c2ed14cedb..a7d16eae02 100644
@@ -2736,8 +2736,8 @@ int coroutine_fn bdrv_co_is_zero_fast(BlockDriverState *bs, int64_t offset,
         return 1;
     }
 
-    ret = bdrv_common_block_status_above(bs, NULL, false, false, offset,
-                                         bytes, &pnum, NULL, NULL, NULL);
+    ret = bdrv_co_common_block_status_above(bs, NULL, false, false, offset,
+                                            bytes, &pnum, NULL, NULL, NULL);
 
     if (ret < 0) {
         return ret;
block/mirror.c +2 -2
index 3c4ab1159d..3cbb610118 100644
@@ -921,8 +921,8 @@ static int coroutine_fn mirror_run(Job *job, Error **errp)
      * active layer. */
     if (s->base == blk_bs(s->target)) {
         if (s->bdev_length > target_length) {
-            ret = blk_truncate(s->target, s->bdev_length, false,
-                               PREALLOC_MODE_OFF, 0, NULL);
+            ret = blk_co_truncate(s->target, s->bdev_length, false,
+                                  PREALLOC_MODE_OFF, 0, NULL);
             if (ret < 0) {
                 goto immediate_exit;
             }
block/parallels.c +14 -14
index a229c06f25..46baea6387 100644
@@ -204,18 +204,18 @@ static int64_t allocate_clusters(BlockDriverState *bs, int64_t sector_num,
          * force the safer-but-slower fallocate.
          */
         if (s->prealloc_mode == PRL_PREALLOC_MODE_TRUNCATE) {
-            ret = bdrv_truncate(bs->file,
-                                (s->data_end + space) << BDRV_SECTOR_BITS,
-                                false, PREALLOC_MODE_OFF, BDRV_REQ_ZERO_WRITE,
-                                NULL);
+            ret = bdrv_co_truncate(bs->file,
+                                   (s->data_end + space) << BDRV_SECTOR_BITS,
+                                   false, PREALLOC_MODE_OFF,
+                                   BDRV_REQ_ZERO_WRITE, NULL);
             if (ret == -ENOTSUP) {
                 s->prealloc_mode = PRL_PREALLOC_MODE_FALLOCATE;
             }
         }
         if (s->prealloc_mode == PRL_PREALLOC_MODE_FALLOCATE) {
-            ret = bdrv_pwrite_zeroes(bs->file,
-                                     s->data_end << BDRV_SECTOR_BITS,
-                                     space << BDRV_SECTOR_BITS, 0);
+            ret = bdrv_co_pwrite_zeroes(bs->file,
+                                        s->data_end << BDRV_SECTOR_BITS,
+                                        space << BDRV_SECTOR_BITS, 0);
         }
         if (ret < 0) {
             return ret;
@@ -277,8 +277,8 @@ static coroutine_fn int parallels_co_flush_to_os(BlockDriverState *bs)
         if (off + to_write > s->header_size) {
             to_write = s->header_size - off;
         }
-        ret = bdrv_pwrite(bs->file, off, to_write, (uint8_t *)s->header + off,
-                          0);
+        ret = bdrv_co_pwrite(bs->file, off, to_write,
+                             (uint8_t *)s->header + off, 0);
         if (ret < 0) {
             qemu_co_mutex_unlock(&s->lock);
             return ret;
@@ -503,8 +503,8 @@ static int coroutine_fn parallels_co_check(BlockDriverState *bs,
              * In order to really repair the image, we must shrink it.
              * That means we have to pass exact=true.
              */
-            ret = bdrv_truncate(bs->file, res->image_end_offset, true,
-                                PREALLOC_MODE_OFF, 0, &local_err);
+            ret = bdrv_co_truncate(bs->file, res->image_end_offset, true,
+                                   PREALLOC_MODE_OFF, 0, &local_err);
             if (ret < 0) {
                 error_report_err(local_err);
                 res->check_errors++;
@@ -599,12 +599,12 @@ static int coroutine_fn parallels_co_create(BlockdevCreateOptions* opts,
     memset(tmp, 0, sizeof(tmp));
     memcpy(tmp, &header, sizeof(header));
 
-    ret = blk_pwrite(blk, 0, BDRV_SECTOR_SIZE, tmp, 0);
+    ret = blk_co_pwrite(blk, 0, BDRV_SECTOR_SIZE, tmp, 0);
     if (ret < 0) {
         goto exit;
     }
-    ret = blk_pwrite_zeroes(blk, BDRV_SECTOR_SIZE,
-                            (bat_sectors - 1) << BDRV_SECTOR_BITS, 0);
+    ret = blk_co_pwrite_zeroes(blk, BDRV_SECTOR_SIZE,
+                               (bat_sectors - 1) << BDRV_SECTOR_BITS, 0);
     if (ret < 0) {
         goto exit;
     }
block/qcow.c +5 -5
index 311aaa8705..7dc29358ba 100644
@@ -890,14 +890,14 @@ static int coroutine_fn qcow_co_create(BlockdevCreateOptions *opts,
     }
 
     /* write all the data */
-    ret = blk_pwrite(qcow_blk, 0, sizeof(header), &header, 0);
+    ret = blk_co_pwrite(qcow_blk, 0, sizeof(header), &header, 0);
     if (ret < 0) {
         goto exit;
     }
 
     if (qcow_opts->has_backing_file) {
-        ret = blk_pwrite(qcow_blk, sizeof(header), backing_filename_len,
-                         qcow_opts->backing_file, 0);
+        ret = blk_co_pwrite(qcow_blk, sizeof(header), backing_filename_len,
+                            qcow_opts->backing_file, 0);
         if (ret < 0) {
             goto exit;
         }
@@ -906,8 +906,8 @@ static int coroutine_fn qcow_co_create(BlockdevCreateOptions *opts,
     tmp = g_malloc0(BDRV_SECTOR_SIZE);
     for (i = 0; i < DIV_ROUND_UP(sizeof(uint64_t) * l1_size, BDRV_SECTOR_SIZE);
          i++) {
-        ret = blk_pwrite(qcow_blk, header_size + BDRV_SECTOR_SIZE * i,
-                         BDRV_SECTOR_SIZE, tmp, 0);
+        ret = blk_co_pwrite(qcow_blk, header_size + BDRV_SECTOR_SIZE * i,
+                            BDRV_SECTOR_SIZE, tmp, 0);
         if (ret < 0) {
             g_free(tmp);
             goto exit;
block/qcow2-snapshot.c +3 -3
index d1d46facbf..62e8a0335d 100644
@@ -441,9 +441,9 @@ int coroutine_fn qcow2_check_read_snapshot_table(BlockDriverState *bs,
     } QEMU_PACKED snapshot_table_pointer;
 
     /* qcow2_do_open() discards this information in check mode */
-    ret = bdrv_pread(bs->file, offsetof(QCowHeader, nb_snapshots),
-                     sizeof(snapshot_table_pointer), &snapshot_table_pointer,
-                     0);
+    ret = bdrv_co_pread(bs->file, offsetof(QCowHeader, nb_snapshots),
+                        sizeof(snapshot_table_pointer), &snapshot_table_pointer,
+                        0);
     if (ret < 0) {
         result->check_errors++;
         fprintf(stderr, "ERROR failed to read the snapshot table pointer from "
block/qcow2.c +12 -12
index d3dad0142e..524207fcfe 100644
@@ -1305,7 +1305,7 @@ static int coroutine_fn qcow2_do_open(BlockDriverState *bs, QDict *options,
     uint64_t l1_vm_state_index;
     bool update_header = false;
 
-    ret = bdrv_pread(bs->file, 0, sizeof(header), &header, 0);
+    ret = bdrv_co_pread(bs->file, 0, sizeof(header), &header, 0);
     if (ret < 0) {
         error_setg_errno(errp, -ret, "Could not read qcow2 header");
         goto fail;
@@ -1381,9 +1381,9 @@ static int coroutine_fn qcow2_do_open(BlockDriverState *bs, QDict *options,
     if (header.header_length > sizeof(header)) {
         s->unknown_header_fields_size = header.header_length - sizeof(header);
         s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
-        ret = bdrv_pread(bs->file, sizeof(header),
-                         s->unknown_header_fields_size,
-                         s->unknown_header_fields, 0);
+        ret = bdrv_co_pread(bs->file, sizeof(header),
+                            s->unknown_header_fields_size,
+                            s->unknown_header_fields, 0);
         if (ret < 0) {
             error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
                              "fields");
@@ -1578,8 +1578,8 @@ static int coroutine_fn qcow2_do_open(BlockDriverState *bs, QDict *options,
             ret = -ENOMEM;
             goto fail;
         }
-        ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_size * L1E_SIZE,
-                         s->l1_table, 0);
+        ret = bdrv_co_pread(bs->file, s->l1_table_offset, s->l1_size * L1E_SIZE,
+                            s->l1_table, 0);
         if (ret < 0) {
             error_setg_errno(errp, -ret, "Could not read L1 table");
             goto fail;
@@ -1696,8 +1696,8 @@ static int coroutine_fn qcow2_do_open(BlockDriverState *bs, QDict *options,
             ret = -EINVAL;
             goto fail;
         }
-        ret = bdrv_pread(bs->file, header.backing_file_offset, len,
-                         bs->auto_backing_file, 0);
+        ret = bdrv_co_pread(bs->file, header.backing_file_offset, len,
+                            bs->auto_backing_file, 0);
         if (ret < 0) {
             error_setg_errno(errp, -ret, "Could not read backing file name");
             goto fail;
@@ -3666,7 +3666,7 @@ qcow2_co_create(BlockdevCreateOptions *create_options, Error **errp)
             cpu_to_be64(QCOW2_INCOMPAT_EXTL2);
     }
 
-    ret = blk_pwrite(blk, 0, cluster_size, header, 0);
+    ret = blk_co_pwrite(blk, 0, cluster_size, header, 0);
     g_free(header);
     if (ret < 0) {
         error_setg_errno(errp, -ret, "Could not write qcow2 header");
@@ -3676,7 +3676,7 @@ qcow2_co_create(BlockdevCreateOptions *create_options, Error **errp)
     /* Write a refcount table with one refcount block */
     refcount_table = g_malloc0(2 * cluster_size);
     refcount_table[0] = cpu_to_be64(2 * cluster_size);
-    ret = blk_pwrite(blk, cluster_size, 2 * cluster_size, refcount_table, 0);
+    ret = blk_co_pwrite(blk, cluster_size, 2 * cluster_size, refcount_table, 0);
     g_free(refcount_table);
 
     if (ret < 0) {
@@ -3731,8 +3731,8 @@ qcow2_co_create(BlockdevCreateOptions *create_options, Error **errp)
     }
 
     /* Okay, now that we have a valid image, let's give it the right size */
-    ret = blk_truncate(blk, qcow2_opts->size, false, qcow2_opts->preallocation,
-                       0, errp);
+    ret = blk_co_truncate(blk, qcow2_opts->size, false,
+                          qcow2_opts->preallocation, 0, errp);
     if (ret < 0) {
         error_prepend(errp, "Could not resize image: ");
         goto out;
block/qed-table.c +1 -1
index 1cc844b1a5..aa203f2627 100644
@@ -100,7 +100,7 @@ static int coroutine_fn qed_write_table(BDRVQEDState *s, uint64_t offset,
     }
 
     if (flush) {
-        ret = bdrv_flush(s->bs);
+        ret = bdrv_co_flush(s->bs);
         if (ret < 0) {
             goto out;
         }
block/qed.c +6 -6
index 9114cde42f..72e95852de 100644
@@ -387,7 +387,7 @@ static int coroutine_fn bdrv_qed_do_open(BlockDriverState *bs, QDict *options,
     int64_t file_size;
     int ret;
 
-    ret = bdrv_pread(bs->file, 0, sizeof(le_header), &le_header, 0);
+    ret = bdrv_co_pread(bs->file, 0, sizeof(le_header), &le_header, 0);
     if (ret < 0) {
         error_setg(errp, "Failed to read QED header");
         return ret;
@@ -485,7 +485,7 @@ static int coroutine_fn bdrv_qed_do_open(BlockDriverState *bs, QDict *options,
         }
 
         /* From here on only known autoclear feature bits are valid */
-        bdrv_flush(bs->file->bs);
+        bdrv_co_flush(bs->file->bs);
     }
 
     s->l1_table = qed_alloc_table(s);
@@ -686,7 +686,7 @@ static int coroutine_fn bdrv_qed_co_create(BlockdevCreateOptions *opts,
      * The QED format associates file length with allocation status,
      * so a new file (which is empty) must have a length of 0.
      */
-    ret = blk_truncate(blk, 0, true, PREALLOC_MODE_OFF, 0, errp);
+    ret = blk_co_truncate(blk, 0, true, PREALLOC_MODE_OFF, 0, errp);
     if (ret < 0) {
         goto out;
     }
@@ -705,18 +705,18 @@ static int coroutine_fn bdrv_qed_co_create(BlockdevCreateOptions *opts,
     }
 
     qed_header_cpu_to_le(&header, &le_header);
-    ret = blk_pwrite(blk, 0, sizeof(le_header), &le_header, 0);
+    ret = blk_co_pwrite(blk, 0, sizeof(le_header), &le_header, 0);
     if (ret < 0) {
         goto out;
     }
-    ret = blk_pwrite(blk, sizeof(le_header), header.backing_filename_size,
+    ret = blk_co_pwrite(blk, sizeof(le_header), header.backing_filename_size,
                      qed_opts->backing_file, 0);
     if (ret < 0) {
         goto out;
     }
 
     l1_table = g_malloc0(l1_size);
-    ret = blk_pwrite(blk, header.l1_table_offset, l1_size, l1_table, 0);
+    ret = blk_co_pwrite(blk, header.l1_table_offset, l1_size, l1_table, 0);
     if (ret < 0) {
         goto out;
     }
block/vdi.c +9 -8
index e942325455..2ecf47216a 100644
@@ -664,7 +664,8 @@ vdi_co_pwritev(BlockDriverState *bs, int64_t offset, int64_t bytes,
              * so this full-cluster write does not overlap a partial write
              * of the same cluster, issued from the "else" branch.
              */
-            ret = bdrv_pwrite(bs->file, data_offset, s->block_size, block, 0);
+            ret = bdrv_co_pwrite(bs->file, data_offset, s->block_size, block,
+                                 0);
             qemu_co_rwlock_unlock(&s->bmap_lock);
         } else {
 nonallocating_write:
@@ -709,7 +710,7 @@ nonallocating_write:
         assert(VDI_IS_ALLOCATED(bmap_first));
         *header = s->header;
         vdi_header_to_le(header);
-        ret = bdrv_pwrite(bs->file, 0, sizeof(*header), header, 0);
+        ret = bdrv_co_pwrite(bs->file, 0, sizeof(*header), header, 0);
         g_free(header);
 
         if (ret < 0) {
@@ -726,8 +727,8 @@ nonallocating_write:
         base = ((uint8_t *)&s->bmap[0]) + bmap_first * SECTOR_SIZE;
         logout("will write %u block map sectors starting from entry %u\n",
                n_sectors, bmap_first);
-        ret = bdrv_pwrite(bs->file, offset * SECTOR_SIZE,
-                          n_sectors * SECTOR_SIZE, base, 0);
+        ret = bdrv_co_pwrite(bs->file, offset * SECTOR_SIZE,
+                             n_sectors * SECTOR_SIZE, base, 0);
     }
 
     return ret;
@@ -845,7 +846,7 @@ static int coroutine_fn vdi_co_do_create(BlockdevCreateOptions *create_options,
         vdi_header_print(&header);
     }
     vdi_header_to_le(&header);
-    ret = blk_pwrite(blk, offset, sizeof(header), &header, 0);
+    ret = blk_co_pwrite(blk, offset, sizeof(header), &header, 0);
     if (ret < 0) {
         error_setg(errp, "Error writing header");
         goto exit;
@@ -866,7 +867,7 @@ static int coroutine_fn vdi_co_do_create(BlockdevCreateOptions *create_options,
                 bmap[i] = VDI_UNALLOCATED;
             }
         }
-        ret = blk_pwrite(blk, offset, bmap_size, bmap, 0);
+        ret = blk_co_pwrite(blk, offset, bmap_size, bmap, 0);
         if (ret < 0) {
             error_setg(errp, "Error writing bmap");
             goto exit;
@@ -875,8 +876,8 @@ static int coroutine_fn vdi_co_do_create(BlockdevCreateOptions *create_options,
     }
 
     if (image_type == VDI_TYPE_STATIC) {
-        ret = blk_truncate(blk, offset + blocks * block_size, false,
-                           PREALLOC_MODE_OFF, 0, errp);
+        ret = blk_co_truncate(blk, offset + blocks * block_size, false,
+                              PREALLOC_MODE_OFF, 0, errp);
         if (ret < 0) {
             error_prepend(errp, "Failed to statically allocate file");
             goto exit;
block/vhdx.c +4 -4
index e10e78ebfd..f7dd4eb092 100644
@@ -2012,15 +2012,15 @@ static int coroutine_fn vhdx_co_create(BlockdevCreateOptions *opts,
     creator = g_utf8_to_utf16("QEMU v" QEMU_VERSION, -1, NULL,
                               &creator_items, NULL);
     signature = cpu_to_le64(VHDX_FILE_SIGNATURE);
-    ret = blk_pwrite(blk, VHDX_FILE_ID_OFFSET, sizeof(signature), &signature,
-                     0);
+    ret = blk_co_pwrite(blk, VHDX_FILE_ID_OFFSET, sizeof(signature), &signature,
+                        0);
     if (ret < 0) {
         error_setg_errno(errp, -ret, "Failed to write file signature");
         goto delete_and_exit;
     }
     if (creator) {
-        ret = blk_pwrite(blk, VHDX_FILE_ID_OFFSET + sizeof(signature),
-                         creator_items * sizeof(gunichar2), creator, 0);
+        ret = blk_co_pwrite(blk, VHDX_FILE_ID_OFFSET + sizeof(signature),
+                            creator_items * sizeof(gunichar2), creator, 0);
         if (ret < 0) {
             error_setg_errno(errp, -ret, "Failed to write creator field");
             goto delete_and_exit;
block/vmdk.c +6 -5
index fe07a54866..d7886a52e1 100644
@@ -1897,7 +1897,8 @@ static int vmdk_read_extent(VmdkExtent *extent, int64_t cluster_offset,
     cluster_buf = g_malloc(buf_bytes);
     uncomp_buf = g_malloc(cluster_bytes);
     BLKDBG_EVENT(extent->file, BLKDBG_READ_COMPRESSED);
-    ret = bdrv_pread(extent->file, cluster_offset, buf_bytes, cluster_buf, 0);
+    ret = bdrv_co_pread(extent->file, cluster_offset, buf_bytes, cluster_buf,
+                        0);
     if (ret < 0) {
         goto out;
     }
@@ -2142,8 +2143,8 @@ vmdk_co_pwritev_compressed(BlockDriverState *bs, int64_t offset, int64_t bytes,
                 return length;
             }
             length = QEMU_ALIGN_UP(length, BDRV_SECTOR_SIZE);
-            ret = bdrv_truncate(s->extents[i].file, length, false,
-                                PREALLOC_MODE_OFF, 0, NULL);
+            ret = bdrv_co_truncate(s->extents[i].file, length, false,
+                                   PREALLOC_MODE_OFF, 0, NULL);
             if (ret < 0) {
                 return ret;
             }
@@ -2584,7 +2585,7 @@ static int coroutine_fn vmdk_co_do_create(int64_t size,
         desc_offset = 0x200;
     }
 
-    ret = blk_pwrite(blk, desc_offset, desc_len, desc, 0);
+    ret = blk_co_pwrite(blk, desc_offset, desc_len, desc, 0);
     if (ret < 0) {
         error_setg_errno(errp, -ret, "Could not write description");
         goto exit;
@@ -2592,7 +2593,7 @@ static int coroutine_fn vmdk_co_do_create(int64_t size,
     /* bdrv_pwrite write padding zeros to align to sector, we don't need that
      * for description file */
     if (desc_offset == 0) {
-        ret = blk_truncate(blk, desc_len, false, PREALLOC_MODE_OFF, 0, errp);
+        ret = blk_co_truncate(blk, desc_len, false, PREALLOC_MODE_OFF, 0, errp);
         if (ret < 0) {
             goto exit;
         }
blockdev.c +1 -1
index 9230888e34..beeb51211a 100644
@@ -2453,7 +2453,7 @@ void coroutine_fn qmp_block_resize(bool has_device, const char *device,
     bdrv_co_unlock(bs);
 
     old_ctx = bdrv_co_enter(bs);
-    blk_truncate(blk, size, false, PREALLOC_MODE_OFF, 0, errp);
+    blk_co_truncate(blk, size, false, PREALLOC_MODE_OFF, 0, errp);
     bdrv_co_leave(bs, old_ctx);
 
     bdrv_co_lock(bs);
Signature · 1 line
2.37.1
#21 lore raw
In reply to Alberto Faria

Hi

Quoted 124 lines · Alberto Faria

This series introduces a static analyzer for QEMU. It consists of a single static-analyzer.py script that relies on libclang's Python bindings, and provides a common framework on which arbitrary static analysis checks can be developed and run against QEMU's code base.

Summary of the series:

- Patch 1 adds the base static analyzer, along with a simple check that finds static functions whose return value is never used, and patch 2 fixes many occurrences of this.

- Patch 3 introduces support for output-comparison check tests, and adds some tests to the abovementioned check.

- Patch 4 makes the analyzer skip checks on a translation unit when it hasn't been modified since the last time those checks passed.

- Patch 5 adds a check to ensure that non-coroutine_fn functions don't perform direct calls to coroutine_fn functions, and patch 6 fixes some violations of this rule.

- Patch 7 adds a check to ensure that operations on coroutine_fn pointers make sense, like assignment and indirect calls, and patch 8 fixes some problems detected by the check. (Implementing this check properly is complicated, since AFAICT annotation attributes cannot be applied directly to types. This part still needs a lot of work.)

- Patch 9 introduces a no_coroutine_fn marker for functions that should not be called from coroutines, makes generated_co_wrapper evaluate to no_coroutine_fn, and adds a check enforcing this rule. Patch 10 fixes some violations that it finds.

The current primary motivation for this work is enforcing rules around block layer coroutines, which is why most of the series focuses on that. However, the static analyzer is intended to be sufficiently generic to satisfy other present and future QEMU static analysis needs.

Performance isn't great, but with some more optimization, the analyzer should be fast enough to be used iteratively during development, given that it avoids reanalyzing unmodified translation units, and that users can restrict the set of translation units under consideration. It should also be fast enough to run in CI (?).

Consider a small QEMU configuration and build (all commands were run on the same 12-thread laptop):

    $ cd build && time ../configure --target-list=x86_64-softmmu && cd ..
    [...]
    real    0m17.232s
    user    0m13.261s
    sys     0m3.895s
    $ time make -C build -j $(nproc) all
    [...]
    real    2m39.029s
    user    14m49.370s
    sys     1m57.364s
    $ time make -C build -j $(nproc) check
    [...]
    real    2m46.349s
    user    6m4.718s
    sys     4m15.660s

We can run the static analyzer against all translation units enabled in this configuration:

    $ time ./static-analyzer.py build
    util/qemu-coroutine.c:122:23: non-coroutine_fn function calls coroutine_fn qemu_coroutine_self()
    io/channel.c:152:17: non-coroutine_fn function calls coroutine_fn qio_channel_yield()
    [...]
    Analyzed 1649 translation units in 520.3 seconds.
    real    8m42.342s
    user    95m51.759s
    sys     0m21.576s

You will need libclang's Python bindings to run this. Try dnf install python3-clang or apt install python3-clang.

It takes around 1 to 2 seconds for the analyzer to load the compilation database, determine which translation units to analyze, etc. The durations reported by the analyzer itself don't include those steps, which is why they differ from what time reports.

We can also analyze only some of the translation units:

    $ time ./static-analyzer.py build block
    block/raw-format.c:420:12: non-coroutine_fn function calls coroutine_fn bdrv_co_ioctl()
    block/blkverify.c:266:12: non-coroutine_fn function calls coroutine_fn bdrv_co_flush()
    [...]
    Analyzed 21 translation units (58 other were up-to-date) in 5.8 seconds.
    real    0m7.031s
    user    0m40.951s
    sys     0m1.299s

Since the previous command had already analyzed all translation units, only the ones that had problems were reanalyzed.

Now skipping all the actual checks, but still parsing and building the AST for each translation unit, and adding --force to reanalyze all translation units:

    $ time ./static-analyzer.py build --force --skip-checks
    Analyzed 1649 translation units in 41.2 seconds.
    real    0m42.296s
    user    7m14.256s
    sys     0m15.803s

And now running a single check:

    $ time ./static-analyzer.py build --force --check return-value-never-used
    Analyzed 1649 translation units in 157.6 seconds.
    real    2m38.759s
    user    29m28.930s
    sys     0m17.968s
Quoted 6 lines

TODO:
- Run in GitLab CI (?).
- Finish the "coroutine_fn" check.
- Add check tests where missing.
- Avoid redundant AST traversals while keeping checks modular.
- More optimization.

Great work so far! This seems easier to hack than my attempt to use clang-tidy to write some qemu checks
(https://github.com/elmarco/clang-tools-extra)

The code seems quite generic, I wonder if such a tool in python wasn't already developed (I couldn't find it easily searching on github).

Why not make it standalone from qemu? Similar to
https://gitlab.com/qemu-project/python-qemu-qmp, you could have your own release management, issue tracker, code formatting, license, CI etc. (you should add copyright header in each file, at least that's pretty much required in qemu nowadays). You could also have the qemu-specific checks there imho (clang-tidy has google & llvm specific checks too)

It would be nice to write some docs, in docs/devel/testing.rst and some new meson/ninja/make targets to run the checks directly from a build tree.

On fc36, I had several dependencies I needed to install manually (imho they should have been pulled by python3-clang), but more annoyingly I got:
clang.cindex.LibclangError: libclang.so: cannot open shared object
file: No such file or directory. To provide a path to libclang use Config.set_library_path() or Config.set_library_file().

clang-libs doesn't install libclang.so, I wonder why. I made a link manually and it works, but it's probably incorrect. I'll try to open issues for the clang packaging.

cheers

Quoted 133 lines

v2:
- Fix parsing of compilation database commands.
- Reorganize checks and split them into separate modules.
- Make "return-value-never-used" ignore __attribute__((unused)) funcs.
- Add a visitor() abstraction wrapping clang_visitChildren() that is faster than using Cursor.get_children() with recursion.
- Add support for implementing tests for checks, and add some tests to "return-value-never-used".
- Use dependency information provided by Ninja to skip checks on translation units that haven't been modified since they last passed those checks.
- Ignore translation units from git submodules.
- And more.

Alberto Faria (10):
Add an extensible static analyzer
Drop unused static function return values
static-analyzer: Support adding tests to checks
static-analyzer: Avoid reanalyzing unmodified translation units
static-analyzer: Enforce coroutine_fn restrictions for direct calls Fix some direct calls from non-coroutine_fn to coroutine_fn
static-analyzer: Enforce coroutine_fn restrictions on function
pointers
Fix some bad coroutine_fn indirect calls and pointer assignments
block: Add no_coroutine_fn marker
Fix some calls from coroutine_fn to no_coroutine_fn

 accel/kvm/kvm-all.c                        |  12 +-
 accel/tcg/plugin-gen.c                     |   9 +-
 accel/tcg/translate-all.c                  |   9 +-
 audio/audio.c                              |   5 +-
 block.c                                    |   2 +-
 block/backup.c                             |   2 +-
 block/block-copy.c                         |   4 +-
 block/commit.c                             |   2 +-
 block/dirty-bitmap.c                       |   6 +-
 block/file-posix.c                         |   6 +-
 block/io.c                                 |  52 +-
 block/mirror.c                             |   4 +-
 block/monitor/block-hmp-cmds.c             |   2 +-
 block/nvme.c                               |   3 +-
 block/parallels.c                          |  28 +-
 block/qcow.c                               |  10 +-
 block/qcow2-bitmap.c                       |   6 +-
 block/qcow2-snapshot.c                     |   6 +-
 block/qcow2.c                              |  38 +-
 block/qcow2.h                              |  14 +-
 block/qed-table.c                          |   2 +-
 block/qed.c                                |  14 +-
 block/quorum.c                             |   7 +-
 block/ssh.c                                |   6 +-
 block/throttle-groups.c                    |   3 +-
 block/vdi.c                                |  17 +-
 block/vhdx.c                               |   8 +-
 block/vmdk.c                               |  11 +-
 block/vpc.c                                |   4 +-
 block/vvfat.c                              |  11 +-
 blockdev.c                                 |   2 +-
 chardev/char-ringbuf.c                     |   4 +-
 contrib/ivshmem-server/main.c              |   4 +-
 contrib/vhost-user-blk/vhost-user-blk.c    |   5 +-
 dump/dump.c                                |   4 +-
 fsdev/virtfs-proxy-helper.c                |   3 +-
 gdbstub.c                                  |  18 +-
 hw/audio/intel-hda.c                       |   7 +-
 hw/audio/pcspk.c                           |   7 +-
 hw/char/virtio-serial-bus.c                |  14 +-
 hw/display/cirrus_vga.c                    |   5 +-
 hw/hyperv/vmbus.c                          |  10 +-
 hw/i386/intel_iommu.c                      |  28 +-
 hw/i386/pc_q35.c                           |   5 +-
 hw/ide/pci.c                               |   4 +-
 hw/net/rtl8139.c                           |   3 +-
 hw/net/virtio-net.c                        |   6 +-
 hw/net/vmxnet3.c                           |   3 +-
 hw/nvme/ctrl.c                             |  17 +-
 hw/nvram/fw_cfg.c                          |   3 +-
 hw/scsi/megasas.c                          |   6 +-
 hw/scsi/mptconfig.c                        |   7 +-
 hw/scsi/mptsas.c                           |  14 +-
 hw/scsi/scsi-bus.c                         |   6 +-
 hw/usb/dev-audio.c                         |  13 +-
 hw/usb/hcd-ehci.c                          |   6 +-
 hw/usb/hcd-ohci.c                          |   4 +-
 hw/usb/hcd-xhci.c                          |  56 +-
 hw/vfio/common.c                           |  21 +-
 hw/virtio/vhost-vdpa.c                     |   3 +-
 hw/virtio/vhost.c                          |  11 +-
 hw/virtio/virtio-iommu.c                   |   4 +-
 hw/virtio/virtio-mem.c                     |   9 +-
 include/block/block-common.h               |   2 +-
 include/block/block-hmp-cmds.h             |   2 +-
 include/block/block-io.h                   |   5 +-
 include/block/block_int-common.h           |  12 +-
 include/qemu/coroutine.h                   |  43 +-
 io/channel-command.c                       |  10 +-
 migration/migration.c                      |  12 +-
 net/dump.c                                 |  16 +-
 net/vhost-vdpa.c                           |   8 +-
 qemu-img.c                                 |   6 +-
 qga/commands-posix-ssh.c                   |  10 +-
 softmmu/physmem.c                          |  18 +-
 softmmu/qtest.c                            |   5 +-
 static-analyzer.py                         | 801 +++++++++++++++++++++
 static_analyzer/__init__.py                | 348 +++++++++
 static_analyzer/coroutine_fn.py            | 280 +++++++
 static_analyzer/no_coroutine_fn.py         | 111 +++
 static_analyzer/return_value_never_used.py | 220 ++++++
 subprojects/libvduse/libvduse.c            |  12 +-
 subprojects/libvhost-user/libvhost-user.c  |  24 +-
 target/i386/host-cpu.c                     |   3 +-
 target/i386/kvm/kvm.c                      |  19 +-
 tcg/optimize.c                             |   3 +-
 tests/qtest/libqos/malloc.c                |   5 +-
 tests/qtest/libqos/qgraph.c                |   3 +-
 tests/qtest/test-x86-cpuid-compat.c        |   8 +-
 tests/qtest/virtio-9p-test.c               |   6 +-
 tests/unit/test-aio-multithread.c          |   5 +-
 tests/vhost-user-bridge.c                  |  19 +-
 ui/vnc.c                                   |  23 +-
 util/aio-posix.c                           |   7 +-
 util/uri.c                                 |  18 +-
 95 files changed, 2160 insertions(+), 519 deletions(-)
 create mode 100755 static-analyzer.py
 create mode 100644 static_analyzer/__init__.py
 create mode 100644 static_analyzer/coroutine_fn.py
 create mode 100644 static_analyzer/no_coroutine_fn.py
 create mode 100644 static_analyzer/return_value_never_used.py

--
2.37.1

#22 lore raw
Quoted 9 lines · Marc-André Lureau

Hi

Great work so far! This seems easier to hack than my attempt to use clang-tidy to write some qemu checks
(https://github.com/elmarco/clang-tools-extra)

The code seems quite generic, I wonder if such a tool in python wasn't already developed (I couldn't find it easily searching on github).

Quoted 7 lines

Why not make it standalone from qemu? Similar to
https://gitlab.com/qemu-project/python-qemu-qmp, you could have your own release management, issue tracker, code formatting, license, CI etc. (you should add copyright header in each file, at least that's pretty much required in qemu nowadays). You could also have the qemu-specific checks there imho (clang-tidy has google & llvm specific checks too)

This is an interesting idea. Indeed, the analyzer is essentially a more easily extensible, Python version of clang-tidy (without the big built-in library of checks).

I think I'll continue working on it embedded in QEMU for now, mostly because it depends on some aspects of the build system, and gradually generalize it to a point where it could be made into a standalone thing.

Quoted 3 lines

It would be nice to write some docs, in docs/devel/testing.rst and some new meson/ninja/make targets to run the checks directly from a build tree.

Sounds good, I'll work on it.

Quoted 10 lines

On fc36, I had several dependencies I needed to install manually (imho they should have been pulled by python3-clang), but more annoyingly I got:
clang.cindex.LibclangError: libclang.so: cannot open shared object
file: No such file or directory. To provide a path to libclang use Config.set_library_path() or Config.set_library_file().

clang-libs doesn't install libclang.so, I wonder why. I made a link manually and it works, but it's probably incorrect. I'll try to open issues for the clang packaging.

That's strange. Thanks for looking into this.

Alberto

#23 lore raw

Hi

Quoted 10 lines · Alberto Faria
Quoted 7 lines · Marc-André Lureau

On fc36, I had several dependencies I needed to install manually (imho they should have been pulled by python3-clang), but more annoyingly I got:
clang.cindex.LibclangError: libclang.so: cannot open shared object
file: No such file or directory. To provide a path to libclang use Config.set_library_path() or Config.set_library_file().

Quoted 5 lines
Quoted 3 lines

clang-libs doesn't install libclang.so, I wonder why. I made a link manually and it works, but it's probably incorrect. I'll try to open issues for the clang packaging.

That's strange. Thanks for looking into this.

No that's normal, I just got confused. clang-devel provides it.

However, I opened https://bugzilla.redhat.com/show_bug.cgi?id=2115362
"python3-clang depends on libclang.so"

maintainer
#24 lore raw
In reply to Alberto Faria
Quoted 5 lines · Alberto Faria

Performance isn't great, but with some more optimization, the analyzer should be fast enough to be used iteratively during development, given that it avoids reanalyzing unmodified translation units, and that users can restrict the set of translation units under consideration. It should also be fast enough to run in CI (?).

I took a look again today, and the results are indeed very nice (I sent a patch series with the code changes from this one).

The performance is not great as you point out. :/ I made a couple attempts at optimizing it, for example the "actual_visitor" can be written in a more efficient way like this, to avoid the stack:

@CFUNCTYPE(c_int, Cursor, Cursor, py_object)
def actual_visitor(node: Cursor, parent: Cursor, client_data:
Cursor) -> int:

try:
node.parent = client_data

# several clang.cindex methods need Cursor._tu to be set node._tu = client_data._tu
r = visitor(node)
if r is VisitorResult.RECURSE:
return 0 \
if conf.lib.clang_visitChildren(node,
actual_visitor, node) != 0 \
else 1
else:
return r.value

except BaseException as e:
# Exceptions can't cross into C. Stash it, abort the visitation, and # reraise it.
if exception is None:
exception = e

return VisitorResult.BREAK.value

root.parent = None
result = conf.lib.clang_visitChildren(root, actual_visitor, root)

if exception is not None:
raise exception

return result == 0

However, it seems like a lost battle. :( Some of the optimizations are stuff that you should just not have to do, for example only invoking "x.kind" once (because it's a property not a field). Another issue is that the bindings are incomplete, for example if you have a ForStmt you just get a Cursor and you are not able to access individual expressions. As a result, this for example is wrong in the return-value-never-used test:

                static int f(void) { return 42; }
                static void g(void) {
                    for (f(); ; ) { } /* should warn, it doesn't */
                }

and I couldn't fix it without breaking "for (; f(); )" because AFAICT the two are indistinguishable.

On top of this, using libclang directly should make it possible to use the Matcher API (the same one used by clang-match), instead of writing everything by hand. It may not be that useful though in practice, but it's a possibility.

Paolo

#25 lore raw

On Freitag, 14. Oktober 2022 00:00:58 CEST Paolo Bonzini wrote:
[...]

Quoted 8 lines

However, it seems like a lost battle. :( Some of the optimizations are stuff that you should just not have to do, for example only invoking "x.kind" once (because it's a property not a field). Another issue is that the bindings are incomplete, for example if you have a ForStmt you just get a Cursor and you are not able to access individual expressions. As a result, this for example is wrong in the return-value-never-used test:

Quoted 7 lines
                static int f(void) { return 42; }
                static void g(void) {
                    for (f(); ; ) { } /* should warn, it doesn't */
                }

and I couldn't fix it without breaking "for (; f(); )" because AFAICT the two are indistinguishable.

You mean accessing the for loop's init expression, condition expression, increment statement? AFAICS those are accessible already by calling get_children() on the for statement cursor:
https://github.com/llvm/llvm-project/blob/main/clang/bindings/python/clang/cindex.py#L1833

I just made a quick test with a short .c file and their demo script:
https://github.com/llvm/llvm-project/blob/main/clang/bindings/python/examples/cindex/cindex-dump.py

And I got all those components of the for loop as children of the for cursor.

Best regards,
Christian Schoenebeck