blob: 568a6f8225113cfc1b03ace693e97b63f35937ef [file] [log] [blame]
Colin Cross3f40fa42015-01-30 17:27:36 -08001// Copyright 2015 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package main
16
17import (
Usta Shrestha2ba28a32022-10-24 11:33:09 -040018 "bytes"
Jeongik Chaa87506f2023-06-01 23:16:41 +090019 "errors"
Colin Cross3f40fa42015-01-30 17:27:36 -080020 "flag"
21 "fmt"
22 "os"
23 "path/filepath"
Jingwen Cheneb76c432021-01-28 08:22:12 -050024 "strings"
Lukacs T. Berkic99c9472021-03-24 10:50:06 +010025 "time"
Colin Cross3f40fa42015-01-30 17:27:36 -080026
Dan Willemsen66213a62021-09-21 17:50:30 -070027 "android/soong/android"
Jeongik Chae114e602023-03-19 00:12:39 +090028 "android/soong/android/allowlists"
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")
Sasha Smundakaf5ca922022-12-12 21:23:34 -080077 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")
Kiyoung Kima37d9ba2023-04-19 13:13:45 +090080 flag.StringVar(&cmdlineArgs.SoongVariables, "soong_variables", "soong.variables", "the file contains all build variables")
MarkDacekd06db5d2022-11-29 00:47:59 +000081 flag.StringVar(&cmdlineArgs.BazelForceEnabledModules, "bazel-force-enabled-modules", "", "additional modules to build with Bazel. Comma-delimited")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020082 flag.BoolVar(&cmdlineArgs.EmptyNinjaFile, "empty-ninja-file", false, "write out a 0-byte ninja file")
LaMont Jones52a72432023-03-09 18:19:35 +000083 flag.BoolVar(&cmdlineArgs.MultitreeBuild, "multitree-build", false, "this is a multitree build")
Chris Parsonsef615e52022-08-18 22:04:11 -040084 flag.BoolVar(&cmdlineArgs.BazelMode, "bazel-mode", false, "use bazel for analysis of certain modules")
Jingwen Chene647db82022-11-01 11:28:29 +000085 flag.BoolVar(&cmdlineArgs.BazelModeStaging, "bazel-mode-staging", false, "use bazel for analysis of certain near-ready modules")
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")
Sebastian Pickl1c4188c2023-10-24 11:18:34 +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 {
Cole Faustbc65a3f2023-08-01 16:38:55 +0000121 err := ctx.Config().BazelContext.QueueBazelSandwichCqueryRequests(ctx.Config())
122 if err != nil {
123 return err
124 }
Sasha Smundak1845f422022-12-13 14:18:58 -0800125 return ctx.Config().BazelContext.InvokeBazel(ctx.Config(), ctx)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200126 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400127 ctx.SetBeforePrepareBuildActionsHook(bazelHook)
Lukacs T. Berkic357c812023-06-20 09:30:06 +0000128 ninjaDeps, err := bootstrap.RunBlueprint(cmdlineArgs.Args, bootstrap.DoEverything, ctx.Context, ctx.Config())
129 maybeQuit(err, "")
Chris Parsons027881c2022-05-24 15:38:38 -0400130 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200131
Sasha Smundak1845f422022-12-13 14:18:58 -0800132 bazelPaths, err := readFileLines(ctx.Config().Getenv("BAZEL_DEPS_FILE"))
MarkDacek0d5bca52022-10-10 20:07:48 +0000133 if err != nil {
134 panic("Bazel deps file not found: " + err.Error())
135 }
136 ninjaDeps = append(ninjaDeps, bazelPaths...)
Sasha Smundak1845f422022-12-13 14:18:58 -0800137 ninjaDeps = append(ninjaDeps, writeBuildGlobsNinjaFile(ctx)...)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200138
Paul Duffin780a1852022-11-05 10:17:12 +0000139 writeDepFile(cmdlineArgs.OutFile, ctx.EventHandler, ninjaDeps)
Jeongik Cha591366d2023-05-08 11:32:52 +0900140
Jeongik Chaa87506f2023-06-01 23:16:41 +0900141 if needToWriteNinjaHint(ctx) {
Jeongik Cha591366d2023-05-08 11:32:52 +0900142 writeNinjaHint(ctx)
143 }
Paul Duffin0c09a432022-11-05 15:28:04 +0000144 return cmdlineArgs.OutFile
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200145}
146
Jeongik Chaa87506f2023-06-01 23:16:41 +0900147func needToWriteNinjaHint(ctx *android.Context) bool {
148 switch ctx.Config().GetenvWithDefault("SOONG_GENERATES_NINJA_HINT", "") {
149 case "always":
150 return true
151 case "depend":
152 if _, err := os.Stat(filepath.Join(ctx.Config().OutDir(), ".ninja_log")); errors.Is(err, os.ErrNotExist) {
153 return true
154 }
155 }
156 return false
157}
158
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200159// Run the code-generation phase to convert BazelTargetModules to BUILD files.
Sasha Smundak1845f422022-12-13 14:18:58 -0800160func runQueryView(queryviewDir, queryviewMarker string, ctx *android.Context) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400161 ctx.EventHandler.Begin("queryview")
162 defer ctx.EventHandler.End("queryview")
Cole Faustb85d1a12022-11-08 18:14:01 -0800163 codegenContext := bp2build.NewCodegenContext(ctx.Config(), ctx, bp2build.QueryView, topDir)
Spandan Das98cb8562023-03-09 23:05:47 +0000164 err := createBazelWorkspace(codegenContext, shared.JoinPath(topDir, queryviewDir), false)
Sasha Smundak1845f422022-12-13 14:18:58 -0800165 maybeQuit(err, "")
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200166 touch(shared.JoinPath(topDir, queryviewMarker))
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200167}
168
Jeongik Chae114e602023-03-19 00:12:39 +0900169func writeNinjaHint(ctx *android.Context) error {
Jeongik Cha73d49112023-05-04 18:16:11 +0900170 ctx.BeginEvent("ninja_hint")
171 defer ctx.EndEvent("ninja_hint")
Jeongik Chab745e2e2023-04-11 14:28:43 +0900172 // The current predictor focuses on reducing false negatives.
173 // If there are too many false positives (e.g., most modules are marked as positive),
174 // real long-running jobs cannot run early.
175 // Therefore, the model should be adjusted in this case.
176 // The model should also be adjusted if there are critical false negatives.
177 predicate := func(j *blueprint.JsonModule) (prioritized bool, weight int) {
178 prioritized = false
179 weight = 0
180 for prefix, w := range allowlists.HugeModuleTypePrefixMap {
181 if strings.HasPrefix(j.Type, prefix) {
182 prioritized = true
183 weight = w
184 return
185 }
Jeongik Chae114e602023-03-19 00:12:39 +0900186 }
Jeongik Chab745e2e2023-04-11 14:28:43 +0900187 dep_count := len(j.Deps)
188 src_count := 0
189 for _, a := range j.Module["Actions"].([]blueprint.JSONAction) {
190 src_count += len(a.Inputs)
191 }
192 input_size := dep_count + src_count
193
194 // Current threshold is an arbitrary value which only consider recall rather than accuracy.
195 if input_size > allowlists.INPUT_SIZE_THRESHOLD {
196 prioritized = true
197 weight += ((input_size) / allowlists.INPUT_SIZE_THRESHOLD) * allowlists.DEFAULT_PRIORITIZED_WEIGHT
198
199 // To prevent some modules from having too large a priority value.
200 if weight > allowlists.HIGH_PRIORITIZED_WEIGHT {
201 weight = allowlists.HIGH_PRIORITIZED_WEIGHT
202 }
203 }
204 return
205 }
206
207 outputsMap := ctx.Context.GetWeightedOutputsFromPredicate(predicate)
208 var outputBuilder strings.Builder
209 for output, weight := range outputsMap {
210 outputBuilder.WriteString(fmt.Sprintf("%s,%d\n", output, weight))
Jeongik Chae114e602023-03-19 00:12:39 +0900211 }
212 weightListFile := filepath.Join(topDir, ctx.Config().OutDir(), ".ninja_weight_list")
213
214 err := os.WriteFile(weightListFile, []byte(outputBuilder.String()), 0644)
215 if err != nil {
216 return fmt.Errorf("could not write ninja weight list file %s", err)
217 }
218 return nil
219}
220
Paul Duffin780a1852022-11-05 10:17:12 +0000221func writeMetrics(configuration android.Config, eventHandler *metrics.EventHandler, metricsDir string) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400222 if len(metricsDir) < 1 {
223 fmt.Fprintf(os.Stderr, "\nMissing required env var for generating soong metrics: LOG_DIR\n")
224 os.Exit(1)
225 }
226 metricsFile := filepath.Join(metricsDir, "soong_build_metrics.pb")
227 err := android.WriteMetrics(configuration, eventHandler, metricsFile)
Sasha Smundak1845f422022-12-13 14:18:58 -0800228 maybeQuit(err, "error writing soong_build metrics %s", metricsFile)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200229}
230
MarkDacekf47e1422023-04-19 16:47:36 +0000231// Errors out if any modules expected to be mixed_built were not, unless
MarkDacek6f6b9622023-05-02 16:28:55 +0000232// the modules did not exist.
MarkDacekf47e1422023-04-19 16:47:36 +0000233func checkForAllowlistIntegrityError(configuration android.Config, isStagingMode bool) error {
MarkDacek6f6b9622023-05-02 16:28:55 +0000234 modules := findMisconfiguredModules(configuration, isStagingMode)
MarkDacekf47e1422023-04-19 16:47:36 +0000235 if len(modules) == 0 {
236 return nil
237 }
238
239 return fmt.Errorf("Error: expected the following modules to be mixed_built: %s", modules)
240}
241
MarkDacek6f6b9622023-05-02 16:28:55 +0000242// Returns true if the given module has all of the following true:
243// 1. Is allowlisted to be built with Bazel.
244// 2. Has a variant which is *not* built with Bazel.
245// 3. Has no variant which is built with Bazel.
246//
247// This indicates the allowlisting of this variant had no effect.
248// TODO(b/280457637): Return true for nonexistent modules.
249func isAllowlistMisconfiguredForModule(module string, mixedBuildsEnabled map[string]struct{}, mixedBuildsDisabled map[string]struct{}) bool {
MarkDacek6f6b9622023-05-02 16:28:55 +0000250 _, enabled := mixedBuildsEnabled[module]
251
252 if enabled {
253 return false
254 }
255
256 _, disabled := mixedBuildsDisabled[module]
257 return disabled
258
259}
260
MarkDacekf47e1422023-04-19 16:47:36 +0000261// Returns the list of modules that should have been mixed_built (per the
262// allowlists and cmdline flags) but were not.
MarkDacek6f6b9622023-05-02 16:28:55 +0000263// Note: nonexistent modules are excluded from the list. See b/280457637
264func findMisconfiguredModules(configuration android.Config, isStagingMode bool) []string {
MarkDacekf47e1422023-04-19 16:47:36 +0000265 retval := []string{}
266 forceEnabledModules := configuration.BazelModulesForceEnabledByFlag()
267
268 mixedBuildsEnabled := configuration.GetMixedBuildsEnabledModules()
MarkDacek6f6b9622023-05-02 16:28:55 +0000269 mixedBuildsDisabled := configuration.GetMixedBuildsDisabledModules()
MarkDacekf47e1422023-04-19 16:47:36 +0000270 for _, module := range allowlists.ProdMixedBuildsEnabledList {
MarkDacek6f6b9622023-05-02 16:28:55 +0000271 if isAllowlistMisconfiguredForModule(module, mixedBuildsEnabled, mixedBuildsDisabled) {
MarkDacekf47e1422023-04-19 16:47:36 +0000272 retval = append(retval, module)
273 }
274 }
275
276 if isStagingMode {
277 for _, module := range allowlists.StagingMixedBuildsEnabledList {
MarkDacek6f6b9622023-05-02 16:28:55 +0000278 if isAllowlistMisconfiguredForModule(module, mixedBuildsEnabled, mixedBuildsDisabled) {
MarkDacekf47e1422023-04-19 16:47:36 +0000279 retval = append(retval, module)
280 }
281 }
282 }
283
284 for module, _ := range forceEnabledModules {
MarkDacek6f6b9622023-05-02 16:28:55 +0000285 if isAllowlistMisconfiguredForModule(module, mixedBuildsEnabled, mixedBuildsDisabled) {
MarkDacekf47e1422023-04-19 16:47:36 +0000286 retval = append(retval, module)
287 }
288 }
289 return retval
290}
291
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800292func writeJsonModuleGraphAndActions(ctx *android.Context, cmdArgs android.CmdArgs) {
293 graphFile, graphErr := os.Create(shared.JoinPath(topDir, cmdArgs.ModuleGraphFile))
Sasha Smundak1845f422022-12-13 14:18:58 -0800294 maybeQuit(graphErr, "graph err")
kgui67007242022-01-25 13:50:25 +0800295 defer graphFile.Close()
Sasha Smundak1845f422022-12-13 14:18:58 -0800296 actionsFile, actionsErr := os.Create(shared.JoinPath(topDir, cmdArgs.ModuleActionsFile))
297 maybeQuit(actionsErr, "actions err")
kgui67007242022-01-25 13:50:25 +0800298 defer actionsFile.Close()
299 ctx.Context.PrintJSONGraphAndActions(graphFile, actionsFile)
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200300}
301
Sasha Smundak1845f422022-12-13 14:18:58 -0800302func writeBuildGlobsNinjaFile(ctx *android.Context) []string {
Chris Parsons715b08f2022-03-22 19:23:40 -0400303 ctx.EventHandler.Begin("globs_ninja_file")
304 defer ctx.EventHandler.End("globs_ninja_file")
305
Sasha Smundak1845f422022-12-13 14:18:58 -0800306 globDir := bootstrap.GlobDirectory(ctx.Config().SoongOutDir(), globListDir)
Lukacs T. Berkic357c812023-06-20 09:30:06 +0000307 err := bootstrap.WriteBuildGlobsNinjaFile(&bootstrap.GlobSingleton{
Chris Parsons715b08f2022-03-22 19:23:40 -0400308 GlobLister: ctx.Globs,
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200309 GlobFile: globFile,
310 GlobDir: globDir,
Chris Parsons715b08f2022-03-22 19:23:40 -0400311 SrcDir: ctx.SrcDir(),
Sasha Smundak1845f422022-12-13 14:18:58 -0800312 }, ctx.Config())
Lukacs T. Berkic357c812023-06-20 09:30:06 +0000313 maybeQuit(err, "")
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200314 return bootstrap.GlobFileListFiles(globDir)
315}
316
Paul Duffin780a1852022-11-05 10:17:12 +0000317func writeDepFile(outputFile string, eventHandler *metrics.EventHandler, ninjaDeps []string) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400318 eventHandler.Begin("ninja_deps")
319 defer eventHandler.End("ninja_deps")
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200320 depFile := shared.JoinPath(topDir, outputFile+".d")
321 err := deptools.WriteDepFile(depFile, outputFile, ninjaDeps)
Sasha Smundak1845f422022-12-13 14:18:58 -0800322 maybeQuit(err, "error writing depfile '%s'", depFile)
Paul Duffin0c09a432022-11-05 15:28:04 +0000323}
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200324
Paul Duffin0c09a432022-11-05 15:28:04 +0000325// runSoongOnlyBuild runs the standard Soong build in a number of different modes.
Sasha Smundak1845f422022-12-13 14:18:58 -0800326func runSoongOnlyBuild(ctx *android.Context, extraNinjaDeps []string) string {
Paul Duffin39eae8f2022-11-05 14:59:52 +0000327 ctx.EventHandler.Begin("soong_build")
328 defer ctx.EventHandler.End("soong_build")
329
Paul Duffin0c09a432022-11-05 15:28:04 +0000330 var stopBefore bootstrap.StopBefore
Sasha Smundak1845f422022-12-13 14:18:58 -0800331 switch ctx.Config().BuildMode {
332 case android.GenerateModuleGraph:
Paul Duffin0c09a432022-11-05 15:28:04 +0000333 stopBefore = bootstrap.StopBeforeWriteNinja
Usta Shrestha7fae6952022-12-21 11:46:28 -0500334 case android.GenerateQueryView, android.GenerateDocFile:
Paul Duffin0c09a432022-11-05 15:28:04 +0000335 stopBefore = bootstrap.StopBeforePrepareBuildActions
Sasha Smundak1845f422022-12-13 14:18:58 -0800336 default:
Paul Duffin0c09a432022-11-05 15:28:04 +0000337 stopBefore = bootstrap.DoEverything
338 }
339
Lukacs T. Berkic357c812023-06-20 09:30:06 +0000340 ninjaDeps, err := bootstrap.RunBlueprint(cmdlineArgs.Args, stopBefore, ctx.Context, ctx.Config())
341 maybeQuit(err, "")
Paul Duffin0c09a432022-11-05 15:28:04 +0000342 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
343
Sasha Smundak1845f422022-12-13 14:18:58 -0800344 globListFiles := writeBuildGlobsNinjaFile(ctx)
Paul Duffin0c09a432022-11-05 15:28:04 +0000345 ninjaDeps = append(ninjaDeps, globListFiles...)
346
347 // Convert the Soong module graph into Bazel BUILD files.
Sasha Smundak1845f422022-12-13 14:18:58 -0800348 switch ctx.Config().BuildMode {
349 case android.GenerateQueryView:
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800350 queryviewMarkerFile := cmdlineArgs.BazelQueryViewDir + ".marker"
Sasha Smundak1845f422022-12-13 14:18:58 -0800351 runQueryView(cmdlineArgs.BazelQueryViewDir, queryviewMarkerFile, ctx)
Paul Duffin0c09a432022-11-05 15:28:04 +0000352 writeDepFile(queryviewMarkerFile, ctx.EventHandler, ninjaDeps)
353 return queryviewMarkerFile
Sasha Smundak1845f422022-12-13 14:18:58 -0800354 case android.GenerateModuleGraph:
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800355 writeJsonModuleGraphAndActions(ctx, cmdlineArgs)
356 writeDepFile(cmdlineArgs.ModuleGraphFile, ctx.EventHandler, ninjaDeps)
357 return cmdlineArgs.ModuleGraphFile
Sasha Smundak1845f422022-12-13 14:18:58 -0800358 case android.GenerateDocFile:
Paul Duffin0c09a432022-11-05 15:28:04 +0000359 // TODO: we could make writeDocs() return the list of documentation files
360 // written and add them to the .d file. Then soong_docs would be re-run
361 // whenever one is deleted.
Sasha Smundak1845f422022-12-13 14:18:58 -0800362 err := writeDocs(ctx, shared.JoinPath(topDir, cmdlineArgs.DocFile))
363 maybeQuit(err, "error building Soong documentation")
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800364 writeDepFile(cmdlineArgs.DocFile, ctx.EventHandler, ninjaDeps)
365 return cmdlineArgs.DocFile
Sasha Smundak1845f422022-12-13 14:18:58 -0800366 default:
Paul Duffin0c09a432022-11-05 15:28:04 +0000367 // The actual output (build.ninja) was written in the RunBlueprint() call
368 // above
369 writeDepFile(cmdlineArgs.OutFile, ctx.EventHandler, ninjaDeps)
Jeongik Chaa87506f2023-06-01 23:16:41 +0900370 if needToWriteNinjaHint(ctx) {
Jeongik Cha591366d2023-05-08 11:32:52 +0900371 writeNinjaHint(ctx)
372 }
Paul Duffinb713ddf2022-11-05 16:14:30 +0000373 return cmdlineArgs.OutFile
Paul Duffin0c09a432022-11-05 15:28:04 +0000374 }
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200375}
376
377// soong_ui dumps the available environment variables to
378// soong.environment.available . Then soong_build itself is run with an empty
379// environment so that the only way environment variables can be accessed is
380// using Config, which tracks access to them.
381
382// At the end of the build, a file called soong.environment.used is written
383// containing the current value of all used environment variables. The next
384// time soong_ui is run, it checks whether any environment variables that was
385// used had changed and if so, it deletes soong.environment.used to cause a
386// rebuild.
387//
388// The dependency of build.ninja on soong.environment.used is declared in
389// build.ninja.d
390func parseAvailableEnv() map[string]string {
391 if availableEnvFile == "" {
392 fmt.Fprintf(os.Stderr, "--available_env not set\n")
393 os.Exit(1)
394 }
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200395 result, err := shared.EnvFromFile(shared.JoinPath(topDir, availableEnvFile))
Sasha Smundak1845f422022-12-13 14:18:58 -0800396 maybeQuit(err, "error reading available environment file '%s'", availableEnvFile)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200397 return result
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200398}
399
Colin Cross3f40fa42015-01-30 17:27:36 -0800400func main() {
401 flag.Parse()
402
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100403 shared.ReexecWithDelveMaybe(delveListen, delvePath)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100404 android.InitSandbox(topDir)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100405
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200406 availableEnv := parseAvailableEnv()
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800407 configuration, err := android.NewConfig(cmdlineArgs, availableEnv)
Sasha Smundak1845f422022-12-13 14:18:58 -0800408 maybeQuit(err, "")
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100409 if configuration.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
410 configuration.SetAllowMissingDependencies()
411 }
412
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800413 extraNinjaDeps := []string{configuration.ProductVariablesFileName, usedEnvFile}
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100414 if shared.IsDebugging() {
Colin Crossaa812d12019-06-19 13:33:24 -0700415 // Add a non-existent file to the dependencies so that soong_build will rerun when the debugger is
416 // enabled even if it completed successfully.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200417 extraNinjaDeps = append(extraNinjaDeps, filepath.Join(configuration.SoongOutDir(), "always_rerun_for_delve"))
Colin Crossaa812d12019-06-19 13:33:24 -0700418 }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500419
Dan Willemsenccf36aa2022-04-20 23:11:43 -0700420 // Bypass configuration.Getenv, as LOG_DIR does not need to be dependency tracked. By definition, it will
421 // change between every CI build, so tracking it would require re-running Soong for every build.
Sasha Smundak1845f422022-12-13 14:18:58 -0800422 metricsDir := availableEnv["LOG_DIR"]
Dan Willemsenccf36aa2022-04-20 23:11:43 -0700423
Joe Onorato2e5e4012022-06-07 17:16:08 -0700424 ctx := newContext(configuration)
Colin Cross46b0c752023-10-27 14:56:12 -0700425 android.StartBackgroundMetrics(configuration)
Joe Onorato2e5e4012022-06-07 17:16:08 -0700426
Sasha Smundak1845f422022-12-13 14:18:58 -0800427 var finalOutputFile string
Joe Onorato2e5e4012022-06-07 17:16:08 -0700428
Sasha Smundak1845f422022-12-13 14:18:58 -0800429 // Run Soong for a specific activity, like bp2build, queryview
430 // or the actual Soong build for the build.ninja file.
431 switch configuration.BuildMode {
432 case android.SymlinkForest:
433 finalOutputFile = runSymlinkForestCreation(ctx, extraNinjaDeps, metricsDir)
434 case android.Bp2build:
435 // Run the alternate pipeline of bp2build mutators and singleton to convert
436 // Blueprint to BUILD files before everything else.
437 finalOutputFile = runBp2Build(ctx, extraNinjaDeps, metricsDir)
Sasha Smundak1845f422022-12-13 14:18:58 -0800438 default:
439 ctx.Register()
MarkDacekf47e1422023-04-19 16:47:36 +0000440 isMixedBuildsEnabled := configuration.IsMixedBuildsEnabled()
441 if isMixedBuildsEnabled {
Sasha Smundak1845f422022-12-13 14:18:58 -0800442 finalOutputFile = runMixedModeBuild(ctx, extraNinjaDeps)
MarkDacekf47e1422023-04-19 16:47:36 +0000443 if cmdlineArgs.EnsureAllowlistIntegrity {
444 if err := checkForAllowlistIntegrityError(configuration, cmdlineArgs.BazelModeStaging); err != nil {
445 maybeQuit(err, "")
446 }
447 }
Sasha Smundak1845f422022-12-13 14:18:58 -0800448 } else {
449 finalOutputFile = runSoongOnlyBuild(ctx, extraNinjaDeps)
450 }
451 writeMetrics(configuration, ctx.EventHandler, metricsDir)
452 }
Chris Parsonsc83398f2023-05-31 18:41:41 +0000453
454 // Register this environment variablesas being an implicit dependencies of
455 // soong_build. Changes to this environment variable will result in
456 // retriggering soong_build.
457 configuration.Getenv("USE_BAZEL_VERSION")
458
Chris Parsonsa3ae0072023-05-10 21:10:08 +0000459 writeUsedEnvironmentFile(configuration)
460
461 // Touch the output file so that it's the newest file created by soong_build.
462 // This is necessary because, if soong_build generated any files which
463 // are ninja inputs to the main output file, then ninja would superfluously
464 // rebuild this output file on the next build invocation.
465 touch(shared.JoinPath(topDir, finalOutputFile))
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100466}
467
Chris Parsonsa3ae0072023-05-10 21:10:08 +0000468func writeUsedEnvironmentFile(configuration android.Config) {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200469 if usedEnvFile == "" {
470 return
471 }
472
473 path := shared.JoinPath(topDir, usedEnvFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100474 data, err := shared.EnvFileContents(configuration.EnvDeps())
Sasha Smundak1845f422022-12-13 14:18:58 -0800475 maybeQuit(err, "error writing used environment file '%s'\n", usedEnvFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100476
Usta Shrestha2ba28a32022-10-24 11:33:09 -0400477 if preexistingData, err := os.ReadFile(path); err != nil {
478 if !os.IsNotExist(err) {
Sasha Smundak1845f422022-12-13 14:18:58 -0800479 maybeQuit(err, "error reading used environment file '%s'", usedEnvFile)
Usta Shrestha2ba28a32022-10-24 11:33:09 -0400480 }
481 } else if bytes.Equal(preexistingData, data) {
482 // used environment file is unchanged
483 return
484 }
Sasha Smundak1845f422022-12-13 14:18:58 -0800485 err = os.WriteFile(path, data, 0666)
486 maybeQuit(err, "error writing used environment file '%s'", usedEnvFile)
Colin Cross3f40fa42015-01-30 17:27:36 -0800487}
Jingwen Chen5ba7e472020-07-15 10:06:41 +0000488
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200489func touch(path string) {
490 f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
Sasha Smundak1845f422022-12-13 14:18:58 -0800491 maybeQuit(err, "Error touching '%s'", path)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200492 err = f.Close()
Sasha Smundak1845f422022-12-13 14:18:58 -0800493 maybeQuit(err, "Error touching '%s'", path)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200494
495 currentTime := time.Now().Local()
496 err = os.Chtimes(path, currentTime, currentTime)
Sasha Smundak1845f422022-12-13 14:18:58 -0800497 maybeQuit(err, "error touching '%s'", path)
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400498}
499
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400500// Read the bazel.list file that the Soong Finder already dumped earlier (hopefully)
501// It contains the locations of BUILD files, BUILD.bazel files, etc. in the source dir
502func getExistingBazelRelatedFiles(topDir string) ([]string, error) {
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200503 bazelFinderFile := filepath.Join(filepath.Dir(cmdlineArgs.ModuleListFile), "bazel.list")
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400504 if !filepath.IsAbs(bazelFinderFile) {
505 // Assume this was a relative path under topDir
506 bazelFinderFile = filepath.Join(topDir, bazelFinderFile)
507 }
Sasha Smundak1845f422022-12-13 14:18:58 -0800508 return readFileLines(bazelFinderFile)
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400509}
510
Spandan Das5af0bd32022-09-28 20:43:08 +0000511func bazelArtifacts() []string {
512 return []string{
513 "bazel-bin",
514 "bazel-genfiles",
515 "bazel-out",
516 "bazel-testlogs",
Usta (Tsering) Shresthac4c07b12022-11-08 18:31:14 -0500517 "bazel-workspace",
Spandan Das5af0bd32022-09-28 20:43:08 +0000518 "bazel-" + filepath.Base(topDir),
519 }
520}
521
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000522// This could in theory easily be separated into a binary that generically
523// merges two directories into a symlink tree. The main obstacle is that this
524// function currently depends on both Bazel-specific knowledge (the existence
525// of bazel-* symlinks) and configuration (the set of BUILD.bazel files that
526// should and should not be kept)
527//
528// Ideally, bp2build would write a file that contains instructions to the
529// symlink tree creation binary. Then the latter would not need to depend on
530// the very heavy-weight machinery of soong_build .
Sasha Smundak1845f422022-12-13 14:18:58 -0800531func runSymlinkForestCreation(ctx *android.Context, extraNinjaDeps []string, metricsDir string) string {
Usta Shresthada15c612022-11-08 14:12:36 -0500532 var ninjaDeps []string
533 var mkdirCount, symlinkCount uint64
534
Paul Duffinb4e8d912022-11-04 13:35:50 +0000535 ctx.EventHandler.Do("symlink_forest", func() {
Usta (Tsering) Shrestha93b2a9b2022-12-01 05:55:35 +0000536 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Sasha Smundak1845f422022-12-13 14:18:58 -0800537 verbose := ctx.Config().IsEnvTrue("BP2BUILD_VERBOSE")
Usta (Tsering) Shrestha93b2a9b2022-12-01 05:55:35 +0000538
539 // PlantSymlinkForest() returns all the directories that were readdir()'ed.
540 // Such a directory SHOULD be added to `ninjaDeps` so that a child directory
541 // or file created/deleted under it would trigger an update of the symlink forest.
Sasha Smundak1845f422022-12-13 14:18:58 -0800542 generatedRoot := shared.JoinPath(ctx.Config().SoongOutDir(), "bp2build")
543 workspaceRoot := shared.JoinPath(ctx.Config().SoongOutDir(), "workspace")
Usta Shresthada15c612022-11-08 14:12:36 -0500544 var symlinkForestDeps []string
Usta (Tsering) Shrestha93b2a9b2022-12-01 05:55:35 +0000545 ctx.EventHandler.Do("plant", func() {
Usta Shresthada15c612022-11-08 14:12:36 -0500546 symlinkForestDeps, mkdirCount, symlinkCount = bp2build.PlantSymlinkForest(
Sasha Smundak1845f422022-12-13 14:18:58 -0800547 verbose, topDir, workspaceRoot, generatedRoot, excludedFromSymlinkForest(ctx, verbose))
Usta (Tsering) Shrestha93b2a9b2022-12-01 05:55:35 +0000548 })
Usta Shresthada15c612022-11-08 14:12:36 -0500549 ninjaDeps = append(ninjaDeps, symlinkForestDeps...)
Usta (Tsering) Shrestha93b2a9b2022-12-01 05:55:35 +0000550 })
Usta Shresthada15c612022-11-08 14:12:36 -0500551
552 writeDepFile(cmdlineArgs.SymlinkForestMarker, ctx.EventHandler, ninjaDeps)
553 touch(shared.JoinPath(topDir, cmdlineArgs.SymlinkForestMarker))
usta4f5d2c12022-10-28 23:32:01 -0400554 codegenMetrics := bp2build.ReadCodegenMetrics(metricsDir)
555 if codegenMetrics == nil {
556 m := bp2build.CreateCodegenMetrics()
557 codegenMetrics = &m
558 } else {
559 //TODO (usta) we cannot determine if we loaded a stale file, i.e. from an unrelated prior
560 //invocation of codegen. We should simply use a separate .pb file
561 }
Usta Shresthada15c612022-11-08 14:12:36 -0500562 codegenMetrics.SetSymlinkCount(symlinkCount)
563 codegenMetrics.SetMkDirCount(mkdirCount)
Paul Duffinb4e8d912022-11-04 13:35:50 +0000564 writeBp2BuildMetrics(codegenMetrics, ctx.EventHandler, metricsDir)
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800565 return cmdlineArgs.SymlinkForestMarker
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000566}
567
Sasha Smundak1845f422022-12-13 14:18:58 -0800568func excludedFromSymlinkForest(ctx *android.Context, verbose bool) []string {
569 excluded := bazelArtifacts()
570 if cmdlineArgs.OutDir[0] != '/' {
571 excluded = append(excluded, cmdlineArgs.OutDir)
572 }
573
574 // Find BUILD files in the srcDir which are not in the allowlist
575 // (android.Bp2BuildConversionAllowlist#ShouldKeepExistingBuildFileForDir)
576 // and return their paths so they can be left out of the Bazel workspace dir (i.e. ignored)
577 existingBazelFiles, err := getExistingBazelRelatedFiles(topDir)
578 maybeQuit(err, "Error determining existing Bazel-related files")
579
580 for _, path := range existingBazelFiles {
581 fullPath := shared.JoinPath(topDir, path)
582 fileInfo, err2 := os.Stat(fullPath)
583 if err2 != nil {
584 // Warn about error, but continue trying to check files
585 fmt.Fprintf(os.Stderr, "WARNING: Error accessing path '%s', err: %s\n", fullPath, err2)
586 continue
587 }
588 // Exclude only files named 'BUILD' or 'BUILD.bazel' and unless forcibly kept
589 if fileInfo.IsDir() ||
590 (fileInfo.Name() != "BUILD" && fileInfo.Name() != "BUILD.bazel") ||
591 ctx.Config().Bp2buildPackageConfig.ShouldKeepExistingBuildFileForDir(filepath.Dir(path)) {
592 // Don't ignore this existing build file
593 continue
594 }
595 if verbose {
596 fmt.Fprintf(os.Stderr, "Ignoring existing BUILD file: %s\n", path)
597 }
598 excluded = append(excluded, path)
599 }
600
601 // Temporarily exclude stuff to make `bazel build //external/...` (and `bazel build //frameworks/...`) work
602 excluded = append(excluded,
603 // FIXME: 'autotest_lib' is a symlink back to external/autotest, and this causes an infinite
604 // symlink expansion error for Bazel
605 "external/autotest/venv/autotest_lib",
606 "external/autotest/autotest_lib",
607 "external/autotest/client/autotest_lib/client",
608
609 // FIXME: The external/google-fruit/extras/bazel_root/third_party/fruit dir is poison
610 // It contains several symlinks back to real source dirs, and those source dirs contain
611 // BUILD files we want to ignore
612 "external/google-fruit/extras/bazel_root/third_party/fruit",
613
614 // FIXME: 'frameworks/compile/slang' has a filegroup error due to an escaping issue
615 "frameworks/compile/slang",
Sasha Smundak1845f422022-12-13 14:18:58 -0800616 )
617 return excluded
618}
619
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500620// Run Soong in the bp2build mode. This creates a standalone context that registers
621// an alternate pipeline of mutators and singletons specifically for generating
622// Bazel BUILD files instead of Ninja files.
Sasha Smundak1845f422022-12-13 14:18:58 -0800623func runBp2Build(ctx *android.Context, extraNinjaDeps []string, metricsDir string) string {
usta4f5d2c12022-10-28 23:32:01 -0400624 var codegenMetrics *bp2build.CodegenMetrics
Paul Duffinb4e8d912022-11-04 13:35:50 +0000625 ctx.EventHandler.Do("bp2build", func() {
Jingwen Cheneb76c432021-01-28 08:22:12 -0500626
Chris Parsons8152a942023-06-06 16:17:50 +0000627 ctx.EventHandler.Do("read_build", func() {
Chris Parsons5011e612023-09-13 23:33:20 +0000628 existingBazelFiles, err := getExistingBazelRelatedFiles(topDir)
629 maybeQuit(err, "Error determining existing Bazel-related files")
630
631 err = ctx.RegisterExistingBazelTargets(topDir, existingBazelFiles)
632 maybeQuit(err, "Error parsing existing Bazel-related files")
Chris Parsons8152a942023-06-06 16:17:50 +0000633 })
634
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400635 // Propagate "allow misssing dependencies" bit. This is normally set in
Paul Duffinb4e8d912022-11-04 13:35:50 +0000636 // newContext(), but we create ctx without calling that method.
Sasha Smundak1845f422022-12-13 14:18:58 -0800637 ctx.SetAllowMissingDependencies(ctx.Config().AllowMissingDependencies())
638 ctx.SetNameInterface(newNameResolver(ctx.Config()))
Paul Duffinb4e8d912022-11-04 13:35:50 +0000639 ctx.RegisterForBazelConversion()
640 ctx.SetModuleListFile(cmdlineArgs.ModuleListFile)
Chris Parsons3a5c1702023-06-13 01:10:20 +0000641 // Skip cloning modules during bp2build's blueprint run. Some mutators set
642 // bp2build-related module values which should be preserved during codegen.
643 ctx.SkipCloneModulesAfterMutators = true
Jingwen Cheneb76c432021-01-28 08:22:12 -0500644
Usta Shresthaa117c582022-10-04 12:13:25 -0400645 var ninjaDeps []string
646 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
647
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400648 // Run the loading and analysis pipeline to prepare the graph of regular
649 // Modules parsed from Android.bp files, and the BazelTargetModules mapped
650 // from the regular Modules.
Paul Duffinb4e8d912022-11-04 13:35:50 +0000651 ctx.EventHandler.Do("bootstrap", func() {
Usta Shresthaa117c582022-10-04 12:13:25 -0400652 blueprintArgs := cmdlineArgs
Lukacs T. Berkic357c812023-06-20 09:30:06 +0000653 bootstrapDeps, err := bootstrap.RunBlueprint(blueprintArgs.Args,
Sasha Smundak1845f422022-12-13 14:18:58 -0800654 bootstrap.StopBeforePrepareBuildActions, ctx.Context, ctx.Config())
Lukacs T. Berkic357c812023-06-20 09:30:06 +0000655 maybeQuit(err, "")
Usta Shresthaa117c582022-10-04 12:13:25 -0400656 ninjaDeps = append(ninjaDeps, bootstrapDeps...)
657 })
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200658
Sasha Smundak1845f422022-12-13 14:18:58 -0800659 globListFiles := writeBuildGlobsNinjaFile(ctx)
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400660 ninjaDeps = append(ninjaDeps, globListFiles...)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200661
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400662 // Run the code-generation phase to convert BazelTargetModules to BUILD files
Usta Shresthaa117c582022-10-04 12:13:25 -0400663 // and print conversion codegenMetrics to the user.
Cole Faustb85d1a12022-11-08 18:14:01 -0800664 codegenContext := bp2build.NewCodegenContext(ctx.Config(), ctx, bp2build.Bp2Build, topDir)
ustaaaf2fd12023-07-01 11:40:36 -0400665 codegenMetrics = bp2build.Codegen(codegenContext)
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200666
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400667 ninjaDeps = append(ninjaDeps, codegenContext.AdditionalNinjaDeps()...)
Chris Parsons715b08f2022-03-22 19:23:40 -0400668
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800669 writeDepFile(cmdlineArgs.Bp2buildMarker, ctx.EventHandler, ninjaDeps)
670 touch(shared.JoinPath(topDir, cmdlineArgs.Bp2buildMarker))
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400671 })
Chris Parsons715b08f2022-03-22 19:23:40 -0400672
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200673 // Only report metrics when in bp2build mode. The metrics aren't relevant
674 // for queryview, since that's a total repo-wide conversion and there's a
675 // 1:1 mapping for each module.
Sasha Smundak1845f422022-12-13 14:18:58 -0800676 if ctx.Config().IsEnvTrue("BP2BUILD_VERBOSE") {
Usta Shresthaa117c582022-10-04 12:13:25 -0400677 codegenMetrics.Print()
Sasha Smundak0fd93e02022-05-19 19:34:31 -0700678 }
Paul Duffinb4e8d912022-11-04 13:35:50 +0000679 writeBp2BuildMetrics(codegenMetrics, ctx.EventHandler, metricsDir)
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800680 return cmdlineArgs.Bp2buildMarker
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500681}
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500682
683// Write Bp2Build metrics into $LOG_DIR
Paul Duffinf4906562022-11-05 14:21:16 +0000684func writeBp2BuildMetrics(codegenMetrics *bp2build.CodegenMetrics, eventHandler *metrics.EventHandler, metricsDir string) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400685 for _, event := range eventHandler.CompletedEvents() {
usta4f5d2c12022-10-28 23:32:01 -0400686 codegenMetrics.AddEvent(&bp2build_metrics_proto.Event{
687 Name: event.Id,
688 StartTime: uint64(event.Start.UnixNano()),
689 RealTime: event.RuntimeNanoseconds(),
690 })
Chris Parsons715b08f2022-03-22 19:23:40 -0400691 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500692 if len(metricsDir) < 1 {
693 fmt.Fprintf(os.Stderr, "\nMissing required env var for generating bp2build metrics: LOG_DIR\n")
694 os.Exit(1)
695 }
Chris Parsons715b08f2022-03-22 19:23:40 -0400696 codegenMetrics.Write(metricsDir)
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500697}
MarkDacek0d5bca52022-10-10 20:07:48 +0000698
Sasha Smundak1845f422022-12-13 14:18:58 -0800699func readFileLines(path string) ([]string, error) {
700 data, err := os.ReadFile(path)
701 if err == nil {
702 return strings.Split(strings.TrimSpace(string(data)), "\n"), nil
MarkDacek0d5bca52022-10-10 20:07:48 +0000703 }
Sasha Smundak1845f422022-12-13 14:18:58 -0800704 return nil, err
705
706}
707func maybeQuit(err error, format string, args ...interface{}) {
708 if err == nil {
709 return
710 }
711 if format != "" {
712 fmt.Fprintln(os.Stderr, fmt.Sprintf(format, args...)+": "+err.Error())
713 } else {
714 fmt.Fprintln(os.Stderr, err)
715 }
716 os.Exit(1)
MarkDacek0d5bca52022-10-10 20:07:48 +0000717}