blob: 4b3161b33100d9840f9983ca23a2324ead869cb8 [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 (
18 "flag"
19 "fmt"
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +010020 "io/ioutil"
Colin Cross3f40fa42015-01-30 17:27:36 -080021 "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"
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020027 "android/soong/bp2build"
Lukacs T. Berki7690c092021-02-26 14:27:36 +010028 "android/soong/shared"
Chris Parsons715b08f2022-03-22 19:23:40 -040029 "android/soong/ui/metrics/bp2build_metrics_proto"
Lukacs T. Berkie571dc32021-08-25 14:14:13 +020030
Colin Cross70b40592015-03-23 12:57:34 -070031 "github.com/google/blueprint/bootstrap"
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +020032 "github.com/google/blueprint/deptools"
Chris Parsons715b08f2022-03-22 19:23:40 -040033 "github.com/google/blueprint/metrics"
Dan Willemsen66213a62021-09-21 17:50:30 -070034 androidProtobuf "google.golang.org/protobuf/android"
Colin Cross3f40fa42015-01-30 17:27:36 -080035)
36
Colin Crosse87040b2017-12-11 15:52:26 -080037var (
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020038 topDir string
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +020039 outDir string
Lukacs T. Berkid6cee7e2021-09-01 16:25:51 +020040 soongOutDir string
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020041 availableEnvFile string
42 usedEnvFile string
43
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +020044 runGoTests bool
45
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +020046 globFile string
47 globListDir string
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020048 delveListen string
49 delvePath string
50
Lukacs T. Berkie571dc32021-08-25 14:14:13 +020051 moduleGraphFile string
kgui67007242022-01-25 13:50:25 +080052 moduleActionsFile string
Jingwen Chen50f93d22020-11-05 07:42:11 -050053 docFile string
54 bazelQueryViewDir string
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020055 bp2buildMarker string
Lukacs T. Berkif9008072021-08-16 15:24:48 +020056
57 cmdlineArgs bootstrap.Args
Colin Crosse87040b2017-12-11 15:52:26 -080058)
59
60func init() {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020061 // Flags that make sense in every mode
Lukacs T. Berki7690c092021-02-26 14:27:36 +010062 flag.StringVar(&topDir, "top", "", "Top directory of the Android source tree")
Lukacs T. Berkid6cee7e2021-09-01 16:25:51 +020063 flag.StringVar(&soongOutDir, "soong_out", "", "Soong output directory (usually $TOP/out/soong)")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020064 flag.StringVar(&availableEnvFile, "available_env", "", "File containing available environment variables")
65 flag.StringVar(&usedEnvFile, "used_env", "", "File containing used environment variables")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020066 flag.StringVar(&globFile, "globFile", "build-globs.ninja", "the Ninja file of globs to output")
67 flag.StringVar(&globListDir, "globListDir", "", "the directory containing the glob list files")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +020068 flag.StringVar(&outDir, "out", "", "the ninja builddir directory")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020069 flag.StringVar(&cmdlineArgs.ModuleListFile, "l", "", "file that lists filepaths to parse")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020070
71 // Debug flags
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +010072 flag.StringVar(&delveListen, "delve_listen", "", "Delve port to listen on for debugging")
73 flag.StringVar(&delvePath, "delve_path", "", "Path to Delve. Only used if --delve_listen is set")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020074 flag.StringVar(&cmdlineArgs.Cpuprofile, "cpuprofile", "", "write cpu profile to file")
75 flag.StringVar(&cmdlineArgs.TraceFile, "trace", "", "write trace to file")
76 flag.StringVar(&cmdlineArgs.Memprofile, "memprofile", "", "write memory profile to file")
77 flag.BoolVar(&cmdlineArgs.NoGC, "nogc", false, "turn off GC for debugging")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020078
79 // Flags representing various modes soong_build can run in
Lukacs T. Berkie571dc32021-08-25 14:14:13 +020080 flag.StringVar(&moduleGraphFile, "module_graph_file", "", "JSON module graph file to output")
kgui67007242022-01-25 13:50:25 +080081 flag.StringVar(&moduleActionsFile, "module_actions_file", "", "JSON file to output inputs/outputs of actions of modules")
Colin Crosse87040b2017-12-11 15:52:26 -080082 flag.StringVar(&docFile, "soong_docs", "", "build documentation file to output")
Lukacs T. Berki47a9d0c2021-03-08 16:34:09 +010083 flag.StringVar(&bazelQueryViewDir, "bazel_queryview_dir", "", "path to the bazel queryview directory relative to --top")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020084 flag.StringVar(&bp2buildMarker, "bp2build_marker", "", "If set, run bp2build, touch the specified marker file then exit")
Lukacs T. Berkif9008072021-08-16 15:24:48 +020085 flag.StringVar(&cmdlineArgs.OutFile, "o", "build.ninja", "the Ninja file to output")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020086 flag.BoolVar(&cmdlineArgs.EmptyNinjaFile, "empty-ninja-file", false, "write out a 0-byte ninja file")
87
88 // Flags that probably shouldn't be flags of soong_build but we haven't found
89 // the time to remove them yet
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +020090 flag.BoolVar(&runGoTests, "t", false, "build and run go tests during bootstrap")
Dan Willemsen66213a62021-09-21 17:50:30 -070091
92 // Disable deterministic randomization in the protobuf package, so incremental
93 // builds with unrelated Soong changes don't trigger large rebuilds (since we
94 // write out text protos in command lines, and command line changes trigger
95 // rebuilds).
96 androidProtobuf.DisableRand()
Colin Crosse87040b2017-12-11 15:52:26 -080097}
98
Jeff Gaston088e29e2017-11-29 16:47:17 -080099func newNameResolver(config android.Config) *android.NameResolver {
100 namespacePathsToExport := make(map[string]bool)
101
Dan Willemsen3fb1fae2018-03-12 15:30:26 -0700102 for _, namespaceName := range config.ExportedNamespaces() {
Jeff Gaston088e29e2017-11-29 16:47:17 -0800103 namespacePathsToExport[namespaceName] = true
104 }
105
106 namespacePathsToExport["."] = true // always export the root namespace
107
108 exportFilter := func(namespace *android.Namespace) bool {
109 return namespacePathsToExport[namespace.Path]
110 }
111
112 return android.NewNameResolver(exportFilter)
113}
114
Lukacs T. Berkiffc9e8d2021-09-07 17:54:38 +0200115func newContext(configuration android.Config) *android.Context {
Colin Crossae8600b2020-10-29 17:09:13 -0700116 ctx := android.NewContext(configuration)
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500117 ctx.Register()
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400118 ctx.SetNameInterface(newNameResolver(configuration))
119 ctx.SetAllowMissingDependencies(configuration.AllowMissingDependencies())
120 return ctx
121}
122
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200123func newConfig(availableEnv map[string]string) android.Config {
124 configuration, err := android.NewConfig(cmdlineArgs.ModuleListFile, runGoTests, outDir, soongOutDir, availableEnv)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400125 if err != nil {
126 fmt.Fprintf(os.Stderr, "%s", err)
127 os.Exit(1)
128 }
129 return configuration
130}
131
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200132// Bazel-enabled mode. Soong runs in two passes.
133// First pass: Analyze the build tree, but only store all bazel commands
134// needed to correctly evaluate the tree in the second pass.
135// TODO(cparsons): Don't output any ninja file, as the second pass will overwrite
136// the incorrect results from the first pass, and file I/O is expensive.
137func runMixedModeBuild(configuration android.Config, firstCtx *android.Context, extraNinjaDeps []string) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400138 firstCtx.EventHandler.Begin("mixed_build")
139 defer firstCtx.EventHandler.End("mixed_build")
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200140
Chris Parsons715b08f2022-03-22 19:23:40 -0400141 firstCtx.EventHandler.Begin("prepare")
142 bootstrap.RunBlueprint(cmdlineArgs, bootstrap.StopBeforeWriteNinja, firstCtx.Context, configuration)
143 firstCtx.EventHandler.End("prepare")
144
145 firstCtx.EventHandler.Begin("bazel")
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200146 // Invoke bazel commands and save results for second pass.
147 if err := configuration.BazelContext.InvokeBazel(); err != nil {
148 fmt.Fprintf(os.Stderr, "%s", err)
149 os.Exit(1)
150 }
151 // Second pass: Full analysis, using the bazel command results. Output ninja file.
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200152 secondConfig, err := android.ConfigForAdditionalRun(configuration)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200153 if err != nil {
154 fmt.Fprintf(os.Stderr, "%s", err)
155 os.Exit(1)
156 }
Chris Parsons715b08f2022-03-22 19:23:40 -0400157 firstCtx.EventHandler.End("bazel")
158
Lukacs T. Berkiffc9e8d2021-09-07 17:54:38 +0200159 secondCtx := newContext(secondConfig)
Chris Parsons715b08f2022-03-22 19:23:40 -0400160 secondCtx.EventHandler = firstCtx.EventHandler
161 secondCtx.EventHandler.Begin("analyze")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200162 ninjaDeps := bootstrap.RunBlueprint(cmdlineArgs, bootstrap.DoEverything, secondCtx.Context, secondConfig)
Lukacs T. Berki6124c9b2021-04-15 15:06:40 +0200163 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Chris Parsons715b08f2022-03-22 19:23:40 -0400164 secondCtx.EventHandler.End("analyze")
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200165
Chris Parsons715b08f2022-03-22 19:23:40 -0400166 globListFiles := writeBuildGlobsNinjaFile(secondCtx, configuration.SoongOutDir(), configuration)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200167 ninjaDeps = append(ninjaDeps, globListFiles...)
168
Chris Parsons715b08f2022-03-22 19:23:40 -0400169 writeDepFile(cmdlineArgs.OutFile, *secondCtx.EventHandler, ninjaDeps)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200170}
171
172// Run the code-generation phase to convert BazelTargetModules to BUILD files.
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200173func runQueryView(queryviewDir, queryviewMarker string, configuration android.Config, ctx *android.Context) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400174 ctx.EventHandler.Begin("queryview")
175 defer ctx.EventHandler.End("queryview")
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200176 codegenContext := bp2build.NewCodegenContext(configuration, *ctx, bp2build.QueryView)
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200177 absoluteQueryViewDir := shared.JoinPath(topDir, queryviewDir)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200178 if err := createBazelQueryView(codegenContext, absoluteQueryViewDir); err != nil {
179 fmt.Fprintf(os.Stderr, "%s", err)
180 os.Exit(1)
181 }
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200182
183 touch(shared.JoinPath(topDir, queryviewMarker))
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200184}
185
Chris Parsons715b08f2022-03-22 19:23:40 -0400186func writeMetrics(configuration android.Config, eventHandler metrics.EventHandler) {
187 metricsDir := configuration.Getenv("LOG_DIR")
188 if len(metricsDir) < 1 {
189 fmt.Fprintf(os.Stderr, "\nMissing required env var for generating soong metrics: LOG_DIR\n")
190 os.Exit(1)
191 }
192 metricsFile := filepath.Join(metricsDir, "soong_build_metrics.pb")
193 err := android.WriteMetrics(configuration, eventHandler, metricsFile)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200194 if err != nil {
195 fmt.Fprintf(os.Stderr, "error writing soong_build metrics %s: %s", metricsFile, err)
196 os.Exit(1)
197 }
198}
199
kgui67007242022-01-25 13:50:25 +0800200func writeJsonModuleGraphAndActions(ctx *android.Context, graphPath string, actionsPath string) {
201 graphFile, graphErr := os.Create(shared.JoinPath(topDir, graphPath))
202 actionsFile, actionsErr := os.Create(shared.JoinPath(topDir, actionsPath))
203 if graphErr != nil || actionsErr != nil {
204 fmt.Fprintf(os.Stderr, "Graph err: %s, actions err: %s", graphErr, actionsErr)
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200205 os.Exit(1)
206 }
207
kgui67007242022-01-25 13:50:25 +0800208 defer graphFile.Close()
209 defer actionsFile.Close()
210 ctx.Context.PrintJSONGraphAndActions(graphFile, actionsFile)
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200211}
212
Chris Parsons715b08f2022-03-22 19:23:40 -0400213func writeBuildGlobsNinjaFile(ctx *android.Context, buildDir string, config interface{}) []string {
214 ctx.EventHandler.Begin("globs_ninja_file")
215 defer ctx.EventHandler.End("globs_ninja_file")
216
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200217 globDir := bootstrap.GlobDirectory(buildDir, globListDir)
218 bootstrap.WriteBuildGlobsNinjaFile(&bootstrap.GlobSingleton{
Chris Parsons715b08f2022-03-22 19:23:40 -0400219 GlobLister: ctx.Globs,
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200220 GlobFile: globFile,
221 GlobDir: globDir,
Chris Parsons715b08f2022-03-22 19:23:40 -0400222 SrcDir: ctx.SrcDir(),
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200223 }, config)
224 return bootstrap.GlobFileListFiles(globDir)
225}
226
Chris Parsons715b08f2022-03-22 19:23:40 -0400227func writeDepFile(outputFile string, eventHandler metrics.EventHandler, ninjaDeps []string) {
228 eventHandler.Begin("ninja_deps")
229 defer eventHandler.End("ninja_deps")
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200230 depFile := shared.JoinPath(topDir, outputFile+".d")
231 err := deptools.WriteDepFile(depFile, outputFile, ninjaDeps)
232 if err != nil {
233 fmt.Fprintf(os.Stderr, "Error writing depfile '%s': %s\n", depFile, err)
234 os.Exit(1)
235 }
236}
237
Jingwen Chen4fabaf52021-05-25 02:40:29 +0000238// doChosenActivity runs Soong for a specific activity, like bp2build, queryview
239// or the actual Soong build for the build.ninja file. Returns the top level
240// output file of the specific activity.
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200241func doChosenActivity(configuration android.Config, extraNinjaDeps []string) string {
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200242 mixedModeBuild := configuration.BazelContext.BazelEnabled()
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200243 generateBazelWorkspace := bp2buildMarker != ""
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200244 generateQueryView := bazelQueryViewDir != ""
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200245 generateModuleGraphFile := moduleGraphFile != ""
246 generateDocFile := docFile != ""
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200247
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200248 if generateBazelWorkspace {
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200249 // Run the alternate pipeline of bp2build mutators and singleton to convert
250 // Blueprint to BUILD files before everything else.
251 runBp2Build(configuration, extraNinjaDeps)
Jingwen Chen4fabaf52021-05-25 02:40:29 +0000252 return bp2buildMarker
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200253 }
254
Lukacs T. Berkieb0454b2021-10-26 13:32:59 +0200255 blueprintArgs := cmdlineArgs
256
Lukacs T. Berkiffc9e8d2021-09-07 17:54:38 +0200257 ctx := newContext(configuration)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200258 if mixedModeBuild {
259 runMixedModeBuild(configuration, ctx, extraNinjaDeps)
260 } else {
Chris Parsons715b08f2022-03-22 19:23:40 -0400261 var stopBefore bootstrap.StopBefore
262 if generateModuleGraphFile {
263 stopBefore = bootstrap.StopBeforeWriteNinja
264 } else if generateQueryView {
265 stopBefore = bootstrap.StopBeforePrepareBuildActions
266 } else if generateDocFile {
267 stopBefore = bootstrap.StopBeforePrepareBuildActions
268 } else {
269 stopBefore = bootstrap.DoEverything
270 }
271
Lukacs T. Berkiffc9e8d2021-09-07 17:54:38 +0200272 ninjaDeps := bootstrap.RunBlueprint(blueprintArgs, stopBefore, ctx.Context, configuration)
Lukacs T. Berki6124c9b2021-04-15 15:06:40 +0200273 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200274
Chris Parsons715b08f2022-03-22 19:23:40 -0400275 globListFiles := writeBuildGlobsNinjaFile(ctx, configuration.SoongOutDir(), configuration)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200276 ninjaDeps = append(ninjaDeps, globListFiles...)
277
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200278 // Convert the Soong module graph into Bazel BUILD files.
279 if generateQueryView {
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200280 queryviewMarkerFile := bazelQueryViewDir + ".marker"
281 runQueryView(bazelQueryViewDir, queryviewMarkerFile, configuration, ctx)
Chris Parsons715b08f2022-03-22 19:23:40 -0400282 writeDepFile(queryviewMarkerFile, *ctx.EventHandler, ninjaDeps)
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200283 return queryviewMarkerFile
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200284 } else if generateModuleGraphFile {
kgui67007242022-01-25 13:50:25 +0800285 writeJsonModuleGraphAndActions(ctx, moduleGraphFile, moduleActionsFile)
Chris Parsons715b08f2022-03-22 19:23:40 -0400286 writeDepFile(moduleGraphFile, *ctx.EventHandler, ninjaDeps)
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200287 return moduleGraphFile
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200288 } else if generateDocFile {
289 // TODO: we could make writeDocs() return the list of documentation files
290 // written and add them to the .d file. Then soong_docs would be re-run
291 // whenever one is deleted.
292 if err := writeDocs(ctx, shared.JoinPath(topDir, docFile)); err != nil {
293 fmt.Fprintf(os.Stderr, "error building Soong documentation: %s\n", err)
294 os.Exit(1)
295 }
Chris Parsons715b08f2022-03-22 19:23:40 -0400296 writeDepFile(docFile, *ctx.EventHandler, ninjaDeps)
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200297 return docFile
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200298 } else {
299 // The actual output (build.ninja) was written in the RunBlueprint() call
300 // above
Chris Parsons715b08f2022-03-22 19:23:40 -0400301 writeDepFile(cmdlineArgs.OutFile, *ctx.EventHandler, ninjaDeps)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200302 }
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200303 }
304
Chris Parsons715b08f2022-03-22 19:23:40 -0400305 writeMetrics(configuration, *ctx.EventHandler)
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200306 return cmdlineArgs.OutFile
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200307}
308
309// soong_ui dumps the available environment variables to
310// soong.environment.available . Then soong_build itself is run with an empty
311// environment so that the only way environment variables can be accessed is
312// using Config, which tracks access to them.
313
314// At the end of the build, a file called soong.environment.used is written
315// containing the current value of all used environment variables. The next
316// time soong_ui is run, it checks whether any environment variables that was
317// used had changed and if so, it deletes soong.environment.used to cause a
318// rebuild.
319//
320// The dependency of build.ninja on soong.environment.used is declared in
321// build.ninja.d
322func parseAvailableEnv() map[string]string {
323 if availableEnvFile == "" {
324 fmt.Fprintf(os.Stderr, "--available_env not set\n")
325 os.Exit(1)
326 }
327
328 result, err := shared.EnvFromFile(shared.JoinPath(topDir, availableEnvFile))
329 if err != nil {
330 fmt.Fprintf(os.Stderr, "error reading available environment file '%s': %s\n", availableEnvFile, err)
331 os.Exit(1)
332 }
333
334 return result
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200335}
336
Colin Cross3f40fa42015-01-30 17:27:36 -0800337func main() {
338 flag.Parse()
339
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100340 shared.ReexecWithDelveMaybe(delveListen, delvePath)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100341 android.InitSandbox(topDir)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100342
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200343 availableEnv := parseAvailableEnv()
Lukacs T. Berki53b2f362021-04-12 14:04:24 +0200344
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200345 configuration := newConfig(availableEnv)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100346 extraNinjaDeps := []string{
347 configuration.ProductVariablesFileName,
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200348 usedEnvFile,
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100349 }
Colin Crossaa812d12019-06-19 13:33:24 -0700350
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100351 if configuration.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
352 configuration.SetAllowMissingDependencies()
353 }
354
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100355 if shared.IsDebugging() {
Colin Crossaa812d12019-06-19 13:33:24 -0700356 // Add a non-existent file to the dependencies so that soong_build will rerun when the debugger is
357 // enabled even if it completed successfully.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200358 extraNinjaDeps = append(extraNinjaDeps, filepath.Join(configuration.SoongOutDir(), "always_rerun_for_delve"))
Colin Crossaa812d12019-06-19 13:33:24 -0700359 }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500360
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200361 finalOutputFile := doChosenActivity(configuration, extraNinjaDeps)
Chris Parsons715b08f2022-03-22 19:23:40 -0400362
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200363 writeUsedEnvironmentFile(configuration, finalOutputFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100364}
365
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200366func writeUsedEnvironmentFile(configuration android.Config, finalOutputFile string) {
367 if usedEnvFile == "" {
368 return
369 }
370
371 path := shared.JoinPath(topDir, usedEnvFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100372 data, err := shared.EnvFileContents(configuration.EnvDeps())
373 if err != nil {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200374 fmt.Fprintf(os.Stderr, "error writing used environment file '%s': %s\n", usedEnvFile, err)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100375 os.Exit(1)
376 }
377
378 err = ioutil.WriteFile(path, data, 0666)
379 if err != nil {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200380 fmt.Fprintf(os.Stderr, "error writing used environment file '%s': %s\n", usedEnvFile, err)
Lukacs T. Berkic99c9472021-03-24 10:50:06 +0100381 os.Exit(1)
382 }
383
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200384 // Touch the output file so that it's not older than the file we just
Lukacs T. Berkic99c9472021-03-24 10:50:06 +0100385 // wrote. We can't write the environment file earlier because one an access
386 // new environment variables while writing it.
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200387 touch(shared.JoinPath(topDir, finalOutputFile))
Colin Cross3f40fa42015-01-30 17:27:36 -0800388}
Jingwen Chen5ba7e472020-07-15 10:06:41 +0000389
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200390func touch(path string) {
391 f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
392 if err != nil {
393 fmt.Fprintf(os.Stderr, "Error touching '%s': %s\n", path, err)
394 os.Exit(1)
395 }
396
397 err = f.Close()
398 if err != nil {
399 fmt.Fprintf(os.Stderr, "Error touching '%s': %s\n", path, err)
400 os.Exit(1)
401 }
402
403 currentTime := time.Now().Local()
404 err = os.Chtimes(path, currentTime, currentTime)
405 if err != nil {
406 fmt.Fprintf(os.Stderr, "error touching '%s': %s\n", path, err)
407 os.Exit(1)
408 }
409}
410
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400411// Find BUILD files in the srcDir which...
412//
413// - are not on the allow list (android/bazel.go#ShouldKeepExistingBuildFileForDir())
414//
415// - won't be overwritten by corresponding bp2build generated files
416//
417// And return their paths so they can be left out of the Bazel workspace dir (i.e. ignored)
Liz Kammer1aefc9d2021-10-18 16:59:00 -0400418func getPathsToIgnoredBuildFiles(topDir string, generatedRoot string, srcDirBazelFiles []string, verbose bool) []string {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400419 paths := make([]string, 0)
420
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400421 for _, srcDirBazelFileRelativePath := range srcDirBazelFiles {
422 srcDirBazelFileFullPath := shared.JoinPath(topDir, srcDirBazelFileRelativePath)
423 fileInfo, err := os.Stat(srcDirBazelFileFullPath)
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400424 if err != nil {
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400425 // Warn about error, but continue trying to check files
426 fmt.Fprintf(os.Stderr, "WARNING: Error accessing path '%s', err: %s\n", srcDirBazelFileFullPath, err)
427 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400428 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400429 if fileInfo.IsDir() {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400430 // Don't ignore entire directories
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400431 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400432 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400433 if !(fileInfo.Name() == "BUILD" || fileInfo.Name() == "BUILD.bazel") {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400434 // Don't ignore this file - it is not a build file
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400435 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400436 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400437 srcDirBazelFileDir := filepath.Dir(srcDirBazelFileRelativePath)
438 if android.ShouldKeepExistingBuildFileForDir(srcDirBazelFileDir) {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400439 // Don't ignore this existing build file
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400440 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400441 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400442 correspondingBp2BuildFile := shared.JoinPath(topDir, generatedRoot, srcDirBazelFileRelativePath)
443 if _, err := os.Stat(correspondingBp2BuildFile); err == nil {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400444 // If bp2build generated an alternate BUILD file, don't exclude this workspace path
445 // BUILD file clash resolution happens later in the symlink forest creation
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400446 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400447 }
Liz Kammer1aefc9d2021-10-18 16:59:00 -0400448 if verbose {
449 fmt.Fprintf(os.Stderr, "Ignoring existing BUILD file: %s\n", srcDirBazelFileRelativePath)
450 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400451 paths = append(paths, srcDirBazelFileRelativePath)
452 }
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400453
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400454 return paths
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400455}
456
457// Returns temporary symlink forest excludes necessary for bazel build //external/... (and bazel build //frameworks/...) to work
458func getTemporaryExcludes() []string {
459 excludes := make([]string, 0)
460
461 // FIXME: 'autotest_lib' is a symlink back to external/autotest, and this causes an infinite symlink expansion error for Bazel
462 excludes = append(excludes, "external/autotest/venv/autotest_lib")
463
464 // FIXME: The external/google-fruit/extras/bazel_root/third_party/fruit dir is poison
465 // It contains several symlinks back to real source dirs, and those source dirs contain BUILD files we want to ignore
466 excludes = append(excludes, "external/google-fruit/extras/bazel_root/third_party/fruit")
467
468 // FIXME: 'frameworks/compile/slang' has a filegroup error due to an escaping issue
469 excludes = append(excludes, "frameworks/compile/slang")
470
471 return excludes
472}
473
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400474// Read the bazel.list file that the Soong Finder already dumped earlier (hopefully)
475// It contains the locations of BUILD files, BUILD.bazel files, etc. in the source dir
476func getExistingBazelRelatedFiles(topDir string) ([]string, error) {
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200477 bazelFinderFile := filepath.Join(filepath.Dir(cmdlineArgs.ModuleListFile), "bazel.list")
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400478 if !filepath.IsAbs(bazelFinderFile) {
479 // Assume this was a relative path under topDir
480 bazelFinderFile = filepath.Join(topDir, bazelFinderFile)
481 }
482 data, err := ioutil.ReadFile(bazelFinderFile)
483 if err != nil {
484 return nil, err
485 }
486 files := strings.Split(strings.TrimSpace(string(data)), "\n")
487 return files, nil
488}
489
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500490// Run Soong in the bp2build mode. This creates a standalone context that registers
491// an alternate pipeline of mutators and singletons specifically for generating
492// Bazel BUILD files instead of Ninja files.
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200493func runBp2Build(configuration android.Config, extraNinjaDeps []string) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400494 eventHandler := metrics.EventHandler{}
495 eventHandler.Begin("bp2build")
496
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500497 // Register an alternate set of singletons and mutators for bazel
498 // conversion for Bazel conversion.
499 bp2buildCtx := android.NewContext(configuration)
Jingwen Cheneb76c432021-01-28 08:22:12 -0500500
Jingwen Chena47f28d2021-11-02 16:43:57 +0000501 // Soong internals like LoadHooks behave differently when running as
502 // bp2build. This is the bit to differentiate between Soong-as-Soong and
503 // Soong-as-bp2build.
504 bp2buildCtx.SetRunningAsBp2build()
505
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200506 // Propagate "allow misssing dependencies" bit. This is normally set in
507 // newContext(), but we create bp2buildCtx without calling that method.
508 bp2buildCtx.SetAllowMissingDependencies(configuration.AllowMissingDependencies())
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500509 bp2buildCtx.SetNameInterface(newNameResolver(configuration))
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200510 bp2buildCtx.RegisterForBazelConversion()
Jingwen Cheneb76c432021-01-28 08:22:12 -0500511
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500512 // The bp2build process is a purely functional process that only depends on
513 // Android.bp files. It must not depend on the values of per-build product
514 // configurations or variables, since those will generate different BUILD
515 // files based on how the user has configured their tree.
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200516 bp2buildCtx.SetModuleListFile(cmdlineArgs.ModuleListFile)
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200517 modulePaths, err := bp2buildCtx.ListModulePaths(".")
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500518 if err != nil {
519 panic(err)
520 }
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500521
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100522 extraNinjaDeps = append(extraNinjaDeps, modulePaths...)
523
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500524 // Run the loading and analysis pipeline to prepare the graph of regular
525 // Modules parsed from Android.bp files, and the BazelTargetModules mapped
526 // from the regular Modules.
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200527 blueprintArgs := cmdlineArgs
Lukacs T. Berkiffc9e8d2021-09-07 17:54:38 +0200528 ninjaDeps := bootstrap.RunBlueprint(blueprintArgs, bootstrap.StopBeforePrepareBuildActions, bp2buildCtx.Context, configuration)
Lukacs T. Berki6124c9b2021-04-15 15:06:40 +0200529 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200530
Chris Parsons715b08f2022-03-22 19:23:40 -0400531 globListFiles := writeBuildGlobsNinjaFile(bp2buildCtx, configuration.SoongOutDir(), configuration)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200532 ninjaDeps = append(ninjaDeps, globListFiles...)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200533
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200534 // Run the code-generation phase to convert BazelTargetModules to BUILD files
535 // and print conversion metrics to the user.
536 codegenContext := bp2build.NewCodegenContext(configuration, *bp2buildCtx, bp2build.Bp2Build)
537 metrics := bp2build.Codegen(codegenContext)
538
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200539 generatedRoot := shared.JoinPath(configuration.SoongOutDir(), "bp2build")
540 workspaceRoot := shared.JoinPath(configuration.SoongOutDir(), "workspace")
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200541
542 excludes := []string{
543 "bazel-bin",
544 "bazel-genfiles",
545 "bazel-out",
546 "bazel-testlogs",
547 "bazel-" + filepath.Base(topDir),
548 }
549
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200550 if outDir[0] != '/' {
551 excludes = append(excludes, outDir)
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200552 }
553
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400554 existingBazelRelatedFiles, err := getExistingBazelRelatedFiles(topDir)
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400555 if err != nil {
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400556 fmt.Fprintf(os.Stderr, "Error determining existing Bazel-related files: %s\n", err)
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400557 os.Exit(1)
558 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400559
Liz Kammer1aefc9d2021-10-18 16:59:00 -0400560 pathsToIgnoredBuildFiles := getPathsToIgnoredBuildFiles(topDir, generatedRoot, existingBazelRelatedFiles, configuration.IsEnvTrue("BP2BUILD_VERBOSE"))
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400561 excludes = append(excludes, pathsToIgnoredBuildFiles...)
562
563 excludes = append(excludes, getTemporaryExcludes()...)
564
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200565 symlinkForestDeps := bp2build.PlantSymlinkForest(
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200566 topDir, workspaceRoot, generatedRoot, ".", excludes)
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200567
Chris Parsons715b08f2022-03-22 19:23:40 -0400568 ninjaDeps = append(ninjaDeps, codegenContext.AdditionalNinjaDeps()...)
569 ninjaDeps = append(ninjaDeps, symlinkForestDeps...)
570
571 writeDepFile(bp2buildMarker, eventHandler, ninjaDeps)
572
573 // Create an empty bp2build marker file.
574 touch(shared.JoinPath(topDir, bp2buildMarker))
575
576 eventHandler.End("bp2build")
577
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200578 // Only report metrics when in bp2build mode. The metrics aren't relevant
579 // for queryview, since that's a total repo-wide conversion and there's a
580 // 1:1 mapping for each module.
581 metrics.Print()
Chris Parsons715b08f2022-03-22 19:23:40 -0400582 writeBp2BuildMetrics(&metrics, configuration, eventHandler)
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500583}
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500584
585// Write Bp2Build metrics into $LOG_DIR
Chris Parsons715b08f2022-03-22 19:23:40 -0400586func writeBp2BuildMetrics(codegenMetrics *bp2build.CodegenMetrics,
587 configuration android.Config, eventHandler metrics.EventHandler) {
588 for _, event := range eventHandler.CompletedEvents() {
589 codegenMetrics.Events = append(codegenMetrics.Events,
590 &bp2build_metrics_proto.Event{
591 Name: event.Id,
592 StartTime: uint64(event.Start.UnixNano()),
593 RealTime: event.RuntimeNanoseconds(),
594 })
595 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500596 metricsDir := configuration.Getenv("LOG_DIR")
597 if len(metricsDir) < 1 {
598 fmt.Fprintf(os.Stderr, "\nMissing required env var for generating bp2build metrics: LOG_DIR\n")
599 os.Exit(1)
600 }
Chris Parsons715b08f2022-03-22 19:23:40 -0400601 codegenMetrics.Write(metricsDir)
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500602}