blob: 53e0e55c48a22af681373cf32149251398f15952 [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
Colin Cross70b40592015-03-23 12:57:34 -070033 "github.com/google/blueprint/bootstrap"
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +020034 "github.com/google/blueprint/deptools"
Chris Parsons715b08f2022-03-22 19:23:40 -040035 "github.com/google/blueprint/metrics"
Dan Willemsen66213a62021-09-21 17:50:30 -070036 androidProtobuf "google.golang.org/protobuf/android"
Colin Cross3f40fa42015-01-30 17:27:36 -080037)
38
Colin Crosse87040b2017-12-11 15:52:26 -080039var (
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020040 topDir string
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020041 availableEnvFile string
42 usedEnvFile string
43
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +020044 globFile string
45 globListDir string
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020046 delveListen string
47 delvePath string
48
Sasha Smundakaf5ca922022-12-12 21:23:34 -080049 cmdlineArgs android.CmdArgs
Colin Crosse87040b2017-12-11 15:52:26 -080050)
51
52func init() {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020053 // Flags that make sense in every mode
Lukacs T. Berki7690c092021-02-26 14:27:36 +010054 flag.StringVar(&topDir, "top", "", "Top directory of the Android source tree")
Sasha Smundakaf5ca922022-12-12 21:23:34 -080055 flag.StringVar(&cmdlineArgs.SoongOutDir, "soong_out", "", "Soong output directory (usually $TOP/out/soong)")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020056 flag.StringVar(&availableEnvFile, "available_env", "", "File containing available environment variables")
57 flag.StringVar(&usedEnvFile, "used_env", "", "File containing used environment variables")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020058 flag.StringVar(&globFile, "globFile", "build-globs.ninja", "the Ninja file of globs to output")
59 flag.StringVar(&globListDir, "globListDir", "", "the directory containing the glob list files")
Sasha Smundakaf5ca922022-12-12 21:23:34 -080060 flag.StringVar(&cmdlineArgs.OutDir, "out", "", "the ninja builddir directory")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020061 flag.StringVar(&cmdlineArgs.ModuleListFile, "l", "", "file that lists filepaths to parse")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020062
63 // Debug flags
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +010064 flag.StringVar(&delveListen, "delve_listen", "", "Delve port to listen on for debugging")
65 flag.StringVar(&delvePath, "delve_path", "", "Path to Delve. Only used if --delve_listen is set")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020066 flag.StringVar(&cmdlineArgs.Cpuprofile, "cpuprofile", "", "write cpu profile to file")
67 flag.StringVar(&cmdlineArgs.TraceFile, "trace", "", "write trace to file")
68 flag.StringVar(&cmdlineArgs.Memprofile, "memprofile", "", "write memory profile to file")
69 flag.BoolVar(&cmdlineArgs.NoGC, "nogc", false, "turn off GC for debugging")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020070
71 // Flags representing various modes soong_build can run in
Sasha Smundakaf5ca922022-12-12 21:23:34 -080072 flag.StringVar(&cmdlineArgs.ModuleGraphFile, "module_graph_file", "", "JSON module graph file to output")
73 flag.StringVar(&cmdlineArgs.ModuleActionsFile, "module_actions_file", "", "JSON file to output inputs/outputs of actions of modules")
74 flag.StringVar(&cmdlineArgs.DocFile, "soong_docs", "", "build documentation file to output")
75 flag.StringVar(&cmdlineArgs.BazelQueryViewDir, "bazel_queryview_dir", "", "path to the bazel queryview directory relative to --top")
76 flag.StringVar(&cmdlineArgs.BazelApiBp2buildDir, "bazel_api_bp2build_dir", "", "path to the bazel api_bp2build directory relative to --top")
77 flag.StringVar(&cmdlineArgs.Bp2buildMarker, "bp2build_marker", "", "If set, run bp2build, touch the specified marker file then exit")
78 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 +020079 flag.StringVar(&cmdlineArgs.OutFile, "o", "build.ninja", "the Ninja file to output")
MarkDacekd06db5d2022-11-29 00:47:59 +000080 flag.StringVar(&cmdlineArgs.BazelForceEnabledModules, "bazel-force-enabled-modules", "", "additional modules to build with Bazel. Comma-delimited")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020081 flag.BoolVar(&cmdlineArgs.EmptyNinjaFile, "empty-ninja-file", false, "write out a 0-byte ninja file")
LaMont Jones52a72432023-03-09 18:19:35 +000082 flag.BoolVar(&cmdlineArgs.MultitreeBuild, "multitree-build", false, "this is a multitree build")
Chris Parsonsef615e52022-08-18 22:04:11 -040083 flag.BoolVar(&cmdlineArgs.BazelMode, "bazel-mode", false, "use bazel for analysis of certain modules")
Jingwen Chene647db82022-11-01 11:28:29 +000084 flag.BoolVar(&cmdlineArgs.BazelModeStaging, "bazel-mode-staging", false, "use bazel for analysis of certain near-ready modules")
Chris Parsonsef615e52022-08-18 22:04:11 -040085 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 -050086 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 +000087 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 +000088 flag.BoolVar(&cmdlineArgs.EnsureAllowlistIntegrity, "ensure-allowlist-integrity", false, "verify that allowlisted modules are mixed-built")
Sasha Smundakaf5ca922022-12-12 21:23:34 -080089 // Flags that probably shouldn't be flags of soong_build, but we haven't found
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020090 // the time to remove them yet
Sasha Smundakaf5ca922022-12-12 21:23:34 -080091 flag.BoolVar(&cmdlineArgs.RunGoTests, "t", false, "build and run go tests during bootstrap")
Dan Willemsen66213a62021-09-21 17:50:30 -070092
93 // Disable deterministic randomization in the protobuf package, so incremental
94 // builds with unrelated Soong changes don't trigger large rebuilds (since we
95 // write out text protos in command lines, and command line changes trigger
96 // rebuilds).
97 androidProtobuf.DisableRand()
Colin Crosse87040b2017-12-11 15:52:26 -080098}
99
Jeff Gaston088e29e2017-11-29 16:47:17 -0800100func newNameResolver(config android.Config) *android.NameResolver {
Paul Duffin3f7bf9f2022-11-08 12:21:15 +0000101 return android.NewNameResolver(config)
Jeff Gaston088e29e2017-11-29 16:47:17 -0800102}
103
Lukacs T. Berkiffc9e8d2021-09-07 17:54:38 +0200104func newContext(configuration android.Config) *android.Context {
Colin Crossae8600b2020-10-29 17:09:13 -0700105 ctx := android.NewContext(configuration)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400106 ctx.SetNameInterface(newNameResolver(configuration))
107 ctx.SetAllowMissingDependencies(configuration.AllowMissingDependencies())
Spandan Dasc5763832022-11-08 18:42:16 +0000108 ctx.AddIncludeTags(configuration.IncludeTags()...)
Sam Delmerico98a73292023-02-21 11:50:29 -0500109 ctx.AddSourceRootDirs(configuration.SourceRootDirs()...)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400110 return ctx
111}
112
Chris Parsonsf874e462022-05-10 13:50:12 -0400113// Bazel-enabled mode. Attaches a mutator to queue Bazel requests, adds a
114// BeforePrepareBuildActionsHook to invoke Bazel, and then uses Bazel metadata
115// for modules that should be handled by Bazel.
Sasha Smundak1845f422022-12-13 14:18:58 -0800116func runMixedModeBuild(ctx *android.Context, extraNinjaDeps []string) string {
Chris Parsonsf874e462022-05-10 13:50:12 -0400117 ctx.EventHandler.Begin("mixed_build")
118 defer ctx.EventHandler.End("mixed_build")
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200119
Chris Parsonsf874e462022-05-10 13:50:12 -0400120 bazelHook := func() error {
Sasha Smundak1845f422022-12-13 14:18:58 -0800121 return ctx.Config().BazelContext.InvokeBazel(ctx.Config(), ctx)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200122 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400123 ctx.SetBeforePrepareBuildActionsHook(bazelHook)
Sasha Smundak1845f422022-12-13 14:18:58 -0800124 ninjaDeps := bootstrap.RunBlueprint(cmdlineArgs.Args, bootstrap.DoEverything, ctx.Context, ctx.Config())
Chris Parsons027881c2022-05-24 15:38:38 -0400125 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200126
Sasha Smundak1845f422022-12-13 14:18:58 -0800127 bazelPaths, err := readFileLines(ctx.Config().Getenv("BAZEL_DEPS_FILE"))
MarkDacek0d5bca52022-10-10 20:07:48 +0000128 if err != nil {
129 panic("Bazel deps file not found: " + err.Error())
130 }
131 ninjaDeps = append(ninjaDeps, bazelPaths...)
Sasha Smundak1845f422022-12-13 14:18:58 -0800132 ninjaDeps = append(ninjaDeps, writeBuildGlobsNinjaFile(ctx)...)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200133
Paul Duffin780a1852022-11-05 10:17:12 +0000134 writeDepFile(cmdlineArgs.OutFile, ctx.EventHandler, ninjaDeps)
Paul Duffin0c09a432022-11-05 15:28:04 +0000135 return cmdlineArgs.OutFile
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200136}
137
138// Run the code-generation phase to convert BazelTargetModules to BUILD files.
Sasha Smundak1845f422022-12-13 14:18:58 -0800139func runQueryView(queryviewDir, queryviewMarker string, ctx *android.Context) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400140 ctx.EventHandler.Begin("queryview")
141 defer ctx.EventHandler.End("queryview")
Cole Faustb85d1a12022-11-08 18:14:01 -0800142 codegenContext := bp2build.NewCodegenContext(ctx.Config(), ctx, bp2build.QueryView, topDir)
Spandan Das98cb8562023-03-09 23:05:47 +0000143 err := createBazelWorkspace(codegenContext, shared.JoinPath(topDir, queryviewDir), false)
Sasha Smundak1845f422022-12-13 14:18:58 -0800144 maybeQuit(err, "")
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200145 touch(shared.JoinPath(topDir, queryviewMarker))
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200146}
147
Spandan Das5af0bd32022-09-28 20:43:08 +0000148// Run the code-generation phase to convert API contributions to BUILD files.
149// Return marker file for the new synthetic workspace
Sasha Smundak1845f422022-12-13 14:18:58 -0800150func runApiBp2build(ctx *android.Context, extraNinjaDeps []string) string {
Spandan Das5af0bd32022-09-28 20:43:08 +0000151 ctx.EventHandler.Begin("api_bp2build")
152 defer ctx.EventHandler.End("api_bp2build")
Spandan Das255648c2023-01-11 03:05:24 +0000153 // api_bp2build does not run the typical pipeline of soong mutators.
154 // Hoevever, it still runs the defaults mutator which can create dependencies.
155 // These dependencies might not always exist (e.g. in tests)
156 ctx.SetAllowMissingDependencies(ctx.Config().AllowMissingDependencies())
Spandan Das5af0bd32022-09-28 20:43:08 +0000157 ctx.RegisterForApiBazelConversion()
158
159 // Register the Android.bp files in the tree
160 // Add them to the workspace's .d file
161 ctx.SetModuleListFile(cmdlineArgs.ModuleListFile)
162 if paths, err := ctx.ListModulePaths("."); err == nil {
163 extraNinjaDeps = append(extraNinjaDeps, paths...)
164 } else {
165 panic(err)
166 }
167
168 // Run the loading and analysis phase
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800169 ninjaDeps := bootstrap.RunBlueprint(cmdlineArgs.Args,
Spandan Das5af0bd32022-09-28 20:43:08 +0000170 bootstrap.StopBeforePrepareBuildActions,
171 ctx.Context,
Sasha Smundak1845f422022-12-13 14:18:58 -0800172 ctx.Config())
Spandan Das5af0bd32022-09-28 20:43:08 +0000173 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
174
175 // Add the globbed dependencies
Sasha Smundak1845f422022-12-13 14:18:58 -0800176 ninjaDeps = append(ninjaDeps, writeBuildGlobsNinjaFile(ctx)...)
Spandan Das5af0bd32022-09-28 20:43:08 +0000177
178 // Run codegen to generate BUILD files
Cole Faustb85d1a12022-11-08 18:14:01 -0800179 codegenContext := bp2build.NewCodegenContext(ctx.Config(), ctx, bp2build.ApiBp2build, topDir)
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800180 absoluteApiBp2buildDir := shared.JoinPath(topDir, cmdlineArgs.BazelApiBp2buildDir)
Spandan Das98cb8562023-03-09 23:05:47 +0000181 // Always generate bp2build_all_srcs filegroups in api_bp2build.
182 // This is necessary to force each Android.bp file to create an equivalent BUILD file
183 // and prevent package boundray issues.
184 // e.g.
185 // Source
186 // f/b/Android.bp
187 // java_library{
188 // name: "foo",
189 // api: "api/current.txt",
190 // }
191 //
192 // f/b/api/Android.bp <- will cause package boundary issues
193 //
194 // Gen
195 // f/b/BUILD
196 // java_contribution{
197 // name: "foo.contribution",
198 // api: "//f/b/api:current.txt",
199 // }
200 //
201 // If we don't generate f/b/api/BUILD, foo.contribution will be unbuildable.
202 err := createBazelWorkspace(codegenContext, absoluteApiBp2buildDir, true)
Sasha Smundak1845f422022-12-13 14:18:58 -0800203 maybeQuit(err, "")
Spandan Das5af0bd32022-09-28 20:43:08 +0000204 ninjaDeps = append(ninjaDeps, codegenContext.AdditionalNinjaDeps()...)
205
206 // Create soong_injection repository
Cole Faust9e384e22023-02-08 17:43:09 -0800207 soongInjectionFiles, err := bp2build.CreateSoongInjectionDirFiles(codegenContext, bp2build.CreateCodegenMetrics())
208 maybeQuit(err, "")
Sasha Smundak1845f422022-12-13 14:18:58 -0800209 absoluteSoongInjectionDir := shared.JoinPath(topDir, ctx.Config().SoongOutDir(), bazel.SoongInjectionDirName)
Spandan Das5af0bd32022-09-28 20:43:08 +0000210 for _, file := range soongInjectionFiles {
Spandan Das067210f2022-12-07 01:14:52 +0000211 // The API targets in api_bp2build workspace do not have any dependency on api_bp2build.
212 // But we need to create these files to prevent errors during Bazel analysis.
213 // These need to be created in Read-Write mode.
214 // This is because the subsequent step (bp2build in api domain analysis) creates them in Read-Write mode
215 // to allow users to edit/experiment in the synthetic workspace.
216 writeReadWriteFile(absoluteSoongInjectionDir, file)
Spandan Das5af0bd32022-09-28 20:43:08 +0000217 }
218
Sasha Smundak1845f422022-12-13 14:18:58 -0800219 workspace := shared.JoinPath(ctx.Config().SoongOutDir(), "api_bp2build")
Spandan Das5af0bd32022-09-28 20:43:08 +0000220 // Create the symlink forest
Usta Shresthada15c612022-11-08 14:12:36 -0500221 symlinkDeps, _, _ := bp2build.PlantSymlinkForest(
Sasha Smundak1845f422022-12-13 14:18:58 -0800222 ctx.Config().IsEnvTrue("BP2BUILD_VERBOSE"),
Spandan Das5af0bd32022-09-28 20:43:08 +0000223 topDir,
224 workspace,
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800225 cmdlineArgs.BazelApiBp2buildDir,
Sasha Smundak1845f422022-12-13 14:18:58 -0800226 apiBuildFileExcludes(ctx))
Spandan Das5af0bd32022-09-28 20:43:08 +0000227 ninjaDeps = append(ninjaDeps, symlinkDeps...)
228
229 workspaceMarkerFile := workspace + ".marker"
Paul Duffin780a1852022-11-05 10:17:12 +0000230 writeDepFile(workspaceMarkerFile, ctx.EventHandler, ninjaDeps)
Spandan Das5af0bd32022-09-28 20:43:08 +0000231 touch(shared.JoinPath(topDir, workspaceMarkerFile))
232 return workspaceMarkerFile
233}
234
235// With some exceptions, api_bp2build does not have any dependencies on the checked-in BUILD files
236// Exclude them from the generated workspace to prevent unrelated errors during the loading phase
Sasha Smundak1845f422022-12-13 14:18:58 -0800237func apiBuildFileExcludes(ctx *android.Context) []string {
238 ret := bazelArtifacts()
Spandan Das5af0bd32022-09-28 20:43:08 +0000239 srcs, err := getExistingBazelRelatedFiles(topDir)
Sasha Smundak1845f422022-12-13 14:18:58 -0800240 maybeQuit(err, "Error determining existing Bazel-related files")
Spandan Das5af0bd32022-09-28 20:43:08 +0000241 for _, src := range srcs {
Sasha Smundak1845f422022-12-13 14:18:58 -0800242 // Exclude all src BUILD files
Spandan Das5af0bd32022-09-28 20:43:08 +0000243 if src != "WORKSPACE" &&
244 src != "BUILD" &&
245 src != "BUILD.bazel" &&
246 !strings.HasPrefix(src, "build/bazel") &&
Spandan Das6b91a382022-11-30 02:17:06 +0000247 !strings.HasPrefix(src, "external/bazel-skylib") &&
Spandan Das5af0bd32022-09-28 20:43:08 +0000248 !strings.HasPrefix(src, "prebuilts/clang") {
249 ret = append(ret, src)
250 }
251 }
Sasha Smundak1845f422022-12-13 14:18:58 -0800252 // Android.bp files for api surfaces are mounted to out/, but out/ should not be a
253 // dep for api_bp2build. Otherwise, api_bp2build will be run every single time
254 ret = append(ret, ctx.Config().OutDir())
Spandan Das5af0bd32022-09-28 20:43:08 +0000255 return ret
256}
257
Jeongik Chae114e602023-03-19 00:12:39 +0900258func writeNinjaHint(ctx *android.Context) error {
259 wantModules := make([]string, len(allowlists.HugeModulesMap))
260 i := 0
261 for k := range allowlists.HugeModulesMap {
262 wantModules[i] = k
263 i += 1
264 }
265 outputsMap := ctx.Context.GetOutputsFromModuleNames(wantModules)
266 var outputBuilder strings.Builder
267 for k, v := range allowlists.HugeModulesMap {
268 for _, output := range outputsMap[k] {
269 outputBuilder.WriteString(fmt.Sprintf("%s,%d\n", output, v))
270 }
271 }
272 weightListFile := filepath.Join(topDir, ctx.Config().OutDir(), ".ninja_weight_list")
273
274 err := os.WriteFile(weightListFile, []byte(outputBuilder.String()), 0644)
275 if err != nil {
276 return fmt.Errorf("could not write ninja weight list file %s", err)
277 }
278 return nil
279}
280
Paul Duffin780a1852022-11-05 10:17:12 +0000281func writeMetrics(configuration android.Config, eventHandler *metrics.EventHandler, metricsDir string) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400282 if len(metricsDir) < 1 {
283 fmt.Fprintf(os.Stderr, "\nMissing required env var for generating soong metrics: LOG_DIR\n")
284 os.Exit(1)
285 }
286 metricsFile := filepath.Join(metricsDir, "soong_build_metrics.pb")
287 err := android.WriteMetrics(configuration, eventHandler, metricsFile)
Sasha Smundak1845f422022-12-13 14:18:58 -0800288 maybeQuit(err, "error writing soong_build metrics %s", metricsFile)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200289}
290
MarkDacekf47e1422023-04-19 16:47:36 +0000291// Errors out if any modules expected to be mixed_built were not, unless
292// there is a platform incompatibility.
293func checkForAllowlistIntegrityError(configuration android.Config, isStagingMode bool) error {
294 modules := findModulesNotMixedBuiltForAnyVariant(configuration, isStagingMode)
295 if len(modules) == 0 {
296 return nil
297 }
298
299 return fmt.Errorf("Error: expected the following modules to be mixed_built: %s", modules)
300}
301
302// Returns the list of modules that should have been mixed_built (per the
303// allowlists and cmdline flags) but were not.
304func findModulesNotMixedBuiltForAnyVariant(configuration android.Config, isStagingMode bool) []string {
305 retval := []string{}
306 forceEnabledModules := configuration.BazelModulesForceEnabledByFlag()
307
308 mixedBuildsEnabled := configuration.GetMixedBuildsEnabledModules()
309 for _, module := range allowlists.ProdMixedBuildsEnabledList {
310 if _, ok := mixedBuildsEnabled[module]; !ok && module != "" {
311 retval = append(retval, module)
312 }
313 }
314
315 if isStagingMode {
316 for _, module := range allowlists.StagingMixedBuildsEnabledList {
317 if _, ok := mixedBuildsEnabled[module]; !ok && module != "" {
318 retval = append(retval, module)
319 }
320 }
321 }
322
323 for module, _ := range forceEnabledModules {
324 if _, ok := mixedBuildsEnabled[module]; !ok && module != "" {
325 retval = append(retval, module)
326 }
327 }
328 return retval
329}
330
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800331func writeJsonModuleGraphAndActions(ctx *android.Context, cmdArgs android.CmdArgs) {
332 graphFile, graphErr := os.Create(shared.JoinPath(topDir, cmdArgs.ModuleGraphFile))
Sasha Smundak1845f422022-12-13 14:18:58 -0800333 maybeQuit(graphErr, "graph err")
kgui67007242022-01-25 13:50:25 +0800334 defer graphFile.Close()
Sasha Smundak1845f422022-12-13 14:18:58 -0800335 actionsFile, actionsErr := os.Create(shared.JoinPath(topDir, cmdArgs.ModuleActionsFile))
336 maybeQuit(actionsErr, "actions err")
kgui67007242022-01-25 13:50:25 +0800337 defer actionsFile.Close()
338 ctx.Context.PrintJSONGraphAndActions(graphFile, actionsFile)
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200339}
340
Sasha Smundak1845f422022-12-13 14:18:58 -0800341func writeBuildGlobsNinjaFile(ctx *android.Context) []string {
Chris Parsons715b08f2022-03-22 19:23:40 -0400342 ctx.EventHandler.Begin("globs_ninja_file")
343 defer ctx.EventHandler.End("globs_ninja_file")
344
Sasha Smundak1845f422022-12-13 14:18:58 -0800345 globDir := bootstrap.GlobDirectory(ctx.Config().SoongOutDir(), globListDir)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200346 bootstrap.WriteBuildGlobsNinjaFile(&bootstrap.GlobSingleton{
Chris Parsons715b08f2022-03-22 19:23:40 -0400347 GlobLister: ctx.Globs,
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200348 GlobFile: globFile,
349 GlobDir: globDir,
Chris Parsons715b08f2022-03-22 19:23:40 -0400350 SrcDir: ctx.SrcDir(),
Sasha Smundak1845f422022-12-13 14:18:58 -0800351 }, ctx.Config())
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200352 return bootstrap.GlobFileListFiles(globDir)
353}
354
Paul Duffin780a1852022-11-05 10:17:12 +0000355func writeDepFile(outputFile string, eventHandler *metrics.EventHandler, ninjaDeps []string) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400356 eventHandler.Begin("ninja_deps")
357 defer eventHandler.End("ninja_deps")
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200358 depFile := shared.JoinPath(topDir, outputFile+".d")
359 err := deptools.WriteDepFile(depFile, outputFile, ninjaDeps)
Sasha Smundak1845f422022-12-13 14:18:58 -0800360 maybeQuit(err, "error writing depfile '%s'", depFile)
Paul Duffin0c09a432022-11-05 15:28:04 +0000361}
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200362
Paul Duffin0c09a432022-11-05 15:28:04 +0000363// runSoongOnlyBuild runs the standard Soong build in a number of different modes.
Sasha Smundak1845f422022-12-13 14:18:58 -0800364func runSoongOnlyBuild(ctx *android.Context, extraNinjaDeps []string) string {
Paul Duffin39eae8f2022-11-05 14:59:52 +0000365 ctx.EventHandler.Begin("soong_build")
366 defer ctx.EventHandler.End("soong_build")
367
Paul Duffin0c09a432022-11-05 15:28:04 +0000368 var stopBefore bootstrap.StopBefore
Sasha Smundak1845f422022-12-13 14:18:58 -0800369 switch ctx.Config().BuildMode {
370 case android.GenerateModuleGraph:
Paul Duffin0c09a432022-11-05 15:28:04 +0000371 stopBefore = bootstrap.StopBeforeWriteNinja
Usta Shrestha7fae6952022-12-21 11:46:28 -0500372 case android.GenerateQueryView, android.GenerateDocFile:
Paul Duffin0c09a432022-11-05 15:28:04 +0000373 stopBefore = bootstrap.StopBeforePrepareBuildActions
Sasha Smundak1845f422022-12-13 14:18:58 -0800374 default:
Paul Duffin0c09a432022-11-05 15:28:04 +0000375 stopBefore = bootstrap.DoEverything
376 }
377
Sasha Smundak1845f422022-12-13 14:18:58 -0800378 ninjaDeps := bootstrap.RunBlueprint(cmdlineArgs.Args, stopBefore, ctx.Context, ctx.Config())
Paul Duffin0c09a432022-11-05 15:28:04 +0000379 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
380
Sasha Smundak1845f422022-12-13 14:18:58 -0800381 globListFiles := writeBuildGlobsNinjaFile(ctx)
Paul Duffin0c09a432022-11-05 15:28:04 +0000382 ninjaDeps = append(ninjaDeps, globListFiles...)
383
384 // Convert the Soong module graph into Bazel BUILD files.
Sasha Smundak1845f422022-12-13 14:18:58 -0800385 switch ctx.Config().BuildMode {
386 case android.GenerateQueryView:
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800387 queryviewMarkerFile := cmdlineArgs.BazelQueryViewDir + ".marker"
Sasha Smundak1845f422022-12-13 14:18:58 -0800388 runQueryView(cmdlineArgs.BazelQueryViewDir, queryviewMarkerFile, ctx)
Paul Duffin0c09a432022-11-05 15:28:04 +0000389 writeDepFile(queryviewMarkerFile, ctx.EventHandler, ninjaDeps)
390 return queryviewMarkerFile
Sasha Smundak1845f422022-12-13 14:18:58 -0800391 case android.GenerateModuleGraph:
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800392 writeJsonModuleGraphAndActions(ctx, cmdlineArgs)
393 writeDepFile(cmdlineArgs.ModuleGraphFile, ctx.EventHandler, ninjaDeps)
394 return cmdlineArgs.ModuleGraphFile
Sasha Smundak1845f422022-12-13 14:18:58 -0800395 case android.GenerateDocFile:
Paul Duffin0c09a432022-11-05 15:28:04 +0000396 // TODO: we could make writeDocs() return the list of documentation files
397 // written and add them to the .d file. Then soong_docs would be re-run
398 // whenever one is deleted.
Sasha Smundak1845f422022-12-13 14:18:58 -0800399 err := writeDocs(ctx, shared.JoinPath(topDir, cmdlineArgs.DocFile))
400 maybeQuit(err, "error building Soong documentation")
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800401 writeDepFile(cmdlineArgs.DocFile, ctx.EventHandler, ninjaDeps)
402 return cmdlineArgs.DocFile
Sasha Smundak1845f422022-12-13 14:18:58 -0800403 default:
Paul Duffin0c09a432022-11-05 15:28:04 +0000404 // The actual output (build.ninja) was written in the RunBlueprint() call
405 // above
406 writeDepFile(cmdlineArgs.OutFile, ctx.EventHandler, ninjaDeps)
Paul Duffinb713ddf2022-11-05 16:14:30 +0000407 return cmdlineArgs.OutFile
Paul Duffin0c09a432022-11-05 15:28:04 +0000408 }
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200409}
410
411// soong_ui dumps the available environment variables to
412// soong.environment.available . Then soong_build itself is run with an empty
413// environment so that the only way environment variables can be accessed is
414// using Config, which tracks access to them.
415
416// At the end of the build, a file called soong.environment.used is written
417// containing the current value of all used environment variables. The next
418// time soong_ui is run, it checks whether any environment variables that was
419// used had changed and if so, it deletes soong.environment.used to cause a
420// rebuild.
421//
422// The dependency of build.ninja on soong.environment.used is declared in
423// build.ninja.d
424func parseAvailableEnv() map[string]string {
425 if availableEnvFile == "" {
426 fmt.Fprintf(os.Stderr, "--available_env not set\n")
427 os.Exit(1)
428 }
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200429 result, err := shared.EnvFromFile(shared.JoinPath(topDir, availableEnvFile))
Sasha Smundak1845f422022-12-13 14:18:58 -0800430 maybeQuit(err, "error reading available environment file '%s'", availableEnvFile)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200431 return result
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200432}
433
Colin Cross3f40fa42015-01-30 17:27:36 -0800434func main() {
435 flag.Parse()
436
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100437 shared.ReexecWithDelveMaybe(delveListen, delvePath)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100438 android.InitSandbox(topDir)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100439
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200440 availableEnv := parseAvailableEnv()
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800441 configuration, err := android.NewConfig(cmdlineArgs, availableEnv)
Sasha Smundak1845f422022-12-13 14:18:58 -0800442 maybeQuit(err, "")
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100443 if configuration.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
444 configuration.SetAllowMissingDependencies()
445 }
446
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800447 extraNinjaDeps := []string{configuration.ProductVariablesFileName, usedEnvFile}
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100448 if shared.IsDebugging() {
Colin Crossaa812d12019-06-19 13:33:24 -0700449 // Add a non-existent file to the dependencies so that soong_build will rerun when the debugger is
450 // enabled even if it completed successfully.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200451 extraNinjaDeps = append(extraNinjaDeps, filepath.Join(configuration.SoongOutDir(), "always_rerun_for_delve"))
Colin Crossaa812d12019-06-19 13:33:24 -0700452 }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500453
Dan Willemsenccf36aa2022-04-20 23:11:43 -0700454 // Bypass configuration.Getenv, as LOG_DIR does not need to be dependency tracked. By definition, it will
455 // change between every CI build, so tracking it would require re-running Soong for every build.
Sasha Smundak1845f422022-12-13 14:18:58 -0800456 metricsDir := availableEnv["LOG_DIR"]
Dan Willemsenccf36aa2022-04-20 23:11:43 -0700457
Joe Onorato2e5e4012022-06-07 17:16:08 -0700458 ctx := newContext(configuration)
Joe Onorato2e5e4012022-06-07 17:16:08 -0700459
Sasha Smundak1845f422022-12-13 14:18:58 -0800460 var finalOutputFile string
Joe Onorato2e5e4012022-06-07 17:16:08 -0700461
Sasha Smundak1845f422022-12-13 14:18:58 -0800462 // Run Soong for a specific activity, like bp2build, queryview
463 // or the actual Soong build for the build.ninja file.
464 switch configuration.BuildMode {
465 case android.SymlinkForest:
466 finalOutputFile = runSymlinkForestCreation(ctx, extraNinjaDeps, metricsDir)
467 case android.Bp2build:
468 // Run the alternate pipeline of bp2build mutators and singleton to convert
469 // Blueprint to BUILD files before everything else.
470 finalOutputFile = runBp2Build(ctx, extraNinjaDeps, metricsDir)
471 case android.ApiBp2build:
472 finalOutputFile = runApiBp2build(ctx, extraNinjaDeps)
473 writeMetrics(configuration, ctx.EventHandler, metricsDir)
474 default:
475 ctx.Register()
MarkDacekf47e1422023-04-19 16:47:36 +0000476 isMixedBuildsEnabled := configuration.IsMixedBuildsEnabled()
477 if isMixedBuildsEnabled {
Sasha Smundak1845f422022-12-13 14:18:58 -0800478 finalOutputFile = runMixedModeBuild(ctx, extraNinjaDeps)
MarkDacekf47e1422023-04-19 16:47:36 +0000479 if cmdlineArgs.EnsureAllowlistIntegrity {
480 if err := checkForAllowlistIntegrityError(configuration, cmdlineArgs.BazelModeStaging); err != nil {
481 maybeQuit(err, "")
482 }
483 }
Sasha Smundak1845f422022-12-13 14:18:58 -0800484 } else {
485 finalOutputFile = runSoongOnlyBuild(ctx, extraNinjaDeps)
486 }
Jeongik Chae114e602023-03-19 00:12:39 +0900487 if ctx.Config().IsEnvTrue("SOONG_GENERATES_NINJA_HINT") {
488 writeNinjaHint(ctx)
489 }
Sasha Smundak1845f422022-12-13 14:18:58 -0800490 writeMetrics(configuration, ctx.EventHandler, metricsDir)
491 }
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200492 writeUsedEnvironmentFile(configuration, finalOutputFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100493}
494
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200495func writeUsedEnvironmentFile(configuration android.Config, finalOutputFile string) {
496 if usedEnvFile == "" {
497 return
498 }
499
500 path := shared.JoinPath(topDir, usedEnvFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100501 data, err := shared.EnvFileContents(configuration.EnvDeps())
Sasha Smundak1845f422022-12-13 14:18:58 -0800502 maybeQuit(err, "error writing used environment file '%s'\n", usedEnvFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100503
Usta Shrestha2ba28a32022-10-24 11:33:09 -0400504 if preexistingData, err := os.ReadFile(path); err != nil {
505 if !os.IsNotExist(err) {
Sasha Smundak1845f422022-12-13 14:18:58 -0800506 maybeQuit(err, "error reading used environment file '%s'", usedEnvFile)
Usta Shrestha2ba28a32022-10-24 11:33:09 -0400507 }
508 } else if bytes.Equal(preexistingData, data) {
509 // used environment file is unchanged
510 return
511 }
Sasha Smundak1845f422022-12-13 14:18:58 -0800512 err = os.WriteFile(path, data, 0666)
513 maybeQuit(err, "error writing used environment file '%s'", usedEnvFile)
514
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200515 // Touch the output file so that it's not older than the file we just
Lukacs T. Berkic99c9472021-03-24 10:50:06 +0100516 // wrote. We can't write the environment file earlier because one an access
517 // new environment variables while writing it.
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200518 touch(shared.JoinPath(topDir, finalOutputFile))
Colin Cross3f40fa42015-01-30 17:27:36 -0800519}
Jingwen Chen5ba7e472020-07-15 10:06:41 +0000520
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200521func touch(path string) {
522 f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
Sasha Smundak1845f422022-12-13 14:18:58 -0800523 maybeQuit(err, "Error touching '%s'", path)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200524 err = f.Close()
Sasha Smundak1845f422022-12-13 14:18:58 -0800525 maybeQuit(err, "Error touching '%s'", path)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200526
527 currentTime := time.Now().Local()
528 err = os.Chtimes(path, currentTime, currentTime)
Sasha Smundak1845f422022-12-13 14:18:58 -0800529 maybeQuit(err, "error touching '%s'", path)
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400530}
531
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400532// Read the bazel.list file that the Soong Finder already dumped earlier (hopefully)
533// It contains the locations of BUILD files, BUILD.bazel files, etc. in the source dir
534func getExistingBazelRelatedFiles(topDir string) ([]string, error) {
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200535 bazelFinderFile := filepath.Join(filepath.Dir(cmdlineArgs.ModuleListFile), "bazel.list")
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400536 if !filepath.IsAbs(bazelFinderFile) {
537 // Assume this was a relative path under topDir
538 bazelFinderFile = filepath.Join(topDir, bazelFinderFile)
539 }
Sasha Smundak1845f422022-12-13 14:18:58 -0800540 return readFileLines(bazelFinderFile)
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400541}
542
Spandan Das5af0bd32022-09-28 20:43:08 +0000543func bazelArtifacts() []string {
544 return []string{
545 "bazel-bin",
546 "bazel-genfiles",
547 "bazel-out",
548 "bazel-testlogs",
Usta (Tsering) Shresthac4c07b12022-11-08 18:31:14 -0500549 "bazel-workspace",
Spandan Das5af0bd32022-09-28 20:43:08 +0000550 "bazel-" + filepath.Base(topDir),
551 }
552}
553
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000554// This could in theory easily be separated into a binary that generically
555// merges two directories into a symlink tree. The main obstacle is that this
556// function currently depends on both Bazel-specific knowledge (the existence
557// of bazel-* symlinks) and configuration (the set of BUILD.bazel files that
558// should and should not be kept)
559//
560// Ideally, bp2build would write a file that contains instructions to the
561// symlink tree creation binary. Then the latter would not need to depend on
562// the very heavy-weight machinery of soong_build .
Sasha Smundak1845f422022-12-13 14:18:58 -0800563func runSymlinkForestCreation(ctx *android.Context, extraNinjaDeps []string, metricsDir string) string {
Usta Shresthada15c612022-11-08 14:12:36 -0500564 var ninjaDeps []string
565 var mkdirCount, symlinkCount uint64
566
Paul Duffinb4e8d912022-11-04 13:35:50 +0000567 ctx.EventHandler.Do("symlink_forest", func() {
Usta (Tsering) Shrestha93b2a9b2022-12-01 05:55:35 +0000568 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Sasha Smundak1845f422022-12-13 14:18:58 -0800569 verbose := ctx.Config().IsEnvTrue("BP2BUILD_VERBOSE")
Usta (Tsering) Shrestha93b2a9b2022-12-01 05:55:35 +0000570
571 // PlantSymlinkForest() returns all the directories that were readdir()'ed.
572 // Such a directory SHOULD be added to `ninjaDeps` so that a child directory
573 // or file created/deleted under it would trigger an update of the symlink forest.
Sasha Smundak1845f422022-12-13 14:18:58 -0800574 generatedRoot := shared.JoinPath(ctx.Config().SoongOutDir(), "bp2build")
575 workspaceRoot := shared.JoinPath(ctx.Config().SoongOutDir(), "workspace")
Usta Shresthada15c612022-11-08 14:12:36 -0500576 var symlinkForestDeps []string
Usta (Tsering) Shrestha93b2a9b2022-12-01 05:55:35 +0000577 ctx.EventHandler.Do("plant", func() {
Usta Shresthada15c612022-11-08 14:12:36 -0500578 symlinkForestDeps, mkdirCount, symlinkCount = bp2build.PlantSymlinkForest(
Sasha Smundak1845f422022-12-13 14:18:58 -0800579 verbose, topDir, workspaceRoot, generatedRoot, excludedFromSymlinkForest(ctx, verbose))
Usta (Tsering) Shrestha93b2a9b2022-12-01 05:55:35 +0000580 })
Usta Shresthada15c612022-11-08 14:12:36 -0500581 ninjaDeps = append(ninjaDeps, symlinkForestDeps...)
Usta (Tsering) Shrestha93b2a9b2022-12-01 05:55:35 +0000582 })
Usta Shresthada15c612022-11-08 14:12:36 -0500583
584 writeDepFile(cmdlineArgs.SymlinkForestMarker, ctx.EventHandler, ninjaDeps)
585 touch(shared.JoinPath(topDir, cmdlineArgs.SymlinkForestMarker))
usta4f5d2c12022-10-28 23:32:01 -0400586 codegenMetrics := bp2build.ReadCodegenMetrics(metricsDir)
587 if codegenMetrics == nil {
588 m := bp2build.CreateCodegenMetrics()
589 codegenMetrics = &m
590 } else {
591 //TODO (usta) we cannot determine if we loaded a stale file, i.e. from an unrelated prior
592 //invocation of codegen. We should simply use a separate .pb file
593 }
Usta Shresthada15c612022-11-08 14:12:36 -0500594 codegenMetrics.SetSymlinkCount(symlinkCount)
595 codegenMetrics.SetMkDirCount(mkdirCount)
Paul Duffinb4e8d912022-11-04 13:35:50 +0000596 writeBp2BuildMetrics(codegenMetrics, ctx.EventHandler, metricsDir)
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800597 return cmdlineArgs.SymlinkForestMarker
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000598}
599
Sasha Smundak1845f422022-12-13 14:18:58 -0800600func excludedFromSymlinkForest(ctx *android.Context, verbose bool) []string {
601 excluded := bazelArtifacts()
602 if cmdlineArgs.OutDir[0] != '/' {
603 excluded = append(excluded, cmdlineArgs.OutDir)
604 }
605
606 // Find BUILD files in the srcDir which are not in the allowlist
607 // (android.Bp2BuildConversionAllowlist#ShouldKeepExistingBuildFileForDir)
608 // and return their paths so they can be left out of the Bazel workspace dir (i.e. ignored)
609 existingBazelFiles, err := getExistingBazelRelatedFiles(topDir)
610 maybeQuit(err, "Error determining existing Bazel-related files")
611
612 for _, path := range existingBazelFiles {
613 fullPath := shared.JoinPath(topDir, path)
614 fileInfo, err2 := os.Stat(fullPath)
615 if err2 != nil {
616 // Warn about error, but continue trying to check files
617 fmt.Fprintf(os.Stderr, "WARNING: Error accessing path '%s', err: %s\n", fullPath, err2)
618 continue
619 }
620 // Exclude only files named 'BUILD' or 'BUILD.bazel' and unless forcibly kept
621 if fileInfo.IsDir() ||
622 (fileInfo.Name() != "BUILD" && fileInfo.Name() != "BUILD.bazel") ||
623 ctx.Config().Bp2buildPackageConfig.ShouldKeepExistingBuildFileForDir(filepath.Dir(path)) {
624 // Don't ignore this existing build file
625 continue
626 }
627 if verbose {
628 fmt.Fprintf(os.Stderr, "Ignoring existing BUILD file: %s\n", path)
629 }
630 excluded = append(excluded, path)
631 }
632
633 // Temporarily exclude stuff to make `bazel build //external/...` (and `bazel build //frameworks/...`) work
634 excluded = append(excluded,
635 // FIXME: 'autotest_lib' is a symlink back to external/autotest, and this causes an infinite
636 // symlink expansion error for Bazel
637 "external/autotest/venv/autotest_lib",
638 "external/autotest/autotest_lib",
639 "external/autotest/client/autotest_lib/client",
640
641 // FIXME: The external/google-fruit/extras/bazel_root/third_party/fruit dir is poison
642 // It contains several symlinks back to real source dirs, and those source dirs contain
643 // BUILD files we want to ignore
644 "external/google-fruit/extras/bazel_root/third_party/fruit",
645
646 // FIXME: 'frameworks/compile/slang' has a filegroup error due to an escaping issue
647 "frameworks/compile/slang",
648
649 // FIXME(b/260809113): 'prebuilts/clang/host/linux-x86/clang-dev' is a tool-generated symlink
650 // directory that contains a BUILD file. The bazel files finder code doesn't traverse into symlink dirs,
651 // and hence is not aware of this BUILD file and exclude it accordingly during symlink forest generation
652 // when checking against keepExistingBuildFiles allowlist.
653 //
654 // This is necessary because globs in //prebuilts/clang/host/linux-x86/BUILD
655 // currently assume no subpackages (keepExistingBuildFile is not recursive for that directory).
656 //
657 // This is a bandaid until we the symlink forest logic can intelligently exclude BUILD files found in
658 // source symlink dirs according to the keepExistingBuildFile allowlist.
659 "prebuilts/clang/host/linux-x86/clang-dev",
660 )
661 return excluded
662}
663
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500664// Run Soong in the bp2build mode. This creates a standalone context that registers
665// an alternate pipeline of mutators and singletons specifically for generating
666// Bazel BUILD files instead of Ninja files.
Sasha Smundak1845f422022-12-13 14:18:58 -0800667func runBp2Build(ctx *android.Context, extraNinjaDeps []string, metricsDir string) string {
usta4f5d2c12022-10-28 23:32:01 -0400668 var codegenMetrics *bp2build.CodegenMetrics
Paul Duffinb4e8d912022-11-04 13:35:50 +0000669 ctx.EventHandler.Do("bp2build", func() {
Jingwen Cheneb76c432021-01-28 08:22:12 -0500670
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400671 // Propagate "allow misssing dependencies" bit. This is normally set in
Paul Duffinb4e8d912022-11-04 13:35:50 +0000672 // newContext(), but we create ctx without calling that method.
Sasha Smundak1845f422022-12-13 14:18:58 -0800673 ctx.SetAllowMissingDependencies(ctx.Config().AllowMissingDependencies())
674 ctx.SetNameInterface(newNameResolver(ctx.Config()))
Paul Duffinb4e8d912022-11-04 13:35:50 +0000675 ctx.RegisterForBazelConversion()
676 ctx.SetModuleListFile(cmdlineArgs.ModuleListFile)
Jingwen Cheneb76c432021-01-28 08:22:12 -0500677
Usta Shresthaa117c582022-10-04 12:13:25 -0400678 var ninjaDeps []string
679 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
680
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400681 // Run the loading and analysis pipeline to prepare the graph of regular
682 // Modules parsed from Android.bp files, and the BazelTargetModules mapped
683 // from the regular Modules.
Paul Duffinb4e8d912022-11-04 13:35:50 +0000684 ctx.EventHandler.Do("bootstrap", func() {
Usta Shresthaa117c582022-10-04 12:13:25 -0400685 blueprintArgs := cmdlineArgs
Sasha Smundak1845f422022-12-13 14:18:58 -0800686 bootstrapDeps := bootstrap.RunBlueprint(blueprintArgs.Args,
687 bootstrap.StopBeforePrepareBuildActions, ctx.Context, ctx.Config())
Usta Shresthaa117c582022-10-04 12:13:25 -0400688 ninjaDeps = append(ninjaDeps, bootstrapDeps...)
689 })
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200690
Sasha Smundak1845f422022-12-13 14:18:58 -0800691 globListFiles := writeBuildGlobsNinjaFile(ctx)
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400692 ninjaDeps = append(ninjaDeps, globListFiles...)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200693
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400694 // Run the code-generation phase to convert BazelTargetModules to BUILD files
Usta Shresthaa117c582022-10-04 12:13:25 -0400695 // and print conversion codegenMetrics to the user.
Cole Faustb85d1a12022-11-08 18:14:01 -0800696 codegenContext := bp2build.NewCodegenContext(ctx.Config(), ctx, bp2build.Bp2Build, topDir)
Paul Duffinb4e8d912022-11-04 13:35:50 +0000697 ctx.EventHandler.Do("codegen", func() {
Usta Shresthaa117c582022-10-04 12:13:25 -0400698 codegenMetrics = bp2build.Codegen(codegenContext)
699 })
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200700
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400701 ninjaDeps = append(ninjaDeps, codegenContext.AdditionalNinjaDeps()...)
Chris Parsons715b08f2022-03-22 19:23:40 -0400702
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800703 writeDepFile(cmdlineArgs.Bp2buildMarker, ctx.EventHandler, ninjaDeps)
704 touch(shared.JoinPath(topDir, cmdlineArgs.Bp2buildMarker))
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400705 })
Chris Parsons715b08f2022-03-22 19:23:40 -0400706
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200707 // Only report metrics when in bp2build mode. The metrics aren't relevant
708 // for queryview, since that's a total repo-wide conversion and there's a
709 // 1:1 mapping for each module.
Sasha Smundak1845f422022-12-13 14:18:58 -0800710 if ctx.Config().IsEnvTrue("BP2BUILD_VERBOSE") {
Usta Shresthaa117c582022-10-04 12:13:25 -0400711 codegenMetrics.Print()
Sasha Smundak0fd93e02022-05-19 19:34:31 -0700712 }
Paul Duffinb4e8d912022-11-04 13:35:50 +0000713 writeBp2BuildMetrics(codegenMetrics, ctx.EventHandler, metricsDir)
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800714 return cmdlineArgs.Bp2buildMarker
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500715}
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500716
717// Write Bp2Build metrics into $LOG_DIR
Paul Duffinf4906562022-11-05 14:21:16 +0000718func writeBp2BuildMetrics(codegenMetrics *bp2build.CodegenMetrics, eventHandler *metrics.EventHandler, metricsDir string) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400719 for _, event := range eventHandler.CompletedEvents() {
usta4f5d2c12022-10-28 23:32:01 -0400720 codegenMetrics.AddEvent(&bp2build_metrics_proto.Event{
721 Name: event.Id,
722 StartTime: uint64(event.Start.UnixNano()),
723 RealTime: event.RuntimeNanoseconds(),
724 })
Chris Parsons715b08f2022-03-22 19:23:40 -0400725 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500726 if len(metricsDir) < 1 {
727 fmt.Fprintf(os.Stderr, "\nMissing required env var for generating bp2build metrics: LOG_DIR\n")
728 os.Exit(1)
729 }
Chris Parsons715b08f2022-03-22 19:23:40 -0400730 codegenMetrics.Write(metricsDir)
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500731}
MarkDacek0d5bca52022-10-10 20:07:48 +0000732
Sasha Smundak1845f422022-12-13 14:18:58 -0800733func readFileLines(path string) ([]string, error) {
734 data, err := os.ReadFile(path)
735 if err == nil {
736 return strings.Split(strings.TrimSpace(string(data)), "\n"), nil
MarkDacek0d5bca52022-10-10 20:07:48 +0000737 }
Sasha Smundak1845f422022-12-13 14:18:58 -0800738 return nil, err
739
740}
741func maybeQuit(err error, format string, args ...interface{}) {
742 if err == nil {
743 return
744 }
745 if format != "" {
746 fmt.Fprintln(os.Stderr, fmt.Sprintf(format, args...)+": "+err.Error())
747 } else {
748 fmt.Fprintln(os.Stderr, err)
749 }
750 os.Exit(1)
MarkDacek0d5bca52022-10-10 20:07:48 +0000751}