blob: a41dbe1b54fdc5a05daa71647e0f083e505ae9e5 [file] [log] [blame]
Dan Willemsen1e704462016-08-21 15:17:17 -07001// Copyright 2017 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 build
16
17import (
Colin Crossb72c9092020-02-10 11:23:49 -080018 "io/ioutil"
Dan Willemsen99a75cd2017-08-04 16:04:04 -070019 "os"
Dan Willemsen1e704462016-08-21 15:17:17 -070020 "path/filepath"
Dan Willemsen99a75cd2017-08-04 16:04:04 -070021 "strconv"
Dan Willemsen99a75cd2017-08-04 16:04:04 -070022
Lukacs T. Berki3243aa52021-02-25 14:44:14 +010023 "android/soong/shared"
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +020024 "github.com/google/blueprint/deptools"
Lukacs T. Berki7690c092021-02-26 14:27:36 +010025
Colin Crossb72c9092020-02-10 11:23:49 -080026 soong_metrics_proto "android/soong/ui/metrics/metrics_proto"
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010027 "github.com/google/blueprint"
28 "github.com/google/blueprint/bootstrap"
Colin Crossb72c9092020-02-10 11:23:49 -080029
30 "github.com/golang/protobuf/proto"
Dan Willemsen99a75cd2017-08-04 16:04:04 -070031 "github.com/google/blueprint/microfactory"
Dan Willemsenb82471a2018-05-17 16:37:09 -070032
Nan Zhang17f27672018-12-12 16:01:49 -080033 "android/soong/ui/metrics"
Dan Willemsenb82471a2018-05-17 16:37:09 -070034 "android/soong/ui/status"
Dan Willemsen1e704462016-08-21 15:17:17 -070035)
36
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020037const (
38 availableEnvFile = "soong.environment.available"
39 usedEnvFile = "soong.environment.used"
40)
41
Lukacs T. Berki7690c092021-02-26 14:27:36 +010042func writeEnvironmentFile(ctx Context, envFile string, envDeps map[string]string) error {
43 data, err := shared.EnvFileContents(envDeps)
44 if err != nil {
45 return err
46 }
47
48 return ioutil.WriteFile(envFile, data, 0644)
49}
50
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000051// This uses Android.bp files and various tools to generate <builddir>/build.ninja.
52//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010053// However, the execution of <builddir>/build.ninja happens later in
54// build/soong/ui/build/build.go#Build()
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000055//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010056// We want to rely on as few prebuilts as possible, so we need to bootstrap
57// Soong. The process is as follows:
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000058//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010059// 1. We use "Microfactory", a simple tool to compile Go code, to build
60// first itself, then soong_ui from soong_ui.bash. This binary contains
61// parts of soong_build that are needed to build itself.
62// 2. This simplified version of soong_build then reads the Blueprint files
63// that describe itself and emits .bootstrap/build.ninja that describes
64// how to build its full version and use that to produce the final Ninja
65// file Soong emits.
66// 3. soong_ui executes .bootstrap/build.ninja
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000067//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010068// (After this, Kati is executed to parse the Makefiles, but that's not part of
69// bootstrapping Soong)
70
71// A tiny struct used to tell Blueprint that it's in bootstrap mode. It would
72// probably be nicer to use a flag in bootstrap.Args instead.
73type BlueprintConfig struct {
Lukacs T. Berki5f6cb1d2021-03-17 15:03:14 +010074 srcDir string
75 buildDir string
76 ninjaBuildDir string
77 debugCompilation bool
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010078}
79
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010080func (c BlueprintConfig) SrcDir() string {
81 return "."
82}
83
84func (c BlueprintConfig) BuildDir() string {
85 return c.buildDir
86}
87
88func (c BlueprintConfig) NinjaBuildDir() string {
89 return c.ninjaBuildDir
90}
91
Lukacs T. Berki5f6cb1d2021-03-17 15:03:14 +010092func (c BlueprintConfig) DebugCompilation() bool {
93 return c.debugCompilation
94}
95
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020096func environmentArgs(config Config, suffix string) []string {
97 return []string{
98 "--available_env", shared.JoinPath(config.SoongOutDir(), availableEnvFile),
99 "--used_env", shared.JoinPath(config.SoongOutDir(), usedEnvFile+suffix),
100 }
101}
102func bootstrapBlueprint(ctx Context, config Config, integratedBp2Build bool) {
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100103 ctx.BeginTrace(metrics.RunSoong, "blueprint bootstrap")
104 defer ctx.EndTrace()
105
106 var args bootstrap.Args
107
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200108 mainNinjaFile := shared.JoinPath(config.SoongOutDir(), "build.ninja")
109 globFile := shared.JoinPath(config.SoongOutDir(), ".bootstrap/soong-build-globs.ninja")
110 bootstrapGlobFile := shared.JoinPath(config.SoongOutDir(), ".bootstrap/build-globs.ninja")
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200111 bootstrapDepFile := shared.JoinPath(config.SoongOutDir(), ".bootstrap/build.ninja.d")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200112
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100113 args.RunGoTests = !config.skipSoongTests
114 args.UseValidations = true // Use validations to depend on tests
115 args.BuildDir = config.SoongOutDir()
116 args.NinjaBuildDir = config.OutDir()
117 args.TopFile = "Android.bp"
118 args.ModuleListFile = filepath.Join(config.FileListDir(), "Android.bp.list")
119 args.OutFile = shared.JoinPath(config.SoongOutDir(), ".bootstrap/build.ninja")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200120 args.GlobFile = globFile
Lukacs T. Berkid7ce8402021-03-17 14:03:51 +0100121 args.GeneratingPrimaryBuilder = true
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100122
Lukacs T. Berki745380c2021-04-12 12:07:44 +0200123 args.DelveListen = os.Getenv("SOONG_DELVE")
124 if args.DelveListen != "" {
125 args.DelvePath = shared.ResolveDelveBinary()
126 }
127
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200128 commonArgs := bootstrap.PrimaryBuilderExtraFlags(args, bootstrapGlobFile, mainNinjaFile)
129 bp2BuildMarkerFile := shared.JoinPath(config.SoongOutDir(), ".bootstrap/bp2build_workspace_marker")
130 mainSoongBuildInputs := []string{"Android.bp"}
131
132 if integratedBp2Build {
133 mainSoongBuildInputs = append(mainSoongBuildInputs, bp2BuildMarkerFile)
134 }
135
136 soongBuildArgs := make([]string, 0)
137 soongBuildArgs = append(soongBuildArgs, commonArgs...)
138 soongBuildArgs = append(soongBuildArgs, environmentArgs(config, "")...)
139 soongBuildArgs = append(soongBuildArgs, "Android.bp")
140
141 mainSoongBuildInvocation := bootstrap.PrimaryBuilderInvocation{
142 Inputs: mainSoongBuildInputs,
143 Outputs: []string{mainNinjaFile},
144 Args: soongBuildArgs,
145 }
146
147 if integratedBp2Build {
148 bp2buildArgs := []string{"--bp2build_marker", bp2BuildMarkerFile}
149 bp2buildArgs = append(bp2buildArgs, commonArgs...)
150 bp2buildArgs = append(bp2buildArgs, environmentArgs(config, ".bp2build")...)
151 bp2buildArgs = append(bp2buildArgs, "Android.bp")
152
153 bp2buildInvocation := bootstrap.PrimaryBuilderInvocation{
154 Inputs: []string{"Android.bp"},
155 Outputs: []string{bp2BuildMarkerFile},
156 Args: bp2buildArgs,
157 }
158 args.PrimaryBuilderInvocations = []bootstrap.PrimaryBuilderInvocation{
159 bp2buildInvocation,
160 mainSoongBuildInvocation,
161 }
162 } else {
163 args.PrimaryBuilderInvocations = []bootstrap.PrimaryBuilderInvocation{mainSoongBuildInvocation}
164 }
165
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100166 blueprintCtx := blueprint.NewContext()
167 blueprintCtx.SetIgnoreUnknownModuleTypes(true)
168 blueprintConfig := BlueprintConfig{
Lukacs T. Berki5f6cb1d2021-03-17 15:03:14 +0100169 srcDir: os.Getenv("TOP"),
170 buildDir: config.SoongOutDir(),
171 ninjaBuildDir: config.OutDir(),
172 debugCompilation: os.Getenv("SOONG_DELVE") != "",
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100173 }
174
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200175 bootstrapDeps := bootstrap.RunBlueprint(args, blueprintCtx, blueprintConfig)
176 err := deptools.WriteDepFile(bootstrapDepFile, args.OutFile, bootstrapDeps)
177 if err != nil {
178 ctx.Fatalf("Error writing depfile '%s': %s", bootstrapDepFile, err)
179 }
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100180}
181
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200182func checkEnvironmentFile(currentEnv *Environment, envFile string) {
183 getenv := func(k string) string {
184 v, _ := currentEnv.Get(k)
185 return v
186 }
187 if stale, _ := shared.StaleEnvFile(envFile, getenv); stale {
188 os.Remove(envFile)
189 }
190}
191
Dan Willemsen1e704462016-08-21 15:17:17 -0700192func runSoong(ctx Context, config Config) {
Nan Zhang17f27672018-12-12 16:01:49 -0800193 ctx.BeginTrace(metrics.RunSoong, "soong")
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700194 defer ctx.EndTrace()
195
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100196 // We have two environment files: .available is the one with every variable,
197 // .used with the ones that were actually used. The latter is used to
198 // determine whether Soong needs to be re-run since why re-run it if only
199 // unused variables were changed?
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200200 envFile := filepath.Join(config.SoongOutDir(), availableEnvFile)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100201
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100202 for _, n := range []string{".bootstrap", ".minibootstrap"} {
203 dir := filepath.Join(config.SoongOutDir(), n)
204 if err := os.MkdirAll(dir, 0755); err != nil {
205 ctx.Fatalf("Cannot mkdir " + dir)
Colin Cross00a8a3f2020-10-29 14:08:31 -0700206 }
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100207 }
Colin Cross00a8a3f2020-10-29 14:08:31 -0700208
Chris Parsonsec1a3dc2021-04-20 15:32:07 -0400209 buildMode := config.bazelBuildMode()
210 integratedBp2Build := (buildMode == mixedBuild) || (buildMode == generateBuildFiles)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200211
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100212 // This is done unconditionally, but does not take a measurable amount of time
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200213 bootstrapBlueprint(ctx, config, integratedBp2Build)
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700214
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100215 soongBuildEnv := config.Environment().Copy()
216 soongBuildEnv.Set("TOP", os.Getenv("TOP"))
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100217 // For Bazel mixed builds.
218 soongBuildEnv.Set("BAZEL_PATH", "./tools/bazel")
219 soongBuildEnv.Set("BAZEL_HOME", filepath.Join(config.BazelOutDir(), "bazelhome"))
220 soongBuildEnv.Set("BAZEL_OUTPUT_BASE", filepath.Join(config.BazelOutDir(), "output"))
221 soongBuildEnv.Set("BAZEL_WORKSPACE", absPath(ctx, "."))
222 soongBuildEnv.Set("BAZEL_METRICS_DIR", config.BazelMetricsDir())
223
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100224 // For Soong bootstrapping tests
225 if os.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
226 soongBuildEnv.Set("ALLOW_MISSING_DEPENDENCIES", "true")
227 }
228
Paul Duffin5e85c662021-03-05 12:26:14 +0000229 err := writeEnvironmentFile(ctx, envFile, soongBuildEnv.AsMap())
230 if err != nil {
231 ctx.Fatalf("failed to write environment file %s: %s", envFile, err)
232 }
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100233
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700234 func() {
Nan Zhang17f27672018-12-12 16:01:49 -0800235 ctx.BeginTrace(metrics.RunSoong, "environment check")
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700236 defer ctx.EndTrace()
237
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200238 soongBuildEnvFile := filepath.Join(config.SoongOutDir(), usedEnvFile)
239 checkEnvironmentFile(soongBuildEnv, soongBuildEnvFile)
240
241 if integratedBp2Build {
242 bp2buildEnvFile := filepath.Join(config.SoongOutDir(), usedEnvFile+".bp2build")
243 checkEnvironmentFile(soongBuildEnv, bp2buildEnvFile)
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700244 }
245 }()
246
Dan Willemsen5af1cbe2018-07-05 21:46:51 -0700247 var cfg microfactory.Config
248 cfg.Map("github.com/google/blueprint", "build/blueprint")
249
250 cfg.TrimPath = absPath(ctx, ".")
251
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700252 func() {
Nan Zhang17f27672018-12-12 16:01:49 -0800253 ctx.BeginTrace(metrics.RunSoong, "bpglob")
Dan Willemsen5af1cbe2018-07-05 21:46:51 -0700254 defer ctx.EndTrace()
255
256 bpglob := filepath.Join(config.SoongOutDir(), ".minibootstrap/bpglob")
257 if _, err := microfactory.Build(&cfg, bpglob, "github.com/google/blueprint/bootstrap/bpglob"); err != nil {
258 ctx.Fatalln("Failed to build bpglob:", err)
259 }
260 }()
261
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700262 ninja := func(name, file string) {
Nan Zhang17f27672018-12-12 16:01:49 -0800263 ctx.BeginTrace(metrics.RunSoong, name)
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700264 defer ctx.EndTrace()
265
Dan Willemsenb82471a2018-05-17 16:37:09 -0700266 fifo := filepath.Join(config.OutDir(), ".ninja_fifo")
Colin Crossb98d3bc2019-03-21 16:02:58 -0700267 nr := status.NewNinjaReader(ctx, ctx.Status.StartTool(), fifo)
268 defer nr.Close()
Dan Willemsenb82471a2018-05-17 16:37:09 -0700269
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700270 cmd := Command(ctx, config, "soong "+name,
271 config.PrebuiltBuildTool("ninja"),
272 "-d", "keepdepfile",
Dan Willemsen08218222020-05-18 14:02:02 -0700273 "-d", "stats",
Dan Willemsen6587bed2020-04-18 20:25:59 -0700274 "-o", "usesphonyoutputs=yes",
275 "-o", "preremoveoutputs=yes",
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700276 "-w", "dupbuild=err",
Dan Willemsen6587bed2020-04-18 20:25:59 -0700277 "-w", "outputdir=err",
278 "-w", "missingoutfile=err",
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700279 "-j", strconv.Itoa(config.Parallel()),
Dan Willemsen02736672018-07-17 17:54:31 -0700280 "--frontend_file", fifo,
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700281 "-f", filepath.Join(config.SoongOutDir(), file))
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500282
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100283 var ninjaEnv Environment
Lukacs T. Berki73ab9282021-03-10 10:48:39 +0100284
285 // This is currently how the command line to invoke soong_build finds the
286 // root of the source tree and the output root
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100287 ninjaEnv.Set("TOP", os.Getenv("TOP"))
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100288
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100289 cmd.Environment = &ninjaEnv
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700290 cmd.Sandbox = soongSandbox
Colin Cross7b97ecd2019-06-19 13:17:59 -0700291 cmd.RunAndStreamOrFatal()
Dan Willemsen1e704462016-08-21 15:17:17 -0700292 }
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +0000293 // This build generates <builddir>/build.ninja, which is used later by build/soong/ui/build/build.go#Build().
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700294 ninja("bootstrap", ".bootstrap/build.ninja")
Colin Crossb72c9092020-02-10 11:23:49 -0800295
Jingwen Cheneb76c432021-01-28 08:22:12 -0500296 var soongBuildMetrics *soong_metrics_proto.SoongBuildMetrics
297 if shouldCollectBuildSoongMetrics(config) {
298 soongBuildMetrics := loadSoongBuildMetrics(ctx, config)
299 logSoongBuildMetrics(ctx, soongBuildMetrics)
300 }
Colin Crossb72c9092020-02-10 11:23:49 -0800301
Colin Cross8ba7d472020-06-25 11:27:52 -0700302 distGzipFile(ctx, config, config.SoongNinjaFile(), "soong")
303
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000304 if !config.SkipKati() {
Colin Cross8ba7d472020-06-25 11:27:52 -0700305 distGzipFile(ctx, config, config.SoongAndroidMk(), "soong")
306 distGzipFile(ctx, config, config.SoongMakeVarsMk(), "soong")
307 }
308
Jingwen Cheneb76c432021-01-28 08:22:12 -0500309 if shouldCollectBuildSoongMetrics(config) && ctx.Metrics != nil {
Colin Crossb72c9092020-02-10 11:23:49 -0800310 ctx.Metrics.SetSoongBuildMetrics(soongBuildMetrics)
311 }
312}
313
Jingwen Cheneb76c432021-01-28 08:22:12 -0500314func shouldCollectBuildSoongMetrics(config Config) bool {
315 // Do not collect metrics protobuf if the soong_build binary ran as the bp2build converter.
Chris Parsonsec1a3dc2021-04-20 15:32:07 -0400316 return config.bazelBuildMode() != generateBuildFiles
Jingwen Cheneb76c432021-01-28 08:22:12 -0500317}
318
Colin Crossb72c9092020-02-10 11:23:49 -0800319func loadSoongBuildMetrics(ctx Context, config Config) *soong_metrics_proto.SoongBuildMetrics {
320 soongBuildMetricsFile := filepath.Join(config.OutDir(), "soong", "soong_build_metrics.pb")
321 buf, err := ioutil.ReadFile(soongBuildMetricsFile)
322 if err != nil {
323 ctx.Fatalf("Failed to load %s: %s", soongBuildMetricsFile, err)
324 }
325 soongBuildMetrics := &soong_metrics_proto.SoongBuildMetrics{}
326 err = proto.Unmarshal(buf, soongBuildMetrics)
327 if err != nil {
328 ctx.Fatalf("Failed to unmarshal %s: %s", soongBuildMetricsFile, err)
329 }
330 return soongBuildMetrics
331}
332
333func logSoongBuildMetrics(ctx Context, metrics *soong_metrics_proto.SoongBuildMetrics) {
334 ctx.Verbosef("soong_build metrics:")
335 ctx.Verbosef(" modules: %v", metrics.GetModules())
336 ctx.Verbosef(" variants: %v", metrics.GetVariants())
337 ctx.Verbosef(" max heap size: %v MB", metrics.GetMaxHeapSize()/1e6)
338 ctx.Verbosef(" total allocation count: %v", metrics.GetTotalAllocCount())
339 ctx.Verbosef(" total allocation size: %v MB", metrics.GetTotalAllocSize()/1e6)
340
Dan Willemsen1e704462016-08-21 15:17:17 -0700341}