blob: beda1842a9a0554d32c11148124cb4891f55e212 [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"
Lukacs T. Berkie571dc32021-08-25 14:14:13 +020028
Colin Cross70b40592015-03-23 12:57:34 -070029 "github.com/google/blueprint/bootstrap"
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +020030 "github.com/google/blueprint/deptools"
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +020031 "github.com/google/blueprint/pathtools"
Colin Cross3f40fa42015-01-30 17:27:36 -080032
Colin Cross635c3b02016-05-18 15:37:25 -070033 "android/soong/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
38 outDir string
39 availableEnvFile string
40 usedEnvFile string
41
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +020042 globFile string
43 globListDir string
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020044 delveListen string
45 delvePath string
46
Lukacs T. Berkie571dc32021-08-25 14:14:13 +020047 moduleGraphFile string
Jingwen Chen50f93d22020-11-05 07:42:11 -050048 docFile string
49 bazelQueryViewDir string
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020050 bp2buildMarker string
Lukacs T. Berkif9008072021-08-16 15:24:48 +020051
52 cmdlineArgs bootstrap.Args
Colin Crosse87040b2017-12-11 15:52:26 -080053)
54
55func init() {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020056 // Flags that make sense in every mode
Lukacs T. Berki7690c092021-02-26 14:27:36 +010057 flag.StringVar(&topDir, "top", "", "Top directory of the Android source tree")
58 flag.StringVar(&outDir, "out", "", "Soong output directory (usually $TOP/out/soong)")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020059 flag.StringVar(&availableEnvFile, "available_env", "", "File containing available environment variables")
60 flag.StringVar(&usedEnvFile, "used_env", "", "File containing used environment variables")
61
62 // Debug flags
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +010063 flag.StringVar(&delveListen, "delve_listen", "", "Delve port to listen on for debugging")
64 flag.StringVar(&delvePath, "delve_path", "", "Path to Delve. Only used if --delve_listen is set")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020065
66 // Flags representing various modes soong_build can run in
Lukacs T. Berkie571dc32021-08-25 14:14:13 +020067 flag.StringVar(&moduleGraphFile, "module_graph_file", "", "JSON module graph file to output")
Colin Crosse87040b2017-12-11 15:52:26 -080068 flag.StringVar(&docFile, "soong_docs", "", "build documentation file to output")
Lukacs T. Berki47a9d0c2021-03-08 16:34:09 +010069 flag.StringVar(&bazelQueryViewDir, "bazel_queryview_dir", "", "path to the bazel queryview directory relative to --top")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020070 flag.StringVar(&bp2buildMarker, "bp2build_marker", "", "If set, run bp2build, touch the specified marker file then exit")
Lukacs T. Berkif9008072021-08-16 15:24:48 +020071
72 flag.StringVar(&cmdlineArgs.OutFile, "o", "build.ninja", "the Ninja file to output")
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +020073 flag.StringVar(&globFile, "globFile", "build-globs.ninja", "the Ninja file of globs to output")
74 flag.StringVar(&globListDir, "globListDir", "", "the directory containing the glob list files")
Lukacs T. Berkif9008072021-08-16 15:24:48 +020075 flag.StringVar(&cmdlineArgs.BuildDir, "b", ".", "the build output directory")
76 flag.StringVar(&cmdlineArgs.NinjaBuildDir, "n", "", "the ninja builddir directory")
Lukacs T. Berkif9008072021-08-16 15:24:48 +020077 flag.StringVar(&cmdlineArgs.Cpuprofile, "cpuprofile", "", "write cpu profile to file")
78 flag.StringVar(&cmdlineArgs.TraceFile, "trace", "", "write trace to file")
79 flag.StringVar(&cmdlineArgs.Memprofile, "memprofile", "", "write memory profile to file")
80 flag.BoolVar(&cmdlineArgs.NoGC, "nogc", false, "turn off GC for debugging")
81 flag.BoolVar(&cmdlineArgs.RunGoTests, "t", false, "build and run go tests during bootstrap")
82 flag.BoolVar(&cmdlineArgs.UseValidations, "use-validations", false, "use validations to depend on go tests")
83 flag.StringVar(&cmdlineArgs.ModuleListFile, "l", "", "file that lists filepaths to parse")
84 flag.BoolVar(&cmdlineArgs.EmptyNinjaFile, "empty-ninja-file", false, "write out a 0-byte ninja file")
Colin Crosse87040b2017-12-11 15:52:26 -080085}
86
Jeff Gaston088e29e2017-11-29 16:47:17 -080087func newNameResolver(config android.Config) *android.NameResolver {
88 namespacePathsToExport := make(map[string]bool)
89
Dan Willemsen3fb1fae2018-03-12 15:30:26 -070090 for _, namespaceName := range config.ExportedNamespaces() {
Jeff Gaston088e29e2017-11-29 16:47:17 -080091 namespacePathsToExport[namespaceName] = true
92 }
93
94 namespacePathsToExport["."] = true // always export the root namespace
95
96 exportFilter := func(namespace *android.Namespace) bool {
97 return namespacePathsToExport[namespace.Path]
98 }
99
100 return android.NewNameResolver(exportFilter)
101}
102
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200103func newContext(configuration android.Config, prepareBuildActions bool) *android.Context {
Colin Crossae8600b2020-10-29 17:09:13 -0700104 ctx := android.NewContext(configuration)
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500105 ctx.Register()
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200106 if !prepareBuildActions {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400107 configuration.SetStopBefore(bootstrap.StopBeforePrepareBuildActions)
108 }
109 ctx.SetNameInterface(newNameResolver(configuration))
110 ctx.SetAllowMissingDependencies(configuration.AllowMissingDependencies())
111 return ctx
112}
113
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200114func newConfig(outDir string, availableEnv map[string]string) android.Config {
115 configuration, err := android.NewConfig(outDir, cmdlineArgs.ModuleListFile, availableEnv)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400116 if err != nil {
117 fmt.Fprintf(os.Stderr, "%s", err)
118 os.Exit(1)
119 }
120 return configuration
121}
122
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200123// Bazel-enabled mode. Soong runs in two passes.
124// First pass: Analyze the build tree, but only store all bazel commands
125// needed to correctly evaluate the tree in the second pass.
126// TODO(cparsons): Don't output any ninja file, as the second pass will overwrite
127// the incorrect results from the first pass, and file I/O is expensive.
128func runMixedModeBuild(configuration android.Config, firstCtx *android.Context, extraNinjaDeps []string) {
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200129 var firstArgs, secondArgs bootstrap.Args
130
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200131 firstArgs = cmdlineArgs
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200132 configuration.SetStopBefore(bootstrap.StopBeforeWriteNinja)
Lukacs T. Berki6124c9b2021-04-15 15:06:40 +0200133 bootstrap.RunBlueprint(firstArgs, firstCtx.Context, configuration)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200134
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200135 // Invoke bazel commands and save results for second pass.
136 if err := configuration.BazelContext.InvokeBazel(); err != nil {
137 fmt.Fprintf(os.Stderr, "%s", err)
138 os.Exit(1)
139 }
140 // Second pass: Full analysis, using the bazel command results. Output ninja file.
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200141 secondConfig, err := android.ConfigForAdditionalRun(configuration)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200142 if err != nil {
143 fmt.Fprintf(os.Stderr, "%s", err)
144 os.Exit(1)
145 }
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200146 secondCtx := newContext(secondConfig, true)
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200147 secondArgs = cmdlineArgs
Lukacs T. Berki6124c9b2021-04-15 15:06:40 +0200148 ninjaDeps := bootstrap.RunBlueprint(secondArgs, secondCtx.Context, secondConfig)
149 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200150
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200151 globListFiles := writeBuildGlobsNinjaFile(secondCtx.SrcDir(), configuration.SoongOutDir(), secondCtx.Globs, configuration)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200152 ninjaDeps = append(ninjaDeps, globListFiles...)
153
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200154 writeDepFile(secondArgs.OutFile, ninjaDeps)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200155}
156
157// Run the code-generation phase to convert BazelTargetModules to BUILD files.
158func runQueryView(configuration android.Config, ctx *android.Context) {
159 codegenContext := bp2build.NewCodegenContext(configuration, *ctx, bp2build.QueryView)
160 absoluteQueryViewDir := shared.JoinPath(topDir, bazelQueryViewDir)
161 if err := createBazelQueryView(codegenContext, absoluteQueryViewDir); err != nil {
162 fmt.Fprintf(os.Stderr, "%s", err)
163 os.Exit(1)
164 }
165}
166
Lukacs T. Berki6124c9b2021-04-15 15:06:40 +0200167func runSoongDocs(configuration android.Config) {
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200168 ctx := newContext(configuration, false)
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200169 soongDocsArgs := cmdlineArgs
Lukacs T. Berki6124c9b2021-04-15 15:06:40 +0200170 bootstrap.RunBlueprint(soongDocsArgs, ctx.Context, configuration)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200171 if err := writeDocs(ctx, configuration, docFile); err != nil {
172 fmt.Fprintf(os.Stderr, "%s", err)
173 os.Exit(1)
174 }
175}
176
177func writeMetrics(configuration android.Config) {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200178 metricsFile := filepath.Join(configuration.SoongOutDir(), "soong_build_metrics.pb")
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200179 err := android.WriteMetrics(configuration, metricsFile)
180 if err != nil {
181 fmt.Fprintf(os.Stderr, "error writing soong_build metrics %s: %s", metricsFile, err)
182 os.Exit(1)
183 }
184}
185
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200186func writeJsonModuleGraph(ctx *android.Context, path string) {
187 f, err := os.Create(shared.JoinPath(topDir, path))
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200188 if err != nil {
189 fmt.Fprintf(os.Stderr, "%s", err)
190 os.Exit(1)
191 }
192
193 defer f.Close()
194 ctx.Context.PrintJSONGraph(f)
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200195}
196
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200197func writeBuildGlobsNinjaFile(srcDir, buildDir string, globs func() pathtools.MultipleGlobResults, config interface{}) []string {
198 globDir := bootstrap.GlobDirectory(buildDir, globListDir)
199 bootstrap.WriteBuildGlobsNinjaFile(&bootstrap.GlobSingleton{
200 GlobLister: globs,
201 GlobFile: globFile,
202 GlobDir: globDir,
203 SrcDir: srcDir,
204 }, config)
205 return bootstrap.GlobFileListFiles(globDir)
206}
207
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200208func writeDepFile(outputFile string, ninjaDeps []string) {
209 depFile := shared.JoinPath(topDir, outputFile+".d")
210 err := deptools.WriteDepFile(depFile, outputFile, ninjaDeps)
211 if err != nil {
212 fmt.Fprintf(os.Stderr, "Error writing depfile '%s': %s\n", depFile, err)
213 os.Exit(1)
214 }
215}
216
Jingwen Chen4fabaf52021-05-25 02:40:29 +0000217// doChosenActivity runs Soong for a specific activity, like bp2build, queryview
218// or the actual Soong build for the build.ninja file. Returns the top level
219// output file of the specific activity.
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200220func doChosenActivity(configuration android.Config, extraNinjaDeps []string) string {
Chris Parsonsec1a3dc2021-04-20 15:32:07 -0400221 bazelConversionRequested := bp2buildMarker != ""
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200222 mixedModeBuild := configuration.BazelContext.BazelEnabled()
223 generateQueryView := bazelQueryViewDir != ""
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200224
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200225 blueprintArgs := cmdlineArgs
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200226 prepareBuildActions := !generateQueryView && moduleGraphFile == ""
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200227 if bazelConversionRequested {
228 // Run the alternate pipeline of bp2build mutators and singleton to convert
229 // Blueprint to BUILD files before everything else.
230 runBp2Build(configuration, extraNinjaDeps)
Jingwen Chen4fabaf52021-05-25 02:40:29 +0000231 return bp2buildMarker
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200232 }
233
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200234 ctx := newContext(configuration, prepareBuildActions)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200235 if mixedModeBuild {
236 runMixedModeBuild(configuration, ctx, extraNinjaDeps)
237 } else {
Lukacs T. Berki6124c9b2021-04-15 15:06:40 +0200238 ninjaDeps := bootstrap.RunBlueprint(blueprintArgs, ctx.Context, configuration)
239 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200240
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200241 globListFiles := writeBuildGlobsNinjaFile(ctx.SrcDir(), configuration.SoongOutDir(), ctx.Globs, configuration)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200242 ninjaDeps = append(ninjaDeps, globListFiles...)
243
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200244 // Convert the Soong module graph into Bazel BUILD files.
245 if generateQueryView {
246 runQueryView(configuration, ctx)
247 return cmdlineArgs.OutFile // TODO: This is a lie
248 } else if moduleGraphFile != "" {
249 writeJsonModuleGraph(ctx, moduleGraphFile)
250 writeDepFile(moduleGraphFile, ninjaDeps)
251 return moduleGraphFile
252 } else {
253 // The actual output (build.ninja) was written in the RunBlueprint() call
254 // above
255 writeDepFile(cmdlineArgs.OutFile, ninjaDeps)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200256 }
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200257 }
258
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200259 writeMetrics(configuration)
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200260 return cmdlineArgs.OutFile
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200261}
262
263// soong_ui dumps the available environment variables to
264// soong.environment.available . Then soong_build itself is run with an empty
265// environment so that the only way environment variables can be accessed is
266// using Config, which tracks access to them.
267
268// At the end of the build, a file called soong.environment.used is written
269// containing the current value of all used environment variables. The next
270// time soong_ui is run, it checks whether any environment variables that was
271// used had changed and if so, it deletes soong.environment.used to cause a
272// rebuild.
273//
274// The dependency of build.ninja on soong.environment.used is declared in
275// build.ninja.d
276func parseAvailableEnv() map[string]string {
277 if availableEnvFile == "" {
278 fmt.Fprintf(os.Stderr, "--available_env not set\n")
279 os.Exit(1)
280 }
281
282 result, err := shared.EnvFromFile(shared.JoinPath(topDir, availableEnvFile))
283 if err != nil {
284 fmt.Fprintf(os.Stderr, "error reading available environment file '%s': %s\n", availableEnvFile, err)
285 os.Exit(1)
286 }
287
288 return result
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200289}
290
Colin Cross3f40fa42015-01-30 17:27:36 -0800291func main() {
292 flag.Parse()
293
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100294 shared.ReexecWithDelveMaybe(delveListen, delvePath)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100295 android.InitSandbox(topDir)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100296
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200297 availableEnv := parseAvailableEnv()
Lukacs T. Berki53b2f362021-04-12 14:04:24 +0200298
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200299 configuration := newConfig(outDir, availableEnv)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100300 extraNinjaDeps := []string{
301 configuration.ProductVariablesFileName,
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200302 usedEnvFile,
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100303 }
Colin Crossaa812d12019-06-19 13:33:24 -0700304
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100305 if configuration.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
306 configuration.SetAllowMissingDependencies()
307 }
308
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100309 if shared.IsDebugging() {
Colin Crossaa812d12019-06-19 13:33:24 -0700310 // Add a non-existent file to the dependencies so that soong_build will rerun when the debugger is
311 // enabled even if it completed successfully.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200312 extraNinjaDeps = append(extraNinjaDeps, filepath.Join(configuration.SoongOutDir(), "always_rerun_for_delve"))
Colin Crossaa812d12019-06-19 13:33:24 -0700313 }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500314
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200315 if docFile != "" {
316 // We don't write an used variables file when generating documentation
317 // because that is done from within the actual builds as a Ninja action and
318 // thus it would overwrite the actual used variables file so this is
319 // special-cased.
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200320 // TODO: Fix this by not passing --used_env to the soong_docs invocation
Lukacs T. Berki6124c9b2021-04-15 15:06:40 +0200321 runSoongDocs(configuration)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200322 return
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400323 }
Jingwen Chen4133ce62020-12-02 04:34:15 -0500324
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200325 finalOutputFile := doChosenActivity(configuration, extraNinjaDeps)
326 writeUsedEnvironmentFile(configuration, finalOutputFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100327}
328
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200329func writeUsedEnvironmentFile(configuration android.Config, finalOutputFile string) {
330 if usedEnvFile == "" {
331 return
332 }
333
334 path := shared.JoinPath(topDir, usedEnvFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100335 data, err := shared.EnvFileContents(configuration.EnvDeps())
336 if err != nil {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200337 fmt.Fprintf(os.Stderr, "error writing used environment file '%s': %s\n", usedEnvFile, err)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100338 os.Exit(1)
339 }
340
341 err = ioutil.WriteFile(path, data, 0666)
342 if err != nil {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200343 fmt.Fprintf(os.Stderr, "error writing used environment file '%s': %s\n", usedEnvFile, err)
Lukacs T. Berkic99c9472021-03-24 10:50:06 +0100344 os.Exit(1)
345 }
346
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200347 // Touch the output file so that it's not older than the file we just
Lukacs T. Berkic99c9472021-03-24 10:50:06 +0100348 // wrote. We can't write the environment file earlier because one an access
349 // new environment variables while writing it.
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200350 touch(shared.JoinPath(topDir, finalOutputFile))
Colin Cross3f40fa42015-01-30 17:27:36 -0800351}
Jingwen Chen5ba7e472020-07-15 10:06:41 +0000352
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200353func touch(path string) {
354 f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
355 if err != nil {
356 fmt.Fprintf(os.Stderr, "Error touching '%s': %s\n", path, err)
357 os.Exit(1)
358 }
359
360 err = f.Close()
361 if err != nil {
362 fmt.Fprintf(os.Stderr, "Error touching '%s': %s\n", path, err)
363 os.Exit(1)
364 }
365
366 currentTime := time.Now().Local()
367 err = os.Chtimes(path, currentTime, currentTime)
368 if err != nil {
369 fmt.Fprintf(os.Stderr, "error touching '%s': %s\n", path, err)
370 os.Exit(1)
371 }
372}
373
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400374// Find BUILD files in the srcDir which...
375//
376// - are not on the allow list (android/bazel.go#ShouldKeepExistingBuildFileForDir())
377//
378// - won't be overwritten by corresponding bp2build generated files
379//
380// 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 -0400381func getPathsToIgnoredBuildFiles(topDir string, generatedRoot string, srcDirBazelFiles []string) []string {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400382 paths := make([]string, 0)
383
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400384 for _, srcDirBazelFileRelativePath := range srcDirBazelFiles {
385 srcDirBazelFileFullPath := shared.JoinPath(topDir, srcDirBazelFileRelativePath)
386 fileInfo, err := os.Stat(srcDirBazelFileFullPath)
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400387 if err != nil {
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400388 // Warn about error, but continue trying to check files
389 fmt.Fprintf(os.Stderr, "WARNING: Error accessing path '%s', err: %s\n", srcDirBazelFileFullPath, err)
390 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400391 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400392 if fileInfo.IsDir() {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400393 // Don't ignore entire directories
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400394 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400395 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400396 if !(fileInfo.Name() == "BUILD" || fileInfo.Name() == "BUILD.bazel") {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400397 // Don't ignore this file - it is not a build file
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400398 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400399 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400400 srcDirBazelFileDir := filepath.Dir(srcDirBazelFileRelativePath)
401 if android.ShouldKeepExistingBuildFileForDir(srcDirBazelFileDir) {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400402 // Don't ignore this existing build file
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400403 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400404 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400405 correspondingBp2BuildFile := shared.JoinPath(topDir, generatedRoot, srcDirBazelFileRelativePath)
406 if _, err := os.Stat(correspondingBp2BuildFile); err == nil {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400407 // If bp2build generated an alternate BUILD file, don't exclude this workspace path
408 // BUILD file clash resolution happens later in the symlink forest creation
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400409 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400410 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400411 fmt.Fprintf(os.Stderr, "Ignoring existing BUILD file: %s\n", srcDirBazelFileRelativePath)
412 paths = append(paths, srcDirBazelFileRelativePath)
413 }
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400414
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400415 return paths
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400416}
417
418// Returns temporary symlink forest excludes necessary for bazel build //external/... (and bazel build //frameworks/...) to work
419func getTemporaryExcludes() []string {
420 excludes := make([]string, 0)
421
422 // FIXME: 'autotest_lib' is a symlink back to external/autotest, and this causes an infinite symlink expansion error for Bazel
423 excludes = append(excludes, "external/autotest/venv/autotest_lib")
424
425 // FIXME: The external/google-fruit/extras/bazel_root/third_party/fruit dir is poison
426 // It contains several symlinks back to real source dirs, and those source dirs contain BUILD files we want to ignore
427 excludes = append(excludes, "external/google-fruit/extras/bazel_root/third_party/fruit")
428
429 // FIXME: 'frameworks/compile/slang' has a filegroup error due to an escaping issue
430 excludes = append(excludes, "frameworks/compile/slang")
431
432 return excludes
433}
434
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400435// Read the bazel.list file that the Soong Finder already dumped earlier (hopefully)
436// It contains the locations of BUILD files, BUILD.bazel files, etc. in the source dir
437func getExistingBazelRelatedFiles(topDir string) ([]string, error) {
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200438 bazelFinderFile := filepath.Join(filepath.Dir(cmdlineArgs.ModuleListFile), "bazel.list")
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400439 if !filepath.IsAbs(bazelFinderFile) {
440 // Assume this was a relative path under topDir
441 bazelFinderFile = filepath.Join(topDir, bazelFinderFile)
442 }
443 data, err := ioutil.ReadFile(bazelFinderFile)
444 if err != nil {
445 return nil, err
446 }
447 files := strings.Split(strings.TrimSpace(string(data)), "\n")
448 return files, nil
449}
450
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500451// Run Soong in the bp2build mode. This creates a standalone context that registers
452// an alternate pipeline of mutators and singletons specifically for generating
453// Bazel BUILD files instead of Ninja files.
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200454func runBp2Build(configuration android.Config, extraNinjaDeps []string) {
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500455 // Register an alternate set of singletons and mutators for bazel
456 // conversion for Bazel conversion.
457 bp2buildCtx := android.NewContext(configuration)
Jingwen Cheneb76c432021-01-28 08:22:12 -0500458
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200459 // Propagate "allow misssing dependencies" bit. This is normally set in
460 // newContext(), but we create bp2buildCtx without calling that method.
461 bp2buildCtx.SetAllowMissingDependencies(configuration.AllowMissingDependencies())
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500462 bp2buildCtx.SetNameInterface(newNameResolver(configuration))
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200463 bp2buildCtx.RegisterForBazelConversion()
Jingwen Cheneb76c432021-01-28 08:22:12 -0500464
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500465 // The bp2build process is a purely functional process that only depends on
466 // Android.bp files. It must not depend on the values of per-build product
467 // configurations or variables, since those will generate different BUILD
468 // files based on how the user has configured their tree.
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200469 bp2buildCtx.SetModuleListFile(cmdlineArgs.ModuleListFile)
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200470 modulePaths, err := bp2buildCtx.ListModulePaths(".")
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500471 if err != nil {
472 panic(err)
473 }
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500474
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100475 extraNinjaDeps = append(extraNinjaDeps, modulePaths...)
476
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200477 // No need to generate Ninja build rules/statements from Modules and Singletons.
478 configuration.SetStopBefore(bootstrap.StopBeforePrepareBuildActions)
479
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500480 // Run the loading and analysis pipeline to prepare the graph of regular
481 // Modules parsed from Android.bp files, and the BazelTargetModules mapped
482 // from the regular Modules.
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200483 blueprintArgs := cmdlineArgs
Lukacs T. Berki6124c9b2021-04-15 15:06:40 +0200484 ninjaDeps := bootstrap.RunBlueprint(blueprintArgs, bp2buildCtx.Context, configuration)
485 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200486
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200487 globListFiles := writeBuildGlobsNinjaFile(bp2buildCtx.SrcDir(), configuration.SoongOutDir(), bp2buildCtx.Globs, configuration)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200488 ninjaDeps = append(ninjaDeps, globListFiles...)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200489
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200490 // Run the code-generation phase to convert BazelTargetModules to BUILD files
491 // and print conversion metrics to the user.
492 codegenContext := bp2build.NewCodegenContext(configuration, *bp2buildCtx, bp2build.Bp2Build)
493 metrics := bp2build.Codegen(codegenContext)
494
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200495 generatedRoot := shared.JoinPath(configuration.SoongOutDir(), "bp2build")
496 workspaceRoot := shared.JoinPath(configuration.SoongOutDir(), "workspace")
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200497
498 excludes := []string{
499 "bazel-bin",
500 "bazel-genfiles",
501 "bazel-out",
502 "bazel-testlogs",
503 "bazel-" + filepath.Base(topDir),
504 }
505
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200506 if cmdlineArgs.NinjaBuildDir[0] != '/' {
507 excludes = append(excludes, cmdlineArgs.NinjaBuildDir)
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200508 }
509
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400510 existingBazelRelatedFiles, err := getExistingBazelRelatedFiles(topDir)
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400511 if err != nil {
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400512 fmt.Fprintf(os.Stderr, "Error determining existing Bazel-related files: %s\n", err)
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400513 os.Exit(1)
514 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400515
516 pathsToIgnoredBuildFiles := getPathsToIgnoredBuildFiles(topDir, generatedRoot, existingBazelRelatedFiles)
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400517 excludes = append(excludes, pathsToIgnoredBuildFiles...)
518
519 excludes = append(excludes, getTemporaryExcludes()...)
520
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200521 symlinkForestDeps := bp2build.PlantSymlinkForest(
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200522 topDir, workspaceRoot, generatedRoot, ".", excludes)
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200523
524 // Only report metrics when in bp2build mode. The metrics aren't relevant
525 // for queryview, since that's a total repo-wide conversion and there's a
526 // 1:1 mapping for each module.
527 metrics.Print()
528
529 ninjaDeps = append(ninjaDeps, codegenContext.AdditionalNinjaDeps()...)
530 ninjaDeps = append(ninjaDeps, symlinkForestDeps...)
531
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200532 writeDepFile(bp2buildMarker, ninjaDeps)
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500533
Jingwen Chen4fabaf52021-05-25 02:40:29 +0000534 // Create an empty bp2build marker file.
535 touch(shared.JoinPath(topDir, bp2buildMarker))
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500536}