blob: d77a089ab111474ae38e37222a2a80cfde1f0462 [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. Berki7690c092021-02-26 14:27:36 +010024
Colin Crossb72c9092020-02-10 11:23:49 -080025 soong_metrics_proto "android/soong/ui/metrics/metrics_proto"
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010026 "github.com/google/blueprint"
27 "github.com/google/blueprint/bootstrap"
Colin Crossb72c9092020-02-10 11:23:49 -080028
29 "github.com/golang/protobuf/proto"
Dan Willemsen99a75cd2017-08-04 16:04:04 -070030 "github.com/google/blueprint/microfactory"
Dan Willemsenb82471a2018-05-17 16:37:09 -070031
Nan Zhang17f27672018-12-12 16:01:49 -080032 "android/soong/ui/metrics"
Dan Willemsenb82471a2018-05-17 16:37:09 -070033 "android/soong/ui/status"
Dan Willemsen1e704462016-08-21 15:17:17 -070034)
35
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020036const (
37 availableEnvFile = "soong.environment.available"
38 usedEnvFile = "soong.environment.used"
39)
40
Lukacs T. Berki7690c092021-02-26 14:27:36 +010041func writeEnvironmentFile(ctx Context, envFile string, envDeps map[string]string) error {
42 data, err := shared.EnvFileContents(envDeps)
43 if err != nil {
44 return err
45 }
46
47 return ioutil.WriteFile(envFile, data, 0644)
48}
49
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000050// This uses Android.bp files and various tools to generate <builddir>/build.ninja.
51//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010052// However, the execution of <builddir>/build.ninja happens later in
53// build/soong/ui/build/build.go#Build()
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000054//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010055// We want to rely on as few prebuilts as possible, so we need to bootstrap
56// Soong. The process is as follows:
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000057//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010058// 1. We use "Microfactory", a simple tool to compile Go code, to build
59// first itself, then soong_ui from soong_ui.bash. This binary contains
60// parts of soong_build that are needed to build itself.
61// 2. This simplified version of soong_build then reads the Blueprint files
62// that describe itself and emits .bootstrap/build.ninja that describes
63// how to build its full version and use that to produce the final Ninja
64// file Soong emits.
65// 3. soong_ui executes .bootstrap/build.ninja
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000066//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010067// (After this, Kati is executed to parse the Makefiles, but that's not part of
68// bootstrapping Soong)
69
70// A tiny struct used to tell Blueprint that it's in bootstrap mode. It would
71// probably be nicer to use a flag in bootstrap.Args instead.
72type BlueprintConfig struct {
Lukacs T. Berki5f6cb1d2021-03-17 15:03:14 +010073 srcDir string
74 buildDir string
75 ninjaBuildDir string
76 debugCompilation bool
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010077}
78
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010079func (c BlueprintConfig) SrcDir() string {
80 return "."
81}
82
83func (c BlueprintConfig) BuildDir() string {
84 return c.buildDir
85}
86
87func (c BlueprintConfig) NinjaBuildDir() string {
88 return c.ninjaBuildDir
89}
90
Lukacs T. Berki5f6cb1d2021-03-17 15:03:14 +010091func (c BlueprintConfig) DebugCompilation() bool {
92 return c.debugCompilation
93}
94
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020095func environmentArgs(config Config, suffix string) []string {
96 return []string{
97 "--available_env", shared.JoinPath(config.SoongOutDir(), availableEnvFile),
98 "--used_env", shared.JoinPath(config.SoongOutDir(), usedEnvFile+suffix),
99 }
100}
101func bootstrapBlueprint(ctx Context, config Config, integratedBp2Build bool) {
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100102 ctx.BeginTrace(metrics.RunSoong, "blueprint bootstrap")
103 defer ctx.EndTrace()
104
105 var args bootstrap.Args
106
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200107 mainNinjaFile := shared.JoinPath(config.SoongOutDir(), "build.ninja")
108 globFile := shared.JoinPath(config.SoongOutDir(), ".bootstrap/soong-build-globs.ninja")
109 bootstrapGlobFile := shared.JoinPath(config.SoongOutDir(), ".bootstrap/build-globs.ninja")
110
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100111 args.RunGoTests = !config.skipSoongTests
112 args.UseValidations = true // Use validations to depend on tests
113 args.BuildDir = config.SoongOutDir()
114 args.NinjaBuildDir = config.OutDir()
115 args.TopFile = "Android.bp"
116 args.ModuleListFile = filepath.Join(config.FileListDir(), "Android.bp.list")
117 args.OutFile = shared.JoinPath(config.SoongOutDir(), ".bootstrap/build.ninja")
118 args.DepFile = shared.JoinPath(config.SoongOutDir(), ".bootstrap/build.ninja.d")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200119 args.GlobFile = globFile
Lukacs T. Berkid7ce8402021-03-17 14:03:51 +0100120 args.GeneratingPrimaryBuilder = true
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100121
Lukacs T. Berki745380c2021-04-12 12:07:44 +0200122 args.DelveListen = os.Getenv("SOONG_DELVE")
123 if args.DelveListen != "" {
124 args.DelvePath = shared.ResolveDelveBinary()
125 }
126
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200127 commonArgs := bootstrap.PrimaryBuilderExtraFlags(args, bootstrapGlobFile, mainNinjaFile)
128 bp2BuildMarkerFile := shared.JoinPath(config.SoongOutDir(), ".bootstrap/bp2build_workspace_marker")
129 mainSoongBuildInputs := []string{"Android.bp"}
130
131 if integratedBp2Build {
132 mainSoongBuildInputs = append(mainSoongBuildInputs, bp2BuildMarkerFile)
133 }
134
135 soongBuildArgs := make([]string, 0)
136 soongBuildArgs = append(soongBuildArgs, commonArgs...)
137 soongBuildArgs = append(soongBuildArgs, environmentArgs(config, "")...)
138 soongBuildArgs = append(soongBuildArgs, "Android.bp")
139
140 mainSoongBuildInvocation := bootstrap.PrimaryBuilderInvocation{
141 Inputs: mainSoongBuildInputs,
142 Outputs: []string{mainNinjaFile},
143 Args: soongBuildArgs,
144 }
145
146 if integratedBp2Build {
147 bp2buildArgs := []string{"--bp2build_marker", bp2BuildMarkerFile}
148 bp2buildArgs = append(bp2buildArgs, commonArgs...)
149 bp2buildArgs = append(bp2buildArgs, environmentArgs(config, ".bp2build")...)
150 bp2buildArgs = append(bp2buildArgs, "Android.bp")
151
152 bp2buildInvocation := bootstrap.PrimaryBuilderInvocation{
153 Inputs: []string{"Android.bp"},
154 Outputs: []string{bp2BuildMarkerFile},
155 Args: bp2buildArgs,
156 }
157 args.PrimaryBuilderInvocations = []bootstrap.PrimaryBuilderInvocation{
158 bp2buildInvocation,
159 mainSoongBuildInvocation,
160 }
161 } else {
162 args.PrimaryBuilderInvocations = []bootstrap.PrimaryBuilderInvocation{mainSoongBuildInvocation}
163 }
164
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100165 blueprintCtx := blueprint.NewContext()
166 blueprintCtx.SetIgnoreUnknownModuleTypes(true)
167 blueprintConfig := BlueprintConfig{
Lukacs T. Berki5f6cb1d2021-03-17 15:03:14 +0100168 srcDir: os.Getenv("TOP"),
169 buildDir: config.SoongOutDir(),
170 ninjaBuildDir: config.OutDir(),
171 debugCompilation: os.Getenv("SOONG_DELVE") != "",
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100172 }
173
174 bootstrap.RunBlueprint(args, blueprintCtx, blueprintConfig)
175}
176
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200177func checkEnvironmentFile(currentEnv *Environment, envFile string) {
178 getenv := func(k string) string {
179 v, _ := currentEnv.Get(k)
180 return v
181 }
182 if stale, _ := shared.StaleEnvFile(envFile, getenv); stale {
183 os.Remove(envFile)
184 }
185}
186
Dan Willemsen1e704462016-08-21 15:17:17 -0700187func runSoong(ctx Context, config Config) {
Nan Zhang17f27672018-12-12 16:01:49 -0800188 ctx.BeginTrace(metrics.RunSoong, "soong")
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700189 defer ctx.EndTrace()
190
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100191 // We have two environment files: .available is the one with every variable,
192 // .used with the ones that were actually used. The latter is used to
193 // determine whether Soong needs to be re-run since why re-run it if only
194 // unused variables were changed?
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200195 envFile := filepath.Join(config.SoongOutDir(), availableEnvFile)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100196
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100197 for _, n := range []string{".bootstrap", ".minibootstrap"} {
198 dir := filepath.Join(config.SoongOutDir(), n)
199 if err := os.MkdirAll(dir, 0755); err != nil {
200 ctx.Fatalf("Cannot mkdir " + dir)
Colin Cross00a8a3f2020-10-29 14:08:31 -0700201 }
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100202 }
Colin Cross00a8a3f2020-10-29 14:08:31 -0700203
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200204 integratedBp2Build := config.Environment().IsEnvTrue("INTEGRATED_BP2BUILD")
205
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100206 // This is done unconditionally, but does not take a measurable amount of time
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200207 bootstrapBlueprint(ctx, config, integratedBp2Build)
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700208
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100209 soongBuildEnv := config.Environment().Copy()
210 soongBuildEnv.Set("TOP", os.Getenv("TOP"))
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100211 // For Bazel mixed builds.
212 soongBuildEnv.Set("BAZEL_PATH", "./tools/bazel")
213 soongBuildEnv.Set("BAZEL_HOME", filepath.Join(config.BazelOutDir(), "bazelhome"))
214 soongBuildEnv.Set("BAZEL_OUTPUT_BASE", filepath.Join(config.BazelOutDir(), "output"))
215 soongBuildEnv.Set("BAZEL_WORKSPACE", absPath(ctx, "."))
216 soongBuildEnv.Set("BAZEL_METRICS_DIR", config.BazelMetricsDir())
217
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100218 // For Soong bootstrapping tests
219 if os.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
220 soongBuildEnv.Set("ALLOW_MISSING_DEPENDENCIES", "true")
221 }
222
Paul Duffin5e85c662021-03-05 12:26:14 +0000223 err := writeEnvironmentFile(ctx, envFile, soongBuildEnv.AsMap())
224 if err != nil {
225 ctx.Fatalf("failed to write environment file %s: %s", envFile, err)
226 }
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100227
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700228 func() {
Nan Zhang17f27672018-12-12 16:01:49 -0800229 ctx.BeginTrace(metrics.RunSoong, "environment check")
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700230 defer ctx.EndTrace()
231
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200232 soongBuildEnvFile := filepath.Join(config.SoongOutDir(), usedEnvFile)
233 checkEnvironmentFile(soongBuildEnv, soongBuildEnvFile)
234
235 if integratedBp2Build {
236 bp2buildEnvFile := filepath.Join(config.SoongOutDir(), usedEnvFile+".bp2build")
237 checkEnvironmentFile(soongBuildEnv, bp2buildEnvFile)
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700238 }
239 }()
240
Dan Willemsen5af1cbe2018-07-05 21:46:51 -0700241 var cfg microfactory.Config
242 cfg.Map("github.com/google/blueprint", "build/blueprint")
243
244 cfg.TrimPath = absPath(ctx, ".")
245
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700246 func() {
Nan Zhang17f27672018-12-12 16:01:49 -0800247 ctx.BeginTrace(metrics.RunSoong, "bpglob")
Dan Willemsen5af1cbe2018-07-05 21:46:51 -0700248 defer ctx.EndTrace()
249
250 bpglob := filepath.Join(config.SoongOutDir(), ".minibootstrap/bpglob")
251 if _, err := microfactory.Build(&cfg, bpglob, "github.com/google/blueprint/bootstrap/bpglob"); err != nil {
252 ctx.Fatalln("Failed to build bpglob:", err)
253 }
254 }()
255
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700256 ninja := func(name, file string) {
Nan Zhang17f27672018-12-12 16:01:49 -0800257 ctx.BeginTrace(metrics.RunSoong, name)
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700258 defer ctx.EndTrace()
259
Dan Willemsenb82471a2018-05-17 16:37:09 -0700260 fifo := filepath.Join(config.OutDir(), ".ninja_fifo")
Colin Crossb98d3bc2019-03-21 16:02:58 -0700261 nr := status.NewNinjaReader(ctx, ctx.Status.StartTool(), fifo)
262 defer nr.Close()
Dan Willemsenb82471a2018-05-17 16:37:09 -0700263
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700264 cmd := Command(ctx, config, "soong "+name,
265 config.PrebuiltBuildTool("ninja"),
266 "-d", "keepdepfile",
Dan Willemsen08218222020-05-18 14:02:02 -0700267 "-d", "stats",
Dan Willemsen6587bed2020-04-18 20:25:59 -0700268 "-o", "usesphonyoutputs=yes",
269 "-o", "preremoveoutputs=yes",
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700270 "-w", "dupbuild=err",
Dan Willemsen6587bed2020-04-18 20:25:59 -0700271 "-w", "outputdir=err",
272 "-w", "missingoutfile=err",
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700273 "-j", strconv.Itoa(config.Parallel()),
Dan Willemsen02736672018-07-17 17:54:31 -0700274 "--frontend_file", fifo,
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700275 "-f", filepath.Join(config.SoongOutDir(), file))
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500276
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100277 var ninjaEnv Environment
Lukacs T. Berki73ab9282021-03-10 10:48:39 +0100278
279 // This is currently how the command line to invoke soong_build finds the
280 // root of the source tree and the output root
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100281 ninjaEnv.Set("TOP", os.Getenv("TOP"))
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100282
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100283 cmd.Environment = &ninjaEnv
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700284 cmd.Sandbox = soongSandbox
Colin Cross7b97ecd2019-06-19 13:17:59 -0700285 cmd.RunAndStreamOrFatal()
Dan Willemsen1e704462016-08-21 15:17:17 -0700286 }
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +0000287 // 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 -0700288 ninja("bootstrap", ".bootstrap/build.ninja")
Colin Crossb72c9092020-02-10 11:23:49 -0800289
Jingwen Cheneb76c432021-01-28 08:22:12 -0500290 var soongBuildMetrics *soong_metrics_proto.SoongBuildMetrics
291 if shouldCollectBuildSoongMetrics(config) {
292 soongBuildMetrics := loadSoongBuildMetrics(ctx, config)
293 logSoongBuildMetrics(ctx, soongBuildMetrics)
294 }
Colin Crossb72c9092020-02-10 11:23:49 -0800295
Colin Cross8ba7d472020-06-25 11:27:52 -0700296 distGzipFile(ctx, config, config.SoongNinjaFile(), "soong")
297
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000298 if !config.SkipKati() {
Colin Cross8ba7d472020-06-25 11:27:52 -0700299 distGzipFile(ctx, config, config.SoongAndroidMk(), "soong")
300 distGzipFile(ctx, config, config.SoongMakeVarsMk(), "soong")
301 }
302
Jingwen Cheneb76c432021-01-28 08:22:12 -0500303 if shouldCollectBuildSoongMetrics(config) && ctx.Metrics != nil {
Colin Crossb72c9092020-02-10 11:23:49 -0800304 ctx.Metrics.SetSoongBuildMetrics(soongBuildMetrics)
305 }
306}
307
Jingwen Cheneb76c432021-01-28 08:22:12 -0500308func shouldCollectBuildSoongMetrics(config Config) bool {
309 // Do not collect metrics protobuf if the soong_build binary ran as the bp2build converter.
310 return config.Environment().IsFalse("GENERATE_BAZEL_FILES")
311}
312
Colin Crossb72c9092020-02-10 11:23:49 -0800313func loadSoongBuildMetrics(ctx Context, config Config) *soong_metrics_proto.SoongBuildMetrics {
314 soongBuildMetricsFile := filepath.Join(config.OutDir(), "soong", "soong_build_metrics.pb")
315 buf, err := ioutil.ReadFile(soongBuildMetricsFile)
316 if err != nil {
317 ctx.Fatalf("Failed to load %s: %s", soongBuildMetricsFile, err)
318 }
319 soongBuildMetrics := &soong_metrics_proto.SoongBuildMetrics{}
320 err = proto.Unmarshal(buf, soongBuildMetrics)
321 if err != nil {
322 ctx.Fatalf("Failed to unmarshal %s: %s", soongBuildMetricsFile, err)
323 }
324 return soongBuildMetrics
325}
326
327func logSoongBuildMetrics(ctx Context, metrics *soong_metrics_proto.SoongBuildMetrics) {
328 ctx.Verbosef("soong_build metrics:")
329 ctx.Verbosef(" modules: %v", metrics.GetModules())
330 ctx.Verbosef(" variants: %v", metrics.GetVariants())
331 ctx.Verbosef(" max heap size: %v MB", metrics.GetMaxHeapSize()/1e6)
332 ctx.Verbosef(" total allocation count: %v", metrics.GetTotalAllocCount())
333 ctx.Verbosef(" total allocation size: %v MB", metrics.GetTotalAllocSize()/1e6)
334
Dan Willemsen1e704462016-08-21 15:17:17 -0700335}