blob: 5c34fd8616c7b7aa4d0a7025f2c598f1b11d38da [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"
Spandan Das5af0bd32022-09-28 20:43:08 +000027 "android/soong/bazel"
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020028 "android/soong/bp2build"
Lukacs T. Berki7690c092021-02-26 14:27:36 +010029 "android/soong/shared"
Chris Parsons715b08f2022-03-22 19:23:40 -040030 "android/soong/ui/metrics/bp2build_metrics_proto"
Lukacs T. Berkie571dc32021-08-25 14:14:13 +020031
Colin Cross70b40592015-03-23 12:57:34 -070032 "github.com/google/blueprint/bootstrap"
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +020033 "github.com/google/blueprint/deptools"
Chris Parsons715b08f2022-03-22 19:23:40 -040034 "github.com/google/blueprint/metrics"
Dan Willemsen66213a62021-09-21 17:50:30 -070035 androidProtobuf "google.golang.org/protobuf/android"
Colin Cross3f40fa42015-01-30 17:27:36 -080036)
37
Colin Crosse87040b2017-12-11 15:52:26 -080038var (
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020039 topDir string
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020040 availableEnvFile string
41 usedEnvFile string
42
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +020043 globFile string
44 globListDir string
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020045 delveListen string
46 delvePath string
47
Sasha Smundakaf5ca922022-12-12 21:23:34 -080048 cmdlineArgs android.CmdArgs
Colin Crosse87040b2017-12-11 15:52:26 -080049)
50
51func init() {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020052 // Flags that make sense in every mode
Lukacs T. Berki7690c092021-02-26 14:27:36 +010053 flag.StringVar(&topDir, "top", "", "Top directory of the Android source tree")
Sasha Smundakaf5ca922022-12-12 21:23:34 -080054 flag.StringVar(&cmdlineArgs.SoongOutDir, "soong_out", "", "Soong output directory (usually $TOP/out/soong)")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020055 flag.StringVar(&availableEnvFile, "available_env", "", "File containing available environment variables")
56 flag.StringVar(&usedEnvFile, "used_env", "", "File containing used environment variables")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020057 flag.StringVar(&globFile, "globFile", "build-globs.ninja", "the Ninja file of globs to output")
58 flag.StringVar(&globListDir, "globListDir", "", "the directory containing the glob list files")
Sasha Smundakaf5ca922022-12-12 21:23:34 -080059 flag.StringVar(&cmdlineArgs.OutDir, "out", "", "the ninja builddir directory")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020060 flag.StringVar(&cmdlineArgs.ModuleListFile, "l", "", "file that lists filepaths to parse")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020061
62 // Debug flags
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +010063 flag.StringVar(&delveListen, "delve_listen", "", "Delve port to listen on for debugging")
64 flag.StringVar(&delvePath, "delve_path", "", "Path to Delve. Only used if --delve_listen is set")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020065 flag.StringVar(&cmdlineArgs.Cpuprofile, "cpuprofile", "", "write cpu profile to file")
66 flag.StringVar(&cmdlineArgs.TraceFile, "trace", "", "write trace to file")
67 flag.StringVar(&cmdlineArgs.Memprofile, "memprofile", "", "write memory profile to file")
68 flag.BoolVar(&cmdlineArgs.NoGC, "nogc", false, "turn off GC for debugging")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020069
70 // Flags representing various modes soong_build can run in
Sasha Smundakaf5ca922022-12-12 21:23:34 -080071 flag.StringVar(&cmdlineArgs.ModuleGraphFile, "module_graph_file", "", "JSON module graph file to output")
72 flag.StringVar(&cmdlineArgs.ModuleActionsFile, "module_actions_file", "", "JSON file to output inputs/outputs of actions of modules")
73 flag.StringVar(&cmdlineArgs.DocFile, "soong_docs", "", "build documentation file to output")
74 flag.StringVar(&cmdlineArgs.BazelQueryViewDir, "bazel_queryview_dir", "", "path to the bazel queryview directory relative to --top")
75 flag.StringVar(&cmdlineArgs.BazelApiBp2buildDir, "bazel_api_bp2build_dir", "", "path to the bazel api_bp2build directory relative to --top")
76 flag.StringVar(&cmdlineArgs.Bp2buildMarker, "bp2build_marker", "", "If set, run bp2build, touch the specified marker file then exit")
77 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 +020078 flag.StringVar(&cmdlineArgs.OutFile, "o", "build.ninja", "the Ninja file to output")
MarkDacekd06db5d2022-11-29 00:47:59 +000079 flag.StringVar(&cmdlineArgs.BazelForceEnabledModules, "bazel-force-enabled-modules", "", "additional modules to build with Bazel. Comma-delimited")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020080 flag.BoolVar(&cmdlineArgs.EmptyNinjaFile, "empty-ninja-file", false, "write out a 0-byte ninja file")
Chris Parsonsef615e52022-08-18 22:04:11 -040081 flag.BoolVar(&cmdlineArgs.BazelMode, "bazel-mode", false, "use bazel for analysis of certain modules")
Jingwen Chene647db82022-11-01 11:28:29 +000082 flag.BoolVar(&cmdlineArgs.BazelModeStaging, "bazel-mode-staging", false, "use bazel for analysis of certain near-ready modules")
Chris Parsonsef615e52022-08-18 22:04:11 -040083 flag.BoolVar(&cmdlineArgs.BazelModeDev, "bazel-mode-dev", false, "use bazel for analysis of a large number of modules (less stable)")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020084
Sasha Smundakaf5ca922022-12-12 21:23:34 -080085 // Flags that probably shouldn't be flags of soong_build, but we haven't found
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020086 // the time to remove them yet
Sasha Smundakaf5ca922022-12-12 21:23:34 -080087 flag.BoolVar(&cmdlineArgs.RunGoTests, "t", false, "build and run go tests during bootstrap")
Dan Willemsen66213a62021-09-21 17:50:30 -070088
89 // Disable deterministic randomization in the protobuf package, so incremental
90 // builds with unrelated Soong changes don't trigger large rebuilds (since we
91 // write out text protos in command lines, and command line changes trigger
92 // rebuilds).
93 androidProtobuf.DisableRand()
Colin Crosse87040b2017-12-11 15:52:26 -080094}
95
Jeff Gaston088e29e2017-11-29 16:47:17 -080096func newNameResolver(config android.Config) *android.NameResolver {
Paul Duffin3f7bf9f2022-11-08 12:21:15 +000097 return android.NewNameResolver(config)
Jeff Gaston088e29e2017-11-29 16:47:17 -080098}
99
Lukacs T. Berkiffc9e8d2021-09-07 17:54:38 +0200100func newContext(configuration android.Config) *android.Context {
Colin Crossae8600b2020-10-29 17:09:13 -0700101 ctx := android.NewContext(configuration)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400102 ctx.SetNameInterface(newNameResolver(configuration))
103 ctx.SetAllowMissingDependencies(configuration.AllowMissingDependencies())
Spandan Dasc5763832022-11-08 18:42:16 +0000104 ctx.AddIncludeTags(configuration.IncludeTags()...)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400105 return ctx
106}
107
Chris Parsonsf874e462022-05-10 13:50:12 -0400108// Bazel-enabled mode. Attaches a mutator to queue Bazel requests, adds a
109// BeforePrepareBuildActionsHook to invoke Bazel, and then uses Bazel metadata
110// for modules that should be handled by Bazel.
Paul Duffin0c09a432022-11-05 15:28:04 +0000111func runMixedModeBuild(configuration android.Config, ctx *android.Context, extraNinjaDeps []string) string {
Chris Parsonsf874e462022-05-10 13:50:12 -0400112 ctx.EventHandler.Begin("mixed_build")
113 defer ctx.EventHandler.End("mixed_build")
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200114
Chris Parsonsf874e462022-05-10 13:50:12 -0400115 bazelHook := func() error {
Sasha Smundak4975c822022-11-16 15:28:18 -0800116 return configuration.BazelContext.InvokeBazel(configuration, ctx)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200117 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400118 ctx.SetBeforePrepareBuildActionsHook(bazelHook)
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800119 ninjaDeps := bootstrap.RunBlueprint(cmdlineArgs.Args, bootstrap.DoEverything, ctx.Context, configuration)
Chris Parsons027881c2022-05-24 15:38:38 -0400120 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200121
MarkDacek0d5bca52022-10-10 20:07:48 +0000122 bazelPaths, err := readBazelPaths(configuration)
123 if err != nil {
124 panic("Bazel deps file not found: " + err.Error())
125 }
126 ninjaDeps = append(ninjaDeps, bazelPaths...)
127
Chris Parsonsf874e462022-05-10 13:50:12 -0400128 globListFiles := writeBuildGlobsNinjaFile(ctx, configuration.SoongOutDir(), configuration)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200129 ninjaDeps = append(ninjaDeps, globListFiles...)
130
Paul Duffin780a1852022-11-05 10:17:12 +0000131 writeDepFile(cmdlineArgs.OutFile, ctx.EventHandler, ninjaDeps)
Paul Duffin0c09a432022-11-05 15:28:04 +0000132 return cmdlineArgs.OutFile
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200133}
134
135// Run the code-generation phase to convert BazelTargetModules to BUILD files.
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200136func runQueryView(queryviewDir, queryviewMarker string, configuration android.Config, ctx *android.Context) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400137 ctx.EventHandler.Begin("queryview")
138 defer ctx.EventHandler.End("queryview")
Paul Duffinc6390592022-11-04 13:35:21 +0000139 codegenContext := bp2build.NewCodegenContext(configuration, ctx, bp2build.QueryView)
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200140 absoluteQueryViewDir := shared.JoinPath(topDir, queryviewDir)
Spandan Das5af0bd32022-09-28 20:43:08 +0000141 if err := createBazelWorkspace(codegenContext, absoluteQueryViewDir); err != nil {
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200142 fmt.Fprintf(os.Stderr, "%s", err)
143 os.Exit(1)
144 }
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200145
146 touch(shared.JoinPath(topDir, queryviewMarker))
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200147}
148
Spandan Das5af0bd32022-09-28 20:43:08 +0000149// Run the code-generation phase to convert API contributions to BUILD files.
150// Return marker file for the new synthetic workspace
Paul Duffinb4e8d912022-11-04 13:35:50 +0000151func runApiBp2build(configuration android.Config, ctx *android.Context, extraNinjaDeps []string) string {
Spandan Das5af0bd32022-09-28 20:43:08 +0000152 ctx.EventHandler.Begin("api_bp2build")
153 defer ctx.EventHandler.End("api_bp2build")
Paul Duffinb4e8d912022-11-04 13:35:50 +0000154 // Do not allow missing dependencies.
155 ctx.SetAllowMissingDependencies(false)
Spandan Das5af0bd32022-09-28 20:43:08 +0000156 ctx.RegisterForApiBazelConversion()
157
158 // Register the Android.bp files in the tree
159 // Add them to the workspace's .d file
160 ctx.SetModuleListFile(cmdlineArgs.ModuleListFile)
161 if paths, err := ctx.ListModulePaths("."); err == nil {
162 extraNinjaDeps = append(extraNinjaDeps, paths...)
163 } else {
164 panic(err)
165 }
166
167 // Run the loading and analysis phase
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800168 ninjaDeps := bootstrap.RunBlueprint(cmdlineArgs.Args,
Spandan Das5af0bd32022-09-28 20:43:08 +0000169 bootstrap.StopBeforePrepareBuildActions,
170 ctx.Context,
171 configuration)
172 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
173
174 // Add the globbed dependencies
175 globs := writeBuildGlobsNinjaFile(ctx, configuration.SoongOutDir(), configuration)
176 ninjaDeps = append(ninjaDeps, globs...)
177
178 // Run codegen to generate BUILD files
Paul Duffinc6390592022-11-04 13:35:21 +0000179 codegenContext := bp2build.NewCodegenContext(configuration, ctx, bp2build.ApiBp2build)
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800180 absoluteApiBp2buildDir := shared.JoinPath(topDir, cmdlineArgs.BazelApiBp2buildDir)
Spandan Das5af0bd32022-09-28 20:43:08 +0000181 if err := createBazelWorkspace(codegenContext, absoluteApiBp2buildDir); err != nil {
182 fmt.Fprintf(os.Stderr, "%s", err)
183 os.Exit(1)
184 }
185 ninjaDeps = append(ninjaDeps, codegenContext.AdditionalNinjaDeps()...)
186
187 // Create soong_injection repository
Spandan Das7b6d5332022-11-01 17:37:07 +0000188 soongInjectionFiles := bp2build.CreateSoongInjectionFiles(configuration, bp2build.CreateCodegenMetrics())
Spandan Das5af0bd32022-09-28 20:43:08 +0000189 absoluteSoongInjectionDir := shared.JoinPath(topDir, configuration.SoongOutDir(), bazel.SoongInjectionDirName)
190 for _, file := range soongInjectionFiles {
Spandan Das067210f2022-12-07 01:14:52 +0000191 // The API targets in api_bp2build workspace do not have any dependency on api_bp2build.
192 // But we need to create these files to prevent errors during Bazel analysis.
193 // These need to be created in Read-Write mode.
194 // This is because the subsequent step (bp2build in api domain analysis) creates them in Read-Write mode
195 // to allow users to edit/experiment in the synthetic workspace.
196 writeReadWriteFile(absoluteSoongInjectionDir, file)
Spandan Das5af0bd32022-09-28 20:43:08 +0000197 }
198
199 workspace := shared.JoinPath(configuration.SoongOutDir(), "api_bp2build")
200
201 excludes := bazelArtifacts()
202 // Exclude all src BUILD files
203 excludes = append(excludes, apiBuildFileExcludes()...)
204
Spandan Das394aa322022-11-03 17:02:10 +0000205 // Android.bp files for api surfaces are mounted to out/, but out/ should not be a
206 // dep for api_bp2build.
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800207 // Otherwise, api_bp2build will be run every single time
Spandan Das394aa322022-11-03 17:02:10 +0000208 excludes = append(excludes, configuration.OutDir())
209
Spandan Das5af0bd32022-09-28 20:43:08 +0000210 // Create the symlink forest
211 symlinkDeps := bp2build.PlantSymlinkForest(
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000212 configuration.IsEnvTrue("BP2BUILD_VERBOSE"),
Spandan Das5af0bd32022-09-28 20:43:08 +0000213 topDir,
214 workspace,
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800215 cmdlineArgs.BazelApiBp2buildDir,
Spandan Das5af0bd32022-09-28 20:43:08 +0000216 excludes)
217 ninjaDeps = append(ninjaDeps, symlinkDeps...)
218
219 workspaceMarkerFile := workspace + ".marker"
Paul Duffin780a1852022-11-05 10:17:12 +0000220 writeDepFile(workspaceMarkerFile, ctx.EventHandler, ninjaDeps)
Spandan Das5af0bd32022-09-28 20:43:08 +0000221 touch(shared.JoinPath(topDir, workspaceMarkerFile))
222 return workspaceMarkerFile
223}
224
225// With some exceptions, api_bp2build does not have any dependencies on the checked-in BUILD files
226// Exclude them from the generated workspace to prevent unrelated errors during the loading phase
227func apiBuildFileExcludes() []string {
228 ret := make([]string, 0)
229
230 srcs, err := getExistingBazelRelatedFiles(topDir)
231 if err != nil {
232 fmt.Fprintf(os.Stderr, "Error determining existing Bazel-related files: %s\n", err)
233 os.Exit(1)
234 }
235 for _, src := range srcs {
236 if src != "WORKSPACE" &&
237 src != "BUILD" &&
238 src != "BUILD.bazel" &&
239 !strings.HasPrefix(src, "build/bazel") &&
Spandan Das6b91a382022-11-30 02:17:06 +0000240 !strings.HasPrefix(src, "external/bazel-skylib") &&
Spandan Das5af0bd32022-09-28 20:43:08 +0000241 !strings.HasPrefix(src, "prebuilts/clang") {
242 ret = append(ret, src)
243 }
244 }
245 return ret
246}
247
Paul Duffin780a1852022-11-05 10:17:12 +0000248func writeMetrics(configuration android.Config, eventHandler *metrics.EventHandler, metricsDir string) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400249 if len(metricsDir) < 1 {
250 fmt.Fprintf(os.Stderr, "\nMissing required env var for generating soong metrics: LOG_DIR\n")
251 os.Exit(1)
252 }
253 metricsFile := filepath.Join(metricsDir, "soong_build_metrics.pb")
254 err := android.WriteMetrics(configuration, eventHandler, metricsFile)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200255 if err != nil {
256 fmt.Fprintf(os.Stderr, "error writing soong_build metrics %s: %s", metricsFile, err)
257 os.Exit(1)
258 }
259}
260
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800261func writeJsonModuleGraphAndActions(ctx *android.Context, cmdArgs android.CmdArgs) {
262 graphFile, graphErr := os.Create(shared.JoinPath(topDir, cmdArgs.ModuleGraphFile))
263 actionsFile, actionsErr := os.Create(shared.JoinPath(topDir, cmdArgs.ModuleActionsFile))
kgui67007242022-01-25 13:50:25 +0800264 if graphErr != nil || actionsErr != nil {
265 fmt.Fprintf(os.Stderr, "Graph err: %s, actions err: %s", graphErr, actionsErr)
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200266 os.Exit(1)
267 }
268
kgui67007242022-01-25 13:50:25 +0800269 defer graphFile.Close()
270 defer actionsFile.Close()
271 ctx.Context.PrintJSONGraphAndActions(graphFile, actionsFile)
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200272}
273
Chris Parsons715b08f2022-03-22 19:23:40 -0400274func writeBuildGlobsNinjaFile(ctx *android.Context, buildDir string, config interface{}) []string {
275 ctx.EventHandler.Begin("globs_ninja_file")
276 defer ctx.EventHandler.End("globs_ninja_file")
277
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200278 globDir := bootstrap.GlobDirectory(buildDir, globListDir)
279 bootstrap.WriteBuildGlobsNinjaFile(&bootstrap.GlobSingleton{
Chris Parsons715b08f2022-03-22 19:23:40 -0400280 GlobLister: ctx.Globs,
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200281 GlobFile: globFile,
282 GlobDir: globDir,
Chris Parsons715b08f2022-03-22 19:23:40 -0400283 SrcDir: ctx.SrcDir(),
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200284 }, config)
285 return bootstrap.GlobFileListFiles(globDir)
286}
287
Paul Duffin780a1852022-11-05 10:17:12 +0000288func writeDepFile(outputFile string, eventHandler *metrics.EventHandler, ninjaDeps []string) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400289 eventHandler.Begin("ninja_deps")
290 defer eventHandler.End("ninja_deps")
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200291 depFile := shared.JoinPath(topDir, outputFile+".d")
292 err := deptools.WriteDepFile(depFile, outputFile, ninjaDeps)
293 if err != nil {
294 fmt.Fprintf(os.Stderr, "Error writing depfile '%s': %s\n", depFile, err)
295 os.Exit(1)
296 }
297}
298
Jingwen Chen4fabaf52021-05-25 02:40:29 +0000299// doChosenActivity runs Soong for a specific activity, like bp2build, queryview
300// or the actual Soong build for the build.ninja file. Returns the top level
301// output file of the specific activity.
Paul Duffinf4906562022-11-05 14:21:16 +0000302func doChosenActivity(ctx *android.Context, configuration android.Config, extraNinjaDeps []string, metricsDir string) string {
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000303 if configuration.BuildMode == android.SymlinkForest {
Paul Duffinb713ddf2022-11-05 16:14:30 +0000304 return runSymlinkForestCreation(configuration, ctx, extraNinjaDeps, metricsDir)
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000305 } else if configuration.BuildMode == android.Bp2build {
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200306 // Run the alternate pipeline of bp2build mutators and singleton to convert
307 // Blueprint to BUILD files before everything else.
Paul Duffinb713ddf2022-11-05 16:14:30 +0000308 return runBp2Build(configuration, ctx, extraNinjaDeps, metricsDir)
Spandan Das5af0bd32022-09-28 20:43:08 +0000309 } else if configuration.BuildMode == android.ApiBp2build {
Paul Duffinb4e8d912022-11-04 13:35:50 +0000310 outputFile := runApiBp2build(configuration, ctx, extraNinjaDeps)
Paul Duffin39eae8f2022-11-05 14:59:52 +0000311 writeMetrics(configuration, ctx.EventHandler, metricsDir)
312 return outputFile
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200313 } else {
Paul Duffinb4e8d912022-11-04 13:35:50 +0000314 ctx.Register()
Paul Duffin39eae8f2022-11-05 14:59:52 +0000315
316 var outputFile string
Paul Duffin0c09a432022-11-05 15:28:04 +0000317 if configuration.IsMixedBuildsEnabled() {
Paul Duffin39eae8f2022-11-05 14:59:52 +0000318 outputFile = runMixedModeBuild(configuration, ctx, extraNinjaDeps)
Chris Parsons715b08f2022-03-22 19:23:40 -0400319 } else {
Paul Duffin39eae8f2022-11-05 14:59:52 +0000320 outputFile = runSoongOnlyBuild(configuration, ctx, extraNinjaDeps)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200321 }
Paul Duffin39eae8f2022-11-05 14:59:52 +0000322
323 writeMetrics(configuration, ctx.EventHandler, metricsDir)
324
325 return outputFile
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200326 }
Paul Duffin0c09a432022-11-05 15:28:04 +0000327}
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200328
Paul Duffin0c09a432022-11-05 15:28:04 +0000329// runSoongOnlyBuild runs the standard Soong build in a number of different modes.
330func runSoongOnlyBuild(configuration android.Config, ctx *android.Context, extraNinjaDeps []string) string {
Paul Duffin39eae8f2022-11-05 14:59:52 +0000331 ctx.EventHandler.Begin("soong_build")
332 defer ctx.EventHandler.End("soong_build")
333
Paul Duffin0c09a432022-11-05 15:28:04 +0000334 var stopBefore bootstrap.StopBefore
335 if configuration.BuildMode == android.GenerateModuleGraph {
336 stopBefore = bootstrap.StopBeforeWriteNinja
337 } else if configuration.BuildMode == android.GenerateQueryView || configuration.BuildMode == android.GenerateDocFile {
338 stopBefore = bootstrap.StopBeforePrepareBuildActions
339 } else {
340 stopBefore = bootstrap.DoEverything
341 }
342
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800343 ninjaDeps := bootstrap.RunBlueprint(cmdlineArgs.Args, stopBefore, ctx.Context, configuration)
Paul Duffin0c09a432022-11-05 15:28:04 +0000344 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
345
346 globListFiles := writeBuildGlobsNinjaFile(ctx, configuration.SoongOutDir(), configuration)
347 ninjaDeps = append(ninjaDeps, globListFiles...)
348
349 // Convert the Soong module graph into Bazel BUILD files.
350 if configuration.BuildMode == android.GenerateQueryView {
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800351 queryviewMarkerFile := cmdlineArgs.BazelQueryViewDir + ".marker"
352 runQueryView(cmdlineArgs.BazelQueryViewDir, queryviewMarkerFile, configuration, ctx)
Paul Duffin0c09a432022-11-05 15:28:04 +0000353 writeDepFile(queryviewMarkerFile, ctx.EventHandler, ninjaDeps)
354 return queryviewMarkerFile
355 } else if configuration.BuildMode == android.GenerateModuleGraph {
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800356 writeJsonModuleGraphAndActions(ctx, cmdlineArgs)
357 writeDepFile(cmdlineArgs.ModuleGraphFile, ctx.EventHandler, ninjaDeps)
358 return cmdlineArgs.ModuleGraphFile
Paul Duffin0c09a432022-11-05 15:28:04 +0000359 } else if configuration.BuildMode == android.GenerateDocFile {
360 // TODO: we could make writeDocs() return the list of documentation files
361 // written and add them to the .d file. Then soong_docs would be re-run
362 // whenever one is deleted.
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800363 if err := writeDocs(ctx, shared.JoinPath(topDir, cmdlineArgs.DocFile)); err != nil {
Paul Duffin0c09a432022-11-05 15:28:04 +0000364 fmt.Fprintf(os.Stderr, "error building Soong documentation: %s\n", err)
365 os.Exit(1)
366 }
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800367 writeDepFile(cmdlineArgs.DocFile, ctx.EventHandler, ninjaDeps)
368 return cmdlineArgs.DocFile
Paul Duffin0c09a432022-11-05 15:28:04 +0000369 } else {
370 // The actual output (build.ninja) was written in the RunBlueprint() call
371 // above
372 writeDepFile(cmdlineArgs.OutFile, ctx.EventHandler, ninjaDeps)
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 }
395
396 result, err := shared.EnvFromFile(shared.JoinPath(topDir, availableEnvFile))
397 if err != nil {
398 fmt.Fprintf(os.Stderr, "error reading available environment file '%s': %s\n", availableEnvFile, err)
399 os.Exit(1)
400 }
401
402 return result
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200403}
404
Colin Cross3f40fa42015-01-30 17:27:36 -0800405func main() {
406 flag.Parse()
407
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100408 shared.ReexecWithDelveMaybe(delveListen, delvePath)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100409 android.InitSandbox(topDir)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100410
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200411 availableEnv := parseAvailableEnv()
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800412 configuration, err := android.NewConfig(cmdlineArgs, availableEnv)
413 if err != nil {
414 fmt.Fprintf(os.Stderr, "%s", err)
415 os.Exit(1)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100416 }
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100417 if configuration.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
418 configuration.SetAllowMissingDependencies()
419 }
420
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800421 extraNinjaDeps := []string{configuration.ProductVariablesFileName, usedEnvFile}
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100422 if shared.IsDebugging() {
Colin Crossaa812d12019-06-19 13:33:24 -0700423 // Add a non-existent file to the dependencies so that soong_build will rerun when the debugger is
424 // enabled even if it completed successfully.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200425 extraNinjaDeps = append(extraNinjaDeps, filepath.Join(configuration.SoongOutDir(), "always_rerun_for_delve"))
Colin Crossaa812d12019-06-19 13:33:24 -0700426 }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500427
Dan Willemsenccf36aa2022-04-20 23:11:43 -0700428 // Bypass configuration.Getenv, as LOG_DIR does not need to be dependency tracked. By definition, it will
429 // change between every CI build, so tracking it would require re-running Soong for every build.
430 logDir := availableEnv["LOG_DIR"]
431
Joe Onorato2e5e4012022-06-07 17:16:08 -0700432 ctx := newContext(configuration)
Joe Onorato2e5e4012022-06-07 17:16:08 -0700433
Paul Duffinf4906562022-11-05 14:21:16 +0000434 finalOutputFile := doChosenActivity(ctx, configuration, extraNinjaDeps, logDir)
Joe Onorato2e5e4012022-06-07 17:16:08 -0700435
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200436 writeUsedEnvironmentFile(configuration, finalOutputFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100437}
438
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200439func writeUsedEnvironmentFile(configuration android.Config, finalOutputFile string) {
440 if usedEnvFile == "" {
441 return
442 }
443
444 path := shared.JoinPath(topDir, usedEnvFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100445 data, err := shared.EnvFileContents(configuration.EnvDeps())
446 if err != nil {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200447 fmt.Fprintf(os.Stderr, "error writing used environment file '%s': %s\n", usedEnvFile, err)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100448 os.Exit(1)
449 }
450
Usta Shrestha2ba28a32022-10-24 11:33:09 -0400451 if preexistingData, err := os.ReadFile(path); err != nil {
452 if !os.IsNotExist(err) {
453 fmt.Fprintf(os.Stderr, "error reading used environment file '%s': %s\n", usedEnvFile, err)
454 os.Exit(1)
455 }
456 } else if bytes.Equal(preexistingData, data) {
457 // used environment file is unchanged
458 return
459 }
460 if err = os.WriteFile(path, data, 0666); err != nil {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200461 fmt.Fprintf(os.Stderr, "error writing used environment file '%s': %s\n", usedEnvFile, err)
Lukacs T. Berkic99c9472021-03-24 10:50:06 +0100462 os.Exit(1)
463 }
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200464 // Touch the output file so that it's not older than the file we just
Lukacs T. Berkic99c9472021-03-24 10:50:06 +0100465 // wrote. We can't write the environment file earlier because one an access
466 // new environment variables while writing it.
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200467 touch(shared.JoinPath(topDir, finalOutputFile))
Colin Cross3f40fa42015-01-30 17:27:36 -0800468}
Jingwen Chen5ba7e472020-07-15 10:06:41 +0000469
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200470func touch(path string) {
471 f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
472 if err != nil {
473 fmt.Fprintf(os.Stderr, "Error touching '%s': %s\n", path, err)
474 os.Exit(1)
475 }
476
477 err = f.Close()
478 if err != nil {
479 fmt.Fprintf(os.Stderr, "Error touching '%s': %s\n", path, err)
480 os.Exit(1)
481 }
482
483 currentTime := time.Now().Local()
484 err = os.Chtimes(path, currentTime, currentTime)
485 if err != nil {
486 fmt.Fprintf(os.Stderr, "error touching '%s': %s\n", path, err)
487 os.Exit(1)
488 }
489}
490
Cole Faust324a92e2022-08-23 15:29:05 -0700491// Find BUILD files in the srcDir which are not in the allowlist
492// (android.Bp2BuildConversionAllowlist#ShouldKeepExistingBuildFileForDir)
493// and return their paths so they can be left out of the Bazel workspace dir (i.e. ignored)
494func getPathsToIgnoredBuildFiles(config android.Bp2BuildConversionAllowlist, topDir string, srcDirBazelFiles []string, verbose bool) []string {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400495 paths := make([]string, 0)
496
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400497 for _, srcDirBazelFileRelativePath := range srcDirBazelFiles {
498 srcDirBazelFileFullPath := shared.JoinPath(topDir, srcDirBazelFileRelativePath)
499 fileInfo, err := os.Stat(srcDirBazelFileFullPath)
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400500 if err != nil {
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400501 // Warn about error, but continue trying to check files
502 fmt.Fprintf(os.Stderr, "WARNING: Error accessing path '%s', err: %s\n", srcDirBazelFileFullPath, err)
503 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400504 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400505 if fileInfo.IsDir() {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400506 // Don't ignore entire directories
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400507 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400508 }
Cole Faust324a92e2022-08-23 15:29:05 -0700509 if fileInfo.Name() != "BUILD" && fileInfo.Name() != "BUILD.bazel" {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400510 // Don't ignore this file - it is not a build file
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400511 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400512 }
Cole Faust324a92e2022-08-23 15:29:05 -0700513 if config.ShouldKeepExistingBuildFileForDir(filepath.Dir(srcDirBazelFileRelativePath)) {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400514 // Don't ignore this existing build file
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400515 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400516 }
Liz Kammer1aefc9d2021-10-18 16:59:00 -0400517 if verbose {
518 fmt.Fprintf(os.Stderr, "Ignoring existing BUILD file: %s\n", srcDirBazelFileRelativePath)
519 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400520 paths = append(paths, srcDirBazelFileRelativePath)
521 }
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400522
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400523 return paths
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400524}
525
526// Returns temporary symlink forest excludes necessary for bazel build //external/... (and bazel build //frameworks/...) to work
527func getTemporaryExcludes() []string {
528 excludes := make([]string, 0)
529
530 // FIXME: 'autotest_lib' is a symlink back to external/autotest, and this causes an infinite symlink expansion error for Bazel
531 excludes = append(excludes, "external/autotest/venv/autotest_lib")
Jingwen Chenc0c50212022-06-07 10:07:22 +0000532 excludes = append(excludes, "external/autotest/autotest_lib")
533 excludes = append(excludes, "external/autotest/client/autotest_lib/client")
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400534
535 // FIXME: The external/google-fruit/extras/bazel_root/third_party/fruit dir is poison
536 // It contains several symlinks back to real source dirs, and those source dirs contain BUILD files we want to ignore
537 excludes = append(excludes, "external/google-fruit/extras/bazel_root/third_party/fruit")
538
539 // FIXME: 'frameworks/compile/slang' has a filegroup error due to an escaping issue
540 excludes = append(excludes, "frameworks/compile/slang")
541
Jingwen Chenbcfadce2022-11-30 08:44:05 +0000542 // FIXME(b/260809113): 'prebuilts/clang/host/linux-x86/clang-dev' is a tool-generated symlink directory that contains a BUILD file.
543 // The bazel files finder code doesn't traverse into symlink dirs, and hence is not aware of this BUILD file and exclude it accordingly
544 // during symlink forest generation when checking against keepExistingBuildFiles allowlist.
545 //
546 // This is necessary because globs in //prebuilts/clang/host/linux-x86/BUILD
547 // currently assume no subpackages (keepExistingBuildFile is not recursive for that directory).
548 //
549 // This is a bandaid until we the symlink forest logic can intelligently exclude BUILD files found in source symlink dirs according
550 // to the keepExistingBuildFile allowlist.
551 excludes = append(excludes, "prebuilts/clang/host/linux-x86/clang-dev")
552
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400553 return excludes
554}
555
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400556// Read the bazel.list file that the Soong Finder already dumped earlier (hopefully)
557// It contains the locations of BUILD files, BUILD.bazel files, etc. in the source dir
558func getExistingBazelRelatedFiles(topDir string) ([]string, error) {
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200559 bazelFinderFile := filepath.Join(filepath.Dir(cmdlineArgs.ModuleListFile), "bazel.list")
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400560 if !filepath.IsAbs(bazelFinderFile) {
561 // Assume this was a relative path under topDir
562 bazelFinderFile = filepath.Join(topDir, bazelFinderFile)
563 }
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800564 data, err := os.ReadFile(bazelFinderFile)
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400565 if err != nil {
566 return nil, err
567 }
568 files := strings.Split(strings.TrimSpace(string(data)), "\n")
569 return files, nil
570}
571
Spandan Das5af0bd32022-09-28 20:43:08 +0000572func bazelArtifacts() []string {
573 return []string{
574 "bazel-bin",
575 "bazel-genfiles",
576 "bazel-out",
577 "bazel-testlogs",
578 "bazel-" + filepath.Base(topDir),
579 }
580}
581
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000582// This could in theory easily be separated into a binary that generically
583// merges two directories into a symlink tree. The main obstacle is that this
584// function currently depends on both Bazel-specific knowledge (the existence
585// of bazel-* symlinks) and configuration (the set of BUILD.bazel files that
586// should and should not be kept)
587//
588// Ideally, bp2build would write a file that contains instructions to the
589// symlink tree creation binary. Then the latter would not need to depend on
590// the very heavy-weight machinery of soong_build .
Paul Duffinb713ddf2022-11-05 16:14:30 +0000591func runSymlinkForestCreation(configuration android.Config, ctx *android.Context, extraNinjaDeps []string, metricsDir string) string {
Paul Duffinb4e8d912022-11-04 13:35:50 +0000592 ctx.EventHandler.Do("symlink_forest", func() {
Usta (Tsering) Shrestha93b2a9b2022-12-01 05:55:35 +0000593 var ninjaDeps []string
594 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000595
Usta (Tsering) Shrestha93b2a9b2022-12-01 05:55:35 +0000596 generatedRoot := shared.JoinPath(configuration.SoongOutDir(), "bp2build")
597 workspaceRoot := shared.JoinPath(configuration.SoongOutDir(), "workspace")
598
599 excludes := bazelArtifacts()
600
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800601 if cmdlineArgs.OutDir[0] != '/' {
602 excludes = append(excludes, cmdlineArgs.OutDir)
Usta (Tsering) Shrestha93b2a9b2022-12-01 05:55:35 +0000603 }
604
605 existingBazelRelatedFiles, err := getExistingBazelRelatedFiles(topDir)
606 if err != nil {
607 fmt.Fprintf(os.Stderr, "Error determining existing Bazel-related files: %s\n", err)
608 os.Exit(1)
609 }
610
611 pathsToIgnoredBuildFiles := getPathsToIgnoredBuildFiles(configuration.Bp2buildPackageConfig, topDir, existingBazelRelatedFiles, configuration.IsEnvTrue("BP2BUILD_VERBOSE"))
612 excludes = append(excludes, pathsToIgnoredBuildFiles...)
613 excludes = append(excludes, getTemporaryExcludes()...)
614
615 // PlantSymlinkForest() returns all the directories that were readdir()'ed.
616 // Such a directory SHOULD be added to `ninjaDeps` so that a child directory
617 // or file created/deleted under it would trigger an update of the symlink forest.
618 ctx.EventHandler.Do("plant", func() {
619 symlinkForestDeps := bp2build.PlantSymlinkForest(
620 configuration.IsEnvTrue("BP2BUILD_VERBOSE"), topDir, workspaceRoot, generatedRoot, excludes)
621 ninjaDeps = append(ninjaDeps, symlinkForestDeps...)
622 })
623
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800624 writeDepFile(cmdlineArgs.SymlinkForestMarker, ctx.EventHandler, ninjaDeps)
625 touch(shared.JoinPath(topDir, cmdlineArgs.SymlinkForestMarker))
Usta (Tsering) Shrestha93b2a9b2022-12-01 05:55:35 +0000626 })
usta4f5d2c12022-10-28 23:32:01 -0400627 codegenMetrics := bp2build.ReadCodegenMetrics(metricsDir)
628 if codegenMetrics == nil {
629 m := bp2build.CreateCodegenMetrics()
630 codegenMetrics = &m
631 } else {
632 //TODO (usta) we cannot determine if we loaded a stale file, i.e. from an unrelated prior
633 //invocation of codegen. We should simply use a separate .pb file
634 }
Paul Duffinb4e8d912022-11-04 13:35:50 +0000635 writeBp2BuildMetrics(codegenMetrics, ctx.EventHandler, metricsDir)
Paul Duffinb713ddf2022-11-05 16:14:30 +0000636
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800637 return cmdlineArgs.SymlinkForestMarker
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000638}
639
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500640// Run Soong in the bp2build mode. This creates a standalone context that registers
641// an alternate pipeline of mutators and singletons specifically for generating
642// Bazel BUILD files instead of Ninja files.
Paul Duffinb713ddf2022-11-05 16:14:30 +0000643func runBp2Build(configuration android.Config, ctx *android.Context, extraNinjaDeps []string, metricsDir string) string {
usta4f5d2c12022-10-28 23:32:01 -0400644 var codegenMetrics *bp2build.CodegenMetrics
Paul Duffinb4e8d912022-11-04 13:35:50 +0000645 ctx.EventHandler.Do("bp2build", func() {
Jingwen Cheneb76c432021-01-28 08:22:12 -0500646
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400647 // Propagate "allow misssing dependencies" bit. This is normally set in
Paul Duffinb4e8d912022-11-04 13:35:50 +0000648 // newContext(), but we create ctx without calling that method.
649 ctx.SetAllowMissingDependencies(configuration.AllowMissingDependencies())
650 ctx.SetNameInterface(newNameResolver(configuration))
651 ctx.RegisterForBazelConversion()
652 ctx.SetModuleListFile(cmdlineArgs.ModuleListFile)
Jingwen Cheneb76c432021-01-28 08:22:12 -0500653
Usta Shresthaa117c582022-10-04 12:13:25 -0400654 var ninjaDeps []string
655 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
656
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400657 // Run the loading and analysis pipeline to prepare the graph of regular
658 // Modules parsed from Android.bp files, and the BazelTargetModules mapped
659 // from the regular Modules.
Paul Duffinb4e8d912022-11-04 13:35:50 +0000660 ctx.EventHandler.Do("bootstrap", func() {
Usta Shresthaa117c582022-10-04 12:13:25 -0400661 blueprintArgs := cmdlineArgs
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800662 bootstrapDeps := bootstrap.RunBlueprint(blueprintArgs.Args, bootstrap.StopBeforePrepareBuildActions, ctx.Context, configuration)
Usta Shresthaa117c582022-10-04 12:13:25 -0400663 ninjaDeps = append(ninjaDeps, bootstrapDeps...)
664 })
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200665
Paul Duffinb4e8d912022-11-04 13:35:50 +0000666 globListFiles := writeBuildGlobsNinjaFile(ctx, configuration.SoongOutDir(), configuration)
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400667 ninjaDeps = append(ninjaDeps, globListFiles...)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200668
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400669 // Run the code-generation phase to convert BazelTargetModules to BUILD files
Usta Shresthaa117c582022-10-04 12:13:25 -0400670 // and print conversion codegenMetrics to the user.
Paul Duffinb4e8d912022-11-04 13:35:50 +0000671 codegenContext := bp2build.NewCodegenContext(configuration, ctx, bp2build.Bp2Build)
672 ctx.EventHandler.Do("codegen", func() {
Usta Shresthaa117c582022-10-04 12:13:25 -0400673 codegenMetrics = bp2build.Codegen(codegenContext)
674 })
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200675
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400676 ninjaDeps = append(ninjaDeps, codegenContext.AdditionalNinjaDeps()...)
Chris Parsons715b08f2022-03-22 19:23:40 -0400677
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800678 writeDepFile(cmdlineArgs.Bp2buildMarker, ctx.EventHandler, ninjaDeps)
679 touch(shared.JoinPath(topDir, cmdlineArgs.Bp2buildMarker))
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400680 })
Chris Parsons715b08f2022-03-22 19:23:40 -0400681
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200682 // Only report metrics when in bp2build mode. The metrics aren't relevant
683 // for queryview, since that's a total repo-wide conversion and there's a
684 // 1:1 mapping for each module.
Sasha Smundak0fd93e02022-05-19 19:34:31 -0700685 if configuration.IsEnvTrue("BP2BUILD_VERBOSE") {
Usta Shresthaa117c582022-10-04 12:13:25 -0400686 codegenMetrics.Print()
Sasha Smundak0fd93e02022-05-19 19:34:31 -0700687 }
Paul Duffinb4e8d912022-11-04 13:35:50 +0000688 writeBp2BuildMetrics(codegenMetrics, ctx.EventHandler, metricsDir)
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800689 return cmdlineArgs.Bp2buildMarker
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500690}
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500691
692// Write Bp2Build metrics into $LOG_DIR
Paul Duffinf4906562022-11-05 14:21:16 +0000693func writeBp2BuildMetrics(codegenMetrics *bp2build.CodegenMetrics, eventHandler *metrics.EventHandler, metricsDir string) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400694 for _, event := range eventHandler.CompletedEvents() {
usta4f5d2c12022-10-28 23:32:01 -0400695 codegenMetrics.AddEvent(&bp2build_metrics_proto.Event{
696 Name: event.Id,
697 StartTime: uint64(event.Start.UnixNano()),
698 RealTime: event.RuntimeNanoseconds(),
699 })
Chris Parsons715b08f2022-03-22 19:23:40 -0400700 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500701 if len(metricsDir) < 1 {
702 fmt.Fprintf(os.Stderr, "\nMissing required env var for generating bp2build metrics: LOG_DIR\n")
703 os.Exit(1)
704 }
Chris Parsons715b08f2022-03-22 19:23:40 -0400705 codegenMetrics.Write(metricsDir)
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500706}
MarkDacek0d5bca52022-10-10 20:07:48 +0000707
708func readBazelPaths(configuration android.Config) ([]string, error) {
709 depsPath := configuration.Getenv("BAZEL_DEPS_FILE")
710
711 data, err := os.ReadFile(depsPath)
712 if err != nil {
713 return nil, err
714 }
715 paths := strings.Split(strings.TrimSpace(string(data)), "\n")
716 return paths, nil
717}