How to get cc_test's full cmd(with args and env) to debug locally?

53 Views Asked by At

I have a complex cc_test which has tons of args and envs specified in the rules:

cc_test(
  name="my_test",
  args=[...tons of args...],
  env= {...tons of envs...},
)

Now I want to run it locally by running ./bazel-bin/my_test, so that I can use GDB to debug it.

The problem is I neeed to copy&paste args and env form the rules manually, to get the full command like:

ENV1=X ENV2=Y ./bazel-bin/my_test --args1=x --args2=y

Which is very a waste of time.

Is there a faster way to get this command? Or is there any other simpler way to debug a cc_test with GDB?

1

There are 1 best solutions below

3
ahumesky On

To see exactly what actions bazel executes and how it executes them, you can use --subcommands: https://bazel.build/docs/user-manual#subcommands

Note that that will also print all the commands executed to build everything in the build request, so there might be a lot of things to look through. But the test execution should be one of the last items.

There is also aquery to examine all the actions in a build target: https://bazel.build/query/aquery

There is also --run_under: https://bazel.build/docs/user-manual#run_under. From this disucussion: https://github.com/bazelbuild/bazel/issues/2815 you would use bazel run instead of bazel test: bazel run <test> --run_under='gdb --args'

Addition:

You could also inspect the cc_test target using an asepct and have it print out the command. It's somewhat specific to cc_test though (i.e. manually inspects the env and args attributes and assembles the command line):

$ cat aspect.bzl 
def _print_cmd_impl(target, ctx):
    executable_path = target[DefaultInfo].files_to_run.executable.path
    env = " ".join(["%s=%s" % (k, v) for k,v in ctx.rule.attr.env.items()])
    args = " ".join(ctx.rule.attr.args)
    print("%s %s %s" % (env, executable_path, args))
    return []

print_cmd = aspect(
    implementation = _print_cmd_impl,
)

$ cat BUILD
cc_test(
  name = "test",
  srcs = ["test.cc"],
  env = {"var1": "val1", "var2": "val2"},
  args = ["arg1", "arg2", "arg3"],
)

$ bazel build test --aspects=aspect.bzl%print_cmd
DEBUG: /usr/local/google/home/ahumesky/bazel-workspaces/cc_test_run_under_gdb/aspect.bzl:5:10: var1=val1 var2=val2 bazel-out/k8-fastbuild/bin/test arg1 arg2 arg3
INFO: Analyzed target //:test (0 packages loaded, 0 targets configured).
INFO: Found 1 target...
Target //:test up-to-date:
  bazel-bin/test
INFO: Elapsed time: 0.182s, Critical Path: 0.01s
INFO: 1 process: 1 internal.
INFO: Build completed successfully, 1 total action