blob: 0a739bd0d42e1a286a27b375436becadcbdc6466 [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
Lukacs T. Berki7690c092021-02-26 14:27:36 +010024 "android/soong/shared"
Jingwen Chen12b4c272021-03-10 02:05:59 -050025
Colin Cross70b40592015-03-23 12:57:34 -070026 "github.com/google/blueprint/bootstrap"
Colin Cross3f40fa42015-01-30 17:27:36 -080027
Colin Cross635c3b02016-05-18 15:37:25 -070028 "android/soong/android"
Jingwen Chendaa54bc2020-12-14 02:58:54 -050029 "android/soong/bp2build"
Colin Cross3f40fa42015-01-30 17:27:36 -080030)
31
Colin Crosse87040b2017-12-11 15:52:26 -080032var (
Lukacs T. Berki7690c092021-02-26 14:27:36 +010033 topDir string
34 outDir string
Jingwen Chen50f93d22020-11-05 07:42:11 -050035 docFile string
36 bazelQueryViewDir string
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +010037 delveListen string
38 delvePath string
Colin Crosse87040b2017-12-11 15:52:26 -080039)
40
41func init() {
Lukacs T. Berki7690c092021-02-26 14:27:36 +010042 flag.StringVar(&topDir, "top", "", "Top directory of the Android source tree")
43 flag.StringVar(&outDir, "out", "", "Soong output directory (usually $TOP/out/soong)")
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +010044 flag.StringVar(&delveListen, "delve_listen", "", "Delve port to listen on for debugging")
45 flag.StringVar(&delvePath, "delve_path", "", "Path to Delve. Only used if --delve_listen is set")
Colin Crosse87040b2017-12-11 15:52:26 -080046 flag.StringVar(&docFile, "soong_docs", "", "build documentation file to output")
Lukacs T. Berki47a9d0c2021-03-08 16:34:09 +010047 flag.StringVar(&bazelQueryViewDir, "bazel_queryview_dir", "", "path to the bazel queryview directory relative to --top")
Colin Crosse87040b2017-12-11 15:52:26 -080048}
49
Jeff Gaston088e29e2017-11-29 16:47:17 -080050func newNameResolver(config android.Config) *android.NameResolver {
51 namespacePathsToExport := make(map[string]bool)
52
Dan Willemsen3fb1fae2018-03-12 15:30:26 -070053 for _, namespaceName := range config.ExportedNamespaces() {
Jeff Gaston088e29e2017-11-29 16:47:17 -080054 namespacePathsToExport[namespaceName] = true
55 }
56
57 namespacePathsToExport["."] = true // always export the root namespace
58
59 exportFilter := func(namespace *android.Namespace) bool {
60 return namespacePathsToExport[namespace.Path]
61 }
62
63 return android.NewNameResolver(exportFilter)
64}
65
Jingwen Chen4133ce62020-12-02 04:34:15 -050066// bazelConversionRequested checks that the user is intending to convert
67// Blueprint to Bazel BUILD files.
68func bazelConversionRequested(configuration android.Config) bool {
Jingwen Chendaa54bc2020-12-14 02:58:54 -050069 return configuration.IsEnvTrue("GENERATE_BAZEL_FILES")
Jingwen Chen4133ce62020-12-02 04:34:15 -050070}
71
Jingwen Chendaa54bc2020-12-14 02:58:54 -050072func newContext(configuration android.Config) *android.Context {
Colin Crossae8600b2020-10-29 17:09:13 -070073 ctx := android.NewContext(configuration)
Jingwen Chendaa54bc2020-12-14 02:58:54 -050074 ctx.Register()
Jingwen Chen4133ce62020-12-02 04:34:15 -050075 if !shouldPrepareBuildActions(configuration) {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040076 configuration.SetStopBefore(bootstrap.StopBeforePrepareBuildActions)
77 }
78 ctx.SetNameInterface(newNameResolver(configuration))
79 ctx.SetAllowMissingDependencies(configuration.AllowMissingDependencies())
80 return ctx
81}
82
83func newConfig(srcDir string) android.Config {
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010084 configuration, err := android.NewConfig(srcDir, bootstrap.CmdlineBuildDir(), bootstrap.CmdlineModuleListFile())
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040085 if err != nil {
86 fmt.Fprintf(os.Stderr, "%s", err)
87 os.Exit(1)
88 }
89 return configuration
90}
91
Colin Cross3f40fa42015-01-30 17:27:36 -080092func main() {
93 flag.Parse()
94
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +010095 shared.ReexecWithDelveMaybe(delveListen, delvePath)
Lukacs T. Berki7690c092021-02-26 14:27:36 +010096 android.InitSandbox(topDir)
97 android.InitEnvironment(shared.JoinPath(topDir, outDir, "soong.environment.available"))
Lukacs T. Berki7690c092021-02-26 14:27:36 +010098
Colin Cross3f40fa42015-01-30 17:27:36 -080099 // The top-level Blueprints file is passed as the first argument.
100 srcDir := filepath.Dir(flag.Arg(0))
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400101 var ctx *android.Context
102 configuration := newConfig(srcDir)
Jingwen Chenc4d91bc2020-11-24 22:59:26 -0500103 extraNinjaDeps := []string{configuration.ProductVariablesFileName}
Colin Crossaa812d12019-06-19 13:33:24 -0700104
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100105 if configuration.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
106 configuration.SetAllowMissingDependencies()
107 }
108
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100109 // These two are here so that we restart a non-debugged soong_build when the
110 // user sets SOONG_DELVE the first time.
111 configuration.Getenv("SOONG_DELVE")
112 configuration.Getenv("SOONG_DELVE_PATH")
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100113 if shared.IsDebugging() {
Colin Crossaa812d12019-06-19 13:33:24 -0700114 // Add a non-existent file to the dependencies so that soong_build will rerun when the debugger is
115 // enabled even if it completed successfully.
116 extraNinjaDeps = append(extraNinjaDeps, filepath.Join(configuration.BuildDir(), "always_rerun_for_delve"))
117 }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500118
119 if bazelConversionRequested(configuration) {
120 // Run the alternate pipeline of bp2build mutators and singleton to convert Blueprint to BUILD files
121 // before everything else.
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500122 runBp2Build(srcDir, configuration)
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500123 // Short-circuit and return.
124 return
125 }
126
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400127 if configuration.BazelContext.BazelEnabled() {
128 // Bazel-enabled mode. Soong runs in two passes.
129 // First pass: Analyze the build tree, but only store all bazel commands
130 // needed to correctly evaluate the tree in the second pass.
131 // TODO(cparsons): Don't output any ninja file, as the second pass will overwrite
132 // the incorrect results from the first pass, and file I/O is expensive.
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500133 firstCtx := newContext(configuration)
Chris Parsons3060ec72020-11-09 20:08:36 -0500134 configuration.SetStopBefore(bootstrap.StopBeforeWriteNinja)
Lukacs T. Berkid7ce8402021-03-17 14:03:51 +0100135 bootstrap.Main(firstCtx.Context, configuration, false, extraNinjaDeps...)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400136 // Invoke bazel commands and save results for second pass.
137 if err := configuration.BazelContext.InvokeBazel(); err != nil {
138 fmt.Fprintf(os.Stderr, "%s", err)
139 os.Exit(1)
140 }
141 // Second pass: Full analysis, using the bazel command results. Output ninja file.
142 secondPassConfig, err := android.ConfigForAdditionalRun(configuration)
143 if err != nil {
144 fmt.Fprintf(os.Stderr, "%s", err)
145 os.Exit(1)
146 }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500147 ctx = newContext(secondPassConfig)
Lukacs T. Berkid7ce8402021-03-17 14:03:51 +0100148 bootstrap.Main(ctx.Context, secondPassConfig, false, extraNinjaDeps...)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400149 } else {
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500150 ctx = newContext(configuration)
Lukacs T. Berkid7ce8402021-03-17 14:03:51 +0100151 bootstrap.Main(ctx.Context, configuration, false, extraNinjaDeps...)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400152 }
Jingwen Chen4133ce62020-12-02 04:34:15 -0500153
154 // Convert the Soong module graph into Bazel BUILD files.
Jingwen Chen50f93d22020-11-05 07:42:11 -0500155 if bazelQueryViewDir != "" {
Jingwen Chen164e0862021-02-19 00:48:40 -0500156 // Run the code-generation phase to convert BazelTargetModules to BUILD files.
157 codegenContext := bp2build.NewCodegenContext(configuration, *ctx, bp2build.QueryView)
Lukacs T. Berki47a9d0c2021-03-08 16:34:09 +0100158 absoluteQueryViewDir := shared.JoinPath(topDir, bazelQueryViewDir)
159 if err := createBazelQueryView(codegenContext, absoluteQueryViewDir); err != nil {
Jingwen Chen5ba7e472020-07-15 10:06:41 +0000160 fmt.Fprintf(os.Stderr, "%s", err)
161 os.Exit(1)
162 }
163 }
164
Colin Crosse87040b2017-12-11 15:52:26 -0800165 if docFile != "" {
Lukacs T. Berki89e9a162021-03-12 08:31:32 +0100166 if err := writeDocs(ctx, configuration, docFile); err != nil {
Colin Cross7089c272019-01-25 22:43:35 -0800167 fmt.Fprintf(os.Stderr, "%s", err)
168 os.Exit(1)
169 }
Colin Crosse87040b2017-12-11 15:52:26 -0800170 }
Colin Crossb72c9092020-02-10 11:23:49 -0800171
172 // TODO(ccross): make this a command line argument. Requires plumbing through blueprint
173 // to affect the command line of the primary builder.
Jingwen Chen4133ce62020-12-02 04:34:15 -0500174 if shouldPrepareBuildActions(configuration) {
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100175 metricsFile := filepath.Join(bootstrap.CmdlineBuildDir(), "soong_build_metrics.pb")
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400176 err := android.WriteMetrics(configuration, metricsFile)
Colin Crossb72c9092020-02-10 11:23:49 -0800177 if err != nil {
178 fmt.Fprintf(os.Stderr, "error writing soong_build metrics %s: %s", metricsFile, err)
179 os.Exit(1)
180 }
181 }
Colin Cross3f40fa42015-01-30 17:27:36 -0800182}
Jingwen Chen5ba7e472020-07-15 10:06:41 +0000183
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500184// Run Soong in the bp2build mode. This creates a standalone context that registers
185// an alternate pipeline of mutators and singletons specifically for generating
186// Bazel BUILD files instead of Ninja files.
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500187func runBp2Build(srcDir string, configuration android.Config) {
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500188 // Register an alternate set of singletons and mutators for bazel
189 // conversion for Bazel conversion.
190 bp2buildCtx := android.NewContext(configuration)
191 bp2buildCtx.RegisterForBazelConversion()
Jingwen Cheneb76c432021-01-28 08:22:12 -0500192
193 // No need to generate Ninja build rules/statements from Modules and Singletons.
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500194 configuration.SetStopBefore(bootstrap.StopBeforePrepareBuildActions)
195 bp2buildCtx.SetNameInterface(newNameResolver(configuration))
Jingwen Cheneb76c432021-01-28 08:22:12 -0500196
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500197 // The bp2build process is a purely functional process that only depends on
198 // Android.bp files. It must not depend on the values of per-build product
199 // configurations or variables, since those will generate different BUILD
200 // files based on how the user has configured their tree.
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100201 bp2buildCtx.SetModuleListFile(bootstrap.CmdlineModuleListFile())
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500202 extraNinjaDeps, err := bp2buildCtx.ListModulePaths(srcDir)
203 if err != nil {
204 panic(err)
205 }
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500206
207 // Run the loading and analysis pipeline to prepare the graph of regular
208 // Modules parsed from Android.bp files, and the BazelTargetModules mapped
209 // from the regular Modules.
Lukacs T. Berkid7ce8402021-03-17 14:03:51 +0100210 bootstrap.Main(bp2buildCtx.Context, configuration, false, extraNinjaDeps...)
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500211
Jingwen Chen164e0862021-02-19 00:48:40 -0500212 // Run the code-generation phase to convert BazelTargetModules to BUILD files
213 // and print conversion metrics to the user.
Jingwen Chen33832f92021-01-24 22:55:54 -0500214 codegenContext := bp2build.NewCodegenContext(configuration, *bp2buildCtx, bp2build.Bp2Build)
Jingwen Chen164e0862021-02-19 00:48:40 -0500215 metrics := bp2build.Codegen(codegenContext)
216
217 // Only report metrics when in bp2build mode. The metrics aren't relevant
218 // for queryview, since that's a total repo-wide conversion and there's a
219 // 1:1 mapping for each module.
220 metrics.Print()
Jingwen Cheneb76c432021-01-28 08:22:12 -0500221
Liz Kammerba3ea162021-02-17 13:22:03 -0500222 extraNinjaDeps = append(extraNinjaDeps, codegenContext.AdditionalNinjaDeps()...)
223 extraNinjaDepsString := strings.Join(extraNinjaDeps, " \\\n ")
224
Jingwen Cheneb76c432021-01-28 08:22:12 -0500225 // Workarounds to support running bp2build in a clean AOSP checkout with no
226 // prior builds, and exiting early as soon as the BUILD files get generated,
227 // therefore not creating build.ninja files that soong_ui and callers of
228 // soong_build expects.
229 //
230 // These files are: build.ninja and build.ninja.d. Since Kati hasn't been
231 // ran as well, and `nothing` is defined in a .mk file, there isn't a ninja
232 // target called `nothing`, so we manually create it here.
233 //
234 // Even though outFile (build.ninja) and depFile (build.ninja.d) are values
235 // passed into bootstrap.Main, they are package-private fields in bootstrap.
236 // Short of modifying Blueprint to add an exported getter, inlining them
237 // here is the next-best practical option.
238 ninjaFileName := "build.ninja"
239 ninjaFile := android.PathForOutput(codegenContext, ninjaFileName)
240 ninjaFileD := android.PathForOutput(codegenContext, ninjaFileName+".d")
Jingwen Cheneb76c432021-01-28 08:22:12 -0500241 // A workaround to create the 'nothing' ninja target so `m nothing` works,
242 // since bp2build runs without Kati, and the 'nothing' target is declared in
243 // a Makefile.
244 android.WriteFileToOutputDir(ninjaFile, []byte("build nothing: phony\n phony_output = true\n"), 0666)
245 android.WriteFileToOutputDir(
246 ninjaFileD,
247 []byte(fmt.Sprintf("%s: \\\n %s\n", ninjaFileName, extraNinjaDepsString)),
248 0666)
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500249}
250
Jingwen Chen4133ce62020-12-02 04:34:15 -0500251// shouldPrepareBuildActions reads configuration and flags if build actions
252// should be generated.
253func shouldPrepareBuildActions(configuration android.Config) bool {
254 // Generating Soong docs
255 if docFile != "" {
256 return false
257 }
258
259 // Generating a directory for Soong query (queryview)
260 if bazelQueryViewDir != "" {
261 return false
262 }
263
264 // Generating a directory for converted Bazel BUILD files
265 return !bazelConversionRequested(configuration)
Jingwen Chen5ba7e472020-07-15 10:06:41 +0000266}