blob: cff65f92eccab4a7aae35af67f626297fae9b5fb [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
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020026 "android/soong/bp2build"
Lukacs T. Berki7690c092021-02-26 14:27:36 +010027 "android/soong/shared"
Colin Cross70b40592015-03-23 12:57:34 -070028 "github.com/google/blueprint/bootstrap"
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +020029 "github.com/google/blueprint/deptools"
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +020030 "github.com/google/blueprint/pathtools"
Colin Cross3f40fa42015-01-30 17:27:36 -080031
Colin Cross635c3b02016-05-18 15:37:25 -070032 "android/soong/android"
Colin Cross3f40fa42015-01-30 17:27:36 -080033)
34
Colin Crosse87040b2017-12-11 15:52:26 -080035var (
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020036 topDir string
37 outDir string
38 availableEnvFile string
39 usedEnvFile string
40
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +020041 globFile string
42 globListDir string
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020043 delveListen string
44 delvePath string
45
Jingwen Chen50f93d22020-11-05 07:42:11 -050046 docFile string
47 bazelQueryViewDir string
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020048 bp2buildMarker string
Lukacs T. Berkif9008072021-08-16 15:24:48 +020049
50 cmdlineArgs bootstrap.Args
Colin Crosse87040b2017-12-11 15:52:26 -080051)
52
53func init() {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020054 // Flags that make sense in every mode
Lukacs T. Berki7690c092021-02-26 14:27:36 +010055 flag.StringVar(&topDir, "top", "", "Top directory of the Android source tree")
56 flag.StringVar(&outDir, "out", "", "Soong output directory (usually $TOP/out/soong)")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020057 flag.StringVar(&availableEnvFile, "available_env", "", "File containing available environment variables")
58 flag.StringVar(&usedEnvFile, "used_env", "", "File containing used environment variables")
59
60 // Debug flags
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +010061 flag.StringVar(&delveListen, "delve_listen", "", "Delve port to listen on for debugging")
62 flag.StringVar(&delvePath, "delve_path", "", "Path to Delve. Only used if --delve_listen is set")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020063
64 // Flags representing various modes soong_build can run in
Colin Crosse87040b2017-12-11 15:52:26 -080065 flag.StringVar(&docFile, "soong_docs", "", "build documentation file to output")
Lukacs T. Berki47a9d0c2021-03-08 16:34:09 +010066 flag.StringVar(&bazelQueryViewDir, "bazel_queryview_dir", "", "path to the bazel queryview directory relative to --top")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020067 flag.StringVar(&bp2buildMarker, "bp2build_marker", "", "If set, run bp2build, touch the specified marker file then exit")
Lukacs T. Berkif9008072021-08-16 15:24:48 +020068
69 flag.StringVar(&cmdlineArgs.OutFile, "o", "build.ninja", "the Ninja file to output")
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +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. Berkif9008072021-08-16 15:24:48 +020072 flag.StringVar(&cmdlineArgs.BuildDir, "b", ".", "the build output directory")
73 flag.StringVar(&cmdlineArgs.NinjaBuildDir, "n", "", "the ninja builddir directory")
74 flag.StringVar(&cmdlineArgs.DepFile, "d", "", "the dependency file to output")
75 flag.StringVar(&cmdlineArgs.Cpuprofile, "cpuprofile", "", "write cpu profile to file")
76 flag.StringVar(&cmdlineArgs.TraceFile, "trace", "", "write trace to file")
77 flag.StringVar(&cmdlineArgs.Memprofile, "memprofile", "", "write memory profile to file")
78 flag.BoolVar(&cmdlineArgs.NoGC, "nogc", false, "turn off GC for debugging")
79 flag.BoolVar(&cmdlineArgs.RunGoTests, "t", false, "build and run go tests during bootstrap")
80 flag.BoolVar(&cmdlineArgs.UseValidations, "use-validations", false, "use validations to depend on go tests")
81 flag.StringVar(&cmdlineArgs.ModuleListFile, "l", "", "file that lists filepaths to parse")
82 flag.BoolVar(&cmdlineArgs.EmptyNinjaFile, "empty-ninja-file", false, "write out a 0-byte ninja file")
Colin Crosse87040b2017-12-11 15:52:26 -080083}
84
Jeff Gaston088e29e2017-11-29 16:47:17 -080085func newNameResolver(config android.Config) *android.NameResolver {
86 namespacePathsToExport := make(map[string]bool)
87
Dan Willemsen3fb1fae2018-03-12 15:30:26 -070088 for _, namespaceName := range config.ExportedNamespaces() {
Jeff Gaston088e29e2017-11-29 16:47:17 -080089 namespacePathsToExport[namespaceName] = true
90 }
91
92 namespacePathsToExport["."] = true // always export the root namespace
93
94 exportFilter := func(namespace *android.Namespace) bool {
95 return namespacePathsToExport[namespace.Path]
96 }
97
98 return android.NewNameResolver(exportFilter)
99}
100
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200101func newContext(configuration android.Config, prepareBuildActions bool) *android.Context {
Colin Crossae8600b2020-10-29 17:09:13 -0700102 ctx := android.NewContext(configuration)
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500103 ctx.Register()
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200104 if !prepareBuildActions {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400105 configuration.SetStopBefore(bootstrap.StopBeforePrepareBuildActions)
106 }
107 ctx.SetNameInterface(newNameResolver(configuration))
108 ctx.SetAllowMissingDependencies(configuration.AllowMissingDependencies())
109 return ctx
110}
111
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200112func newConfig(outDir string, availableEnv map[string]string) android.Config {
113 configuration, err := android.NewConfig(outDir, cmdlineArgs.ModuleListFile, availableEnv)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400114 if err != nil {
115 fmt.Fprintf(os.Stderr, "%s", err)
116 os.Exit(1)
117 }
118 return configuration
119}
120
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200121// Bazel-enabled mode. Soong runs in two passes.
122// First pass: Analyze the build tree, but only store all bazel commands
123// needed to correctly evaluate the tree in the second pass.
124// TODO(cparsons): Don't output any ninja file, as the second pass will overwrite
125// the incorrect results from the first pass, and file I/O is expensive.
126func runMixedModeBuild(configuration android.Config, firstCtx *android.Context, extraNinjaDeps []string) {
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200127 var firstArgs, secondArgs bootstrap.Args
128
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200129 firstArgs = cmdlineArgs
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200130 configuration.SetStopBefore(bootstrap.StopBeforeWriteNinja)
Lukacs T. Berki6124c9b2021-04-15 15:06:40 +0200131 bootstrap.RunBlueprint(firstArgs, firstCtx.Context, configuration)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200132
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200133 // Invoke bazel commands and save results for second pass.
134 if err := configuration.BazelContext.InvokeBazel(); err != nil {
135 fmt.Fprintf(os.Stderr, "%s", err)
136 os.Exit(1)
137 }
138 // Second pass: Full analysis, using the bazel command results. Output ninja file.
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200139 secondConfig, err := android.ConfigForAdditionalRun(configuration)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200140 if err != nil {
141 fmt.Fprintf(os.Stderr, "%s", err)
142 os.Exit(1)
143 }
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200144 secondCtx := newContext(secondConfig, true)
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200145 secondArgs = cmdlineArgs
Lukacs T. Berki6124c9b2021-04-15 15:06:40 +0200146 ninjaDeps := bootstrap.RunBlueprint(secondArgs, secondCtx.Context, secondConfig)
147 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200148
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200149 globListFiles := writeBuildGlobsNinjaFile(secondCtx.SrcDir(), configuration.SoongOutDir(), secondCtx.Globs, configuration)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200150 ninjaDeps = append(ninjaDeps, globListFiles...)
151
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200152 err = deptools.WriteDepFile(shared.JoinPath(topDir, secondArgs.DepFile), secondArgs.OutFile, ninjaDeps)
153 if err != nil {
154 fmt.Fprintf(os.Stderr, "Error writing depfile '%s': %s\n", secondArgs.DepFile, err)
155 os.Exit(1)
156 }
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200157}
158
159// Run the code-generation phase to convert BazelTargetModules to BUILD files.
160func runQueryView(configuration android.Config, ctx *android.Context) {
161 codegenContext := bp2build.NewCodegenContext(configuration, *ctx, bp2build.QueryView)
162 absoluteQueryViewDir := shared.JoinPath(topDir, bazelQueryViewDir)
163 if err := createBazelQueryView(codegenContext, absoluteQueryViewDir); err != nil {
164 fmt.Fprintf(os.Stderr, "%s", err)
165 os.Exit(1)
166 }
167}
168
Lukacs T. Berki6124c9b2021-04-15 15:06:40 +0200169func runSoongDocs(configuration android.Config) {
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200170 ctx := newContext(configuration, false)
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200171 soongDocsArgs := cmdlineArgs
Lukacs T. Berki6124c9b2021-04-15 15:06:40 +0200172 bootstrap.RunBlueprint(soongDocsArgs, ctx.Context, configuration)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200173 if err := writeDocs(ctx, configuration, docFile); err != nil {
174 fmt.Fprintf(os.Stderr, "%s", err)
175 os.Exit(1)
176 }
177}
178
179func writeMetrics(configuration android.Config) {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200180 metricsFile := filepath.Join(configuration.SoongOutDir(), "soong_build_metrics.pb")
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200181 err := android.WriteMetrics(configuration, metricsFile)
182 if err != nil {
183 fmt.Fprintf(os.Stderr, "error writing soong_build metrics %s: %s", metricsFile, err)
184 os.Exit(1)
185 }
186}
187
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200188func writeJsonModuleGraph(configuration android.Config, ctx *android.Context, path string, extraNinjaDeps []string) {
189 f, err := os.Create(path)
190 if err != nil {
191 fmt.Fprintf(os.Stderr, "%s", err)
192 os.Exit(1)
193 }
194
195 defer f.Close()
196 ctx.Context.PrintJSONGraph(f)
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200197 writeFakeNinjaFile(extraNinjaDeps, configuration.SoongOutDir())
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200198}
199
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200200func writeBuildGlobsNinjaFile(srcDir, buildDir string, globs func() pathtools.MultipleGlobResults, config interface{}) []string {
201 globDir := bootstrap.GlobDirectory(buildDir, globListDir)
202 bootstrap.WriteBuildGlobsNinjaFile(&bootstrap.GlobSingleton{
203 GlobLister: globs,
204 GlobFile: globFile,
205 GlobDir: globDir,
206 SrcDir: srcDir,
207 }, config)
208 return bootstrap.GlobFileListFiles(globDir)
209}
210
Jingwen Chen4fabaf52021-05-25 02:40:29 +0000211// doChosenActivity runs Soong for a specific activity, like bp2build, queryview
212// or the actual Soong build for the build.ninja file. Returns the top level
213// output file of the specific activity.
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200214func doChosenActivity(configuration android.Config, extraNinjaDeps []string) string {
Chris Parsonsec1a3dc2021-04-20 15:32:07 -0400215 bazelConversionRequested := bp2buildMarker != ""
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200216 mixedModeBuild := configuration.BazelContext.BazelEnabled()
217 generateQueryView := bazelQueryViewDir != ""
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200218 jsonModuleFile := configuration.Getenv("SOONG_DUMP_JSON_MODULE_GRAPH")
219
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200220 blueprintArgs := cmdlineArgs
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200221 prepareBuildActions := !generateQueryView && jsonModuleFile == ""
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200222 if bazelConversionRequested {
223 // Run the alternate pipeline of bp2build mutators and singleton to convert
224 // Blueprint to BUILD files before everything else.
225 runBp2Build(configuration, extraNinjaDeps)
Jingwen Chen4fabaf52021-05-25 02:40:29 +0000226 return bp2buildMarker
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200227 }
228
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200229 ctx := newContext(configuration, prepareBuildActions)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200230 if mixedModeBuild {
231 runMixedModeBuild(configuration, ctx, extraNinjaDeps)
232 } else {
Lukacs T. Berki6124c9b2021-04-15 15:06:40 +0200233 ninjaDeps := bootstrap.RunBlueprint(blueprintArgs, ctx.Context, configuration)
234 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200235
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200236 globListFiles := writeBuildGlobsNinjaFile(ctx.SrcDir(), configuration.SoongOutDir(), ctx.Globs, configuration)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200237 ninjaDeps = append(ninjaDeps, globListFiles...)
238
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200239 err := deptools.WriteDepFile(shared.JoinPath(topDir, blueprintArgs.DepFile), blueprintArgs.OutFile, ninjaDeps)
240 if err != nil {
241 fmt.Fprintf(os.Stderr, "Error writing depfile '%s': %s\n", blueprintArgs.DepFile, err)
242 os.Exit(1)
243 }
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200244 }
245
246 // Convert the Soong module graph into Bazel BUILD files.
247 if generateQueryView {
248 runQueryView(configuration, ctx)
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200249 return cmdlineArgs.OutFile // TODO: This is a lie
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200250 }
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200251
252 if jsonModuleFile != "" {
253 writeJsonModuleGraph(configuration, ctx, jsonModuleFile, extraNinjaDeps)
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200254 return cmdlineArgs.OutFile // TODO: This is a lie
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200255 }
256
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200257 writeMetrics(configuration)
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200258 return cmdlineArgs.OutFile
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200259}
260
261// soong_ui dumps the available environment variables to
262// soong.environment.available . Then soong_build itself is run with an empty
263// environment so that the only way environment variables can be accessed is
264// using Config, which tracks access to them.
265
266// At the end of the build, a file called soong.environment.used is written
267// containing the current value of all used environment variables. The next
268// time soong_ui is run, it checks whether any environment variables that was
269// used had changed and if so, it deletes soong.environment.used to cause a
270// rebuild.
271//
272// The dependency of build.ninja on soong.environment.used is declared in
273// build.ninja.d
274func parseAvailableEnv() map[string]string {
275 if availableEnvFile == "" {
276 fmt.Fprintf(os.Stderr, "--available_env not set\n")
277 os.Exit(1)
278 }
279
280 result, err := shared.EnvFromFile(shared.JoinPath(topDir, availableEnvFile))
281 if err != nil {
282 fmt.Fprintf(os.Stderr, "error reading available environment file '%s': %s\n", availableEnvFile, err)
283 os.Exit(1)
284 }
285
286 return result
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200287}
288
Colin Cross3f40fa42015-01-30 17:27:36 -0800289func main() {
290 flag.Parse()
291
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100292 shared.ReexecWithDelveMaybe(delveListen, delvePath)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100293 android.InitSandbox(topDir)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100294
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200295 availableEnv := parseAvailableEnv()
Lukacs T. Berki53b2f362021-04-12 14:04:24 +0200296
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200297 configuration := newConfig(outDir, availableEnv)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100298 extraNinjaDeps := []string{
299 configuration.ProductVariablesFileName,
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200300 usedEnvFile,
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100301 }
Colin Crossaa812d12019-06-19 13:33:24 -0700302
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100303 if configuration.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
304 configuration.SetAllowMissingDependencies()
305 }
306
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100307 if shared.IsDebugging() {
Colin Crossaa812d12019-06-19 13:33:24 -0700308 // Add a non-existent file to the dependencies so that soong_build will rerun when the debugger is
309 // enabled even if it completed successfully.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200310 extraNinjaDeps = append(extraNinjaDeps, filepath.Join(configuration.SoongOutDir(), "always_rerun_for_delve"))
Colin Crossaa812d12019-06-19 13:33:24 -0700311 }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500312
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200313 if docFile != "" {
314 // We don't write an used variables file when generating documentation
315 // because that is done from within the actual builds as a Ninja action and
316 // thus it would overwrite the actual used variables file so this is
317 // special-cased.
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200318 // TODO: Fix this by not passing --used_env to the soong_docs invocation
Lukacs T. Berki6124c9b2021-04-15 15:06:40 +0200319 runSoongDocs(configuration)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200320 return
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400321 }
Jingwen Chen4133ce62020-12-02 04:34:15 -0500322
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200323 finalOutputFile := doChosenActivity(configuration, extraNinjaDeps)
324 writeUsedEnvironmentFile(configuration, finalOutputFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100325}
326
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200327func writeUsedEnvironmentFile(configuration android.Config, finalOutputFile string) {
328 if usedEnvFile == "" {
329 return
330 }
331
332 path := shared.JoinPath(topDir, usedEnvFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100333 data, err := shared.EnvFileContents(configuration.EnvDeps())
334 if err != nil {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200335 fmt.Fprintf(os.Stderr, "error writing used environment file '%s': %s\n", usedEnvFile, err)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100336 os.Exit(1)
337 }
338
339 err = ioutil.WriteFile(path, data, 0666)
340 if err != nil {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200341 fmt.Fprintf(os.Stderr, "error writing used environment file '%s': %s\n", usedEnvFile, err)
Lukacs T. Berkic99c9472021-03-24 10:50:06 +0100342 os.Exit(1)
343 }
344
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200345 // Touch the output file so that it's not older than the file we just
Lukacs T. Berkic99c9472021-03-24 10:50:06 +0100346 // wrote. We can't write the environment file earlier because one an access
347 // new environment variables while writing it.
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200348 touch(shared.JoinPath(topDir, finalOutputFile))
Colin Cross3f40fa42015-01-30 17:27:36 -0800349}
Jingwen Chen5ba7e472020-07-15 10:06:41 +0000350
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200351// Workarounds to support running bp2build in a clean AOSP checkout with no
352// prior builds, and exiting early as soon as the BUILD files get generated,
353// therefore not creating build.ninja files that soong_ui and callers of
354// soong_build expects.
355//
356// These files are: build.ninja and build.ninja.d. Since Kati hasn't been
357// ran as well, and `nothing` is defined in a .mk file, there isn't a ninja
358// target called `nothing`, so we manually create it here.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200359func writeFakeNinjaFile(extraNinjaDeps []string, soongOutDir string) {
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200360 extraNinjaDepsString := strings.Join(extraNinjaDeps, " \\\n ")
361
362 ninjaFileName := "build.ninja"
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200363 ninjaFile := shared.JoinPath(topDir, soongOutDir, ninjaFileName)
364 ninjaFileD := shared.JoinPath(topDir, soongOutDir, ninjaFileName+".d")
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200365 // A workaround to create the 'nothing' ninja target so `m nothing` works,
366 // since bp2build runs without Kati, and the 'nothing' target is declared in
367 // a Makefile.
368 ioutil.WriteFile(ninjaFile, []byte("build nothing: phony\n phony_output = true\n"), 0666)
369 ioutil.WriteFile(ninjaFileD,
Jingwen Chen4fabaf52021-05-25 02:40:29 +0000370 []byte(fmt.Sprintf("%s: \\\n %s\n", ninjaFile, extraNinjaDepsString)),
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200371 0666)
372}
373
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200374func touch(path string) {
375 f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
376 if err != nil {
377 fmt.Fprintf(os.Stderr, "Error touching '%s': %s\n", path, err)
378 os.Exit(1)
379 }
380
381 err = f.Close()
382 if err != nil {
383 fmt.Fprintf(os.Stderr, "Error touching '%s': %s\n", path, err)
384 os.Exit(1)
385 }
386
387 currentTime := time.Now().Local()
388 err = os.Chtimes(path, currentTime, currentTime)
389 if err != nil {
390 fmt.Fprintf(os.Stderr, "error touching '%s': %s\n", path, err)
391 os.Exit(1)
392 }
393}
394
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400395// Find BUILD files in the srcDir which...
396//
397// - are not on the allow list (android/bazel.go#ShouldKeepExistingBuildFileForDir())
398//
399// - won't be overwritten by corresponding bp2build generated files
400//
401// And return their paths so they can be left out of the Bazel workspace dir (i.e. ignored)
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400402func getPathsToIgnoredBuildFiles(topDir string, generatedRoot string, srcDirBazelFiles []string) []string {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400403 paths := make([]string, 0)
404
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400405 for _, srcDirBazelFileRelativePath := range srcDirBazelFiles {
406 srcDirBazelFileFullPath := shared.JoinPath(topDir, srcDirBazelFileRelativePath)
407 fileInfo, err := os.Stat(srcDirBazelFileFullPath)
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400408 if err != nil {
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400409 // Warn about error, but continue trying to check files
410 fmt.Fprintf(os.Stderr, "WARNING: Error accessing path '%s', err: %s\n", srcDirBazelFileFullPath, err)
411 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400412 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400413 if fileInfo.IsDir() {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400414 // Don't ignore entire directories
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 if !(fileInfo.Name() == "BUILD" || fileInfo.Name() == "BUILD.bazel") {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400418 // Don't ignore this file - it is not a build file
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400419 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400420 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400421 srcDirBazelFileDir := filepath.Dir(srcDirBazelFileRelativePath)
422 if android.ShouldKeepExistingBuildFileForDir(srcDirBazelFileDir) {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400423 // Don't ignore this existing build file
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400424 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400425 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400426 correspondingBp2BuildFile := shared.JoinPath(topDir, generatedRoot, srcDirBazelFileRelativePath)
427 if _, err := os.Stat(correspondingBp2BuildFile); err == nil {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400428 // If bp2build generated an alternate BUILD file, don't exclude this workspace path
429 // BUILD file clash resolution happens later in the symlink forest creation
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400430 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400431 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400432 fmt.Fprintf(os.Stderr, "Ignoring existing BUILD file: %s\n", srcDirBazelFileRelativePath)
433 paths = append(paths, srcDirBazelFileRelativePath)
434 }
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400435
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400436 return paths
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400437}
438
439// Returns temporary symlink forest excludes necessary for bazel build //external/... (and bazel build //frameworks/...) to work
440func getTemporaryExcludes() []string {
441 excludes := make([]string, 0)
442
443 // FIXME: 'autotest_lib' is a symlink back to external/autotest, and this causes an infinite symlink expansion error for Bazel
444 excludes = append(excludes, "external/autotest/venv/autotest_lib")
445
446 // FIXME: The external/google-fruit/extras/bazel_root/third_party/fruit dir is poison
447 // It contains several symlinks back to real source dirs, and those source dirs contain BUILD files we want to ignore
448 excludes = append(excludes, "external/google-fruit/extras/bazel_root/third_party/fruit")
449
450 // FIXME: 'frameworks/compile/slang' has a filegroup error due to an escaping issue
451 excludes = append(excludes, "frameworks/compile/slang")
452
453 return excludes
454}
455
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400456// Read the bazel.list file that the Soong Finder already dumped earlier (hopefully)
457// It contains the locations of BUILD files, BUILD.bazel files, etc. in the source dir
458func getExistingBazelRelatedFiles(topDir string) ([]string, error) {
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200459 bazelFinderFile := filepath.Join(filepath.Dir(cmdlineArgs.ModuleListFile), "bazel.list")
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400460 if !filepath.IsAbs(bazelFinderFile) {
461 // Assume this was a relative path under topDir
462 bazelFinderFile = filepath.Join(topDir, bazelFinderFile)
463 }
464 data, err := ioutil.ReadFile(bazelFinderFile)
465 if err != nil {
466 return nil, err
467 }
468 files := strings.Split(strings.TrimSpace(string(data)), "\n")
469 return files, nil
470}
471
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500472// Run Soong in the bp2build mode. This creates a standalone context that registers
473// an alternate pipeline of mutators and singletons specifically for generating
474// Bazel BUILD files instead of Ninja files.
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200475func runBp2Build(configuration android.Config, extraNinjaDeps []string) {
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500476 // Register an alternate set of singletons and mutators for bazel
477 // conversion for Bazel conversion.
478 bp2buildCtx := android.NewContext(configuration)
Jingwen Cheneb76c432021-01-28 08:22:12 -0500479
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200480 // Propagate "allow misssing dependencies" bit. This is normally set in
481 // newContext(), but we create bp2buildCtx without calling that method.
482 bp2buildCtx.SetAllowMissingDependencies(configuration.AllowMissingDependencies())
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500483 bp2buildCtx.SetNameInterface(newNameResolver(configuration))
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200484 bp2buildCtx.RegisterForBazelConversion()
Jingwen Cheneb76c432021-01-28 08:22:12 -0500485
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500486 // The bp2build process is a purely functional process that only depends on
487 // Android.bp files. It must not depend on the values of per-build product
488 // configurations or variables, since those will generate different BUILD
489 // files based on how the user has configured their tree.
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200490 bp2buildCtx.SetModuleListFile(cmdlineArgs.ModuleListFile)
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200491 modulePaths, err := bp2buildCtx.ListModulePaths(".")
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500492 if err != nil {
493 panic(err)
494 }
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500495
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100496 extraNinjaDeps = append(extraNinjaDeps, modulePaths...)
497
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200498 // No need to generate Ninja build rules/statements from Modules and Singletons.
499 configuration.SetStopBefore(bootstrap.StopBeforePrepareBuildActions)
500
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500501 // Run the loading and analysis pipeline to prepare the graph of regular
502 // Modules parsed from Android.bp files, and the BazelTargetModules mapped
503 // from the regular Modules.
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200504 blueprintArgs := cmdlineArgs
Lukacs T. Berki6124c9b2021-04-15 15:06:40 +0200505 ninjaDeps := bootstrap.RunBlueprint(blueprintArgs, bp2buildCtx.Context, configuration)
506 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200507
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200508 globListFiles := writeBuildGlobsNinjaFile(bp2buildCtx.SrcDir(), configuration.SoongOutDir(), bp2buildCtx.Globs, configuration)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200509 ninjaDeps = append(ninjaDeps, globListFiles...)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200510
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200511 // Run the code-generation phase to convert BazelTargetModules to BUILD files
512 // and print conversion metrics to the user.
513 codegenContext := bp2build.NewCodegenContext(configuration, *bp2buildCtx, bp2build.Bp2Build)
514 metrics := bp2build.Codegen(codegenContext)
515
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200516 generatedRoot := shared.JoinPath(configuration.SoongOutDir(), "bp2build")
517 workspaceRoot := shared.JoinPath(configuration.SoongOutDir(), "workspace")
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200518
519 excludes := []string{
520 "bazel-bin",
521 "bazel-genfiles",
522 "bazel-out",
523 "bazel-testlogs",
524 "bazel-" + filepath.Base(topDir),
525 }
526
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200527 if cmdlineArgs.NinjaBuildDir[0] != '/' {
528 excludes = append(excludes, cmdlineArgs.NinjaBuildDir)
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200529 }
530
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400531 existingBazelRelatedFiles, err := getExistingBazelRelatedFiles(topDir)
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400532 if err != nil {
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400533 fmt.Fprintf(os.Stderr, "Error determining existing Bazel-related files: %s\n", err)
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400534 os.Exit(1)
535 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400536
537 pathsToIgnoredBuildFiles := getPathsToIgnoredBuildFiles(topDir, generatedRoot, existingBazelRelatedFiles)
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400538 excludes = append(excludes, pathsToIgnoredBuildFiles...)
539
540 excludes = append(excludes, getTemporaryExcludes()...)
541
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200542 symlinkForestDeps := bp2build.PlantSymlinkForest(
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200543 topDir, workspaceRoot, generatedRoot, ".", excludes)
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200544
545 // Only report metrics when in bp2build mode. The metrics aren't relevant
546 // for queryview, since that's a total repo-wide conversion and there's a
547 // 1:1 mapping for each module.
548 metrics.Print()
549
550 ninjaDeps = append(ninjaDeps, codegenContext.AdditionalNinjaDeps()...)
551 ninjaDeps = append(ninjaDeps, symlinkForestDeps...)
552
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200553 depFile := bp2buildMarker + ".d"
554 err = deptools.WriteDepFile(shared.JoinPath(topDir, depFile), bp2buildMarker, ninjaDeps)
555 if err != nil {
556 fmt.Fprintf(os.Stderr, "Cannot write depfile '%s': %s\n", depFile, err)
557 os.Exit(1)
558 }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500559
Jingwen Chen4fabaf52021-05-25 02:40:29 +0000560 // Create an empty bp2build marker file.
561 touch(shared.JoinPath(topDir, bp2buildMarker))
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500562}