blob: e006c9d7e492137041e41df1c3eade83d1cc8990 [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"
Colin Cross3f40fa42015-01-30 17:27:36 -080019 "flag"
20 "fmt"
21 "os"
22 "path/filepath"
Jingwen Cheneb76c432021-01-28 08:22:12 -050023 "strings"
Lukacs T. Berkic99c9472021-03-24 10:50:06 +010024 "time"
Colin Cross3f40fa42015-01-30 17:27:36 -080025
Dan Willemsen66213a62021-09-21 17:50:30 -070026 "android/soong/android"
Jeongik Chae114e602023-03-19 00:12:39 +090027 "android/soong/android/allowlists"
Spandan Das5af0bd32022-09-28 20:43:08 +000028 "android/soong/bazel"
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020029 "android/soong/bp2build"
Lukacs T. Berki7690c092021-02-26 14:27:36 +010030 "android/soong/shared"
Chris Parsons715b08f2022-03-22 19:23:40 -040031 "android/soong/ui/metrics/bp2build_metrics_proto"
Lukacs T. Berkie571dc32021-08-25 14:14:13 +020032
Jeongik Chab745e2e2023-04-11 14:28:43 +090033 "github.com/google/blueprint"
Colin Cross70b40592015-03-23 12:57:34 -070034 "github.com/google/blueprint/bootstrap"
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +020035 "github.com/google/blueprint/deptools"
Chris Parsons715b08f2022-03-22 19:23:40 -040036 "github.com/google/blueprint/metrics"
Dan Willemsen66213a62021-09-21 17:50:30 -070037 androidProtobuf "google.golang.org/protobuf/android"
Colin Cross3f40fa42015-01-30 17:27:36 -080038)
39
Colin Crosse87040b2017-12-11 15:52:26 -080040var (
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020041 topDir string
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020042 availableEnvFile string
43 usedEnvFile string
44
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +020045 globFile string
46 globListDir string
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020047 delveListen string
48 delvePath string
49
Sasha Smundakaf5ca922022-12-12 21:23:34 -080050 cmdlineArgs android.CmdArgs
Colin Crosse87040b2017-12-11 15:52:26 -080051)
52
53func init() {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020054 // Flags that make sense in every mode
Lukacs T. Berki7690c092021-02-26 14:27:36 +010055 flag.StringVar(&topDir, "top", "", "Top directory of the Android source tree")
Sasha Smundakaf5ca922022-12-12 21:23:34 -080056 flag.StringVar(&cmdlineArgs.SoongOutDir, "soong_out", "", "Soong output directory (usually $TOP/out/soong)")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020057 flag.StringVar(&availableEnvFile, "available_env", "", "File containing available environment variables")
58 flag.StringVar(&usedEnvFile, "used_env", "", "File containing used environment variables")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020059 flag.StringVar(&globFile, "globFile", "build-globs.ninja", "the Ninja file of globs to output")
60 flag.StringVar(&globListDir, "globListDir", "", "the directory containing the glob list files")
Sasha Smundakaf5ca922022-12-12 21:23:34 -080061 flag.StringVar(&cmdlineArgs.OutDir, "out", "", "the ninja builddir directory")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020062 flag.StringVar(&cmdlineArgs.ModuleListFile, "l", "", "file that lists filepaths to parse")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020063
64 // Debug flags
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +010065 flag.StringVar(&delveListen, "delve_listen", "", "Delve port to listen on for debugging")
66 flag.StringVar(&delvePath, "delve_path", "", "Path to Delve. Only used if --delve_listen is set")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020067 flag.StringVar(&cmdlineArgs.Cpuprofile, "cpuprofile", "", "write cpu profile to file")
68 flag.StringVar(&cmdlineArgs.TraceFile, "trace", "", "write trace to file")
69 flag.StringVar(&cmdlineArgs.Memprofile, "memprofile", "", "write memory profile to file")
70 flag.BoolVar(&cmdlineArgs.NoGC, "nogc", false, "turn off GC for debugging")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020071
72 // Flags representing various modes soong_build can run in
Sasha Smundakaf5ca922022-12-12 21:23:34 -080073 flag.StringVar(&cmdlineArgs.ModuleGraphFile, "module_graph_file", "", "JSON module graph file to output")
74 flag.StringVar(&cmdlineArgs.ModuleActionsFile, "module_actions_file", "", "JSON file to output inputs/outputs of actions of modules")
75 flag.StringVar(&cmdlineArgs.DocFile, "soong_docs", "", "build documentation file to output")
76 flag.StringVar(&cmdlineArgs.BazelQueryViewDir, "bazel_queryview_dir", "", "path to the bazel queryview directory relative to --top")
77 flag.StringVar(&cmdlineArgs.BazelApiBp2buildDir, "bazel_api_bp2build_dir", "", "path to the bazel api_bp2build directory relative to --top")
78 flag.StringVar(&cmdlineArgs.Bp2buildMarker, "bp2build_marker", "", "If set, run bp2build, touch the specified marker file then exit")
79 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 +020080 flag.StringVar(&cmdlineArgs.OutFile, "o", "build.ninja", "the Ninja file to output")
Kiyoung Kima37d9ba2023-04-19 13:13:45 +090081 flag.StringVar(&cmdlineArgs.SoongVariables, "soong_variables", "soong.variables", "the file contains all build variables")
MarkDacekd06db5d2022-11-29 00:47:59 +000082 flag.StringVar(&cmdlineArgs.BazelForceEnabledModules, "bazel-force-enabled-modules", "", "additional modules to build with Bazel. Comma-delimited")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020083 flag.BoolVar(&cmdlineArgs.EmptyNinjaFile, "empty-ninja-file", false, "write out a 0-byte ninja file")
LaMont Jones52a72432023-03-09 18:19:35 +000084 flag.BoolVar(&cmdlineArgs.MultitreeBuild, "multitree-build", false, "this is a multitree build")
Chris Parsonsef615e52022-08-18 22:04:11 -040085 flag.BoolVar(&cmdlineArgs.BazelMode, "bazel-mode", false, "use bazel for analysis of certain modules")
Jingwen Chene647db82022-11-01 11:28:29 +000086 flag.BoolVar(&cmdlineArgs.BazelModeStaging, "bazel-mode-staging", false, "use bazel for analysis of certain near-ready modules")
Chris Parsonsef615e52022-08-18 22:04:11 -040087 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 -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
138 if ctx.Config().IsEnvTrue("SOONG_GENERATES_NINJA_HINT") {
139 writeNinjaHint(ctx)
140 }
Paul Duffin0c09a432022-11-05 15:28:04 +0000141 return cmdlineArgs.OutFile
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200142}
143
144// Run the code-generation phase to convert BazelTargetModules to BUILD files.
Sasha Smundak1845f422022-12-13 14:18:58 -0800145func runQueryView(queryviewDir, queryviewMarker string, ctx *android.Context) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400146 ctx.EventHandler.Begin("queryview")
147 defer ctx.EventHandler.End("queryview")
Cole Faustb85d1a12022-11-08 18:14:01 -0800148 codegenContext := bp2build.NewCodegenContext(ctx.Config(), ctx, bp2build.QueryView, topDir)
Spandan Das98cb8562023-03-09 23:05:47 +0000149 err := createBazelWorkspace(codegenContext, shared.JoinPath(topDir, queryviewDir), false)
Sasha Smundak1845f422022-12-13 14:18:58 -0800150 maybeQuit(err, "")
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200151 touch(shared.JoinPath(topDir, queryviewMarker))
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200152}
153
Spandan Das5af0bd32022-09-28 20:43:08 +0000154// Run the code-generation phase to convert API contributions to BUILD files.
155// Return marker file for the new synthetic workspace
Sasha Smundak1845f422022-12-13 14:18:58 -0800156func runApiBp2build(ctx *android.Context, extraNinjaDeps []string) string {
Spandan Das5af0bd32022-09-28 20:43:08 +0000157 ctx.EventHandler.Begin("api_bp2build")
158 defer ctx.EventHandler.End("api_bp2build")
Spandan Das255648c2023-01-11 03:05:24 +0000159 // api_bp2build does not run the typical pipeline of soong mutators.
160 // Hoevever, it still runs the defaults mutator which can create dependencies.
161 // These dependencies might not always exist (e.g. in tests)
162 ctx.SetAllowMissingDependencies(ctx.Config().AllowMissingDependencies())
Spandan Das5af0bd32022-09-28 20:43:08 +0000163 ctx.RegisterForApiBazelConversion()
164
165 // Register the Android.bp files in the tree
166 // Add them to the workspace's .d file
167 ctx.SetModuleListFile(cmdlineArgs.ModuleListFile)
168 if paths, err := ctx.ListModulePaths("."); err == nil {
169 extraNinjaDeps = append(extraNinjaDeps, paths...)
170 } else {
171 panic(err)
172 }
173
174 // Run the loading and analysis phase
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800175 ninjaDeps := bootstrap.RunBlueprint(cmdlineArgs.Args,
Spandan Das5af0bd32022-09-28 20:43:08 +0000176 bootstrap.StopBeforePrepareBuildActions,
177 ctx.Context,
Sasha Smundak1845f422022-12-13 14:18:58 -0800178 ctx.Config())
Spandan Das5af0bd32022-09-28 20:43:08 +0000179 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
180
181 // Add the globbed dependencies
Sasha Smundak1845f422022-12-13 14:18:58 -0800182 ninjaDeps = append(ninjaDeps, writeBuildGlobsNinjaFile(ctx)...)
Spandan Das5af0bd32022-09-28 20:43:08 +0000183
184 // Run codegen to generate BUILD files
Cole Faustb85d1a12022-11-08 18:14:01 -0800185 codegenContext := bp2build.NewCodegenContext(ctx.Config(), ctx, bp2build.ApiBp2build, topDir)
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800186 absoluteApiBp2buildDir := shared.JoinPath(topDir, cmdlineArgs.BazelApiBp2buildDir)
Spandan Das98cb8562023-03-09 23:05:47 +0000187 // Always generate bp2build_all_srcs filegroups in api_bp2build.
188 // This is necessary to force each Android.bp file to create an equivalent BUILD file
189 // and prevent package boundray issues.
190 // e.g.
191 // Source
192 // f/b/Android.bp
193 // java_library{
194 // name: "foo",
195 // api: "api/current.txt",
196 // }
197 //
198 // f/b/api/Android.bp <- will cause package boundary issues
199 //
200 // Gen
201 // f/b/BUILD
202 // java_contribution{
203 // name: "foo.contribution",
204 // api: "//f/b/api:current.txt",
205 // }
206 //
207 // If we don't generate f/b/api/BUILD, foo.contribution will be unbuildable.
208 err := createBazelWorkspace(codegenContext, absoluteApiBp2buildDir, true)
Sasha Smundak1845f422022-12-13 14:18:58 -0800209 maybeQuit(err, "")
Spandan Das5af0bd32022-09-28 20:43:08 +0000210 ninjaDeps = append(ninjaDeps, codegenContext.AdditionalNinjaDeps()...)
211
212 // Create soong_injection repository
Cole Faust9e384e22023-02-08 17:43:09 -0800213 soongInjectionFiles, err := bp2build.CreateSoongInjectionDirFiles(codegenContext, bp2build.CreateCodegenMetrics())
214 maybeQuit(err, "")
Sasha Smundak1845f422022-12-13 14:18:58 -0800215 absoluteSoongInjectionDir := shared.JoinPath(topDir, ctx.Config().SoongOutDir(), bazel.SoongInjectionDirName)
Spandan Das5af0bd32022-09-28 20:43:08 +0000216 for _, file := range soongInjectionFiles {
Spandan Das067210f2022-12-07 01:14:52 +0000217 // The API targets in api_bp2build workspace do not have any dependency on api_bp2build.
218 // But we need to create these files to prevent errors during Bazel analysis.
219 // These need to be created in Read-Write mode.
220 // This is because the subsequent step (bp2build in api domain analysis) creates them in Read-Write mode
221 // to allow users to edit/experiment in the synthetic workspace.
222 writeReadWriteFile(absoluteSoongInjectionDir, file)
Spandan Das5af0bd32022-09-28 20:43:08 +0000223 }
224
Sasha Smundak1845f422022-12-13 14:18:58 -0800225 workspace := shared.JoinPath(ctx.Config().SoongOutDir(), "api_bp2build")
Spandan Das5af0bd32022-09-28 20:43:08 +0000226 // Create the symlink forest
Usta Shresthada15c612022-11-08 14:12:36 -0500227 symlinkDeps, _, _ := bp2build.PlantSymlinkForest(
Sasha Smundak1845f422022-12-13 14:18:58 -0800228 ctx.Config().IsEnvTrue("BP2BUILD_VERBOSE"),
Spandan Das5af0bd32022-09-28 20:43:08 +0000229 topDir,
230 workspace,
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800231 cmdlineArgs.BazelApiBp2buildDir,
Sasha Smundak1845f422022-12-13 14:18:58 -0800232 apiBuildFileExcludes(ctx))
Spandan Das5af0bd32022-09-28 20:43:08 +0000233 ninjaDeps = append(ninjaDeps, symlinkDeps...)
234
235 workspaceMarkerFile := workspace + ".marker"
Paul Duffin780a1852022-11-05 10:17:12 +0000236 writeDepFile(workspaceMarkerFile, ctx.EventHandler, ninjaDeps)
Spandan Das5af0bd32022-09-28 20:43:08 +0000237 touch(shared.JoinPath(topDir, workspaceMarkerFile))
238 return workspaceMarkerFile
239}
240
241// With some exceptions, api_bp2build does not have any dependencies on the checked-in BUILD files
242// Exclude them from the generated workspace to prevent unrelated errors during the loading phase
Sasha Smundak1845f422022-12-13 14:18:58 -0800243func apiBuildFileExcludes(ctx *android.Context) []string {
244 ret := bazelArtifacts()
Spandan Das5af0bd32022-09-28 20:43:08 +0000245 srcs, err := getExistingBazelRelatedFiles(topDir)
Sasha Smundak1845f422022-12-13 14:18:58 -0800246 maybeQuit(err, "Error determining existing Bazel-related files")
Spandan Das5af0bd32022-09-28 20:43:08 +0000247 for _, src := range srcs {
Sasha Smundak1845f422022-12-13 14:18:58 -0800248 // Exclude all src BUILD files
Spandan Das5af0bd32022-09-28 20:43:08 +0000249 if src != "WORKSPACE" &&
250 src != "BUILD" &&
251 src != "BUILD.bazel" &&
252 !strings.HasPrefix(src, "build/bazel") &&
Spandan Das6b91a382022-11-30 02:17:06 +0000253 !strings.HasPrefix(src, "external/bazel-skylib") &&
Spandan Das5af0bd32022-09-28 20:43:08 +0000254 !strings.HasPrefix(src, "prebuilts/clang") {
255 ret = append(ret, src)
256 }
257 }
Sasha Smundak1845f422022-12-13 14:18:58 -0800258 // Android.bp files for api surfaces are mounted to out/, but out/ should not be a
259 // dep for api_bp2build. Otherwise, api_bp2build will be run every single time
260 ret = append(ret, ctx.Config().OutDir())
Spandan Das5af0bd32022-09-28 20:43:08 +0000261 return ret
262}
263
Jeongik Chae114e602023-03-19 00:12:39 +0900264func writeNinjaHint(ctx *android.Context) error {
Jeongik Cha73d49112023-05-04 18:16:11 +0900265 ctx.BeginEvent("ninja_hint")
266 defer ctx.EndEvent("ninja_hint")
Jeongik Chab745e2e2023-04-11 14:28:43 +0900267 // The current predictor focuses on reducing false negatives.
268 // If there are too many false positives (e.g., most modules are marked as positive),
269 // real long-running jobs cannot run early.
270 // Therefore, the model should be adjusted in this case.
271 // The model should also be adjusted if there are critical false negatives.
272 predicate := func(j *blueprint.JsonModule) (prioritized bool, weight int) {
273 prioritized = false
274 weight = 0
275 for prefix, w := range allowlists.HugeModuleTypePrefixMap {
276 if strings.HasPrefix(j.Type, prefix) {
277 prioritized = true
278 weight = w
279 return
280 }
Jeongik Chae114e602023-03-19 00:12:39 +0900281 }
Jeongik Chab745e2e2023-04-11 14:28:43 +0900282 dep_count := len(j.Deps)
283 src_count := 0
284 for _, a := range j.Module["Actions"].([]blueprint.JSONAction) {
285 src_count += len(a.Inputs)
286 }
287 input_size := dep_count + src_count
288
289 // Current threshold is an arbitrary value which only consider recall rather than accuracy.
290 if input_size > allowlists.INPUT_SIZE_THRESHOLD {
291 prioritized = true
292 weight += ((input_size) / allowlists.INPUT_SIZE_THRESHOLD) * allowlists.DEFAULT_PRIORITIZED_WEIGHT
293
294 // To prevent some modules from having too large a priority value.
295 if weight > allowlists.HIGH_PRIORITIZED_WEIGHT {
296 weight = allowlists.HIGH_PRIORITIZED_WEIGHT
297 }
298 }
299 return
300 }
301
302 outputsMap := ctx.Context.GetWeightedOutputsFromPredicate(predicate)
303 var outputBuilder strings.Builder
304 for output, weight := range outputsMap {
305 outputBuilder.WriteString(fmt.Sprintf("%s,%d\n", output, weight))
Jeongik Chae114e602023-03-19 00:12:39 +0900306 }
307 weightListFile := filepath.Join(topDir, ctx.Config().OutDir(), ".ninja_weight_list")
308
309 err := os.WriteFile(weightListFile, []byte(outputBuilder.String()), 0644)
310 if err != nil {
311 return fmt.Errorf("could not write ninja weight list file %s", err)
312 }
313 return nil
314}
315
Paul Duffin780a1852022-11-05 10:17:12 +0000316func writeMetrics(configuration android.Config, eventHandler *metrics.EventHandler, metricsDir string) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400317 if len(metricsDir) < 1 {
318 fmt.Fprintf(os.Stderr, "\nMissing required env var for generating soong metrics: LOG_DIR\n")
319 os.Exit(1)
320 }
321 metricsFile := filepath.Join(metricsDir, "soong_build_metrics.pb")
322 err := android.WriteMetrics(configuration, eventHandler, metricsFile)
Sasha Smundak1845f422022-12-13 14:18:58 -0800323 maybeQuit(err, "error writing soong_build metrics %s", metricsFile)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200324}
325
MarkDacekf47e1422023-04-19 16:47:36 +0000326// Errors out if any modules expected to be mixed_built were not, unless
MarkDacek6f6b9622023-05-02 16:28:55 +0000327// the modules did not exist.
MarkDacekf47e1422023-04-19 16:47:36 +0000328func checkForAllowlistIntegrityError(configuration android.Config, isStagingMode bool) error {
MarkDacek6f6b9622023-05-02 16:28:55 +0000329 modules := findMisconfiguredModules(configuration, isStagingMode)
MarkDacekf47e1422023-04-19 16:47:36 +0000330 if len(modules) == 0 {
331 return nil
332 }
333
334 return fmt.Errorf("Error: expected the following modules to be mixed_built: %s", modules)
335}
336
MarkDacek6f6b9622023-05-02 16:28:55 +0000337// Returns true if the given module has all of the following true:
338// 1. Is allowlisted to be built with Bazel.
339// 2. Has a variant which is *not* built with Bazel.
340// 3. Has no variant which is built with Bazel.
341//
342// This indicates the allowlisting of this variant had no effect.
343// TODO(b/280457637): Return true for nonexistent modules.
344func isAllowlistMisconfiguredForModule(module string, mixedBuildsEnabled map[string]struct{}, mixedBuildsDisabled map[string]struct{}) bool {
MarkDacek6f6b9622023-05-02 16:28:55 +0000345 _, enabled := mixedBuildsEnabled[module]
346
347 if enabled {
348 return false
349 }
350
351 _, disabled := mixedBuildsDisabled[module]
352 return disabled
353
354}
355
MarkDacekf47e1422023-04-19 16:47:36 +0000356// Returns the list of modules that should have been mixed_built (per the
357// allowlists and cmdline flags) but were not.
MarkDacek6f6b9622023-05-02 16:28:55 +0000358// Note: nonexistent modules are excluded from the list. See b/280457637
359func findMisconfiguredModules(configuration android.Config, isStagingMode bool) []string {
MarkDacekf47e1422023-04-19 16:47:36 +0000360 retval := []string{}
361 forceEnabledModules := configuration.BazelModulesForceEnabledByFlag()
362
363 mixedBuildsEnabled := configuration.GetMixedBuildsEnabledModules()
MarkDacek6f6b9622023-05-02 16:28:55 +0000364 mixedBuildsDisabled := configuration.GetMixedBuildsDisabledModules()
MarkDacekf47e1422023-04-19 16:47:36 +0000365 for _, module := range allowlists.ProdMixedBuildsEnabledList {
MarkDacek6f6b9622023-05-02 16:28:55 +0000366 if isAllowlistMisconfiguredForModule(module, mixedBuildsEnabled, mixedBuildsDisabled) {
MarkDacekf47e1422023-04-19 16:47:36 +0000367 retval = append(retval, module)
368 }
369 }
370
371 if isStagingMode {
372 for _, module := range allowlists.StagingMixedBuildsEnabledList {
MarkDacek6f6b9622023-05-02 16:28:55 +0000373 if isAllowlistMisconfiguredForModule(module, mixedBuildsEnabled, mixedBuildsDisabled) {
MarkDacekf47e1422023-04-19 16:47:36 +0000374 retval = append(retval, module)
375 }
376 }
377 }
378
379 for module, _ := range forceEnabledModules {
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 return retval
385}
386
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800387func writeJsonModuleGraphAndActions(ctx *android.Context, cmdArgs android.CmdArgs) {
388 graphFile, graphErr := os.Create(shared.JoinPath(topDir, cmdArgs.ModuleGraphFile))
Sasha Smundak1845f422022-12-13 14:18:58 -0800389 maybeQuit(graphErr, "graph err")
kgui67007242022-01-25 13:50:25 +0800390 defer graphFile.Close()
Sasha Smundak1845f422022-12-13 14:18:58 -0800391 actionsFile, actionsErr := os.Create(shared.JoinPath(topDir, cmdArgs.ModuleActionsFile))
392 maybeQuit(actionsErr, "actions err")
kgui67007242022-01-25 13:50:25 +0800393 defer actionsFile.Close()
394 ctx.Context.PrintJSONGraphAndActions(graphFile, actionsFile)
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200395}
396
Sasha Smundak1845f422022-12-13 14:18:58 -0800397func writeBuildGlobsNinjaFile(ctx *android.Context) []string {
Chris Parsons715b08f2022-03-22 19:23:40 -0400398 ctx.EventHandler.Begin("globs_ninja_file")
399 defer ctx.EventHandler.End("globs_ninja_file")
400
Sasha Smundak1845f422022-12-13 14:18:58 -0800401 globDir := bootstrap.GlobDirectory(ctx.Config().SoongOutDir(), globListDir)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200402 bootstrap.WriteBuildGlobsNinjaFile(&bootstrap.GlobSingleton{
Chris Parsons715b08f2022-03-22 19:23:40 -0400403 GlobLister: ctx.Globs,
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200404 GlobFile: globFile,
405 GlobDir: globDir,
Chris Parsons715b08f2022-03-22 19:23:40 -0400406 SrcDir: ctx.SrcDir(),
Sasha Smundak1845f422022-12-13 14:18:58 -0800407 }, ctx.Config())
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200408 return bootstrap.GlobFileListFiles(globDir)
409}
410
Paul Duffin780a1852022-11-05 10:17:12 +0000411func writeDepFile(outputFile string, eventHandler *metrics.EventHandler, ninjaDeps []string) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400412 eventHandler.Begin("ninja_deps")
413 defer eventHandler.End("ninja_deps")
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200414 depFile := shared.JoinPath(topDir, outputFile+".d")
415 err := deptools.WriteDepFile(depFile, outputFile, ninjaDeps)
Sasha Smundak1845f422022-12-13 14:18:58 -0800416 maybeQuit(err, "error writing depfile '%s'", depFile)
Paul Duffin0c09a432022-11-05 15:28:04 +0000417}
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200418
Paul Duffin0c09a432022-11-05 15:28:04 +0000419// runSoongOnlyBuild runs the standard Soong build in a number of different modes.
Sasha Smundak1845f422022-12-13 14:18:58 -0800420func runSoongOnlyBuild(ctx *android.Context, extraNinjaDeps []string) string {
Paul Duffin39eae8f2022-11-05 14:59:52 +0000421 ctx.EventHandler.Begin("soong_build")
422 defer ctx.EventHandler.End("soong_build")
423
Paul Duffin0c09a432022-11-05 15:28:04 +0000424 var stopBefore bootstrap.StopBefore
Sasha Smundak1845f422022-12-13 14:18:58 -0800425 switch ctx.Config().BuildMode {
426 case android.GenerateModuleGraph:
Paul Duffin0c09a432022-11-05 15:28:04 +0000427 stopBefore = bootstrap.StopBeforeWriteNinja
Usta Shrestha7fae6952022-12-21 11:46:28 -0500428 case android.GenerateQueryView, android.GenerateDocFile:
Paul Duffin0c09a432022-11-05 15:28:04 +0000429 stopBefore = bootstrap.StopBeforePrepareBuildActions
Sasha Smundak1845f422022-12-13 14:18:58 -0800430 default:
Paul Duffin0c09a432022-11-05 15:28:04 +0000431 stopBefore = bootstrap.DoEverything
432 }
433
Sasha Smundak1845f422022-12-13 14:18:58 -0800434 ninjaDeps := bootstrap.RunBlueprint(cmdlineArgs.Args, stopBefore, ctx.Context, ctx.Config())
Paul Duffin0c09a432022-11-05 15:28:04 +0000435 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
436
Sasha Smundak1845f422022-12-13 14:18:58 -0800437 globListFiles := writeBuildGlobsNinjaFile(ctx)
Paul Duffin0c09a432022-11-05 15:28:04 +0000438 ninjaDeps = append(ninjaDeps, globListFiles...)
439
440 // Convert the Soong module graph into Bazel BUILD files.
Sasha Smundak1845f422022-12-13 14:18:58 -0800441 switch ctx.Config().BuildMode {
442 case android.GenerateQueryView:
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800443 queryviewMarkerFile := cmdlineArgs.BazelQueryViewDir + ".marker"
Sasha Smundak1845f422022-12-13 14:18:58 -0800444 runQueryView(cmdlineArgs.BazelQueryViewDir, queryviewMarkerFile, ctx)
Paul Duffin0c09a432022-11-05 15:28:04 +0000445 writeDepFile(queryviewMarkerFile, ctx.EventHandler, ninjaDeps)
446 return queryviewMarkerFile
Sasha Smundak1845f422022-12-13 14:18:58 -0800447 case android.GenerateModuleGraph:
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800448 writeJsonModuleGraphAndActions(ctx, cmdlineArgs)
449 writeDepFile(cmdlineArgs.ModuleGraphFile, ctx.EventHandler, ninjaDeps)
450 return cmdlineArgs.ModuleGraphFile
Sasha Smundak1845f422022-12-13 14:18:58 -0800451 case android.GenerateDocFile:
Paul Duffin0c09a432022-11-05 15:28:04 +0000452 // TODO: we could make writeDocs() return the list of documentation files
453 // written and add them to the .d file. Then soong_docs would be re-run
454 // whenever one is deleted.
Sasha Smundak1845f422022-12-13 14:18:58 -0800455 err := writeDocs(ctx, shared.JoinPath(topDir, cmdlineArgs.DocFile))
456 maybeQuit(err, "error building Soong documentation")
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800457 writeDepFile(cmdlineArgs.DocFile, ctx.EventHandler, ninjaDeps)
458 return cmdlineArgs.DocFile
Sasha Smundak1845f422022-12-13 14:18:58 -0800459 default:
Paul Duffin0c09a432022-11-05 15:28:04 +0000460 // The actual output (build.ninja) was written in the RunBlueprint() call
461 // above
462 writeDepFile(cmdlineArgs.OutFile, ctx.EventHandler, ninjaDeps)
Jeongik Cha591366d2023-05-08 11:32:52 +0900463 if ctx.Config().IsEnvTrue("SOONG_GENERATES_NINJA_HINT") {
464 writeNinjaHint(ctx)
465 }
Paul Duffinb713ddf2022-11-05 16:14:30 +0000466 return cmdlineArgs.OutFile
Paul Duffin0c09a432022-11-05 15:28:04 +0000467 }
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200468}
469
470// soong_ui dumps the available environment variables to
471// soong.environment.available . Then soong_build itself is run with an empty
472// environment so that the only way environment variables can be accessed is
473// using Config, which tracks access to them.
474
475// At the end of the build, a file called soong.environment.used is written
476// containing the current value of all used environment variables. The next
477// time soong_ui is run, it checks whether any environment variables that was
478// used had changed and if so, it deletes soong.environment.used to cause a
479// rebuild.
480//
481// The dependency of build.ninja on soong.environment.used is declared in
482// build.ninja.d
483func parseAvailableEnv() map[string]string {
484 if availableEnvFile == "" {
485 fmt.Fprintf(os.Stderr, "--available_env not set\n")
486 os.Exit(1)
487 }
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200488 result, err := shared.EnvFromFile(shared.JoinPath(topDir, availableEnvFile))
Sasha Smundak1845f422022-12-13 14:18:58 -0800489 maybeQuit(err, "error reading available environment file '%s'", availableEnvFile)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200490 return result
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200491}
492
Colin Cross3f40fa42015-01-30 17:27:36 -0800493func main() {
494 flag.Parse()
495
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100496 shared.ReexecWithDelveMaybe(delveListen, delvePath)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100497 android.InitSandbox(topDir)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100498
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200499 availableEnv := parseAvailableEnv()
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800500 configuration, err := android.NewConfig(cmdlineArgs, availableEnv)
Sasha Smundak1845f422022-12-13 14:18:58 -0800501 maybeQuit(err, "")
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100502 if configuration.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
503 configuration.SetAllowMissingDependencies()
504 }
505
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800506 extraNinjaDeps := []string{configuration.ProductVariablesFileName, usedEnvFile}
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100507 if shared.IsDebugging() {
Colin Crossaa812d12019-06-19 13:33:24 -0700508 // Add a non-existent file to the dependencies so that soong_build will rerun when the debugger is
509 // enabled even if it completed successfully.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200510 extraNinjaDeps = append(extraNinjaDeps, filepath.Join(configuration.SoongOutDir(), "always_rerun_for_delve"))
Colin Crossaa812d12019-06-19 13:33:24 -0700511 }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500512
Dan Willemsenccf36aa2022-04-20 23:11:43 -0700513 // Bypass configuration.Getenv, as LOG_DIR does not need to be dependency tracked. By definition, it will
514 // change between every CI build, so tracking it would require re-running Soong for every build.
Sasha Smundak1845f422022-12-13 14:18:58 -0800515 metricsDir := availableEnv["LOG_DIR"]
Dan Willemsenccf36aa2022-04-20 23:11:43 -0700516
Joe Onorato2e5e4012022-06-07 17:16:08 -0700517 ctx := newContext(configuration)
Joe Onorato2e5e4012022-06-07 17:16:08 -0700518
Sasha Smundak1845f422022-12-13 14:18:58 -0800519 var finalOutputFile string
Joe Onorato2e5e4012022-06-07 17:16:08 -0700520
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900521 writeSymlink := false
522
Sasha Smundak1845f422022-12-13 14:18:58 -0800523 // Run Soong for a specific activity, like bp2build, queryview
524 // or the actual Soong build for the build.ninja file.
525 switch configuration.BuildMode {
526 case android.SymlinkForest:
527 finalOutputFile = runSymlinkForestCreation(ctx, extraNinjaDeps, metricsDir)
528 case android.Bp2build:
529 // Run the alternate pipeline of bp2build mutators and singleton to convert
530 // Blueprint to BUILD files before everything else.
531 finalOutputFile = runBp2Build(ctx, extraNinjaDeps, metricsDir)
532 case android.ApiBp2build:
533 finalOutputFile = runApiBp2build(ctx, extraNinjaDeps)
534 writeMetrics(configuration, ctx.EventHandler, metricsDir)
535 default:
536 ctx.Register()
MarkDacekf47e1422023-04-19 16:47:36 +0000537 isMixedBuildsEnabled := configuration.IsMixedBuildsEnabled()
538 if isMixedBuildsEnabled {
Sasha Smundak1845f422022-12-13 14:18:58 -0800539 finalOutputFile = runMixedModeBuild(ctx, extraNinjaDeps)
MarkDacekf47e1422023-04-19 16:47:36 +0000540 if cmdlineArgs.EnsureAllowlistIntegrity {
541 if err := checkForAllowlistIntegrityError(configuration, cmdlineArgs.BazelModeStaging); err != nil {
542 maybeQuit(err, "")
543 }
544 }
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900545 writeSymlink = true
Sasha Smundak1845f422022-12-13 14:18:58 -0800546 } else {
547 finalOutputFile = runSoongOnlyBuild(ctx, extraNinjaDeps)
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900548
549 if configuration.BuildMode == android.AnalysisNoBazel {
550 writeSymlink = true
551 }
Sasha Smundak1845f422022-12-13 14:18:58 -0800552 }
553 writeMetrics(configuration, ctx.EventHandler, metricsDir)
554 }
Chris Parsonsa3ae0072023-05-10 21:10:08 +0000555 writeUsedEnvironmentFile(configuration)
556
557 // Touch the output file so that it's the newest file created by soong_build.
558 // This is necessary because, if soong_build generated any files which
559 // are ninja inputs to the main output file, then ninja would superfluously
560 // rebuild this output file on the next build invocation.
561 touch(shared.JoinPath(topDir, finalOutputFile))
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900562
563 // TODO(b/277029044): Remove this function once build.<product>.ninja lands
564 if writeSymlink {
565 writeBuildNinjaSymlink(configuration, finalOutputFile)
566 }
567}
568
569// TODO(b/277029044): Remove this function once build.<product>.ninja lands
570func writeBuildNinjaSymlink(config android.Config, source string) {
571 targetPath := shared.JoinPath(topDir, config.SoongOutDir(), "build.ninja")
572 sourcePath := shared.JoinPath(topDir, source)
573
574 if targetPath == sourcePath {
575 return
576 }
577
578 os.Remove(targetPath)
579 os.Symlink(sourcePath, targetPath)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100580}
581
Chris Parsonsa3ae0072023-05-10 21:10:08 +0000582func writeUsedEnvironmentFile(configuration android.Config) {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200583 if usedEnvFile == "" {
584 return
585 }
586
587 path := shared.JoinPath(topDir, usedEnvFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100588 data, err := shared.EnvFileContents(configuration.EnvDeps())
Sasha Smundak1845f422022-12-13 14:18:58 -0800589 maybeQuit(err, "error writing used environment file '%s'\n", usedEnvFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100590
Usta Shrestha2ba28a32022-10-24 11:33:09 -0400591 if preexistingData, err := os.ReadFile(path); err != nil {
592 if !os.IsNotExist(err) {
Sasha Smundak1845f422022-12-13 14:18:58 -0800593 maybeQuit(err, "error reading used environment file '%s'", usedEnvFile)
Usta Shrestha2ba28a32022-10-24 11:33:09 -0400594 }
595 } else if bytes.Equal(preexistingData, data) {
596 // used environment file is unchanged
597 return
598 }
Sasha Smundak1845f422022-12-13 14:18:58 -0800599 err = os.WriteFile(path, data, 0666)
600 maybeQuit(err, "error writing used environment file '%s'", usedEnvFile)
Colin Cross3f40fa42015-01-30 17:27:36 -0800601}
Jingwen Chen5ba7e472020-07-15 10:06:41 +0000602
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200603func touch(path string) {
604 f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
Sasha Smundak1845f422022-12-13 14:18:58 -0800605 maybeQuit(err, "Error touching '%s'", path)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200606 err = f.Close()
Sasha Smundak1845f422022-12-13 14:18:58 -0800607 maybeQuit(err, "Error touching '%s'", path)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200608
609 currentTime := time.Now().Local()
610 err = os.Chtimes(path, currentTime, currentTime)
Sasha Smundak1845f422022-12-13 14:18:58 -0800611 maybeQuit(err, "error touching '%s'", path)
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400612}
613
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400614// Read the bazel.list file that the Soong Finder already dumped earlier (hopefully)
615// It contains the locations of BUILD files, BUILD.bazel files, etc. in the source dir
616func getExistingBazelRelatedFiles(topDir string) ([]string, error) {
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200617 bazelFinderFile := filepath.Join(filepath.Dir(cmdlineArgs.ModuleListFile), "bazel.list")
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400618 if !filepath.IsAbs(bazelFinderFile) {
619 // Assume this was a relative path under topDir
620 bazelFinderFile = filepath.Join(topDir, bazelFinderFile)
621 }
Sasha Smundak1845f422022-12-13 14:18:58 -0800622 return readFileLines(bazelFinderFile)
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400623}
624
Spandan Das5af0bd32022-09-28 20:43:08 +0000625func bazelArtifacts() []string {
626 return []string{
627 "bazel-bin",
628 "bazel-genfiles",
629 "bazel-out",
630 "bazel-testlogs",
Usta (Tsering) Shresthac4c07b12022-11-08 18:31:14 -0500631 "bazel-workspace",
Spandan Das5af0bd32022-09-28 20:43:08 +0000632 "bazel-" + filepath.Base(topDir),
633 }
634}
635
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000636// This could in theory easily be separated into a binary that generically
637// merges two directories into a symlink tree. The main obstacle is that this
638// function currently depends on both Bazel-specific knowledge (the existence
639// of bazel-* symlinks) and configuration (the set of BUILD.bazel files that
640// should and should not be kept)
641//
642// Ideally, bp2build would write a file that contains instructions to the
643// symlink tree creation binary. Then the latter would not need to depend on
644// the very heavy-weight machinery of soong_build .
Sasha Smundak1845f422022-12-13 14:18:58 -0800645func runSymlinkForestCreation(ctx *android.Context, extraNinjaDeps []string, metricsDir string) string {
Usta Shresthada15c612022-11-08 14:12:36 -0500646 var ninjaDeps []string
647 var mkdirCount, symlinkCount uint64
648
Paul Duffinb4e8d912022-11-04 13:35:50 +0000649 ctx.EventHandler.Do("symlink_forest", func() {
Usta (Tsering) Shrestha93b2a9b2022-12-01 05:55:35 +0000650 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Sasha Smundak1845f422022-12-13 14:18:58 -0800651 verbose := ctx.Config().IsEnvTrue("BP2BUILD_VERBOSE")
Usta (Tsering) Shrestha93b2a9b2022-12-01 05:55:35 +0000652
653 // PlantSymlinkForest() returns all the directories that were readdir()'ed.
654 // Such a directory SHOULD be added to `ninjaDeps` so that a child directory
655 // or file created/deleted under it would trigger an update of the symlink forest.
Sasha Smundak1845f422022-12-13 14:18:58 -0800656 generatedRoot := shared.JoinPath(ctx.Config().SoongOutDir(), "bp2build")
657 workspaceRoot := shared.JoinPath(ctx.Config().SoongOutDir(), "workspace")
Usta Shresthada15c612022-11-08 14:12:36 -0500658 var symlinkForestDeps []string
Usta (Tsering) Shrestha93b2a9b2022-12-01 05:55:35 +0000659 ctx.EventHandler.Do("plant", func() {
Usta Shresthada15c612022-11-08 14:12:36 -0500660 symlinkForestDeps, mkdirCount, symlinkCount = bp2build.PlantSymlinkForest(
Sasha Smundak1845f422022-12-13 14:18:58 -0800661 verbose, topDir, workspaceRoot, generatedRoot, excludedFromSymlinkForest(ctx, verbose))
Usta (Tsering) Shrestha93b2a9b2022-12-01 05:55:35 +0000662 })
Usta Shresthada15c612022-11-08 14:12:36 -0500663 ninjaDeps = append(ninjaDeps, symlinkForestDeps...)
Usta (Tsering) Shrestha93b2a9b2022-12-01 05:55:35 +0000664 })
Usta Shresthada15c612022-11-08 14:12:36 -0500665
666 writeDepFile(cmdlineArgs.SymlinkForestMarker, ctx.EventHandler, ninjaDeps)
667 touch(shared.JoinPath(topDir, cmdlineArgs.SymlinkForestMarker))
usta4f5d2c12022-10-28 23:32:01 -0400668 codegenMetrics := bp2build.ReadCodegenMetrics(metricsDir)
669 if codegenMetrics == nil {
670 m := bp2build.CreateCodegenMetrics()
671 codegenMetrics = &m
672 } else {
673 //TODO (usta) we cannot determine if we loaded a stale file, i.e. from an unrelated prior
674 //invocation of codegen. We should simply use a separate .pb file
675 }
Usta Shresthada15c612022-11-08 14:12:36 -0500676 codegenMetrics.SetSymlinkCount(symlinkCount)
677 codegenMetrics.SetMkDirCount(mkdirCount)
Paul Duffinb4e8d912022-11-04 13:35:50 +0000678 writeBp2BuildMetrics(codegenMetrics, ctx.EventHandler, metricsDir)
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800679 return cmdlineArgs.SymlinkForestMarker
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000680}
681
Sasha Smundak1845f422022-12-13 14:18:58 -0800682func excludedFromSymlinkForest(ctx *android.Context, verbose bool) []string {
683 excluded := bazelArtifacts()
684 if cmdlineArgs.OutDir[0] != '/' {
685 excluded = append(excluded, cmdlineArgs.OutDir)
686 }
687
688 // Find BUILD files in the srcDir which are not in the allowlist
689 // (android.Bp2BuildConversionAllowlist#ShouldKeepExistingBuildFileForDir)
690 // and return their paths so they can be left out of the Bazel workspace dir (i.e. ignored)
691 existingBazelFiles, err := getExistingBazelRelatedFiles(topDir)
692 maybeQuit(err, "Error determining existing Bazel-related files")
693
694 for _, path := range existingBazelFiles {
695 fullPath := shared.JoinPath(topDir, path)
696 fileInfo, err2 := os.Stat(fullPath)
697 if err2 != nil {
698 // Warn about error, but continue trying to check files
699 fmt.Fprintf(os.Stderr, "WARNING: Error accessing path '%s', err: %s\n", fullPath, err2)
700 continue
701 }
702 // Exclude only files named 'BUILD' or 'BUILD.bazel' and unless forcibly kept
703 if fileInfo.IsDir() ||
704 (fileInfo.Name() != "BUILD" && fileInfo.Name() != "BUILD.bazel") ||
705 ctx.Config().Bp2buildPackageConfig.ShouldKeepExistingBuildFileForDir(filepath.Dir(path)) {
706 // Don't ignore this existing build file
707 continue
708 }
709 if verbose {
710 fmt.Fprintf(os.Stderr, "Ignoring existing BUILD file: %s\n", path)
711 }
712 excluded = append(excluded, path)
713 }
714
715 // Temporarily exclude stuff to make `bazel build //external/...` (and `bazel build //frameworks/...`) work
716 excluded = append(excluded,
717 // FIXME: 'autotest_lib' is a symlink back to external/autotest, and this causes an infinite
718 // symlink expansion error for Bazel
719 "external/autotest/venv/autotest_lib",
720 "external/autotest/autotest_lib",
721 "external/autotest/client/autotest_lib/client",
722
723 // FIXME: The external/google-fruit/extras/bazel_root/third_party/fruit dir is poison
724 // It contains several symlinks back to real source dirs, and those source dirs contain
725 // BUILD files we want to ignore
726 "external/google-fruit/extras/bazel_root/third_party/fruit",
727
728 // FIXME: 'frameworks/compile/slang' has a filegroup error due to an escaping issue
729 "frameworks/compile/slang",
730
731 // FIXME(b/260809113): 'prebuilts/clang/host/linux-x86/clang-dev' is a tool-generated symlink
732 // directory that contains a BUILD file. The bazel files finder code doesn't traverse into symlink dirs,
733 // and hence is not aware of this BUILD file and exclude it accordingly during symlink forest generation
734 // when checking against keepExistingBuildFiles allowlist.
735 //
736 // This is necessary because globs in //prebuilts/clang/host/linux-x86/BUILD
737 // currently assume no subpackages (keepExistingBuildFile is not recursive for that directory).
738 //
739 // This is a bandaid until we the symlink forest logic can intelligently exclude BUILD files found in
740 // source symlink dirs according to the keepExistingBuildFile allowlist.
741 "prebuilts/clang/host/linux-x86/clang-dev",
742 )
743 return excluded
744}
745
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500746// Run Soong in the bp2build mode. This creates a standalone context that registers
747// an alternate pipeline of mutators and singletons specifically for generating
748// Bazel BUILD files instead of Ninja files.
Sasha Smundak1845f422022-12-13 14:18:58 -0800749func runBp2Build(ctx *android.Context, extraNinjaDeps []string, metricsDir string) string {
usta4f5d2c12022-10-28 23:32:01 -0400750 var codegenMetrics *bp2build.CodegenMetrics
Paul Duffinb4e8d912022-11-04 13:35:50 +0000751 ctx.EventHandler.Do("bp2build", func() {
Jingwen Cheneb76c432021-01-28 08:22:12 -0500752
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400753 // Propagate "allow misssing dependencies" bit. This is normally set in
Paul Duffinb4e8d912022-11-04 13:35:50 +0000754 // newContext(), but we create ctx without calling that method.
Sasha Smundak1845f422022-12-13 14:18:58 -0800755 ctx.SetAllowMissingDependencies(ctx.Config().AllowMissingDependencies())
756 ctx.SetNameInterface(newNameResolver(ctx.Config()))
Paul Duffinb4e8d912022-11-04 13:35:50 +0000757 ctx.RegisterForBazelConversion()
758 ctx.SetModuleListFile(cmdlineArgs.ModuleListFile)
Jingwen Cheneb76c432021-01-28 08:22:12 -0500759
Usta Shresthaa117c582022-10-04 12:13:25 -0400760 var ninjaDeps []string
761 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
762
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400763 // Run the loading and analysis pipeline to prepare the graph of regular
764 // Modules parsed from Android.bp files, and the BazelTargetModules mapped
765 // from the regular Modules.
Paul Duffinb4e8d912022-11-04 13:35:50 +0000766 ctx.EventHandler.Do("bootstrap", func() {
Usta Shresthaa117c582022-10-04 12:13:25 -0400767 blueprintArgs := cmdlineArgs
Sasha Smundak1845f422022-12-13 14:18:58 -0800768 bootstrapDeps := bootstrap.RunBlueprint(blueprintArgs.Args,
769 bootstrap.StopBeforePrepareBuildActions, ctx.Context, ctx.Config())
Usta Shresthaa117c582022-10-04 12:13:25 -0400770 ninjaDeps = append(ninjaDeps, bootstrapDeps...)
771 })
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200772
Sasha Smundak1845f422022-12-13 14:18:58 -0800773 globListFiles := writeBuildGlobsNinjaFile(ctx)
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400774 ninjaDeps = append(ninjaDeps, globListFiles...)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200775
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400776 // Run the code-generation phase to convert BazelTargetModules to BUILD files
Usta Shresthaa117c582022-10-04 12:13:25 -0400777 // and print conversion codegenMetrics to the user.
Cole Faustb85d1a12022-11-08 18:14:01 -0800778 codegenContext := bp2build.NewCodegenContext(ctx.Config(), ctx, bp2build.Bp2Build, topDir)
Paul Duffinb4e8d912022-11-04 13:35:50 +0000779 ctx.EventHandler.Do("codegen", func() {
Usta Shresthaa117c582022-10-04 12:13:25 -0400780 codegenMetrics = bp2build.Codegen(codegenContext)
781 })
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200782
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400783 ninjaDeps = append(ninjaDeps, codegenContext.AdditionalNinjaDeps()...)
Chris Parsons715b08f2022-03-22 19:23:40 -0400784
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800785 writeDepFile(cmdlineArgs.Bp2buildMarker, ctx.EventHandler, ninjaDeps)
786 touch(shared.JoinPath(topDir, cmdlineArgs.Bp2buildMarker))
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400787 })
Chris Parsons715b08f2022-03-22 19:23:40 -0400788
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200789 // Only report metrics when in bp2build mode. The metrics aren't relevant
790 // for queryview, since that's a total repo-wide conversion and there's a
791 // 1:1 mapping for each module.
Sasha Smundak1845f422022-12-13 14:18:58 -0800792 if ctx.Config().IsEnvTrue("BP2BUILD_VERBOSE") {
Usta Shresthaa117c582022-10-04 12:13:25 -0400793 codegenMetrics.Print()
Sasha Smundak0fd93e02022-05-19 19:34:31 -0700794 }
Paul Duffinb4e8d912022-11-04 13:35:50 +0000795 writeBp2BuildMetrics(codegenMetrics, ctx.EventHandler, metricsDir)
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800796 return cmdlineArgs.Bp2buildMarker
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500797}
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500798
799// Write Bp2Build metrics into $LOG_DIR
Paul Duffinf4906562022-11-05 14:21:16 +0000800func writeBp2BuildMetrics(codegenMetrics *bp2build.CodegenMetrics, eventHandler *metrics.EventHandler, metricsDir string) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400801 for _, event := range eventHandler.CompletedEvents() {
usta4f5d2c12022-10-28 23:32:01 -0400802 codegenMetrics.AddEvent(&bp2build_metrics_proto.Event{
803 Name: event.Id,
804 StartTime: uint64(event.Start.UnixNano()),
805 RealTime: event.RuntimeNanoseconds(),
806 })
Chris Parsons715b08f2022-03-22 19:23:40 -0400807 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500808 if len(metricsDir) < 1 {
809 fmt.Fprintf(os.Stderr, "\nMissing required env var for generating bp2build metrics: LOG_DIR\n")
810 os.Exit(1)
811 }
Chris Parsons715b08f2022-03-22 19:23:40 -0400812 codegenMetrics.Write(metricsDir)
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500813}
MarkDacek0d5bca52022-10-10 20:07:48 +0000814
Sasha Smundak1845f422022-12-13 14:18:58 -0800815func readFileLines(path string) ([]string, error) {
816 data, err := os.ReadFile(path)
817 if err == nil {
818 return strings.Split(strings.TrimSpace(string(data)), "\n"), nil
MarkDacek0d5bca52022-10-10 20:07:48 +0000819 }
Sasha Smundak1845f422022-12-13 14:18:58 -0800820 return nil, err
821
822}
823func maybeQuit(err error, format string, args ...interface{}) {
824 if err == nil {
825 return
826 }
827 if format != "" {
828 fmt.Fprintln(os.Stderr, fmt.Sprintf(format, args...)+": "+err.Error())
829 } else {
830 fmt.Fprintln(os.Stderr, err)
831 }
832 os.Exit(1)
MarkDacek0d5bca52022-10-10 20:07:48 +0000833}