blob: f4a63a4a56cd727c607476ad8d862d80053badb9 [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"
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +010021 "io/ioutil"
Colin Cross3f40fa42015-01-30 17:27:36 -080022 "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"
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. Berki89fcdcb2021-09-07 09:10:33 +020041 outDir string
Lukacs T. Berkid6cee7e2021-09-01 16:25:51 +020042 soongOutDir string
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020043 availableEnvFile string
44 usedEnvFile string
45
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +020046 runGoTests bool
47
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +020048 globFile string
49 globListDir string
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020050 delveListen string
51 delvePath string
52
Spandan Das5af0bd32022-09-28 20:43:08 +000053 moduleGraphFile string
54 moduleActionsFile string
55 docFile string
56 bazelQueryViewDir string
57 bazelApiBp2buildDir string
58 bp2buildMarker string
Lukacs T. Berkic541cd22022-10-26 07:26:50 +000059 symlinkForestMarker string
Lukacs T. Berkif9008072021-08-16 15:24:48 +020060
61 cmdlineArgs bootstrap.Args
Colin Crosse87040b2017-12-11 15:52:26 -080062)
63
64func init() {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020065 // Flags that make sense in every mode
Lukacs T. Berki7690c092021-02-26 14:27:36 +010066 flag.StringVar(&topDir, "top", "", "Top directory of the Android source tree")
Lukacs T. Berkid6cee7e2021-09-01 16:25:51 +020067 flag.StringVar(&soongOutDir, "soong_out", "", "Soong output directory (usually $TOP/out/soong)")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020068 flag.StringVar(&availableEnvFile, "available_env", "", "File containing available environment variables")
69 flag.StringVar(&usedEnvFile, "used_env", "", "File containing used environment variables")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020070 flag.StringVar(&globFile, "globFile", "build-globs.ninja", "the Ninja file of globs to output")
71 flag.StringVar(&globListDir, "globListDir", "", "the directory containing the glob list files")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +020072 flag.StringVar(&outDir, "out", "", "the ninja builddir directory")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020073 flag.StringVar(&cmdlineArgs.ModuleListFile, "l", "", "file that lists filepaths to parse")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020074
75 // Debug flags
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +010076 flag.StringVar(&delveListen, "delve_listen", "", "Delve port to listen on for debugging")
77 flag.StringVar(&delvePath, "delve_path", "", "Path to Delve. Only used if --delve_listen is set")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020078 flag.StringVar(&cmdlineArgs.Cpuprofile, "cpuprofile", "", "write cpu profile to file")
79 flag.StringVar(&cmdlineArgs.TraceFile, "trace", "", "write trace to file")
80 flag.StringVar(&cmdlineArgs.Memprofile, "memprofile", "", "write memory profile to file")
81 flag.BoolVar(&cmdlineArgs.NoGC, "nogc", false, "turn off GC for debugging")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020082
83 // Flags representing various modes soong_build can run in
Lukacs T. Berkie571dc32021-08-25 14:14:13 +020084 flag.StringVar(&moduleGraphFile, "module_graph_file", "", "JSON module graph file to output")
kgui67007242022-01-25 13:50:25 +080085 flag.StringVar(&moduleActionsFile, "module_actions_file", "", "JSON file to output inputs/outputs of actions of modules")
Colin Crosse87040b2017-12-11 15:52:26 -080086 flag.StringVar(&docFile, "soong_docs", "", "build documentation file to output")
Lukacs T. Berki47a9d0c2021-03-08 16:34:09 +010087 flag.StringVar(&bazelQueryViewDir, "bazel_queryview_dir", "", "path to the bazel queryview directory relative to --top")
Spandan Das5af0bd32022-09-28 20:43:08 +000088 flag.StringVar(&bazelApiBp2buildDir, "bazel_api_bp2build_dir", "", "path to the bazel api_bp2build directory relative to --top")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020089 flag.StringVar(&bp2buildMarker, "bp2build_marker", "", "If set, run bp2build, touch the specified marker file then exit")
Lukacs T. Berkic541cd22022-10-26 07:26:50 +000090 flag.StringVar(&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 +020091 flag.StringVar(&cmdlineArgs.OutFile, "o", "build.ninja", "the Ninja file to output")
MarkDacekd06db5d2022-11-29 00:47:59 +000092 flag.StringVar(&cmdlineArgs.BazelForceEnabledModules, "bazel-force-enabled-modules", "", "additional modules to build with Bazel. Comma-delimited")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020093 flag.BoolVar(&cmdlineArgs.EmptyNinjaFile, "empty-ninja-file", false, "write out a 0-byte ninja file")
Chris Parsonsef615e52022-08-18 22:04:11 -040094 flag.BoolVar(&cmdlineArgs.BazelMode, "bazel-mode", false, "use bazel for analysis of certain modules")
Jingwen Chene647db82022-11-01 11:28:29 +000095 flag.BoolVar(&cmdlineArgs.BazelModeStaging, "bazel-mode-staging", false, "use bazel for analysis of certain near-ready modules")
Chris Parsonsef615e52022-08-18 22:04:11 -040096 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 +020097
98 // Flags that probably shouldn't be flags of soong_build but we haven't found
99 // the time to remove them yet
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200100 flag.BoolVar(&runGoTests, "t", false, "build and run go tests during bootstrap")
Dan Willemsen66213a62021-09-21 17:50:30 -0700101
102 // Disable deterministic randomization in the protobuf package, so incremental
103 // builds with unrelated Soong changes don't trigger large rebuilds (since we
104 // write out text protos in command lines, and command line changes trigger
105 // rebuilds).
106 androidProtobuf.DisableRand()
Colin Crosse87040b2017-12-11 15:52:26 -0800107}
108
Jeff Gaston088e29e2017-11-29 16:47:17 -0800109func newNameResolver(config android.Config) *android.NameResolver {
Paul Duffin3f7bf9f2022-11-08 12:21:15 +0000110 return android.NewNameResolver(config)
Jeff Gaston088e29e2017-11-29 16:47:17 -0800111}
112
Lukacs T. Berkiffc9e8d2021-09-07 17:54:38 +0200113func newContext(configuration android.Config) *android.Context {
Colin Crossae8600b2020-10-29 17:09:13 -0700114 ctx := android.NewContext(configuration)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400115 ctx.SetNameInterface(newNameResolver(configuration))
116 ctx.SetAllowMissingDependencies(configuration.AllowMissingDependencies())
Spandan Dasc5763832022-11-08 18:42:16 +0000117 ctx.AddIncludeTags(configuration.IncludeTags()...)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400118 return ctx
119}
120
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200121func newConfig(availableEnv map[string]string) android.Config {
Chris Parsonsad876012022-08-20 14:48:32 -0400122 var buildMode android.SoongBuildMode
MarkDacekd06db5d2022-11-29 00:47:59 +0000123 var bazelForceEnabledModules []string
124 if len(cmdlineArgs.BazelForceEnabledModules) > 0 {
125 bazelForceEnabledModules = strings.Split(cmdlineArgs.BazelForceEnabledModules, ",")
126 }
Chris Parsonsad876012022-08-20 14:48:32 -0400127
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000128 if symlinkForestMarker != "" {
129 buildMode = android.SymlinkForest
130 } else if bp2buildMarker != "" {
Chris Parsonsad876012022-08-20 14:48:32 -0400131 buildMode = android.Bp2build
132 } else if bazelQueryViewDir != "" {
133 buildMode = android.GenerateQueryView
Spandan Das5af0bd32022-09-28 20:43:08 +0000134 } else if bazelApiBp2buildDir != "" {
135 buildMode = android.ApiBp2build
Chris Parsonsad876012022-08-20 14:48:32 -0400136 } else if moduleGraphFile != "" {
137 buildMode = android.GenerateModuleGraph
138 } else if docFile != "" {
139 buildMode = android.GenerateDocFile
Chris Parsonsef615e52022-08-18 22:04:11 -0400140 } else if cmdlineArgs.BazelModeDev {
141 buildMode = android.BazelDevMode
142 } else if cmdlineArgs.BazelMode {
143 buildMode = android.BazelProdMode
MarkDacekb78465d2022-10-18 20:10:16 +0000144 } else if cmdlineArgs.BazelModeStaging {
145 buildMode = android.BazelStagingMode
Chris Parsonsad876012022-08-20 14:48:32 -0400146 } else {
147 buildMode = android.AnalysisNoBazel
148 }
149
MarkDacekd06db5d2022-11-29 00:47:59 +0000150 configuration, err := android.NewConfig(cmdlineArgs.ModuleListFile, buildMode, runGoTests, outDir, soongOutDir, availableEnv, bazelForceEnabledModules)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400151 if err != nil {
152 fmt.Fprintf(os.Stderr, "%s", err)
153 os.Exit(1)
154 }
155 return configuration
156}
157
Chris Parsonsf874e462022-05-10 13:50:12 -0400158// Bazel-enabled mode. Attaches a mutator to queue Bazel requests, adds a
159// BeforePrepareBuildActionsHook to invoke Bazel, and then uses Bazel metadata
160// for modules that should be handled by Bazel.
Paul Duffin0c09a432022-11-05 15:28:04 +0000161func runMixedModeBuild(configuration android.Config, ctx *android.Context, extraNinjaDeps []string) string {
Chris Parsonsf874e462022-05-10 13:50:12 -0400162 ctx.EventHandler.Begin("mixed_build")
163 defer ctx.EventHandler.End("mixed_build")
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200164
Chris Parsonsf874e462022-05-10 13:50:12 -0400165 bazelHook := func() error {
Sasha Smundak4975c822022-11-16 15:28:18 -0800166 return configuration.BazelContext.InvokeBazel(configuration, ctx)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200167 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400168 ctx.SetBeforePrepareBuildActionsHook(bazelHook)
Chris Parsonsf874e462022-05-10 13:50:12 -0400169 ninjaDeps := bootstrap.RunBlueprint(cmdlineArgs, bootstrap.DoEverything, ctx.Context, configuration)
Chris Parsons027881c2022-05-24 15:38:38 -0400170 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200171
MarkDacek0d5bca52022-10-10 20:07:48 +0000172 bazelPaths, err := readBazelPaths(configuration)
173 if err != nil {
174 panic("Bazel deps file not found: " + err.Error())
175 }
176 ninjaDeps = append(ninjaDeps, bazelPaths...)
177
Chris Parsonsf874e462022-05-10 13:50:12 -0400178 globListFiles := writeBuildGlobsNinjaFile(ctx, configuration.SoongOutDir(), configuration)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200179 ninjaDeps = append(ninjaDeps, globListFiles...)
180
Paul Duffin780a1852022-11-05 10:17:12 +0000181 writeDepFile(cmdlineArgs.OutFile, ctx.EventHandler, ninjaDeps)
Paul Duffin0c09a432022-11-05 15:28:04 +0000182 return cmdlineArgs.OutFile
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200183}
184
185// Run the code-generation phase to convert BazelTargetModules to BUILD files.
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200186func runQueryView(queryviewDir, queryviewMarker string, configuration android.Config, ctx *android.Context) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400187 ctx.EventHandler.Begin("queryview")
188 defer ctx.EventHandler.End("queryview")
Paul Duffinc6390592022-11-04 13:35:21 +0000189 codegenContext := bp2build.NewCodegenContext(configuration, ctx, bp2build.QueryView)
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200190 absoluteQueryViewDir := shared.JoinPath(topDir, queryviewDir)
Spandan Das5af0bd32022-09-28 20:43:08 +0000191 if err := createBazelWorkspace(codegenContext, absoluteQueryViewDir); err != nil {
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200192 fmt.Fprintf(os.Stderr, "%s", err)
193 os.Exit(1)
194 }
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200195
196 touch(shared.JoinPath(topDir, queryviewMarker))
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200197}
198
Spandan Das5af0bd32022-09-28 20:43:08 +0000199// Run the code-generation phase to convert API contributions to BUILD files.
200// Return marker file for the new synthetic workspace
Paul Duffinb4e8d912022-11-04 13:35:50 +0000201func runApiBp2build(configuration android.Config, ctx *android.Context, extraNinjaDeps []string) string {
Spandan Das5af0bd32022-09-28 20:43:08 +0000202 ctx.EventHandler.Begin("api_bp2build")
203 defer ctx.EventHandler.End("api_bp2build")
Paul Duffinb4e8d912022-11-04 13:35:50 +0000204 // Do not allow missing dependencies.
205 ctx.SetAllowMissingDependencies(false)
Spandan Das5af0bd32022-09-28 20:43:08 +0000206 ctx.RegisterForApiBazelConversion()
207
208 // Register the Android.bp files in the tree
209 // Add them to the workspace's .d file
210 ctx.SetModuleListFile(cmdlineArgs.ModuleListFile)
211 if paths, err := ctx.ListModulePaths("."); err == nil {
212 extraNinjaDeps = append(extraNinjaDeps, paths...)
213 } else {
214 panic(err)
215 }
216
217 // Run the loading and analysis phase
218 ninjaDeps := bootstrap.RunBlueprint(cmdlineArgs,
219 bootstrap.StopBeforePrepareBuildActions,
220 ctx.Context,
221 configuration)
222 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
223
224 // Add the globbed dependencies
225 globs := writeBuildGlobsNinjaFile(ctx, configuration.SoongOutDir(), configuration)
226 ninjaDeps = append(ninjaDeps, globs...)
227
228 // Run codegen to generate BUILD files
Paul Duffinc6390592022-11-04 13:35:21 +0000229 codegenContext := bp2build.NewCodegenContext(configuration, ctx, bp2build.ApiBp2build)
Spandan Das5af0bd32022-09-28 20:43:08 +0000230 absoluteApiBp2buildDir := shared.JoinPath(topDir, bazelApiBp2buildDir)
231 if err := createBazelWorkspace(codegenContext, absoluteApiBp2buildDir); err != nil {
232 fmt.Fprintf(os.Stderr, "%s", err)
233 os.Exit(1)
234 }
235 ninjaDeps = append(ninjaDeps, codegenContext.AdditionalNinjaDeps()...)
236
237 // Create soong_injection repository
Spandan Das7b6d5332022-11-01 17:37:07 +0000238 soongInjectionFiles := bp2build.CreateSoongInjectionFiles(configuration, bp2build.CreateCodegenMetrics())
Spandan Das5af0bd32022-09-28 20:43:08 +0000239 absoluteSoongInjectionDir := shared.JoinPath(topDir, configuration.SoongOutDir(), bazel.SoongInjectionDirName)
240 for _, file := range soongInjectionFiles {
241 writeReadOnlyFile(absoluteSoongInjectionDir, file)
242 }
243
244 workspace := shared.JoinPath(configuration.SoongOutDir(), "api_bp2build")
245
246 excludes := bazelArtifacts()
247 // Exclude all src BUILD files
248 excludes = append(excludes, apiBuildFileExcludes()...)
249
Spandan Das394aa322022-11-03 17:02:10 +0000250 // Android.bp files for api surfaces are mounted to out/, but out/ should not be a
251 // dep for api_bp2build.
252 // Otherwise api_bp2build will be run every single time
253 excludes = append(excludes, configuration.OutDir())
254
Spandan Das5af0bd32022-09-28 20:43:08 +0000255 // Create the symlink forest
256 symlinkDeps := bp2build.PlantSymlinkForest(
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000257 configuration.IsEnvTrue("BP2BUILD_VERBOSE"),
Spandan Das5af0bd32022-09-28 20:43:08 +0000258 topDir,
259 workspace,
260 bazelApiBp2buildDir,
Spandan Das5af0bd32022-09-28 20:43:08 +0000261 excludes)
262 ninjaDeps = append(ninjaDeps, symlinkDeps...)
263
264 workspaceMarkerFile := workspace + ".marker"
Paul Duffin780a1852022-11-05 10:17:12 +0000265 writeDepFile(workspaceMarkerFile, ctx.EventHandler, ninjaDeps)
Spandan Das5af0bd32022-09-28 20:43:08 +0000266 touch(shared.JoinPath(topDir, workspaceMarkerFile))
267 return workspaceMarkerFile
268}
269
270// With some exceptions, api_bp2build does not have any dependencies on the checked-in BUILD files
271// Exclude them from the generated workspace to prevent unrelated errors during the loading phase
272func apiBuildFileExcludes() []string {
273 ret := make([]string, 0)
274
275 srcs, err := getExistingBazelRelatedFiles(topDir)
276 if err != nil {
277 fmt.Fprintf(os.Stderr, "Error determining existing Bazel-related files: %s\n", err)
278 os.Exit(1)
279 }
280 for _, src := range srcs {
281 if src != "WORKSPACE" &&
282 src != "BUILD" &&
283 src != "BUILD.bazel" &&
284 !strings.HasPrefix(src, "build/bazel") &&
Spandan Das6b91a382022-11-30 02:17:06 +0000285 !strings.HasPrefix(src, "external/bazel-skylib") &&
Spandan Das5af0bd32022-09-28 20:43:08 +0000286 !strings.HasPrefix(src, "prebuilts/clang") {
287 ret = append(ret, src)
288 }
289 }
290 return ret
291}
292
Paul Duffin780a1852022-11-05 10:17:12 +0000293func writeMetrics(configuration android.Config, eventHandler *metrics.EventHandler, metricsDir string) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400294 if len(metricsDir) < 1 {
295 fmt.Fprintf(os.Stderr, "\nMissing required env var for generating soong metrics: LOG_DIR\n")
296 os.Exit(1)
297 }
298 metricsFile := filepath.Join(metricsDir, "soong_build_metrics.pb")
299 err := android.WriteMetrics(configuration, eventHandler, metricsFile)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200300 if err != nil {
301 fmt.Fprintf(os.Stderr, "error writing soong_build metrics %s: %s", metricsFile, err)
302 os.Exit(1)
303 }
304}
305
kgui67007242022-01-25 13:50:25 +0800306func writeJsonModuleGraphAndActions(ctx *android.Context, graphPath string, actionsPath string) {
307 graphFile, graphErr := os.Create(shared.JoinPath(topDir, graphPath))
308 actionsFile, actionsErr := os.Create(shared.JoinPath(topDir, actionsPath))
309 if graphErr != nil || actionsErr != nil {
310 fmt.Fprintf(os.Stderr, "Graph err: %s, actions err: %s", graphErr, actionsErr)
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200311 os.Exit(1)
312 }
313
kgui67007242022-01-25 13:50:25 +0800314 defer graphFile.Close()
315 defer actionsFile.Close()
316 ctx.Context.PrintJSONGraphAndActions(graphFile, actionsFile)
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200317}
318
Chris Parsons715b08f2022-03-22 19:23:40 -0400319func writeBuildGlobsNinjaFile(ctx *android.Context, buildDir string, config interface{}) []string {
320 ctx.EventHandler.Begin("globs_ninja_file")
321 defer ctx.EventHandler.End("globs_ninja_file")
322
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200323 globDir := bootstrap.GlobDirectory(buildDir, globListDir)
324 bootstrap.WriteBuildGlobsNinjaFile(&bootstrap.GlobSingleton{
Chris Parsons715b08f2022-03-22 19:23:40 -0400325 GlobLister: ctx.Globs,
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200326 GlobFile: globFile,
327 GlobDir: globDir,
Chris Parsons715b08f2022-03-22 19:23:40 -0400328 SrcDir: ctx.SrcDir(),
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200329 }, config)
330 return bootstrap.GlobFileListFiles(globDir)
331}
332
Paul Duffin780a1852022-11-05 10:17:12 +0000333func writeDepFile(outputFile string, eventHandler *metrics.EventHandler, ninjaDeps []string) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400334 eventHandler.Begin("ninja_deps")
335 defer eventHandler.End("ninja_deps")
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200336 depFile := shared.JoinPath(topDir, outputFile+".d")
337 err := deptools.WriteDepFile(depFile, outputFile, ninjaDeps)
338 if err != nil {
339 fmt.Fprintf(os.Stderr, "Error writing depfile '%s': %s\n", depFile, err)
340 os.Exit(1)
341 }
342}
343
Jingwen Chen4fabaf52021-05-25 02:40:29 +0000344// doChosenActivity runs Soong for a specific activity, like bp2build, queryview
345// or the actual Soong build for the build.ninja file. Returns the top level
346// output file of the specific activity.
Paul Duffinf4906562022-11-05 14:21:16 +0000347func doChosenActivity(ctx *android.Context, configuration android.Config, extraNinjaDeps []string, metricsDir string) string {
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000348 if configuration.BuildMode == android.SymlinkForest {
Paul Duffinb713ddf2022-11-05 16:14:30 +0000349 return runSymlinkForestCreation(configuration, ctx, extraNinjaDeps, metricsDir)
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000350 } else if configuration.BuildMode == android.Bp2build {
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200351 // Run the alternate pipeline of bp2build mutators and singleton to convert
352 // Blueprint to BUILD files before everything else.
Paul Duffinb713ddf2022-11-05 16:14:30 +0000353 return runBp2Build(configuration, ctx, extraNinjaDeps, metricsDir)
Spandan Das5af0bd32022-09-28 20:43:08 +0000354 } else if configuration.BuildMode == android.ApiBp2build {
Paul Duffinb4e8d912022-11-04 13:35:50 +0000355 outputFile := runApiBp2build(configuration, ctx, extraNinjaDeps)
Paul Duffin39eae8f2022-11-05 14:59:52 +0000356 writeMetrics(configuration, ctx.EventHandler, metricsDir)
357 return outputFile
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200358 } else {
Paul Duffinb4e8d912022-11-04 13:35:50 +0000359 ctx.Register()
Paul Duffin39eae8f2022-11-05 14:59:52 +0000360
361 var outputFile string
Paul Duffin0c09a432022-11-05 15:28:04 +0000362 if configuration.IsMixedBuildsEnabled() {
Paul Duffin39eae8f2022-11-05 14:59:52 +0000363 outputFile = runMixedModeBuild(configuration, ctx, extraNinjaDeps)
Chris Parsons715b08f2022-03-22 19:23:40 -0400364 } else {
Paul Duffin39eae8f2022-11-05 14:59:52 +0000365 outputFile = runSoongOnlyBuild(configuration, ctx, extraNinjaDeps)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200366 }
Paul Duffin39eae8f2022-11-05 14:59:52 +0000367
368 writeMetrics(configuration, ctx.EventHandler, metricsDir)
369
370 return outputFile
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200371 }
Paul Duffin0c09a432022-11-05 15:28:04 +0000372}
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200373
Paul Duffin0c09a432022-11-05 15:28:04 +0000374// runSoongOnlyBuild runs the standard Soong build in a number of different modes.
375func runSoongOnlyBuild(configuration android.Config, ctx *android.Context, extraNinjaDeps []string) string {
Paul Duffin39eae8f2022-11-05 14:59:52 +0000376 ctx.EventHandler.Begin("soong_build")
377 defer ctx.EventHandler.End("soong_build")
378
Paul Duffin0c09a432022-11-05 15:28:04 +0000379 var stopBefore bootstrap.StopBefore
380 if configuration.BuildMode == android.GenerateModuleGraph {
381 stopBefore = bootstrap.StopBeforeWriteNinja
382 } else if configuration.BuildMode == android.GenerateQueryView || configuration.BuildMode == android.GenerateDocFile {
383 stopBefore = bootstrap.StopBeforePrepareBuildActions
384 } else {
385 stopBefore = bootstrap.DoEverything
386 }
387
388 ninjaDeps := bootstrap.RunBlueprint(cmdlineArgs, stopBefore, ctx.Context, configuration)
389 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
390
391 globListFiles := writeBuildGlobsNinjaFile(ctx, configuration.SoongOutDir(), configuration)
392 ninjaDeps = append(ninjaDeps, globListFiles...)
393
394 // Convert the Soong module graph into Bazel BUILD files.
395 if configuration.BuildMode == android.GenerateQueryView {
396 queryviewMarkerFile := bazelQueryViewDir + ".marker"
397 runQueryView(bazelQueryViewDir, queryviewMarkerFile, configuration, ctx)
398 writeDepFile(queryviewMarkerFile, ctx.EventHandler, ninjaDeps)
399 return queryviewMarkerFile
400 } else if configuration.BuildMode == android.GenerateModuleGraph {
401 writeJsonModuleGraphAndActions(ctx, moduleGraphFile, moduleActionsFile)
402 writeDepFile(moduleGraphFile, ctx.EventHandler, ninjaDeps)
403 return moduleGraphFile
404 } else if configuration.BuildMode == android.GenerateDocFile {
405 // TODO: we could make writeDocs() return the list of documentation files
406 // written and add them to the .d file. Then soong_docs would be re-run
407 // whenever one is deleted.
408 if err := writeDocs(ctx, shared.JoinPath(topDir, docFile)); err != nil {
409 fmt.Fprintf(os.Stderr, "error building Soong documentation: %s\n", err)
410 os.Exit(1)
411 }
412 writeDepFile(docFile, ctx.EventHandler, ninjaDeps)
413 return docFile
414 } else {
415 // The actual output (build.ninja) was written in the RunBlueprint() call
416 // above
417 writeDepFile(cmdlineArgs.OutFile, ctx.EventHandler, ninjaDeps)
Paul Duffinb713ddf2022-11-05 16:14:30 +0000418 return cmdlineArgs.OutFile
Paul Duffin0c09a432022-11-05 15:28:04 +0000419 }
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200420}
421
422// soong_ui dumps the available environment variables to
423// soong.environment.available . Then soong_build itself is run with an empty
424// environment so that the only way environment variables can be accessed is
425// using Config, which tracks access to them.
426
427// At the end of the build, a file called soong.environment.used is written
428// containing the current value of all used environment variables. The next
429// time soong_ui is run, it checks whether any environment variables that was
430// used had changed and if so, it deletes soong.environment.used to cause a
431// rebuild.
432//
433// The dependency of build.ninja on soong.environment.used is declared in
434// build.ninja.d
435func parseAvailableEnv() map[string]string {
436 if availableEnvFile == "" {
437 fmt.Fprintf(os.Stderr, "--available_env not set\n")
438 os.Exit(1)
439 }
440
441 result, err := shared.EnvFromFile(shared.JoinPath(topDir, availableEnvFile))
442 if err != nil {
443 fmt.Fprintf(os.Stderr, "error reading available environment file '%s': %s\n", availableEnvFile, err)
444 os.Exit(1)
445 }
446
447 return result
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200448}
449
Colin Cross3f40fa42015-01-30 17:27:36 -0800450func main() {
451 flag.Parse()
452
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100453 shared.ReexecWithDelveMaybe(delveListen, delvePath)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100454 android.InitSandbox(topDir)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100455
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200456 availableEnv := parseAvailableEnv()
Lukacs T. Berki53b2f362021-04-12 14:04:24 +0200457
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200458 configuration := newConfig(availableEnv)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100459 extraNinjaDeps := []string{
460 configuration.ProductVariablesFileName,
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200461 usedEnvFile,
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100462 }
Colin Crossaa812d12019-06-19 13:33:24 -0700463
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100464 if configuration.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
465 configuration.SetAllowMissingDependencies()
466 }
467
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100468 if shared.IsDebugging() {
Colin Crossaa812d12019-06-19 13:33:24 -0700469 // Add a non-existent file to the dependencies so that soong_build will rerun when the debugger is
470 // enabled even if it completed successfully.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200471 extraNinjaDeps = append(extraNinjaDeps, filepath.Join(configuration.SoongOutDir(), "always_rerun_for_delve"))
Colin Crossaa812d12019-06-19 13:33:24 -0700472 }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500473
Dan Willemsenccf36aa2022-04-20 23:11:43 -0700474 // Bypass configuration.Getenv, as LOG_DIR does not need to be dependency tracked. By definition, it will
475 // change between every CI build, so tracking it would require re-running Soong for every build.
476 logDir := availableEnv["LOG_DIR"]
477
Joe Onorato2e5e4012022-06-07 17:16:08 -0700478 ctx := newContext(configuration)
Joe Onorato2e5e4012022-06-07 17:16:08 -0700479
Paul Duffinf4906562022-11-05 14:21:16 +0000480 finalOutputFile := doChosenActivity(ctx, configuration, extraNinjaDeps, logDir)
Joe Onorato2e5e4012022-06-07 17:16:08 -0700481
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200482 writeUsedEnvironmentFile(configuration, finalOutputFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100483}
484
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200485func writeUsedEnvironmentFile(configuration android.Config, finalOutputFile string) {
486 if usedEnvFile == "" {
487 return
488 }
489
490 path := shared.JoinPath(topDir, usedEnvFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100491 data, err := shared.EnvFileContents(configuration.EnvDeps())
492 if err != nil {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200493 fmt.Fprintf(os.Stderr, "error writing used environment file '%s': %s\n", usedEnvFile, err)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100494 os.Exit(1)
495 }
496
Usta Shrestha2ba28a32022-10-24 11:33:09 -0400497 if preexistingData, err := os.ReadFile(path); err != nil {
498 if !os.IsNotExist(err) {
499 fmt.Fprintf(os.Stderr, "error reading used environment file '%s': %s\n", usedEnvFile, err)
500 os.Exit(1)
501 }
502 } else if bytes.Equal(preexistingData, data) {
503 // used environment file is unchanged
504 return
505 }
506 if err = os.WriteFile(path, data, 0666); err != nil {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200507 fmt.Fprintf(os.Stderr, "error writing used environment file '%s': %s\n", usedEnvFile, err)
Lukacs T. Berkic99c9472021-03-24 10:50:06 +0100508 os.Exit(1)
509 }
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200510 // Touch the output file so that it's not older than the file we just
Lukacs T. Berkic99c9472021-03-24 10:50:06 +0100511 // wrote. We can't write the environment file earlier because one an access
512 // new environment variables while writing it.
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200513 touch(shared.JoinPath(topDir, finalOutputFile))
Colin Cross3f40fa42015-01-30 17:27:36 -0800514}
Jingwen Chen5ba7e472020-07-15 10:06:41 +0000515
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200516func touch(path string) {
517 f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
518 if err != nil {
519 fmt.Fprintf(os.Stderr, "Error touching '%s': %s\n", path, err)
520 os.Exit(1)
521 }
522
523 err = f.Close()
524 if err != nil {
525 fmt.Fprintf(os.Stderr, "Error touching '%s': %s\n", path, err)
526 os.Exit(1)
527 }
528
529 currentTime := time.Now().Local()
530 err = os.Chtimes(path, currentTime, currentTime)
531 if err != nil {
532 fmt.Fprintf(os.Stderr, "error touching '%s': %s\n", path, err)
533 os.Exit(1)
534 }
535}
536
Cole Faust324a92e2022-08-23 15:29:05 -0700537// Find BUILD files in the srcDir which are not in the allowlist
538// (android.Bp2BuildConversionAllowlist#ShouldKeepExistingBuildFileForDir)
539// and return their paths so they can be left out of the Bazel workspace dir (i.e. ignored)
540func getPathsToIgnoredBuildFiles(config android.Bp2BuildConversionAllowlist, topDir string, srcDirBazelFiles []string, verbose bool) []string {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400541 paths := make([]string, 0)
542
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400543 for _, srcDirBazelFileRelativePath := range srcDirBazelFiles {
544 srcDirBazelFileFullPath := shared.JoinPath(topDir, srcDirBazelFileRelativePath)
545 fileInfo, err := os.Stat(srcDirBazelFileFullPath)
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400546 if err != nil {
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400547 // Warn about error, but continue trying to check files
548 fmt.Fprintf(os.Stderr, "WARNING: Error accessing path '%s', err: %s\n", srcDirBazelFileFullPath, err)
549 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400550 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400551 if fileInfo.IsDir() {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400552 // Don't ignore entire directories
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400553 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400554 }
Cole Faust324a92e2022-08-23 15:29:05 -0700555 if fileInfo.Name() != "BUILD" && fileInfo.Name() != "BUILD.bazel" {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400556 // Don't ignore this file - it is not a build file
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400557 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400558 }
Cole Faust324a92e2022-08-23 15:29:05 -0700559 if config.ShouldKeepExistingBuildFileForDir(filepath.Dir(srcDirBazelFileRelativePath)) {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400560 // Don't ignore this existing build file
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400561 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400562 }
Liz Kammer1aefc9d2021-10-18 16:59:00 -0400563 if verbose {
564 fmt.Fprintf(os.Stderr, "Ignoring existing BUILD file: %s\n", srcDirBazelFileRelativePath)
565 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400566 paths = append(paths, srcDirBazelFileRelativePath)
567 }
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400568
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400569 return paths
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400570}
571
572// Returns temporary symlink forest excludes necessary for bazel build //external/... (and bazel build //frameworks/...) to work
573func getTemporaryExcludes() []string {
574 excludes := make([]string, 0)
575
576 // FIXME: 'autotest_lib' is a symlink back to external/autotest, and this causes an infinite symlink expansion error for Bazel
577 excludes = append(excludes, "external/autotest/venv/autotest_lib")
Jingwen Chenc0c50212022-06-07 10:07:22 +0000578 excludes = append(excludes, "external/autotest/autotest_lib")
579 excludes = append(excludes, "external/autotest/client/autotest_lib/client")
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400580
581 // FIXME: The external/google-fruit/extras/bazel_root/third_party/fruit dir is poison
582 // It contains several symlinks back to real source dirs, and those source dirs contain BUILD files we want to ignore
583 excludes = append(excludes, "external/google-fruit/extras/bazel_root/third_party/fruit")
584
585 // FIXME: 'frameworks/compile/slang' has a filegroup error due to an escaping issue
586 excludes = append(excludes, "frameworks/compile/slang")
587
Jingwen Chenbcfadce2022-11-30 08:44:05 +0000588 // FIXME(b/260809113): 'prebuilts/clang/host/linux-x86/clang-dev' is a tool-generated symlink directory that contains a BUILD file.
589 // The bazel files finder code doesn't traverse into symlink dirs, and hence is not aware of this BUILD file and exclude it accordingly
590 // during symlink forest generation when checking against keepExistingBuildFiles allowlist.
591 //
592 // This is necessary because globs in //prebuilts/clang/host/linux-x86/BUILD
593 // currently assume no subpackages (keepExistingBuildFile is not recursive for that directory).
594 //
595 // This is a bandaid until we the symlink forest logic can intelligently exclude BUILD files found in source symlink dirs according
596 // to the keepExistingBuildFile allowlist.
597 excludes = append(excludes, "prebuilts/clang/host/linux-x86/clang-dev")
598
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400599 return excludes
600}
601
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400602// Read the bazel.list file that the Soong Finder already dumped earlier (hopefully)
603// It contains the locations of BUILD files, BUILD.bazel files, etc. in the source dir
604func getExistingBazelRelatedFiles(topDir string) ([]string, error) {
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200605 bazelFinderFile := filepath.Join(filepath.Dir(cmdlineArgs.ModuleListFile), "bazel.list")
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400606 if !filepath.IsAbs(bazelFinderFile) {
607 // Assume this was a relative path under topDir
608 bazelFinderFile = filepath.Join(topDir, bazelFinderFile)
609 }
610 data, err := ioutil.ReadFile(bazelFinderFile)
611 if err != nil {
612 return nil, err
613 }
614 files := strings.Split(strings.TrimSpace(string(data)), "\n")
615 return files, nil
616}
617
Spandan Das5af0bd32022-09-28 20:43:08 +0000618func bazelArtifacts() []string {
619 return []string{
620 "bazel-bin",
621 "bazel-genfiles",
622 "bazel-out",
623 "bazel-testlogs",
624 "bazel-" + filepath.Base(topDir),
625 }
626}
627
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000628// This could in theory easily be separated into a binary that generically
629// merges two directories into a symlink tree. The main obstacle is that this
630// function currently depends on both Bazel-specific knowledge (the existence
631// of bazel-* symlinks) and configuration (the set of BUILD.bazel files that
632// should and should not be kept)
633//
634// Ideally, bp2build would write a file that contains instructions to the
635// symlink tree creation binary. Then the latter would not need to depend on
636// the very heavy-weight machinery of soong_build .
Paul Duffinb713ddf2022-11-05 16:14:30 +0000637func runSymlinkForestCreation(configuration android.Config, ctx *android.Context, extraNinjaDeps []string, metricsDir string) string {
Paul Duffinb4e8d912022-11-04 13:35:50 +0000638 ctx.EventHandler.Do("symlink_forest", func() {
Usta (Tsering) Shrestha93b2a9b2022-12-01 05:55:35 +0000639 var ninjaDeps []string
640 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000641
Usta (Tsering) Shrestha93b2a9b2022-12-01 05:55:35 +0000642 generatedRoot := shared.JoinPath(configuration.SoongOutDir(), "bp2build")
643 workspaceRoot := shared.JoinPath(configuration.SoongOutDir(), "workspace")
644
645 excludes := bazelArtifacts()
646
647 if outDir[0] != '/' {
648 excludes = append(excludes, outDir)
649 }
650
651 existingBazelRelatedFiles, err := getExistingBazelRelatedFiles(topDir)
652 if err != nil {
653 fmt.Fprintf(os.Stderr, "Error determining existing Bazel-related files: %s\n", err)
654 os.Exit(1)
655 }
656
657 pathsToIgnoredBuildFiles := getPathsToIgnoredBuildFiles(configuration.Bp2buildPackageConfig, topDir, existingBazelRelatedFiles, configuration.IsEnvTrue("BP2BUILD_VERBOSE"))
658 excludes = append(excludes, pathsToIgnoredBuildFiles...)
659 excludes = append(excludes, getTemporaryExcludes()...)
660
661 // PlantSymlinkForest() returns all the directories that were readdir()'ed.
662 // Such a directory SHOULD be added to `ninjaDeps` so that a child directory
663 // or file created/deleted under it would trigger an update of the symlink forest.
664 ctx.EventHandler.Do("plant", func() {
665 symlinkForestDeps := bp2build.PlantSymlinkForest(
666 configuration.IsEnvTrue("BP2BUILD_VERBOSE"), topDir, workspaceRoot, generatedRoot, excludes)
667 ninjaDeps = append(ninjaDeps, symlinkForestDeps...)
668 })
669
670 writeDepFile(symlinkForestMarker, ctx.EventHandler, ninjaDeps)
671 touch(shared.JoinPath(topDir, symlinkForestMarker))
672 })
usta4f5d2c12022-10-28 23:32:01 -0400673 codegenMetrics := bp2build.ReadCodegenMetrics(metricsDir)
674 if codegenMetrics == nil {
675 m := bp2build.CreateCodegenMetrics()
676 codegenMetrics = &m
677 } else {
678 //TODO (usta) we cannot determine if we loaded a stale file, i.e. from an unrelated prior
679 //invocation of codegen. We should simply use a separate .pb file
680 }
Paul Duffinb4e8d912022-11-04 13:35:50 +0000681 writeBp2BuildMetrics(codegenMetrics, ctx.EventHandler, metricsDir)
Paul Duffinb713ddf2022-11-05 16:14:30 +0000682
683 return symlinkForestMarker
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000684}
685
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500686// Run Soong in the bp2build mode. This creates a standalone context that registers
687// an alternate pipeline of mutators and singletons specifically for generating
688// Bazel BUILD files instead of Ninja files.
Paul Duffinb713ddf2022-11-05 16:14:30 +0000689func runBp2Build(configuration android.Config, ctx *android.Context, extraNinjaDeps []string, metricsDir string) string {
usta4f5d2c12022-10-28 23:32:01 -0400690 var codegenMetrics *bp2build.CodegenMetrics
Paul Duffinb4e8d912022-11-04 13:35:50 +0000691 ctx.EventHandler.Do("bp2build", func() {
Jingwen Cheneb76c432021-01-28 08:22:12 -0500692
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400693 // Propagate "allow misssing dependencies" bit. This is normally set in
Paul Duffinb4e8d912022-11-04 13:35:50 +0000694 // newContext(), but we create ctx without calling that method.
695 ctx.SetAllowMissingDependencies(configuration.AllowMissingDependencies())
696 ctx.SetNameInterface(newNameResolver(configuration))
697 ctx.RegisterForBazelConversion()
698 ctx.SetModuleListFile(cmdlineArgs.ModuleListFile)
Jingwen Cheneb76c432021-01-28 08:22:12 -0500699
Usta Shresthaa117c582022-10-04 12:13:25 -0400700 var ninjaDeps []string
701 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
702
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400703 // Run the loading and analysis pipeline to prepare the graph of regular
704 // Modules parsed from Android.bp files, and the BazelTargetModules mapped
705 // from the regular Modules.
Paul Duffinb4e8d912022-11-04 13:35:50 +0000706 ctx.EventHandler.Do("bootstrap", func() {
Usta Shresthaa117c582022-10-04 12:13:25 -0400707 blueprintArgs := cmdlineArgs
Paul Duffinb4e8d912022-11-04 13:35:50 +0000708 bootstrapDeps := bootstrap.RunBlueprint(blueprintArgs, bootstrap.StopBeforePrepareBuildActions, ctx.Context, configuration)
Usta Shresthaa117c582022-10-04 12:13:25 -0400709 ninjaDeps = append(ninjaDeps, bootstrapDeps...)
710 })
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200711
Paul Duffinb4e8d912022-11-04 13:35:50 +0000712 globListFiles := writeBuildGlobsNinjaFile(ctx, configuration.SoongOutDir(), configuration)
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400713 ninjaDeps = append(ninjaDeps, globListFiles...)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200714
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400715 // Run the code-generation phase to convert BazelTargetModules to BUILD files
Usta Shresthaa117c582022-10-04 12:13:25 -0400716 // and print conversion codegenMetrics to the user.
Paul Duffinb4e8d912022-11-04 13:35:50 +0000717 codegenContext := bp2build.NewCodegenContext(configuration, ctx, bp2build.Bp2Build)
718 ctx.EventHandler.Do("codegen", func() {
Usta Shresthaa117c582022-10-04 12:13:25 -0400719 codegenMetrics = bp2build.Codegen(codegenContext)
720 })
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200721
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400722 ninjaDeps = append(ninjaDeps, codegenContext.AdditionalNinjaDeps()...)
Chris Parsons715b08f2022-03-22 19:23:40 -0400723
Paul Duffinb4e8d912022-11-04 13:35:50 +0000724 writeDepFile(bp2buildMarker, ctx.EventHandler, ninjaDeps)
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000725 touch(shared.JoinPath(topDir, bp2buildMarker))
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400726 })
Chris Parsons715b08f2022-03-22 19:23:40 -0400727
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200728 // Only report metrics when in bp2build mode. The metrics aren't relevant
729 // for queryview, since that's a total repo-wide conversion and there's a
730 // 1:1 mapping for each module.
Sasha Smundak0fd93e02022-05-19 19:34:31 -0700731 if configuration.IsEnvTrue("BP2BUILD_VERBOSE") {
Usta Shresthaa117c582022-10-04 12:13:25 -0400732 codegenMetrics.Print()
Sasha Smundak0fd93e02022-05-19 19:34:31 -0700733 }
Paul Duffinb4e8d912022-11-04 13:35:50 +0000734 writeBp2BuildMetrics(codegenMetrics, ctx.EventHandler, metricsDir)
Paul Duffinb713ddf2022-11-05 16:14:30 +0000735 return bp2buildMarker
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500736}
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500737
738// Write Bp2Build metrics into $LOG_DIR
Paul Duffinf4906562022-11-05 14:21:16 +0000739func writeBp2BuildMetrics(codegenMetrics *bp2build.CodegenMetrics, eventHandler *metrics.EventHandler, metricsDir string) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400740 for _, event := range eventHandler.CompletedEvents() {
usta4f5d2c12022-10-28 23:32:01 -0400741 codegenMetrics.AddEvent(&bp2build_metrics_proto.Event{
742 Name: event.Id,
743 StartTime: uint64(event.Start.UnixNano()),
744 RealTime: event.RuntimeNanoseconds(),
745 })
Chris Parsons715b08f2022-03-22 19:23:40 -0400746 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500747 if len(metricsDir) < 1 {
748 fmt.Fprintf(os.Stderr, "\nMissing required env var for generating bp2build metrics: LOG_DIR\n")
749 os.Exit(1)
750 }
Chris Parsons715b08f2022-03-22 19:23:40 -0400751 codegenMetrics.Write(metricsDir)
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500752}
MarkDacek0d5bca52022-10-10 20:07:48 +0000753
754func readBazelPaths(configuration android.Config) ([]string, error) {
755 depsPath := configuration.Getenv("BAZEL_DEPS_FILE")
756
757 data, err := os.ReadFile(depsPath)
758 if err != nil {
759 return nil, err
760 }
761 paths := strings.Split(strings.TrimSpace(string(data)), "\n")
762 return paths, nil
763}