blob: 3e724ee531c37a7c4360df6a01671b3d391aae4f [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
Lukacs T. Berkid6cee7e2021-09-01 16:25:51 +020038 soongOutDir string
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020039 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")
Lukacs T. Berkid6cee7e2021-09-01 16:25:51 +020058 flag.StringVar(&soongOutDir, "soong_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")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020061 flag.StringVar(&globFile, "globFile", "build-globs.ninja", "the Ninja file of globs to output")
62 flag.StringVar(&globListDir, "globListDir", "", "the directory containing the glob list files")
Lukacs T. Berkid6cee7e2021-09-01 16:25:51 +020063 flag.StringVar(&cmdlineArgs.OutDir, "out", "", "the ninja builddir directory")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020064 flag.StringVar(&cmdlineArgs.ModuleListFile, "l", "", "file that lists filepaths to parse")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020065
66 // Debug flags
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +010067 flag.StringVar(&delveListen, "delve_listen", "", "Delve port to listen on for debugging")
68 flag.StringVar(&delvePath, "delve_path", "", "Path to Delve. Only used if --delve_listen is set")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020069 flag.StringVar(&cmdlineArgs.Cpuprofile, "cpuprofile", "", "write cpu profile to file")
70 flag.StringVar(&cmdlineArgs.TraceFile, "trace", "", "write trace to file")
71 flag.StringVar(&cmdlineArgs.Memprofile, "memprofile", "", "write memory profile to file")
72 flag.BoolVar(&cmdlineArgs.NoGC, "nogc", false, "turn off GC for debugging")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020073
74 // Flags representing various modes soong_build can run in
Lukacs T. Berkie571dc32021-08-25 14:14:13 +020075 flag.StringVar(&moduleGraphFile, "module_graph_file", "", "JSON module graph file to output")
Colin Crosse87040b2017-12-11 15:52:26 -080076 flag.StringVar(&docFile, "soong_docs", "", "build documentation file to output")
Lukacs T. Berki47a9d0c2021-03-08 16:34:09 +010077 flag.StringVar(&bazelQueryViewDir, "bazel_queryview_dir", "", "path to the bazel queryview directory relative to --top")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020078 flag.StringVar(&bp2buildMarker, "bp2build_marker", "", "If set, run bp2build, touch the specified marker file then exit")
Lukacs T. Berkif9008072021-08-16 15:24:48 +020079 flag.StringVar(&cmdlineArgs.OutFile, "o", "build.ninja", "the Ninja file to output")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020080 flag.BoolVar(&cmdlineArgs.EmptyNinjaFile, "empty-ninja-file", false, "write out a 0-byte ninja file")
81
82 // Flags that probably shouldn't be flags of soong_build but we haven't found
83 // the time to remove them yet
Lukacs T. Berkif9008072021-08-16 15:24:48 +020084 flag.BoolVar(&cmdlineArgs.RunGoTests, "t", false, "build and run go tests during bootstrap")
85 flag.BoolVar(&cmdlineArgs.UseValidations, "use-validations", false, "use validations to depend on go tests")
Colin Crosse87040b2017-12-11 15:52:26 -080086}
87
Jeff Gaston088e29e2017-11-29 16:47:17 -080088func newNameResolver(config android.Config) *android.NameResolver {
89 namespacePathsToExport := make(map[string]bool)
90
Dan Willemsen3fb1fae2018-03-12 15:30:26 -070091 for _, namespaceName := range config.ExportedNamespaces() {
Jeff Gaston088e29e2017-11-29 16:47:17 -080092 namespacePathsToExport[namespaceName] = true
93 }
94
95 namespacePathsToExport["."] = true // always export the root namespace
96
97 exportFilter := func(namespace *android.Namespace) bool {
98 return namespacePathsToExport[namespace.Path]
99 }
100
101 return android.NewNameResolver(exportFilter)
102}
103
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200104func newContext(configuration android.Config, prepareBuildActions bool) *android.Context {
Colin Crossae8600b2020-10-29 17:09:13 -0700105 ctx := android.NewContext(configuration)
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500106 ctx.Register()
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200107 if !prepareBuildActions {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400108 configuration.SetStopBefore(bootstrap.StopBeforePrepareBuildActions)
109 }
110 ctx.SetNameInterface(newNameResolver(configuration))
111 ctx.SetAllowMissingDependencies(configuration.AllowMissingDependencies())
112 return ctx
113}
114
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +0200115func newConfig(cmdlineArgs bootstrap.Args, outDir string, availableEnv map[string]string) android.Config {
116 configuration, err := android.NewConfig(cmdlineArgs, outDir, availableEnv)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400117 if err != nil {
118 fmt.Fprintf(os.Stderr, "%s", err)
119 os.Exit(1)
120 }
121 return configuration
122}
123
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200124// Bazel-enabled mode. Soong runs in two passes.
125// First pass: Analyze the build tree, but only store all bazel commands
126// needed to correctly evaluate the tree in the second pass.
127// TODO(cparsons): Don't output any ninja file, as the second pass will overwrite
128// the incorrect results from the first pass, and file I/O is expensive.
129func runMixedModeBuild(configuration android.Config, firstCtx *android.Context, extraNinjaDeps []string) {
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200130 var firstArgs, secondArgs bootstrap.Args
131
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200132 firstArgs = cmdlineArgs
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200133 configuration.SetStopBefore(bootstrap.StopBeforeWriteNinja)
Lukacs T. Berki6124c9b2021-04-15 15:06:40 +0200134 bootstrap.RunBlueprint(firstArgs, firstCtx.Context, configuration)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200135
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200136 // Invoke bazel commands and save results for second pass.
137 if err := configuration.BazelContext.InvokeBazel(); err != nil {
138 fmt.Fprintf(os.Stderr, "%s", err)
139 os.Exit(1)
140 }
141 // Second pass: Full analysis, using the bazel command results. Output ninja file.
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +0200142 secondArgs = cmdlineArgs
143 secondConfig, err := android.ConfigForAdditionalRun(secondArgs, configuration)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200144 if err != nil {
145 fmt.Fprintf(os.Stderr, "%s", err)
146 os.Exit(1)
147 }
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200148 secondCtx := newContext(secondConfig, true)
Lukacs T. Berki6124c9b2021-04-15 15:06:40 +0200149 ninjaDeps := bootstrap.RunBlueprint(secondArgs, secondCtx.Context, secondConfig)
150 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200151
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200152 globListFiles := writeBuildGlobsNinjaFile(secondCtx.SrcDir(), configuration.SoongOutDir(), secondCtx.Globs, configuration)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200153 ninjaDeps = append(ninjaDeps, globListFiles...)
154
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200155 writeDepFile(secondArgs.OutFile, ninjaDeps)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200156}
157
158// Run the code-generation phase to convert BazelTargetModules to BUILD files.
159func runQueryView(configuration android.Config, ctx *android.Context) {
160 codegenContext := bp2build.NewCodegenContext(configuration, *ctx, bp2build.QueryView)
161 absoluteQueryViewDir := shared.JoinPath(topDir, bazelQueryViewDir)
162 if err := createBazelQueryView(codegenContext, absoluteQueryViewDir); err != nil {
163 fmt.Fprintf(os.Stderr, "%s", err)
164 os.Exit(1)
165 }
166}
167
Lukacs T. Berki6124c9b2021-04-15 15:06:40 +0200168func runSoongDocs(configuration android.Config) {
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200169 ctx := newContext(configuration, false)
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200170 soongDocsArgs := cmdlineArgs
Lukacs T. Berki6124c9b2021-04-15 15:06:40 +0200171 bootstrap.RunBlueprint(soongDocsArgs, ctx.Context, configuration)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200172 if err := writeDocs(ctx, configuration, docFile); err != nil {
173 fmt.Fprintf(os.Stderr, "%s", err)
174 os.Exit(1)
175 }
176}
177
178func writeMetrics(configuration android.Config) {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200179 metricsFile := filepath.Join(configuration.SoongOutDir(), "soong_build_metrics.pb")
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200180 err := android.WriteMetrics(configuration, metricsFile)
181 if err != nil {
182 fmt.Fprintf(os.Stderr, "error writing soong_build metrics %s: %s", metricsFile, err)
183 os.Exit(1)
184 }
185}
186
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200187func writeJsonModuleGraph(ctx *android.Context, path string) {
188 f, err := os.Create(shared.JoinPath(topDir, path))
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200189 if err != nil {
190 fmt.Fprintf(os.Stderr, "%s", err)
191 os.Exit(1)
192 }
193
194 defer f.Close()
195 ctx.Context.PrintJSONGraph(f)
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200196}
197
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200198func writeBuildGlobsNinjaFile(srcDir, buildDir string, globs func() pathtools.MultipleGlobResults, config interface{}) []string {
199 globDir := bootstrap.GlobDirectory(buildDir, globListDir)
200 bootstrap.WriteBuildGlobsNinjaFile(&bootstrap.GlobSingleton{
201 GlobLister: globs,
202 GlobFile: globFile,
203 GlobDir: globDir,
204 SrcDir: srcDir,
205 }, config)
206 return bootstrap.GlobFileListFiles(globDir)
207}
208
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200209func writeDepFile(outputFile string, ninjaDeps []string) {
210 depFile := shared.JoinPath(topDir, outputFile+".d")
211 err := deptools.WriteDepFile(depFile, outputFile, ninjaDeps)
212 if err != nil {
213 fmt.Fprintf(os.Stderr, "Error writing depfile '%s': %s\n", depFile, err)
214 os.Exit(1)
215 }
216}
217
Jingwen Chen4fabaf52021-05-25 02:40:29 +0000218// doChosenActivity runs Soong for a specific activity, like bp2build, queryview
219// or the actual Soong build for the build.ninja file. Returns the top level
220// output file of the specific activity.
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200221func doChosenActivity(configuration android.Config, extraNinjaDeps []string) string {
Chris Parsonsec1a3dc2021-04-20 15:32:07 -0400222 bazelConversionRequested := bp2buildMarker != ""
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200223 mixedModeBuild := configuration.BazelContext.BazelEnabled()
224 generateQueryView := bazelQueryViewDir != ""
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200225
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200226 blueprintArgs := cmdlineArgs
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200227 prepareBuildActions := !generateQueryView && moduleGraphFile == ""
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200228 if bazelConversionRequested {
229 // Run the alternate pipeline of bp2build mutators and singleton to convert
230 // Blueprint to BUILD files before everything else.
231 runBp2Build(configuration, extraNinjaDeps)
Jingwen Chen4fabaf52021-05-25 02:40:29 +0000232 return bp2buildMarker
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200233 }
234
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200235 ctx := newContext(configuration, prepareBuildActions)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200236 if mixedModeBuild {
237 runMixedModeBuild(configuration, ctx, extraNinjaDeps)
238 } else {
Lukacs T. Berki6124c9b2021-04-15 15:06:40 +0200239 ninjaDeps := bootstrap.RunBlueprint(blueprintArgs, ctx.Context, configuration)
240 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200241
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200242 globListFiles := writeBuildGlobsNinjaFile(ctx.SrcDir(), configuration.SoongOutDir(), ctx.Globs, configuration)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200243 ninjaDeps = append(ninjaDeps, globListFiles...)
244
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200245 // Convert the Soong module graph into Bazel BUILD files.
246 if generateQueryView {
247 runQueryView(configuration, ctx)
248 return cmdlineArgs.OutFile // TODO: This is a lie
249 } else if moduleGraphFile != "" {
250 writeJsonModuleGraph(ctx, moduleGraphFile)
251 writeDepFile(moduleGraphFile, ninjaDeps)
252 return moduleGraphFile
253 } else {
254 // The actual output (build.ninja) was written in the RunBlueprint() call
255 // above
256 writeDepFile(cmdlineArgs.OutFile, ninjaDeps)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200257 }
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200258 }
259
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200260 writeMetrics(configuration)
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200261 return cmdlineArgs.OutFile
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200262}
263
264// soong_ui dumps the available environment variables to
265// soong.environment.available . Then soong_build itself is run with an empty
266// environment so that the only way environment variables can be accessed is
267// using Config, which tracks access to them.
268
269// At the end of the build, a file called soong.environment.used is written
270// containing the current value of all used environment variables. The next
271// time soong_ui is run, it checks whether any environment variables that was
272// used had changed and if so, it deletes soong.environment.used to cause a
273// rebuild.
274//
275// The dependency of build.ninja on soong.environment.used is declared in
276// build.ninja.d
277func parseAvailableEnv() map[string]string {
278 if availableEnvFile == "" {
279 fmt.Fprintf(os.Stderr, "--available_env not set\n")
280 os.Exit(1)
281 }
282
283 result, err := shared.EnvFromFile(shared.JoinPath(topDir, availableEnvFile))
284 if err != nil {
285 fmt.Fprintf(os.Stderr, "error reading available environment file '%s': %s\n", availableEnvFile, err)
286 os.Exit(1)
287 }
288
289 return result
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200290}
291
Colin Cross3f40fa42015-01-30 17:27:36 -0800292func main() {
293 flag.Parse()
294
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100295 shared.ReexecWithDelveMaybe(delveListen, delvePath)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100296 android.InitSandbox(topDir)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100297
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200298 availableEnv := parseAvailableEnv()
Lukacs T. Berki53b2f362021-04-12 14:04:24 +0200299
Lukacs T. Berkid6cee7e2021-09-01 16:25:51 +0200300 configuration := newConfig(cmdlineArgs, soongOutDir, availableEnv)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100301 extraNinjaDeps := []string{
302 configuration.ProductVariablesFileName,
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200303 usedEnvFile,
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100304 }
Colin Crossaa812d12019-06-19 13:33:24 -0700305
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100306 if configuration.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
307 configuration.SetAllowMissingDependencies()
308 }
309
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100310 if shared.IsDebugging() {
Colin Crossaa812d12019-06-19 13:33:24 -0700311 // Add a non-existent file to the dependencies so that soong_build will rerun when the debugger is
312 // enabled even if it completed successfully.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200313 extraNinjaDeps = append(extraNinjaDeps, filepath.Join(configuration.SoongOutDir(), "always_rerun_for_delve"))
Colin Crossaa812d12019-06-19 13:33:24 -0700314 }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500315
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200316 if docFile != "" {
317 // We don't write an used variables file when generating documentation
318 // because that is done from within the actual builds as a Ninja action and
319 // thus it would overwrite the actual used variables file so this is
320 // special-cased.
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200321 // TODO: Fix this by not passing --used_env to the soong_docs invocation
Lukacs T. Berki6124c9b2021-04-15 15:06:40 +0200322 runSoongDocs(configuration)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200323 return
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400324 }
Jingwen Chen4133ce62020-12-02 04:34:15 -0500325
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200326 finalOutputFile := doChosenActivity(configuration, extraNinjaDeps)
327 writeUsedEnvironmentFile(configuration, finalOutputFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100328}
329
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200330func writeUsedEnvironmentFile(configuration android.Config, finalOutputFile string) {
331 if usedEnvFile == "" {
332 return
333 }
334
335 path := shared.JoinPath(topDir, usedEnvFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100336 data, err := shared.EnvFileContents(configuration.EnvDeps())
337 if err != nil {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200338 fmt.Fprintf(os.Stderr, "error writing used environment file '%s': %s\n", usedEnvFile, err)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100339 os.Exit(1)
340 }
341
342 err = ioutil.WriteFile(path, data, 0666)
343 if err != nil {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200344 fmt.Fprintf(os.Stderr, "error writing used environment file '%s': %s\n", usedEnvFile, err)
Lukacs T. Berkic99c9472021-03-24 10:50:06 +0100345 os.Exit(1)
346 }
347
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200348 // Touch the output file so that it's not older than the file we just
Lukacs T. Berkic99c9472021-03-24 10:50:06 +0100349 // wrote. We can't write the environment file earlier because one an access
350 // new environment variables while writing it.
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200351 touch(shared.JoinPath(topDir, finalOutputFile))
Colin Cross3f40fa42015-01-30 17:27:36 -0800352}
Jingwen Chen5ba7e472020-07-15 10:06:41 +0000353
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200354func touch(path string) {
355 f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
356 if err != nil {
357 fmt.Fprintf(os.Stderr, "Error touching '%s': %s\n", path, err)
358 os.Exit(1)
359 }
360
361 err = f.Close()
362 if err != nil {
363 fmt.Fprintf(os.Stderr, "Error touching '%s': %s\n", path, err)
364 os.Exit(1)
365 }
366
367 currentTime := time.Now().Local()
368 err = os.Chtimes(path, currentTime, currentTime)
369 if err != nil {
370 fmt.Fprintf(os.Stderr, "error touching '%s': %s\n", path, err)
371 os.Exit(1)
372 }
373}
374
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400375// Find BUILD files in the srcDir which...
376//
377// - are not on the allow list (android/bazel.go#ShouldKeepExistingBuildFileForDir())
378//
379// - won't be overwritten by corresponding bp2build generated files
380//
381// 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 -0400382func getPathsToIgnoredBuildFiles(topDir string, generatedRoot string, srcDirBazelFiles []string) []string {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400383 paths := make([]string, 0)
384
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400385 for _, srcDirBazelFileRelativePath := range srcDirBazelFiles {
386 srcDirBazelFileFullPath := shared.JoinPath(topDir, srcDirBazelFileRelativePath)
387 fileInfo, err := os.Stat(srcDirBazelFileFullPath)
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400388 if err != nil {
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400389 // Warn about error, but continue trying to check files
390 fmt.Fprintf(os.Stderr, "WARNING: Error accessing path '%s', err: %s\n", srcDirBazelFileFullPath, err)
391 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400392 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400393 if fileInfo.IsDir() {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400394 // Don't ignore entire directories
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400395 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400396 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400397 if !(fileInfo.Name() == "BUILD" || fileInfo.Name() == "BUILD.bazel") {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400398 // Don't ignore this file - it is not a build file
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400399 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400400 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400401 srcDirBazelFileDir := filepath.Dir(srcDirBazelFileRelativePath)
402 if android.ShouldKeepExistingBuildFileForDir(srcDirBazelFileDir) {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400403 // Don't ignore this existing build file
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400404 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400405 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400406 correspondingBp2BuildFile := shared.JoinPath(topDir, generatedRoot, srcDirBazelFileRelativePath)
407 if _, err := os.Stat(correspondingBp2BuildFile); err == nil {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400408 // If bp2build generated an alternate BUILD file, don't exclude this workspace path
409 // BUILD file clash resolution happens later in the symlink forest creation
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 fmt.Fprintf(os.Stderr, "Ignoring existing BUILD file: %s\n", srcDirBazelFileRelativePath)
413 paths = append(paths, srcDirBazelFileRelativePath)
414 }
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400415
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400416 return paths
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400417}
418
419// Returns temporary symlink forest excludes necessary for bazel build //external/... (and bazel build //frameworks/...) to work
420func getTemporaryExcludes() []string {
421 excludes := make([]string, 0)
422
423 // FIXME: 'autotest_lib' is a symlink back to external/autotest, and this causes an infinite symlink expansion error for Bazel
424 excludes = append(excludes, "external/autotest/venv/autotest_lib")
425
426 // FIXME: The external/google-fruit/extras/bazel_root/third_party/fruit dir is poison
427 // It contains several symlinks back to real source dirs, and those source dirs contain BUILD files we want to ignore
428 excludes = append(excludes, "external/google-fruit/extras/bazel_root/third_party/fruit")
429
430 // FIXME: 'frameworks/compile/slang' has a filegroup error due to an escaping issue
431 excludes = append(excludes, "frameworks/compile/slang")
432
433 return excludes
434}
435
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400436// Read the bazel.list file that the Soong Finder already dumped earlier (hopefully)
437// It contains the locations of BUILD files, BUILD.bazel files, etc. in the source dir
438func getExistingBazelRelatedFiles(topDir string) ([]string, error) {
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200439 bazelFinderFile := filepath.Join(filepath.Dir(cmdlineArgs.ModuleListFile), "bazel.list")
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400440 if !filepath.IsAbs(bazelFinderFile) {
441 // Assume this was a relative path under topDir
442 bazelFinderFile = filepath.Join(topDir, bazelFinderFile)
443 }
444 data, err := ioutil.ReadFile(bazelFinderFile)
445 if err != nil {
446 return nil, err
447 }
448 files := strings.Split(strings.TrimSpace(string(data)), "\n")
449 return files, nil
450}
451
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500452// Run Soong in the bp2build mode. This creates a standalone context that registers
453// an alternate pipeline of mutators and singletons specifically for generating
454// Bazel BUILD files instead of Ninja files.
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200455func runBp2Build(configuration android.Config, extraNinjaDeps []string) {
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500456 // Register an alternate set of singletons and mutators for bazel
457 // conversion for Bazel conversion.
458 bp2buildCtx := android.NewContext(configuration)
Jingwen Cheneb76c432021-01-28 08:22:12 -0500459
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200460 // Propagate "allow misssing dependencies" bit. This is normally set in
461 // newContext(), but we create bp2buildCtx without calling that method.
462 bp2buildCtx.SetAllowMissingDependencies(configuration.AllowMissingDependencies())
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500463 bp2buildCtx.SetNameInterface(newNameResolver(configuration))
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200464 bp2buildCtx.RegisterForBazelConversion()
Jingwen Cheneb76c432021-01-28 08:22:12 -0500465
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500466 // The bp2build process is a purely functional process that only depends on
467 // Android.bp files. It must not depend on the values of per-build product
468 // configurations or variables, since those will generate different BUILD
469 // files based on how the user has configured their tree.
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200470 bp2buildCtx.SetModuleListFile(cmdlineArgs.ModuleListFile)
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200471 modulePaths, err := bp2buildCtx.ListModulePaths(".")
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500472 if err != nil {
473 panic(err)
474 }
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500475
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100476 extraNinjaDeps = append(extraNinjaDeps, modulePaths...)
477
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200478 // No need to generate Ninja build rules/statements from Modules and Singletons.
479 configuration.SetStopBefore(bootstrap.StopBeforePrepareBuildActions)
480
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500481 // Run the loading and analysis pipeline to prepare the graph of regular
482 // Modules parsed from Android.bp files, and the BazelTargetModules mapped
483 // from the regular Modules.
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200484 blueprintArgs := cmdlineArgs
Lukacs T. Berki6124c9b2021-04-15 15:06:40 +0200485 ninjaDeps := bootstrap.RunBlueprint(blueprintArgs, bp2buildCtx.Context, configuration)
486 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200487
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200488 globListFiles := writeBuildGlobsNinjaFile(bp2buildCtx.SrcDir(), configuration.SoongOutDir(), bp2buildCtx.Globs, configuration)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200489 ninjaDeps = append(ninjaDeps, globListFiles...)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200490
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200491 // Run the code-generation phase to convert BazelTargetModules to BUILD files
492 // and print conversion metrics to the user.
493 codegenContext := bp2build.NewCodegenContext(configuration, *bp2buildCtx, bp2build.Bp2Build)
494 metrics := bp2build.Codegen(codegenContext)
495
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200496 generatedRoot := shared.JoinPath(configuration.SoongOutDir(), "bp2build")
497 workspaceRoot := shared.JoinPath(configuration.SoongOutDir(), "workspace")
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200498
499 excludes := []string{
500 "bazel-bin",
501 "bazel-genfiles",
502 "bazel-out",
503 "bazel-testlogs",
504 "bazel-" + filepath.Base(topDir),
505 }
506
Lukacs T. Berkib078ade2021-08-31 10:42:08 +0200507 if cmdlineArgs.OutDir[0] != '/' {
508 excludes = append(excludes, cmdlineArgs.OutDir)
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200509 }
510
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400511 existingBazelRelatedFiles, err := getExistingBazelRelatedFiles(topDir)
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400512 if err != nil {
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400513 fmt.Fprintf(os.Stderr, "Error determining existing Bazel-related files: %s\n", err)
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400514 os.Exit(1)
515 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400516
517 pathsToIgnoredBuildFiles := getPathsToIgnoredBuildFiles(topDir, generatedRoot, existingBazelRelatedFiles)
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400518 excludes = append(excludes, pathsToIgnoredBuildFiles...)
519
520 excludes = append(excludes, getTemporaryExcludes()...)
521
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200522 symlinkForestDeps := bp2build.PlantSymlinkForest(
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200523 topDir, workspaceRoot, generatedRoot, ".", excludes)
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200524
525 // Only report metrics when in bp2build mode. The metrics aren't relevant
526 // for queryview, since that's a total repo-wide conversion and there's a
527 // 1:1 mapping for each module.
528 metrics.Print()
529
530 ninjaDeps = append(ninjaDeps, codegenContext.AdditionalNinjaDeps()...)
531 ninjaDeps = append(ninjaDeps, symlinkForestDeps...)
532
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200533 writeDepFile(bp2buildMarker, ninjaDeps)
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500534
Jingwen Chen4fabaf52021-05-25 02:40:29 +0000535 // Create an empty bp2build marker file.
536 touch(shared.JoinPath(topDir, bp2buildMarker))
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500537}