blob: a8a65b1ea0eab204808aa6a5cc3053248840fe7d [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 {
68 srcDir string
69 buildDir string
70 ninjaBuildDir string
71}
72
73func (c BlueprintConfig) GeneratingPrimaryBuilder() bool {
74 return true
75}
76
77func (c BlueprintConfig) SrcDir() string {
78 return "."
79}
80
81func (c BlueprintConfig) BuildDir() string {
82 return c.buildDir
83}
84
85func (c BlueprintConfig) NinjaBuildDir() string {
86 return c.ninjaBuildDir
87}
88
89func bootstrapBlueprint(ctx Context, config Config) {
90 ctx.BeginTrace(metrics.RunSoong, "blueprint bootstrap")
91 defer ctx.EndTrace()
92
93 var args bootstrap.Args
94
95 args.RunGoTests = !config.skipSoongTests
96 args.UseValidations = true // Use validations to depend on tests
97 args.BuildDir = config.SoongOutDir()
98 args.NinjaBuildDir = config.OutDir()
99 args.TopFile = "Android.bp"
100 args.ModuleListFile = filepath.Join(config.FileListDir(), "Android.bp.list")
101 args.OutFile = shared.JoinPath(config.SoongOutDir(), ".bootstrap/build.ninja")
102 args.DepFile = shared.JoinPath(config.SoongOutDir(), ".bootstrap/build.ninja.d")
103 args.GlobFile = shared.JoinPath(config.SoongOutDir(), ".bootstrap/soong-build-globs.ninja")
104
105 blueprintCtx := blueprint.NewContext()
106 blueprintCtx.SetIgnoreUnknownModuleTypes(true)
107 blueprintConfig := BlueprintConfig{
108 srcDir: os.Getenv("TOP"),
109 buildDir: config.SoongOutDir(),
110 ninjaBuildDir: config.OutDir(),
111 }
112
113 bootstrap.RunBlueprint(args, blueprintCtx, blueprintConfig)
114}
115
Dan Willemsen1e704462016-08-21 15:17:17 -0700116func runSoong(ctx Context, config Config) {
Nan Zhang17f27672018-12-12 16:01:49 -0800117 ctx.BeginTrace(metrics.RunSoong, "soong")
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700118 defer ctx.EndTrace()
119
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100120 // We have two environment files: .available is the one with every variable,
121 // .used with the ones that were actually used. The latter is used to
122 // determine whether Soong needs to be re-run since why re-run it if only
123 // unused variables were changed?
124 envFile := filepath.Join(config.SoongOutDir(), "soong.environment.available")
125
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100126 for _, n := range []string{".bootstrap", ".minibootstrap"} {
127 dir := filepath.Join(config.SoongOutDir(), n)
128 if err := os.MkdirAll(dir, 0755); err != nil {
129 ctx.Fatalf("Cannot mkdir " + dir)
Colin Cross00a8a3f2020-10-29 14:08:31 -0700130 }
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100131 }
Colin Cross00a8a3f2020-10-29 14:08:31 -0700132
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100133 // This is done unconditionally, but does not take a measurable amount of time
134 bootstrapBlueprint(ctx, config)
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700135
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100136 soongBuildEnv := config.Environment().Copy()
137 soongBuildEnv.Set("TOP", os.Getenv("TOP"))
138 // These two dependencies are read from bootstrap.go, but also need to be here
139 // so that soong_build can declare a dependency on them
140 soongBuildEnv.Set("SOONG_DELVE", os.Getenv("SOONG_DELVE"))
141 soongBuildEnv.Set("SOONG_DELVE_PATH", os.Getenv("SOONG_DELVE_PATH"))
142 soongBuildEnv.Set("SOONG_OUTDIR", config.SoongOutDir())
143 // For Bazel mixed builds.
144 soongBuildEnv.Set("BAZEL_PATH", "./tools/bazel")
145 soongBuildEnv.Set("BAZEL_HOME", filepath.Join(config.BazelOutDir(), "bazelhome"))
146 soongBuildEnv.Set("BAZEL_OUTPUT_BASE", filepath.Join(config.BazelOutDir(), "output"))
147 soongBuildEnv.Set("BAZEL_WORKSPACE", absPath(ctx, "."))
148 soongBuildEnv.Set("BAZEL_METRICS_DIR", config.BazelMetricsDir())
149
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100150 // For Soong bootstrapping tests
151 if os.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
152 soongBuildEnv.Set("ALLOW_MISSING_DEPENDENCIES", "true")
153 }
154
Paul Duffin5e85c662021-03-05 12:26:14 +0000155 err := writeEnvironmentFile(ctx, envFile, soongBuildEnv.AsMap())
156 if err != nil {
157 ctx.Fatalf("failed to write environment file %s: %s", envFile, err)
158 }
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100159
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700160 func() {
Nan Zhang17f27672018-12-12 16:01:49 -0800161 ctx.BeginTrace(metrics.RunSoong, "environment check")
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700162 defer ctx.EndTrace()
163
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100164 envFile := filepath.Join(config.SoongOutDir(), "soong.environment.used")
Lukacs T. Berki3243aa52021-02-25 14:44:14 +0100165 getenv := func(k string) string {
Lukacs T. Berkib4ced9d2021-03-10 15:43:06 +0100166 v, _ := soongBuildEnv.Get(k)
Lukacs T. Berki3243aa52021-02-25 14:44:14 +0100167 return v
168 }
169 if stale, _ := shared.StaleEnvFile(envFile, getenv); stale {
170 os.Remove(envFile)
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700171 }
172 }()
173
Dan Willemsen5af1cbe2018-07-05 21:46:51 -0700174 var cfg microfactory.Config
175 cfg.Map("github.com/google/blueprint", "build/blueprint")
176
177 cfg.TrimPath = absPath(ctx, ".")
178
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700179 func() {
Nan Zhang17f27672018-12-12 16:01:49 -0800180 ctx.BeginTrace(metrics.RunSoong, "bpglob")
Dan Willemsen5af1cbe2018-07-05 21:46:51 -0700181 defer ctx.EndTrace()
182
183 bpglob := filepath.Join(config.SoongOutDir(), ".minibootstrap/bpglob")
184 if _, err := microfactory.Build(&cfg, bpglob, "github.com/google/blueprint/bootstrap/bpglob"); err != nil {
185 ctx.Fatalln("Failed to build bpglob:", err)
186 }
187 }()
188
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700189 ninja := func(name, file string) {
Nan Zhang17f27672018-12-12 16:01:49 -0800190 ctx.BeginTrace(metrics.RunSoong, name)
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700191 defer ctx.EndTrace()
192
Dan Willemsenb82471a2018-05-17 16:37:09 -0700193 fifo := filepath.Join(config.OutDir(), ".ninja_fifo")
Colin Crossb98d3bc2019-03-21 16:02:58 -0700194 nr := status.NewNinjaReader(ctx, ctx.Status.StartTool(), fifo)
195 defer nr.Close()
Dan Willemsenb82471a2018-05-17 16:37:09 -0700196
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700197 cmd := Command(ctx, config, "soong "+name,
198 config.PrebuiltBuildTool("ninja"),
199 "-d", "keepdepfile",
Dan Willemsen08218222020-05-18 14:02:02 -0700200 "-d", "stats",
Dan Willemsen6587bed2020-04-18 20:25:59 -0700201 "-o", "usesphonyoutputs=yes",
202 "-o", "preremoveoutputs=yes",
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700203 "-w", "dupbuild=err",
Dan Willemsen6587bed2020-04-18 20:25:59 -0700204 "-w", "outputdir=err",
205 "-w", "missingoutfile=err",
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700206 "-j", strconv.Itoa(config.Parallel()),
Dan Willemsen02736672018-07-17 17:54:31 -0700207 "--frontend_file", fifo,
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700208 "-f", filepath.Join(config.SoongOutDir(), file))
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500209
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100210 var ninjaEnv Environment
Lukacs T. Berki73ab9282021-03-10 10:48:39 +0100211
212 // This is currently how the command line to invoke soong_build finds the
213 // root of the source tree and the output root
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100214 ninjaEnv.Set("TOP", os.Getenv("TOP"))
215 ninjaEnv.Set("SOONG_OUTDIR", config.SoongOutDir())
Lukacs T. Berki73ab9282021-03-10 10:48:39 +0100216
Lukacs T. Berki73ab9282021-03-10 10:48:39 +0100217 // For debugging
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100218 if os.Getenv("SOONG_DELVE") != "" {
Lukacs T. Berkib4ced9d2021-03-10 15:43:06 +0100219 ninjaEnv.Set("SOONG_DELVE", os.Getenv("SOONG_DELVE"))
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100220 ninjaEnv.Set("SOONG_DELVE_PATH", shared.ResolveDelveBinary())
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100221 }
222
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100223 cmd.Environment = &ninjaEnv
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700224 cmd.Sandbox = soongSandbox
Colin Cross7b97ecd2019-06-19 13:17:59 -0700225 cmd.RunAndStreamOrFatal()
Dan Willemsen1e704462016-08-21 15:17:17 -0700226 }
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +0000227 // 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 -0700228 ninja("bootstrap", ".bootstrap/build.ninja")
Colin Crossb72c9092020-02-10 11:23:49 -0800229
Jingwen Cheneb76c432021-01-28 08:22:12 -0500230 var soongBuildMetrics *soong_metrics_proto.SoongBuildMetrics
231 if shouldCollectBuildSoongMetrics(config) {
232 soongBuildMetrics := loadSoongBuildMetrics(ctx, config)
233 logSoongBuildMetrics(ctx, soongBuildMetrics)
234 }
Colin Crossb72c9092020-02-10 11:23:49 -0800235
Colin Cross8ba7d472020-06-25 11:27:52 -0700236 distGzipFile(ctx, config, config.SoongNinjaFile(), "soong")
237
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000238 if !config.SkipKati() {
Colin Cross8ba7d472020-06-25 11:27:52 -0700239 distGzipFile(ctx, config, config.SoongAndroidMk(), "soong")
240 distGzipFile(ctx, config, config.SoongMakeVarsMk(), "soong")
241 }
242
Jingwen Cheneb76c432021-01-28 08:22:12 -0500243 if shouldCollectBuildSoongMetrics(config) && ctx.Metrics != nil {
Colin Crossb72c9092020-02-10 11:23:49 -0800244 ctx.Metrics.SetSoongBuildMetrics(soongBuildMetrics)
245 }
246}
247
Jingwen Cheneb76c432021-01-28 08:22:12 -0500248func shouldCollectBuildSoongMetrics(config Config) bool {
249 // Do not collect metrics protobuf if the soong_build binary ran as the bp2build converter.
250 return config.Environment().IsFalse("GENERATE_BAZEL_FILES")
251}
252
Colin Crossb72c9092020-02-10 11:23:49 -0800253func loadSoongBuildMetrics(ctx Context, config Config) *soong_metrics_proto.SoongBuildMetrics {
254 soongBuildMetricsFile := filepath.Join(config.OutDir(), "soong", "soong_build_metrics.pb")
255 buf, err := ioutil.ReadFile(soongBuildMetricsFile)
256 if err != nil {
257 ctx.Fatalf("Failed to load %s: %s", soongBuildMetricsFile, err)
258 }
259 soongBuildMetrics := &soong_metrics_proto.SoongBuildMetrics{}
260 err = proto.Unmarshal(buf, soongBuildMetrics)
261 if err != nil {
262 ctx.Fatalf("Failed to unmarshal %s: %s", soongBuildMetricsFile, err)
263 }
264 return soongBuildMetrics
265}
266
267func logSoongBuildMetrics(ctx Context, metrics *soong_metrics_proto.SoongBuildMetrics) {
268 ctx.Verbosef("soong_build metrics:")
269 ctx.Verbosef(" modules: %v", metrics.GetModules())
270 ctx.Verbosef(" variants: %v", metrics.GetVariants())
271 ctx.Verbosef(" max heap size: %v MB", metrics.GetMaxHeapSize()/1e6)
272 ctx.Verbosef(" total allocation count: %v", metrics.GetTotalAllocCount())
273 ctx.Verbosef(" total allocation size: %v MB", metrics.GetTotalAllocSize()/1e6)
274
Dan Willemsen1e704462016-08-21 15:17:17 -0700275}