blob: 7a4cb29f9231ab06571615222e6c050f121257fa [file] [log] [blame]
Colin Cross3f40fa42015-01-30 17:27:36 -08001// Copyright 2015 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package main
16
17import (
18 "flag"
19 "fmt"
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +010020 "io/ioutil"
Colin Cross3f40fa42015-01-30 17:27:36 -080021 "os"
22 "path/filepath"
Jingwen Cheneb76c432021-01-28 08:22:12 -050023 "strings"
Lukacs T. Berkic99c9472021-03-24 10:50:06 +010024 "time"
Colin Cross3f40fa42015-01-30 17:27:36 -080025
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020026 "android/soong/bp2build"
Lukacs T. Berki7690c092021-02-26 14:27:36 +010027 "android/soong/shared"
Colin Cross70b40592015-03-23 12:57:34 -070028 "github.com/google/blueprint/bootstrap"
Colin Cross3f40fa42015-01-30 17:27:36 -080029
Colin Cross635c3b02016-05-18 15:37:25 -070030 "android/soong/android"
Colin Cross3f40fa42015-01-30 17:27:36 -080031)
32
Colin Crosse87040b2017-12-11 15:52:26 -080033var (
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020034 topDir string
35 outDir string
36 availableEnvFile string
37 usedEnvFile string
38
39 delveListen string
40 delvePath string
41
Jingwen Chen50f93d22020-11-05 07:42:11 -050042 docFile string
43 bazelQueryViewDir string
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020044 bp2buildMarker string
Colin Crosse87040b2017-12-11 15:52:26 -080045)
46
47func init() {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020048 // Flags that make sense in every mode
Lukacs T. Berki7690c092021-02-26 14:27:36 +010049 flag.StringVar(&topDir, "top", "", "Top directory of the Android source tree")
50 flag.StringVar(&outDir, "out", "", "Soong output directory (usually $TOP/out/soong)")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020051 flag.StringVar(&availableEnvFile, "available_env", "", "File containing available environment variables")
52 flag.StringVar(&usedEnvFile, "used_env", "", "File containing used environment variables")
53
54 // Debug flags
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +010055 flag.StringVar(&delveListen, "delve_listen", "", "Delve port to listen on for debugging")
56 flag.StringVar(&delvePath, "delve_path", "", "Path to Delve. Only used if --delve_listen is set")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020057
58 // Flags representing various modes soong_build can run in
Colin Crosse87040b2017-12-11 15:52:26 -080059 flag.StringVar(&docFile, "soong_docs", "", "build documentation file to output")
Lukacs T. Berki47a9d0c2021-03-08 16:34:09 +010060 flag.StringVar(&bazelQueryViewDir, "bazel_queryview_dir", "", "path to the bazel queryview directory relative to --top")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020061 flag.StringVar(&bp2buildMarker, "bp2build_marker", "", "If set, run bp2build, touch the specified marker file then exit")
Colin Crosse87040b2017-12-11 15:52:26 -080062}
63
Jeff Gaston088e29e2017-11-29 16:47:17 -080064func newNameResolver(config android.Config) *android.NameResolver {
65 namespacePathsToExport := make(map[string]bool)
66
Dan Willemsen3fb1fae2018-03-12 15:30:26 -070067 for _, namespaceName := range config.ExportedNamespaces() {
Jeff Gaston088e29e2017-11-29 16:47:17 -080068 namespacePathsToExport[namespaceName] = true
69 }
70
71 namespacePathsToExport["."] = true // always export the root namespace
72
73 exportFilter := func(namespace *android.Namespace) bool {
74 return namespacePathsToExport[namespace.Path]
75 }
76
77 return android.NewNameResolver(exportFilter)
78}
79
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +020080func newContext(configuration android.Config, prepareBuildActions bool) *android.Context {
Colin Crossae8600b2020-10-29 17:09:13 -070081 ctx := android.NewContext(configuration)
Jingwen Chendaa54bc2020-12-14 02:58:54 -050082 ctx.Register()
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +020083 if !prepareBuildActions {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040084 configuration.SetStopBefore(bootstrap.StopBeforePrepareBuildActions)
85 }
86 ctx.SetNameInterface(newNameResolver(configuration))
87 ctx.SetAllowMissingDependencies(configuration.AllowMissingDependencies())
88 return ctx
89}
90
Lukacs T. Berki53b2f362021-04-12 14:04:24 +020091func newConfig(srcDir, outDir string, availableEnv map[string]string) android.Config {
92 configuration, err := android.NewConfig(srcDir, outDir, bootstrap.CmdlineModuleListFile(), availableEnv)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040093 if err != nil {
94 fmt.Fprintf(os.Stderr, "%s", err)
95 os.Exit(1)
96 }
97 return configuration
98}
99
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200100// Bazel-enabled mode. Soong runs in two passes.
101// First pass: Analyze the build tree, but only store all bazel commands
102// needed to correctly evaluate the tree in the second pass.
103// TODO(cparsons): Don't output any ninja file, as the second pass will overwrite
104// the incorrect results from the first pass, and file I/O is expensive.
105func runMixedModeBuild(configuration android.Config, firstCtx *android.Context, extraNinjaDeps []string) {
106 configuration.SetStopBefore(bootstrap.StopBeforeWriteNinja)
107 bootstrap.Main(firstCtx.Context, configuration, false, extraNinjaDeps...)
108 // Invoke bazel commands and save results for second pass.
109 if err := configuration.BazelContext.InvokeBazel(); err != nil {
110 fmt.Fprintf(os.Stderr, "%s", err)
111 os.Exit(1)
112 }
113 // Second pass: Full analysis, using the bazel command results. Output ninja file.
114 secondPassConfig, err := android.ConfigForAdditionalRun(configuration)
115 if err != nil {
116 fmt.Fprintf(os.Stderr, "%s", err)
117 os.Exit(1)
118 }
119 secondCtx := newContext(secondPassConfig, true)
120 bootstrap.Main(secondCtx.Context, secondPassConfig, false, extraNinjaDeps...)
121}
122
123// Run the code-generation phase to convert BazelTargetModules to BUILD files.
124func runQueryView(configuration android.Config, ctx *android.Context) {
125 codegenContext := bp2build.NewCodegenContext(configuration, *ctx, bp2build.QueryView)
126 absoluteQueryViewDir := shared.JoinPath(topDir, bazelQueryViewDir)
127 if err := createBazelQueryView(codegenContext, absoluteQueryViewDir); err != nil {
128 fmt.Fprintf(os.Stderr, "%s", err)
129 os.Exit(1)
130 }
131}
132
133func runSoongDocs(configuration android.Config, extraNinjaDeps []string) {
134 ctx := newContext(configuration, false)
135 bootstrap.Main(ctx.Context, configuration, false, extraNinjaDeps...)
136 if err := writeDocs(ctx, configuration, docFile); err != nil {
137 fmt.Fprintf(os.Stderr, "%s", err)
138 os.Exit(1)
139 }
140}
141
142func writeMetrics(configuration android.Config) {
Lukacs T. Berki745380c2021-04-12 12:07:44 +0200143 metricsFile := filepath.Join(configuration.BuildDir(), "soong_build_metrics.pb")
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200144 err := android.WriteMetrics(configuration, metricsFile)
145 if err != nil {
146 fmt.Fprintf(os.Stderr, "error writing soong_build metrics %s: %s", metricsFile, err)
147 os.Exit(1)
148 }
149}
150
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200151func writeJsonModuleGraph(configuration android.Config, ctx *android.Context, path string, extraNinjaDeps []string) {
152 f, err := os.Create(path)
153 if err != nil {
154 fmt.Fprintf(os.Stderr, "%s", err)
155 os.Exit(1)
156 }
157
158 defer f.Close()
159 ctx.Context.PrintJSONGraph(f)
160 writeFakeNinjaFile(extraNinjaDeps, configuration.BuildDir())
161}
162
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200163func doChosenActivity(configuration android.Config, extraNinjaDeps []string) string {
164 bazelConversionRequested := configuration.IsEnvTrue("GENERATE_BAZEL_FILES") || bp2buildMarker != ""
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200165 mixedModeBuild := configuration.BazelContext.BazelEnabled()
166 generateQueryView := bazelQueryViewDir != ""
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200167 jsonModuleFile := configuration.Getenv("SOONG_DUMP_JSON_MODULE_GRAPH")
168
169 prepareBuildActions := !generateQueryView && jsonModuleFile == ""
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200170
171 if bazelConversionRequested {
172 // Run the alternate pipeline of bp2build mutators and singleton to convert
173 // Blueprint to BUILD files before everything else.
174 runBp2Build(configuration, extraNinjaDeps)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200175 if bp2buildMarker != "" {
176 return bp2buildMarker
177 } else {
178 return bootstrap.CmdlineOutFile()
179 }
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200180 }
181
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200182 ctx := newContext(configuration, prepareBuildActions)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200183 if mixedModeBuild {
184 runMixedModeBuild(configuration, ctx, extraNinjaDeps)
185 } else {
186 bootstrap.Main(ctx.Context, configuration, false, extraNinjaDeps...)
187 }
188
189 // Convert the Soong module graph into Bazel BUILD files.
190 if generateQueryView {
191 runQueryView(configuration, ctx)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200192 return bootstrap.CmdlineOutFile() // TODO: This is a lie
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200193 }
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200194
195 if jsonModuleFile != "" {
196 writeJsonModuleGraph(configuration, ctx, jsonModuleFile, extraNinjaDeps)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200197 return bootstrap.CmdlineOutFile() // TODO: This is a lie
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200198 }
199
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200200 writeMetrics(configuration)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200201 return bootstrap.CmdlineOutFile()
202}
203
204// soong_ui dumps the available environment variables to
205// soong.environment.available . Then soong_build itself is run with an empty
206// environment so that the only way environment variables can be accessed is
207// using Config, which tracks access to them.
208
209// At the end of the build, a file called soong.environment.used is written
210// containing the current value of all used environment variables. The next
211// time soong_ui is run, it checks whether any environment variables that was
212// used had changed and if so, it deletes soong.environment.used to cause a
213// rebuild.
214//
215// The dependency of build.ninja on soong.environment.used is declared in
216// build.ninja.d
217func parseAvailableEnv() map[string]string {
218 if availableEnvFile == "" {
219 fmt.Fprintf(os.Stderr, "--available_env not set\n")
220 os.Exit(1)
221 }
222
223 result, err := shared.EnvFromFile(shared.JoinPath(topDir, availableEnvFile))
224 if err != nil {
225 fmt.Fprintf(os.Stderr, "error reading available environment file '%s': %s\n", availableEnvFile, err)
226 os.Exit(1)
227 }
228
229 return result
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200230}
231
Colin Cross3f40fa42015-01-30 17:27:36 -0800232func main() {
233 flag.Parse()
234
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100235 shared.ReexecWithDelveMaybe(delveListen, delvePath)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100236 android.InitSandbox(topDir)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100237
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200238 availableEnv := parseAvailableEnv()
Lukacs T. Berki53b2f362021-04-12 14:04:24 +0200239
Colin Cross3f40fa42015-01-30 17:27:36 -0800240 // The top-level Blueprints file is passed as the first argument.
241 srcDir := filepath.Dir(flag.Arg(0))
Lukacs T. Berki53b2f362021-04-12 14:04:24 +0200242 configuration := newConfig(srcDir, outDir, availableEnv)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100243 extraNinjaDeps := []string{
244 configuration.ProductVariablesFileName,
245 shared.JoinPath(outDir, "soong.environment.used"),
246 }
Colin Crossaa812d12019-06-19 13:33:24 -0700247
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100248 if configuration.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
249 configuration.SetAllowMissingDependencies()
250 }
251
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100252 if shared.IsDebugging() {
Colin Crossaa812d12019-06-19 13:33:24 -0700253 // Add a non-existent file to the dependencies so that soong_build will rerun when the debugger is
254 // enabled even if it completed successfully.
255 extraNinjaDeps = append(extraNinjaDeps, filepath.Join(configuration.BuildDir(), "always_rerun_for_delve"))
256 }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500257
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200258 if docFile != "" {
259 // We don't write an used variables file when generating documentation
260 // because that is done from within the actual builds as a Ninja action and
261 // thus it would overwrite the actual used variables file so this is
262 // special-cased.
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200263 // TODO: Fix this by not passing --used_env to the soong_docs invocation
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200264 runSoongDocs(configuration, extraNinjaDeps)
265 return
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400266 }
Jingwen Chen4133ce62020-12-02 04:34:15 -0500267
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200268 finalOutputFile := doChosenActivity(configuration, extraNinjaDeps)
269 writeUsedEnvironmentFile(configuration, finalOutputFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100270}
271
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200272func writeUsedEnvironmentFile(configuration android.Config, finalOutputFile string) {
273 if usedEnvFile == "" {
274 return
275 }
276
277 path := shared.JoinPath(topDir, usedEnvFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100278 data, err := shared.EnvFileContents(configuration.EnvDeps())
279 if err != nil {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200280 fmt.Fprintf(os.Stderr, "error writing used environment file '%s': %s\n", usedEnvFile, err)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100281 os.Exit(1)
282 }
283
284 err = ioutil.WriteFile(path, data, 0666)
285 if err != nil {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200286 fmt.Fprintf(os.Stderr, "error writing used environment file '%s': %s\n", usedEnvFile, err)
Lukacs T. Berkic99c9472021-03-24 10:50:06 +0100287 os.Exit(1)
288 }
289
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200290 // Touch the output file so that it's not older than the file we just
Lukacs T. Berkic99c9472021-03-24 10:50:06 +0100291 // wrote. We can't write the environment file earlier because one an access
292 // new environment variables while writing it.
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200293 touch(shared.JoinPath(topDir, finalOutputFile))
Colin Cross3f40fa42015-01-30 17:27:36 -0800294}
Jingwen Chen5ba7e472020-07-15 10:06:41 +0000295
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200296// Workarounds to support running bp2build in a clean AOSP checkout with no
297// prior builds, and exiting early as soon as the BUILD files get generated,
298// therefore not creating build.ninja files that soong_ui and callers of
299// soong_build expects.
300//
301// These files are: build.ninja and build.ninja.d. Since Kati hasn't been
302// ran as well, and `nothing` is defined in a .mk file, there isn't a ninja
303// target called `nothing`, so we manually create it here.
304func writeFakeNinjaFile(extraNinjaDeps []string, buildDir string) {
305 extraNinjaDepsString := strings.Join(extraNinjaDeps, " \\\n ")
306
307 ninjaFileName := "build.ninja"
308 ninjaFile := shared.JoinPath(topDir, buildDir, ninjaFileName)
309 ninjaFileD := shared.JoinPath(topDir, buildDir, ninjaFileName)
310 // A workaround to create the 'nothing' ninja target so `m nothing` works,
311 // since bp2build runs without Kati, and the 'nothing' target is declared in
312 // a Makefile.
313 ioutil.WriteFile(ninjaFile, []byte("build nothing: phony\n phony_output = true\n"), 0666)
314 ioutil.WriteFile(ninjaFileD,
315 []byte(fmt.Sprintf("%s: \\\n %s\n", ninjaFileName, extraNinjaDepsString)),
316 0666)
317}
318
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200319func touch(path string) {
320 f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
321 if err != nil {
322 fmt.Fprintf(os.Stderr, "Error touching '%s': %s\n", path, err)
323 os.Exit(1)
324 }
325
326 err = f.Close()
327 if err != nil {
328 fmt.Fprintf(os.Stderr, "Error touching '%s': %s\n", path, err)
329 os.Exit(1)
330 }
331
332 currentTime := time.Now().Local()
333 err = os.Chtimes(path, currentTime, currentTime)
334 if err != nil {
335 fmt.Fprintf(os.Stderr, "error touching '%s': %s\n", path, err)
336 os.Exit(1)
337 }
338}
339
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500340// Run Soong in the bp2build mode. This creates a standalone context that registers
341// an alternate pipeline of mutators and singletons specifically for generating
342// Bazel BUILD files instead of Ninja files.
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200343func runBp2Build(configuration android.Config, extraNinjaDeps []string) {
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500344 // Register an alternate set of singletons and mutators for bazel
345 // conversion for Bazel conversion.
346 bp2buildCtx := android.NewContext(configuration)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200347 bp2buildCtx.SetAllowMissingDependencies(configuration.AllowMissingDependencies())
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500348 bp2buildCtx.RegisterForBazelConversion()
Jingwen Cheneb76c432021-01-28 08:22:12 -0500349
350 // No need to generate Ninja build rules/statements from Modules and Singletons.
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500351 configuration.SetStopBefore(bootstrap.StopBeforePrepareBuildActions)
352 bp2buildCtx.SetNameInterface(newNameResolver(configuration))
Jingwen Cheneb76c432021-01-28 08:22:12 -0500353
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500354 // The bp2build process is a purely functional process that only depends on
355 // Android.bp files. It must not depend on the values of per-build product
356 // configurations or variables, since those will generate different BUILD
357 // files based on how the user has configured their tree.
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100358 bp2buildCtx.SetModuleListFile(bootstrap.CmdlineModuleListFile())
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200359 modulePaths, err := bp2buildCtx.ListModulePaths(configuration.SrcDir())
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500360 if err != nil {
361 panic(err)
362 }
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500363
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100364 extraNinjaDeps = append(extraNinjaDeps, modulePaths...)
365
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500366 // Run the loading and analysis pipeline to prepare the graph of regular
367 // Modules parsed from Android.bp files, and the BazelTargetModules mapped
368 // from the regular Modules.
Lukacs T. Berkid7ce8402021-03-17 14:03:51 +0100369 bootstrap.Main(bp2buildCtx.Context, configuration, false, extraNinjaDeps...)
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500370
Jingwen Chen164e0862021-02-19 00:48:40 -0500371 // Run the code-generation phase to convert BazelTargetModules to BUILD files
372 // and print conversion metrics to the user.
Jingwen Chen33832f92021-01-24 22:55:54 -0500373 codegenContext := bp2build.NewCodegenContext(configuration, *bp2buildCtx, bp2build.Bp2Build)
Jingwen Chen164e0862021-02-19 00:48:40 -0500374 metrics := bp2build.Codegen(codegenContext)
375
376 // Only report metrics when in bp2build mode. The metrics aren't relevant
377 // for queryview, since that's a total repo-wide conversion and there's a
378 // 1:1 mapping for each module.
379 metrics.Print()
Jingwen Cheneb76c432021-01-28 08:22:12 -0500380
Liz Kammerba3ea162021-02-17 13:22:03 -0500381 extraNinjaDeps = append(extraNinjaDeps, codegenContext.AdditionalNinjaDeps()...)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200382 if bp2buildMarker != "" {
383 touch(shared.JoinPath(topDir, bp2buildMarker))
384 } else {
385 writeFakeNinjaFile(extraNinjaDeps, codegenContext.Config().BuildDir())
386 }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500387}