blob: 712841465a7543aab7f501176f59bb5db2a496b4 [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
Colin Crossf3bdbcb2021-06-01 11:43:55 -0700122 args.EmptyNinjaFile = config.EmptyNinjaFile()
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100123
Lukacs T. Berki745380c2021-04-12 12:07:44 +0200124 args.DelveListen = os.Getenv("SOONG_DELVE")
125 if args.DelveListen != "" {
126 args.DelvePath = shared.ResolveDelveBinary()
127 }
128
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200129 commonArgs := bootstrap.PrimaryBuilderExtraFlags(args, bootstrapGlobFile, mainNinjaFile)
130 bp2BuildMarkerFile := shared.JoinPath(config.SoongOutDir(), ".bootstrap/bp2build_workspace_marker")
131 mainSoongBuildInputs := []string{"Android.bp"}
132
133 if integratedBp2Build {
134 mainSoongBuildInputs = append(mainSoongBuildInputs, bp2BuildMarkerFile)
135 }
136
137 soongBuildArgs := make([]string, 0)
138 soongBuildArgs = append(soongBuildArgs, commonArgs...)
139 soongBuildArgs = append(soongBuildArgs, environmentArgs(config, "")...)
140 soongBuildArgs = append(soongBuildArgs, "Android.bp")
141
142 mainSoongBuildInvocation := bootstrap.PrimaryBuilderInvocation{
143 Inputs: mainSoongBuildInputs,
144 Outputs: []string{mainNinjaFile},
145 Args: soongBuildArgs,
146 }
147
148 if integratedBp2Build {
149 bp2buildArgs := []string{"--bp2build_marker", bp2BuildMarkerFile}
150 bp2buildArgs = append(bp2buildArgs, commonArgs...)
151 bp2buildArgs = append(bp2buildArgs, environmentArgs(config, ".bp2build")...)
152 bp2buildArgs = append(bp2buildArgs, "Android.bp")
153
154 bp2buildInvocation := bootstrap.PrimaryBuilderInvocation{
155 Inputs: []string{"Android.bp"},
156 Outputs: []string{bp2BuildMarkerFile},
157 Args: bp2buildArgs,
158 }
Jingwen Chen4fabaf52021-05-25 02:40:29 +0000159 args.PrimaryBuilderInvocations = []bootstrap.PrimaryBuilderInvocation{bp2buildInvocation}
160 if config.bazelBuildMode() == mixedBuild {
161 args.PrimaryBuilderInvocations = append(args.PrimaryBuilderInvocations, mainSoongBuildInvocation)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200162 }
163 } else {
164 args.PrimaryBuilderInvocations = []bootstrap.PrimaryBuilderInvocation{mainSoongBuildInvocation}
165 }
166
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100167 blueprintCtx := blueprint.NewContext()
168 blueprintCtx.SetIgnoreUnknownModuleTypes(true)
169 blueprintConfig := BlueprintConfig{
Lukacs T. Berki5f6cb1d2021-03-17 15:03:14 +0100170 srcDir: os.Getenv("TOP"),
171 buildDir: config.SoongOutDir(),
172 ninjaBuildDir: config.OutDir(),
173 debugCompilation: os.Getenv("SOONG_DELVE") != "",
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100174 }
175
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200176 bootstrapDeps := bootstrap.RunBlueprint(args, blueprintCtx, blueprintConfig)
177 err := deptools.WriteDepFile(bootstrapDepFile, args.OutFile, bootstrapDeps)
178 if err != nil {
179 ctx.Fatalf("Error writing depfile '%s': %s", bootstrapDepFile, err)
180 }
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100181}
182
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200183func checkEnvironmentFile(currentEnv *Environment, envFile string) {
184 getenv := func(k string) string {
185 v, _ := currentEnv.Get(k)
186 return v
187 }
188 if stale, _ := shared.StaleEnvFile(envFile, getenv); stale {
189 os.Remove(envFile)
190 }
191}
192
Dan Willemsen1e704462016-08-21 15:17:17 -0700193func runSoong(ctx Context, config Config) {
Nan Zhang17f27672018-12-12 16:01:49 -0800194 ctx.BeginTrace(metrics.RunSoong, "soong")
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700195 defer ctx.EndTrace()
196
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100197 // We have two environment files: .available is the one with every variable,
198 // .used with the ones that were actually used. The latter is used to
199 // determine whether Soong needs to be re-run since why re-run it if only
200 // unused variables were changed?
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200201 envFile := filepath.Join(config.SoongOutDir(), availableEnvFile)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100202
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100203 for _, n := range []string{".bootstrap", ".minibootstrap"} {
204 dir := filepath.Join(config.SoongOutDir(), n)
205 if err := os.MkdirAll(dir, 0755); err != nil {
206 ctx.Fatalf("Cannot mkdir " + dir)
Colin Cross00a8a3f2020-10-29 14:08:31 -0700207 }
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100208 }
Colin Cross00a8a3f2020-10-29 14:08:31 -0700209
Chris Parsonsec1a3dc2021-04-20 15:32:07 -0400210 buildMode := config.bazelBuildMode()
211 integratedBp2Build := (buildMode == mixedBuild) || (buildMode == generateBuildFiles)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200212
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100213 // This is done unconditionally, but does not take a measurable amount of time
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200214 bootstrapBlueprint(ctx, config, integratedBp2Build)
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700215
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100216 soongBuildEnv := config.Environment().Copy()
217 soongBuildEnv.Set("TOP", os.Getenv("TOP"))
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100218 // For Bazel mixed builds.
219 soongBuildEnv.Set("BAZEL_PATH", "./tools/bazel")
220 soongBuildEnv.Set("BAZEL_HOME", filepath.Join(config.BazelOutDir(), "bazelhome"))
221 soongBuildEnv.Set("BAZEL_OUTPUT_BASE", filepath.Join(config.BazelOutDir(), "output"))
222 soongBuildEnv.Set("BAZEL_WORKSPACE", absPath(ctx, "."))
223 soongBuildEnv.Set("BAZEL_METRICS_DIR", config.BazelMetricsDir())
224
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100225 // For Soong bootstrapping tests
226 if os.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
227 soongBuildEnv.Set("ALLOW_MISSING_DEPENDENCIES", "true")
228 }
229
Paul Duffin5e85c662021-03-05 12:26:14 +0000230 err := writeEnvironmentFile(ctx, envFile, soongBuildEnv.AsMap())
231 if err != nil {
232 ctx.Fatalf("failed to write environment file %s: %s", envFile, err)
233 }
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100234
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700235 func() {
Nan Zhang17f27672018-12-12 16:01:49 -0800236 ctx.BeginTrace(metrics.RunSoong, "environment check")
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700237 defer ctx.EndTrace()
238
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200239 soongBuildEnvFile := filepath.Join(config.SoongOutDir(), usedEnvFile)
240 checkEnvironmentFile(soongBuildEnv, soongBuildEnvFile)
241
242 if integratedBp2Build {
243 bp2buildEnvFile := filepath.Join(config.SoongOutDir(), usedEnvFile+".bp2build")
244 checkEnvironmentFile(soongBuildEnv, bp2buildEnvFile)
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700245 }
246 }()
247
Dan Willemsen5af1cbe2018-07-05 21:46:51 -0700248 var cfg microfactory.Config
249 cfg.Map("github.com/google/blueprint", "build/blueprint")
250
251 cfg.TrimPath = absPath(ctx, ".")
252
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700253 func() {
Nan Zhang17f27672018-12-12 16:01:49 -0800254 ctx.BeginTrace(metrics.RunSoong, "bpglob")
Dan Willemsen5af1cbe2018-07-05 21:46:51 -0700255 defer ctx.EndTrace()
256
257 bpglob := filepath.Join(config.SoongOutDir(), ".minibootstrap/bpglob")
258 if _, err := microfactory.Build(&cfg, bpglob, "github.com/google/blueprint/bootstrap/bpglob"); err != nil {
259 ctx.Fatalln("Failed to build bpglob:", err)
260 }
261 }()
262
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700263 ninja := func(name, file string) {
Nan Zhang17f27672018-12-12 16:01:49 -0800264 ctx.BeginTrace(metrics.RunSoong, name)
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700265 defer ctx.EndTrace()
266
Dan Willemsenb82471a2018-05-17 16:37:09 -0700267 fifo := filepath.Join(config.OutDir(), ".ninja_fifo")
Colin Crossb98d3bc2019-03-21 16:02:58 -0700268 nr := status.NewNinjaReader(ctx, ctx.Status.StartTool(), fifo)
269 defer nr.Close()
Dan Willemsenb82471a2018-05-17 16:37:09 -0700270
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700271 cmd := Command(ctx, config, "soong "+name,
272 config.PrebuiltBuildTool("ninja"),
273 "-d", "keepdepfile",
Dan Willemsen08218222020-05-18 14:02:02 -0700274 "-d", "stats",
Dan Willemsen6587bed2020-04-18 20:25:59 -0700275 "-o", "usesphonyoutputs=yes",
276 "-o", "preremoveoutputs=yes",
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700277 "-w", "dupbuild=err",
Dan Willemsen6587bed2020-04-18 20:25:59 -0700278 "-w", "outputdir=err",
279 "-w", "missingoutfile=err",
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700280 "-j", strconv.Itoa(config.Parallel()),
Dan Willemsen02736672018-07-17 17:54:31 -0700281 "--frontend_file", fifo,
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700282 "-f", filepath.Join(config.SoongOutDir(), file))
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500283
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100284 var ninjaEnv Environment
Lukacs T. Berki73ab9282021-03-10 10:48:39 +0100285
286 // This is currently how the command line to invoke soong_build finds the
287 // root of the source tree and the output root
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100288 ninjaEnv.Set("TOP", os.Getenv("TOP"))
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100289
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100290 cmd.Environment = &ninjaEnv
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700291 cmd.Sandbox = soongSandbox
Colin Cross7b97ecd2019-06-19 13:17:59 -0700292 cmd.RunAndStreamOrFatal()
Dan Willemsen1e704462016-08-21 15:17:17 -0700293 }
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +0000294 // 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 -0700295 ninja("bootstrap", ".bootstrap/build.ninja")
Colin Crossb72c9092020-02-10 11:23:49 -0800296
Jingwen Cheneb76c432021-01-28 08:22:12 -0500297 var soongBuildMetrics *soong_metrics_proto.SoongBuildMetrics
298 if shouldCollectBuildSoongMetrics(config) {
299 soongBuildMetrics := loadSoongBuildMetrics(ctx, config)
300 logSoongBuildMetrics(ctx, soongBuildMetrics)
301 }
Colin Crossb72c9092020-02-10 11:23:49 -0800302
Colin Cross8ba7d472020-06-25 11:27:52 -0700303 distGzipFile(ctx, config, config.SoongNinjaFile(), "soong")
304
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000305 if !config.SkipKati() {
Colin Cross8ba7d472020-06-25 11:27:52 -0700306 distGzipFile(ctx, config, config.SoongAndroidMk(), "soong")
307 distGzipFile(ctx, config, config.SoongMakeVarsMk(), "soong")
308 }
309
Jingwen Cheneb76c432021-01-28 08:22:12 -0500310 if shouldCollectBuildSoongMetrics(config) && ctx.Metrics != nil {
Colin Crossb72c9092020-02-10 11:23:49 -0800311 ctx.Metrics.SetSoongBuildMetrics(soongBuildMetrics)
312 }
313}
314
Jingwen Cheneb76c432021-01-28 08:22:12 -0500315func shouldCollectBuildSoongMetrics(config Config) bool {
316 // Do not collect metrics protobuf if the soong_build binary ran as the bp2build converter.
Chris Parsonsec1a3dc2021-04-20 15:32:07 -0400317 return config.bazelBuildMode() != generateBuildFiles
Jingwen Cheneb76c432021-01-28 08:22:12 -0500318}
319
Colin Crossb72c9092020-02-10 11:23:49 -0800320func loadSoongBuildMetrics(ctx Context, config Config) *soong_metrics_proto.SoongBuildMetrics {
321 soongBuildMetricsFile := filepath.Join(config.OutDir(), "soong", "soong_build_metrics.pb")
322 buf, err := ioutil.ReadFile(soongBuildMetricsFile)
323 if err != nil {
324 ctx.Fatalf("Failed to load %s: %s", soongBuildMetricsFile, err)
325 }
326 soongBuildMetrics := &soong_metrics_proto.SoongBuildMetrics{}
327 err = proto.Unmarshal(buf, soongBuildMetrics)
328 if err != nil {
329 ctx.Fatalf("Failed to unmarshal %s: %s", soongBuildMetricsFile, err)
330 }
331 return soongBuildMetrics
332}
333
334func logSoongBuildMetrics(ctx Context, metrics *soong_metrics_proto.SoongBuildMetrics) {
335 ctx.Verbosef("soong_build metrics:")
336 ctx.Verbosef(" modules: %v", metrics.GetModules())
337 ctx.Verbosef(" variants: %v", metrics.GetVariants())
338 ctx.Verbosef(" max heap size: %v MB", metrics.GetMaxHeapSize()/1e6)
339 ctx.Verbosef(" total allocation count: %v", metrics.GetTotalAllocCount())
340 ctx.Verbosef(" total allocation size: %v MB", metrics.GetTotalAllocSize()/1e6)
341
Dan Willemsen1e704462016-08-21 15:17:17 -0700342}