Skip to content

About

Bazel tools to analyze C/C++ metadata and target dependencies

Resources

Stars

19 stars

Watchers

5 watching

Forks

Repository files navigation

Bazel C/C++ Metadata Analyzer (bazel_cc_meta)

Bazel tools to analyze C/C++ metadata and target dependencies.

The objective of this library is to enable Bazel projects to generate helpful metadata around the C/C++ targets and their dependencies. Core capabilities include:

  • Generate a compile_commands.json file for all C/C++ sources involved in a project's builds.
    • The compile_commands.json captures compilation commands and enables use of clangd (LSP) and other clang-based tools.
  • Gather a mapping of targets to "exports", aka includable headers, such that missing direct dependencies can be automatically found.
  • Analyze direct dependencies of targets compared to included headers to add missing ones or remove unused ones.

Additional features include:

  • Generate a clang_tidy_fixes.yaml that combines all clang-tidy fixes (--export-fixes).
    • This combined report is generated by running clang-tidy in an aspect (that depends on the main cc metadata aspect).
  • Useful script to apply the fixes reported by clang-tidy (like clang-apply-replacements, but actually usable).

Getting started

MODULE.bazel (recommended)

Importing into a Bazel module is done as usual. Some examples are given below.

Release version from Bazel Central Registry (recommended)

Put the following into your MODULE.bazel file (with X.Y.Z being the latest version on the registry):

bazel_dep(name = "bazel_cc_meta", version = "X.Y.Z")

Release version as http_archive

Put the following into your MODULE.bazel file (filling in version numbers and SHA, see releases page)

http_archive = use_repo_rule("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")

bazel_dep(name = "bazel_skylib", version = "<insert appropriate version number>")
bazel_dep(name = "rules_python", version = "<insert appropriate version number>")
bazel_dep(name = "rules_cc", version = "<insert appropriate version number>")
bazel_dep(name = "rules_shell", version = "<insert appropriate version number>")
bazel_dep(name = "buildozer", version = "<insert appropriate version number>")

http_archive(
    name = "bazel_cc_meta",
    integrity = "<insert sha integrity check>",
    strip_prefix = "bazel_cc_meta-X.Y.Z",
    urls = ["https://github.com/mikael-s-persson/bazel_cc_meta/archive/refs/tags/vX.Y.Z.tar.gz"],
)

Git commit as git_override

Put the following into your MODULE.bazel file

bazel_dep(name = "bazel_cc_meta", version = "0.0.0")
git_override(
    module_name = "bazel_cc_meta",
    commit = <commit_you_are_interested_in>,
    remote = "https://github.com/mikael-s-persson/bazel_cc_meta",
)

Usage

This section describes the basic usage and setup of bazel_cc_meta to generate the metadata. The next section describes additional features for linting.

Default aspect

The most basic usage of bazel_cc_meta is to use the default configurations (aspect).

  • Default aspect: @bazel_cc_meta//:defs.bzl%default_cc_meta_aspect
  • Default refresh "all" tool: @bazel_cc_meta//cc_meta:refresh_all
  • Fix dependency tool: @bazel_cc_meta//cc_meta:fix_deps

If default tools (aspect or refresh tool) are not appropriate (see Known issues), custom configurations can be created, see Custom aspects and Custom deviations sections.

To use the default tools, use bazel run to invoke the refresh tool:

bazel run [build_options] @bazel_cc_meta//cc_meta:refresh_all -- [build_options]

Where build_options should be the build configuration options you need when building your targets, e.g., -c opt --config=clang. The trailing build_options are the options that the script will use when invoking bazel under-the-hood, so those are the options that truly determine what gets analyzed (technically, the first set is just the option for running the script). Unless you are cross-compiling, they generally should match, mostly to avoid unnecessarily invalidating the build cache. In short, they should usually match and match how you typically build your project.

The refresh script runs the "aspect" on the build graph spawning from //... and generates three files:

  • compile_commands.json: Compilation commands for all your sources (and "external" sources) and enables the use of clangd (LSP) and other clang-based tools.
  • target_exports.json: Maps all discoverable targets to their set of "exports", aka public headers (including textual headers). Headers might be listed multiple times with every alternative path with which they could be included.
  • dependency_issues.json: Summary of dependency issues found in your targets, such as missing dependencies (aka "not_found" headers) and unused ones.

Running the aspect on your build graph does not require your code's actual build artifacts and will only run on targets whose aspect output are not up-to-date. Thus, it's usually very quick after the first run, benefitting from Bazel's powerful caching system.

To automatically fix the issues listed in dependency_issues.json, run the fix_deps tool:

bazel run [build_options] @bazel_cc_meta//cc_meta:fix_deps

Pre-commit hook: The examples directory also includes a example bash script that can be used to run fix_deps as a pre-commit hook (see examples/precommit_fix.sh).

The build_options don't really matter here, as fix_deps does not build anything and it's just a vanilla python script, but reusing your usual build options avoid unnecessary cache invalidation. Under-the-hood, it uses buildozer to fix issues with the build rules, and it's therefore subject to buildozer's shortcomings (see Known issues).

This is pretty much it. But, given how creative C++ programmers are at creating convoluted build rules that defeat any sane analysis tool, there is a good chance that customizations will be needed to work around those issues (see Known issues).

Tags

Certain tags can by used in the tags attribute of targets to tell bazel_cc_meta to treat certain targets differently.

  • alwayslink = True attribute will cause the target to be considered as always used if it is being depended upon, so it won't be removed by the fixer, since that is generally the intention with these targets.
  • tags = ["cc_meta_skip"] this tag causes the target to be skipped by bazel_cc_meta aspects. Outputs will still be produced for basic information like exports and compile commands, but crucially, preprocessing will not be attempted to list included files (some source files are too convoluted or arcane for this step to work).
  • tags = ["cc_meta_forward_exports"] this tag causes the exports of the target's direct dependencies to be forward or attributed to this target. Note that this is not recursive.

If you need some of the above behaviors to apply to targets not under your control, you will have to create a custom deviations set (see following sections). But if you can, using these tags will perform better (not by much) and be cleaner.

Custom aspects

The mechanics of this tool rely on three components:

  • A Bazel Aspect that analyzes the targets. An aspect is like a shadow build graph that can be "tacked on" to build rules.
  • A refresh script that primarily runs a given aspect on a given set of target patterns, like //...:all.
  • A set of deviations (and tags) that configure the aspect to treat specific targets differently.

Effectively, in order to customize either the target patterns or the deviations, you need to instantiate your own custom trio of components. Doing so requires a BUILD and a .bzl file (don't ask why). The deviations and refresh script will be rules in your BUILD file. The aspect, parametrized by your custom deviations, will be created in your .bzl file.

In a BUILD file (e.g., //my:BUILD):

load("@bazel_cc_meta//cc_meta:cc_meta.bzl", "make_cc_meta_deviations", "refresh_cc_meta")

make_cc_meta_deviations(
    name = "my_cc_meta_deviations",
    deviations = {
        # gtest and gtest_main export the gtest headers and should always be linked in (for main).
        "@com_google_googletest//:gtest": {"exports": [
            "gtest/gtest.h",
            "gmock/gmock.h",
        ]},
        "@com_google_googletest//:gtest_main": {
            "alwaysused": True,
            "forward_exports": True,
        },
    },
    visibility = ["//visibility:public"],
)

refresh_cc_meta(
    name = "refresh_foo_cc_meta",
    cc_meta_aspect = "//my:defs.bzl%my_cc_meta_aspect",   # Default: "@bazel_cc_meta//:defs.bzl%default_cc_meta_aspect"
    targets = ["//my:foo"],                               # Default: "//..." (aka "all")
    visibility = ["//visibility:public"],
)

In a bzl file (e.g., //my:defs.bzl):

load("@bazel_cc_meta//cc_meta:cc_meta.bzl", "cc_meta_aspect_factory")

my_cc_meta_aspect = cc_meta_aspect_factory(
    deviations = [Label("@//my:my_cc_meta_deviations")],  # Default: []
    skipped_tags = ["hacky_target"],                      # Default: [] ("cc_meta_skip" still applies)
)

Note that multiple deviations rules can be given to the aspect, so that they can be logically separated. Generally, the attributes are subject to select too. The following section digs into how those deviations are specified.

Running your own custom aspect simply involve replacing @bazel_cc_meta//cc_meta:refresh_all with your custom refresh tool, e.g., //my:refresh_foo_cc_meta in the example above. The fix_deps tool does not need to change.

Custom deviations

The deviations are structured as a dictionary of dictionaries. The top-level key is the Label or Target to which the deviations should be applied. A deviation set is dictionary that can contain a few elements (all optional):

  • "exports": a list of include paths (as they would appear in dependent code) that should be added to the set of "exports" paths discovered for that target. This can be used for false-negatives, unusual include path specifications or deeply-wrapped targets.
  • "alwaysused": a bool to signal that this target should always be considered as used, even if the dependent is not including any of its headers. By default, targets with the attribute "alwayslink = True" will be considered used. In some cases, with wrapped targets for example, it might be required to externally mark additional targets as used. Adding 'alwayslink = True' to a target has the same effect.
  • "forward_exports": a bool to signal that this target should be considered as exporting all of its direct dependencies' exports. Note that this is not recursive, it only forwards direct exports. Applying this rule recursively is fraught with problems, so that option does not exist (sorry). Adding "cc_meta_forward_exports" to a target's 'tags' attribute has the same effect (preferred, if possible).
  • "skip": a bool to signal that this target should not be analyzed. Note, however, that the other deviations will still be applied. In other words, listing "exports" and setting "skip" to true results that target not being analyzed but having that specific set of exports added. Similarly, in conjunction with "forward_exports", the target would have only its direct dependencies' exports. Adding "cc_meta_skip" to a target's 'tags' attribute has the same effect (preferred, if possible).

Selecting deviations

Deviations can be "selected" (in the Bazel select sense) through the aspect specified in the "refresh" rule. This is, unfortunately, a bit verbose. Here is a basic example of a selectable set of deviations.

In a BUILD file (e.g., //my:BUILD):

load("@bazel_cc_meta//cc_meta:cc_meta.bzl", "make_cc_meta_deviations", "refresh_cc_meta")

make_cc_meta_deviations(
    name = "my_cc_meta_deviations",
    deviations = {
        # ... General deviations.
    },
    visibility = ["//visibility:public"],
)

make_cc_meta_deviations(
    name = "my_cc_meta_deviations_linux_only",
    deviations = {
        # ... Linux-only additional deviations.
    },
    # Restrict the deviations to Linux if the labels in the dictionary only exist in Linux.
    target_compatible_with = select({
        "@platforms//os:linux": [],
        "//conditions:default": ["@platforms//:incompatible"],
    }),
    visibility = ["//visibility:public"],
)

refresh_cc_meta(
    name = "refresh_foo_cc_meta",
    # Select the aspect based on the platform.
    cc_meta_aspect = select({
        "@platforms//os:linux": "//my:defs.bzl%my_cc_meta_aspect_for_linux",
        "//conditions:default": "//my:defs.bzl%my_cc_meta_aspect",
    }),
    visibility = ["//visibility:public"],
)

In a bzl file (e.g., //my:defs.bzl):

load("@bazel_cc_meta//cc_meta:cc_meta.bzl", "cc_meta_aspect_factory")

my_cc_meta_aspect = cc_meta_aspect_factory(
    deviations = [Label("@//my:my_cc_meta_deviations")],
)

# Create an aspect for Linux that include both general and Linux-only deviations.
my_cc_meta_aspect_for_linux = cc_meta_aspect_factory(
    deviations = [Label("@//my:my_cc_meta_deviations"), Label("@//my:my_cc_meta_deviations_linux_only")],
)

Linters

Some linting tools are provided as addtional features of bazel_cc_meta for convenience and because they inter-operate nicely with the core functionality.

Clang-tidy aspect

The clang-tidy aspect is exactly what it sounds like, an aspect that runs clang-tidy over all the source files in all your bazel targets. It works in a way that is very similar to the core aspect for generating the metadata. The macros and aspect definitions are found in cc_meta/linters.bzl.

  • Default aspect: @bazel_cc_meta//cc_meta:linters.bzl%default_clang_tidy_aspect
  • Default gather "all" reports tool: @bazel_cc_meta//cc_meta:gather_clang_tidy_all
  • Apply clang-tidy fixes tool: @bazel_cc_meta//cc_meta:apply_clang_tidy_fixes

NOTE: The default aspect is very unlikely to be appropriate since it will only find the .clang-tidy and .clang-format files if they happen to be brought as a dependency some other way. You will probably have to create a custom clang-tidy aspect with your tidy and format configs.

To create your own clang-tidy aspect, you will first have to create a filegroup target for your config files. In a top-level BUILD file:

filegroup(
    name = "my_clang_tidy_configs",
    srcs = [
        ".clang-tidy",
        ".clang-format",
    ],
    visibility = ["//visibility:public"],
)

Then, in a bzl file (e.g., //my:defs.bzl), you create your own aspect:

load("@bazel_cc_meta//cc_meta:linters.bzl", "clang_tidy_aspect_factory")
load("//my:cc_meta_defs.bzl", "my_cc_meta_aspect")  # Not needed if it's in the same *.bzl file.

my_clang_tidy_aspect = clang_tidy_aspect_factory(
    tidy_configs = [Label("//:my_clang_tidy_configs")],  # Makes configs findable during aspect's run
    cc_meta_aspect = my_cc_meta_aspect,                  # Needed to obtain compiler commands
)

When specifying the tidy_configs argument, the set of labels (and associated files) are brought into the execution dependencies for the clang-tidy invocation, making them discoverable in the usual way that clang-tidy discovers them recursively in parent directories of the files it is analysing. If you want to explicitly provide a particular config file, you can use the tidy_config_file argument instead and provide a filegroup target with a single file in it (a .clang-tidy-like file). That way, you could have multiple aspects running different sets of checks (e.g., lightweight set for a pre-merge hook versus a heavier one for nightlies).

The clang-tidy executable that the aspect uses is detected and derived from the cc_toolchain associated with the targets analysed. In other words, if you use the default toolchain, which finds a system compiler like /usr/bin/gcc or /usr/bin/clang, depending on your system's environment, then the clang-tidy aspect will attempt to use /usr/bin/clang-tidy, or fail if that is not installed on your system. If you use a hermetic toolchain (e.g., toolchains_llvm), then the clang-tidy aspect attempts to find clang-tidy in the set of files associated with that toolchain, and fails otherwise.

Similar to the "refresh" script, there is an associated "gather" script for the clang-tidy aspect that can be created for your project's needs, for your target patterns and custom aspect. In a BUILD file, you would define that script like so (say, in //my:BUILD):

load("@bazel_cc_meta//cc_meta:linters.bzl", "clang_tidy_issues_gatherer")
clang_tidy_issues_gatherer(
    name = "gather_clang_tidy_issues",
    clang_tidy_aspect = "//my:defs.bzl%my_clang_tidy_aspect",  # Default: "@bazel_cc_meta//cc_meta:linters.bzl%default_clang_tidy_aspect"
    targets = ["//my:foo"],  # Default: "//..." (aka "all")
    visibility = ["//visibility:public"],
)

Then, you can run the aspect and gather all the reported fixes into a single file the same way as with the refresh scripts:

bazel run [build_options] //my:gather_clang_tidy_issues -- [build_options]

This will generate a clang_tidy_fixes.yaml file containing all fixable issues that clang-tidy found.

The gather script can also take the following additional arguments:

  • --gather-into-yaml=path: Output path for combined yaml (default: clang_tidy_fixes.yaml).
  • --no-gather-into-yaml: Flag to suppress output of the combined yaml.
  • --gather-into-gitlab=path: Output path for a Code Climate JSON for a Gitlab CI runner (default: none).
  • --gather-into-github=path: Output path for a SARIF JSON file for a Github CI runner (default: none).

Apply clang-tidy fixes

The @bazel_cc_meta//cc_meta:apply_clang_tidy_fixes script takes reported fixes from clang-tidy and applies them.

This is basically a replacement for the standard clang-apply-replacements tool, except that it doesn't suck. Instead of doing very brittle and arcane directory traversals in search of compile commands and clang-tidy fixes like clang-apply-replacements does, this script takes a path to a specific yaml file containing the fixes you want to apply. And it has a number of other useful options.

This script can be invoked directly (build and run) or through bazel run. And it has the following arguments:

  • -f,--fixes=path: Path to the yaml file containing clang-tidy fixes (default: clang_tidy_fixes.yaml).
  • -y,--yes: Flag to run in non-interactive mode. In the default interactive mode, each fix must be confirmed (enter or type 'y'), and if any fixes conflict with each other (overlap), the user is prompted to make a choice. In non-interactive mode, all fixes are applied and only the first of any set of conflicting fixes is applied.
  • -d,--dry-run: Flag to run through the fixes without writing out the changes to the files.
  • --exclude-paths=regex: A regex applied to file paths, if it matches, those files are not fixed (default: "external/"). If it's an empty string, it will be replaced by a match-nothing.
  • --include-paths=regex: A regex applied to file paths, if it matches, those files are fixed, unless they match the --exclude-paths pattern (default: ".*").
  • --exclude-checks=regex: A regex applied to checks, checks matching this pattern won't be fixed (default: "modernize-use-ranges" (because it breaks the code by leaving stray commas)). If it's an empty string, it will be replaced by a match-nothing.
  • --include-checks=regex: A regex applied to checks, checks matching this pattern will be fixed, unless they match the --exclude-checks pattern (default: ".*").
  • [file] ...: Remaining arguments are a list of files to fix, if none, then fix everything. This is obviously useful if creating a pre-commit hook (append the list of changed files).

Known issues

Approximate target queries

The refresh tool must use Bazel's cquery command to obtain a full list of dependencies spawning from the given target pattern (e.g., //...:all) and attempts to do so using the cquery (aka Configurable Query) in order to respect the build configuration (e.g., --config=, -c dbg, etc.). This facility is approximate and could result in missing some targets. If you suspect that is the case (if using a particularly difficult configuration, such as for cross-compilation), then you can check what bazel cquery //...:all produces and if it lacks certain desired target, create your own custom 'refresh' rule (see previous section) with a more fine-grained target pattern.

Common problematic libraries

Some common libraries use convoluted target topologies (and unsurprisingly, all of them come from Google). Here are some suggested deviations to use to resolve some issues with common libraries:

make_cc_meta_deviations(
    name = "some_suggested_cc_meta_deviations",
    deviations = {
        # gtest and gtest_main export the gtest headers and should always be linked in (for main).
        "@com_google_googletest//:gtest": {"exports": [
            "gtest/gtest.h",
            "gmock/gmock.h",
        ]},
        "@com_google_googletest//:gtest_main": {
            "alwaysused": True,
            "forward_exports": True,
        },

        # benchmark and benchmark_main export the benchmark headers and should always be linked in (for main).
        "@com_google_benchmark//:benchmark": {"exports": [
            "benchmark/benchmark.h",
        ]},
        "@com_google_benchmark//:benchmark_main": {
            "alwaysused": True,
            "forward_exports": True,
        },

        # protobuf's public target effectively re-exports its private dependencies' headers.
        "@com_google_protobuf//:protobuf": {"forward_exports": True},
    },
)

Fixing generated targets will fail

This is a basic limitation of trying to use buildozer to add or remove dependencies in generated targets. Fixes to generated targets have to be done manually because buildozer cannot know where those targets actually come from or where it's appropriate to change the dependencies.

Canonical public targets

Again, when packages declare aliases and wrapper targets, it causes problems. In particular, when trying to add missing dependencies such targets will generally resolve to some underlying private target that is not meant or allowed to be depended upon. It's not possible to reassign such targets back to the intended public alias. In these cases, there will be errors trying to add those dependencies and might require manual fixing.

Try adding a deviation on the alias target, especially "alwaysused" and "forward_exports".

Preprocessor logic

To discover include statements, this tool invokes the compiler in a preprocessor-only mode (-E) and asks for very shallow include expansion to efficiently discover only the top-level includes. This means that it can, to a degree, resolve preprocessor-based conditional includes and such, but it is limited and could fail on sources that use tricky preprocessor logic to decide what headers to include. Problems could be:

  • Discovering the wrong includes.
  • Failing to preprocess the sources if deeply buried #define's are required to resolve top-level includes.

These problems can generally be solved by either skipping those targets or by wrapping the problematic inclusion patterns in a more limited (and skipped) target. Those sorts of complicated preprocessor-based inclusion logic should be limited and insulated for good practice anyways, so this limitation is almost a feature rather than a bug. And if you do this kind of nonsense in your own code, in this century, then just fix it!

Textual headers

Bazel's cc_* targets (in particular, cc_library) distinguish between hdrs and textual_hdrs by the key difference that textual_hdrs are files that can be included by dependents (and public), like regular headers, but are not parsable (aka compilable) on their own. Commonly, these are header-like files that some libraries have which require some special inclusion pattern, such as #define'ing some things first or including the file within some class declaration. Again, this is very bad practice and heavily discouraged (as are preprocessor-based include logic). Bazel provides textual_hdrs to support this brittle and antiquated pattern that is still common in legacy libraries, and otherwise assumes all hdrs can be compiled or parsed on their own (eventually, for pre-compiled headers or C++ modules).

This tool makes the same assumption. If you have code that does not follow that rule for all targets (which probably "just works" until you try to enable modules or layering checks), fix or skip those targets. The fix is generally to move such non-standalone "headers" to the textual_hdrs attribute of your target.

In order to discover includes, this tool attempts to parse all files in hdrs and srcs, which means that includes within textual_hdrs are not discoverable, potentially leading to spurious issues being reported.

Using GCC

Broadly-speaking, GCC and Clang are compatible, but there are differences that can matter in some cases. Since this tool (bazel_cc_meta) is mostly aimed at LLVM/Clang, such as producing a compiler_commands.json file to be consumed by clangd (LSP server), it's generally recommended to use Clang as your compiler.

First, compilation flags may not be entirely the same between compilers, e.g., your build configuration might conditionally add flags only for Clang, or Bazel's C/C++ rules might also do that (I know it does, but not in ways that matters for clangd, afaik). In general, it is safer to use Clang at least when generating the compiler_commands.json (i.e., when invoking the refresh script).

Second, GCC has particular idiosyncracies when it comes to extracting the dependencies (aka includes) while running the preprocessor-only pass, which this tool relies on to match imports to exports. The result is that identification of direct includes using GCC is less reliable, especially in the face of libraries (headers) being installed on the host/exec environment. In a nutshell, Clang allows for all include paths to be removed and successfully produce a list of direct unresolved includes. With GCC, this is not possible: removing all include paths causes unresolved includes of standard headers to trigger preprocessing errors (even if it's specifically instructed not to fail for that reason). So, we are forced to keep built-in include paths (e.g., /usr/include) and assume that any included file that GCC finds in those directories were meant to come from the system and not a Bazel target dependency. Of course, that assumption may be wrong, as in the case where the same library exists in both places (e.g., your Bazel project uses @abseil-cpp, but you also have libabsl-dev installed on your system).

For those reasons, please use Clang, at least when running the refresh script.

Disclaimer

This package is highly experimental. Keep your expectations low in terms of supported platforms or target topologies. The weirder the setup, like using lots of "wrapper" targets, aliases or generated targets, the less likely it is to work.

The primary platform targeted (where it is actually used) is Linux with a reasonably recent Bazel and Python versions (guessing, at least Python > 3.8, and Bazel > 7.0).

Contributing

Contribute through the typical github mechanisms:

  • Report issues
  • Before reporting an issue, keep in mind that LSPs / editors can be finicky and sometimes require restarting the editor or the LSP server to properly refresh their caches.
  • Create pull requests

License

Copyright 2025-present, Mikael Persson. This project licensed under the Apache 2.0 license.

Credits

This tool was inspired by, and is effectively a combination of, the following tools:

The gist of this new tool is to use the best of both worlds. DWYU employs Bazel's aspects to create a shadow build graph over the existing build graph to extract information about imports and exports of cc_* targets in order to find and fix issues with dependencies. However, the implementation is unfortunately quite slow and limited, and bazel_cc_meta greatly improves the performance and adds the mapping of target to exports which allows for not just finding missing dependencies but also fixing them. Then, Hedron's generator of the compile_commands.json is based entirely on Bazel's query features (query, cquery and aquery) to extract the compilation commands for each source file. That has a number of problems, such as being approximate (Bazel's query system cannot always accurately reflect the actual build graph), very slow (invoking Bazel on each target), and cannot effectively employ Bazel's caching system to avoid repeated analysis of up-to-date targets. Gathering the compiler commands through an aspect is a far superior mechanism that solves all these shortcomings.

About

Bazel tools to analyze C/C++ metadata and target dependencies

Resources

Stars

19 stars

Watchers

5 watching

Forks

Releases

Packages

Contributors

Languages