blob: d2eadbaece21a9603de8d9707d44daf08bac8760 [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"
Chris Parsons8152a942023-06-06 16:17:50 +000024 "regexp"
Jingwen Cheneb76c432021-01-28 08:22:12 -050025 "strings"
Lukacs T. Berkic99c9472021-03-24 10:50:06 +010026 "time"
Colin Cross3f40fa42015-01-30 17:27:36 -080027
Dan Willemsen66213a62021-09-21 17:50:30 -070028 "android/soong/android"
Jeongik Chae114e602023-03-19 00:12:39 +090029 "android/soong/android/allowlists"
Spandan Das5af0bd32022-09-28 20:43:08 +000030 "android/soong/bazel"
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020031 "android/soong/bp2build"
Lukacs T. Berki7690c092021-02-26 14:27:36 +010032 "android/soong/shared"
Chris Parsons715b08f2022-03-22 19:23:40 -040033 "android/soong/ui/metrics/bp2build_metrics_proto"
Lukacs T. Berkie571dc32021-08-25 14:14:13 +020034
Jeongik Chab745e2e2023-04-11 14:28:43 +090035 "github.com/google/blueprint"
Colin Cross70b40592015-03-23 12:57:34 -070036 "github.com/google/blueprint/bootstrap"
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +020037 "github.com/google/blueprint/deptools"
Chris Parsons715b08f2022-03-22 19:23:40 -040038 "github.com/google/blueprint/metrics"
Dan Willemsen66213a62021-09-21 17:50:30 -070039 androidProtobuf "google.golang.org/protobuf/android"
Colin Cross3f40fa42015-01-30 17:27:36 -080040)
41
Colin Crosse87040b2017-12-11 15:52:26 -080042var (
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020043 topDir string
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020044 availableEnvFile string
45 usedEnvFile string
46
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +020047 globFile string
48 globListDir string
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020049 delveListen string
50 delvePath string
51
Sasha Smundakaf5ca922022-12-12 21:23:34 -080052 cmdlineArgs android.CmdArgs
Colin Crosse87040b2017-12-11 15:52:26 -080053)
54
55func init() {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020056 // Flags that make sense in every mode
Lukacs T. Berki7690c092021-02-26 14:27:36 +010057 flag.StringVar(&topDir, "top", "", "Top directory of the Android source tree")
Sasha Smundakaf5ca922022-12-12 21:23:34 -080058 flag.StringVar(&cmdlineArgs.SoongOutDir, "soong_out", "", "Soong output directory (usually $TOP/out/soong)")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020059 flag.StringVar(&availableEnvFile, "available_env", "", "File containing available environment variables")
60 flag.StringVar(&usedEnvFile, "used_env", "", "File containing used environment variables")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020061 flag.StringVar(&globFile, "globFile", "build-globs.ninja", "the Ninja file of globs to output")
62 flag.StringVar(&globListDir, "globListDir", "", "the directory containing the glob list files")
Sasha Smundakaf5ca922022-12-12 21:23:34 -080063 flag.StringVar(&cmdlineArgs.OutDir, "out", "", "the ninja builddir directory")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020064 flag.StringVar(&cmdlineArgs.ModuleListFile, "l", "", "file that lists filepaths to parse")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020065
66 // Debug flags
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +010067 flag.StringVar(&delveListen, "delve_listen", "", "Delve port to listen on for debugging")
68 flag.StringVar(&delvePath, "delve_path", "", "Path to Delve. Only used if --delve_listen is set")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020069 flag.StringVar(&cmdlineArgs.Cpuprofile, "cpuprofile", "", "write cpu profile to file")
70 flag.StringVar(&cmdlineArgs.TraceFile, "trace", "", "write trace to file")
71 flag.StringVar(&cmdlineArgs.Memprofile, "memprofile", "", "write memory profile to file")
72 flag.BoolVar(&cmdlineArgs.NoGC, "nogc", false, "turn off GC for debugging")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020073
74 // Flags representing various modes soong_build can run in
Sasha Smundakaf5ca922022-12-12 21:23:34 -080075 flag.StringVar(&cmdlineArgs.ModuleGraphFile, "module_graph_file", "", "JSON module graph file to output")
76 flag.StringVar(&cmdlineArgs.ModuleActionsFile, "module_actions_file", "", "JSON file to output inputs/outputs of actions of modules")
77 flag.StringVar(&cmdlineArgs.DocFile, "soong_docs", "", "build documentation file to output")
78 flag.StringVar(&cmdlineArgs.BazelQueryViewDir, "bazel_queryview_dir", "", "path to the bazel queryview directory relative to --top")
79 flag.StringVar(&cmdlineArgs.BazelApiBp2buildDir, "bazel_api_bp2build_dir", "", "path to the bazel api_bp2build directory relative to --top")
80 flag.StringVar(&cmdlineArgs.Bp2buildMarker, "bp2build_marker", "", "If set, run bp2build, touch the specified marker file then exit")
81 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 +020082 flag.StringVar(&cmdlineArgs.OutFile, "o", "build.ninja", "the Ninja file to output")
Kiyoung Kima37d9ba2023-04-19 13:13:45 +090083 flag.StringVar(&cmdlineArgs.SoongVariables, "soong_variables", "soong.variables", "the file contains all build variables")
MarkDacekd06db5d2022-11-29 00:47:59 +000084 flag.StringVar(&cmdlineArgs.BazelForceEnabledModules, "bazel-force-enabled-modules", "", "additional modules to build with Bazel. Comma-delimited")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020085 flag.BoolVar(&cmdlineArgs.EmptyNinjaFile, "empty-ninja-file", false, "write out a 0-byte ninja file")
LaMont Jones52a72432023-03-09 18:19:35 +000086 flag.BoolVar(&cmdlineArgs.MultitreeBuild, "multitree-build", false, "this is a multitree build")
Chris Parsonsef615e52022-08-18 22:04:11 -040087 flag.BoolVar(&cmdlineArgs.BazelMode, "bazel-mode", false, "use bazel for analysis of certain modules")
Jingwen Chene647db82022-11-01 11:28:29 +000088 flag.BoolVar(&cmdlineArgs.BazelModeStaging, "bazel-mode-staging", false, "use bazel for analysis of certain near-ready modules")
Chris Parsonsef615e52022-08-18 22:04:11 -040089 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 -050090 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 +000091 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 +000092 flag.BoolVar(&cmdlineArgs.EnsureAllowlistIntegrity, "ensure-allowlist-integrity", false, "verify that allowlisted modules are mixed-built")
Sasha Smundakaf5ca922022-12-12 21:23:34 -080093 // Flags that probably shouldn't be flags of soong_build, but we haven't found
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020094 // the time to remove them yet
Sasha Smundakaf5ca922022-12-12 21:23:34 -080095 flag.BoolVar(&cmdlineArgs.RunGoTests, "t", false, "build and run go tests during bootstrap")
Dan Willemsen66213a62021-09-21 17:50:30 -070096
97 // Disable deterministic randomization in the protobuf package, so incremental
98 // builds with unrelated Soong changes don't trigger large rebuilds (since we
99 // write out text protos in command lines, and command line changes trigger
100 // rebuilds).
101 androidProtobuf.DisableRand()
Colin Crosse87040b2017-12-11 15:52:26 -0800102}
103
Jeff Gaston088e29e2017-11-29 16:47:17 -0800104func newNameResolver(config android.Config) *android.NameResolver {
Paul Duffin3f7bf9f2022-11-08 12:21:15 +0000105 return android.NewNameResolver(config)
Jeff Gaston088e29e2017-11-29 16:47:17 -0800106}
107
Lukacs T. Berkiffc9e8d2021-09-07 17:54:38 +0200108func newContext(configuration android.Config) *android.Context {
Colin Crossae8600b2020-10-29 17:09:13 -0700109 ctx := android.NewContext(configuration)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400110 ctx.SetNameInterface(newNameResolver(configuration))
111 ctx.SetAllowMissingDependencies(configuration.AllowMissingDependencies())
Spandan Dasc5763832022-11-08 18:42:16 +0000112 ctx.AddIncludeTags(configuration.IncludeTags()...)
Sam Delmerico98a73292023-02-21 11:50:29 -0500113 ctx.AddSourceRootDirs(configuration.SourceRootDirs()...)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400114 return ctx
115}
116
Chris Parsonsf874e462022-05-10 13:50:12 -0400117// Bazel-enabled mode. Attaches a mutator to queue Bazel requests, adds a
118// BeforePrepareBuildActionsHook to invoke Bazel, and then uses Bazel metadata
119// for modules that should be handled by Bazel.
Sasha Smundak1845f422022-12-13 14:18:58 -0800120func runMixedModeBuild(ctx *android.Context, extraNinjaDeps []string) string {
Chris Parsonsf874e462022-05-10 13:50:12 -0400121 ctx.EventHandler.Begin("mixed_build")
122 defer ctx.EventHandler.End("mixed_build")
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200123
Chris Parsonsf874e462022-05-10 13:50:12 -0400124 bazelHook := func() error {
Sasha Smundak1845f422022-12-13 14:18:58 -0800125 return ctx.Config().BazelContext.InvokeBazel(ctx.Config(), ctx)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200126 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400127 ctx.SetBeforePrepareBuildActionsHook(bazelHook)
Sasha Smundak1845f422022-12-13 14:18:58 -0800128 ninjaDeps := bootstrap.RunBlueprint(cmdlineArgs.Args, bootstrap.DoEverything, ctx.Context, ctx.Config())
Chris Parsons027881c2022-05-24 15:38:38 -0400129 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200130
Sasha Smundak1845f422022-12-13 14:18:58 -0800131 bazelPaths, err := readFileLines(ctx.Config().Getenv("BAZEL_DEPS_FILE"))
MarkDacek0d5bca52022-10-10 20:07:48 +0000132 if err != nil {
133 panic("Bazel deps file not found: " + err.Error())
134 }
135 ninjaDeps = append(ninjaDeps, bazelPaths...)
Sasha Smundak1845f422022-12-13 14:18:58 -0800136 ninjaDeps = append(ninjaDeps, writeBuildGlobsNinjaFile(ctx)...)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200137
Paul Duffin780a1852022-11-05 10:17:12 +0000138 writeDepFile(cmdlineArgs.OutFile, ctx.EventHandler, ninjaDeps)
Jeongik Cha591366d2023-05-08 11:32:52 +0900139
Jeongik Chaa87506f2023-06-01 23:16:41 +0900140 if needToWriteNinjaHint(ctx) {
Jeongik Cha591366d2023-05-08 11:32:52 +0900141 writeNinjaHint(ctx)
142 }
Paul Duffin0c09a432022-11-05 15:28:04 +0000143 return cmdlineArgs.OutFile
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200144}
145
Jeongik Chaa87506f2023-06-01 23:16:41 +0900146func needToWriteNinjaHint(ctx *android.Context) bool {
147 switch ctx.Config().GetenvWithDefault("SOONG_GENERATES_NINJA_HINT", "") {
148 case "always":
149 return true
150 case "depend":
151 if _, err := os.Stat(filepath.Join(ctx.Config().OutDir(), ".ninja_log")); errors.Is(err, os.ErrNotExist) {
152 return true
153 }
154 }
155 return false
156}
157
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200158// Run the code-generation phase to convert BazelTargetModules to BUILD files.
Sasha Smundak1845f422022-12-13 14:18:58 -0800159func runQueryView(queryviewDir, queryviewMarker string, ctx *android.Context) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400160 ctx.EventHandler.Begin("queryview")
161 defer ctx.EventHandler.End("queryview")
Cole Faustb85d1a12022-11-08 18:14:01 -0800162 codegenContext := bp2build.NewCodegenContext(ctx.Config(), ctx, bp2build.QueryView, topDir)
Spandan Das98cb8562023-03-09 23:05:47 +0000163 err := createBazelWorkspace(codegenContext, shared.JoinPath(topDir, queryviewDir), false)
Sasha Smundak1845f422022-12-13 14:18:58 -0800164 maybeQuit(err, "")
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200165 touch(shared.JoinPath(topDir, queryviewMarker))
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200166}
167
Spandan Das5af0bd32022-09-28 20:43:08 +0000168// Run the code-generation phase to convert API contributions to BUILD files.
169// Return marker file for the new synthetic workspace
Sasha Smundak1845f422022-12-13 14:18:58 -0800170func runApiBp2build(ctx *android.Context, extraNinjaDeps []string) string {
Spandan Das5af0bd32022-09-28 20:43:08 +0000171 ctx.EventHandler.Begin("api_bp2build")
172 defer ctx.EventHandler.End("api_bp2build")
Spandan Das255648c2023-01-11 03:05:24 +0000173 // api_bp2build does not run the typical pipeline of soong mutators.
174 // Hoevever, it still runs the defaults mutator which can create dependencies.
175 // These dependencies might not always exist (e.g. in tests)
176 ctx.SetAllowMissingDependencies(ctx.Config().AllowMissingDependencies())
Spandan Das5af0bd32022-09-28 20:43:08 +0000177 ctx.RegisterForApiBazelConversion()
178
179 // Register the Android.bp files in the tree
180 // Add them to the workspace's .d file
181 ctx.SetModuleListFile(cmdlineArgs.ModuleListFile)
182 if paths, err := ctx.ListModulePaths("."); err == nil {
183 extraNinjaDeps = append(extraNinjaDeps, paths...)
184 } else {
185 panic(err)
186 }
187
188 // Run the loading and analysis phase
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800189 ninjaDeps := bootstrap.RunBlueprint(cmdlineArgs.Args,
Spandan Das5af0bd32022-09-28 20:43:08 +0000190 bootstrap.StopBeforePrepareBuildActions,
191 ctx.Context,
Sasha Smundak1845f422022-12-13 14:18:58 -0800192 ctx.Config())
Spandan Das5af0bd32022-09-28 20:43:08 +0000193 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
194
195 // Add the globbed dependencies
Sasha Smundak1845f422022-12-13 14:18:58 -0800196 ninjaDeps = append(ninjaDeps, writeBuildGlobsNinjaFile(ctx)...)
Spandan Das5af0bd32022-09-28 20:43:08 +0000197
198 // Run codegen to generate BUILD files
Cole Faustb85d1a12022-11-08 18:14:01 -0800199 codegenContext := bp2build.NewCodegenContext(ctx.Config(), ctx, bp2build.ApiBp2build, topDir)
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800200 absoluteApiBp2buildDir := shared.JoinPath(topDir, cmdlineArgs.BazelApiBp2buildDir)
Spandan Das98cb8562023-03-09 23:05:47 +0000201 // Always generate bp2build_all_srcs filegroups in api_bp2build.
202 // This is necessary to force each Android.bp file to create an equivalent BUILD file
203 // and prevent package boundray issues.
204 // e.g.
205 // Source
206 // f/b/Android.bp
207 // java_library{
208 // name: "foo",
209 // api: "api/current.txt",
210 // }
211 //
212 // f/b/api/Android.bp <- will cause package boundary issues
213 //
214 // Gen
215 // f/b/BUILD
216 // java_contribution{
217 // name: "foo.contribution",
218 // api: "//f/b/api:current.txt",
219 // }
220 //
221 // If we don't generate f/b/api/BUILD, foo.contribution will be unbuildable.
222 err := createBazelWorkspace(codegenContext, absoluteApiBp2buildDir, true)
Sasha Smundak1845f422022-12-13 14:18:58 -0800223 maybeQuit(err, "")
Spandan Das5af0bd32022-09-28 20:43:08 +0000224 ninjaDeps = append(ninjaDeps, codegenContext.AdditionalNinjaDeps()...)
225
226 // Create soong_injection repository
Cole Faust9e384e22023-02-08 17:43:09 -0800227 soongInjectionFiles, err := bp2build.CreateSoongInjectionDirFiles(codegenContext, bp2build.CreateCodegenMetrics())
228 maybeQuit(err, "")
Sasha Smundak1845f422022-12-13 14:18:58 -0800229 absoluteSoongInjectionDir := shared.JoinPath(topDir, ctx.Config().SoongOutDir(), bazel.SoongInjectionDirName)
Spandan Das5af0bd32022-09-28 20:43:08 +0000230 for _, file := range soongInjectionFiles {
Spandan Das067210f2022-12-07 01:14:52 +0000231 // The API targets in api_bp2build workspace do not have any dependency on api_bp2build.
232 // But we need to create these files to prevent errors during Bazel analysis.
233 // These need to be created in Read-Write mode.
234 // This is because the subsequent step (bp2build in api domain analysis) creates them in Read-Write mode
235 // to allow users to edit/experiment in the synthetic workspace.
236 writeReadWriteFile(absoluteSoongInjectionDir, file)
Spandan Das5af0bd32022-09-28 20:43:08 +0000237 }
238
Sasha Smundak1845f422022-12-13 14:18:58 -0800239 workspace := shared.JoinPath(ctx.Config().SoongOutDir(), "api_bp2build")
Spandan Das5af0bd32022-09-28 20:43:08 +0000240 // Create the symlink forest
Usta Shresthada15c612022-11-08 14:12:36 -0500241 symlinkDeps, _, _ := bp2build.PlantSymlinkForest(
Sasha Smundak1845f422022-12-13 14:18:58 -0800242 ctx.Config().IsEnvTrue("BP2BUILD_VERBOSE"),
Spandan Das5af0bd32022-09-28 20:43:08 +0000243 topDir,
244 workspace,
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800245 cmdlineArgs.BazelApiBp2buildDir,
Sasha Smundak1845f422022-12-13 14:18:58 -0800246 apiBuildFileExcludes(ctx))
Spandan Das5af0bd32022-09-28 20:43:08 +0000247 ninjaDeps = append(ninjaDeps, symlinkDeps...)
248
249 workspaceMarkerFile := workspace + ".marker"
Paul Duffin780a1852022-11-05 10:17:12 +0000250 writeDepFile(workspaceMarkerFile, ctx.EventHandler, ninjaDeps)
Spandan Das5af0bd32022-09-28 20:43:08 +0000251 touch(shared.JoinPath(topDir, workspaceMarkerFile))
252 return workspaceMarkerFile
253}
254
255// With some exceptions, api_bp2build does not have any dependencies on the checked-in BUILD files
256// Exclude them from the generated workspace to prevent unrelated errors during the loading phase
Sasha Smundak1845f422022-12-13 14:18:58 -0800257func apiBuildFileExcludes(ctx *android.Context) []string {
258 ret := bazelArtifacts()
Spandan Das5af0bd32022-09-28 20:43:08 +0000259 srcs, err := getExistingBazelRelatedFiles(topDir)
Sasha Smundak1845f422022-12-13 14:18:58 -0800260 maybeQuit(err, "Error determining existing Bazel-related files")
Spandan Das5af0bd32022-09-28 20:43:08 +0000261 for _, src := range srcs {
Sasha Smundak1845f422022-12-13 14:18:58 -0800262 // Exclude all src BUILD files
Spandan Das5af0bd32022-09-28 20:43:08 +0000263 if src != "WORKSPACE" &&
264 src != "BUILD" &&
265 src != "BUILD.bazel" &&
266 !strings.HasPrefix(src, "build/bazel") &&
Spandan Das6b91a382022-11-30 02:17:06 +0000267 !strings.HasPrefix(src, "external/bazel-skylib") &&
Spandan Das5af0bd32022-09-28 20:43:08 +0000268 !strings.HasPrefix(src, "prebuilts/clang") {
269 ret = append(ret, src)
270 }
271 }
Sasha Smundak1845f422022-12-13 14:18:58 -0800272 // Android.bp files for api surfaces are mounted to out/, but out/ should not be a
273 // dep for api_bp2build. Otherwise, api_bp2build will be run every single time
274 ret = append(ret, ctx.Config().OutDir())
Spandan Das5af0bd32022-09-28 20:43:08 +0000275 return ret
276}
277
Jeongik Chae114e602023-03-19 00:12:39 +0900278func writeNinjaHint(ctx *android.Context) error {
Jeongik Cha73d49112023-05-04 18:16:11 +0900279 ctx.BeginEvent("ninja_hint")
280 defer ctx.EndEvent("ninja_hint")
Jeongik Chab745e2e2023-04-11 14:28:43 +0900281 // The current predictor focuses on reducing false negatives.
282 // If there are too many false positives (e.g., most modules are marked as positive),
283 // real long-running jobs cannot run early.
284 // Therefore, the model should be adjusted in this case.
285 // The model should also be adjusted if there are critical false negatives.
286 predicate := func(j *blueprint.JsonModule) (prioritized bool, weight int) {
287 prioritized = false
288 weight = 0
289 for prefix, w := range allowlists.HugeModuleTypePrefixMap {
290 if strings.HasPrefix(j.Type, prefix) {
291 prioritized = true
292 weight = w
293 return
294 }
Jeongik Chae114e602023-03-19 00:12:39 +0900295 }
Jeongik Chab745e2e2023-04-11 14:28:43 +0900296 dep_count := len(j.Deps)
297 src_count := 0
298 for _, a := range j.Module["Actions"].([]blueprint.JSONAction) {
299 src_count += len(a.Inputs)
300 }
301 input_size := dep_count + src_count
302
303 // Current threshold is an arbitrary value which only consider recall rather than accuracy.
304 if input_size > allowlists.INPUT_SIZE_THRESHOLD {
305 prioritized = true
306 weight += ((input_size) / allowlists.INPUT_SIZE_THRESHOLD) * allowlists.DEFAULT_PRIORITIZED_WEIGHT
307
308 // To prevent some modules from having too large a priority value.
309 if weight > allowlists.HIGH_PRIORITIZED_WEIGHT {
310 weight = allowlists.HIGH_PRIORITIZED_WEIGHT
311 }
312 }
313 return
314 }
315
316 outputsMap := ctx.Context.GetWeightedOutputsFromPredicate(predicate)
317 var outputBuilder strings.Builder
318 for output, weight := range outputsMap {
319 outputBuilder.WriteString(fmt.Sprintf("%s,%d\n", output, weight))
Jeongik Chae114e602023-03-19 00:12:39 +0900320 }
321 weightListFile := filepath.Join(topDir, ctx.Config().OutDir(), ".ninja_weight_list")
322
323 err := os.WriteFile(weightListFile, []byte(outputBuilder.String()), 0644)
324 if err != nil {
325 return fmt.Errorf("could not write ninja weight list file %s", err)
326 }
327 return nil
328}
329
Paul Duffin780a1852022-11-05 10:17:12 +0000330func writeMetrics(configuration android.Config, eventHandler *metrics.EventHandler, metricsDir string) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400331 if len(metricsDir) < 1 {
332 fmt.Fprintf(os.Stderr, "\nMissing required env var for generating soong metrics: LOG_DIR\n")
333 os.Exit(1)
334 }
335 metricsFile := filepath.Join(metricsDir, "soong_build_metrics.pb")
336 err := android.WriteMetrics(configuration, eventHandler, metricsFile)
Sasha Smundak1845f422022-12-13 14:18:58 -0800337 maybeQuit(err, "error writing soong_build metrics %s", metricsFile)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200338}
339
MarkDacekf47e1422023-04-19 16:47:36 +0000340// Errors out if any modules expected to be mixed_built were not, unless
MarkDacek6f6b9622023-05-02 16:28:55 +0000341// the modules did not exist.
MarkDacekf47e1422023-04-19 16:47:36 +0000342func checkForAllowlistIntegrityError(configuration android.Config, isStagingMode bool) error {
MarkDacek6f6b9622023-05-02 16:28:55 +0000343 modules := findMisconfiguredModules(configuration, isStagingMode)
MarkDacekf47e1422023-04-19 16:47:36 +0000344 if len(modules) == 0 {
345 return nil
346 }
347
348 return fmt.Errorf("Error: expected the following modules to be mixed_built: %s", modules)
349}
350
MarkDacek6f6b9622023-05-02 16:28:55 +0000351// Returns true if the given module has all of the following true:
352// 1. Is allowlisted to be built with Bazel.
353// 2. Has a variant which is *not* built with Bazel.
354// 3. Has no variant which is built with Bazel.
355//
356// This indicates the allowlisting of this variant had no effect.
357// TODO(b/280457637): Return true for nonexistent modules.
358func isAllowlistMisconfiguredForModule(module string, mixedBuildsEnabled map[string]struct{}, mixedBuildsDisabled map[string]struct{}) bool {
MarkDacek6f6b9622023-05-02 16:28:55 +0000359 _, enabled := mixedBuildsEnabled[module]
360
361 if enabled {
362 return false
363 }
364
365 _, disabled := mixedBuildsDisabled[module]
366 return disabled
367
368}
369
MarkDacekf47e1422023-04-19 16:47:36 +0000370// Returns the list of modules that should have been mixed_built (per the
371// allowlists and cmdline flags) but were not.
MarkDacek6f6b9622023-05-02 16:28:55 +0000372// Note: nonexistent modules are excluded from the list. See b/280457637
373func findMisconfiguredModules(configuration android.Config, isStagingMode bool) []string {
MarkDacekf47e1422023-04-19 16:47:36 +0000374 retval := []string{}
375 forceEnabledModules := configuration.BazelModulesForceEnabledByFlag()
376
377 mixedBuildsEnabled := configuration.GetMixedBuildsEnabledModules()
MarkDacek6f6b9622023-05-02 16:28:55 +0000378 mixedBuildsDisabled := configuration.GetMixedBuildsDisabledModules()
MarkDacekf47e1422023-04-19 16:47:36 +0000379 for _, module := range allowlists.ProdMixedBuildsEnabledList {
MarkDacek6f6b9622023-05-02 16:28:55 +0000380 if isAllowlistMisconfiguredForModule(module, mixedBuildsEnabled, mixedBuildsDisabled) {
MarkDacekf47e1422023-04-19 16:47:36 +0000381 retval = append(retval, module)
382 }
383 }
384
385 if isStagingMode {
386 for _, module := range allowlists.StagingMixedBuildsEnabledList {
MarkDacek6f6b9622023-05-02 16:28:55 +0000387 if isAllowlistMisconfiguredForModule(module, mixedBuildsEnabled, mixedBuildsDisabled) {
MarkDacekf47e1422023-04-19 16:47:36 +0000388 retval = append(retval, module)
389 }
390 }
391 }
392
393 for module, _ := range forceEnabledModules {
MarkDacek6f6b9622023-05-02 16:28:55 +0000394 if isAllowlistMisconfiguredForModule(module, mixedBuildsEnabled, mixedBuildsDisabled) {
MarkDacekf47e1422023-04-19 16:47:36 +0000395 retval = append(retval, module)
396 }
397 }
398 return retval
399}
400
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800401func writeJsonModuleGraphAndActions(ctx *android.Context, cmdArgs android.CmdArgs) {
402 graphFile, graphErr := os.Create(shared.JoinPath(topDir, cmdArgs.ModuleGraphFile))
Sasha Smundak1845f422022-12-13 14:18:58 -0800403 maybeQuit(graphErr, "graph err")
kgui67007242022-01-25 13:50:25 +0800404 defer graphFile.Close()
Sasha Smundak1845f422022-12-13 14:18:58 -0800405 actionsFile, actionsErr := os.Create(shared.JoinPath(topDir, cmdArgs.ModuleActionsFile))
406 maybeQuit(actionsErr, "actions err")
kgui67007242022-01-25 13:50:25 +0800407 defer actionsFile.Close()
408 ctx.Context.PrintJSONGraphAndActions(graphFile, actionsFile)
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200409}
410
Sasha Smundak1845f422022-12-13 14:18:58 -0800411func writeBuildGlobsNinjaFile(ctx *android.Context) []string {
Chris Parsons715b08f2022-03-22 19:23:40 -0400412 ctx.EventHandler.Begin("globs_ninja_file")
413 defer ctx.EventHandler.End("globs_ninja_file")
414
Sasha Smundak1845f422022-12-13 14:18:58 -0800415 globDir := bootstrap.GlobDirectory(ctx.Config().SoongOutDir(), globListDir)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200416 bootstrap.WriteBuildGlobsNinjaFile(&bootstrap.GlobSingleton{
Chris Parsons715b08f2022-03-22 19:23:40 -0400417 GlobLister: ctx.Globs,
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200418 GlobFile: globFile,
419 GlobDir: globDir,
Chris Parsons715b08f2022-03-22 19:23:40 -0400420 SrcDir: ctx.SrcDir(),
Sasha Smundak1845f422022-12-13 14:18:58 -0800421 }, ctx.Config())
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200422 return bootstrap.GlobFileListFiles(globDir)
423}
424
Paul Duffin780a1852022-11-05 10:17:12 +0000425func writeDepFile(outputFile string, eventHandler *metrics.EventHandler, ninjaDeps []string) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400426 eventHandler.Begin("ninja_deps")
427 defer eventHandler.End("ninja_deps")
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200428 depFile := shared.JoinPath(topDir, outputFile+".d")
429 err := deptools.WriteDepFile(depFile, outputFile, ninjaDeps)
Sasha Smundak1845f422022-12-13 14:18:58 -0800430 maybeQuit(err, "error writing depfile '%s'", depFile)
Paul Duffin0c09a432022-11-05 15:28:04 +0000431}
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200432
Paul Duffin0c09a432022-11-05 15:28:04 +0000433// runSoongOnlyBuild runs the standard Soong build in a number of different modes.
Sasha Smundak1845f422022-12-13 14:18:58 -0800434func runSoongOnlyBuild(ctx *android.Context, extraNinjaDeps []string) string {
Paul Duffin39eae8f2022-11-05 14:59:52 +0000435 ctx.EventHandler.Begin("soong_build")
436 defer ctx.EventHandler.End("soong_build")
437
Paul Duffin0c09a432022-11-05 15:28:04 +0000438 var stopBefore bootstrap.StopBefore
Sasha Smundak1845f422022-12-13 14:18:58 -0800439 switch ctx.Config().BuildMode {
440 case android.GenerateModuleGraph:
Paul Duffin0c09a432022-11-05 15:28:04 +0000441 stopBefore = bootstrap.StopBeforeWriteNinja
Usta Shrestha7fae6952022-12-21 11:46:28 -0500442 case android.GenerateQueryView, android.GenerateDocFile:
Paul Duffin0c09a432022-11-05 15:28:04 +0000443 stopBefore = bootstrap.StopBeforePrepareBuildActions
Sasha Smundak1845f422022-12-13 14:18:58 -0800444 default:
Paul Duffin0c09a432022-11-05 15:28:04 +0000445 stopBefore = bootstrap.DoEverything
446 }
447
Sasha Smundak1845f422022-12-13 14:18:58 -0800448 ninjaDeps := bootstrap.RunBlueprint(cmdlineArgs.Args, stopBefore, ctx.Context, ctx.Config())
Paul Duffin0c09a432022-11-05 15:28:04 +0000449 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
450
Sasha Smundak1845f422022-12-13 14:18:58 -0800451 globListFiles := writeBuildGlobsNinjaFile(ctx)
Paul Duffin0c09a432022-11-05 15:28:04 +0000452 ninjaDeps = append(ninjaDeps, globListFiles...)
453
454 // Convert the Soong module graph into Bazel BUILD files.
Sasha Smundak1845f422022-12-13 14:18:58 -0800455 switch ctx.Config().BuildMode {
456 case android.GenerateQueryView:
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800457 queryviewMarkerFile := cmdlineArgs.BazelQueryViewDir + ".marker"
Sasha Smundak1845f422022-12-13 14:18:58 -0800458 runQueryView(cmdlineArgs.BazelQueryViewDir, queryviewMarkerFile, ctx)
Paul Duffin0c09a432022-11-05 15:28:04 +0000459 writeDepFile(queryviewMarkerFile, ctx.EventHandler, ninjaDeps)
460 return queryviewMarkerFile
Sasha Smundak1845f422022-12-13 14:18:58 -0800461 case android.GenerateModuleGraph:
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800462 writeJsonModuleGraphAndActions(ctx, cmdlineArgs)
463 writeDepFile(cmdlineArgs.ModuleGraphFile, ctx.EventHandler, ninjaDeps)
464 return cmdlineArgs.ModuleGraphFile
Sasha Smundak1845f422022-12-13 14:18:58 -0800465 case android.GenerateDocFile:
Paul Duffin0c09a432022-11-05 15:28:04 +0000466 // TODO: we could make writeDocs() return the list of documentation files
467 // written and add them to the .d file. Then soong_docs would be re-run
468 // whenever one is deleted.
Sasha Smundak1845f422022-12-13 14:18:58 -0800469 err := writeDocs(ctx, shared.JoinPath(topDir, cmdlineArgs.DocFile))
470 maybeQuit(err, "error building Soong documentation")
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800471 writeDepFile(cmdlineArgs.DocFile, ctx.EventHandler, ninjaDeps)
472 return cmdlineArgs.DocFile
Sasha Smundak1845f422022-12-13 14:18:58 -0800473 default:
Paul Duffin0c09a432022-11-05 15:28:04 +0000474 // The actual output (build.ninja) was written in the RunBlueprint() call
475 // above
476 writeDepFile(cmdlineArgs.OutFile, ctx.EventHandler, ninjaDeps)
Jeongik Chaa87506f2023-06-01 23:16:41 +0900477 if needToWriteNinjaHint(ctx) {
Jeongik Cha591366d2023-05-08 11:32:52 +0900478 writeNinjaHint(ctx)
479 }
Paul Duffinb713ddf2022-11-05 16:14:30 +0000480 return cmdlineArgs.OutFile
Paul Duffin0c09a432022-11-05 15:28:04 +0000481 }
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200482}
483
484// soong_ui dumps the available environment variables to
485// soong.environment.available . Then soong_build itself is run with an empty
486// environment so that the only way environment variables can be accessed is
487// using Config, which tracks access to them.
488
489// At the end of the build, a file called soong.environment.used is written
490// containing the current value of all used environment variables. The next
491// time soong_ui is run, it checks whether any environment variables that was
492// used had changed and if so, it deletes soong.environment.used to cause a
493// rebuild.
494//
495// The dependency of build.ninja on soong.environment.used is declared in
496// build.ninja.d
497func parseAvailableEnv() map[string]string {
498 if availableEnvFile == "" {
499 fmt.Fprintf(os.Stderr, "--available_env not set\n")
500 os.Exit(1)
501 }
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200502 result, err := shared.EnvFromFile(shared.JoinPath(topDir, availableEnvFile))
Sasha Smundak1845f422022-12-13 14:18:58 -0800503 maybeQuit(err, "error reading available environment file '%s'", availableEnvFile)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200504 return result
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200505}
506
Colin Cross3f40fa42015-01-30 17:27:36 -0800507func main() {
508 flag.Parse()
509
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100510 shared.ReexecWithDelveMaybe(delveListen, delvePath)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100511 android.InitSandbox(topDir)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100512
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200513 availableEnv := parseAvailableEnv()
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800514 configuration, err := android.NewConfig(cmdlineArgs, availableEnv)
Sasha Smundak1845f422022-12-13 14:18:58 -0800515 maybeQuit(err, "")
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100516 if configuration.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
517 configuration.SetAllowMissingDependencies()
518 }
519
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800520 extraNinjaDeps := []string{configuration.ProductVariablesFileName, usedEnvFile}
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100521 if shared.IsDebugging() {
Colin Crossaa812d12019-06-19 13:33:24 -0700522 // Add a non-existent file to the dependencies so that soong_build will rerun when the debugger is
523 // enabled even if it completed successfully.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200524 extraNinjaDeps = append(extraNinjaDeps, filepath.Join(configuration.SoongOutDir(), "always_rerun_for_delve"))
Colin Crossaa812d12019-06-19 13:33:24 -0700525 }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500526
Dan Willemsenccf36aa2022-04-20 23:11:43 -0700527 // Bypass configuration.Getenv, as LOG_DIR does not need to be dependency tracked. By definition, it will
528 // change between every CI build, so tracking it would require re-running Soong for every build.
Sasha Smundak1845f422022-12-13 14:18:58 -0800529 metricsDir := availableEnv["LOG_DIR"]
Dan Willemsenccf36aa2022-04-20 23:11:43 -0700530
Joe Onorato2e5e4012022-06-07 17:16:08 -0700531 ctx := newContext(configuration)
Joe Onorato2e5e4012022-06-07 17:16:08 -0700532
Sasha Smundak1845f422022-12-13 14:18:58 -0800533 var finalOutputFile string
Joe Onorato2e5e4012022-06-07 17:16:08 -0700534
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900535 writeSymlink := false
536
Sasha Smundak1845f422022-12-13 14:18:58 -0800537 // Run Soong for a specific activity, like bp2build, queryview
538 // or the actual Soong build for the build.ninja file.
539 switch configuration.BuildMode {
540 case android.SymlinkForest:
541 finalOutputFile = runSymlinkForestCreation(ctx, extraNinjaDeps, metricsDir)
542 case android.Bp2build:
543 // Run the alternate pipeline of bp2build mutators and singleton to convert
544 // Blueprint to BUILD files before everything else.
545 finalOutputFile = runBp2Build(ctx, extraNinjaDeps, metricsDir)
546 case android.ApiBp2build:
547 finalOutputFile = runApiBp2build(ctx, extraNinjaDeps)
548 writeMetrics(configuration, ctx.EventHandler, metricsDir)
549 default:
550 ctx.Register()
MarkDacekf47e1422023-04-19 16:47:36 +0000551 isMixedBuildsEnabled := configuration.IsMixedBuildsEnabled()
552 if isMixedBuildsEnabled {
Sasha Smundak1845f422022-12-13 14:18:58 -0800553 finalOutputFile = runMixedModeBuild(ctx, extraNinjaDeps)
MarkDacekf47e1422023-04-19 16:47:36 +0000554 if cmdlineArgs.EnsureAllowlistIntegrity {
555 if err := checkForAllowlistIntegrityError(configuration, cmdlineArgs.BazelModeStaging); err != nil {
556 maybeQuit(err, "")
557 }
558 }
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900559 writeSymlink = true
Sasha Smundak1845f422022-12-13 14:18:58 -0800560 } else {
561 finalOutputFile = runSoongOnlyBuild(ctx, extraNinjaDeps)
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900562
563 if configuration.BuildMode == android.AnalysisNoBazel {
564 writeSymlink = true
565 }
Sasha Smundak1845f422022-12-13 14:18:58 -0800566 }
567 writeMetrics(configuration, ctx.EventHandler, metricsDir)
568 }
Chris Parsonsc83398f2023-05-31 18:41:41 +0000569
570 // Register this environment variablesas being an implicit dependencies of
571 // soong_build. Changes to this environment variable will result in
572 // retriggering soong_build.
573 configuration.Getenv("USE_BAZEL_VERSION")
574
Chris Parsonsa3ae0072023-05-10 21:10:08 +0000575 writeUsedEnvironmentFile(configuration)
576
577 // Touch the output file so that it's the newest file created by soong_build.
578 // This is necessary because, if soong_build generated any files which
579 // are ninja inputs to the main output file, then ninja would superfluously
580 // rebuild this output file on the next build invocation.
581 touch(shared.JoinPath(topDir, finalOutputFile))
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900582
583 // TODO(b/277029044): Remove this function once build.<product>.ninja lands
584 if writeSymlink {
585 writeBuildNinjaSymlink(configuration, finalOutputFile)
586 }
587}
588
589// TODO(b/277029044): Remove this function once build.<product>.ninja lands
590func writeBuildNinjaSymlink(config android.Config, source string) {
591 targetPath := shared.JoinPath(topDir, config.SoongOutDir(), "build.ninja")
592 sourcePath := shared.JoinPath(topDir, source)
593
594 if targetPath == sourcePath {
595 return
596 }
597
598 os.Remove(targetPath)
599 os.Symlink(sourcePath, targetPath)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100600}
601
Chris Parsonsa3ae0072023-05-10 21:10:08 +0000602func writeUsedEnvironmentFile(configuration android.Config) {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200603 if usedEnvFile == "" {
604 return
605 }
606
607 path := shared.JoinPath(topDir, usedEnvFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100608 data, err := shared.EnvFileContents(configuration.EnvDeps())
Sasha Smundak1845f422022-12-13 14:18:58 -0800609 maybeQuit(err, "error writing used environment file '%s'\n", usedEnvFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100610
Usta Shrestha2ba28a32022-10-24 11:33:09 -0400611 if preexistingData, err := os.ReadFile(path); err != nil {
612 if !os.IsNotExist(err) {
Sasha Smundak1845f422022-12-13 14:18:58 -0800613 maybeQuit(err, "error reading used environment file '%s'", usedEnvFile)
Usta Shrestha2ba28a32022-10-24 11:33:09 -0400614 }
615 } else if bytes.Equal(preexistingData, data) {
616 // used environment file is unchanged
617 return
618 }
Sasha Smundak1845f422022-12-13 14:18:58 -0800619 err = os.WriteFile(path, data, 0666)
620 maybeQuit(err, "error writing used environment file '%s'", usedEnvFile)
Colin Cross3f40fa42015-01-30 17:27:36 -0800621}
Jingwen Chen5ba7e472020-07-15 10:06:41 +0000622
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200623func touch(path string) {
624 f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
Sasha Smundak1845f422022-12-13 14:18:58 -0800625 maybeQuit(err, "Error touching '%s'", path)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200626 err = f.Close()
Sasha Smundak1845f422022-12-13 14:18:58 -0800627 maybeQuit(err, "Error touching '%s'", path)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200628
629 currentTime := time.Now().Local()
630 err = os.Chtimes(path, currentTime, currentTime)
Sasha Smundak1845f422022-12-13 14:18:58 -0800631 maybeQuit(err, "error touching '%s'", path)
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400632}
633
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400634// Read the bazel.list file that the Soong Finder already dumped earlier (hopefully)
635// It contains the locations of BUILD files, BUILD.bazel files, etc. in the source dir
636func getExistingBazelRelatedFiles(topDir string) ([]string, error) {
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200637 bazelFinderFile := filepath.Join(filepath.Dir(cmdlineArgs.ModuleListFile), "bazel.list")
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400638 if !filepath.IsAbs(bazelFinderFile) {
639 // Assume this was a relative path under topDir
640 bazelFinderFile = filepath.Join(topDir, bazelFinderFile)
641 }
Sasha Smundak1845f422022-12-13 14:18:58 -0800642 return readFileLines(bazelFinderFile)
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400643}
644
Spandan Das5af0bd32022-09-28 20:43:08 +0000645func bazelArtifacts() []string {
646 return []string{
647 "bazel-bin",
648 "bazel-genfiles",
649 "bazel-out",
650 "bazel-testlogs",
Usta (Tsering) Shresthac4c07b12022-11-08 18:31:14 -0500651 "bazel-workspace",
Spandan Das5af0bd32022-09-28 20:43:08 +0000652 "bazel-" + filepath.Base(topDir),
653 }
654}
655
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000656// This could in theory easily be separated into a binary that generically
657// merges two directories into a symlink tree. The main obstacle is that this
658// function currently depends on both Bazel-specific knowledge (the existence
659// of bazel-* symlinks) and configuration (the set of BUILD.bazel files that
660// should and should not be kept)
661//
662// Ideally, bp2build would write a file that contains instructions to the
663// symlink tree creation binary. Then the latter would not need to depend on
664// the very heavy-weight machinery of soong_build .
Sasha Smundak1845f422022-12-13 14:18:58 -0800665func runSymlinkForestCreation(ctx *android.Context, extraNinjaDeps []string, metricsDir string) string {
Usta Shresthada15c612022-11-08 14:12:36 -0500666 var ninjaDeps []string
667 var mkdirCount, symlinkCount uint64
668
Paul Duffinb4e8d912022-11-04 13:35:50 +0000669 ctx.EventHandler.Do("symlink_forest", func() {
Usta (Tsering) Shrestha93b2a9b2022-12-01 05:55:35 +0000670 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Sasha Smundak1845f422022-12-13 14:18:58 -0800671 verbose := ctx.Config().IsEnvTrue("BP2BUILD_VERBOSE")
Usta (Tsering) Shrestha93b2a9b2022-12-01 05:55:35 +0000672
673 // PlantSymlinkForest() returns all the directories that were readdir()'ed.
674 // Such a directory SHOULD be added to `ninjaDeps` so that a child directory
675 // or file created/deleted under it would trigger an update of the symlink forest.
Sasha Smundak1845f422022-12-13 14:18:58 -0800676 generatedRoot := shared.JoinPath(ctx.Config().SoongOutDir(), "bp2build")
677 workspaceRoot := shared.JoinPath(ctx.Config().SoongOutDir(), "workspace")
Usta Shresthada15c612022-11-08 14:12:36 -0500678 var symlinkForestDeps []string
Usta (Tsering) Shrestha93b2a9b2022-12-01 05:55:35 +0000679 ctx.EventHandler.Do("plant", func() {
Usta Shresthada15c612022-11-08 14:12:36 -0500680 symlinkForestDeps, mkdirCount, symlinkCount = bp2build.PlantSymlinkForest(
Sasha Smundak1845f422022-12-13 14:18:58 -0800681 verbose, topDir, workspaceRoot, generatedRoot, excludedFromSymlinkForest(ctx, verbose))
Usta (Tsering) Shrestha93b2a9b2022-12-01 05:55:35 +0000682 })
Usta Shresthada15c612022-11-08 14:12:36 -0500683 ninjaDeps = append(ninjaDeps, symlinkForestDeps...)
Usta (Tsering) Shrestha93b2a9b2022-12-01 05:55:35 +0000684 })
Usta Shresthada15c612022-11-08 14:12:36 -0500685
686 writeDepFile(cmdlineArgs.SymlinkForestMarker, ctx.EventHandler, ninjaDeps)
687 touch(shared.JoinPath(topDir, cmdlineArgs.SymlinkForestMarker))
usta4f5d2c12022-10-28 23:32:01 -0400688 codegenMetrics := bp2build.ReadCodegenMetrics(metricsDir)
689 if codegenMetrics == nil {
690 m := bp2build.CreateCodegenMetrics()
691 codegenMetrics = &m
692 } else {
693 //TODO (usta) we cannot determine if we loaded a stale file, i.e. from an unrelated prior
694 //invocation of codegen. We should simply use a separate .pb file
695 }
Usta Shresthada15c612022-11-08 14:12:36 -0500696 codegenMetrics.SetSymlinkCount(symlinkCount)
697 codegenMetrics.SetMkDirCount(mkdirCount)
Paul Duffinb4e8d912022-11-04 13:35:50 +0000698 writeBp2BuildMetrics(codegenMetrics, ctx.EventHandler, metricsDir)
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800699 return cmdlineArgs.SymlinkForestMarker
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000700}
701
Sasha Smundak1845f422022-12-13 14:18:58 -0800702func excludedFromSymlinkForest(ctx *android.Context, verbose bool) []string {
703 excluded := bazelArtifacts()
704 if cmdlineArgs.OutDir[0] != '/' {
705 excluded = append(excluded, cmdlineArgs.OutDir)
706 }
707
708 // Find BUILD files in the srcDir which are not in the allowlist
709 // (android.Bp2BuildConversionAllowlist#ShouldKeepExistingBuildFileForDir)
710 // and return their paths so they can be left out of the Bazel workspace dir (i.e. ignored)
711 existingBazelFiles, err := getExistingBazelRelatedFiles(topDir)
712 maybeQuit(err, "Error determining existing Bazel-related files")
713
714 for _, path := range existingBazelFiles {
715 fullPath := shared.JoinPath(topDir, path)
716 fileInfo, err2 := os.Stat(fullPath)
717 if err2 != nil {
718 // Warn about error, but continue trying to check files
719 fmt.Fprintf(os.Stderr, "WARNING: Error accessing path '%s', err: %s\n", fullPath, err2)
720 continue
721 }
722 // Exclude only files named 'BUILD' or 'BUILD.bazel' and unless forcibly kept
723 if fileInfo.IsDir() ||
724 (fileInfo.Name() != "BUILD" && fileInfo.Name() != "BUILD.bazel") ||
725 ctx.Config().Bp2buildPackageConfig.ShouldKeepExistingBuildFileForDir(filepath.Dir(path)) {
726 // Don't ignore this existing build file
727 continue
728 }
729 if verbose {
730 fmt.Fprintf(os.Stderr, "Ignoring existing BUILD file: %s\n", path)
731 }
732 excluded = append(excluded, path)
733 }
734
735 // Temporarily exclude stuff to make `bazel build //external/...` (and `bazel build //frameworks/...`) work
736 excluded = append(excluded,
737 // FIXME: 'autotest_lib' is a symlink back to external/autotest, and this causes an infinite
738 // symlink expansion error for Bazel
739 "external/autotest/venv/autotest_lib",
740 "external/autotest/autotest_lib",
741 "external/autotest/client/autotest_lib/client",
742
743 // FIXME: The external/google-fruit/extras/bazel_root/third_party/fruit dir is poison
744 // It contains several symlinks back to real source dirs, and those source dirs contain
745 // BUILD files we want to ignore
746 "external/google-fruit/extras/bazel_root/third_party/fruit",
747
748 // FIXME: 'frameworks/compile/slang' has a filegroup error due to an escaping issue
749 "frameworks/compile/slang",
750
751 // FIXME(b/260809113): 'prebuilts/clang/host/linux-x86/clang-dev' is a tool-generated symlink
752 // directory that contains a BUILD file. The bazel files finder code doesn't traverse into symlink dirs,
753 // and hence is not aware of this BUILD file and exclude it accordingly during symlink forest generation
754 // when checking against keepExistingBuildFiles allowlist.
755 //
756 // This is necessary because globs in //prebuilts/clang/host/linux-x86/BUILD
757 // currently assume no subpackages (keepExistingBuildFile is not recursive for that directory).
758 //
759 // This is a bandaid until we the symlink forest logic can intelligently exclude BUILD files found in
760 // source symlink dirs according to the keepExistingBuildFile allowlist.
761 "prebuilts/clang/host/linux-x86/clang-dev",
762 )
763 return excluded
764}
765
Chris Parsons8152a942023-06-06 16:17:50 +0000766// buildTargetsByPackage parses Bazel BUILD.bazel and BUILD files under
767// the workspace, and returns a map containing names of Bazel targets defined in
768// these BUILD files.
769// For example, maps "//foo/bar" to ["baz", "qux"] if `//foo/bar:{baz,qux}` exist.
770func buildTargetsByPackage(ctx *android.Context) map[string][]string {
771 existingBazelFiles, err := getExistingBazelRelatedFiles(topDir)
772 maybeQuit(err, "Error determining existing Bazel-related files")
773
774 result := map[string][]string{}
775
776 // Search for instances of `name = "$NAME"` (with arbitrary spacing).
777 targetNameRegex := regexp.MustCompile(`(?m)^\s*name\s*=\s*\"([^\"]+)\"`)
778
779 for _, path := range existingBazelFiles {
780 if !ctx.Config().Bp2buildPackageConfig.ShouldKeepExistingBuildFileForDir(filepath.Dir(path)) {
781 continue
782 }
783 fullPath := shared.JoinPath(topDir, path)
784 sourceDir := filepath.Dir(path)
785 fileInfo, err := os.Stat(fullPath)
786 maybeQuit(err, "Error accessing Bazel file '%s'", fullPath)
787
788 if !fileInfo.IsDir() &&
789 (fileInfo.Name() == "BUILD" || fileInfo.Name() == "BUILD.bazel") {
790 // Process this BUILD file.
791 buildFileContent, err := os.ReadFile(fullPath)
792 maybeQuit(err, "Error reading Bazel file '%s'", fullPath)
793
794 matches := targetNameRegex.FindAllStringSubmatch(string(buildFileContent), -1)
795 for _, match := range matches {
796 result[sourceDir] = append(result[sourceDir], match[1])
797 }
798 }
799 }
800 return result
801}
802
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500803// Run Soong in the bp2build mode. This creates a standalone context that registers
804// an alternate pipeline of mutators and singletons specifically for generating
805// Bazel BUILD files instead of Ninja files.
Sasha Smundak1845f422022-12-13 14:18:58 -0800806func runBp2Build(ctx *android.Context, extraNinjaDeps []string, metricsDir string) string {
usta4f5d2c12022-10-28 23:32:01 -0400807 var codegenMetrics *bp2build.CodegenMetrics
Paul Duffinb4e8d912022-11-04 13:35:50 +0000808 ctx.EventHandler.Do("bp2build", func() {
Jingwen Cheneb76c432021-01-28 08:22:12 -0500809
Chris Parsons8152a942023-06-06 16:17:50 +0000810 ctx.EventHandler.Do("read_build", func() {
811 ctx.Config().SetBazelBuildFileTargets(buildTargetsByPackage(ctx))
812 })
813
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400814 // Propagate "allow misssing dependencies" bit. This is normally set in
Paul Duffinb4e8d912022-11-04 13:35:50 +0000815 // newContext(), but we create ctx without calling that method.
Sasha Smundak1845f422022-12-13 14:18:58 -0800816 ctx.SetAllowMissingDependencies(ctx.Config().AllowMissingDependencies())
817 ctx.SetNameInterface(newNameResolver(ctx.Config()))
Paul Duffinb4e8d912022-11-04 13:35:50 +0000818 ctx.RegisterForBazelConversion()
819 ctx.SetModuleListFile(cmdlineArgs.ModuleListFile)
Chris Parsons3a5c1702023-06-13 01:10:20 +0000820 // Skip cloning modules during bp2build's blueprint run. Some mutators set
821 // bp2build-related module values which should be preserved during codegen.
822 ctx.SkipCloneModulesAfterMutators = true
Jingwen Cheneb76c432021-01-28 08:22:12 -0500823
Usta Shresthaa117c582022-10-04 12:13:25 -0400824 var ninjaDeps []string
825 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
826
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400827 // Run the loading and analysis pipeline to prepare the graph of regular
828 // Modules parsed from Android.bp files, and the BazelTargetModules mapped
829 // from the regular Modules.
Paul Duffinb4e8d912022-11-04 13:35:50 +0000830 ctx.EventHandler.Do("bootstrap", func() {
Usta Shresthaa117c582022-10-04 12:13:25 -0400831 blueprintArgs := cmdlineArgs
Sasha Smundak1845f422022-12-13 14:18:58 -0800832 bootstrapDeps := bootstrap.RunBlueprint(blueprintArgs.Args,
833 bootstrap.StopBeforePrepareBuildActions, ctx.Context, ctx.Config())
Usta Shresthaa117c582022-10-04 12:13:25 -0400834 ninjaDeps = append(ninjaDeps, bootstrapDeps...)
835 })
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200836
Sasha Smundak1845f422022-12-13 14:18:58 -0800837 globListFiles := writeBuildGlobsNinjaFile(ctx)
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400838 ninjaDeps = append(ninjaDeps, globListFiles...)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200839
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400840 // Run the code-generation phase to convert BazelTargetModules to BUILD files
Usta Shresthaa117c582022-10-04 12:13:25 -0400841 // and print conversion codegenMetrics to the user.
Cole Faustb85d1a12022-11-08 18:14:01 -0800842 codegenContext := bp2build.NewCodegenContext(ctx.Config(), ctx, bp2build.Bp2Build, topDir)
Paul Duffinb4e8d912022-11-04 13:35:50 +0000843 ctx.EventHandler.Do("codegen", func() {
Usta Shresthaa117c582022-10-04 12:13:25 -0400844 codegenMetrics = bp2build.Codegen(codegenContext)
845 })
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200846
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400847 ninjaDeps = append(ninjaDeps, codegenContext.AdditionalNinjaDeps()...)
Chris Parsons715b08f2022-03-22 19:23:40 -0400848
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800849 writeDepFile(cmdlineArgs.Bp2buildMarker, ctx.EventHandler, ninjaDeps)
850 touch(shared.JoinPath(topDir, cmdlineArgs.Bp2buildMarker))
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400851 })
Chris Parsons715b08f2022-03-22 19:23:40 -0400852
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200853 // Only report metrics when in bp2build mode. The metrics aren't relevant
854 // for queryview, since that's a total repo-wide conversion and there's a
855 // 1:1 mapping for each module.
Sasha Smundak1845f422022-12-13 14:18:58 -0800856 if ctx.Config().IsEnvTrue("BP2BUILD_VERBOSE") {
Usta Shresthaa117c582022-10-04 12:13:25 -0400857 codegenMetrics.Print()
Sasha Smundak0fd93e02022-05-19 19:34:31 -0700858 }
Paul Duffinb4e8d912022-11-04 13:35:50 +0000859 writeBp2BuildMetrics(codegenMetrics, ctx.EventHandler, metricsDir)
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800860 return cmdlineArgs.Bp2buildMarker
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500861}
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500862
863// Write Bp2Build metrics into $LOG_DIR
Paul Duffinf4906562022-11-05 14:21:16 +0000864func writeBp2BuildMetrics(codegenMetrics *bp2build.CodegenMetrics, eventHandler *metrics.EventHandler, metricsDir string) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400865 for _, event := range eventHandler.CompletedEvents() {
usta4f5d2c12022-10-28 23:32:01 -0400866 codegenMetrics.AddEvent(&bp2build_metrics_proto.Event{
867 Name: event.Id,
868 StartTime: uint64(event.Start.UnixNano()),
869 RealTime: event.RuntimeNanoseconds(),
870 })
Chris Parsons715b08f2022-03-22 19:23:40 -0400871 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500872 if len(metricsDir) < 1 {
873 fmt.Fprintf(os.Stderr, "\nMissing required env var for generating bp2build metrics: LOG_DIR\n")
874 os.Exit(1)
875 }
Chris Parsons715b08f2022-03-22 19:23:40 -0400876 codegenMetrics.Write(metricsDir)
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500877}
MarkDacek0d5bca52022-10-10 20:07:48 +0000878
Sasha Smundak1845f422022-12-13 14:18:58 -0800879func readFileLines(path string) ([]string, error) {
880 data, err := os.ReadFile(path)
881 if err == nil {
882 return strings.Split(strings.TrimSpace(string(data)), "\n"), nil
MarkDacek0d5bca52022-10-10 20:07:48 +0000883 }
Sasha Smundak1845f422022-12-13 14:18:58 -0800884 return nil, err
885
886}
887func maybeQuit(err error, format string, args ...interface{}) {
888 if err == nil {
889 return
890 }
891 if format != "" {
892 fmt.Fprintln(os.Stderr, fmt.Sprintf(format, args...)+": "+err.Error())
893 } else {
894 fmt.Fprintln(os.Stderr, err)
895 }
896 os.Exit(1)
MarkDacek0d5bca52022-10-10 20:07:48 +0000897}