blob: 81337620db0824384ee776ae4d1d16fd9fbcc64b [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 Cross9191df22021-10-29 13:11:32 -070018 "fmt"
Colin Crossb72c9092020-02-10 11:23:49 -080019 "io/ioutil"
Dan Willemsen99a75cd2017-08-04 16:04:04 -070020 "os"
Dan Willemsen1e704462016-08-21 15:17:17 -070021 "path/filepath"
Dan Willemsen99a75cd2017-08-04 16:04:04 -070022 "strconv"
Dan Willemsen99a75cd2017-08-04 16:04:04 -070023
Dan Willemsen4591b642021-05-24 14:24:12 -070024 "android/soong/ui/metrics"
Colin Crossb72c9092020-02-10 11:23:49 -080025 soong_metrics_proto "android/soong/ui/metrics/metrics_proto"
Dan Willemsen4591b642021-05-24 14:24:12 -070026 "android/soong/ui/status"
27
28 "android/soong/shared"
29
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010030 "github.com/google/blueprint"
31 "github.com/google/blueprint/bootstrap"
Dan Willemsen4591b642021-05-24 14:24:12 -070032 "github.com/google/blueprint/deptools"
Dan Willemsen99a75cd2017-08-04 16:04:04 -070033 "github.com/google/blueprint/microfactory"
Dan Willemsenb82471a2018-05-17 16:37:09 -070034
Dan Willemsen4591b642021-05-24 14:24:12 -070035 "google.golang.org/protobuf/proto"
Dan Willemsen1e704462016-08-21 15:17:17 -070036)
37
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020038const (
39 availableEnvFile = "soong.environment.available"
40 usedEnvFile = "soong.environment.used"
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +020041
42 soongBuildTag = "build"
43 bp2buildTag = "bp2build"
44 jsonModuleGraphTag = "modulegraph"
45 queryviewTag = "queryview"
46 soongDocsTag = "soong_docs"
Colin Cross9191df22021-10-29 13:11:32 -070047
48 // bootstrapEpoch is used to determine if an incremental build is incompatible with the current
49 // version of bootstrap and needs cleaning before continuing the build. Increment this for
50 // incompatible changes, for example when moving the location of the bpglob binary that is
51 // executed during bootstrap before the primary builder has had a chance to update the path.
Lukacs T. Berki9985d9a2021-11-04 11:47:42 +010052 bootstrapEpoch = 1
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020053)
54
Lukacs T. Berki7690c092021-02-26 14:27:36 +010055func writeEnvironmentFile(ctx Context, envFile string, envDeps map[string]string) error {
56 data, err := shared.EnvFileContents(envDeps)
57 if err != nil {
58 return err
59 }
60
61 return ioutil.WriteFile(envFile, data, 0644)
62}
63
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000064// This uses Android.bp files and various tools to generate <builddir>/build.ninja.
65//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010066// However, the execution of <builddir>/build.ninja happens later in
67// build/soong/ui/build/build.go#Build()
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000068//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010069// We want to rely on as few prebuilts as possible, so we need to bootstrap
70// Soong. The process is as follows:
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000071//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010072// 1. We use "Microfactory", a simple tool to compile Go code, to build
73// first itself, then soong_ui from soong_ui.bash. This binary contains
74// parts of soong_build that are needed to build itself.
75// 2. This simplified version of soong_build then reads the Blueprint files
76// that describe itself and emits .bootstrap/build.ninja that describes
77// how to build its full version and use that to produce the final Ninja
78// file Soong emits.
79// 3. soong_ui executes .bootstrap/build.ninja
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000080//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010081// (After this, Kati is executed to parse the Makefiles, but that's not part of
82// bootstrapping Soong)
83
84// A tiny struct used to tell Blueprint that it's in bootstrap mode. It would
85// probably be nicer to use a flag in bootstrap.Args instead.
86type BlueprintConfig struct {
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +020087 toolDir string
88 soongOutDir string
89 outDir string
90 runGoTests bool
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +020091 debugCompilation bool
92 subninjas []string
93 primaryBuilderInvocations []bootstrap.PrimaryBuilderInvocation
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010094}
95
Lukacs T. Berkia806e412021-09-01 08:57:48 +020096func (c BlueprintConfig) HostToolDir() string {
97 return c.toolDir
98}
99
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200100func (c BlueprintConfig) SoongOutDir() string {
101 return c.soongOutDir
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100102}
103
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200104func (c BlueprintConfig) OutDir() string {
105 return c.outDir
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100106}
107
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +0200108func (c BlueprintConfig) RunGoTests() bool {
109 return c.runGoTests
110}
111
Lukacs T. Berki5f6cb1d2021-03-17 15:03:14 +0100112func (c BlueprintConfig) DebugCompilation() bool {
113 return c.debugCompilation
114}
115
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +0200116func (c BlueprintConfig) Subninjas() []string {
117 return c.subninjas
118}
119
120func (c BlueprintConfig) PrimaryBuilderInvocations() []bootstrap.PrimaryBuilderInvocation {
121 return c.primaryBuilderInvocations
122}
123
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200124func environmentArgs(config Config, tag string) []string {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200125 return []string{
126 "--available_env", shared.JoinPath(config.SoongOutDir(), availableEnvFile),
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200127 "--used_env", config.UsedEnvFile(tag),
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200128 }
129}
Spandan Das8f99ae62021-06-11 16:48:06 +0000130
Colin Cross9191df22021-10-29 13:11:32 -0700131func writeEmptyFile(ctx Context, path string) {
Spandan Das8f99ae62021-06-11 16:48:06 +0000132 err := os.MkdirAll(filepath.Dir(path), 0777)
133 if err != nil {
Colin Cross9191df22021-10-29 13:11:32 -0700134 ctx.Fatalf("Failed to create parent directories of empty file '%s': %s", path, err)
Spandan Das8f99ae62021-06-11 16:48:06 +0000135 }
136
Colin Cross9191df22021-10-29 13:11:32 -0700137 if exists, err := fileExists(path); err != nil {
138 ctx.Fatalf("Failed to check if file '%s' exists: %s", path, err)
139 } else if !exists {
Spandan Das8f99ae62021-06-11 16:48:06 +0000140 err = ioutil.WriteFile(path, nil, 0666)
141 if err != nil {
Colin Cross9191df22021-10-29 13:11:32 -0700142 ctx.Fatalf("Failed to create empty file '%s': %s", path, err)
Spandan Das8f99ae62021-06-11 16:48:06 +0000143 }
144 }
145}
146
Colin Cross9191df22021-10-29 13:11:32 -0700147func fileExists(path string) (bool, error) {
148 if _, err := os.Stat(path); os.IsNotExist(err) {
149 return false, nil
150 } else if err != nil {
151 return false, err
152 }
153 return true, nil
154}
155
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000156func primaryBuilderInvocation(
157 config Config,
158 name string,
159 output string,
160 specificArgs []string,
161 description string) bootstrap.PrimaryBuilderInvocation {
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200162 commonArgs := make([]string, 0, 0)
163
164 if !config.skipSoongTests {
165 commonArgs = append(commonArgs, "-t")
166 }
167
168 commonArgs = append(commonArgs, "-l", filepath.Join(config.FileListDir(), "Android.bp.list"))
Lukacs T. Berki13644272022-01-05 10:29:56 +0100169 invocationEnv := make(map[string]string)
170 debugMode := os.Getenv("SOONG_DELVE") != ""
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200171
Lukacs T. Berki13644272022-01-05 10:29:56 +0100172 if debugMode {
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200173 commonArgs = append(commonArgs, "--delve_listen", os.Getenv("SOONG_DELVE"))
174 commonArgs = append(commonArgs, "--delve_path", shared.ResolveDelveBinary())
Lukacs T. Berki13644272022-01-05 10:29:56 +0100175 // GODEBUG=asyncpreemptoff=1 disables the preemption of goroutines. This
176 // is useful because the preemption happens by sending SIGURG to the OS
177 // thread hosting the goroutine in question and each signal results in
178 // work that needs to be done by Delve; it uses ptrace to debug the Go
179 // process and the tracer process must deal with every signal (it is not
180 // possible to selectively ignore SIGURG). This makes debugging slower,
181 // sometimes by an order of magnitude depending on luck.
182 // The original reason for adding async preemption to Go is here:
183 // https://github.com/golang/proposal/blob/master/design/24543-non-cooperative-preemption.md
184 invocationEnv["GODEBUG"] = "asyncpreemptoff=1"
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200185 }
186
187 allArgs := make([]string, 0, 0)
188 allArgs = append(allArgs, specificArgs...)
189 allArgs = append(allArgs,
190 "--globListDir", name,
191 "--globFile", config.NamedGlobFile(name))
192
193 allArgs = append(allArgs, commonArgs...)
194 allArgs = append(allArgs, environmentArgs(config, name)...)
195 allArgs = append(allArgs, "Android.bp")
196
197 return bootstrap.PrimaryBuilderInvocation{
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000198 Inputs: []string{"Android.bp"},
199 Outputs: []string{output},
200 Args: allArgs,
201 Description: description,
Lukacs T. Berki2fad3412022-01-04 14:40:13 +0100202 // NB: Changing the value of this environment variable will not result in a
203 // rebuild. The bootstrap Ninja file will change, but apparently Ninja does
204 // not consider changing the pool specified in a statement a change that's
205 // worth rebuilding for.
206 Console: os.Getenv("SOONG_UNBUFFERED_OUTPUT") == "1",
Lukacs T. Berki13644272022-01-05 10:29:56 +0100207 Env: invocationEnv,
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200208 }
209}
210
Colin Cross9191df22021-10-29 13:11:32 -0700211// bootstrapEpochCleanup deletes files used by bootstrap during incremental builds across
212// incompatible changes. Incompatible changes are marked by incrementing the bootstrapEpoch
213// constant. A tree is considered out of date for the current epoch of the
214// .soong.bootstrap.epoch.<epoch> file doesn't exist.
215func bootstrapEpochCleanup(ctx Context, config Config) {
216 epochFile := fmt.Sprintf(".soong.bootstrap.epoch.%d", bootstrapEpoch)
217 epochPath := filepath.Join(config.SoongOutDir(), epochFile)
218 if exists, err := fileExists(epochPath); err != nil {
219 ctx.Fatalf("failed to check if bootstrap epoch file %q exists: %q", epochPath, err)
220 } else if !exists {
221 // The tree is out of date for the current epoch, delete files used by bootstrap
222 // and force the primary builder to rerun.
223 os.Remove(filepath.Join(config.SoongOutDir(), "build.ninja"))
224 for _, globFile := range bootstrapGlobFileList(config) {
225 os.Remove(globFile)
226 }
227
228 // Mark the tree as up to date with the current epoch by writing the epoch marker file.
229 writeEmptyFile(ctx, epochPath)
230 }
231}
232
233func bootstrapGlobFileList(config Config) []string {
234 return []string{
235 config.NamedGlobFile(soongBuildTag),
236 config.NamedGlobFile(bp2buildTag),
237 config.NamedGlobFile(jsonModuleGraphTag),
238 config.NamedGlobFile(queryviewTag),
239 config.NamedGlobFile(soongDocsTag),
240 }
241}
242
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200243func bootstrapBlueprint(ctx Context, config Config) {
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100244 ctx.BeginTrace(metrics.RunSoong, "blueprint bootstrap")
245 defer ctx.EndTrace()
246
Colin Cross9191df22021-10-29 13:11:32 -0700247 // Clean up some files for incremental builds across incompatible changes.
248 bootstrapEpochCleanup(ctx, config)
249
Cole Faust65f298c2021-10-28 16:05:13 -0700250 mainSoongBuildExtraArgs := []string{"-o", config.SoongNinjaFile()}
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200251 if config.EmptyNinjaFile() {
252 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--empty-ninja-file")
Lukacs T. Berki745380c2021-04-12 12:07:44 +0200253 }
254
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200255 mainSoongBuildInvocation := primaryBuilderInvocation(
256 config,
257 soongBuildTag,
Cole Faust65f298c2021-10-28 16:05:13 -0700258 config.SoongNinjaFile(),
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000259 mainSoongBuildExtraArgs,
260 fmt.Sprintf("analyzing Android.bp files and generating ninja file at %s", config.SoongNinjaFile()),
261 )
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200262
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200263 if config.bazelBuildMode() == mixedBuild {
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200264 // Mixed builds call Bazel from soong_build and they therefore need the
265 // Bazel workspace to be available. Make that so by adding a dependency on
266 // the bp2build marker file to the action that invokes soong_build .
267 mainSoongBuildInvocation.Inputs = append(mainSoongBuildInvocation.Inputs,
268 config.Bp2BuildMarkerFile())
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200269 }
270
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200271 bp2buildInvocation := primaryBuilderInvocation(
272 config,
273 bp2buildTag,
274 config.Bp2BuildMarkerFile(),
275 []string{
276 "--bp2build_marker", config.Bp2BuildMarkerFile(),
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000277 },
278 fmt.Sprintf("converting Android.bp files to BUILD files at %s/bp2build", config.SoongOutDir()),
279 )
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200280
281 jsonModuleGraphInvocation := primaryBuilderInvocation(
282 config,
283 jsonModuleGraphTag,
284 config.ModuleGraphFile(),
285 []string{
286 "--module_graph_file", config.ModuleGraphFile(),
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000287 },
288 fmt.Sprintf("generating the Soong module graph at %s", config.ModuleGraphFile()),
289 )
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200290
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000291 queryviewDir := filepath.Join(config.SoongOutDir(), "queryview")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200292 queryviewInvocation := primaryBuilderInvocation(
293 config,
294 queryviewTag,
295 config.QueryviewMarkerFile(),
296 []string{
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000297 "--bazel_queryview_dir", queryviewDir,
298 },
299 fmt.Sprintf("generating the Soong module graph as a Bazel workspace at %s", queryviewDir),
300 )
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200301
302 soongDocsInvocation := primaryBuilderInvocation(
303 config,
304 soongDocsTag,
305 config.SoongDocsHtml(),
306 []string{
307 "--soong_docs", config.SoongDocsHtml(),
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000308 },
309 fmt.Sprintf("generating Soong docs at %s", config.SoongDocsHtml()),
310 )
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200311
312 globFiles := []string{
313 config.NamedGlobFile(soongBuildTag),
314 config.NamedGlobFile(bp2buildTag),
315 config.NamedGlobFile(jsonModuleGraphTag),
316 config.NamedGlobFile(queryviewTag),
317 config.NamedGlobFile(soongDocsTag),
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200318 }
319
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200320 // The glob .ninja files are subninja'd. However, they are generated during
321 // the build itself so we write an empty file if the file does not exist yet
322 // so that the subninja doesn't fail on clean builds
Colin Cross9191df22021-10-29 13:11:32 -0700323 for _, globFile := range bootstrapGlobFileList(config) {
324 writeEmptyFile(ctx, globFile)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200325 }
326
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200327 var blueprintArgs bootstrap.Args
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200328
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200329 blueprintArgs.ModuleListFile = filepath.Join(config.FileListDir(), "Android.bp.list")
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100330 blueprintArgs.OutFile = shared.JoinPath(config.SoongOutDir(), "bootstrap.ninja")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200331 blueprintArgs.EmptyNinjaFile = false
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200332
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100333 blueprintCtx := blueprint.NewContext()
334 blueprintCtx.SetIgnoreUnknownModuleTypes(true)
335 blueprintConfig := BlueprintConfig{
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200336 soongOutDir: config.SoongOutDir(),
337 toolDir: config.HostToolDir(),
338 outDir: config.OutDir(),
339 runGoTests: !config.skipSoongTests,
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200340 // If we want to debug soong_build, we need to compile it for debugging
341 debugCompilation: os.Getenv("SOONG_DELVE") != "",
342 subninjas: globFiles,
343 primaryBuilderInvocations: []bootstrap.PrimaryBuilderInvocation{
344 mainSoongBuildInvocation,
345 bp2buildInvocation,
346 jsonModuleGraphInvocation,
347 queryviewInvocation,
348 soongDocsInvocation},
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100349 }
350
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200351 bootstrapDeps := bootstrap.RunBlueprint(blueprintArgs, bootstrap.DoEverything, blueprintCtx, blueprintConfig)
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100352 bootstrapDepFile := shared.JoinPath(config.SoongOutDir(), "bootstrap.ninja.d")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200353 err := deptools.WriteDepFile(bootstrapDepFile, blueprintArgs.OutFile, bootstrapDeps)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200354 if err != nil {
355 ctx.Fatalf("Error writing depfile '%s': %s", bootstrapDepFile, err)
356 }
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100357}
358
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200359func checkEnvironmentFile(currentEnv *Environment, envFile string) {
360 getenv := func(k string) string {
361 v, _ := currentEnv.Get(k)
362 return v
363 }
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200364
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200365 if stale, _ := shared.StaleEnvFile(envFile, getenv); stale {
366 os.Remove(envFile)
367 }
368}
369
Dan Willemsen1e704462016-08-21 15:17:17 -0700370func runSoong(ctx Context, config Config) {
Nan Zhang17f27672018-12-12 16:01:49 -0800371 ctx.BeginTrace(metrics.RunSoong, "soong")
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700372 defer ctx.EndTrace()
373
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100374 // We have two environment files: .available is the one with every variable,
375 // .used with the ones that were actually used. The latter is used to
376 // determine whether Soong needs to be re-run since why re-run it if only
377 // unused variables were changed?
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200378 envFile := filepath.Join(config.SoongOutDir(), availableEnvFile)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100379
Chris Parsonsec1a3dc2021-04-20 15:32:07 -0400380 buildMode := config.bazelBuildMode()
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200381 integratedBp2Build := buildMode == mixedBuild
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200382
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100383 // This is done unconditionally, but does not take a measurable amount of time
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200384 bootstrapBlueprint(ctx, config)
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700385
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100386 soongBuildEnv := config.Environment().Copy()
387 soongBuildEnv.Set("TOP", os.Getenv("TOP"))
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100388 // For Bazel mixed builds.
389 soongBuildEnv.Set("BAZEL_PATH", "./tools/bazel")
390 soongBuildEnv.Set("BAZEL_HOME", filepath.Join(config.BazelOutDir(), "bazelhome"))
391 soongBuildEnv.Set("BAZEL_OUTPUT_BASE", filepath.Join(config.BazelOutDir(), "output"))
392 soongBuildEnv.Set("BAZEL_WORKSPACE", absPath(ctx, "."))
393 soongBuildEnv.Set("BAZEL_METRICS_DIR", config.BazelMetricsDir())
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500394 soongBuildEnv.Set("LOG_DIR", config.LogsDir())
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100395
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100396 // For Soong bootstrapping tests
397 if os.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
398 soongBuildEnv.Set("ALLOW_MISSING_DEPENDENCIES", "true")
399 }
400
Paul Duffin5e85c662021-03-05 12:26:14 +0000401 err := writeEnvironmentFile(ctx, envFile, soongBuildEnv.AsMap())
402 if err != nil {
403 ctx.Fatalf("failed to write environment file %s: %s", envFile, err)
404 }
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100405
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700406 func() {
Nan Zhang17f27672018-12-12 16:01:49 -0800407 ctx.BeginTrace(metrics.RunSoong, "environment check")
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700408 defer ctx.EndTrace()
409
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200410 checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(soongBuildTag))
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200411
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200412 if integratedBp2Build || config.Bp2Build() {
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200413 checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(bp2buildTag))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200414 }
415
416 if config.JsonModuleGraph() {
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200417 checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(jsonModuleGraphTag))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200418 }
419
420 if config.Queryview() {
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200421 checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(queryviewTag))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200422 }
423
424 if config.SoongDocs() {
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200425 checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(soongDocsTag))
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700426 }
427 }()
428
Colin Cross9191df22021-10-29 13:11:32 -0700429 runMicrofactory(ctx, config, "bpglob", "github.com/google/blueprint/bootstrap/bpglob",
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700430 map[string]string{"github.com/google/blueprint": "build/blueprint"})
Dan Willemsen5af1cbe2018-07-05 21:46:51 -0700431
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200432 ninja := func(name, ninjaFile string, targets ...string) {
Nan Zhang17f27672018-12-12 16:01:49 -0800433 ctx.BeginTrace(metrics.RunSoong, name)
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700434 defer ctx.EndTrace()
435
Dan Willemsenb82471a2018-05-17 16:37:09 -0700436 fifo := filepath.Join(config.OutDir(), ".ninja_fifo")
Colin Crossb98d3bc2019-03-21 16:02:58 -0700437 nr := status.NewNinjaReader(ctx, ctx.Status.StartTool(), fifo)
438 defer nr.Close()
Dan Willemsenb82471a2018-05-17 16:37:09 -0700439
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200440 ninjaArgs := []string{
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700441 "-d", "keepdepfile",
Dan Willemsen08218222020-05-18 14:02:02 -0700442 "-d", "stats",
Dan Willemsen6587bed2020-04-18 20:25:59 -0700443 "-o", "usesphonyoutputs=yes",
444 "-o", "preremoveoutputs=yes",
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700445 "-w", "dupbuild=err",
Dan Willemsen6587bed2020-04-18 20:25:59 -0700446 "-w", "outputdir=err",
447 "-w", "missingoutfile=err",
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700448 "-j", strconv.Itoa(config.Parallel()),
Dan Willemsen02736672018-07-17 17:54:31 -0700449 "--frontend_file", fifo,
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200450 "-f", filepath.Join(config.SoongOutDir(), ninjaFile),
451 }
452
453 ninjaArgs = append(ninjaArgs, targets...)
454 cmd := Command(ctx, config, "soong "+name,
455 config.PrebuiltBuildTool("ninja"), ninjaArgs...)
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500456
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100457 var ninjaEnv Environment
Lukacs T. Berki73ab9282021-03-10 10:48:39 +0100458
459 // This is currently how the command line to invoke soong_build finds the
460 // root of the source tree and the output root
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100461 ninjaEnv.Set("TOP", os.Getenv("TOP"))
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100462
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100463 cmd.Environment = &ninjaEnv
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700464 cmd.Sandbox = soongSandbox
Colin Cross7b97ecd2019-06-19 13:17:59 -0700465 cmd.RunAndStreamOrFatal()
Dan Willemsen1e704462016-08-21 15:17:17 -0700466 }
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200467
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200468 targets := make([]string, 0, 0)
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200469
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200470 if config.JsonModuleGraph() {
471 targets = append(targets, config.ModuleGraphFile())
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200472 }
473
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200474 if config.Bp2Build() {
475 targets = append(targets, config.Bp2BuildMarkerFile())
476 }
477
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200478 if config.Queryview() {
479 targets = append(targets, config.QueryviewMarkerFile())
480 }
481
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200482 if config.SoongDocs() {
483 targets = append(targets, config.SoongDocsHtml())
484 }
485
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200486 if config.SoongBuildInvocationNeeded() {
487 // This build generates <builddir>/build.ninja, which is used later by build/soong/ui/build/build.go#Build().
Cole Faust65f298c2021-10-28 16:05:13 -0700488 targets = append(targets, config.SoongNinjaFile())
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200489 }
490
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100491 ninja("bootstrap", "bootstrap.ninja", targets...)
Colin Crossb72c9092020-02-10 11:23:49 -0800492
Jingwen Cheneb76c432021-01-28 08:22:12 -0500493 var soongBuildMetrics *soong_metrics_proto.SoongBuildMetrics
494 if shouldCollectBuildSoongMetrics(config) {
495 soongBuildMetrics := loadSoongBuildMetrics(ctx, config)
496 logSoongBuildMetrics(ctx, soongBuildMetrics)
497 }
Colin Crossb72c9092020-02-10 11:23:49 -0800498
Colin Cross8ba7d472020-06-25 11:27:52 -0700499 distGzipFile(ctx, config, config.SoongNinjaFile(), "soong")
500
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000501 if !config.SkipKati() {
Colin Cross8ba7d472020-06-25 11:27:52 -0700502 distGzipFile(ctx, config, config.SoongAndroidMk(), "soong")
503 distGzipFile(ctx, config, config.SoongMakeVarsMk(), "soong")
504 }
505
Jingwen Cheneb76c432021-01-28 08:22:12 -0500506 if shouldCollectBuildSoongMetrics(config) && ctx.Metrics != nil {
Colin Crossb72c9092020-02-10 11:23:49 -0800507 ctx.Metrics.SetSoongBuildMetrics(soongBuildMetrics)
508 }
509}
510
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100511func runMicrofactory(ctx Context, config Config, name string, pkg string, mapping map[string]string) {
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700512 ctx.BeginTrace(metrics.RunSoong, name)
513 defer ctx.EndTrace()
514 cfg := microfactory.Config{TrimPath: absPath(ctx, ".")}
515 for pkgPrefix, pathPrefix := range mapping {
516 cfg.Map(pkgPrefix, pathPrefix)
517 }
518
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100519 exePath := filepath.Join(config.SoongOutDir(), name)
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700520 dir := filepath.Dir(exePath)
521 if err := os.MkdirAll(dir, 0777); err != nil {
522 ctx.Fatalf("cannot create %s: %s", dir, err)
523 }
524 if _, err := microfactory.Build(&cfg, exePath, pkg); err != nil {
525 ctx.Fatalf("failed to build %s: %s", name, err)
526 }
527}
528
Jingwen Cheneb76c432021-01-28 08:22:12 -0500529func shouldCollectBuildSoongMetrics(config Config) bool {
Jingwen Chendd9725c2021-06-24 08:41:16 +0000530 // Do not collect metrics protobuf if the soong_build binary ran as the
531 // bp2build converter or the JSON graph dump.
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200532 return config.SoongBuildInvocationNeeded()
Jingwen Cheneb76c432021-01-28 08:22:12 -0500533}
534
Colin Crossb72c9092020-02-10 11:23:49 -0800535func loadSoongBuildMetrics(ctx Context, config Config) *soong_metrics_proto.SoongBuildMetrics {
536 soongBuildMetricsFile := filepath.Join(config.OutDir(), "soong", "soong_build_metrics.pb")
537 buf, err := ioutil.ReadFile(soongBuildMetricsFile)
538 if err != nil {
539 ctx.Fatalf("Failed to load %s: %s", soongBuildMetricsFile, err)
540 }
541 soongBuildMetrics := &soong_metrics_proto.SoongBuildMetrics{}
542 err = proto.Unmarshal(buf, soongBuildMetrics)
543 if err != nil {
544 ctx.Fatalf("Failed to unmarshal %s: %s", soongBuildMetricsFile, err)
545 }
546 return soongBuildMetrics
547}
548
549func logSoongBuildMetrics(ctx Context, metrics *soong_metrics_proto.SoongBuildMetrics) {
550 ctx.Verbosef("soong_build metrics:")
551 ctx.Verbosef(" modules: %v", metrics.GetModules())
552 ctx.Verbosef(" variants: %v", metrics.GetVariants())
553 ctx.Verbosef(" max heap size: %v MB", metrics.GetMaxHeapSize()/1e6)
554 ctx.Verbosef(" total allocation count: %v", metrics.GetTotalAllocCount())
555 ctx.Verbosef(" total allocation size: %v MB", metrics.GetTotalAllocSize()/1e6)
556
Dan Willemsen1e704462016-08-21 15:17:17 -0700557}