blob: 69756778c74b5cd6b925b2b26c8491f7b41726c3 [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 Parsons9402ca82023-02-23 17:28:06 -050088 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 +000089 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 +000090 flag.BoolVar(&cmdlineArgs.EnsureAllowlistIntegrity, "ensure-allowlist-integrity", false, "verify that allowlisted modules are mixed-built")
Sasha Smundakaf5ca922022-12-12 21:23:34 -080091 // Flags that probably shouldn't be flags of soong_build, but we haven't found
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020092 // the time to remove them yet
Sasha Smundakaf5ca922022-12-12 21:23:34 -080093 flag.BoolVar(&cmdlineArgs.RunGoTests, "t", false, "build and run go tests during bootstrap")
Dan Willemsen66213a62021-09-21 17:50:30 -070094
95 // Disable deterministic randomization in the protobuf package, so incremental
96 // builds with unrelated Soong changes don't trigger large rebuilds (since we
97 // write out text protos in command lines, and command line changes trigger
98 // rebuilds).
99 androidProtobuf.DisableRand()
Colin Crosse87040b2017-12-11 15:52:26 -0800100}
101
Jeff Gaston088e29e2017-11-29 16:47:17 -0800102func newNameResolver(config android.Config) *android.NameResolver {
Paul Duffin3f7bf9f2022-11-08 12:21:15 +0000103 return android.NewNameResolver(config)
Jeff Gaston088e29e2017-11-29 16:47:17 -0800104}
105
Lukacs T. Berkiffc9e8d2021-09-07 17:54:38 +0200106func newContext(configuration android.Config) *android.Context {
Colin Crossae8600b2020-10-29 17:09:13 -0700107 ctx := android.NewContext(configuration)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400108 ctx.SetNameInterface(newNameResolver(configuration))
109 ctx.SetAllowMissingDependencies(configuration.AllowMissingDependencies())
Spandan Dasc5763832022-11-08 18:42:16 +0000110 ctx.AddIncludeTags(configuration.IncludeTags()...)
Sam Delmerico98a73292023-02-21 11:50:29 -0500111 ctx.AddSourceRootDirs(configuration.SourceRootDirs()...)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400112 return ctx
113}
114
Chris Parsonsf874e462022-05-10 13:50:12 -0400115// Bazel-enabled mode. Attaches a mutator to queue Bazel requests, adds a
116// BeforePrepareBuildActionsHook to invoke Bazel, and then uses Bazel metadata
117// for modules that should be handled by Bazel.
Sasha Smundak1845f422022-12-13 14:18:58 -0800118func runMixedModeBuild(ctx *android.Context, extraNinjaDeps []string) string {
Chris Parsonsf874e462022-05-10 13:50:12 -0400119 ctx.EventHandler.Begin("mixed_build")
120 defer ctx.EventHandler.End("mixed_build")
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200121
Chris Parsonsf874e462022-05-10 13:50:12 -0400122 bazelHook := func() error {
Sasha Smundak1845f422022-12-13 14:18:58 -0800123 return ctx.Config().BazelContext.InvokeBazel(ctx.Config(), ctx)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200124 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400125 ctx.SetBeforePrepareBuildActionsHook(bazelHook)
Sasha Smundak1845f422022-12-13 14:18:58 -0800126 ninjaDeps := bootstrap.RunBlueprint(cmdlineArgs.Args, bootstrap.DoEverything, ctx.Context, ctx.Config())
Chris Parsons027881c2022-05-24 15:38:38 -0400127 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200128
Sasha Smundak1845f422022-12-13 14:18:58 -0800129 bazelPaths, err := readFileLines(ctx.Config().Getenv("BAZEL_DEPS_FILE"))
MarkDacek0d5bca52022-10-10 20:07:48 +0000130 if err != nil {
131 panic("Bazel deps file not found: " + err.Error())
132 }
133 ninjaDeps = append(ninjaDeps, bazelPaths...)
Sasha Smundak1845f422022-12-13 14:18:58 -0800134 ninjaDeps = append(ninjaDeps, writeBuildGlobsNinjaFile(ctx)...)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200135
Paul Duffin780a1852022-11-05 10:17:12 +0000136 writeDepFile(cmdlineArgs.OutFile, ctx.EventHandler, ninjaDeps)
Jeongik Cha591366d2023-05-08 11:32:52 +0900137
Jeongik Chaa87506f2023-06-01 23:16:41 +0900138 if needToWriteNinjaHint(ctx) {
Jeongik Cha591366d2023-05-08 11:32:52 +0900139 writeNinjaHint(ctx)
140 }
Paul Duffin0c09a432022-11-05 15:28:04 +0000141 return cmdlineArgs.OutFile
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200142}
143
Jeongik Chaa87506f2023-06-01 23:16:41 +0900144func needToWriteNinjaHint(ctx *android.Context) bool {
145 switch ctx.Config().GetenvWithDefault("SOONG_GENERATES_NINJA_HINT", "") {
146 case "always":
147 return true
148 case "depend":
149 if _, err := os.Stat(filepath.Join(ctx.Config().OutDir(), ".ninja_log")); errors.Is(err, os.ErrNotExist) {
150 return true
151 }
152 }
153 return false
154}
155
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200156// Run the code-generation phase to convert BazelTargetModules to BUILD files.
Sasha Smundak1845f422022-12-13 14:18:58 -0800157func runQueryView(queryviewDir, queryviewMarker string, ctx *android.Context) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400158 ctx.EventHandler.Begin("queryview")
159 defer ctx.EventHandler.End("queryview")
Cole Faustb85d1a12022-11-08 18:14:01 -0800160 codegenContext := bp2build.NewCodegenContext(ctx.Config(), ctx, bp2build.QueryView, topDir)
Spandan Das98cb8562023-03-09 23:05:47 +0000161 err := createBazelWorkspace(codegenContext, shared.JoinPath(topDir, queryviewDir), false)
Sasha Smundak1845f422022-12-13 14:18:58 -0800162 maybeQuit(err, "")
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200163 touch(shared.JoinPath(topDir, queryviewMarker))
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200164}
165
Spandan Das5af0bd32022-09-28 20:43:08 +0000166// Run the code-generation phase to convert API contributions to BUILD files.
167// Return marker file for the new synthetic workspace
Sasha Smundak1845f422022-12-13 14:18:58 -0800168func runApiBp2build(ctx *android.Context, extraNinjaDeps []string) string {
Spandan Das5af0bd32022-09-28 20:43:08 +0000169 ctx.EventHandler.Begin("api_bp2build")
170 defer ctx.EventHandler.End("api_bp2build")
Spandan Das255648c2023-01-11 03:05:24 +0000171 // api_bp2build does not run the typical pipeline of soong mutators.
172 // Hoevever, it still runs the defaults mutator which can create dependencies.
173 // These dependencies might not always exist (e.g. in tests)
174 ctx.SetAllowMissingDependencies(ctx.Config().AllowMissingDependencies())
Spandan Das5af0bd32022-09-28 20:43:08 +0000175 ctx.RegisterForApiBazelConversion()
176
177 // Register the Android.bp files in the tree
178 // Add them to the workspace's .d file
179 ctx.SetModuleListFile(cmdlineArgs.ModuleListFile)
180 if paths, err := ctx.ListModulePaths("."); err == nil {
181 extraNinjaDeps = append(extraNinjaDeps, paths...)
182 } else {
183 panic(err)
184 }
185
186 // Run the loading and analysis phase
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800187 ninjaDeps := bootstrap.RunBlueprint(cmdlineArgs.Args,
Spandan Das5af0bd32022-09-28 20:43:08 +0000188 bootstrap.StopBeforePrepareBuildActions,
189 ctx.Context,
Sasha Smundak1845f422022-12-13 14:18:58 -0800190 ctx.Config())
Spandan Das5af0bd32022-09-28 20:43:08 +0000191 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
192
193 // Add the globbed dependencies
Sasha Smundak1845f422022-12-13 14:18:58 -0800194 ninjaDeps = append(ninjaDeps, writeBuildGlobsNinjaFile(ctx)...)
Spandan Das5af0bd32022-09-28 20:43:08 +0000195
196 // Run codegen to generate BUILD files
Cole Faustb85d1a12022-11-08 18:14:01 -0800197 codegenContext := bp2build.NewCodegenContext(ctx.Config(), ctx, bp2build.ApiBp2build, topDir)
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800198 absoluteApiBp2buildDir := shared.JoinPath(topDir, cmdlineArgs.BazelApiBp2buildDir)
Spandan Das98cb8562023-03-09 23:05:47 +0000199 // Always generate bp2build_all_srcs filegroups in api_bp2build.
200 // This is necessary to force each Android.bp file to create an equivalent BUILD file
201 // and prevent package boundray issues.
202 // e.g.
203 // Source
204 // f/b/Android.bp
205 // java_library{
206 // name: "foo",
207 // api: "api/current.txt",
208 // }
209 //
210 // f/b/api/Android.bp <- will cause package boundary issues
211 //
212 // Gen
213 // f/b/BUILD
214 // java_contribution{
215 // name: "foo.contribution",
216 // api: "//f/b/api:current.txt",
217 // }
218 //
219 // If we don't generate f/b/api/BUILD, foo.contribution will be unbuildable.
220 err := createBazelWorkspace(codegenContext, absoluteApiBp2buildDir, true)
Sasha Smundak1845f422022-12-13 14:18:58 -0800221 maybeQuit(err, "")
Spandan Das5af0bd32022-09-28 20:43:08 +0000222 ninjaDeps = append(ninjaDeps, codegenContext.AdditionalNinjaDeps()...)
223
224 // Create soong_injection repository
Cole Faust9e384e22023-02-08 17:43:09 -0800225 soongInjectionFiles, err := bp2build.CreateSoongInjectionDirFiles(codegenContext, bp2build.CreateCodegenMetrics())
226 maybeQuit(err, "")
Sasha Smundak1845f422022-12-13 14:18:58 -0800227 absoluteSoongInjectionDir := shared.JoinPath(topDir, ctx.Config().SoongOutDir(), bazel.SoongInjectionDirName)
Spandan Das5af0bd32022-09-28 20:43:08 +0000228 for _, file := range soongInjectionFiles {
Spandan Das067210f2022-12-07 01:14:52 +0000229 // The API targets in api_bp2build workspace do not have any dependency on api_bp2build.
230 // But we need to create these files to prevent errors during Bazel analysis.
231 // These need to be created in Read-Write mode.
232 // This is because the subsequent step (bp2build in api domain analysis) creates them in Read-Write mode
233 // to allow users to edit/experiment in the synthetic workspace.
234 writeReadWriteFile(absoluteSoongInjectionDir, file)
Spandan Das5af0bd32022-09-28 20:43:08 +0000235 }
236
Sasha Smundak1845f422022-12-13 14:18:58 -0800237 workspace := shared.JoinPath(ctx.Config().SoongOutDir(), "api_bp2build")
Spandan Das5af0bd32022-09-28 20:43:08 +0000238 // Create the symlink forest
Usta Shresthada15c612022-11-08 14:12:36 -0500239 symlinkDeps, _, _ := bp2build.PlantSymlinkForest(
Sasha Smundak1845f422022-12-13 14:18:58 -0800240 ctx.Config().IsEnvTrue("BP2BUILD_VERBOSE"),
Spandan Das5af0bd32022-09-28 20:43:08 +0000241 topDir,
242 workspace,
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800243 cmdlineArgs.BazelApiBp2buildDir,
Sasha Smundak1845f422022-12-13 14:18:58 -0800244 apiBuildFileExcludes(ctx))
Spandan Das5af0bd32022-09-28 20:43:08 +0000245 ninjaDeps = append(ninjaDeps, symlinkDeps...)
246
247 workspaceMarkerFile := workspace + ".marker"
Paul Duffin780a1852022-11-05 10:17:12 +0000248 writeDepFile(workspaceMarkerFile, ctx.EventHandler, ninjaDeps)
Spandan Das5af0bd32022-09-28 20:43:08 +0000249 touch(shared.JoinPath(topDir, workspaceMarkerFile))
250 return workspaceMarkerFile
251}
252
253// With some exceptions, api_bp2build does not have any dependencies on the checked-in BUILD files
254// Exclude them from the generated workspace to prevent unrelated errors during the loading phase
Sasha Smundak1845f422022-12-13 14:18:58 -0800255func apiBuildFileExcludes(ctx *android.Context) []string {
256 ret := bazelArtifacts()
Spandan Das5af0bd32022-09-28 20:43:08 +0000257 srcs, err := getExistingBazelRelatedFiles(topDir)
Sasha Smundak1845f422022-12-13 14:18:58 -0800258 maybeQuit(err, "Error determining existing Bazel-related files")
Spandan Das5af0bd32022-09-28 20:43:08 +0000259 for _, src := range srcs {
Sasha Smundak1845f422022-12-13 14:18:58 -0800260 // Exclude all src BUILD files
Spandan Das5af0bd32022-09-28 20:43:08 +0000261 if src != "WORKSPACE" &&
262 src != "BUILD" &&
263 src != "BUILD.bazel" &&
264 !strings.HasPrefix(src, "build/bazel") &&
Spandan Das6b91a382022-11-30 02:17:06 +0000265 !strings.HasPrefix(src, "external/bazel-skylib") &&
Spandan Das5af0bd32022-09-28 20:43:08 +0000266 !strings.HasPrefix(src, "prebuilts/clang") {
267 ret = append(ret, src)
268 }
269 }
Sasha Smundak1845f422022-12-13 14:18:58 -0800270 // Android.bp files for api surfaces are mounted to out/, but out/ should not be a
271 // dep for api_bp2build. Otherwise, api_bp2build will be run every single time
272 ret = append(ret, ctx.Config().OutDir())
Spandan Das5af0bd32022-09-28 20:43:08 +0000273 return ret
274}
275
Jeongik Chae114e602023-03-19 00:12:39 +0900276func writeNinjaHint(ctx *android.Context) error {
Jeongik Cha73d49112023-05-04 18:16:11 +0900277 ctx.BeginEvent("ninja_hint")
278 defer ctx.EndEvent("ninja_hint")
Jeongik Chab745e2e2023-04-11 14:28:43 +0900279 // The current predictor focuses on reducing false negatives.
280 // If there are too many false positives (e.g., most modules are marked as positive),
281 // real long-running jobs cannot run early.
282 // Therefore, the model should be adjusted in this case.
283 // The model should also be adjusted if there are critical false negatives.
284 predicate := func(j *blueprint.JsonModule) (prioritized bool, weight int) {
285 prioritized = false
286 weight = 0
287 for prefix, w := range allowlists.HugeModuleTypePrefixMap {
288 if strings.HasPrefix(j.Type, prefix) {
289 prioritized = true
290 weight = w
291 return
292 }
Jeongik Chae114e602023-03-19 00:12:39 +0900293 }
Jeongik Chab745e2e2023-04-11 14:28:43 +0900294 dep_count := len(j.Deps)
295 src_count := 0
296 for _, a := range j.Module["Actions"].([]blueprint.JSONAction) {
297 src_count += len(a.Inputs)
298 }
299 input_size := dep_count + src_count
300
301 // Current threshold is an arbitrary value which only consider recall rather than accuracy.
302 if input_size > allowlists.INPUT_SIZE_THRESHOLD {
303 prioritized = true
304 weight += ((input_size) / allowlists.INPUT_SIZE_THRESHOLD) * allowlists.DEFAULT_PRIORITIZED_WEIGHT
305
306 // To prevent some modules from having too large a priority value.
307 if weight > allowlists.HIGH_PRIORITIZED_WEIGHT {
308 weight = allowlists.HIGH_PRIORITIZED_WEIGHT
309 }
310 }
311 return
312 }
313
314 outputsMap := ctx.Context.GetWeightedOutputsFromPredicate(predicate)
315 var outputBuilder strings.Builder
316 for output, weight := range outputsMap {
317 outputBuilder.WriteString(fmt.Sprintf("%s,%d\n", output, weight))
Jeongik Chae114e602023-03-19 00:12:39 +0900318 }
319 weightListFile := filepath.Join(topDir, ctx.Config().OutDir(), ".ninja_weight_list")
320
321 err := os.WriteFile(weightListFile, []byte(outputBuilder.String()), 0644)
322 if err != nil {
323 return fmt.Errorf("could not write ninja weight list file %s", err)
324 }
325 return nil
326}
327
Paul Duffin780a1852022-11-05 10:17:12 +0000328func writeMetrics(configuration android.Config, eventHandler *metrics.EventHandler, metricsDir string) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400329 if len(metricsDir) < 1 {
330 fmt.Fprintf(os.Stderr, "\nMissing required env var for generating soong metrics: LOG_DIR\n")
331 os.Exit(1)
332 }
333 metricsFile := filepath.Join(metricsDir, "soong_build_metrics.pb")
334 err := android.WriteMetrics(configuration, eventHandler, metricsFile)
Sasha Smundak1845f422022-12-13 14:18:58 -0800335 maybeQuit(err, "error writing soong_build metrics %s", metricsFile)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200336}
337
MarkDacekf47e1422023-04-19 16:47:36 +0000338// Errors out if any modules expected to be mixed_built were not, unless
MarkDacek6f6b9622023-05-02 16:28:55 +0000339// the modules did not exist.
MarkDacekf47e1422023-04-19 16:47:36 +0000340func checkForAllowlistIntegrityError(configuration android.Config, isStagingMode bool) error {
MarkDacek6f6b9622023-05-02 16:28:55 +0000341 modules := findMisconfiguredModules(configuration, isStagingMode)
MarkDacekf47e1422023-04-19 16:47:36 +0000342 if len(modules) == 0 {
343 return nil
344 }
345
346 return fmt.Errorf("Error: expected the following modules to be mixed_built: %s", modules)
347}
348
MarkDacek6f6b9622023-05-02 16:28:55 +0000349// Returns true if the given module has all of the following true:
350// 1. Is allowlisted to be built with Bazel.
351// 2. Has a variant which is *not* built with Bazel.
352// 3. Has no variant which is built with Bazel.
353//
354// This indicates the allowlisting of this variant had no effect.
355// TODO(b/280457637): Return true for nonexistent modules.
356func isAllowlistMisconfiguredForModule(module string, mixedBuildsEnabled map[string]struct{}, mixedBuildsDisabled map[string]struct{}) bool {
MarkDacek6f6b9622023-05-02 16:28:55 +0000357 _, enabled := mixedBuildsEnabled[module]
358
359 if enabled {
360 return false
361 }
362
363 _, disabled := mixedBuildsDisabled[module]
364 return disabled
365
366}
367
MarkDacekf47e1422023-04-19 16:47:36 +0000368// Returns the list of modules that should have been mixed_built (per the
369// allowlists and cmdline flags) but were not.
MarkDacek6f6b9622023-05-02 16:28:55 +0000370// Note: nonexistent modules are excluded from the list. See b/280457637
371func findMisconfiguredModules(configuration android.Config, isStagingMode bool) []string {
MarkDacekf47e1422023-04-19 16:47:36 +0000372 retval := []string{}
373 forceEnabledModules := configuration.BazelModulesForceEnabledByFlag()
374
375 mixedBuildsEnabled := configuration.GetMixedBuildsEnabledModules()
MarkDacek6f6b9622023-05-02 16:28:55 +0000376 mixedBuildsDisabled := configuration.GetMixedBuildsDisabledModules()
MarkDacekf47e1422023-04-19 16:47:36 +0000377 for _, module := range allowlists.ProdMixedBuildsEnabledList {
MarkDacek6f6b9622023-05-02 16:28:55 +0000378 if isAllowlistMisconfiguredForModule(module, mixedBuildsEnabled, mixedBuildsDisabled) {
MarkDacekf47e1422023-04-19 16:47:36 +0000379 retval = append(retval, module)
380 }
381 }
382
383 if isStagingMode {
384 for _, module := range allowlists.StagingMixedBuildsEnabledList {
MarkDacek6f6b9622023-05-02 16:28:55 +0000385 if isAllowlistMisconfiguredForModule(module, mixedBuildsEnabled, mixedBuildsDisabled) {
MarkDacekf47e1422023-04-19 16:47:36 +0000386 retval = append(retval, module)
387 }
388 }
389 }
390
391 for module, _ := range forceEnabledModules {
MarkDacek6f6b9622023-05-02 16:28:55 +0000392 if isAllowlistMisconfiguredForModule(module, mixedBuildsEnabled, mixedBuildsDisabled) {
MarkDacekf47e1422023-04-19 16:47:36 +0000393 retval = append(retval, module)
394 }
395 }
396 return retval
397}
398
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800399func writeJsonModuleGraphAndActions(ctx *android.Context, cmdArgs android.CmdArgs) {
400 graphFile, graphErr := os.Create(shared.JoinPath(topDir, cmdArgs.ModuleGraphFile))
Sasha Smundak1845f422022-12-13 14:18:58 -0800401 maybeQuit(graphErr, "graph err")
kgui67007242022-01-25 13:50:25 +0800402 defer graphFile.Close()
Sasha Smundak1845f422022-12-13 14:18:58 -0800403 actionsFile, actionsErr := os.Create(shared.JoinPath(topDir, cmdArgs.ModuleActionsFile))
404 maybeQuit(actionsErr, "actions err")
kgui67007242022-01-25 13:50:25 +0800405 defer actionsFile.Close()
406 ctx.Context.PrintJSONGraphAndActions(graphFile, actionsFile)
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200407}
408
Sasha Smundak1845f422022-12-13 14:18:58 -0800409func writeBuildGlobsNinjaFile(ctx *android.Context) []string {
Chris Parsons715b08f2022-03-22 19:23:40 -0400410 ctx.EventHandler.Begin("globs_ninja_file")
411 defer ctx.EventHandler.End("globs_ninja_file")
412
Sasha Smundak1845f422022-12-13 14:18:58 -0800413 globDir := bootstrap.GlobDirectory(ctx.Config().SoongOutDir(), globListDir)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200414 bootstrap.WriteBuildGlobsNinjaFile(&bootstrap.GlobSingleton{
Chris Parsons715b08f2022-03-22 19:23:40 -0400415 GlobLister: ctx.Globs,
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200416 GlobFile: globFile,
417 GlobDir: globDir,
Chris Parsons715b08f2022-03-22 19:23:40 -0400418 SrcDir: ctx.SrcDir(),
Sasha Smundak1845f422022-12-13 14:18:58 -0800419 }, ctx.Config())
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200420 return bootstrap.GlobFileListFiles(globDir)
421}
422
Paul Duffin780a1852022-11-05 10:17:12 +0000423func writeDepFile(outputFile string, eventHandler *metrics.EventHandler, ninjaDeps []string) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400424 eventHandler.Begin("ninja_deps")
425 defer eventHandler.End("ninja_deps")
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200426 depFile := shared.JoinPath(topDir, outputFile+".d")
427 err := deptools.WriteDepFile(depFile, outputFile, ninjaDeps)
Sasha Smundak1845f422022-12-13 14:18:58 -0800428 maybeQuit(err, "error writing depfile '%s'", depFile)
Paul Duffin0c09a432022-11-05 15:28:04 +0000429}
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200430
Paul Duffin0c09a432022-11-05 15:28:04 +0000431// runSoongOnlyBuild runs the standard Soong build in a number of different modes.
Sasha Smundak1845f422022-12-13 14:18:58 -0800432func runSoongOnlyBuild(ctx *android.Context, extraNinjaDeps []string) string {
Paul Duffin39eae8f2022-11-05 14:59:52 +0000433 ctx.EventHandler.Begin("soong_build")
434 defer ctx.EventHandler.End("soong_build")
435
Paul Duffin0c09a432022-11-05 15:28:04 +0000436 var stopBefore bootstrap.StopBefore
Sasha Smundak1845f422022-12-13 14:18:58 -0800437 switch ctx.Config().BuildMode {
438 case android.GenerateModuleGraph:
Paul Duffin0c09a432022-11-05 15:28:04 +0000439 stopBefore = bootstrap.StopBeforeWriteNinja
Usta Shrestha7fae6952022-12-21 11:46:28 -0500440 case android.GenerateQueryView, android.GenerateDocFile:
Paul Duffin0c09a432022-11-05 15:28:04 +0000441 stopBefore = bootstrap.StopBeforePrepareBuildActions
Sasha Smundak1845f422022-12-13 14:18:58 -0800442 default:
Paul Duffin0c09a432022-11-05 15:28:04 +0000443 stopBefore = bootstrap.DoEverything
444 }
445
Sasha Smundak1845f422022-12-13 14:18:58 -0800446 ninjaDeps := bootstrap.RunBlueprint(cmdlineArgs.Args, stopBefore, ctx.Context, ctx.Config())
Paul Duffin0c09a432022-11-05 15:28:04 +0000447 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
448
Sasha Smundak1845f422022-12-13 14:18:58 -0800449 globListFiles := writeBuildGlobsNinjaFile(ctx)
Paul Duffin0c09a432022-11-05 15:28:04 +0000450 ninjaDeps = append(ninjaDeps, globListFiles...)
451
452 // Convert the Soong module graph into Bazel BUILD files.
Sasha Smundak1845f422022-12-13 14:18:58 -0800453 switch ctx.Config().BuildMode {
454 case android.GenerateQueryView:
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800455 queryviewMarkerFile := cmdlineArgs.BazelQueryViewDir + ".marker"
Sasha Smundak1845f422022-12-13 14:18:58 -0800456 runQueryView(cmdlineArgs.BazelQueryViewDir, queryviewMarkerFile, ctx)
Paul Duffin0c09a432022-11-05 15:28:04 +0000457 writeDepFile(queryviewMarkerFile, ctx.EventHandler, ninjaDeps)
458 return queryviewMarkerFile
Sasha Smundak1845f422022-12-13 14:18:58 -0800459 case android.GenerateModuleGraph:
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800460 writeJsonModuleGraphAndActions(ctx, cmdlineArgs)
461 writeDepFile(cmdlineArgs.ModuleGraphFile, ctx.EventHandler, ninjaDeps)
462 return cmdlineArgs.ModuleGraphFile
Sasha Smundak1845f422022-12-13 14:18:58 -0800463 case android.GenerateDocFile:
Paul Duffin0c09a432022-11-05 15:28:04 +0000464 // TODO: we could make writeDocs() return the list of documentation files
465 // written and add them to the .d file. Then soong_docs would be re-run
466 // whenever one is deleted.
Sasha Smundak1845f422022-12-13 14:18:58 -0800467 err := writeDocs(ctx, shared.JoinPath(topDir, cmdlineArgs.DocFile))
468 maybeQuit(err, "error building Soong documentation")
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800469 writeDepFile(cmdlineArgs.DocFile, ctx.EventHandler, ninjaDeps)
470 return cmdlineArgs.DocFile
Sasha Smundak1845f422022-12-13 14:18:58 -0800471 default:
Paul Duffin0c09a432022-11-05 15:28:04 +0000472 // The actual output (build.ninja) was written in the RunBlueprint() call
473 // above
474 writeDepFile(cmdlineArgs.OutFile, ctx.EventHandler, ninjaDeps)
Jeongik Chaa87506f2023-06-01 23:16:41 +0900475 if needToWriteNinjaHint(ctx) {
Jeongik Cha591366d2023-05-08 11:32:52 +0900476 writeNinjaHint(ctx)
477 }
Paul Duffinb713ddf2022-11-05 16:14:30 +0000478 return cmdlineArgs.OutFile
Paul Duffin0c09a432022-11-05 15:28:04 +0000479 }
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200480}
481
482// soong_ui dumps the available environment variables to
483// soong.environment.available . Then soong_build itself is run with an empty
484// environment so that the only way environment variables can be accessed is
485// using Config, which tracks access to them.
486
487// At the end of the build, a file called soong.environment.used is written
488// containing the current value of all used environment variables. The next
489// time soong_ui is run, it checks whether any environment variables that was
490// used had changed and if so, it deletes soong.environment.used to cause a
491// rebuild.
492//
493// The dependency of build.ninja on soong.environment.used is declared in
494// build.ninja.d
495func parseAvailableEnv() map[string]string {
496 if availableEnvFile == "" {
497 fmt.Fprintf(os.Stderr, "--available_env not set\n")
498 os.Exit(1)
499 }
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200500 result, err := shared.EnvFromFile(shared.JoinPath(topDir, availableEnvFile))
Sasha Smundak1845f422022-12-13 14:18:58 -0800501 maybeQuit(err, "error reading available environment file '%s'", availableEnvFile)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200502 return result
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200503}
504
Colin Cross3f40fa42015-01-30 17:27:36 -0800505func main() {
506 flag.Parse()
507
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100508 shared.ReexecWithDelveMaybe(delveListen, delvePath)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100509 android.InitSandbox(topDir)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100510
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200511 availableEnv := parseAvailableEnv()
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800512 configuration, err := android.NewConfig(cmdlineArgs, availableEnv)
Sasha Smundak1845f422022-12-13 14:18:58 -0800513 maybeQuit(err, "")
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100514 if configuration.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
515 configuration.SetAllowMissingDependencies()
516 }
517
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800518 extraNinjaDeps := []string{configuration.ProductVariablesFileName, usedEnvFile}
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100519 if shared.IsDebugging() {
Colin Crossaa812d12019-06-19 13:33:24 -0700520 // Add a non-existent file to the dependencies so that soong_build will rerun when the debugger is
521 // enabled even if it completed successfully.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200522 extraNinjaDeps = append(extraNinjaDeps, filepath.Join(configuration.SoongOutDir(), "always_rerun_for_delve"))
Colin Crossaa812d12019-06-19 13:33:24 -0700523 }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500524
Dan Willemsenccf36aa2022-04-20 23:11:43 -0700525 // Bypass configuration.Getenv, as LOG_DIR does not need to be dependency tracked. By definition, it will
526 // change between every CI build, so tracking it would require re-running Soong for every build.
Sasha Smundak1845f422022-12-13 14:18:58 -0800527 metricsDir := availableEnv["LOG_DIR"]
Dan Willemsenccf36aa2022-04-20 23:11:43 -0700528
Joe Onorato2e5e4012022-06-07 17:16:08 -0700529 ctx := newContext(configuration)
Joe Onorato2e5e4012022-06-07 17:16:08 -0700530
Sasha Smundak1845f422022-12-13 14:18:58 -0800531 var finalOutputFile string
Joe Onorato2e5e4012022-06-07 17:16:08 -0700532
Sasha Smundak1845f422022-12-13 14:18:58 -0800533 // Run Soong for a specific activity, like bp2build, queryview
534 // or the actual Soong build for the build.ninja file.
535 switch configuration.BuildMode {
536 case android.SymlinkForest:
537 finalOutputFile = runSymlinkForestCreation(ctx, extraNinjaDeps, metricsDir)
538 case android.Bp2build:
539 // Run the alternate pipeline of bp2build mutators and singleton to convert
540 // Blueprint to BUILD files before everything else.
541 finalOutputFile = runBp2Build(ctx, extraNinjaDeps, metricsDir)
542 case android.ApiBp2build:
543 finalOutputFile = runApiBp2build(ctx, extraNinjaDeps)
544 writeMetrics(configuration, ctx.EventHandler, metricsDir)
545 default:
546 ctx.Register()
MarkDacekf47e1422023-04-19 16:47:36 +0000547 isMixedBuildsEnabled := configuration.IsMixedBuildsEnabled()
548 if isMixedBuildsEnabled {
Sasha Smundak1845f422022-12-13 14:18:58 -0800549 finalOutputFile = runMixedModeBuild(ctx, extraNinjaDeps)
MarkDacekf47e1422023-04-19 16:47:36 +0000550 if cmdlineArgs.EnsureAllowlistIntegrity {
551 if err := checkForAllowlistIntegrityError(configuration, cmdlineArgs.BazelModeStaging); err != nil {
552 maybeQuit(err, "")
553 }
554 }
Sasha Smundak1845f422022-12-13 14:18:58 -0800555 } else {
556 finalOutputFile = runSoongOnlyBuild(ctx, extraNinjaDeps)
557 }
558 writeMetrics(configuration, ctx.EventHandler, metricsDir)
559 }
Chris Parsonsc83398f2023-05-31 18:41:41 +0000560
561 // Register this environment variablesas being an implicit dependencies of
562 // soong_build. Changes to this environment variable will result in
563 // retriggering soong_build.
564 configuration.Getenv("USE_BAZEL_VERSION")
565
Chris Parsonsa3ae0072023-05-10 21:10:08 +0000566 writeUsedEnvironmentFile(configuration)
567
568 // Touch the output file so that it's the newest file created by soong_build.
569 // This is necessary because, if soong_build generated any files which
570 // are ninja inputs to the main output file, then ninja would superfluously
571 // rebuild this output file on the next build invocation.
572 touch(shared.JoinPath(topDir, finalOutputFile))
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100573}
574
Chris Parsonsa3ae0072023-05-10 21:10:08 +0000575func writeUsedEnvironmentFile(configuration android.Config) {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200576 if usedEnvFile == "" {
577 return
578 }
579
580 path := shared.JoinPath(topDir, usedEnvFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100581 data, err := shared.EnvFileContents(configuration.EnvDeps())
Sasha Smundak1845f422022-12-13 14:18:58 -0800582 maybeQuit(err, "error writing used environment file '%s'\n", usedEnvFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100583
Usta Shrestha2ba28a32022-10-24 11:33:09 -0400584 if preexistingData, err := os.ReadFile(path); err != nil {
585 if !os.IsNotExist(err) {
Sasha Smundak1845f422022-12-13 14:18:58 -0800586 maybeQuit(err, "error reading used environment file '%s'", usedEnvFile)
Usta Shrestha2ba28a32022-10-24 11:33:09 -0400587 }
588 } else if bytes.Equal(preexistingData, data) {
589 // used environment file is unchanged
590 return
591 }
Sasha Smundak1845f422022-12-13 14:18:58 -0800592 err = os.WriteFile(path, data, 0666)
593 maybeQuit(err, "error writing used environment file '%s'", usedEnvFile)
Colin Cross3f40fa42015-01-30 17:27:36 -0800594}
Jingwen Chen5ba7e472020-07-15 10:06:41 +0000595
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200596func touch(path string) {
597 f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
Sasha Smundak1845f422022-12-13 14:18:58 -0800598 maybeQuit(err, "Error touching '%s'", path)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200599 err = f.Close()
Sasha Smundak1845f422022-12-13 14:18:58 -0800600 maybeQuit(err, "Error touching '%s'", path)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200601
602 currentTime := time.Now().Local()
603 err = os.Chtimes(path, currentTime, currentTime)
Sasha Smundak1845f422022-12-13 14:18:58 -0800604 maybeQuit(err, "error touching '%s'", path)
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400605}
606
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400607// Read the bazel.list file that the Soong Finder already dumped earlier (hopefully)
608// It contains the locations of BUILD files, BUILD.bazel files, etc. in the source dir
609func getExistingBazelRelatedFiles(topDir string) ([]string, error) {
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200610 bazelFinderFile := filepath.Join(filepath.Dir(cmdlineArgs.ModuleListFile), "bazel.list")
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400611 if !filepath.IsAbs(bazelFinderFile) {
612 // Assume this was a relative path under topDir
613 bazelFinderFile = filepath.Join(topDir, bazelFinderFile)
614 }
Sasha Smundak1845f422022-12-13 14:18:58 -0800615 return readFileLines(bazelFinderFile)
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400616}
617
Spandan Das5af0bd32022-09-28 20:43:08 +0000618func bazelArtifacts() []string {
619 return []string{
620 "bazel-bin",
621 "bazel-genfiles",
622 "bazel-out",
623 "bazel-testlogs",
Usta (Tsering) Shresthac4c07b12022-11-08 18:31:14 -0500624 "bazel-workspace",
Spandan Das5af0bd32022-09-28 20:43:08 +0000625 "bazel-" + filepath.Base(topDir),
626 }
627}
628
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000629// This could in theory easily be separated into a binary that generically
630// merges two directories into a symlink tree. The main obstacle is that this
631// function currently depends on both Bazel-specific knowledge (the existence
632// of bazel-* symlinks) and configuration (the set of BUILD.bazel files that
633// should and should not be kept)
634//
635// Ideally, bp2build would write a file that contains instructions to the
636// symlink tree creation binary. Then the latter would not need to depend on
637// the very heavy-weight machinery of soong_build .
Sasha Smundak1845f422022-12-13 14:18:58 -0800638func runSymlinkForestCreation(ctx *android.Context, extraNinjaDeps []string, metricsDir string) string {
Usta Shresthada15c612022-11-08 14:12:36 -0500639 var ninjaDeps []string
640 var mkdirCount, symlinkCount uint64
641
Paul Duffinb4e8d912022-11-04 13:35:50 +0000642 ctx.EventHandler.Do("symlink_forest", func() {
Usta (Tsering) Shrestha93b2a9b2022-12-01 05:55:35 +0000643 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Sasha Smundak1845f422022-12-13 14:18:58 -0800644 verbose := ctx.Config().IsEnvTrue("BP2BUILD_VERBOSE")
Usta (Tsering) Shrestha93b2a9b2022-12-01 05:55:35 +0000645
646 // PlantSymlinkForest() returns all the directories that were readdir()'ed.
647 // Such a directory SHOULD be added to `ninjaDeps` so that a child directory
648 // or file created/deleted under it would trigger an update of the symlink forest.
Sasha Smundak1845f422022-12-13 14:18:58 -0800649 generatedRoot := shared.JoinPath(ctx.Config().SoongOutDir(), "bp2build")
650 workspaceRoot := shared.JoinPath(ctx.Config().SoongOutDir(), "workspace")
Usta Shresthada15c612022-11-08 14:12:36 -0500651 var symlinkForestDeps []string
Usta (Tsering) Shrestha93b2a9b2022-12-01 05:55:35 +0000652 ctx.EventHandler.Do("plant", func() {
Usta Shresthada15c612022-11-08 14:12:36 -0500653 symlinkForestDeps, mkdirCount, symlinkCount = bp2build.PlantSymlinkForest(
Sasha Smundak1845f422022-12-13 14:18:58 -0800654 verbose, topDir, workspaceRoot, generatedRoot, excludedFromSymlinkForest(ctx, verbose))
Usta (Tsering) Shrestha93b2a9b2022-12-01 05:55:35 +0000655 })
Usta Shresthada15c612022-11-08 14:12:36 -0500656 ninjaDeps = append(ninjaDeps, symlinkForestDeps...)
Usta (Tsering) Shrestha93b2a9b2022-12-01 05:55:35 +0000657 })
Usta Shresthada15c612022-11-08 14:12:36 -0500658
659 writeDepFile(cmdlineArgs.SymlinkForestMarker, ctx.EventHandler, ninjaDeps)
660 touch(shared.JoinPath(topDir, cmdlineArgs.SymlinkForestMarker))
usta4f5d2c12022-10-28 23:32:01 -0400661 codegenMetrics := bp2build.ReadCodegenMetrics(metricsDir)
662 if codegenMetrics == nil {
663 m := bp2build.CreateCodegenMetrics()
664 codegenMetrics = &m
665 } else {
666 //TODO (usta) we cannot determine if we loaded a stale file, i.e. from an unrelated prior
667 //invocation of codegen. We should simply use a separate .pb file
668 }
Usta Shresthada15c612022-11-08 14:12:36 -0500669 codegenMetrics.SetSymlinkCount(symlinkCount)
670 codegenMetrics.SetMkDirCount(mkdirCount)
Paul Duffinb4e8d912022-11-04 13:35:50 +0000671 writeBp2BuildMetrics(codegenMetrics, ctx.EventHandler, metricsDir)
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800672 return cmdlineArgs.SymlinkForestMarker
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000673}
674
Sasha Smundak1845f422022-12-13 14:18:58 -0800675func excludedFromSymlinkForest(ctx *android.Context, verbose bool) []string {
676 excluded := bazelArtifacts()
677 if cmdlineArgs.OutDir[0] != '/' {
678 excluded = append(excluded, cmdlineArgs.OutDir)
679 }
680
681 // Find BUILD files in the srcDir which are not in the allowlist
682 // (android.Bp2BuildConversionAllowlist#ShouldKeepExistingBuildFileForDir)
683 // and return their paths so they can be left out of the Bazel workspace dir (i.e. ignored)
684 existingBazelFiles, err := getExistingBazelRelatedFiles(topDir)
685 maybeQuit(err, "Error determining existing Bazel-related files")
686
687 for _, path := range existingBazelFiles {
688 fullPath := shared.JoinPath(topDir, path)
689 fileInfo, err2 := os.Stat(fullPath)
690 if err2 != nil {
691 // Warn about error, but continue trying to check files
692 fmt.Fprintf(os.Stderr, "WARNING: Error accessing path '%s', err: %s\n", fullPath, err2)
693 continue
694 }
695 // Exclude only files named 'BUILD' or 'BUILD.bazel' and unless forcibly kept
696 if fileInfo.IsDir() ||
697 (fileInfo.Name() != "BUILD" && fileInfo.Name() != "BUILD.bazel") ||
698 ctx.Config().Bp2buildPackageConfig.ShouldKeepExistingBuildFileForDir(filepath.Dir(path)) {
699 // Don't ignore this existing build file
700 continue
701 }
702 if verbose {
703 fmt.Fprintf(os.Stderr, "Ignoring existing BUILD file: %s\n", path)
704 }
705 excluded = append(excluded, path)
706 }
707
708 // Temporarily exclude stuff to make `bazel build //external/...` (and `bazel build //frameworks/...`) work
709 excluded = append(excluded,
710 // FIXME: 'autotest_lib' is a symlink back to external/autotest, and this causes an infinite
711 // symlink expansion error for Bazel
712 "external/autotest/venv/autotest_lib",
713 "external/autotest/autotest_lib",
714 "external/autotest/client/autotest_lib/client",
715
716 // FIXME: The external/google-fruit/extras/bazel_root/third_party/fruit dir is poison
717 // It contains several symlinks back to real source dirs, and those source dirs contain
718 // BUILD files we want to ignore
719 "external/google-fruit/extras/bazel_root/third_party/fruit",
720
721 // FIXME: 'frameworks/compile/slang' has a filegroup error due to an escaping issue
722 "frameworks/compile/slang",
723
724 // FIXME(b/260809113): 'prebuilts/clang/host/linux-x86/clang-dev' is a tool-generated symlink
725 // directory that contains a BUILD file. The bazel files finder code doesn't traverse into symlink dirs,
726 // and hence is not aware of this BUILD file and exclude it accordingly during symlink forest generation
727 // when checking against keepExistingBuildFiles allowlist.
728 //
729 // This is necessary because globs in //prebuilts/clang/host/linux-x86/BUILD
730 // currently assume no subpackages (keepExistingBuildFile is not recursive for that directory).
731 //
732 // This is a bandaid until we the symlink forest logic can intelligently exclude BUILD files found in
733 // source symlink dirs according to the keepExistingBuildFile allowlist.
734 "prebuilts/clang/host/linux-x86/clang-dev",
735 )
736 return excluded
737}
738
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500739// Run Soong in the bp2build mode. This creates a standalone context that registers
740// an alternate pipeline of mutators and singletons specifically for generating
741// Bazel BUILD files instead of Ninja files.
Sasha Smundak1845f422022-12-13 14:18:58 -0800742func runBp2Build(ctx *android.Context, extraNinjaDeps []string, metricsDir string) string {
usta4f5d2c12022-10-28 23:32:01 -0400743 var codegenMetrics *bp2build.CodegenMetrics
Paul Duffinb4e8d912022-11-04 13:35:50 +0000744 ctx.EventHandler.Do("bp2build", func() {
Jingwen Cheneb76c432021-01-28 08:22:12 -0500745
Chris Parsons8152a942023-06-06 16:17:50 +0000746 ctx.EventHandler.Do("read_build", func() {
Chris Parsonse1f25232023-06-16 20:47:03 +0000747 existingBazelFiles, err := getExistingBazelRelatedFiles(topDir)
748 maybeQuit(err, "Error determining existing Bazel-related files")
749
750 err = ctx.ParseBuildFiles(topDir, existingBazelFiles)
751 maybeQuit(err, "Error parsing existing Bazel-related files")
Chris Parsons8152a942023-06-06 16:17:50 +0000752 })
753
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400754 // Propagate "allow misssing dependencies" bit. This is normally set in
Paul Duffinb4e8d912022-11-04 13:35:50 +0000755 // newContext(), but we create ctx without calling that method.
Sasha Smundak1845f422022-12-13 14:18:58 -0800756 ctx.SetAllowMissingDependencies(ctx.Config().AllowMissingDependencies())
757 ctx.SetNameInterface(newNameResolver(ctx.Config()))
Paul Duffinb4e8d912022-11-04 13:35:50 +0000758 ctx.RegisterForBazelConversion()
759 ctx.SetModuleListFile(cmdlineArgs.ModuleListFile)
Chris Parsons3a5c1702023-06-13 01:10:20 +0000760 // Skip cloning modules during bp2build's blueprint run. Some mutators set
761 // bp2build-related module values which should be preserved during codegen.
762 ctx.SkipCloneModulesAfterMutators = true
Jingwen Cheneb76c432021-01-28 08:22:12 -0500763
Usta Shresthaa117c582022-10-04 12:13:25 -0400764 var ninjaDeps []string
765 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
766
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400767 // Run the loading and analysis pipeline to prepare the graph of regular
768 // Modules parsed from Android.bp files, and the BazelTargetModules mapped
769 // from the regular Modules.
Paul Duffinb4e8d912022-11-04 13:35:50 +0000770 ctx.EventHandler.Do("bootstrap", func() {
Usta Shresthaa117c582022-10-04 12:13:25 -0400771 blueprintArgs := cmdlineArgs
Sasha Smundak1845f422022-12-13 14:18:58 -0800772 bootstrapDeps := bootstrap.RunBlueprint(blueprintArgs.Args,
773 bootstrap.StopBeforePrepareBuildActions, ctx.Context, ctx.Config())
Usta Shresthaa117c582022-10-04 12:13:25 -0400774 ninjaDeps = append(ninjaDeps, bootstrapDeps...)
775 })
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200776
Sasha Smundak1845f422022-12-13 14:18:58 -0800777 globListFiles := writeBuildGlobsNinjaFile(ctx)
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400778 ninjaDeps = append(ninjaDeps, globListFiles...)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200779
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400780 // Run the code-generation phase to convert BazelTargetModules to BUILD files
Usta Shresthaa117c582022-10-04 12:13:25 -0400781 // and print conversion codegenMetrics to the user.
Cole Faustb85d1a12022-11-08 18:14:01 -0800782 codegenContext := bp2build.NewCodegenContext(ctx.Config(), ctx, bp2build.Bp2Build, topDir)
Paul Duffinb4e8d912022-11-04 13:35:50 +0000783 ctx.EventHandler.Do("codegen", func() {
Usta Shresthaa117c582022-10-04 12:13:25 -0400784 codegenMetrics = bp2build.Codegen(codegenContext)
785 })
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200786
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400787 ninjaDeps = append(ninjaDeps, codegenContext.AdditionalNinjaDeps()...)
Chris Parsons715b08f2022-03-22 19:23:40 -0400788
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800789 writeDepFile(cmdlineArgs.Bp2buildMarker, ctx.EventHandler, ninjaDeps)
790 touch(shared.JoinPath(topDir, cmdlineArgs.Bp2buildMarker))
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400791 })
Chris Parsons715b08f2022-03-22 19:23:40 -0400792
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200793 // Only report metrics when in bp2build mode. The metrics aren't relevant
794 // for queryview, since that's a total repo-wide conversion and there's a
795 // 1:1 mapping for each module.
Sasha Smundak1845f422022-12-13 14:18:58 -0800796 if ctx.Config().IsEnvTrue("BP2BUILD_VERBOSE") {
Usta Shresthaa117c582022-10-04 12:13:25 -0400797 codegenMetrics.Print()
Sasha Smundak0fd93e02022-05-19 19:34:31 -0700798 }
Paul Duffinb4e8d912022-11-04 13:35:50 +0000799 writeBp2BuildMetrics(codegenMetrics, ctx.EventHandler, metricsDir)
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800800 return cmdlineArgs.Bp2buildMarker
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500801}
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500802
803// Write Bp2Build metrics into $LOG_DIR
Paul Duffinf4906562022-11-05 14:21:16 +0000804func writeBp2BuildMetrics(codegenMetrics *bp2build.CodegenMetrics, eventHandler *metrics.EventHandler, metricsDir string) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400805 for _, event := range eventHandler.CompletedEvents() {
usta4f5d2c12022-10-28 23:32:01 -0400806 codegenMetrics.AddEvent(&bp2build_metrics_proto.Event{
807 Name: event.Id,
808 StartTime: uint64(event.Start.UnixNano()),
809 RealTime: event.RuntimeNanoseconds(),
810 })
Chris Parsons715b08f2022-03-22 19:23:40 -0400811 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500812 if len(metricsDir) < 1 {
813 fmt.Fprintf(os.Stderr, "\nMissing required env var for generating bp2build metrics: LOG_DIR\n")
814 os.Exit(1)
815 }
Chris Parsons715b08f2022-03-22 19:23:40 -0400816 codegenMetrics.Write(metricsDir)
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500817}
MarkDacek0d5bca52022-10-10 20:07:48 +0000818
Sasha Smundak1845f422022-12-13 14:18:58 -0800819func readFileLines(path string) ([]string, error) {
820 data, err := os.ReadFile(path)
821 if err == nil {
822 return strings.Split(strings.TrimSpace(string(data)), "\n"), nil
MarkDacek0d5bca52022-10-10 20:07:48 +0000823 }
Sasha Smundak1845f422022-12-13 14:18:58 -0800824 return nil, err
825
826}
827func maybeQuit(err error, format string, args ...interface{}) {
828 if err == nil {
829 return
830 }
831 if format != "" {
832 fmt.Fprintln(os.Stderr, fmt.Sprintf(format, args...)+": "+err.Error())
833 } else {
834 fmt.Fprintln(os.Stderr, err)
835 }
836 os.Exit(1)
MarkDacek0d5bca52022-10-10 20:07:48 +0000837}