blob: 3a6fecaf05f18313ee6d87eed93eafb23bd42071 [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"
20 "os"
21 "path/filepath"
Jingwen Cheneb76c432021-01-28 08:22:12 -050022 "strings"
Colin Cross3f40fa42015-01-30 17:27:36 -080023
Colin Cross70b40592015-03-23 12:57:34 -070024 "github.com/google/blueprint/bootstrap"
Colin Cross3f40fa42015-01-30 17:27:36 -080025
Colin Cross635c3b02016-05-18 15:37:25 -070026 "android/soong/android"
Jingwen Chendaa54bc2020-12-14 02:58:54 -050027 "android/soong/bp2build"
Colin Cross3f40fa42015-01-30 17:27:36 -080028)
29
Colin Crosse87040b2017-12-11 15:52:26 -080030var (
Jingwen Chen50f93d22020-11-05 07:42:11 -050031 docFile string
32 bazelQueryViewDir string
Colin Crosse87040b2017-12-11 15:52:26 -080033)
34
35func init() {
36 flag.StringVar(&docFile, "soong_docs", "", "build documentation file to output")
Jingwen Chen50f93d22020-11-05 07:42:11 -050037 flag.StringVar(&bazelQueryViewDir, "bazel_queryview_dir", "", "path to the bazel queryview directory")
Colin Crosse87040b2017-12-11 15:52:26 -080038}
39
Jeff Gaston088e29e2017-11-29 16:47:17 -080040func newNameResolver(config android.Config) *android.NameResolver {
41 namespacePathsToExport := make(map[string]bool)
42
Dan Willemsen3fb1fae2018-03-12 15:30:26 -070043 for _, namespaceName := range config.ExportedNamespaces() {
Jeff Gaston088e29e2017-11-29 16:47:17 -080044 namespacePathsToExport[namespaceName] = true
45 }
46
47 namespacePathsToExport["."] = true // always export the root namespace
48
49 exportFilter := func(namespace *android.Namespace) bool {
50 return namespacePathsToExport[namespace.Path]
51 }
52
53 return android.NewNameResolver(exportFilter)
54}
55
Jingwen Chen4133ce62020-12-02 04:34:15 -050056// bazelConversionRequested checks that the user is intending to convert
57// Blueprint to Bazel BUILD files.
58func bazelConversionRequested(configuration android.Config) bool {
Jingwen Chendaa54bc2020-12-14 02:58:54 -050059 return configuration.IsEnvTrue("GENERATE_BAZEL_FILES")
Jingwen Chen4133ce62020-12-02 04:34:15 -050060}
61
Jingwen Chendaa54bc2020-12-14 02:58:54 -050062func newContext(configuration android.Config) *android.Context {
Colin Crossae8600b2020-10-29 17:09:13 -070063 ctx := android.NewContext(configuration)
Jingwen Chendaa54bc2020-12-14 02:58:54 -050064 ctx.Register()
Jingwen Chen4133ce62020-12-02 04:34:15 -050065 if !shouldPrepareBuildActions(configuration) {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040066 configuration.SetStopBefore(bootstrap.StopBeforePrepareBuildActions)
67 }
68 ctx.SetNameInterface(newNameResolver(configuration))
69 ctx.SetAllowMissingDependencies(configuration.AllowMissingDependencies())
70 return ctx
71}
72
73func newConfig(srcDir string) android.Config {
74 configuration, err := android.NewConfig(srcDir, bootstrap.BuildDir, bootstrap.ModuleListFile)
75 if err != nil {
76 fmt.Fprintf(os.Stderr, "%s", err)
77 os.Exit(1)
78 }
79 return configuration
80}
81
Colin Cross3f40fa42015-01-30 17:27:36 -080082func main() {
Lukacs T. Berkia5e0f712020-05-18 09:50:18 +020083 android.ReexecWithDelveMaybe()
Colin Cross3f40fa42015-01-30 17:27:36 -080084 flag.Parse()
85
86 // The top-level Blueprints file is passed as the first argument.
87 srcDir := filepath.Dir(flag.Arg(0))
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040088 var ctx *android.Context
89 configuration := newConfig(srcDir)
Jingwen Chenc4d91bc2020-11-24 22:59:26 -050090 extraNinjaDeps := []string{configuration.ProductVariablesFileName}
Colin Crossaa812d12019-06-19 13:33:24 -070091
92 // Read the SOONG_DELVE again through configuration so that there is a dependency on the environment variable
93 // and soong_build will rerun when it is set for the first time.
94 if listen := configuration.Getenv("SOONG_DELVE"); listen != "" {
95 // Add a non-existent file to the dependencies so that soong_build will rerun when the debugger is
96 // enabled even if it completed successfully.
97 extraNinjaDeps = append(extraNinjaDeps, filepath.Join(configuration.BuildDir(), "always_rerun_for_delve"))
98 }
Jingwen Chendaa54bc2020-12-14 02:58:54 -050099
100 if bazelConversionRequested(configuration) {
101 // Run the alternate pipeline of bp2build mutators and singleton to convert Blueprint to BUILD files
102 // before everything else.
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500103 runBp2Build(srcDir, configuration)
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500104 // Short-circuit and return.
105 return
106 }
107
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400108 if configuration.BazelContext.BazelEnabled() {
109 // Bazel-enabled mode. Soong runs in two passes.
110 // First pass: Analyze the build tree, but only store all bazel commands
111 // needed to correctly evaluate the tree in the second pass.
112 // TODO(cparsons): Don't output any ninja file, as the second pass will overwrite
113 // the incorrect results from the first pass, and file I/O is expensive.
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500114 firstCtx := newContext(configuration)
Chris Parsons3060ec72020-11-09 20:08:36 -0500115 configuration.SetStopBefore(bootstrap.StopBeforeWriteNinja)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400116 bootstrap.Main(firstCtx.Context, configuration, extraNinjaDeps...)
117 // Invoke bazel commands and save results for second pass.
118 if err := configuration.BazelContext.InvokeBazel(); err != nil {
119 fmt.Fprintf(os.Stderr, "%s", err)
120 os.Exit(1)
121 }
122 // Second pass: Full analysis, using the bazel command results. Output ninja file.
123 secondPassConfig, err := android.ConfigForAdditionalRun(configuration)
124 if err != nil {
125 fmt.Fprintf(os.Stderr, "%s", err)
126 os.Exit(1)
127 }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500128 ctx = newContext(secondPassConfig)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400129 bootstrap.Main(ctx.Context, secondPassConfig, extraNinjaDeps...)
130 } else {
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500131 ctx = newContext(configuration)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400132 bootstrap.Main(ctx.Context, configuration, extraNinjaDeps...)
133 }
Jingwen Chen4133ce62020-12-02 04:34:15 -0500134
135 // Convert the Soong module graph into Bazel BUILD files.
Jingwen Chen50f93d22020-11-05 07:42:11 -0500136 if bazelQueryViewDir != "" {
Jingwen Chen164e0862021-02-19 00:48:40 -0500137 // Run the code-generation phase to convert BazelTargetModules to BUILD files.
138 codegenContext := bp2build.NewCodegenContext(configuration, *ctx, bp2build.QueryView)
139 if err := createBazelQueryView(codegenContext, bazelQueryViewDir); err != nil {
Jingwen Chen5ba7e472020-07-15 10:06:41 +0000140 fmt.Fprintf(os.Stderr, "%s", err)
141 os.Exit(1)
142 }
143 }
144
Colin Crosse87040b2017-12-11 15:52:26 -0800145 if docFile != "" {
Sasha Smundakff483392019-02-07 12:10:56 -0800146 if err := writeDocs(ctx, docFile); err != nil {
Colin Cross7089c272019-01-25 22:43:35 -0800147 fmt.Fprintf(os.Stderr, "%s", err)
148 os.Exit(1)
149 }
Colin Crosse87040b2017-12-11 15:52:26 -0800150 }
Colin Crossb72c9092020-02-10 11:23:49 -0800151
152 // TODO(ccross): make this a command line argument. Requires plumbing through blueprint
153 // to affect the command line of the primary builder.
Jingwen Chen4133ce62020-12-02 04:34:15 -0500154 if shouldPrepareBuildActions(configuration) {
Colin Crossb72c9092020-02-10 11:23:49 -0800155 metricsFile := filepath.Join(bootstrap.BuildDir, "soong_build_metrics.pb")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400156 err := android.WriteMetrics(configuration, metricsFile)
Colin Crossb72c9092020-02-10 11:23:49 -0800157 if err != nil {
158 fmt.Fprintf(os.Stderr, "error writing soong_build metrics %s: %s", metricsFile, err)
159 os.Exit(1)
160 }
161 }
Colin Cross3f40fa42015-01-30 17:27:36 -0800162}
Jingwen Chen5ba7e472020-07-15 10:06:41 +0000163
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500164// Run Soong in the bp2build mode. This creates a standalone context that registers
165// an alternate pipeline of mutators and singletons specifically for generating
166// Bazel BUILD files instead of Ninja files.
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500167func runBp2Build(srcDir string, configuration android.Config) {
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500168 // Register an alternate set of singletons and mutators for bazel
169 // conversion for Bazel conversion.
170 bp2buildCtx := android.NewContext(configuration)
171 bp2buildCtx.RegisterForBazelConversion()
Jingwen Cheneb76c432021-01-28 08:22:12 -0500172
173 // No need to generate Ninja build rules/statements from Modules and Singletons.
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500174 configuration.SetStopBefore(bootstrap.StopBeforePrepareBuildActions)
175 bp2buildCtx.SetNameInterface(newNameResolver(configuration))
Jingwen Cheneb76c432021-01-28 08:22:12 -0500176
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500177 // The bp2build process is a purely functional process that only depends on
178 // Android.bp files. It must not depend on the values of per-build product
179 // configurations or variables, since those will generate different BUILD
180 // files based on how the user has configured their tree.
181 bp2buildCtx.SetModuleListFile(bootstrap.ModuleListFile)
182 extraNinjaDeps, err := bp2buildCtx.ListModulePaths(srcDir)
183 if err != nil {
184 panic(err)
185 }
186 extraNinjaDepsString := strings.Join(extraNinjaDeps, " \\\n ")
187
188 // Run the loading and analysis pipeline to prepare the graph of regular
189 // Modules parsed from Android.bp files, and the BazelTargetModules mapped
190 // from the regular Modules.
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500191 bootstrap.Main(bp2buildCtx.Context, configuration, extraNinjaDeps...)
192
Jingwen Chen164e0862021-02-19 00:48:40 -0500193 // Run the code-generation phase to convert BazelTargetModules to BUILD files
194 // and print conversion metrics to the user.
Jingwen Chen33832f92021-01-24 22:55:54 -0500195 codegenContext := bp2build.NewCodegenContext(configuration, *bp2buildCtx, bp2build.Bp2Build)
Jingwen Chen164e0862021-02-19 00:48:40 -0500196 metrics := bp2build.Codegen(codegenContext)
197
198 // Only report metrics when in bp2build mode. The metrics aren't relevant
199 // for queryview, since that's a total repo-wide conversion and there's a
200 // 1:1 mapping for each module.
201 metrics.Print()
Jingwen Cheneb76c432021-01-28 08:22:12 -0500202
203 // Workarounds to support running bp2build in a clean AOSP checkout with no
204 // prior builds, and exiting early as soon as the BUILD files get generated,
205 // therefore not creating build.ninja files that soong_ui and callers of
206 // soong_build expects.
207 //
208 // These files are: build.ninja and build.ninja.d. Since Kati hasn't been
209 // ran as well, and `nothing` is defined in a .mk file, there isn't a ninja
210 // target called `nothing`, so we manually create it here.
211 //
212 // Even though outFile (build.ninja) and depFile (build.ninja.d) are values
213 // passed into bootstrap.Main, they are package-private fields in bootstrap.
214 // Short of modifying Blueprint to add an exported getter, inlining them
215 // here is the next-best practical option.
216 ninjaFileName := "build.ninja"
217 ninjaFile := android.PathForOutput(codegenContext, ninjaFileName)
218 ninjaFileD := android.PathForOutput(codegenContext, ninjaFileName+".d")
Jingwen Cheneb76c432021-01-28 08:22:12 -0500219 // A workaround to create the 'nothing' ninja target so `m nothing` works,
220 // since bp2build runs without Kati, and the 'nothing' target is declared in
221 // a Makefile.
222 android.WriteFileToOutputDir(ninjaFile, []byte("build nothing: phony\n phony_output = true\n"), 0666)
223 android.WriteFileToOutputDir(
224 ninjaFileD,
225 []byte(fmt.Sprintf("%s: \\\n %s\n", ninjaFileName, extraNinjaDepsString)),
226 0666)
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500227}
228
Jingwen Chen4133ce62020-12-02 04:34:15 -0500229// shouldPrepareBuildActions reads configuration and flags if build actions
230// should be generated.
231func shouldPrepareBuildActions(configuration android.Config) bool {
232 // Generating Soong docs
233 if docFile != "" {
234 return false
235 }
236
237 // Generating a directory for Soong query (queryview)
238 if bazelQueryViewDir != "" {
239 return false
240 }
241
242 // Generating a directory for converted Bazel BUILD files
243 return !bazelConversionRequested(configuration)
Jingwen Chen5ba7e472020-07-15 10:06:41 +0000244}