blob: ce20ec8893ed25d9f7850f96be4359ea6b52bcd9 [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 Crosscb33a002021-04-12 22:25:17 -070028
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"
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
41 delveListen string
42 delvePath string
43
Jingwen Chen50f93d22020-11-05 07:42:11 -050044 docFile string
45 bazelQueryViewDir string
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020046 bp2buildMarker string
Lukacs T. Berkif9008072021-08-16 15:24:48 +020047
48 cmdlineArgs bootstrap.Args
Colin Crosse87040b2017-12-11 15:52:26 -080049)
50
51func init() {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020052 // Flags that make sense in every mode
Lukacs T. Berki7690c092021-02-26 14:27:36 +010053 flag.StringVar(&topDir, "top", "", "Top directory of the Android source tree")
54 flag.StringVar(&outDir, "out", "", "Soong output directory (usually $TOP/out/soong)")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020055 flag.StringVar(&availableEnvFile, "available_env", "", "File containing available environment variables")
56 flag.StringVar(&usedEnvFile, "used_env", "", "File containing used environment variables")
57
58 // Debug flags
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +010059 flag.StringVar(&delveListen, "delve_listen", "", "Delve port to listen on for debugging")
60 flag.StringVar(&delvePath, "delve_path", "", "Path to Delve. Only used if --delve_listen is set")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020061
62 // Flags representing various modes soong_build can run in
Colin Crosse87040b2017-12-11 15:52:26 -080063 flag.StringVar(&docFile, "soong_docs", "", "build documentation file to output")
Lukacs T. Berki47a9d0c2021-03-08 16:34:09 +010064 flag.StringVar(&bazelQueryViewDir, "bazel_queryview_dir", "", "path to the bazel queryview directory relative to --top")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020065 flag.StringVar(&bp2buildMarker, "bp2build_marker", "", "If set, run bp2build, touch the specified marker file then exit")
Lukacs T. Berkif9008072021-08-16 15:24:48 +020066
67 flag.StringVar(&cmdlineArgs.OutFile, "o", "build.ninja", "the Ninja file to output")
68 flag.StringVar(&cmdlineArgs.GlobFile, "globFile", "build-globs.ninja", "the Ninja file of globs to output")
69 flag.StringVar(&cmdlineArgs.GlobListDir, "globListDir", "", "the directory containing the glob list files")
70 flag.StringVar(&cmdlineArgs.BuildDir, "b", ".", "the build output directory")
71 flag.StringVar(&cmdlineArgs.NinjaBuildDir, "n", "", "the ninja builddir directory")
72 flag.StringVar(&cmdlineArgs.DepFile, "d", "", "the dependency file to output")
73 flag.StringVar(&cmdlineArgs.Cpuprofile, "cpuprofile", "", "write cpu profile to file")
74 flag.StringVar(&cmdlineArgs.TraceFile, "trace", "", "write trace to file")
75 flag.StringVar(&cmdlineArgs.Memprofile, "memprofile", "", "write memory profile to file")
76 flag.BoolVar(&cmdlineArgs.NoGC, "nogc", false, "turn off GC for debugging")
77 flag.BoolVar(&cmdlineArgs.RunGoTests, "t", false, "build and run go tests during bootstrap")
78 flag.BoolVar(&cmdlineArgs.UseValidations, "use-validations", false, "use validations to depend on go tests")
79 flag.StringVar(&cmdlineArgs.ModuleListFile, "l", "", "file that lists filepaths to parse")
80 flag.BoolVar(&cmdlineArgs.EmptyNinjaFile, "empty-ninja-file", false, "write out a 0-byte ninja file")
Colin Crosse87040b2017-12-11 15:52:26 -080081}
82
Jeff Gaston088e29e2017-11-29 16:47:17 -080083func newNameResolver(config android.Config) *android.NameResolver {
84 namespacePathsToExport := make(map[string]bool)
85
Dan Willemsen3fb1fae2018-03-12 15:30:26 -070086 for _, namespaceName := range config.ExportedNamespaces() {
Jeff Gaston088e29e2017-11-29 16:47:17 -080087 namespacePathsToExport[namespaceName] = true
88 }
89
90 namespacePathsToExport["."] = true // always export the root namespace
91
92 exportFilter := func(namespace *android.Namespace) bool {
93 return namespacePathsToExport[namespace.Path]
94 }
95
96 return android.NewNameResolver(exportFilter)
97}
98
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +020099func newContext(configuration android.Config, prepareBuildActions bool) *android.Context {
Colin Crossae8600b2020-10-29 17:09:13 -0700100 ctx := android.NewContext(configuration)
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500101 ctx.Register()
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200102 if !prepareBuildActions {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400103 configuration.SetStopBefore(bootstrap.StopBeforePrepareBuildActions)
104 }
105 ctx.SetNameInterface(newNameResolver(configuration))
106 ctx.SetAllowMissingDependencies(configuration.AllowMissingDependencies())
107 return ctx
108}
109
Lukacs T. Berki53b2f362021-04-12 14:04:24 +0200110func newConfig(srcDir, outDir string, availableEnv map[string]string) android.Config {
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200111 configuration, err := android.NewConfig(srcDir, outDir, cmdlineArgs.ModuleListFile, availableEnv)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400112 if err != nil {
113 fmt.Fprintf(os.Stderr, "%s", err)
114 os.Exit(1)
115 }
116 return configuration
117}
118
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200119// Bazel-enabled mode. Soong runs in two passes.
120// First pass: Analyze the build tree, but only store all bazel commands
121// needed to correctly evaluate the tree in the second pass.
122// TODO(cparsons): Don't output any ninja file, as the second pass will overwrite
123// the incorrect results from the first pass, and file I/O is expensive.
124func runMixedModeBuild(configuration android.Config, firstCtx *android.Context, extraNinjaDeps []string) {
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200125 var firstArgs, secondArgs bootstrap.Args
126
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200127 firstArgs = cmdlineArgs
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200128 configuration.SetStopBefore(bootstrap.StopBeforeWriteNinja)
Lukacs T. Berki6124c9b2021-04-15 15:06:40 +0200129 bootstrap.RunBlueprint(firstArgs, firstCtx.Context, configuration)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200130
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200131 // Invoke bazel commands and save results for second pass.
132 if err := configuration.BazelContext.InvokeBazel(); err != nil {
133 fmt.Fprintf(os.Stderr, "%s", err)
134 os.Exit(1)
135 }
136 // Second pass: Full analysis, using the bazel command results. Output ninja file.
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200137 secondConfig, err := android.ConfigForAdditionalRun(configuration)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200138 if err != nil {
139 fmt.Fprintf(os.Stderr, "%s", err)
140 os.Exit(1)
141 }
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200142 secondCtx := newContext(secondConfig, true)
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200143 secondArgs = cmdlineArgs
Lukacs T. Berki6124c9b2021-04-15 15:06:40 +0200144 ninjaDeps := bootstrap.RunBlueprint(secondArgs, secondCtx.Context, secondConfig)
145 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200146 err = deptools.WriteDepFile(shared.JoinPath(topDir, secondArgs.DepFile), secondArgs.OutFile, ninjaDeps)
147 if err != nil {
148 fmt.Fprintf(os.Stderr, "Error writing depfile '%s': %s\n", secondArgs.DepFile, err)
149 os.Exit(1)
150 }
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200151}
152
153// Run the code-generation phase to convert BazelTargetModules to BUILD files.
154func runQueryView(configuration android.Config, ctx *android.Context) {
155 codegenContext := bp2build.NewCodegenContext(configuration, *ctx, bp2build.QueryView)
156 absoluteQueryViewDir := shared.JoinPath(topDir, bazelQueryViewDir)
157 if err := createBazelQueryView(codegenContext, absoluteQueryViewDir); err != nil {
158 fmt.Fprintf(os.Stderr, "%s", err)
159 os.Exit(1)
160 }
161}
162
Lukacs T. Berki6124c9b2021-04-15 15:06:40 +0200163func runSoongDocs(configuration android.Config) {
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200164 ctx := newContext(configuration, false)
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200165 soongDocsArgs := cmdlineArgs
Lukacs T. Berki6124c9b2021-04-15 15:06:40 +0200166 bootstrap.RunBlueprint(soongDocsArgs, ctx.Context, configuration)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200167 if err := writeDocs(ctx, configuration, docFile); err != nil {
168 fmt.Fprintf(os.Stderr, "%s", err)
169 os.Exit(1)
170 }
171}
172
173func writeMetrics(configuration android.Config) {
Lukacs T. Berki745380c2021-04-12 12:07:44 +0200174 metricsFile := filepath.Join(configuration.BuildDir(), "soong_build_metrics.pb")
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200175 err := android.WriteMetrics(configuration, metricsFile)
176 if err != nil {
177 fmt.Fprintf(os.Stderr, "error writing soong_build metrics %s: %s", metricsFile, err)
178 os.Exit(1)
179 }
180}
181
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200182func writeJsonModuleGraph(configuration android.Config, ctx *android.Context, path string, extraNinjaDeps []string) {
183 f, err := os.Create(path)
184 if err != nil {
185 fmt.Fprintf(os.Stderr, "%s", err)
186 os.Exit(1)
187 }
188
189 defer f.Close()
190 ctx.Context.PrintJSONGraph(f)
191 writeFakeNinjaFile(extraNinjaDeps, configuration.BuildDir())
192}
193
Jingwen Chen4fabaf52021-05-25 02:40:29 +0000194// doChosenActivity runs Soong for a specific activity, like bp2build, queryview
195// or the actual Soong build for the build.ninja file. Returns the top level
196// output file of the specific activity.
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200197func doChosenActivity(configuration android.Config, extraNinjaDeps []string) string {
Chris Parsonsec1a3dc2021-04-20 15:32:07 -0400198 bazelConversionRequested := bp2buildMarker != ""
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200199 mixedModeBuild := configuration.BazelContext.BazelEnabled()
200 generateQueryView := bazelQueryViewDir != ""
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200201 jsonModuleFile := configuration.Getenv("SOONG_DUMP_JSON_MODULE_GRAPH")
202
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200203 blueprintArgs := cmdlineArgs
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200204 prepareBuildActions := !generateQueryView && jsonModuleFile == ""
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200205 if bazelConversionRequested {
206 // Run the alternate pipeline of bp2build mutators and singleton to convert
207 // Blueprint to BUILD files before everything else.
208 runBp2Build(configuration, extraNinjaDeps)
Jingwen Chen4fabaf52021-05-25 02:40:29 +0000209 return bp2buildMarker
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200210 }
211
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200212 ctx := newContext(configuration, prepareBuildActions)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200213 if mixedModeBuild {
214 runMixedModeBuild(configuration, ctx, extraNinjaDeps)
215 } else {
Lukacs T. Berki6124c9b2021-04-15 15:06:40 +0200216 ninjaDeps := bootstrap.RunBlueprint(blueprintArgs, ctx.Context, configuration)
217 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200218 err := deptools.WriteDepFile(shared.JoinPath(topDir, blueprintArgs.DepFile), blueprintArgs.OutFile, ninjaDeps)
219 if err != nil {
220 fmt.Fprintf(os.Stderr, "Error writing depfile '%s': %s\n", blueprintArgs.DepFile, err)
221 os.Exit(1)
222 }
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200223 }
224
225 // Convert the Soong module graph into Bazel BUILD files.
226 if generateQueryView {
227 runQueryView(configuration, ctx)
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200228 return cmdlineArgs.OutFile // TODO: This is a lie
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200229 }
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200230
231 if jsonModuleFile != "" {
232 writeJsonModuleGraph(configuration, ctx, jsonModuleFile, extraNinjaDeps)
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200233 return cmdlineArgs.OutFile // TODO: This is a lie
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200234 }
235
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200236 writeMetrics(configuration)
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200237 return cmdlineArgs.OutFile
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200238}
239
240// soong_ui dumps the available environment variables to
241// soong.environment.available . Then soong_build itself is run with an empty
242// environment so that the only way environment variables can be accessed is
243// using Config, which tracks access to them.
244
245// At the end of the build, a file called soong.environment.used is written
246// containing the current value of all used environment variables. The next
247// time soong_ui is run, it checks whether any environment variables that was
248// used had changed and if so, it deletes soong.environment.used to cause a
249// rebuild.
250//
251// The dependency of build.ninja on soong.environment.used is declared in
252// build.ninja.d
253func parseAvailableEnv() map[string]string {
254 if availableEnvFile == "" {
255 fmt.Fprintf(os.Stderr, "--available_env not set\n")
256 os.Exit(1)
257 }
258
259 result, err := shared.EnvFromFile(shared.JoinPath(topDir, availableEnvFile))
260 if err != nil {
261 fmt.Fprintf(os.Stderr, "error reading available environment file '%s': %s\n", availableEnvFile, err)
262 os.Exit(1)
263 }
264
265 return result
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200266}
267
Colin Cross3f40fa42015-01-30 17:27:36 -0800268func main() {
269 flag.Parse()
270
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100271 shared.ReexecWithDelveMaybe(delveListen, delvePath)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100272 android.InitSandbox(topDir)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100273
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200274 availableEnv := parseAvailableEnv()
Lukacs T. Berki53b2f362021-04-12 14:04:24 +0200275
Colin Cross3f40fa42015-01-30 17:27:36 -0800276 // The top-level Blueprints file is passed as the first argument.
277 srcDir := filepath.Dir(flag.Arg(0))
Lukacs T. Berki53b2f362021-04-12 14:04:24 +0200278 configuration := newConfig(srcDir, outDir, availableEnv)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100279 extraNinjaDeps := []string{
280 configuration.ProductVariablesFileName,
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200281 usedEnvFile,
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100282 }
Colin Crossaa812d12019-06-19 13:33:24 -0700283
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100284 if configuration.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
285 configuration.SetAllowMissingDependencies()
286 }
287
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100288 if shared.IsDebugging() {
Colin Crossaa812d12019-06-19 13:33:24 -0700289 // Add a non-existent file to the dependencies so that soong_build will rerun when the debugger is
290 // enabled even if it completed successfully.
291 extraNinjaDeps = append(extraNinjaDeps, filepath.Join(configuration.BuildDir(), "always_rerun_for_delve"))
292 }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500293
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200294 if docFile != "" {
295 // We don't write an used variables file when generating documentation
296 // because that is done from within the actual builds as a Ninja action and
297 // thus it would overwrite the actual used variables file so this is
298 // special-cased.
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200299 // TODO: Fix this by not passing --used_env to the soong_docs invocation
Lukacs T. Berki6124c9b2021-04-15 15:06:40 +0200300 runSoongDocs(configuration)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200301 return
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400302 }
Jingwen Chen4133ce62020-12-02 04:34:15 -0500303
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200304 finalOutputFile := doChosenActivity(configuration, extraNinjaDeps)
305 writeUsedEnvironmentFile(configuration, finalOutputFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100306}
307
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200308func writeUsedEnvironmentFile(configuration android.Config, finalOutputFile string) {
309 if usedEnvFile == "" {
310 return
311 }
312
313 path := shared.JoinPath(topDir, usedEnvFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100314 data, err := shared.EnvFileContents(configuration.EnvDeps())
315 if err != nil {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200316 fmt.Fprintf(os.Stderr, "error writing used environment file '%s': %s\n", usedEnvFile, err)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100317 os.Exit(1)
318 }
319
320 err = ioutil.WriteFile(path, data, 0666)
321 if err != nil {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200322 fmt.Fprintf(os.Stderr, "error writing used environment file '%s': %s\n", usedEnvFile, err)
Lukacs T. Berkic99c9472021-03-24 10:50:06 +0100323 os.Exit(1)
324 }
325
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200326 // Touch the output file so that it's not older than the file we just
Lukacs T. Berkic99c9472021-03-24 10:50:06 +0100327 // wrote. We can't write the environment file earlier because one an access
328 // new environment variables while writing it.
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200329 touch(shared.JoinPath(topDir, finalOutputFile))
Colin Cross3f40fa42015-01-30 17:27:36 -0800330}
Jingwen Chen5ba7e472020-07-15 10:06:41 +0000331
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200332// Workarounds to support running bp2build in a clean AOSP checkout with no
333// prior builds, and exiting early as soon as the BUILD files get generated,
334// therefore not creating build.ninja files that soong_ui and callers of
335// soong_build expects.
336//
337// These files are: build.ninja and build.ninja.d. Since Kati hasn't been
338// ran as well, and `nothing` is defined in a .mk file, there isn't a ninja
339// target called `nothing`, so we manually create it here.
340func writeFakeNinjaFile(extraNinjaDeps []string, buildDir string) {
341 extraNinjaDepsString := strings.Join(extraNinjaDeps, " \\\n ")
342
343 ninjaFileName := "build.ninja"
344 ninjaFile := shared.JoinPath(topDir, buildDir, ninjaFileName)
Jingwen Chen4fabaf52021-05-25 02:40:29 +0000345 ninjaFileD := shared.JoinPath(topDir, buildDir, ninjaFileName+".d")
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200346 // A workaround to create the 'nothing' ninja target so `m nothing` works,
347 // since bp2build runs without Kati, and the 'nothing' target is declared in
348 // a Makefile.
349 ioutil.WriteFile(ninjaFile, []byte("build nothing: phony\n phony_output = true\n"), 0666)
350 ioutil.WriteFile(ninjaFileD,
Jingwen Chen4fabaf52021-05-25 02:40:29 +0000351 []byte(fmt.Sprintf("%s: \\\n %s\n", ninjaFile, extraNinjaDepsString)),
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200352 0666)
353}
354
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200355func touch(path string) {
356 f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
357 if err != nil {
358 fmt.Fprintf(os.Stderr, "Error touching '%s': %s\n", path, err)
359 os.Exit(1)
360 }
361
362 err = f.Close()
363 if err != nil {
364 fmt.Fprintf(os.Stderr, "Error touching '%s': %s\n", path, err)
365 os.Exit(1)
366 }
367
368 currentTime := time.Now().Local()
369 err = os.Chtimes(path, currentTime, currentTime)
370 if err != nil {
371 fmt.Fprintf(os.Stderr, "error touching '%s': %s\n", path, err)
372 os.Exit(1)
373 }
374}
375
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400376// Find BUILD files in the srcDir which...
377//
378// - are not on the allow list (android/bazel.go#ShouldKeepExistingBuildFileForDir())
379//
380// - won't be overwritten by corresponding bp2build generated files
381//
382// 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 -0400383func getPathsToIgnoredBuildFiles(topDir string, generatedRoot string, srcDirBazelFiles []string) []string {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400384 paths := make([]string, 0)
385
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400386 for _, srcDirBazelFileRelativePath := range srcDirBazelFiles {
387 srcDirBazelFileFullPath := shared.JoinPath(topDir, srcDirBazelFileRelativePath)
388 fileInfo, err := os.Stat(srcDirBazelFileFullPath)
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400389 if err != nil {
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400390 // Warn about error, but continue trying to check files
391 fmt.Fprintf(os.Stderr, "WARNING: Error accessing path '%s', err: %s\n", srcDirBazelFileFullPath, err)
392 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400393 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400394 if fileInfo.IsDir() {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400395 // Don't ignore entire directories
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400396 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400397 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400398 if !(fileInfo.Name() == "BUILD" || fileInfo.Name() == "BUILD.bazel") {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400399 // Don't ignore this file - it is not a build file
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400400 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400401 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400402 srcDirBazelFileDir := filepath.Dir(srcDirBazelFileRelativePath)
403 if android.ShouldKeepExistingBuildFileForDir(srcDirBazelFileDir) {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400404 // Don't ignore this existing build file
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400405 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400406 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400407 correspondingBp2BuildFile := shared.JoinPath(topDir, generatedRoot, srcDirBazelFileRelativePath)
408 if _, err := os.Stat(correspondingBp2BuildFile); err == nil {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400409 // If bp2build generated an alternate BUILD file, don't exclude this workspace path
410 // BUILD file clash resolution happens later in the symlink forest creation
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400411 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400412 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400413 fmt.Fprintf(os.Stderr, "Ignoring existing BUILD file: %s\n", srcDirBazelFileRelativePath)
414 paths = append(paths, srcDirBazelFileRelativePath)
415 }
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400416
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400417 return paths
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400418}
419
420// Returns temporary symlink forest excludes necessary for bazel build //external/... (and bazel build //frameworks/...) to work
421func getTemporaryExcludes() []string {
422 excludes := make([]string, 0)
423
424 // FIXME: 'autotest_lib' is a symlink back to external/autotest, and this causes an infinite symlink expansion error for Bazel
425 excludes = append(excludes, "external/autotest/venv/autotest_lib")
426
427 // FIXME: The external/google-fruit/extras/bazel_root/third_party/fruit dir is poison
428 // It contains several symlinks back to real source dirs, and those source dirs contain BUILD files we want to ignore
429 excludes = append(excludes, "external/google-fruit/extras/bazel_root/third_party/fruit")
430
431 // FIXME: 'frameworks/compile/slang' has a filegroup error due to an escaping issue
432 excludes = append(excludes, "frameworks/compile/slang")
433
434 return excludes
435}
436
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400437// Read the bazel.list file that the Soong Finder already dumped earlier (hopefully)
438// It contains the locations of BUILD files, BUILD.bazel files, etc. in the source dir
439func getExistingBazelRelatedFiles(topDir string) ([]string, error) {
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200440 bazelFinderFile := filepath.Join(filepath.Dir(cmdlineArgs.ModuleListFile), "bazel.list")
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400441 if !filepath.IsAbs(bazelFinderFile) {
442 // Assume this was a relative path under topDir
443 bazelFinderFile = filepath.Join(topDir, bazelFinderFile)
444 }
445 data, err := ioutil.ReadFile(bazelFinderFile)
446 if err != nil {
447 return nil, err
448 }
449 files := strings.Split(strings.TrimSpace(string(data)), "\n")
450 return files, nil
451}
452
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500453// Run Soong in the bp2build mode. This creates a standalone context that registers
454// an alternate pipeline of mutators and singletons specifically for generating
455// Bazel BUILD files instead of Ninja files.
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200456func runBp2Build(configuration android.Config, extraNinjaDeps []string) {
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500457 // Register an alternate set of singletons and mutators for bazel
458 // conversion for Bazel conversion.
459 bp2buildCtx := android.NewContext(configuration)
Jingwen Cheneb76c432021-01-28 08:22:12 -0500460
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200461 // Propagate "allow misssing dependencies" bit. This is normally set in
462 // newContext(), but we create bp2buildCtx without calling that method.
463 bp2buildCtx.SetAllowMissingDependencies(configuration.AllowMissingDependencies())
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500464 bp2buildCtx.SetNameInterface(newNameResolver(configuration))
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200465 bp2buildCtx.RegisterForBazelConversion()
Jingwen Cheneb76c432021-01-28 08:22:12 -0500466
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500467 // The bp2build process is a purely functional process that only depends on
468 // Android.bp files. It must not depend on the values of per-build product
469 // configurations or variables, since those will generate different BUILD
470 // files based on how the user has configured their tree.
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200471 bp2buildCtx.SetModuleListFile(cmdlineArgs.ModuleListFile)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200472 modulePaths, err := bp2buildCtx.ListModulePaths(configuration.SrcDir())
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500473 if err != nil {
474 panic(err)
475 }
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500476
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100477 extraNinjaDeps = append(extraNinjaDeps, modulePaths...)
478
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200479 // No need to generate Ninja build rules/statements from Modules and Singletons.
480 configuration.SetStopBefore(bootstrap.StopBeforePrepareBuildActions)
481
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500482 // Run the loading and analysis pipeline to prepare the graph of regular
483 // Modules parsed from Android.bp files, and the BazelTargetModules mapped
484 // from the regular Modules.
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200485 blueprintArgs := cmdlineArgs
Lukacs T. Berki6124c9b2021-04-15 15:06:40 +0200486 ninjaDeps := bootstrap.RunBlueprint(blueprintArgs, bp2buildCtx.Context, configuration)
487 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200488
Jingwen Chen53dfa402021-08-12 09:37:14 +0000489 // Generate out/soong/.bootstrap/build-globs.ninja with the actions to generate flattened globfiles
490 // containing the globs seen during bp2build conversion
491 if blueprintArgs.GlobFile != "" {
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200492 bootstrap.WriteBuildGlobsNinjaFile(blueprintArgs.GlobListDir, bp2buildCtx.Context, blueprintArgs, configuration)
Jingwen Chen53dfa402021-08-12 09:37:14 +0000493 }
494 // Add the depfile on the expanded globs in out/soong/.primary/globs
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200495 ninjaDeps = append(ninjaDeps, bootstrap.GlobFileListFiles(configuration, blueprintArgs.GlobListDir)...)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200496
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200497 // Run the code-generation phase to convert BazelTargetModules to BUILD files
498 // and print conversion metrics to the user.
499 codegenContext := bp2build.NewCodegenContext(configuration, *bp2buildCtx, bp2build.Bp2Build)
500 metrics := bp2build.Codegen(codegenContext)
501
502 generatedRoot := shared.JoinPath(configuration.BuildDir(), "bp2build")
503 workspaceRoot := shared.JoinPath(configuration.BuildDir(), "workspace")
504
505 excludes := []string{
506 "bazel-bin",
507 "bazel-genfiles",
508 "bazel-out",
509 "bazel-testlogs",
510 "bazel-" + filepath.Base(topDir),
511 }
512
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200513 if cmdlineArgs.NinjaBuildDir[0] != '/' {
514 excludes = append(excludes, cmdlineArgs.NinjaBuildDir)
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200515 }
516
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400517 existingBazelRelatedFiles, err := getExistingBazelRelatedFiles(topDir)
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400518 if err != nil {
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400519 fmt.Fprintf(os.Stderr, "Error determining existing Bazel-related files: %s\n", err)
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400520 os.Exit(1)
521 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400522
523 pathsToIgnoredBuildFiles := getPathsToIgnoredBuildFiles(topDir, generatedRoot, existingBazelRelatedFiles)
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400524 excludes = append(excludes, pathsToIgnoredBuildFiles...)
525
526 excludes = append(excludes, getTemporaryExcludes()...)
527
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200528 symlinkForestDeps := bp2build.PlantSymlinkForest(
529 topDir, workspaceRoot, generatedRoot, configuration.SrcDir(), excludes)
530
531 // Only report metrics when in bp2build mode. The metrics aren't relevant
532 // for queryview, since that's a total repo-wide conversion and there's a
533 // 1:1 mapping for each module.
534 metrics.Print()
535
536 ninjaDeps = append(ninjaDeps, codegenContext.AdditionalNinjaDeps()...)
537 ninjaDeps = append(ninjaDeps, symlinkForestDeps...)
538
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200539 depFile := bp2buildMarker + ".d"
540 err = deptools.WriteDepFile(shared.JoinPath(topDir, depFile), bp2buildMarker, ninjaDeps)
541 if err != nil {
542 fmt.Fprintf(os.Stderr, "Cannot write depfile '%s': %s\n", depFile, err)
543 os.Exit(1)
544 }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500545
Jingwen Chen4fabaf52021-05-25 02:40:29 +0000546 // Create an empty bp2build marker file.
547 touch(shared.JoinPath(topDir, bp2buildMarker))
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500548}