Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions go/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ bzl_library(
"//go/private:context",
"//go/private:go_toolchain",
"//go/private:providers",
"//go/private/aspects:all_rules",
"//go/private/rules:library",
"//go/private/rules:nogo",
"//go/private/rules:sdk",
Expand Down
2 changes: 2 additions & 0 deletions go/private/actions/archive.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,8 @@ def emit_archive(go, source = None, _recompile_suffix = "", recompile_internal_d
is_external_pkg = is_external_pkg,
)

# Buildinfo metadata is collected via aspect and stored separately

data = GoArchiveData(
# TODO(#2578): reconsider the provider API. There's a lot of redundant
# information here. Some fields are tuples instead of lists or dicts
Expand Down
4 changes: 4 additions & 0 deletions go/private/actions/binary.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ def emit_binary(
gc_linkopts = [],
version_file = None,
info_file = None,
buildinfo_metadata = None,
target_label = None,
executable = None):
"""See go/toolchains.rst#binary for full documentation."""

Expand Down Expand Up @@ -61,6 +63,8 @@ def emit_binary(
gc_linkopts = gc_linkopts,
version_file = version_file,
info_file = info_file,
buildinfo_metadata = buildinfo_metadata,
target_label = target_label,
)
cgo_dynamic_deps = [
d
Expand Down
67 changes: 66 additions & 1 deletion go/private/actions/link.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -44,14 +44,70 @@ def emit_link(
executable = None,
gc_linkopts = [],
version_file = None,
info_file = None):
info_file = None,
buildinfo_metadata = None,
target_label = None):
"""See go/toolchains.rst#link for full documentation."""

if archive == None:
fail("archive is a required parameter")
if executable == None:
fail("executable is a required parameter")

# Generate buildinfo dependency file for Go 1.18+ buildInfo support
buildinfo_file = None
if buildinfo_metadata:
buildinfo_file = go.declare_file(go, path = executable.basename + ".buildinfo.txt")

# Materialize depsets at link time
importpaths = buildinfo_metadata.importpaths.to_list()
metadata_targets = buildinfo_metadata.metadata_providers.to_list()

# Build version map from metadata providers
# Sort targets by label for deterministic version resolution
# This ensures reproducible builds and consistent action cache keys
sorted_targets = sorted(
metadata_targets,
key = lambda t: str(t.label) if hasattr(t, "label") else str(t),
)

version_map = {}
for target in sorted_targets:
# Extract version info from PackageInfo provider
if hasattr(target, "package_info"):
# Handle both single object and list of package_info
package_infos = target.package_info if type(target.package_info) == type([]) else [target.package_info]
for info in package_infos:
if hasattr(info, "module") and hasattr(info, "version"):
module = info.module
version = info.version

# Use first version (by sorted label order) if duplicates exist
# This makes conflicts deterministic and debuggable
if module not in version_map:
version_map[module] = version

# Build buildinfo content
content_lines = []

# Add main package path
if archive.data.importpath:
content_lines.append("path\t{}".format(archive.data.importpath))

# Add dependencies with versions
# Sort importpaths for deterministic output, which is required for:
# 1. Bazel action caching - identical inputs must produce identical outputs
# 2. Reproducible builds across different machines
# 3. Easier debugging and testing with predictable output order
for importpath in sorted(importpaths):
version = version_map.get(importpath, "(devel)")
content_lines.append("dep\t{}\t{}".format(importpath, version))

go.actions.write(
output = buildinfo_file,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we track info as depsets (see comment above), we could materialize that into a file at execution time using TemplateDict or Args. I can take over that part if you want.

content = "\n".join(content_lines) + "\n" if content_lines else "",
)

# Exclude -lstdc++ from link options. We don't want to link against it
# unless we actually have some C++ code. _cgo_codegen will include it
# in archives via CGO_LDFLAGS if it's needed.
Expand Down Expand Up @@ -167,6 +223,13 @@ def emit_link(
builder_args.add("-o", executable)
builder_args.add("-main", archive.data.file)
builder_args.add("-p", archive.data.importmap)

# Pass buildinfo file to builder if available
if buildinfo_file:
builder_args.add("-buildinfo", buildinfo_file)
if target_label:
builder_args.add("-bazeltarget", target_label)

tool_args.add_all(gc_linkopts)
tool_args.add_all(go.toolchain.flags.link)

Expand All @@ -177,6 +240,8 @@ def emit_link(
tool_args.add_joined("-extldflags", extldflags, join_with = " ")

inputs_direct = stamp_inputs + [go.sdk.package_list]
if buildinfo_file:
inputs_direct.append(buildinfo_file)
if go.coverage_enabled and go.coverdata:
inputs_direct.append(go.coverdata.data.file)
inputs_transitive = [
Expand Down
12 changes: 12 additions & 0 deletions go/private/aspects/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
filegroup(
name = "all_rules",
srcs = glob(["**/*.bzl"]),
visibility = ["//visibility:public"],
)

filegroup(
name = "all_files",
testonly = True,
srcs = glob(["**"]),
visibility = ["//visibility:public"],
)
100 changes: 100 additions & 0 deletions go/private/aspects/buildinfo_aspect.bzl
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
"""Aspect to collect package_info metadata for buildInfo.

This aspect traverses Go binary dependencies and collects version information
from Gazelle-generated package_info targets referenced via the package_metadata
common attribute (inherited from REPO.bazel default_package_metadata).

Implementation based on bazel-contrib/supply-chain gather_metadata pattern.
Currently doesn't use the supply chain tools dep for this as it is not yet
stable and we still need to support WORKSPACE which the supply-chain tools
doesn't have support for.
"""

load(
"//go/private:providers.bzl",
"GoArchive",
)

visibility(["//go/private/..."])

BuildInfoMetadata = provider(
doc = "INTERNAL: Provides dependency version metadata for buildInfo. Do not depend on this provider.",
fields = {
"importpaths": "Depset of importpath strings from Go dependencies",
"metadata_providers": "Depset of PackageInfo providers with version data",
},
)

def _buildinfo_aspect_impl(target, ctx):
"""Collects package_info metadata from dependencies.

This aspect collects version information from package_metadata attributes
(set via REPO.bazel default_package_metadata in go_repository) and tracks
importpaths from Go dependencies. The actual version matching is deferred
to execution time to avoid quadratic memory usage.

Args:
target: The target being visited
ctx: The aspect context

Returns:
List containing BuildInfoMetadata provider
"""
direct_importpaths = []
direct_metadata = []
transitive_importpaths = []
transitive_metadata = []

# Collect importpath from this target if it's a Go target
if GoArchive in target:
importpath = target[GoArchive].data.importpath
if importpath:
direct_importpaths.append(importpath)

# Check package_metadata common attribute (Bazel 6+)
# This is set via REPO.bazel default_package_metadata in go_repository
if hasattr(ctx.rule.attr, "package_metadata"):
attr_value = ctx.rule.attr.package_metadata
if attr_value:
package_metadata = attr_value if type(attr_value) == type([]) else [attr_value]

# Store the metadata targets directly for later processing
direct_metadata.extend(package_metadata)

# Collect transitive metadata from Go dependencies only
# Only traverse deps and embed to avoid non-Go dependencies
for attr_name in ["deps", "embed"]:
if not hasattr(ctx.rule.attr, attr_name):
continue

attr_value = getattr(ctx.rule.attr, attr_name)
if not attr_value:
continue

deps = attr_value if type(attr_value) == type([]) else [attr_value]
for dep in deps:
# Collect transitive BuildInfoMetadata
if BuildInfoMetadata in dep:
transitive_importpaths.append(dep[BuildInfoMetadata].importpaths)
transitive_metadata.append(dep[BuildInfoMetadata].metadata_providers)

# Build depsets (empty depsets are efficient, no need for early return)
return [BuildInfoMetadata(
importpaths = depset(
direct = direct_importpaths,
transitive = transitive_importpaths,
),
metadata_providers = depset(
direct = direct_metadata,
transitive = transitive_metadata,
),
)]

buildinfo_aspect = aspect(
doc = "Collects package_info metadata for Go buildInfo",
implementation = _buildinfo_aspect_impl,
attr_aspects = ["deps", "embed"], # Only traverse Go dependencies
provides = [BuildInfoMetadata],
# Apply to generated targets including package_info
apply_to_generating_rules = True,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would think that we don't want this (e.g. don't traverse code generators that produce .go files in sources), but I may be missing a use case.

)
1 change: 1 addition & 0 deletions go/private/rules/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ bzl_library(
"//go/private:mode",
"//go/private:providers",
"//go/private:rpath",
"//go/private/aspects:all_rules",
"//go/private/rules:transition",
],
)
Expand Down
33 changes: 31 additions & 2 deletions go/private/rules/binary.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,11 @@ load(
"GoInfo",
"GoSDK",
)
load(
"//go/private/aspects:buildinfo_aspect.bzl",
"BuildInfoMetadata",
"buildinfo_aspect",
)
load(
"//go/private/rules:transition.bzl",
"go_transition",
Expand Down Expand Up @@ -155,6 +160,28 @@ def _go_binary_impl(ctx):
importable = False,
is_main = is_main,
)

# Collect version metadata from aspect for buildInfo
# Merge ALL metadata from all deps and embed targets to ensure complete coverage
all_importpaths = []
all_metadata = []
for attr_name in ["embed", "deps"]:
if not hasattr(ctx.attr, attr_name):
continue
for target in getattr(ctx.attr, attr_name):
if BuildInfoMetadata in target:
all_importpaths.append(target[BuildInfoMetadata].importpaths)
all_metadata.append(target[BuildInfoMetadata].metadata_providers)

buildinfo_metadata = None
if all_importpaths:
buildinfo_metadata = BuildInfoMetadata(
importpaths = depset(transitive = all_importpaths),
metadata_providers = depset(transitive = all_metadata),
)

# Get Bazel target label for buildInfo
target_label = str(ctx.label)
name = ctx.attr.basename
if not name:
name = ctx.label.name
Expand All @@ -172,6 +199,8 @@ def _go_binary_impl(ctx):
version_file = ctx.version_file,
info_file = ctx.info_file,
executable = executable,
buildinfo_metadata = buildinfo_metadata,
target_label = target_label,
)
validation_output = archive.data._validation_output
nogo_diagnostics = archive.data._nogo_diagnostics
Expand Down Expand Up @@ -279,14 +308,14 @@ def _go_binary_kwargs(go_cc_aspects = []):
),
"deps": attr.label_list(
providers = [GoInfo],
aspects = go_cc_aspects,
aspects = go_cc_aspects + [buildinfo_aspect],
doc = """List of Go libraries this package imports directly.
These may be `go_library` rules or compatible rules with the [GoInfo] provider.
""",
),
"embed": attr.label_list(
providers = [GoInfo],
aspects = go_cc_aspects,
aspects = go_cc_aspects + [buildinfo_aspect],
doc = """List of Go libraries whose sources should be compiled together with this
binary's sources. Labels listed here must name `go_library`,
`go_proto_library`, or other compatible targets with the [GoInfo] provider.
Expand Down
2 changes: 2 additions & 0 deletions go/tools/builders/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ filegroup(
"ar.go",
"asm.go",
"builder.go",
"buildinfo.go",
"cc.go",
"cgo2.go",
"compilepkg.go",
Expand All @@ -101,6 +102,7 @@ filegroup(
"generate_test_main.go",
"importcfg.go",
"link.go",
"modinfo.go",
"nogo.go",
"nogo_validation.go",
"read.go",
Expand Down
Loading