blob: a4554fc342b4e1209402260cb1922256ca38bf8d [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. Berki7690c092021-02-26 14:27:36 +010026 "android/soong/shared"
Colin Cross70b40592015-03-23 12:57:34 -070027 "github.com/google/blueprint/bootstrap"
Colin Cross3f40fa42015-01-30 17:27:36 -080028
Colin Cross635c3b02016-05-18 15:37:25 -070029 "android/soong/android"
Jingwen Chendaa54bc2020-12-14 02:58:54 -050030 "android/soong/bp2build"
Colin Cross3f40fa42015-01-30 17:27:36 -080031)
32
Colin Crosse87040b2017-12-11 15:52:26 -080033var (
Lukacs T. Berki7690c092021-02-26 14:27:36 +010034 topDir string
35 outDir string
Jingwen Chen50f93d22020-11-05 07:42:11 -050036 docFile string
37 bazelQueryViewDir string
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +010038 delveListen string
39 delvePath string
Colin Crosse87040b2017-12-11 15:52:26 -080040)
41
42func init() {
Lukacs T. Berki7690c092021-02-26 14:27:36 +010043 flag.StringVar(&topDir, "top", "", "Top directory of the Android source tree")
44 flag.StringVar(&outDir, "out", "", "Soong output directory (usually $TOP/out/soong)")
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +010045 flag.StringVar(&delveListen, "delve_listen", "", "Delve port to listen on for debugging")
46 flag.StringVar(&delvePath, "delve_path", "", "Path to Delve. Only used if --delve_listen is set")
Colin Crosse87040b2017-12-11 15:52:26 -080047 flag.StringVar(&docFile, "soong_docs", "", "build documentation file to output")
Lukacs T. Berki47a9d0c2021-03-08 16:34:09 +010048 flag.StringVar(&bazelQueryViewDir, "bazel_queryview_dir", "", "path to the bazel queryview directory relative to --top")
Colin Crosse87040b2017-12-11 15:52:26 -080049}
50
Jeff Gaston088e29e2017-11-29 16:47:17 -080051func newNameResolver(config android.Config) *android.NameResolver {
52 namespacePathsToExport := make(map[string]bool)
53
Dan Willemsen3fb1fae2018-03-12 15:30:26 -070054 for _, namespaceName := range config.ExportedNamespaces() {
Jeff Gaston088e29e2017-11-29 16:47:17 -080055 namespacePathsToExport[namespaceName] = true
56 }
57
58 namespacePathsToExport["."] = true // always export the root namespace
59
60 exportFilter := func(namespace *android.Namespace) bool {
61 return namespacePathsToExport[namespace.Path]
62 }
63
64 return android.NewNameResolver(exportFilter)
65}
66
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +020067func newContext(configuration android.Config, prepareBuildActions bool) *android.Context {
Colin Crossae8600b2020-10-29 17:09:13 -070068 ctx := android.NewContext(configuration)
Jingwen Chendaa54bc2020-12-14 02:58:54 -050069 ctx.Register()
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +020070 if !prepareBuildActions {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040071 configuration.SetStopBefore(bootstrap.StopBeforePrepareBuildActions)
72 }
73 ctx.SetNameInterface(newNameResolver(configuration))
74 ctx.SetAllowMissingDependencies(configuration.AllowMissingDependencies())
75 return ctx
76}
77
Lukacs T. Berki53b2f362021-04-12 14:04:24 +020078func newConfig(srcDir, outDir string, availableEnv map[string]string) android.Config {
79 configuration, err := android.NewConfig(srcDir, outDir, bootstrap.CmdlineModuleListFile(), availableEnv)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040080 if err != nil {
81 fmt.Fprintf(os.Stderr, "%s", err)
82 os.Exit(1)
83 }
84 return configuration
85}
86
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +020087// Bazel-enabled mode. Soong runs in two passes.
88// First pass: Analyze the build tree, but only store all bazel commands
89// needed to correctly evaluate the tree in the second pass.
90// TODO(cparsons): Don't output any ninja file, as the second pass will overwrite
91// the incorrect results from the first pass, and file I/O is expensive.
92func runMixedModeBuild(configuration android.Config, firstCtx *android.Context, extraNinjaDeps []string) {
93 configuration.SetStopBefore(bootstrap.StopBeforeWriteNinja)
94 bootstrap.Main(firstCtx.Context, configuration, false, extraNinjaDeps...)
95 // Invoke bazel commands and save results for second pass.
96 if err := configuration.BazelContext.InvokeBazel(); err != nil {
97 fmt.Fprintf(os.Stderr, "%s", err)
98 os.Exit(1)
99 }
100 // Second pass: Full analysis, using the bazel command results. Output ninja file.
101 secondPassConfig, err := android.ConfigForAdditionalRun(configuration)
102 if err != nil {
103 fmt.Fprintf(os.Stderr, "%s", err)
104 os.Exit(1)
105 }
106 secondCtx := newContext(secondPassConfig, true)
107 bootstrap.Main(secondCtx.Context, secondPassConfig, false, extraNinjaDeps...)
108}
109
110// Run the code-generation phase to convert BazelTargetModules to BUILD files.
111func runQueryView(configuration android.Config, ctx *android.Context) {
112 codegenContext := bp2build.NewCodegenContext(configuration, *ctx, bp2build.QueryView)
113 absoluteQueryViewDir := shared.JoinPath(topDir, bazelQueryViewDir)
114 if err := createBazelQueryView(codegenContext, absoluteQueryViewDir); err != nil {
115 fmt.Fprintf(os.Stderr, "%s", err)
116 os.Exit(1)
117 }
118}
119
120func runSoongDocs(configuration android.Config, extraNinjaDeps []string) {
121 ctx := newContext(configuration, false)
122 bootstrap.Main(ctx.Context, configuration, false, extraNinjaDeps...)
123 if err := writeDocs(ctx, configuration, docFile); err != nil {
124 fmt.Fprintf(os.Stderr, "%s", err)
125 os.Exit(1)
126 }
127}
128
129func writeMetrics(configuration android.Config) {
Lukacs T. Berki745380c2021-04-12 12:07:44 +0200130 metricsFile := filepath.Join(configuration.BuildDir(), "soong_build_metrics.pb")
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200131 err := android.WriteMetrics(configuration, metricsFile)
132 if err != nil {
133 fmt.Fprintf(os.Stderr, "error writing soong_build metrics %s: %s", metricsFile, err)
134 os.Exit(1)
135 }
136}
137
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200138func writeJsonModuleGraph(configuration android.Config, ctx *android.Context, path string, extraNinjaDeps []string) {
139 f, err := os.Create(path)
140 if err != nil {
141 fmt.Fprintf(os.Stderr, "%s", err)
142 os.Exit(1)
143 }
144
145 defer f.Close()
146 ctx.Context.PrintJSONGraph(f)
147 writeFakeNinjaFile(extraNinjaDeps, configuration.BuildDir())
148}
149
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200150func doChosenActivity(configuration android.Config, extraNinjaDeps []string) {
151 bazelConversionRequested := configuration.IsEnvTrue("GENERATE_BAZEL_FILES")
152 mixedModeBuild := configuration.BazelContext.BazelEnabled()
153 generateQueryView := bazelQueryViewDir != ""
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200154 jsonModuleFile := configuration.Getenv("SOONG_DUMP_JSON_MODULE_GRAPH")
155
156 prepareBuildActions := !generateQueryView && jsonModuleFile == ""
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200157
158 if bazelConversionRequested {
159 // Run the alternate pipeline of bp2build mutators and singleton to convert
160 // Blueprint to BUILD files before everything else.
161 runBp2Build(configuration, extraNinjaDeps)
162 return
163 }
164
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200165 ctx := newContext(configuration, prepareBuildActions)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200166 if mixedModeBuild {
167 runMixedModeBuild(configuration, ctx, extraNinjaDeps)
168 } else {
169 bootstrap.Main(ctx.Context, configuration, false, extraNinjaDeps...)
170 }
171
172 // Convert the Soong module graph into Bazel BUILD files.
173 if generateQueryView {
174 runQueryView(configuration, ctx)
175 return
176 }
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200177
178 if jsonModuleFile != "" {
179 writeJsonModuleGraph(configuration, ctx, jsonModuleFile, extraNinjaDeps)
180 return
181 }
182
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200183 writeMetrics(configuration)
184}
185
Colin Cross3f40fa42015-01-30 17:27:36 -0800186func main() {
187 flag.Parse()
188
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100189 shared.ReexecWithDelveMaybe(delveListen, delvePath)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100190 android.InitSandbox(topDir)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100191
Lukacs T. Berki53b2f362021-04-12 14:04:24 +0200192 // soong_ui dumps the available environment variables to
193 // soong.environment.available . Then soong_build itself is run with an empty
194 // environment so that the only way environment variables can be accessed is
195 // using Config, which tracks access to them.
196
197 // At the end of the build, a file called soong.environment.used is written
198 // containing the current value of all used environment variables. The next
199 // time soong_ui is run, it checks whether any environment variables that was
200 // used had changed and if so, it deletes soong.environment.used to cause a
201 // rebuild.
202 //
203 // The dependency of build.ninja on soong.environment.used is declared in
204 // build.ninja.d
205 availableEnvFile := shared.JoinPath(topDir, outDir, "soong.environment.available")
206 usedEnvFile := shared.JoinPath(topDir, outDir, "soong.environment.used")
207 availableEnv, err := shared.EnvFromFile(availableEnvFile)
208 if err != nil {
209 fmt.Fprintf(os.Stderr, "error reading available environment file %s: %s\n", availableEnvFile, err)
210 os.Exit(1)
211 }
212
Colin Cross3f40fa42015-01-30 17:27:36 -0800213 // The top-level Blueprints file is passed as the first argument.
214 srcDir := filepath.Dir(flag.Arg(0))
Lukacs T. Berki53b2f362021-04-12 14:04:24 +0200215 configuration := newConfig(srcDir, outDir, availableEnv)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100216 extraNinjaDeps := []string{
217 configuration.ProductVariablesFileName,
218 shared.JoinPath(outDir, "soong.environment.used"),
219 }
Colin Crossaa812d12019-06-19 13:33:24 -0700220
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100221 if configuration.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
222 configuration.SetAllowMissingDependencies()
223 }
224
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100225 if shared.IsDebugging() {
Colin Crossaa812d12019-06-19 13:33:24 -0700226 // Add a non-existent file to the dependencies so that soong_build will rerun when the debugger is
227 // enabled even if it completed successfully.
228 extraNinjaDeps = append(extraNinjaDeps, filepath.Join(configuration.BuildDir(), "always_rerun_for_delve"))
229 }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500230
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200231 if docFile != "" {
232 // We don't write an used variables file when generating documentation
233 // because that is done from within the actual builds as a Ninja action and
234 // thus it would overwrite the actual used variables file so this is
235 // special-cased.
236 runSoongDocs(configuration, extraNinjaDeps)
237 return
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400238 }
Jingwen Chen4133ce62020-12-02 04:34:15 -0500239
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200240 doChosenActivity(configuration, extraNinjaDeps)
Lukacs T. Berki53b2f362021-04-12 14:04:24 +0200241 writeUsedEnvironmentFile(usedEnvFile, configuration)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100242}
243
Lukacs T. Berki53b2f362021-04-12 14:04:24 +0200244func writeUsedEnvironmentFile(path string, configuration android.Config) {
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100245 data, err := shared.EnvFileContents(configuration.EnvDeps())
246 if err != nil {
Lukacs T. Berki53b2f362021-04-12 14:04:24 +0200247 fmt.Fprintf(os.Stderr, "error writing used environment file %s: %s\n", path, err)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100248 os.Exit(1)
249 }
250
251 err = ioutil.WriteFile(path, data, 0666)
252 if err != nil {
Lukacs T. Berki53b2f362021-04-12 14:04:24 +0200253 fmt.Fprintf(os.Stderr, "error writing used environment file %s: %s\n", path, err)
Lukacs T. Berkic99c9472021-03-24 10:50:06 +0100254 os.Exit(1)
255 }
256
257 // Touch the output Ninja file so that it's not older than the file we just
258 // wrote. We can't write the environment file earlier because one an access
259 // new environment variables while writing it.
260 outputNinjaFile := shared.JoinPath(topDir, bootstrap.CmdlineOutFile())
261 currentTime := time.Now().Local()
262 err = os.Chtimes(outputNinjaFile, currentTime, currentTime)
263 if err != nil {
264 fmt.Fprintf(os.Stderr, "error touching output file %s: %s\n", outputNinjaFile, err)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100265 os.Exit(1)
266 }
Colin Cross3f40fa42015-01-30 17:27:36 -0800267}
Jingwen Chen5ba7e472020-07-15 10:06:41 +0000268
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200269// Workarounds to support running bp2build in a clean AOSP checkout with no
270// prior builds, and exiting early as soon as the BUILD files get generated,
271// therefore not creating build.ninja files that soong_ui and callers of
272// soong_build expects.
273//
274// These files are: build.ninja and build.ninja.d. Since Kati hasn't been
275// ran as well, and `nothing` is defined in a .mk file, there isn't a ninja
276// target called `nothing`, so we manually create it here.
277func writeFakeNinjaFile(extraNinjaDeps []string, buildDir string) {
278 extraNinjaDepsString := strings.Join(extraNinjaDeps, " \\\n ")
279
280 ninjaFileName := "build.ninja"
281 ninjaFile := shared.JoinPath(topDir, buildDir, ninjaFileName)
282 ninjaFileD := shared.JoinPath(topDir, buildDir, ninjaFileName)
283 // A workaround to create the 'nothing' ninja target so `m nothing` works,
284 // since bp2build runs without Kati, and the 'nothing' target is declared in
285 // a Makefile.
286 ioutil.WriteFile(ninjaFile, []byte("build nothing: phony\n phony_output = true\n"), 0666)
287 ioutil.WriteFile(ninjaFileD,
288 []byte(fmt.Sprintf("%s: \\\n %s\n", ninjaFileName, extraNinjaDepsString)),
289 0666)
290}
291
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500292// Run Soong in the bp2build mode. This creates a standalone context that registers
293// an alternate pipeline of mutators and singletons specifically for generating
294// Bazel BUILD files instead of Ninja files.
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200295func runBp2Build(configuration android.Config, extraNinjaDeps []string) {
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500296 // Register an alternate set of singletons and mutators for bazel
297 // conversion for Bazel conversion.
298 bp2buildCtx := android.NewContext(configuration)
299 bp2buildCtx.RegisterForBazelConversion()
Jingwen Cheneb76c432021-01-28 08:22:12 -0500300
301 // No need to generate Ninja build rules/statements from Modules and Singletons.
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500302 configuration.SetStopBefore(bootstrap.StopBeforePrepareBuildActions)
303 bp2buildCtx.SetNameInterface(newNameResolver(configuration))
Jingwen Cheneb76c432021-01-28 08:22:12 -0500304
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500305 // The bp2build process is a purely functional process that only depends on
306 // Android.bp files. It must not depend on the values of per-build product
307 // configurations or variables, since those will generate different BUILD
308 // files based on how the user has configured their tree.
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100309 bp2buildCtx.SetModuleListFile(bootstrap.CmdlineModuleListFile())
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200310 modulePaths, err := bp2buildCtx.ListModulePaths(configuration.SrcDir())
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500311 if err != nil {
312 panic(err)
313 }
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500314
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100315 extraNinjaDeps = append(extraNinjaDeps, modulePaths...)
316
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500317 // Run the loading and analysis pipeline to prepare the graph of regular
318 // Modules parsed from Android.bp files, and the BazelTargetModules mapped
319 // from the regular Modules.
Lukacs T. Berkid7ce8402021-03-17 14:03:51 +0100320 bootstrap.Main(bp2buildCtx.Context, configuration, false, extraNinjaDeps...)
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500321
Jingwen Chen164e0862021-02-19 00:48:40 -0500322 // Run the code-generation phase to convert BazelTargetModules to BUILD files
323 // and print conversion metrics to the user.
Jingwen Chen33832f92021-01-24 22:55:54 -0500324 codegenContext := bp2build.NewCodegenContext(configuration, *bp2buildCtx, bp2build.Bp2Build)
Jingwen Chen164e0862021-02-19 00:48:40 -0500325 metrics := bp2build.Codegen(codegenContext)
326
327 // Only report metrics when in bp2build mode. The metrics aren't relevant
328 // for queryview, since that's a total repo-wide conversion and there's a
329 // 1:1 mapping for each module.
330 metrics.Print()
Jingwen Cheneb76c432021-01-28 08:22:12 -0500331
Liz Kammerba3ea162021-02-17 13:22:03 -0500332 extraNinjaDeps = append(extraNinjaDeps, codegenContext.AdditionalNinjaDeps()...)
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200333 writeFakeNinjaFile(extraNinjaDeps, codegenContext.Config().BuildDir())
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500334}