blob: e2fc78cef076d60e30aed4900c6f6b7cf2395775 [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"
Jingwen Chen12b4c272021-03-10 02:05:59 -050027
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"
Jingwen Chendaa54bc2020-12-14 02:58:54 -050031 "android/soong/bp2build"
Colin Cross3f40fa42015-01-30 17:27:36 -080032)
33
Colin Crosse87040b2017-12-11 15:52:26 -080034var (
Lukacs T. Berki7690c092021-02-26 14:27:36 +010035 topDir string
36 outDir string
Jingwen Chen50f93d22020-11-05 07:42:11 -050037 docFile string
38 bazelQueryViewDir string
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +010039 delveListen string
40 delvePath string
Colin Crosse87040b2017-12-11 15:52:26 -080041)
42
43func init() {
Lukacs T. Berki7690c092021-02-26 14:27:36 +010044 flag.StringVar(&topDir, "top", "", "Top directory of the Android source tree")
45 flag.StringVar(&outDir, "out", "", "Soong output directory (usually $TOP/out/soong)")
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +010046 flag.StringVar(&delveListen, "delve_listen", "", "Delve port to listen on for debugging")
47 flag.StringVar(&delvePath, "delve_path", "", "Path to Delve. Only used if --delve_listen is set")
Colin Crosse87040b2017-12-11 15:52:26 -080048 flag.StringVar(&docFile, "soong_docs", "", "build documentation file to output")
Lukacs T. Berki47a9d0c2021-03-08 16:34:09 +010049 flag.StringVar(&bazelQueryViewDir, "bazel_queryview_dir", "", "path to the bazel queryview directory relative to --top")
Colin Crosse87040b2017-12-11 15:52:26 -080050}
51
Jeff Gaston088e29e2017-11-29 16:47:17 -080052func newNameResolver(config android.Config) *android.NameResolver {
53 namespacePathsToExport := make(map[string]bool)
54
Dan Willemsen3fb1fae2018-03-12 15:30:26 -070055 for _, namespaceName := range config.ExportedNamespaces() {
Jeff Gaston088e29e2017-11-29 16:47:17 -080056 namespacePathsToExport[namespaceName] = true
57 }
58
59 namespacePathsToExport["."] = true // always export the root namespace
60
61 exportFilter := func(namespace *android.Namespace) bool {
62 return namespacePathsToExport[namespace.Path]
63 }
64
65 return android.NewNameResolver(exportFilter)
66}
67
Jingwen Chen4133ce62020-12-02 04:34:15 -050068// bazelConversionRequested checks that the user is intending to convert
69// Blueprint to Bazel BUILD files.
70func bazelConversionRequested(configuration android.Config) bool {
Jingwen Chendaa54bc2020-12-14 02:58:54 -050071 return configuration.IsEnvTrue("GENERATE_BAZEL_FILES")
Jingwen Chen4133ce62020-12-02 04:34:15 -050072}
73
Jingwen Chendaa54bc2020-12-14 02:58:54 -050074func newContext(configuration android.Config) *android.Context {
Colin Crossae8600b2020-10-29 17:09:13 -070075 ctx := android.NewContext(configuration)
Jingwen Chendaa54bc2020-12-14 02:58:54 -050076 ctx.Register()
Jingwen Chen4133ce62020-12-02 04:34:15 -050077 if !shouldPrepareBuildActions(configuration) {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040078 configuration.SetStopBefore(bootstrap.StopBeforePrepareBuildActions)
79 }
80 ctx.SetNameInterface(newNameResolver(configuration))
81 ctx.SetAllowMissingDependencies(configuration.AllowMissingDependencies())
82 return ctx
83}
84
85func newConfig(srcDir string) android.Config {
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010086 configuration, err := android.NewConfig(srcDir, bootstrap.CmdlineBuildDir(), bootstrap.CmdlineModuleListFile())
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040087 if err != nil {
88 fmt.Fprintf(os.Stderr, "%s", err)
89 os.Exit(1)
90 }
91 return configuration
92}
93
Colin Cross3f40fa42015-01-30 17:27:36 -080094func main() {
95 flag.Parse()
96
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +010097 shared.ReexecWithDelveMaybe(delveListen, delvePath)
Lukacs T. Berki7690c092021-02-26 14:27:36 +010098 android.InitSandbox(topDir)
99 android.InitEnvironment(shared.JoinPath(topDir, outDir, "soong.environment.available"))
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100100
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100101 usedVariablesFile := shared.JoinPath(outDir, "soong.environment.used")
Colin Cross3f40fa42015-01-30 17:27:36 -0800102 // The top-level Blueprints file is passed as the first argument.
103 srcDir := filepath.Dir(flag.Arg(0))
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400104 var ctx *android.Context
105 configuration := newConfig(srcDir)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100106 extraNinjaDeps := []string{
107 configuration.ProductVariablesFileName,
108 shared.JoinPath(outDir, "soong.environment.used"),
109 }
Colin Crossaa812d12019-06-19 13:33:24 -0700110
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100111 if configuration.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
112 configuration.SetAllowMissingDependencies()
113 }
114
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100115 // These two are here so that we restart a non-debugged soong_build when the
116 // user sets SOONG_DELVE the first time.
117 configuration.Getenv("SOONG_DELVE")
118 configuration.Getenv("SOONG_DELVE_PATH")
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100119 if shared.IsDebugging() {
Colin Crossaa812d12019-06-19 13:33:24 -0700120 // Add a non-existent file to the dependencies so that soong_build will rerun when the debugger is
121 // enabled even if it completed successfully.
122 extraNinjaDeps = append(extraNinjaDeps, filepath.Join(configuration.BuildDir(), "always_rerun_for_delve"))
123 }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500124
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100125 bazelConversionRequested := bazelConversionRequested(configuration)
126 if bazelConversionRequested {
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500127 // Run the alternate pipeline of bp2build mutators and singleton to convert Blueprint to BUILD files
128 // before everything else.
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100129 runBp2Build(srcDir, configuration, extraNinjaDeps)
130 } else if configuration.BazelContext.BazelEnabled() {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400131 // Bazel-enabled mode. Soong runs in two passes.
132 // First pass: Analyze the build tree, but only store all bazel commands
133 // needed to correctly evaluate the tree in the second pass.
134 // TODO(cparsons): Don't output any ninja file, as the second pass will overwrite
135 // the incorrect results from the first pass, and file I/O is expensive.
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500136 firstCtx := newContext(configuration)
Chris Parsons3060ec72020-11-09 20:08:36 -0500137 configuration.SetStopBefore(bootstrap.StopBeforeWriteNinja)
Lukacs T. Berkid7ce8402021-03-17 14:03:51 +0100138 bootstrap.Main(firstCtx.Context, configuration, false, extraNinjaDeps...)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400139 // Invoke bazel commands and save results for second pass.
140 if err := configuration.BazelContext.InvokeBazel(); err != nil {
141 fmt.Fprintf(os.Stderr, "%s", err)
142 os.Exit(1)
143 }
144 // Second pass: Full analysis, using the bazel command results. Output ninja file.
145 secondPassConfig, err := android.ConfigForAdditionalRun(configuration)
146 if err != nil {
147 fmt.Fprintf(os.Stderr, "%s", err)
148 os.Exit(1)
149 }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500150 ctx = newContext(secondPassConfig)
Lukacs T. Berkid7ce8402021-03-17 14:03:51 +0100151 bootstrap.Main(ctx.Context, secondPassConfig, false, extraNinjaDeps...)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400152 } else {
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500153 ctx = newContext(configuration)
Lukacs T. Berkid7ce8402021-03-17 14:03:51 +0100154 bootstrap.Main(ctx.Context, configuration, false, extraNinjaDeps...)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400155 }
Jingwen Chen4133ce62020-12-02 04:34:15 -0500156
157 // Convert the Soong module graph into Bazel BUILD files.
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100158 if !bazelConversionRequested && bazelQueryViewDir != "" {
Jingwen Chen164e0862021-02-19 00:48:40 -0500159 // Run the code-generation phase to convert BazelTargetModules to BUILD files.
160 codegenContext := bp2build.NewCodegenContext(configuration, *ctx, bp2build.QueryView)
Lukacs T. Berki47a9d0c2021-03-08 16:34:09 +0100161 absoluteQueryViewDir := shared.JoinPath(topDir, bazelQueryViewDir)
162 if err := createBazelQueryView(codegenContext, absoluteQueryViewDir); err != nil {
Jingwen Chen5ba7e472020-07-15 10:06:41 +0000163 fmt.Fprintf(os.Stderr, "%s", err)
164 os.Exit(1)
165 }
166 }
167
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100168 if !bazelConversionRequested && docFile != "" {
Lukacs T. Berki89e9a162021-03-12 08:31:32 +0100169 if err := writeDocs(ctx, configuration, docFile); err != nil {
Colin Cross7089c272019-01-25 22:43:35 -0800170 fmt.Fprintf(os.Stderr, "%s", err)
171 os.Exit(1)
172 }
Colin Crosse87040b2017-12-11 15:52:26 -0800173 }
Colin Crossb72c9092020-02-10 11:23:49 -0800174
175 // TODO(ccross): make this a command line argument. Requires plumbing through blueprint
176 // to affect the command line of the primary builder.
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100177 if !bazelConversionRequested && shouldPrepareBuildActions(configuration) {
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100178 metricsFile := filepath.Join(bootstrap.CmdlineBuildDir(), "soong_build_metrics.pb")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400179 err := android.WriteMetrics(configuration, metricsFile)
Colin Crossb72c9092020-02-10 11:23:49 -0800180 if err != nil {
181 fmt.Fprintf(os.Stderr, "error writing soong_build metrics %s: %s", metricsFile, err)
182 os.Exit(1)
183 }
184 }
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100185
186 if docFile == "" {
187 // Let's not overwrite the used variables file when generating
188 // documentation
189 writeUsedVariablesFile(shared.JoinPath(topDir, usedVariablesFile), configuration)
190 }
191}
192
193func writeUsedVariablesFile(path string, configuration android.Config) {
194 data, err := shared.EnvFileContents(configuration.EnvDeps())
195 if err != nil {
Lukacs T. Berkic99c9472021-03-24 10:50:06 +0100196 fmt.Fprintf(os.Stderr, "error writing used variables file %s: %s\n", path, err)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100197 os.Exit(1)
198 }
199
200 err = ioutil.WriteFile(path, data, 0666)
201 if err != nil {
Lukacs T. Berkic99c9472021-03-24 10:50:06 +0100202 fmt.Fprintf(os.Stderr, "error writing used variables file %s: %s\n", path, err)
203 os.Exit(1)
204 }
205
206 // Touch the output Ninja file so that it's not older than the file we just
207 // wrote. We can't write the environment file earlier because one an access
208 // new environment variables while writing it.
209 outputNinjaFile := shared.JoinPath(topDir, bootstrap.CmdlineOutFile())
210 currentTime := time.Now().Local()
211 err = os.Chtimes(outputNinjaFile, currentTime, currentTime)
212 if err != nil {
213 fmt.Fprintf(os.Stderr, "error touching output file %s: %s\n", outputNinjaFile, err)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100214 os.Exit(1)
215 }
Colin Cross3f40fa42015-01-30 17:27:36 -0800216}
Jingwen Chen5ba7e472020-07-15 10:06:41 +0000217
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500218// Run Soong in the bp2build mode. This creates a standalone context that registers
219// an alternate pipeline of mutators and singletons specifically for generating
220// Bazel BUILD files instead of Ninja files.
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100221func runBp2Build(srcDir string, configuration android.Config, extraNinjaDeps []string) {
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500222 // Register an alternate set of singletons and mutators for bazel
223 // conversion for Bazel conversion.
224 bp2buildCtx := android.NewContext(configuration)
225 bp2buildCtx.RegisterForBazelConversion()
Jingwen Cheneb76c432021-01-28 08:22:12 -0500226
227 // No need to generate Ninja build rules/statements from Modules and Singletons.
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500228 configuration.SetStopBefore(bootstrap.StopBeforePrepareBuildActions)
229 bp2buildCtx.SetNameInterface(newNameResolver(configuration))
Jingwen Cheneb76c432021-01-28 08:22:12 -0500230
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500231 // The bp2build process is a purely functional process that only depends on
232 // Android.bp files. It must not depend on the values of per-build product
233 // configurations or variables, since those will generate different BUILD
234 // files based on how the user has configured their tree.
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100235 bp2buildCtx.SetModuleListFile(bootstrap.CmdlineModuleListFile())
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100236 modulePaths, err := bp2buildCtx.ListModulePaths(srcDir)
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500237 if err != nil {
238 panic(err)
239 }
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500240
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100241 extraNinjaDeps = append(extraNinjaDeps, modulePaths...)
242
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500243 // Run the loading and analysis pipeline to prepare the graph of regular
244 // Modules parsed from Android.bp files, and the BazelTargetModules mapped
245 // from the regular Modules.
Lukacs T. Berkid7ce8402021-03-17 14:03:51 +0100246 bootstrap.Main(bp2buildCtx.Context, configuration, false, extraNinjaDeps...)
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500247
Jingwen Chen164e0862021-02-19 00:48:40 -0500248 // Run the code-generation phase to convert BazelTargetModules to BUILD files
249 // and print conversion metrics to the user.
Jingwen Chen33832f92021-01-24 22:55:54 -0500250 codegenContext := bp2build.NewCodegenContext(configuration, *bp2buildCtx, bp2build.Bp2Build)
Jingwen Chen164e0862021-02-19 00:48:40 -0500251 metrics := bp2build.Codegen(codegenContext)
252
253 // Only report metrics when in bp2build mode. The metrics aren't relevant
254 // for queryview, since that's a total repo-wide conversion and there's a
255 // 1:1 mapping for each module.
256 metrics.Print()
Jingwen Cheneb76c432021-01-28 08:22:12 -0500257
Liz Kammerba3ea162021-02-17 13:22:03 -0500258 extraNinjaDeps = append(extraNinjaDeps, codegenContext.AdditionalNinjaDeps()...)
259 extraNinjaDepsString := strings.Join(extraNinjaDeps, " \\\n ")
260
Jingwen Cheneb76c432021-01-28 08:22:12 -0500261 // Workarounds to support running bp2build in a clean AOSP checkout with no
262 // prior builds, and exiting early as soon as the BUILD files get generated,
263 // therefore not creating build.ninja files that soong_ui and callers of
264 // soong_build expects.
265 //
266 // These files are: build.ninja and build.ninja.d. Since Kati hasn't been
267 // ran as well, and `nothing` is defined in a .mk file, there isn't a ninja
268 // target called `nothing`, so we manually create it here.
269 //
270 // Even though outFile (build.ninja) and depFile (build.ninja.d) are values
271 // passed into bootstrap.Main, they are package-private fields in bootstrap.
272 // Short of modifying Blueprint to add an exported getter, inlining them
273 // here is the next-best practical option.
274 ninjaFileName := "build.ninja"
275 ninjaFile := android.PathForOutput(codegenContext, ninjaFileName)
276 ninjaFileD := android.PathForOutput(codegenContext, ninjaFileName+".d")
Jingwen Cheneb76c432021-01-28 08:22:12 -0500277 // A workaround to create the 'nothing' ninja target so `m nothing` works,
278 // since bp2build runs without Kati, and the 'nothing' target is declared in
279 // a Makefile.
280 android.WriteFileToOutputDir(ninjaFile, []byte("build nothing: phony\n phony_output = true\n"), 0666)
281 android.WriteFileToOutputDir(
282 ninjaFileD,
283 []byte(fmt.Sprintf("%s: \\\n %s\n", ninjaFileName, extraNinjaDepsString)),
284 0666)
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500285}
286
Jingwen Chen4133ce62020-12-02 04:34:15 -0500287// shouldPrepareBuildActions reads configuration and flags if build actions
288// should be generated.
289func shouldPrepareBuildActions(configuration android.Config) bool {
290 // Generating Soong docs
291 if docFile != "" {
292 return false
293 }
294
295 // Generating a directory for Soong query (queryview)
296 if bazelQueryViewDir != "" {
297 return false
298 }
299
300 // Generating a directory for converted Bazel BUILD files
301 return !bazelConversionRequested(configuration)
Jingwen Chen5ba7e472020-07-15 10:06:41 +0000302}