blob: 0089075a42afebdc52d18c6aeca4300e0cf98054 [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. Berki7690c092021-02-26 14:27:36 +010036func writeEnvironmentFile(ctx Context, envFile string, envDeps map[string]string) error {
37 data, err := shared.EnvFileContents(envDeps)
38 if err != nil {
39 return err
40 }
41
42 return ioutil.WriteFile(envFile, data, 0644)
43}
44
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000045// This uses Android.bp files and various tools to generate <builddir>/build.ninja.
46//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010047// However, the execution of <builddir>/build.ninja happens later in
48// build/soong/ui/build/build.go#Build()
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000049//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010050// We want to rely on as few prebuilts as possible, so we need to bootstrap
51// Soong. The process is as follows:
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000052//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010053// 1. We use "Microfactory", a simple tool to compile Go code, to build
54// first itself, then soong_ui from soong_ui.bash. This binary contains
55// parts of soong_build that are needed to build itself.
56// 2. This simplified version of soong_build then reads the Blueprint files
57// that describe itself and emits .bootstrap/build.ninja that describes
58// how to build its full version and use that to produce the final Ninja
59// file Soong emits.
60// 3. soong_ui executes .bootstrap/build.ninja
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000061//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010062// (After this, Kati is executed to parse the Makefiles, but that's not part of
63// bootstrapping Soong)
64
65// A tiny struct used to tell Blueprint that it's in bootstrap mode. It would
66// probably be nicer to use a flag in bootstrap.Args instead.
67type BlueprintConfig struct {
Lukacs T. Berki5f6cb1d2021-03-17 15:03:14 +010068 srcDir string
69 buildDir string
70 ninjaBuildDir string
71 debugCompilation bool
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010072}
73
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010074func (c BlueprintConfig) SrcDir() string {
75 return "."
76}
77
78func (c BlueprintConfig) BuildDir() string {
79 return c.buildDir
80}
81
82func (c BlueprintConfig) NinjaBuildDir() string {
83 return c.ninjaBuildDir
84}
85
Lukacs T. Berki5f6cb1d2021-03-17 15:03:14 +010086func (c BlueprintConfig) DebugCompilation() bool {
87 return c.debugCompilation
88}
89
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010090func bootstrapBlueprint(ctx Context, config Config) {
91 ctx.BeginTrace(metrics.RunSoong, "blueprint bootstrap")
92 defer ctx.EndTrace()
93
94 var args bootstrap.Args
95
96 args.RunGoTests = !config.skipSoongTests
97 args.UseValidations = true // Use validations to depend on tests
98 args.BuildDir = config.SoongOutDir()
99 args.NinjaBuildDir = config.OutDir()
100 args.TopFile = "Android.bp"
101 args.ModuleListFile = filepath.Join(config.FileListDir(), "Android.bp.list")
102 args.OutFile = shared.JoinPath(config.SoongOutDir(), ".bootstrap/build.ninja")
103 args.DepFile = shared.JoinPath(config.SoongOutDir(), ".bootstrap/build.ninja.d")
104 args.GlobFile = shared.JoinPath(config.SoongOutDir(), ".bootstrap/soong-build-globs.ninja")
Lukacs T. Berkid7ce8402021-03-17 14:03:51 +0100105 args.GeneratingPrimaryBuilder = true
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100106
Lukacs T. Berki745380c2021-04-12 12:07:44 +0200107 args.DelveListen = os.Getenv("SOONG_DELVE")
108 if args.DelveListen != "" {
109 args.DelvePath = shared.ResolveDelveBinary()
110 }
111
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100112 blueprintCtx := blueprint.NewContext()
113 blueprintCtx.SetIgnoreUnknownModuleTypes(true)
114 blueprintConfig := BlueprintConfig{
Lukacs T. Berki5f6cb1d2021-03-17 15:03:14 +0100115 srcDir: os.Getenv("TOP"),
116 buildDir: config.SoongOutDir(),
117 ninjaBuildDir: config.OutDir(),
118 debugCompilation: os.Getenv("SOONG_DELVE") != "",
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100119 }
120
121 bootstrap.RunBlueprint(args, blueprintCtx, blueprintConfig)
122}
123
Dan Willemsen1e704462016-08-21 15:17:17 -0700124func runSoong(ctx Context, config Config) {
Nan Zhang17f27672018-12-12 16:01:49 -0800125 ctx.BeginTrace(metrics.RunSoong, "soong")
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700126 defer ctx.EndTrace()
127
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100128 // We have two environment files: .available is the one with every variable,
129 // .used with the ones that were actually used. The latter is used to
130 // determine whether Soong needs to be re-run since why re-run it if only
131 // unused variables were changed?
132 envFile := filepath.Join(config.SoongOutDir(), "soong.environment.available")
133
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100134 for _, n := range []string{".bootstrap", ".minibootstrap"} {
135 dir := filepath.Join(config.SoongOutDir(), n)
136 if err := os.MkdirAll(dir, 0755); err != nil {
137 ctx.Fatalf("Cannot mkdir " + dir)
Colin Cross00a8a3f2020-10-29 14:08:31 -0700138 }
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100139 }
Colin Cross00a8a3f2020-10-29 14:08:31 -0700140
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100141 // This is done unconditionally, but does not take a measurable amount of time
142 bootstrapBlueprint(ctx, config)
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700143
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100144 soongBuildEnv := config.Environment().Copy()
145 soongBuildEnv.Set("TOP", os.Getenv("TOP"))
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100146 // For Bazel mixed builds.
147 soongBuildEnv.Set("BAZEL_PATH", "./tools/bazel")
148 soongBuildEnv.Set("BAZEL_HOME", filepath.Join(config.BazelOutDir(), "bazelhome"))
149 soongBuildEnv.Set("BAZEL_OUTPUT_BASE", filepath.Join(config.BazelOutDir(), "output"))
150 soongBuildEnv.Set("BAZEL_WORKSPACE", absPath(ctx, "."))
151 soongBuildEnv.Set("BAZEL_METRICS_DIR", config.BazelMetricsDir())
152
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100153 // For Soong bootstrapping tests
154 if os.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
155 soongBuildEnv.Set("ALLOW_MISSING_DEPENDENCIES", "true")
156 }
157
Paul Duffin5e85c662021-03-05 12:26:14 +0000158 err := writeEnvironmentFile(ctx, envFile, soongBuildEnv.AsMap())
159 if err != nil {
160 ctx.Fatalf("failed to write environment file %s: %s", envFile, err)
161 }
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100162
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700163 func() {
Nan Zhang17f27672018-12-12 16:01:49 -0800164 ctx.BeginTrace(metrics.RunSoong, "environment check")
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700165 defer ctx.EndTrace()
166
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100167 envFile := filepath.Join(config.SoongOutDir(), "soong.environment.used")
Lukacs T. Berki3243aa52021-02-25 14:44:14 +0100168 getenv := func(k string) string {
Lukacs T. Berkib4ced9d2021-03-10 15:43:06 +0100169 v, _ := soongBuildEnv.Get(k)
Lukacs T. Berki3243aa52021-02-25 14:44:14 +0100170 return v
171 }
172 if stale, _ := shared.StaleEnvFile(envFile, getenv); stale {
173 os.Remove(envFile)
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700174 }
175 }()
176
Dan Willemsen5af1cbe2018-07-05 21:46:51 -0700177 var cfg microfactory.Config
178 cfg.Map("github.com/google/blueprint", "build/blueprint")
179
180 cfg.TrimPath = absPath(ctx, ".")
181
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700182 func() {
Nan Zhang17f27672018-12-12 16:01:49 -0800183 ctx.BeginTrace(metrics.RunSoong, "bpglob")
Dan Willemsen5af1cbe2018-07-05 21:46:51 -0700184 defer ctx.EndTrace()
185
186 bpglob := filepath.Join(config.SoongOutDir(), ".minibootstrap/bpglob")
187 if _, err := microfactory.Build(&cfg, bpglob, "github.com/google/blueprint/bootstrap/bpglob"); err != nil {
188 ctx.Fatalln("Failed to build bpglob:", err)
189 }
190 }()
191
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700192 ninja := func(name, file string) {
Nan Zhang17f27672018-12-12 16:01:49 -0800193 ctx.BeginTrace(metrics.RunSoong, name)
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700194 defer ctx.EndTrace()
195
Dan Willemsenb82471a2018-05-17 16:37:09 -0700196 fifo := filepath.Join(config.OutDir(), ".ninja_fifo")
Colin Crossb98d3bc2019-03-21 16:02:58 -0700197 nr := status.NewNinjaReader(ctx, ctx.Status.StartTool(), fifo)
198 defer nr.Close()
Dan Willemsenb82471a2018-05-17 16:37:09 -0700199
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700200 cmd := Command(ctx, config, "soong "+name,
201 config.PrebuiltBuildTool("ninja"),
202 "-d", "keepdepfile",
Dan Willemsen08218222020-05-18 14:02:02 -0700203 "-d", "stats",
Dan Willemsen6587bed2020-04-18 20:25:59 -0700204 "-o", "usesphonyoutputs=yes",
205 "-o", "preremoveoutputs=yes",
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700206 "-w", "dupbuild=err",
Dan Willemsen6587bed2020-04-18 20:25:59 -0700207 "-w", "outputdir=err",
208 "-w", "missingoutfile=err",
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700209 "-j", strconv.Itoa(config.Parallel()),
Dan Willemsen02736672018-07-17 17:54:31 -0700210 "--frontend_file", fifo,
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700211 "-f", filepath.Join(config.SoongOutDir(), file))
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500212
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100213 var ninjaEnv Environment
Lukacs T. Berki73ab9282021-03-10 10:48:39 +0100214
215 // This is currently how the command line to invoke soong_build finds the
216 // root of the source tree and the output root
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100217 ninjaEnv.Set("TOP", os.Getenv("TOP"))
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100218
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100219 cmd.Environment = &ninjaEnv
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700220 cmd.Sandbox = soongSandbox
Colin Cross7b97ecd2019-06-19 13:17:59 -0700221 cmd.RunAndStreamOrFatal()
Dan Willemsen1e704462016-08-21 15:17:17 -0700222 }
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +0000223 // 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 -0700224 ninja("bootstrap", ".bootstrap/build.ninja")
Colin Crossb72c9092020-02-10 11:23:49 -0800225
Jingwen Cheneb76c432021-01-28 08:22:12 -0500226 var soongBuildMetrics *soong_metrics_proto.SoongBuildMetrics
227 if shouldCollectBuildSoongMetrics(config) {
228 soongBuildMetrics := loadSoongBuildMetrics(ctx, config)
229 logSoongBuildMetrics(ctx, soongBuildMetrics)
230 }
Colin Crossb72c9092020-02-10 11:23:49 -0800231
Colin Cross8ba7d472020-06-25 11:27:52 -0700232 distGzipFile(ctx, config, config.SoongNinjaFile(), "soong")
233
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000234 if !config.SkipKati() {
Colin Cross8ba7d472020-06-25 11:27:52 -0700235 distGzipFile(ctx, config, config.SoongAndroidMk(), "soong")
236 distGzipFile(ctx, config, config.SoongMakeVarsMk(), "soong")
237 }
238
Jingwen Cheneb76c432021-01-28 08:22:12 -0500239 if shouldCollectBuildSoongMetrics(config) && ctx.Metrics != nil {
Colin Crossb72c9092020-02-10 11:23:49 -0800240 ctx.Metrics.SetSoongBuildMetrics(soongBuildMetrics)
241 }
242}
243
Jingwen Cheneb76c432021-01-28 08:22:12 -0500244func shouldCollectBuildSoongMetrics(config Config) bool {
245 // Do not collect metrics protobuf if the soong_build binary ran as the bp2build converter.
246 return config.Environment().IsFalse("GENERATE_BAZEL_FILES")
247}
248
Colin Crossb72c9092020-02-10 11:23:49 -0800249func loadSoongBuildMetrics(ctx Context, config Config) *soong_metrics_proto.SoongBuildMetrics {
250 soongBuildMetricsFile := filepath.Join(config.OutDir(), "soong", "soong_build_metrics.pb")
251 buf, err := ioutil.ReadFile(soongBuildMetricsFile)
252 if err != nil {
253 ctx.Fatalf("Failed to load %s: %s", soongBuildMetricsFile, err)
254 }
255 soongBuildMetrics := &soong_metrics_proto.SoongBuildMetrics{}
256 err = proto.Unmarshal(buf, soongBuildMetrics)
257 if err != nil {
258 ctx.Fatalf("Failed to unmarshal %s: %s", soongBuildMetricsFile, err)
259 }
260 return soongBuildMetrics
261}
262
263func logSoongBuildMetrics(ctx Context, metrics *soong_metrics_proto.SoongBuildMetrics) {
264 ctx.Verbosef("soong_build metrics:")
265 ctx.Verbosef(" modules: %v", metrics.GetModules())
266 ctx.Verbosef(" variants: %v", metrics.GetVariants())
267 ctx.Verbosef(" max heap size: %v MB", metrics.GetMaxHeapSize()/1e6)
268 ctx.Verbosef(" total allocation count: %v", metrics.GetTotalAllocCount())
269 ctx.Verbosef(" total allocation size: %v MB", metrics.GetTotalAllocSize()/1e6)
270
Dan Willemsen1e704462016-08-21 15:17:17 -0700271}