blob: b3a6ee07df678c3ddf2573a2dea80938574aaaa2 [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"
Lukacs T. Berkie571dc32021-08-25 14:14:13 +020029
Colin Cross70b40592015-03-23 12:57:34 -070030 "github.com/google/blueprint/bootstrap"
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +020031 "github.com/google/blueprint/deptools"
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +020032 "github.com/google/blueprint/pathtools"
Dan Willemsen66213a62021-09-21 17:50:30 -070033 androidProtobuf "google.golang.org/protobuf/android"
Colin Cross3f40fa42015-01-30 17:27:36 -080034)
35
Colin Crosse87040b2017-12-11 15:52:26 -080036var (
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020037 topDir string
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +020038 outDir string
Lukacs T. Berkid6cee7e2021-09-01 16:25:51 +020039 soongOutDir string
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020040 availableEnvFile string
41 usedEnvFile string
42
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +020043 runGoTests bool
44
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +020045 globFile string
46 globListDir string
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020047 delveListen string
48 delvePath string
49
Lukacs T. Berkie571dc32021-08-25 14:14:13 +020050 moduleGraphFile string
kgui67007242022-01-25 13:50:25 +080051 moduleActionsFile string
Jingwen Chen50f93d22020-11-05 07:42:11 -050052 docFile string
53 bazelQueryViewDir string
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020054 bp2buildMarker string
Lukacs T. Berkif9008072021-08-16 15:24:48 +020055
56 cmdlineArgs bootstrap.Args
Colin Crosse87040b2017-12-11 15:52:26 -080057)
58
59func init() {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020060 // Flags that make sense in every mode
Lukacs T. Berki7690c092021-02-26 14:27:36 +010061 flag.StringVar(&topDir, "top", "", "Top directory of the Android source tree")
Lukacs T. Berkid6cee7e2021-09-01 16:25:51 +020062 flag.StringVar(&soongOutDir, "soong_out", "", "Soong output directory (usually $TOP/out/soong)")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020063 flag.StringVar(&availableEnvFile, "available_env", "", "File containing available environment variables")
64 flag.StringVar(&usedEnvFile, "used_env", "", "File containing used environment variables")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020065 flag.StringVar(&globFile, "globFile", "build-globs.ninja", "the Ninja file of globs to output")
66 flag.StringVar(&globListDir, "globListDir", "", "the directory containing the glob list files")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +020067 flag.StringVar(&outDir, "out", "", "the ninja builddir directory")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020068 flag.StringVar(&cmdlineArgs.ModuleListFile, "l", "", "file that lists filepaths to parse")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020069
70 // Debug flags
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +010071 flag.StringVar(&delveListen, "delve_listen", "", "Delve port to listen on for debugging")
72 flag.StringVar(&delvePath, "delve_path", "", "Path to Delve. Only used if --delve_listen is set")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020073 flag.StringVar(&cmdlineArgs.Cpuprofile, "cpuprofile", "", "write cpu profile to file")
74 flag.StringVar(&cmdlineArgs.TraceFile, "trace", "", "write trace to file")
75 flag.StringVar(&cmdlineArgs.Memprofile, "memprofile", "", "write memory profile to file")
76 flag.BoolVar(&cmdlineArgs.NoGC, "nogc", false, "turn off GC for debugging")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020077
78 // Flags representing various modes soong_build can run in
Lukacs T. Berkie571dc32021-08-25 14:14:13 +020079 flag.StringVar(&moduleGraphFile, "module_graph_file", "", "JSON module graph file to output")
kgui67007242022-01-25 13:50:25 +080080 flag.StringVar(&moduleActionsFile, "module_actions_file", "", "JSON file to output inputs/outputs of actions of modules")
Colin Crosse87040b2017-12-11 15:52:26 -080081 flag.StringVar(&docFile, "soong_docs", "", "build documentation file to output")
Lukacs T. Berki47a9d0c2021-03-08 16:34:09 +010082 flag.StringVar(&bazelQueryViewDir, "bazel_queryview_dir", "", "path to the bazel queryview directory relative to --top")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020083 flag.StringVar(&bp2buildMarker, "bp2build_marker", "", "If set, run bp2build, touch the specified marker file then exit")
Lukacs T. Berkif9008072021-08-16 15:24:48 +020084 flag.StringVar(&cmdlineArgs.OutFile, "o", "build.ninja", "the Ninja file to output")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020085 flag.BoolVar(&cmdlineArgs.EmptyNinjaFile, "empty-ninja-file", false, "write out a 0-byte ninja file")
86
87 // Flags that probably shouldn't be flags of soong_build but we haven't found
88 // the time to remove them yet
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +020089 flag.BoolVar(&runGoTests, "t", false, "build and run go tests during bootstrap")
Dan Willemsen66213a62021-09-21 17:50:30 -070090
91 // Disable deterministic randomization in the protobuf package, so incremental
92 // builds with unrelated Soong changes don't trigger large rebuilds (since we
93 // write out text protos in command lines, and command line changes trigger
94 // rebuilds).
95 androidProtobuf.DisableRand()
Colin Crosse87040b2017-12-11 15:52:26 -080096}
97
Jeff Gaston088e29e2017-11-29 16:47:17 -080098func newNameResolver(config android.Config) *android.NameResolver {
99 namespacePathsToExport := make(map[string]bool)
100
Dan Willemsen3fb1fae2018-03-12 15:30:26 -0700101 for _, namespaceName := range config.ExportedNamespaces() {
Jeff Gaston088e29e2017-11-29 16:47:17 -0800102 namespacePathsToExport[namespaceName] = true
103 }
104
105 namespacePathsToExport["."] = true // always export the root namespace
106
107 exportFilter := func(namespace *android.Namespace) bool {
108 return namespacePathsToExport[namespace.Path]
109 }
110
111 return android.NewNameResolver(exportFilter)
112}
113
Lukacs T. Berkiffc9e8d2021-09-07 17:54:38 +0200114func newContext(configuration android.Config) *android.Context {
Colin Crossae8600b2020-10-29 17:09:13 -0700115 ctx := android.NewContext(configuration)
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500116 ctx.Register()
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400117 ctx.SetNameInterface(newNameResolver(configuration))
118 ctx.SetAllowMissingDependencies(configuration.AllowMissingDependencies())
119 return ctx
120}
121
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200122func newConfig(availableEnv map[string]string) android.Config {
123 configuration, err := android.NewConfig(cmdlineArgs.ModuleListFile, runGoTests, outDir, soongOutDir, availableEnv)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400124 if err != nil {
125 fmt.Fprintf(os.Stderr, "%s", err)
126 os.Exit(1)
127 }
128 return configuration
129}
130
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200131// Bazel-enabled mode. Soong runs in two passes.
132// First pass: Analyze the build tree, but only store all bazel commands
133// needed to correctly evaluate the tree in the second pass.
134// TODO(cparsons): Don't output any ninja file, as the second pass will overwrite
135// the incorrect results from the first pass, and file I/O is expensive.
136func runMixedModeBuild(configuration android.Config, firstCtx *android.Context, extraNinjaDeps []string) {
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200137 bootstrap.RunBlueprint(cmdlineArgs, bootstrap.StopBeforeWriteNinja, firstCtx.Context, configuration)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200138
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200139 // Invoke bazel commands and save results for second pass.
140 if err := configuration.BazelContext.InvokeBazel(); err != nil {
141 fmt.Fprintf(os.Stderr, "%s", err)
142 os.Exit(1)
143 }
144 // Second pass: Full analysis, using the bazel command results. Output ninja file.
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200145 secondConfig, err := android.ConfigForAdditionalRun(configuration)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200146 if err != nil {
147 fmt.Fprintf(os.Stderr, "%s", err)
148 os.Exit(1)
149 }
Lukacs T. Berkiffc9e8d2021-09-07 17:54:38 +0200150 secondCtx := newContext(secondConfig)
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200151 ninjaDeps := bootstrap.RunBlueprint(cmdlineArgs, bootstrap.DoEverything, secondCtx.Context, secondConfig)
Lukacs T. Berki6124c9b2021-04-15 15:06:40 +0200152 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200153
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200154 globListFiles := writeBuildGlobsNinjaFile(secondCtx.SrcDir(), configuration.SoongOutDir(), secondCtx.Globs, configuration)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200155 ninjaDeps = append(ninjaDeps, globListFiles...)
156
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200157 writeDepFile(cmdlineArgs.OutFile, ninjaDeps)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200158}
159
160// Run the code-generation phase to convert BazelTargetModules to BUILD files.
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200161func runQueryView(queryviewDir, queryviewMarker string, configuration android.Config, ctx *android.Context) {
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200162 codegenContext := bp2build.NewCodegenContext(configuration, *ctx, bp2build.QueryView)
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200163 absoluteQueryViewDir := shared.JoinPath(topDir, queryviewDir)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200164 if err := createBazelQueryView(codegenContext, absoluteQueryViewDir); err != nil {
165 fmt.Fprintf(os.Stderr, "%s", err)
166 os.Exit(1)
167 }
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200168
169 touch(shared.JoinPath(topDir, queryviewMarker))
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200170}
171
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200172func writeMetrics(configuration android.Config) {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200173 metricsFile := filepath.Join(configuration.SoongOutDir(), "soong_build_metrics.pb")
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200174 err := android.WriteMetrics(configuration, metricsFile)
175 if err != nil {
176 fmt.Fprintf(os.Stderr, "error writing soong_build metrics %s: %s", metricsFile, err)
177 os.Exit(1)
178 }
179}
180
kgui67007242022-01-25 13:50:25 +0800181func writeJsonModuleGraphAndActions(ctx *android.Context, graphPath string, actionsPath string) {
182 graphFile, graphErr := os.Create(shared.JoinPath(topDir, graphPath))
183 actionsFile, actionsErr := os.Create(shared.JoinPath(topDir, actionsPath))
184 if graphErr != nil || actionsErr != nil {
185 fmt.Fprintf(os.Stderr, "Graph err: %s, actions err: %s", graphErr, actionsErr)
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200186 os.Exit(1)
187 }
188
kgui67007242022-01-25 13:50:25 +0800189 defer graphFile.Close()
190 defer actionsFile.Close()
191 ctx.Context.PrintJSONGraphAndActions(graphFile, actionsFile)
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200192}
193
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200194func writeBuildGlobsNinjaFile(srcDir, buildDir string, globs func() pathtools.MultipleGlobResults, config interface{}) []string {
195 globDir := bootstrap.GlobDirectory(buildDir, globListDir)
196 bootstrap.WriteBuildGlobsNinjaFile(&bootstrap.GlobSingleton{
197 GlobLister: globs,
198 GlobFile: globFile,
199 GlobDir: globDir,
200 SrcDir: srcDir,
201 }, config)
202 return bootstrap.GlobFileListFiles(globDir)
203}
204
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200205func writeDepFile(outputFile string, ninjaDeps []string) {
206 depFile := shared.JoinPath(topDir, outputFile+".d")
207 err := deptools.WriteDepFile(depFile, outputFile, ninjaDeps)
208 if err != nil {
209 fmt.Fprintf(os.Stderr, "Error writing depfile '%s': %s\n", depFile, err)
210 os.Exit(1)
211 }
212}
213
Jingwen Chen4fabaf52021-05-25 02:40:29 +0000214// doChosenActivity runs Soong for a specific activity, like bp2build, queryview
215// or the actual Soong build for the build.ninja file. Returns the top level
216// output file of the specific activity.
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200217func doChosenActivity(configuration android.Config, extraNinjaDeps []string) string {
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200218 mixedModeBuild := configuration.BazelContext.BazelEnabled()
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200219 generateBazelWorkspace := bp2buildMarker != ""
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200220 generateQueryView := bazelQueryViewDir != ""
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200221 generateModuleGraphFile := moduleGraphFile != ""
222 generateDocFile := docFile != ""
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200223
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200224 if generateBazelWorkspace {
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200225 // Run the alternate pipeline of bp2build mutators and singleton to convert
226 // Blueprint to BUILD files before everything else.
227 runBp2Build(configuration, extraNinjaDeps)
Jingwen Chen4fabaf52021-05-25 02:40:29 +0000228 return bp2buildMarker
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200229 }
230
Lukacs T. Berkieb0454b2021-10-26 13:32:59 +0200231 blueprintArgs := cmdlineArgs
232
233 var stopBefore bootstrap.StopBefore
234 if generateModuleGraphFile {
235 stopBefore = bootstrap.StopBeforeWriteNinja
236 } else if generateQueryView {
237 stopBefore = bootstrap.StopBeforePrepareBuildActions
238 } else if generateDocFile {
239 stopBefore = bootstrap.StopBeforePrepareBuildActions
240 } else {
241 stopBefore = bootstrap.DoEverything
242 }
243
Lukacs T. Berkiffc9e8d2021-09-07 17:54:38 +0200244 ctx := newContext(configuration)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200245 if mixedModeBuild {
246 runMixedModeBuild(configuration, ctx, extraNinjaDeps)
247 } else {
Lukacs T. Berkiffc9e8d2021-09-07 17:54:38 +0200248 ninjaDeps := bootstrap.RunBlueprint(blueprintArgs, stopBefore, ctx.Context, configuration)
Lukacs T. Berki6124c9b2021-04-15 15:06:40 +0200249 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200250
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200251 globListFiles := writeBuildGlobsNinjaFile(ctx.SrcDir(), configuration.SoongOutDir(), ctx.Globs, configuration)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200252 ninjaDeps = append(ninjaDeps, globListFiles...)
253
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200254 // Convert the Soong module graph into Bazel BUILD files.
255 if generateQueryView {
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200256 queryviewMarkerFile := bazelQueryViewDir + ".marker"
257 runQueryView(bazelQueryViewDir, queryviewMarkerFile, configuration, ctx)
258 writeDepFile(queryviewMarkerFile, ninjaDeps)
259 return queryviewMarkerFile
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200260 } else if generateModuleGraphFile {
kgui67007242022-01-25 13:50:25 +0800261 writeJsonModuleGraphAndActions(ctx, moduleGraphFile, moduleActionsFile)
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200262 writeDepFile(moduleGraphFile, ninjaDeps)
263 return moduleGraphFile
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200264 } else if generateDocFile {
265 // TODO: we could make writeDocs() return the list of documentation files
266 // written and add them to the .d file. Then soong_docs would be re-run
267 // whenever one is deleted.
268 if err := writeDocs(ctx, shared.JoinPath(topDir, docFile)); err != nil {
269 fmt.Fprintf(os.Stderr, "error building Soong documentation: %s\n", err)
270 os.Exit(1)
271 }
272 writeDepFile(docFile, ninjaDeps)
273 return docFile
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200274 } else {
275 // The actual output (build.ninja) was written in the RunBlueprint() call
276 // above
277 writeDepFile(cmdlineArgs.OutFile, ninjaDeps)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200278 }
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200279 }
280
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200281 writeMetrics(configuration)
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200282 return cmdlineArgs.OutFile
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200283}
284
285// soong_ui dumps the available environment variables to
286// soong.environment.available . Then soong_build itself is run with an empty
287// environment so that the only way environment variables can be accessed is
288// using Config, which tracks access to them.
289
290// At the end of the build, a file called soong.environment.used is written
291// containing the current value of all used environment variables. The next
292// time soong_ui is run, it checks whether any environment variables that was
293// used had changed and if so, it deletes soong.environment.used to cause a
294// rebuild.
295//
296// The dependency of build.ninja on soong.environment.used is declared in
297// build.ninja.d
298func parseAvailableEnv() map[string]string {
299 if availableEnvFile == "" {
300 fmt.Fprintf(os.Stderr, "--available_env not set\n")
301 os.Exit(1)
302 }
303
304 result, err := shared.EnvFromFile(shared.JoinPath(topDir, availableEnvFile))
305 if err != nil {
306 fmt.Fprintf(os.Stderr, "error reading available environment file '%s': %s\n", availableEnvFile, err)
307 os.Exit(1)
308 }
309
310 return result
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200311}
312
Colin Cross3f40fa42015-01-30 17:27:36 -0800313func main() {
314 flag.Parse()
315
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100316 shared.ReexecWithDelveMaybe(delveListen, delvePath)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100317 android.InitSandbox(topDir)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100318
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200319 availableEnv := parseAvailableEnv()
Lukacs T. Berki53b2f362021-04-12 14:04:24 +0200320
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200321 configuration := newConfig(availableEnv)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100322 extraNinjaDeps := []string{
323 configuration.ProductVariablesFileName,
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200324 usedEnvFile,
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100325 }
Colin Crossaa812d12019-06-19 13:33:24 -0700326
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100327 if configuration.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
328 configuration.SetAllowMissingDependencies()
329 }
330
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100331 if shared.IsDebugging() {
Colin Crossaa812d12019-06-19 13:33:24 -0700332 // Add a non-existent file to the dependencies so that soong_build will rerun when the debugger is
333 // enabled even if it completed successfully.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200334 extraNinjaDeps = append(extraNinjaDeps, filepath.Join(configuration.SoongOutDir(), "always_rerun_for_delve"))
Colin Crossaa812d12019-06-19 13:33:24 -0700335 }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500336
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200337 finalOutputFile := doChosenActivity(configuration, extraNinjaDeps)
338 writeUsedEnvironmentFile(configuration, finalOutputFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100339}
340
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200341func writeUsedEnvironmentFile(configuration android.Config, finalOutputFile string) {
342 if usedEnvFile == "" {
343 return
344 }
345
346 path := shared.JoinPath(topDir, usedEnvFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100347 data, err := shared.EnvFileContents(configuration.EnvDeps())
348 if err != nil {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200349 fmt.Fprintf(os.Stderr, "error writing used environment file '%s': %s\n", usedEnvFile, err)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100350 os.Exit(1)
351 }
352
353 err = ioutil.WriteFile(path, data, 0666)
354 if err != nil {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200355 fmt.Fprintf(os.Stderr, "error writing used environment file '%s': %s\n", usedEnvFile, err)
Lukacs T. Berkic99c9472021-03-24 10:50:06 +0100356 os.Exit(1)
357 }
358
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200359 // Touch the output file so that it's not older than the file we just
Lukacs T. Berkic99c9472021-03-24 10:50:06 +0100360 // wrote. We can't write the environment file earlier because one an access
361 // new environment variables while writing it.
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200362 touch(shared.JoinPath(topDir, finalOutputFile))
Colin Cross3f40fa42015-01-30 17:27:36 -0800363}
Jingwen Chen5ba7e472020-07-15 10:06:41 +0000364
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200365func touch(path string) {
366 f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
367 if err != nil {
368 fmt.Fprintf(os.Stderr, "Error touching '%s': %s\n", path, err)
369 os.Exit(1)
370 }
371
372 err = f.Close()
373 if err != nil {
374 fmt.Fprintf(os.Stderr, "Error touching '%s': %s\n", path, err)
375 os.Exit(1)
376 }
377
378 currentTime := time.Now().Local()
379 err = os.Chtimes(path, currentTime, currentTime)
380 if err != nil {
381 fmt.Fprintf(os.Stderr, "error touching '%s': %s\n", path, err)
382 os.Exit(1)
383 }
384}
385
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400386// Find BUILD files in the srcDir which...
387//
388// - are not on the allow list (android/bazel.go#ShouldKeepExistingBuildFileForDir())
389//
390// - won't be overwritten by corresponding bp2build generated files
391//
392// 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 -0400393func getPathsToIgnoredBuildFiles(topDir string, generatedRoot string, srcDirBazelFiles []string, verbose bool) []string {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400394 paths := make([]string, 0)
395
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400396 for _, srcDirBazelFileRelativePath := range srcDirBazelFiles {
397 srcDirBazelFileFullPath := shared.JoinPath(topDir, srcDirBazelFileRelativePath)
398 fileInfo, err := os.Stat(srcDirBazelFileFullPath)
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400399 if err != nil {
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400400 // Warn about error, but continue trying to check files
401 fmt.Fprintf(os.Stderr, "WARNING: Error accessing path '%s', err: %s\n", srcDirBazelFileFullPath, err)
402 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400403 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400404 if fileInfo.IsDir() {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400405 // Don't ignore entire directories
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400406 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400407 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400408 if !(fileInfo.Name() == "BUILD" || fileInfo.Name() == "BUILD.bazel") {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400409 // Don't ignore this file - it is not a build file
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400410 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400411 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400412 srcDirBazelFileDir := filepath.Dir(srcDirBazelFileRelativePath)
413 if android.ShouldKeepExistingBuildFileForDir(srcDirBazelFileDir) {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400414 // Don't ignore this existing build file
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400415 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400416 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400417 correspondingBp2BuildFile := shared.JoinPath(topDir, generatedRoot, srcDirBazelFileRelativePath)
418 if _, err := os.Stat(correspondingBp2BuildFile); err == nil {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400419 // If bp2build generated an alternate BUILD file, don't exclude this workspace path
420 // BUILD file clash resolution happens later in the symlink forest creation
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400421 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400422 }
Liz Kammer1aefc9d2021-10-18 16:59:00 -0400423 if verbose {
424 fmt.Fprintf(os.Stderr, "Ignoring existing BUILD file: %s\n", srcDirBazelFileRelativePath)
425 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400426 paths = append(paths, srcDirBazelFileRelativePath)
427 }
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400428
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400429 return paths
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400430}
431
432// Returns temporary symlink forest excludes necessary for bazel build //external/... (and bazel build //frameworks/...) to work
433func getTemporaryExcludes() []string {
434 excludes := make([]string, 0)
435
436 // FIXME: 'autotest_lib' is a symlink back to external/autotest, and this causes an infinite symlink expansion error for Bazel
437 excludes = append(excludes, "external/autotest/venv/autotest_lib")
438
439 // FIXME: The external/google-fruit/extras/bazel_root/third_party/fruit dir is poison
440 // It contains several symlinks back to real source dirs, and those source dirs contain BUILD files we want to ignore
441 excludes = append(excludes, "external/google-fruit/extras/bazel_root/third_party/fruit")
442
443 // FIXME: 'frameworks/compile/slang' has a filegroup error due to an escaping issue
444 excludes = append(excludes, "frameworks/compile/slang")
445
446 return excludes
447}
448
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400449// Read the bazel.list file that the Soong Finder already dumped earlier (hopefully)
450// It contains the locations of BUILD files, BUILD.bazel files, etc. in the source dir
451func getExistingBazelRelatedFiles(topDir string) ([]string, error) {
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200452 bazelFinderFile := filepath.Join(filepath.Dir(cmdlineArgs.ModuleListFile), "bazel.list")
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400453 if !filepath.IsAbs(bazelFinderFile) {
454 // Assume this was a relative path under topDir
455 bazelFinderFile = filepath.Join(topDir, bazelFinderFile)
456 }
457 data, err := ioutil.ReadFile(bazelFinderFile)
458 if err != nil {
459 return nil, err
460 }
461 files := strings.Split(strings.TrimSpace(string(data)), "\n")
462 return files, nil
463}
464
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500465// Run Soong in the bp2build mode. This creates a standalone context that registers
466// an alternate pipeline of mutators and singletons specifically for generating
467// Bazel BUILD files instead of Ninja files.
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200468func runBp2Build(configuration android.Config, extraNinjaDeps []string) {
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500469 // Register an alternate set of singletons and mutators for bazel
470 // conversion for Bazel conversion.
471 bp2buildCtx := android.NewContext(configuration)
Jingwen Cheneb76c432021-01-28 08:22:12 -0500472
Jingwen Chena47f28d2021-11-02 16:43:57 +0000473 // Soong internals like LoadHooks behave differently when running as
474 // bp2build. This is the bit to differentiate between Soong-as-Soong and
475 // Soong-as-bp2build.
476 bp2buildCtx.SetRunningAsBp2build()
477
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200478 // Propagate "allow misssing dependencies" bit. This is normally set in
479 // newContext(), but we create bp2buildCtx without calling that method.
480 bp2buildCtx.SetAllowMissingDependencies(configuration.AllowMissingDependencies())
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500481 bp2buildCtx.SetNameInterface(newNameResolver(configuration))
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200482 bp2buildCtx.RegisterForBazelConversion()
Jingwen Cheneb76c432021-01-28 08:22:12 -0500483
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500484 // The bp2build process is a purely functional process that only depends on
485 // Android.bp files. It must not depend on the values of per-build product
486 // configurations or variables, since those will generate different BUILD
487 // files based on how the user has configured their tree.
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200488 bp2buildCtx.SetModuleListFile(cmdlineArgs.ModuleListFile)
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200489 modulePaths, err := bp2buildCtx.ListModulePaths(".")
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500490 if err != nil {
491 panic(err)
492 }
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500493
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100494 extraNinjaDeps = append(extraNinjaDeps, modulePaths...)
495
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500496 // Run the loading and analysis pipeline to prepare the graph of regular
497 // Modules parsed from Android.bp files, and the BazelTargetModules mapped
498 // from the regular Modules.
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200499 blueprintArgs := cmdlineArgs
Lukacs T. Berkiffc9e8d2021-09-07 17:54:38 +0200500 ninjaDeps := bootstrap.RunBlueprint(blueprintArgs, bootstrap.StopBeforePrepareBuildActions, bp2buildCtx.Context, configuration)
Lukacs T. Berki6124c9b2021-04-15 15:06:40 +0200501 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200502
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200503 globListFiles := writeBuildGlobsNinjaFile(bp2buildCtx.SrcDir(), configuration.SoongOutDir(), bp2buildCtx.Globs, configuration)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200504 ninjaDeps = append(ninjaDeps, globListFiles...)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200505
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200506 // Run the code-generation phase to convert BazelTargetModules to BUILD files
507 // and print conversion metrics to the user.
508 codegenContext := bp2build.NewCodegenContext(configuration, *bp2buildCtx, bp2build.Bp2Build)
509 metrics := bp2build.Codegen(codegenContext)
510
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200511 generatedRoot := shared.JoinPath(configuration.SoongOutDir(), "bp2build")
512 workspaceRoot := shared.JoinPath(configuration.SoongOutDir(), "workspace")
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200513
514 excludes := []string{
515 "bazel-bin",
516 "bazel-genfiles",
517 "bazel-out",
518 "bazel-testlogs",
519 "bazel-" + filepath.Base(topDir),
520 }
521
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200522 if outDir[0] != '/' {
523 excludes = append(excludes, outDir)
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200524 }
525
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400526 existingBazelRelatedFiles, err := getExistingBazelRelatedFiles(topDir)
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400527 if err != nil {
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400528 fmt.Fprintf(os.Stderr, "Error determining existing Bazel-related files: %s\n", err)
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400529 os.Exit(1)
530 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400531
Liz Kammer1aefc9d2021-10-18 16:59:00 -0400532 pathsToIgnoredBuildFiles := getPathsToIgnoredBuildFiles(topDir, generatedRoot, existingBazelRelatedFiles, configuration.IsEnvTrue("BP2BUILD_VERBOSE"))
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400533 excludes = append(excludes, pathsToIgnoredBuildFiles...)
534
535 excludes = append(excludes, getTemporaryExcludes()...)
536
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200537 symlinkForestDeps := bp2build.PlantSymlinkForest(
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200538 topDir, workspaceRoot, generatedRoot, ".", excludes)
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200539
540 // Only report metrics when in bp2build mode. The metrics aren't relevant
541 // for queryview, since that's a total repo-wide conversion and there's a
542 // 1:1 mapping for each module.
543 metrics.Print()
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500544 writeBp2BuildMetrics(&metrics, configuration)
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200545
546 ninjaDeps = append(ninjaDeps, codegenContext.AdditionalNinjaDeps()...)
547 ninjaDeps = append(ninjaDeps, symlinkForestDeps...)
548
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200549 writeDepFile(bp2buildMarker, ninjaDeps)
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500550
Jingwen Chen4fabaf52021-05-25 02:40:29 +0000551 // Create an empty bp2build marker file.
552 touch(shared.JoinPath(topDir, bp2buildMarker))
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500553}
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500554
555// Write Bp2Build metrics into $LOG_DIR
556func writeBp2BuildMetrics(metrics *bp2build.CodegenMetrics, configuration android.Config) {
557 metricsDir := configuration.Getenv("LOG_DIR")
558 if len(metricsDir) < 1 {
559 fmt.Fprintf(os.Stderr, "\nMissing required env var for generating bp2build metrics: LOG_DIR\n")
560 os.Exit(1)
561 }
562 metrics.Write(metricsDir)
563}