blob: 2e6b6d44a752d97d5d062273311cec6f0432d571 [file] [log] [blame]
Colin Cross3f40fa42015-01-30 17:27:36 -08001// Copyright 2015 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package main
16
17import (
Usta Shrestha2ba28a32022-10-24 11:33:09 -040018 "bytes"
Jeongik Chaa87506f2023-06-01 23:16:41 +090019 "errors"
Colin Cross3f40fa42015-01-30 17:27:36 -080020 "flag"
21 "fmt"
22 "os"
23 "path/filepath"
Jingwen Cheneb76c432021-01-28 08:22:12 -050024 "strings"
Lukacs T. Berkic99c9472021-03-24 10:50:06 +010025 "time"
Colin Cross3f40fa42015-01-30 17:27:36 -080026
Dan Willemsen66213a62021-09-21 17:50:30 -070027 "android/soong/android"
Jeongik Chae114e602023-03-19 00:12:39 +090028 "android/soong/android/allowlists"
Spandan Das5af0bd32022-09-28 20:43:08 +000029 "android/soong/bazel"
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020030 "android/soong/bp2build"
Lukacs T. Berki7690c092021-02-26 14:27:36 +010031 "android/soong/shared"
Chris Parsons715b08f2022-03-22 19:23:40 -040032 "android/soong/ui/metrics/bp2build_metrics_proto"
Lukacs T. Berkie571dc32021-08-25 14:14:13 +020033
Jeongik Chab745e2e2023-04-11 14:28:43 +090034 "github.com/google/blueprint"
Colin Cross70b40592015-03-23 12:57:34 -070035 "github.com/google/blueprint/bootstrap"
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +020036 "github.com/google/blueprint/deptools"
Chris Parsons715b08f2022-03-22 19:23:40 -040037 "github.com/google/blueprint/metrics"
Dan Willemsen66213a62021-09-21 17:50:30 -070038 androidProtobuf "google.golang.org/protobuf/android"
Colin Cross3f40fa42015-01-30 17:27:36 -080039)
40
Colin Crosse87040b2017-12-11 15:52:26 -080041var (
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020042 topDir string
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020043 availableEnvFile string
44 usedEnvFile string
45
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +020046 globFile string
47 globListDir string
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020048 delveListen string
49 delvePath string
50
Sasha Smundakaf5ca922022-12-12 21:23:34 -080051 cmdlineArgs android.CmdArgs
Colin Crosse87040b2017-12-11 15:52:26 -080052)
53
54func init() {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020055 // Flags that make sense in every mode
Lukacs T. Berki7690c092021-02-26 14:27:36 +010056 flag.StringVar(&topDir, "top", "", "Top directory of the Android source tree")
Sasha Smundakaf5ca922022-12-12 21:23:34 -080057 flag.StringVar(&cmdlineArgs.SoongOutDir, "soong_out", "", "Soong output directory (usually $TOP/out/soong)")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020058 flag.StringVar(&availableEnvFile, "available_env", "", "File containing available environment variables")
59 flag.StringVar(&usedEnvFile, "used_env", "", "File containing used environment variables")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020060 flag.StringVar(&globFile, "globFile", "build-globs.ninja", "the Ninja file of globs to output")
61 flag.StringVar(&globListDir, "globListDir", "", "the directory containing the glob list files")
Sasha Smundakaf5ca922022-12-12 21:23:34 -080062 flag.StringVar(&cmdlineArgs.OutDir, "out", "", "the ninja builddir directory")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020063 flag.StringVar(&cmdlineArgs.ModuleListFile, "l", "", "file that lists filepaths to parse")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020064
65 // Debug flags
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +010066 flag.StringVar(&delveListen, "delve_listen", "", "Delve port to listen on for debugging")
67 flag.StringVar(&delvePath, "delve_path", "", "Path to Delve. Only used if --delve_listen is set")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020068 flag.StringVar(&cmdlineArgs.Cpuprofile, "cpuprofile", "", "write cpu profile to file")
69 flag.StringVar(&cmdlineArgs.TraceFile, "trace", "", "write trace to file")
70 flag.StringVar(&cmdlineArgs.Memprofile, "memprofile", "", "write memory profile to file")
71 flag.BoolVar(&cmdlineArgs.NoGC, "nogc", false, "turn off GC for debugging")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020072
73 // Flags representing various modes soong_build can run in
Sasha Smundakaf5ca922022-12-12 21:23:34 -080074 flag.StringVar(&cmdlineArgs.ModuleGraphFile, "module_graph_file", "", "JSON module graph file to output")
75 flag.StringVar(&cmdlineArgs.ModuleActionsFile, "module_actions_file", "", "JSON file to output inputs/outputs of actions of modules")
76 flag.StringVar(&cmdlineArgs.DocFile, "soong_docs", "", "build documentation file to output")
77 flag.StringVar(&cmdlineArgs.BazelQueryViewDir, "bazel_queryview_dir", "", "path to the bazel queryview directory relative to --top")
78 flag.StringVar(&cmdlineArgs.BazelApiBp2buildDir, "bazel_api_bp2build_dir", "", "path to the bazel api_bp2build directory relative to --top")
79 flag.StringVar(&cmdlineArgs.Bp2buildMarker, "bp2build_marker", "", "If set, run bp2build, touch the specified marker file then exit")
80 flag.StringVar(&cmdlineArgs.SymlinkForestMarker, "symlink_forest_marker", "", "If set, create the bp2build symlink forest, touch the specified marker file, then exit")
Lukacs T. Berkif9008072021-08-16 15:24:48 +020081 flag.StringVar(&cmdlineArgs.OutFile, "o", "build.ninja", "the Ninja file to output")
Kiyoung Kima37d9ba2023-04-19 13:13:45 +090082 flag.StringVar(&cmdlineArgs.SoongVariables, "soong_variables", "soong.variables", "the file contains all build variables")
MarkDacekd06db5d2022-11-29 00:47:59 +000083 flag.StringVar(&cmdlineArgs.BazelForceEnabledModules, "bazel-force-enabled-modules", "", "additional modules to build with Bazel. Comma-delimited")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020084 flag.BoolVar(&cmdlineArgs.EmptyNinjaFile, "empty-ninja-file", false, "write out a 0-byte ninja file")
LaMont Jones52a72432023-03-09 18:19:35 +000085 flag.BoolVar(&cmdlineArgs.MultitreeBuild, "multitree-build", false, "this is a multitree build")
Chris Parsonsef615e52022-08-18 22:04:11 -040086 flag.BoolVar(&cmdlineArgs.BazelMode, "bazel-mode", false, "use bazel for analysis of certain modules")
Jingwen Chene647db82022-11-01 11:28:29 +000087 flag.BoolVar(&cmdlineArgs.BazelModeStaging, "bazel-mode-staging", false, "use bazel for analysis of certain near-ready modules")
Chris Parsonsef615e52022-08-18 22:04:11 -040088 flag.BoolVar(&cmdlineArgs.BazelModeDev, "bazel-mode-dev", false, "use bazel for analysis of a large number of modules (less stable)")
Chris Parsons9402ca82023-02-23 17:28:06 -050089 flag.BoolVar(&cmdlineArgs.UseBazelProxy, "use-bazel-proxy", false, "communicate with bazel using unix socket proxy instead of spawning subprocesses")
Jihoon Kang1bff0342023-01-17 20:40:22 +000090 flag.BoolVar(&cmdlineArgs.BuildFromTextStub, "build-from-text-stub", false, "build Java stubs from API text files instead of source files")
MarkDacekf47e1422023-04-19 16:47:36 +000091 flag.BoolVar(&cmdlineArgs.EnsureAllowlistIntegrity, "ensure-allowlist-integrity", false, "verify that allowlisted modules are mixed-built")
Sasha Smundakaf5ca922022-12-12 21:23:34 -080092 // Flags that probably shouldn't be flags of soong_build, but we haven't found
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020093 // the time to remove them yet
Sasha Smundakaf5ca922022-12-12 21:23:34 -080094 flag.BoolVar(&cmdlineArgs.RunGoTests, "t", false, "build and run go tests during bootstrap")
Dan Willemsen66213a62021-09-21 17:50:30 -070095
96 // Disable deterministic randomization in the protobuf package, so incremental
97 // builds with unrelated Soong changes don't trigger large rebuilds (since we
98 // write out text protos in command lines, and command line changes trigger
99 // rebuilds).
100 androidProtobuf.DisableRand()
Colin Crosse87040b2017-12-11 15:52:26 -0800101}
102
Jeff Gaston088e29e2017-11-29 16:47:17 -0800103func newNameResolver(config android.Config) *android.NameResolver {
Paul Duffin3f7bf9f2022-11-08 12:21:15 +0000104 return android.NewNameResolver(config)
Jeff Gaston088e29e2017-11-29 16:47:17 -0800105}
106
Lukacs T. Berkiffc9e8d2021-09-07 17:54:38 +0200107func newContext(configuration android.Config) *android.Context {
Colin Crossae8600b2020-10-29 17:09:13 -0700108 ctx := android.NewContext(configuration)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400109 ctx.SetNameInterface(newNameResolver(configuration))
110 ctx.SetAllowMissingDependencies(configuration.AllowMissingDependencies())
Spandan Dasc5763832022-11-08 18:42:16 +0000111 ctx.AddIncludeTags(configuration.IncludeTags()...)
Sam Delmerico98a73292023-02-21 11:50:29 -0500112 ctx.AddSourceRootDirs(configuration.SourceRootDirs()...)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400113 return ctx
114}
115
Chris Parsonsf874e462022-05-10 13:50:12 -0400116// Bazel-enabled mode. Attaches a mutator to queue Bazel requests, adds a
117// BeforePrepareBuildActionsHook to invoke Bazel, and then uses Bazel metadata
118// for modules that should be handled by Bazel.
Sasha Smundak1845f422022-12-13 14:18:58 -0800119func runMixedModeBuild(ctx *android.Context, extraNinjaDeps []string) string {
Chris Parsonsf874e462022-05-10 13:50:12 -0400120 ctx.EventHandler.Begin("mixed_build")
121 defer ctx.EventHandler.End("mixed_build")
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200122
Chris Parsonsf874e462022-05-10 13:50:12 -0400123 bazelHook := func() error {
Sasha Smundak1845f422022-12-13 14:18:58 -0800124 return ctx.Config().BazelContext.InvokeBazel(ctx.Config(), ctx)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200125 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400126 ctx.SetBeforePrepareBuildActionsHook(bazelHook)
Sasha Smundak1845f422022-12-13 14:18:58 -0800127 ninjaDeps := bootstrap.RunBlueprint(cmdlineArgs.Args, bootstrap.DoEverything, ctx.Context, ctx.Config())
Chris Parsons027881c2022-05-24 15:38:38 -0400128 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200129
Sasha Smundak1845f422022-12-13 14:18:58 -0800130 bazelPaths, err := readFileLines(ctx.Config().Getenv("BAZEL_DEPS_FILE"))
MarkDacek0d5bca52022-10-10 20:07:48 +0000131 if err != nil {
132 panic("Bazel deps file not found: " + err.Error())
133 }
134 ninjaDeps = append(ninjaDeps, bazelPaths...)
Sasha Smundak1845f422022-12-13 14:18:58 -0800135 ninjaDeps = append(ninjaDeps, writeBuildGlobsNinjaFile(ctx)...)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200136
Paul Duffin780a1852022-11-05 10:17:12 +0000137 writeDepFile(cmdlineArgs.OutFile, ctx.EventHandler, ninjaDeps)
Jeongik Cha591366d2023-05-08 11:32:52 +0900138
Jeongik Chaa87506f2023-06-01 23:16:41 +0900139 if needToWriteNinjaHint(ctx) {
Jeongik Cha591366d2023-05-08 11:32:52 +0900140 writeNinjaHint(ctx)
141 }
Paul Duffin0c09a432022-11-05 15:28:04 +0000142 return cmdlineArgs.OutFile
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200143}
144
Jeongik Chaa87506f2023-06-01 23:16:41 +0900145func needToWriteNinjaHint(ctx *android.Context) bool {
146 switch ctx.Config().GetenvWithDefault("SOONG_GENERATES_NINJA_HINT", "") {
147 case "always":
148 return true
149 case "depend":
150 if _, err := os.Stat(filepath.Join(ctx.Config().OutDir(), ".ninja_log")); errors.Is(err, os.ErrNotExist) {
151 return true
152 }
153 }
154 return false
155}
156
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200157// Run the code-generation phase to convert BazelTargetModules to BUILD files.
Sasha Smundak1845f422022-12-13 14:18:58 -0800158func runQueryView(queryviewDir, queryviewMarker string, ctx *android.Context) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400159 ctx.EventHandler.Begin("queryview")
160 defer ctx.EventHandler.End("queryview")
Cole Faustb85d1a12022-11-08 18:14:01 -0800161 codegenContext := bp2build.NewCodegenContext(ctx.Config(), ctx, bp2build.QueryView, topDir)
Spandan Das98cb8562023-03-09 23:05:47 +0000162 err := createBazelWorkspace(codegenContext, shared.JoinPath(topDir, queryviewDir), false)
Sasha Smundak1845f422022-12-13 14:18:58 -0800163 maybeQuit(err, "")
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200164 touch(shared.JoinPath(topDir, queryviewMarker))
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200165}
166
Spandan Das5af0bd32022-09-28 20:43:08 +0000167// Run the code-generation phase to convert API contributions to BUILD files.
168// Return marker file for the new synthetic workspace
Sasha Smundak1845f422022-12-13 14:18:58 -0800169func runApiBp2build(ctx *android.Context, extraNinjaDeps []string) string {
Spandan Das5af0bd32022-09-28 20:43:08 +0000170 ctx.EventHandler.Begin("api_bp2build")
171 defer ctx.EventHandler.End("api_bp2build")
Spandan Das255648c2023-01-11 03:05:24 +0000172 // api_bp2build does not run the typical pipeline of soong mutators.
173 // Hoevever, it still runs the defaults mutator which can create dependencies.
174 // These dependencies might not always exist (e.g. in tests)
175 ctx.SetAllowMissingDependencies(ctx.Config().AllowMissingDependencies())
Spandan Das5af0bd32022-09-28 20:43:08 +0000176 ctx.RegisterForApiBazelConversion()
177
178 // Register the Android.bp files in the tree
179 // Add them to the workspace's .d file
180 ctx.SetModuleListFile(cmdlineArgs.ModuleListFile)
181 if paths, err := ctx.ListModulePaths("."); err == nil {
182 extraNinjaDeps = append(extraNinjaDeps, paths...)
183 } else {
184 panic(err)
185 }
186
187 // Run the loading and analysis phase
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800188 ninjaDeps := bootstrap.RunBlueprint(cmdlineArgs.Args,
Spandan Das5af0bd32022-09-28 20:43:08 +0000189 bootstrap.StopBeforePrepareBuildActions,
190 ctx.Context,
Sasha Smundak1845f422022-12-13 14:18:58 -0800191 ctx.Config())
Spandan Das5af0bd32022-09-28 20:43:08 +0000192 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
193
194 // Add the globbed dependencies
Sasha Smundak1845f422022-12-13 14:18:58 -0800195 ninjaDeps = append(ninjaDeps, writeBuildGlobsNinjaFile(ctx)...)
Spandan Das5af0bd32022-09-28 20:43:08 +0000196
197 // Run codegen to generate BUILD files
Cole Faustb85d1a12022-11-08 18:14:01 -0800198 codegenContext := bp2build.NewCodegenContext(ctx.Config(), ctx, bp2build.ApiBp2build, topDir)
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800199 absoluteApiBp2buildDir := shared.JoinPath(topDir, cmdlineArgs.BazelApiBp2buildDir)
Spandan Das98cb8562023-03-09 23:05:47 +0000200 // Always generate bp2build_all_srcs filegroups in api_bp2build.
201 // This is necessary to force each Android.bp file to create an equivalent BUILD file
202 // and prevent package boundray issues.
203 // e.g.
204 // Source
205 // f/b/Android.bp
206 // java_library{
207 // name: "foo",
208 // api: "api/current.txt",
209 // }
210 //
211 // f/b/api/Android.bp <- will cause package boundary issues
212 //
213 // Gen
214 // f/b/BUILD
215 // java_contribution{
216 // name: "foo.contribution",
217 // api: "//f/b/api:current.txt",
218 // }
219 //
220 // If we don't generate f/b/api/BUILD, foo.contribution will be unbuildable.
221 err := createBazelWorkspace(codegenContext, absoluteApiBp2buildDir, true)
Sasha Smundak1845f422022-12-13 14:18:58 -0800222 maybeQuit(err, "")
Spandan Das5af0bd32022-09-28 20:43:08 +0000223 ninjaDeps = append(ninjaDeps, codegenContext.AdditionalNinjaDeps()...)
224
225 // Create soong_injection repository
Cole Faust9e384e22023-02-08 17:43:09 -0800226 soongInjectionFiles, err := bp2build.CreateSoongInjectionDirFiles(codegenContext, bp2build.CreateCodegenMetrics())
227 maybeQuit(err, "")
Sasha Smundak1845f422022-12-13 14:18:58 -0800228 absoluteSoongInjectionDir := shared.JoinPath(topDir, ctx.Config().SoongOutDir(), bazel.SoongInjectionDirName)
Spandan Das5af0bd32022-09-28 20:43:08 +0000229 for _, file := range soongInjectionFiles {
Spandan Das067210f2022-12-07 01:14:52 +0000230 // The API targets in api_bp2build workspace do not have any dependency on api_bp2build.
231 // But we need to create these files to prevent errors during Bazel analysis.
232 // These need to be created in Read-Write mode.
233 // This is because the subsequent step (bp2build in api domain analysis) creates them in Read-Write mode
234 // to allow users to edit/experiment in the synthetic workspace.
235 writeReadWriteFile(absoluteSoongInjectionDir, file)
Spandan Das5af0bd32022-09-28 20:43:08 +0000236 }
237
Sasha Smundak1845f422022-12-13 14:18:58 -0800238 workspace := shared.JoinPath(ctx.Config().SoongOutDir(), "api_bp2build")
Spandan Das5af0bd32022-09-28 20:43:08 +0000239 // Create the symlink forest
Usta Shresthada15c612022-11-08 14:12:36 -0500240 symlinkDeps, _, _ := bp2build.PlantSymlinkForest(
Sasha Smundak1845f422022-12-13 14:18:58 -0800241 ctx.Config().IsEnvTrue("BP2BUILD_VERBOSE"),
Spandan Das5af0bd32022-09-28 20:43:08 +0000242 topDir,
243 workspace,
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800244 cmdlineArgs.BazelApiBp2buildDir,
Sasha Smundak1845f422022-12-13 14:18:58 -0800245 apiBuildFileExcludes(ctx))
Spandan Das5af0bd32022-09-28 20:43:08 +0000246 ninjaDeps = append(ninjaDeps, symlinkDeps...)
247
248 workspaceMarkerFile := workspace + ".marker"
Paul Duffin780a1852022-11-05 10:17:12 +0000249 writeDepFile(workspaceMarkerFile, ctx.EventHandler, ninjaDeps)
Spandan Das5af0bd32022-09-28 20:43:08 +0000250 touch(shared.JoinPath(topDir, workspaceMarkerFile))
251 return workspaceMarkerFile
252}
253
254// With some exceptions, api_bp2build does not have any dependencies on the checked-in BUILD files
255// Exclude them from the generated workspace to prevent unrelated errors during the loading phase
Sasha Smundak1845f422022-12-13 14:18:58 -0800256func apiBuildFileExcludes(ctx *android.Context) []string {
257 ret := bazelArtifacts()
Spandan Das5af0bd32022-09-28 20:43:08 +0000258 srcs, err := getExistingBazelRelatedFiles(topDir)
Sasha Smundak1845f422022-12-13 14:18:58 -0800259 maybeQuit(err, "Error determining existing Bazel-related files")
Spandan Das5af0bd32022-09-28 20:43:08 +0000260 for _, src := range srcs {
Sasha Smundak1845f422022-12-13 14:18:58 -0800261 // Exclude all src BUILD files
Spandan Das5af0bd32022-09-28 20:43:08 +0000262 if src != "WORKSPACE" &&
263 src != "BUILD" &&
264 src != "BUILD.bazel" &&
265 !strings.HasPrefix(src, "build/bazel") &&
Spandan Das6b91a382022-11-30 02:17:06 +0000266 !strings.HasPrefix(src, "external/bazel-skylib") &&
Spandan Das5af0bd32022-09-28 20:43:08 +0000267 !strings.HasPrefix(src, "prebuilts/clang") {
268 ret = append(ret, src)
269 }
270 }
Sasha Smundak1845f422022-12-13 14:18:58 -0800271 // Android.bp files for api surfaces are mounted to out/, but out/ should not be a
272 // dep for api_bp2build. Otherwise, api_bp2build will be run every single time
273 ret = append(ret, ctx.Config().OutDir())
Spandan Das5af0bd32022-09-28 20:43:08 +0000274 return ret
275}
276
Jeongik Chae114e602023-03-19 00:12:39 +0900277func writeNinjaHint(ctx *android.Context) error {
Jeongik Cha73d49112023-05-04 18:16:11 +0900278 ctx.BeginEvent("ninja_hint")
279 defer ctx.EndEvent("ninja_hint")
Jeongik Chab745e2e2023-04-11 14:28:43 +0900280 // The current predictor focuses on reducing false negatives.
281 // If there are too many false positives (e.g., most modules are marked as positive),
282 // real long-running jobs cannot run early.
283 // Therefore, the model should be adjusted in this case.
284 // The model should also be adjusted if there are critical false negatives.
285 predicate := func(j *blueprint.JsonModule) (prioritized bool, weight int) {
286 prioritized = false
287 weight = 0
288 for prefix, w := range allowlists.HugeModuleTypePrefixMap {
289 if strings.HasPrefix(j.Type, prefix) {
290 prioritized = true
291 weight = w
292 return
293 }
Jeongik Chae114e602023-03-19 00:12:39 +0900294 }
Jeongik Chab745e2e2023-04-11 14:28:43 +0900295 dep_count := len(j.Deps)
296 src_count := 0
297 for _, a := range j.Module["Actions"].([]blueprint.JSONAction) {
298 src_count += len(a.Inputs)
299 }
300 input_size := dep_count + src_count
301
302 // Current threshold is an arbitrary value which only consider recall rather than accuracy.
303 if input_size > allowlists.INPUT_SIZE_THRESHOLD {
304 prioritized = true
305 weight += ((input_size) / allowlists.INPUT_SIZE_THRESHOLD) * allowlists.DEFAULT_PRIORITIZED_WEIGHT
306
307 // To prevent some modules from having too large a priority value.
308 if weight > allowlists.HIGH_PRIORITIZED_WEIGHT {
309 weight = allowlists.HIGH_PRIORITIZED_WEIGHT
310 }
311 }
312 return
313 }
314
315 outputsMap := ctx.Context.GetWeightedOutputsFromPredicate(predicate)
316 var outputBuilder strings.Builder
317 for output, weight := range outputsMap {
318 outputBuilder.WriteString(fmt.Sprintf("%s,%d\n", output, weight))
Jeongik Chae114e602023-03-19 00:12:39 +0900319 }
320 weightListFile := filepath.Join(topDir, ctx.Config().OutDir(), ".ninja_weight_list")
321
322 err := os.WriteFile(weightListFile, []byte(outputBuilder.String()), 0644)
323 if err != nil {
324 return fmt.Errorf("could not write ninja weight list file %s", err)
325 }
326 return nil
327}
328
Paul Duffin780a1852022-11-05 10:17:12 +0000329func writeMetrics(configuration android.Config, eventHandler *metrics.EventHandler, metricsDir string) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400330 if len(metricsDir) < 1 {
331 fmt.Fprintf(os.Stderr, "\nMissing required env var for generating soong metrics: LOG_DIR\n")
332 os.Exit(1)
333 }
334 metricsFile := filepath.Join(metricsDir, "soong_build_metrics.pb")
335 err := android.WriteMetrics(configuration, eventHandler, metricsFile)
Sasha Smundak1845f422022-12-13 14:18:58 -0800336 maybeQuit(err, "error writing soong_build metrics %s", metricsFile)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200337}
338
MarkDacekf47e1422023-04-19 16:47:36 +0000339// Errors out if any modules expected to be mixed_built were not, unless
MarkDacek6f6b9622023-05-02 16:28:55 +0000340// the modules did not exist.
MarkDacekf47e1422023-04-19 16:47:36 +0000341func checkForAllowlistIntegrityError(configuration android.Config, isStagingMode bool) error {
MarkDacek6f6b9622023-05-02 16:28:55 +0000342 modules := findMisconfiguredModules(configuration, isStagingMode)
MarkDacekf47e1422023-04-19 16:47:36 +0000343 if len(modules) == 0 {
344 return nil
345 }
346
347 return fmt.Errorf("Error: expected the following modules to be mixed_built: %s", modules)
348}
349
MarkDacek6f6b9622023-05-02 16:28:55 +0000350// Returns true if the given module has all of the following true:
351// 1. Is allowlisted to be built with Bazel.
352// 2. Has a variant which is *not* built with Bazel.
353// 3. Has no variant which is built with Bazel.
354//
355// This indicates the allowlisting of this variant had no effect.
356// TODO(b/280457637): Return true for nonexistent modules.
357func isAllowlistMisconfiguredForModule(module string, mixedBuildsEnabled map[string]struct{}, mixedBuildsDisabled map[string]struct{}) bool {
MarkDacek6f6b9622023-05-02 16:28:55 +0000358 _, enabled := mixedBuildsEnabled[module]
359
360 if enabled {
361 return false
362 }
363
364 _, disabled := mixedBuildsDisabled[module]
365 return disabled
366
367}
368
MarkDacekf47e1422023-04-19 16:47:36 +0000369// Returns the list of modules that should have been mixed_built (per the
370// allowlists and cmdline flags) but were not.
MarkDacek6f6b9622023-05-02 16:28:55 +0000371// Note: nonexistent modules are excluded from the list. See b/280457637
372func findMisconfiguredModules(configuration android.Config, isStagingMode bool) []string {
MarkDacekf47e1422023-04-19 16:47:36 +0000373 retval := []string{}
374 forceEnabledModules := configuration.BazelModulesForceEnabledByFlag()
375
376 mixedBuildsEnabled := configuration.GetMixedBuildsEnabledModules()
MarkDacek6f6b9622023-05-02 16:28:55 +0000377 mixedBuildsDisabled := configuration.GetMixedBuildsDisabledModules()
MarkDacekf47e1422023-04-19 16:47:36 +0000378 for _, module := range allowlists.ProdMixedBuildsEnabledList {
MarkDacek6f6b9622023-05-02 16:28:55 +0000379 if isAllowlistMisconfiguredForModule(module, mixedBuildsEnabled, mixedBuildsDisabled) {
MarkDacekf47e1422023-04-19 16:47:36 +0000380 retval = append(retval, module)
381 }
382 }
383
384 if isStagingMode {
385 for _, module := range allowlists.StagingMixedBuildsEnabledList {
MarkDacek6f6b9622023-05-02 16:28:55 +0000386 if isAllowlistMisconfiguredForModule(module, mixedBuildsEnabled, mixedBuildsDisabled) {
MarkDacekf47e1422023-04-19 16:47:36 +0000387 retval = append(retval, module)
388 }
389 }
390 }
391
392 for module, _ := range forceEnabledModules {
MarkDacek6f6b9622023-05-02 16:28:55 +0000393 if isAllowlistMisconfiguredForModule(module, mixedBuildsEnabled, mixedBuildsDisabled) {
MarkDacekf47e1422023-04-19 16:47:36 +0000394 retval = append(retval, module)
395 }
396 }
397 return retval
398}
399
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800400func writeJsonModuleGraphAndActions(ctx *android.Context, cmdArgs android.CmdArgs) {
401 graphFile, graphErr := os.Create(shared.JoinPath(topDir, cmdArgs.ModuleGraphFile))
Sasha Smundak1845f422022-12-13 14:18:58 -0800402 maybeQuit(graphErr, "graph err")
kgui67007242022-01-25 13:50:25 +0800403 defer graphFile.Close()
Sasha Smundak1845f422022-12-13 14:18:58 -0800404 actionsFile, actionsErr := os.Create(shared.JoinPath(topDir, cmdArgs.ModuleActionsFile))
405 maybeQuit(actionsErr, "actions err")
kgui67007242022-01-25 13:50:25 +0800406 defer actionsFile.Close()
407 ctx.Context.PrintJSONGraphAndActions(graphFile, actionsFile)
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200408}
409
Sasha Smundak1845f422022-12-13 14:18:58 -0800410func writeBuildGlobsNinjaFile(ctx *android.Context) []string {
Chris Parsons715b08f2022-03-22 19:23:40 -0400411 ctx.EventHandler.Begin("globs_ninja_file")
412 defer ctx.EventHandler.End("globs_ninja_file")
413
Sasha Smundak1845f422022-12-13 14:18:58 -0800414 globDir := bootstrap.GlobDirectory(ctx.Config().SoongOutDir(), globListDir)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200415 bootstrap.WriteBuildGlobsNinjaFile(&bootstrap.GlobSingleton{
Chris Parsons715b08f2022-03-22 19:23:40 -0400416 GlobLister: ctx.Globs,
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200417 GlobFile: globFile,
418 GlobDir: globDir,
Chris Parsons715b08f2022-03-22 19:23:40 -0400419 SrcDir: ctx.SrcDir(),
Sasha Smundak1845f422022-12-13 14:18:58 -0800420 }, ctx.Config())
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200421 return bootstrap.GlobFileListFiles(globDir)
422}
423
Paul Duffin780a1852022-11-05 10:17:12 +0000424func writeDepFile(outputFile string, eventHandler *metrics.EventHandler, ninjaDeps []string) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400425 eventHandler.Begin("ninja_deps")
426 defer eventHandler.End("ninja_deps")
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200427 depFile := shared.JoinPath(topDir, outputFile+".d")
428 err := deptools.WriteDepFile(depFile, outputFile, ninjaDeps)
Sasha Smundak1845f422022-12-13 14:18:58 -0800429 maybeQuit(err, "error writing depfile '%s'", depFile)
Paul Duffin0c09a432022-11-05 15:28:04 +0000430}
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200431
Paul Duffin0c09a432022-11-05 15:28:04 +0000432// runSoongOnlyBuild runs the standard Soong build in a number of different modes.
Sasha Smundak1845f422022-12-13 14:18:58 -0800433func runSoongOnlyBuild(ctx *android.Context, extraNinjaDeps []string) string {
Paul Duffin39eae8f2022-11-05 14:59:52 +0000434 ctx.EventHandler.Begin("soong_build")
435 defer ctx.EventHandler.End("soong_build")
436
Paul Duffin0c09a432022-11-05 15:28:04 +0000437 var stopBefore bootstrap.StopBefore
Sasha Smundak1845f422022-12-13 14:18:58 -0800438 switch ctx.Config().BuildMode {
439 case android.GenerateModuleGraph:
Paul Duffin0c09a432022-11-05 15:28:04 +0000440 stopBefore = bootstrap.StopBeforeWriteNinja
Usta Shrestha7fae6952022-12-21 11:46:28 -0500441 case android.GenerateQueryView, android.GenerateDocFile:
Paul Duffin0c09a432022-11-05 15:28:04 +0000442 stopBefore = bootstrap.StopBeforePrepareBuildActions
Sasha Smundak1845f422022-12-13 14:18:58 -0800443 default:
Paul Duffin0c09a432022-11-05 15:28:04 +0000444 stopBefore = bootstrap.DoEverything
445 }
446
Sasha Smundak1845f422022-12-13 14:18:58 -0800447 ninjaDeps := bootstrap.RunBlueprint(cmdlineArgs.Args, stopBefore, ctx.Context, ctx.Config())
Paul Duffin0c09a432022-11-05 15:28:04 +0000448 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
449
Sasha Smundak1845f422022-12-13 14:18:58 -0800450 globListFiles := writeBuildGlobsNinjaFile(ctx)
Paul Duffin0c09a432022-11-05 15:28:04 +0000451 ninjaDeps = append(ninjaDeps, globListFiles...)
452
453 // Convert the Soong module graph into Bazel BUILD files.
Sasha Smundak1845f422022-12-13 14:18:58 -0800454 switch ctx.Config().BuildMode {
455 case android.GenerateQueryView:
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800456 queryviewMarkerFile := cmdlineArgs.BazelQueryViewDir + ".marker"
Sasha Smundak1845f422022-12-13 14:18:58 -0800457 runQueryView(cmdlineArgs.BazelQueryViewDir, queryviewMarkerFile, ctx)
Paul Duffin0c09a432022-11-05 15:28:04 +0000458 writeDepFile(queryviewMarkerFile, ctx.EventHandler, ninjaDeps)
459 return queryviewMarkerFile
Sasha Smundak1845f422022-12-13 14:18:58 -0800460 case android.GenerateModuleGraph:
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800461 writeJsonModuleGraphAndActions(ctx, cmdlineArgs)
462 writeDepFile(cmdlineArgs.ModuleGraphFile, ctx.EventHandler, ninjaDeps)
463 return cmdlineArgs.ModuleGraphFile
Sasha Smundak1845f422022-12-13 14:18:58 -0800464 case android.GenerateDocFile:
Paul Duffin0c09a432022-11-05 15:28:04 +0000465 // TODO: we could make writeDocs() return the list of documentation files
466 // written and add them to the .d file. Then soong_docs would be re-run
467 // whenever one is deleted.
Sasha Smundak1845f422022-12-13 14:18:58 -0800468 err := writeDocs(ctx, shared.JoinPath(topDir, cmdlineArgs.DocFile))
469 maybeQuit(err, "error building Soong documentation")
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800470 writeDepFile(cmdlineArgs.DocFile, ctx.EventHandler, ninjaDeps)
471 return cmdlineArgs.DocFile
Sasha Smundak1845f422022-12-13 14:18:58 -0800472 default:
Paul Duffin0c09a432022-11-05 15:28:04 +0000473 // The actual output (build.ninja) was written in the RunBlueprint() call
474 // above
475 writeDepFile(cmdlineArgs.OutFile, ctx.EventHandler, ninjaDeps)
Jeongik Chaa87506f2023-06-01 23:16:41 +0900476 if needToWriteNinjaHint(ctx) {
Jeongik Cha591366d2023-05-08 11:32:52 +0900477 writeNinjaHint(ctx)
478 }
Paul Duffinb713ddf2022-11-05 16:14:30 +0000479 return cmdlineArgs.OutFile
Paul Duffin0c09a432022-11-05 15:28:04 +0000480 }
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200481}
482
483// soong_ui dumps the available environment variables to
484// soong.environment.available . Then soong_build itself is run with an empty
485// environment so that the only way environment variables can be accessed is
486// using Config, which tracks access to them.
487
488// At the end of the build, a file called soong.environment.used is written
489// containing the current value of all used environment variables. The next
490// time soong_ui is run, it checks whether any environment variables that was
491// used had changed and if so, it deletes soong.environment.used to cause a
492// rebuild.
493//
494// The dependency of build.ninja on soong.environment.used is declared in
495// build.ninja.d
496func parseAvailableEnv() map[string]string {
497 if availableEnvFile == "" {
498 fmt.Fprintf(os.Stderr, "--available_env not set\n")
499 os.Exit(1)
500 }
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200501 result, err := shared.EnvFromFile(shared.JoinPath(topDir, availableEnvFile))
Sasha Smundak1845f422022-12-13 14:18:58 -0800502 maybeQuit(err, "error reading available environment file '%s'", availableEnvFile)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200503 return result
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200504}
505
Colin Cross3f40fa42015-01-30 17:27:36 -0800506func main() {
507 flag.Parse()
508
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100509 shared.ReexecWithDelveMaybe(delveListen, delvePath)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100510 android.InitSandbox(topDir)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100511
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200512 availableEnv := parseAvailableEnv()
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800513 configuration, err := android.NewConfig(cmdlineArgs, availableEnv)
Sasha Smundak1845f422022-12-13 14:18:58 -0800514 maybeQuit(err, "")
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100515 if configuration.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
516 configuration.SetAllowMissingDependencies()
517 }
518
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800519 extraNinjaDeps := []string{configuration.ProductVariablesFileName, usedEnvFile}
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100520 if shared.IsDebugging() {
Colin Crossaa812d12019-06-19 13:33:24 -0700521 // Add a non-existent file to the dependencies so that soong_build will rerun when the debugger is
522 // enabled even if it completed successfully.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200523 extraNinjaDeps = append(extraNinjaDeps, filepath.Join(configuration.SoongOutDir(), "always_rerun_for_delve"))
Colin Crossaa812d12019-06-19 13:33:24 -0700524 }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500525
Dan Willemsenccf36aa2022-04-20 23:11:43 -0700526 // Bypass configuration.Getenv, as LOG_DIR does not need to be dependency tracked. By definition, it will
527 // change between every CI build, so tracking it would require re-running Soong for every build.
Sasha Smundak1845f422022-12-13 14:18:58 -0800528 metricsDir := availableEnv["LOG_DIR"]
Dan Willemsenccf36aa2022-04-20 23:11:43 -0700529
Joe Onorato2e5e4012022-06-07 17:16:08 -0700530 ctx := newContext(configuration)
Joe Onorato2e5e4012022-06-07 17:16:08 -0700531
Sasha Smundak1845f422022-12-13 14:18:58 -0800532 var finalOutputFile string
Joe Onorato2e5e4012022-06-07 17:16:08 -0700533
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900534 writeSymlink := false
535
Sasha Smundak1845f422022-12-13 14:18:58 -0800536 // Run Soong for a specific activity, like bp2build, queryview
537 // or the actual Soong build for the build.ninja file.
538 switch configuration.BuildMode {
539 case android.SymlinkForest:
540 finalOutputFile = runSymlinkForestCreation(ctx, extraNinjaDeps, metricsDir)
541 case android.Bp2build:
542 // Run the alternate pipeline of bp2build mutators and singleton to convert
543 // Blueprint to BUILD files before everything else.
544 finalOutputFile = runBp2Build(ctx, extraNinjaDeps, metricsDir)
545 case android.ApiBp2build:
546 finalOutputFile = runApiBp2build(ctx, extraNinjaDeps)
547 writeMetrics(configuration, ctx.EventHandler, metricsDir)
548 default:
549 ctx.Register()
MarkDacekf47e1422023-04-19 16:47:36 +0000550 isMixedBuildsEnabled := configuration.IsMixedBuildsEnabled()
551 if isMixedBuildsEnabled {
Sasha Smundak1845f422022-12-13 14:18:58 -0800552 finalOutputFile = runMixedModeBuild(ctx, extraNinjaDeps)
MarkDacekf47e1422023-04-19 16:47:36 +0000553 if cmdlineArgs.EnsureAllowlistIntegrity {
554 if err := checkForAllowlistIntegrityError(configuration, cmdlineArgs.BazelModeStaging); err != nil {
555 maybeQuit(err, "")
556 }
557 }
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900558 writeSymlink = true
Sasha Smundak1845f422022-12-13 14:18:58 -0800559 } else {
560 finalOutputFile = runSoongOnlyBuild(ctx, extraNinjaDeps)
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900561
562 if configuration.BuildMode == android.AnalysisNoBazel {
563 writeSymlink = true
564 }
Sasha Smundak1845f422022-12-13 14:18:58 -0800565 }
566 writeMetrics(configuration, ctx.EventHandler, metricsDir)
567 }
Chris Parsonsc83398f2023-05-31 18:41:41 +0000568
569 // Register this environment variablesas being an implicit dependencies of
570 // soong_build. Changes to this environment variable will result in
571 // retriggering soong_build.
572 configuration.Getenv("USE_BAZEL_VERSION")
573
Chris Parsonsa3ae0072023-05-10 21:10:08 +0000574 writeUsedEnvironmentFile(configuration)
575
576 // Touch the output file so that it's the newest file created by soong_build.
577 // This is necessary because, if soong_build generated any files which
578 // are ninja inputs to the main output file, then ninja would superfluously
579 // rebuild this output file on the next build invocation.
580 touch(shared.JoinPath(topDir, finalOutputFile))
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900581
582 // TODO(b/277029044): Remove this function once build.<product>.ninja lands
583 if writeSymlink {
584 writeBuildNinjaSymlink(configuration, finalOutputFile)
585 }
586}
587
588// TODO(b/277029044): Remove this function once build.<product>.ninja lands
589func writeBuildNinjaSymlink(config android.Config, source string) {
590 targetPath := shared.JoinPath(topDir, config.SoongOutDir(), "build.ninja")
591 sourcePath := shared.JoinPath(topDir, source)
592
593 if targetPath == sourcePath {
594 return
595 }
596
597 os.Remove(targetPath)
598 os.Symlink(sourcePath, targetPath)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100599}
600
Chris Parsonsa3ae0072023-05-10 21:10:08 +0000601func writeUsedEnvironmentFile(configuration android.Config) {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200602 if usedEnvFile == "" {
603 return
604 }
605
606 path := shared.JoinPath(topDir, usedEnvFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100607 data, err := shared.EnvFileContents(configuration.EnvDeps())
Sasha Smundak1845f422022-12-13 14:18:58 -0800608 maybeQuit(err, "error writing used environment file '%s'\n", usedEnvFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100609
Usta Shrestha2ba28a32022-10-24 11:33:09 -0400610 if preexistingData, err := os.ReadFile(path); err != nil {
611 if !os.IsNotExist(err) {
Sasha Smundak1845f422022-12-13 14:18:58 -0800612 maybeQuit(err, "error reading used environment file '%s'", usedEnvFile)
Usta Shrestha2ba28a32022-10-24 11:33:09 -0400613 }
614 } else if bytes.Equal(preexistingData, data) {
615 // used environment file is unchanged
616 return
617 }
Sasha Smundak1845f422022-12-13 14:18:58 -0800618 err = os.WriteFile(path, data, 0666)
619 maybeQuit(err, "error writing used environment file '%s'", usedEnvFile)
Colin Cross3f40fa42015-01-30 17:27:36 -0800620}
Jingwen Chen5ba7e472020-07-15 10:06:41 +0000621
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200622func touch(path string) {
623 f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
Sasha Smundak1845f422022-12-13 14:18:58 -0800624 maybeQuit(err, "Error touching '%s'", path)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200625 err = f.Close()
Sasha Smundak1845f422022-12-13 14:18:58 -0800626 maybeQuit(err, "Error touching '%s'", path)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200627
628 currentTime := time.Now().Local()
629 err = os.Chtimes(path, currentTime, currentTime)
Sasha Smundak1845f422022-12-13 14:18:58 -0800630 maybeQuit(err, "error touching '%s'", path)
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400631}
632
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400633// Read the bazel.list file that the Soong Finder already dumped earlier (hopefully)
634// It contains the locations of BUILD files, BUILD.bazel files, etc. in the source dir
635func getExistingBazelRelatedFiles(topDir string) ([]string, error) {
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200636 bazelFinderFile := filepath.Join(filepath.Dir(cmdlineArgs.ModuleListFile), "bazel.list")
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400637 if !filepath.IsAbs(bazelFinderFile) {
638 // Assume this was a relative path under topDir
639 bazelFinderFile = filepath.Join(topDir, bazelFinderFile)
640 }
Sasha Smundak1845f422022-12-13 14:18:58 -0800641 return readFileLines(bazelFinderFile)
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400642}
643
Spandan Das5af0bd32022-09-28 20:43:08 +0000644func bazelArtifacts() []string {
645 return []string{
646 "bazel-bin",
647 "bazel-genfiles",
648 "bazel-out",
649 "bazel-testlogs",
Usta (Tsering) Shresthac4c07b12022-11-08 18:31:14 -0500650 "bazel-workspace",
Spandan Das5af0bd32022-09-28 20:43:08 +0000651 "bazel-" + filepath.Base(topDir),
652 }
653}
654
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000655// This could in theory easily be separated into a binary that generically
656// merges two directories into a symlink tree. The main obstacle is that this
657// function currently depends on both Bazel-specific knowledge (the existence
658// of bazel-* symlinks) and configuration (the set of BUILD.bazel files that
659// should and should not be kept)
660//
661// Ideally, bp2build would write a file that contains instructions to the
662// symlink tree creation binary. Then the latter would not need to depend on
663// the very heavy-weight machinery of soong_build .
Sasha Smundak1845f422022-12-13 14:18:58 -0800664func runSymlinkForestCreation(ctx *android.Context, extraNinjaDeps []string, metricsDir string) string {
Usta Shresthada15c612022-11-08 14:12:36 -0500665 var ninjaDeps []string
666 var mkdirCount, symlinkCount uint64
667
Paul Duffinb4e8d912022-11-04 13:35:50 +0000668 ctx.EventHandler.Do("symlink_forest", func() {
Usta (Tsering) Shrestha93b2a9b2022-12-01 05:55:35 +0000669 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Sasha Smundak1845f422022-12-13 14:18:58 -0800670 verbose := ctx.Config().IsEnvTrue("BP2BUILD_VERBOSE")
Usta (Tsering) Shrestha93b2a9b2022-12-01 05:55:35 +0000671
672 // PlantSymlinkForest() returns all the directories that were readdir()'ed.
673 // Such a directory SHOULD be added to `ninjaDeps` so that a child directory
674 // or file created/deleted under it would trigger an update of the symlink forest.
Sasha Smundak1845f422022-12-13 14:18:58 -0800675 generatedRoot := shared.JoinPath(ctx.Config().SoongOutDir(), "bp2build")
676 workspaceRoot := shared.JoinPath(ctx.Config().SoongOutDir(), "workspace")
Usta Shresthada15c612022-11-08 14:12:36 -0500677 var symlinkForestDeps []string
Usta (Tsering) Shrestha93b2a9b2022-12-01 05:55:35 +0000678 ctx.EventHandler.Do("plant", func() {
Usta Shresthada15c612022-11-08 14:12:36 -0500679 symlinkForestDeps, mkdirCount, symlinkCount = bp2build.PlantSymlinkForest(
Sasha Smundak1845f422022-12-13 14:18:58 -0800680 verbose, topDir, workspaceRoot, generatedRoot, excludedFromSymlinkForest(ctx, verbose))
Usta (Tsering) Shrestha93b2a9b2022-12-01 05:55:35 +0000681 })
Usta Shresthada15c612022-11-08 14:12:36 -0500682 ninjaDeps = append(ninjaDeps, symlinkForestDeps...)
Usta (Tsering) Shrestha93b2a9b2022-12-01 05:55:35 +0000683 })
Usta Shresthada15c612022-11-08 14:12:36 -0500684
685 writeDepFile(cmdlineArgs.SymlinkForestMarker, ctx.EventHandler, ninjaDeps)
686 touch(shared.JoinPath(topDir, cmdlineArgs.SymlinkForestMarker))
usta4f5d2c12022-10-28 23:32:01 -0400687 codegenMetrics := bp2build.ReadCodegenMetrics(metricsDir)
688 if codegenMetrics == nil {
689 m := bp2build.CreateCodegenMetrics()
690 codegenMetrics = &m
691 } else {
692 //TODO (usta) we cannot determine if we loaded a stale file, i.e. from an unrelated prior
693 //invocation of codegen. We should simply use a separate .pb file
694 }
Usta Shresthada15c612022-11-08 14:12:36 -0500695 codegenMetrics.SetSymlinkCount(symlinkCount)
696 codegenMetrics.SetMkDirCount(mkdirCount)
Paul Duffinb4e8d912022-11-04 13:35:50 +0000697 writeBp2BuildMetrics(codegenMetrics, ctx.EventHandler, metricsDir)
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800698 return cmdlineArgs.SymlinkForestMarker
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000699}
700
Sasha Smundak1845f422022-12-13 14:18:58 -0800701func excludedFromSymlinkForest(ctx *android.Context, verbose bool) []string {
702 excluded := bazelArtifacts()
703 if cmdlineArgs.OutDir[0] != '/' {
704 excluded = append(excluded, cmdlineArgs.OutDir)
705 }
706
707 // Find BUILD files in the srcDir which are not in the allowlist
708 // (android.Bp2BuildConversionAllowlist#ShouldKeepExistingBuildFileForDir)
709 // and return their paths so they can be left out of the Bazel workspace dir (i.e. ignored)
710 existingBazelFiles, err := getExistingBazelRelatedFiles(topDir)
711 maybeQuit(err, "Error determining existing Bazel-related files")
712
713 for _, path := range existingBazelFiles {
714 fullPath := shared.JoinPath(topDir, path)
715 fileInfo, err2 := os.Stat(fullPath)
716 if err2 != nil {
717 // Warn about error, but continue trying to check files
718 fmt.Fprintf(os.Stderr, "WARNING: Error accessing path '%s', err: %s\n", fullPath, err2)
719 continue
720 }
721 // Exclude only files named 'BUILD' or 'BUILD.bazel' and unless forcibly kept
722 if fileInfo.IsDir() ||
723 (fileInfo.Name() != "BUILD" && fileInfo.Name() != "BUILD.bazel") ||
724 ctx.Config().Bp2buildPackageConfig.ShouldKeepExistingBuildFileForDir(filepath.Dir(path)) {
725 // Don't ignore this existing build file
726 continue
727 }
728 if verbose {
729 fmt.Fprintf(os.Stderr, "Ignoring existing BUILD file: %s\n", path)
730 }
731 excluded = append(excluded, path)
732 }
733
734 // Temporarily exclude stuff to make `bazel build //external/...` (and `bazel build //frameworks/...`) work
735 excluded = append(excluded,
736 // FIXME: 'autotest_lib' is a symlink back to external/autotest, and this causes an infinite
737 // symlink expansion error for Bazel
738 "external/autotest/venv/autotest_lib",
739 "external/autotest/autotest_lib",
740 "external/autotest/client/autotest_lib/client",
741
742 // FIXME: The external/google-fruit/extras/bazel_root/third_party/fruit dir is poison
743 // It contains several symlinks back to real source dirs, and those source dirs contain
744 // BUILD files we want to ignore
745 "external/google-fruit/extras/bazel_root/third_party/fruit",
746
747 // FIXME: 'frameworks/compile/slang' has a filegroup error due to an escaping issue
748 "frameworks/compile/slang",
749
750 // FIXME(b/260809113): 'prebuilts/clang/host/linux-x86/clang-dev' is a tool-generated symlink
751 // directory that contains a BUILD file. The bazel files finder code doesn't traverse into symlink dirs,
752 // and hence is not aware of this BUILD file and exclude it accordingly during symlink forest generation
753 // when checking against keepExistingBuildFiles allowlist.
754 //
755 // This is necessary because globs in //prebuilts/clang/host/linux-x86/BUILD
756 // currently assume no subpackages (keepExistingBuildFile is not recursive for that directory).
757 //
758 // This is a bandaid until we the symlink forest logic can intelligently exclude BUILD files found in
759 // source symlink dirs according to the keepExistingBuildFile allowlist.
760 "prebuilts/clang/host/linux-x86/clang-dev",
761 )
762 return excluded
763}
764
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500765// Run Soong in the bp2build mode. This creates a standalone context that registers
766// an alternate pipeline of mutators and singletons specifically for generating
767// Bazel BUILD files instead of Ninja files.
Sasha Smundak1845f422022-12-13 14:18:58 -0800768func runBp2Build(ctx *android.Context, extraNinjaDeps []string, metricsDir string) string {
usta4f5d2c12022-10-28 23:32:01 -0400769 var codegenMetrics *bp2build.CodegenMetrics
Paul Duffinb4e8d912022-11-04 13:35:50 +0000770 ctx.EventHandler.Do("bp2build", func() {
Jingwen Cheneb76c432021-01-28 08:22:12 -0500771
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400772 // Propagate "allow misssing dependencies" bit. This is normally set in
Paul Duffinb4e8d912022-11-04 13:35:50 +0000773 // newContext(), but we create ctx without calling that method.
Sasha Smundak1845f422022-12-13 14:18:58 -0800774 ctx.SetAllowMissingDependencies(ctx.Config().AllowMissingDependencies())
775 ctx.SetNameInterface(newNameResolver(ctx.Config()))
Paul Duffinb4e8d912022-11-04 13:35:50 +0000776 ctx.RegisterForBazelConversion()
777 ctx.SetModuleListFile(cmdlineArgs.ModuleListFile)
Jingwen Cheneb76c432021-01-28 08:22:12 -0500778
Usta Shresthaa117c582022-10-04 12:13:25 -0400779 var ninjaDeps []string
780 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
781
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400782 // Run the loading and analysis pipeline to prepare the graph of regular
783 // Modules parsed from Android.bp files, and the BazelTargetModules mapped
784 // from the regular Modules.
Paul Duffinb4e8d912022-11-04 13:35:50 +0000785 ctx.EventHandler.Do("bootstrap", func() {
Usta Shresthaa117c582022-10-04 12:13:25 -0400786 blueprintArgs := cmdlineArgs
Sasha Smundak1845f422022-12-13 14:18:58 -0800787 bootstrapDeps := bootstrap.RunBlueprint(blueprintArgs.Args,
788 bootstrap.StopBeforePrepareBuildActions, ctx.Context, ctx.Config())
Usta Shresthaa117c582022-10-04 12:13:25 -0400789 ninjaDeps = append(ninjaDeps, bootstrapDeps...)
790 })
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200791
Sasha Smundak1845f422022-12-13 14:18:58 -0800792 globListFiles := writeBuildGlobsNinjaFile(ctx)
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400793 ninjaDeps = append(ninjaDeps, globListFiles...)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200794
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400795 // Run the code-generation phase to convert BazelTargetModules to BUILD files
Usta Shresthaa117c582022-10-04 12:13:25 -0400796 // and print conversion codegenMetrics to the user.
Cole Faustb85d1a12022-11-08 18:14:01 -0800797 codegenContext := bp2build.NewCodegenContext(ctx.Config(), ctx, bp2build.Bp2Build, topDir)
Paul Duffinb4e8d912022-11-04 13:35:50 +0000798 ctx.EventHandler.Do("codegen", func() {
Usta Shresthaa117c582022-10-04 12:13:25 -0400799 codegenMetrics = bp2build.Codegen(codegenContext)
800 })
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200801
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400802 ninjaDeps = append(ninjaDeps, codegenContext.AdditionalNinjaDeps()...)
Chris Parsons715b08f2022-03-22 19:23:40 -0400803
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800804 writeDepFile(cmdlineArgs.Bp2buildMarker, ctx.EventHandler, ninjaDeps)
805 touch(shared.JoinPath(topDir, cmdlineArgs.Bp2buildMarker))
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400806 })
Chris Parsons715b08f2022-03-22 19:23:40 -0400807
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200808 // Only report metrics when in bp2build mode. The metrics aren't relevant
809 // for queryview, since that's a total repo-wide conversion and there's a
810 // 1:1 mapping for each module.
Sasha Smundak1845f422022-12-13 14:18:58 -0800811 if ctx.Config().IsEnvTrue("BP2BUILD_VERBOSE") {
Usta Shresthaa117c582022-10-04 12:13:25 -0400812 codegenMetrics.Print()
Sasha Smundak0fd93e02022-05-19 19:34:31 -0700813 }
Paul Duffinb4e8d912022-11-04 13:35:50 +0000814 writeBp2BuildMetrics(codegenMetrics, ctx.EventHandler, metricsDir)
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800815 return cmdlineArgs.Bp2buildMarker
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500816}
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500817
818// Write Bp2Build metrics into $LOG_DIR
Paul Duffinf4906562022-11-05 14:21:16 +0000819func writeBp2BuildMetrics(codegenMetrics *bp2build.CodegenMetrics, eventHandler *metrics.EventHandler, metricsDir string) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400820 for _, event := range eventHandler.CompletedEvents() {
usta4f5d2c12022-10-28 23:32:01 -0400821 codegenMetrics.AddEvent(&bp2build_metrics_proto.Event{
822 Name: event.Id,
823 StartTime: uint64(event.Start.UnixNano()),
824 RealTime: event.RuntimeNanoseconds(),
825 })
Chris Parsons715b08f2022-03-22 19:23:40 -0400826 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500827 if len(metricsDir) < 1 {
828 fmt.Fprintf(os.Stderr, "\nMissing required env var for generating bp2build metrics: LOG_DIR\n")
829 os.Exit(1)
830 }
Chris Parsons715b08f2022-03-22 19:23:40 -0400831 codegenMetrics.Write(metricsDir)
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500832}
MarkDacek0d5bca52022-10-10 20:07:48 +0000833
Sasha Smundak1845f422022-12-13 14:18:58 -0800834func readFileLines(path string) ([]string, error) {
835 data, err := os.ReadFile(path)
836 if err == nil {
837 return strings.Split(strings.TrimSpace(string(data)), "\n"), nil
MarkDacek0d5bca52022-10-10 20:07:48 +0000838 }
Sasha Smundak1845f422022-12-13 14:18:58 -0800839 return nil, err
840
841}
842func maybeQuit(err error, format string, args ...interface{}) {
843 if err == nil {
844 return
845 }
846 if format != "" {
847 fmt.Fprintln(os.Stderr, fmt.Sprintf(format, args...)+": "+err.Error())
848 } else {
849 fmt.Fprintln(os.Stderr, err)
850 }
851 os.Exit(1)
MarkDacek0d5bca52022-10-10 20:07:48 +0000852}