blob: ac00fe61f8270307e7a9515d540747c2826b975a [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 (
Dan Willemsende360442022-04-20 21:21:55 -070018 "errors"
Colin Cross9191df22021-10-29 13:11:32 -070019 "fmt"
Dan Willemsende360442022-04-20 21:21:55 -070020 "io/fs"
Colin Crossb72c9092020-02-10 11:23:49 -080021 "io/ioutil"
Dan Willemsen99a75cd2017-08-04 16:04:04 -070022 "os"
Dan Willemsen1e704462016-08-21 15:17:17 -070023 "path/filepath"
Dan Willemsen99a75cd2017-08-04 16:04:04 -070024 "strconv"
Usta Shrestha8dc8b0a2022-08-10 17:39:37 -040025 "strings"
Dan Willemsen99a75cd2017-08-04 16:04:04 -070026
Dan Willemsen4591b642021-05-24 14:24:12 -070027 "android/soong/ui/metrics"
Colin Crossb72c9092020-02-10 11:23:49 -080028 soong_metrics_proto "android/soong/ui/metrics/metrics_proto"
Dan Willemsen4591b642021-05-24 14:24:12 -070029 "android/soong/ui/status"
30
31 "android/soong/shared"
32
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010033 "github.com/google/blueprint"
34 "github.com/google/blueprint/bootstrap"
Dan Willemsen99a75cd2017-08-04 16:04:04 -070035 "github.com/google/blueprint/microfactory"
Dan Willemsenb82471a2018-05-17 16:37:09 -070036
Dan Willemsen4591b642021-05-24 14:24:12 -070037 "google.golang.org/protobuf/proto"
Dan Willemsen1e704462016-08-21 15:17:17 -070038)
39
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020040const (
41 availableEnvFile = "soong.environment.available"
42 usedEnvFile = "soong.environment.used"
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +020043
44 soongBuildTag = "build"
45 bp2buildTag = "bp2build"
46 jsonModuleGraphTag = "modulegraph"
47 queryviewTag = "queryview"
48 soongDocsTag = "soong_docs"
Colin Cross9191df22021-10-29 13:11:32 -070049
50 // bootstrapEpoch is used to determine if an incremental build is incompatible with the current
51 // version of bootstrap and needs cleaning before continuing the build. Increment this for
52 // incompatible changes, for example when moving the location of the bpglob binary that is
53 // executed during bootstrap before the primary builder has had a chance to update the path.
Lukacs T. Berki9985d9a2021-11-04 11:47:42 +010054 bootstrapEpoch = 1
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020055)
56
Lukacs T. Berki7690c092021-02-26 14:27:36 +010057func writeEnvironmentFile(ctx Context, envFile string, envDeps map[string]string) error {
58 data, err := shared.EnvFileContents(envDeps)
59 if err != nil {
60 return err
61 }
62
63 return ioutil.WriteFile(envFile, data, 0644)
64}
65
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000066// This uses Android.bp files and various tools to generate <builddir>/build.ninja.
67//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010068// However, the execution of <builddir>/build.ninja happens later in
69// build/soong/ui/build/build.go#Build()
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000070//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010071// We want to rely on as few prebuilts as possible, so we need to bootstrap
72// Soong. The process is as follows:
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000073//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010074// 1. We use "Microfactory", a simple tool to compile Go code, to build
75// first itself, then soong_ui from soong_ui.bash. This binary contains
76// parts of soong_build that are needed to build itself.
77// 2. This simplified version of soong_build then reads the Blueprint files
78// that describe itself and emits .bootstrap/build.ninja that describes
79// how to build its full version and use that to produce the final Ninja
80// file Soong emits.
81// 3. soong_ui executes .bootstrap/build.ninja
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000082//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010083// (After this, Kati is executed to parse the Makefiles, but that's not part of
84// bootstrapping Soong)
85
86// A tiny struct used to tell Blueprint that it's in bootstrap mode. It would
87// probably be nicer to use a flag in bootstrap.Args instead.
88type BlueprintConfig struct {
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +020089 toolDir string
90 soongOutDir string
91 outDir string
92 runGoTests bool
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +020093 debugCompilation bool
94 subninjas []string
95 primaryBuilderInvocations []bootstrap.PrimaryBuilderInvocation
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010096}
97
Lukacs T. Berkia806e412021-09-01 08:57:48 +020098func (c BlueprintConfig) HostToolDir() string {
99 return c.toolDir
100}
101
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200102func (c BlueprintConfig) SoongOutDir() string {
103 return c.soongOutDir
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100104}
105
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200106func (c BlueprintConfig) OutDir() string {
107 return c.outDir
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100108}
109
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +0200110func (c BlueprintConfig) RunGoTests() bool {
111 return c.runGoTests
112}
113
Lukacs T. Berki5f6cb1d2021-03-17 15:03:14 +0100114func (c BlueprintConfig) DebugCompilation() bool {
115 return c.debugCompilation
116}
117
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +0200118func (c BlueprintConfig) Subninjas() []string {
119 return c.subninjas
120}
121
122func (c BlueprintConfig) PrimaryBuilderInvocations() []bootstrap.PrimaryBuilderInvocation {
123 return c.primaryBuilderInvocations
124}
125
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200126func environmentArgs(config Config, tag string) []string {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200127 return []string{
128 "--available_env", shared.JoinPath(config.SoongOutDir(), availableEnvFile),
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200129 "--used_env", config.UsedEnvFile(tag),
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200130 }
131}
Spandan Das8f99ae62021-06-11 16:48:06 +0000132
Colin Cross9191df22021-10-29 13:11:32 -0700133func writeEmptyFile(ctx Context, path string) {
Spandan Das8f99ae62021-06-11 16:48:06 +0000134 err := os.MkdirAll(filepath.Dir(path), 0777)
135 if err != nil {
Colin Cross9191df22021-10-29 13:11:32 -0700136 ctx.Fatalf("Failed to create parent directories of empty file '%s': %s", path, err)
Spandan Das8f99ae62021-06-11 16:48:06 +0000137 }
138
Colin Cross9191df22021-10-29 13:11:32 -0700139 if exists, err := fileExists(path); err != nil {
140 ctx.Fatalf("Failed to check if file '%s' exists: %s", path, err)
141 } else if !exists {
Spandan Das8f99ae62021-06-11 16:48:06 +0000142 err = ioutil.WriteFile(path, nil, 0666)
143 if err != nil {
Colin Cross9191df22021-10-29 13:11:32 -0700144 ctx.Fatalf("Failed to create empty file '%s': %s", path, err)
Spandan Das8f99ae62021-06-11 16:48:06 +0000145 }
146 }
147}
148
Colin Cross9191df22021-10-29 13:11:32 -0700149func fileExists(path string) (bool, error) {
150 if _, err := os.Stat(path); os.IsNotExist(err) {
151 return false, nil
152 } else if err != nil {
153 return false, err
154 }
155 return true, nil
156}
157
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000158func primaryBuilderInvocation(
159 config Config,
160 name string,
161 output string,
162 specificArgs []string,
163 description string) bootstrap.PrimaryBuilderInvocation {
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200164 commonArgs := make([]string, 0, 0)
165
166 if !config.skipSoongTests {
167 commonArgs = append(commonArgs, "-t")
168 }
169
170 commonArgs = append(commonArgs, "-l", filepath.Join(config.FileListDir(), "Android.bp.list"))
Lukacs T. Berki13644272022-01-05 10:29:56 +0100171 invocationEnv := make(map[string]string)
ustafb67fd12022-08-19 19:26:00 -0400172 if os.Getenv("SOONG_DELVE") != "" {
173 //debug mode
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200174 commonArgs = append(commonArgs, "--delve_listen", os.Getenv("SOONG_DELVE"))
175 commonArgs = append(commonArgs, "--delve_path", shared.ResolveDelveBinary())
Lukacs T. Berki13644272022-01-05 10:29:56 +0100176 // GODEBUG=asyncpreemptoff=1 disables the preemption of goroutines. This
177 // is useful because the preemption happens by sending SIGURG to the OS
178 // thread hosting the goroutine in question and each signal results in
179 // work that needs to be done by Delve; it uses ptrace to debug the Go
180 // process and the tracer process must deal with every signal (it is not
181 // possible to selectively ignore SIGURG). This makes debugging slower,
182 // sometimes by an order of magnitude depending on luck.
183 // The original reason for adding async preemption to Go is here:
184 // https://github.com/golang/proposal/blob/master/design/24543-non-cooperative-preemption.md
185 invocationEnv["GODEBUG"] = "asyncpreemptoff=1"
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200186 }
187
ustafb67fd12022-08-19 19:26:00 -0400188 var allArgs []string
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200189 allArgs = append(allArgs, specificArgs...)
190 allArgs = append(allArgs,
191 "--globListDir", name,
192 "--globFile", config.NamedGlobFile(name))
193
194 allArgs = append(allArgs, commonArgs...)
195 allArgs = append(allArgs, environmentArgs(config, name)...)
196 allArgs = append(allArgs, "Android.bp")
197
198 return bootstrap.PrimaryBuilderInvocation{
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000199 Inputs: []string{"Android.bp"},
200 Outputs: []string{output},
201 Args: allArgs,
202 Description: description,
Lukacs T. Berki2fad3412022-01-04 14:40:13 +0100203 // NB: Changing the value of this environment variable will not result in a
204 // rebuild. The bootstrap Ninja file will change, but apparently Ninja does
205 // not consider changing the pool specified in a statement a change that's
206 // worth rebuilding for.
207 Console: os.Getenv("SOONG_UNBUFFERED_OUTPUT") == "1",
Lukacs T. Berki13644272022-01-05 10:29:56 +0100208 Env: invocationEnv,
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200209 }
210}
211
Colin Cross9191df22021-10-29 13:11:32 -0700212// bootstrapEpochCleanup deletes files used by bootstrap during incremental builds across
213// incompatible changes. Incompatible changes are marked by incrementing the bootstrapEpoch
214// constant. A tree is considered out of date for the current epoch of the
215// .soong.bootstrap.epoch.<epoch> file doesn't exist.
216func bootstrapEpochCleanup(ctx Context, config Config) {
217 epochFile := fmt.Sprintf(".soong.bootstrap.epoch.%d", bootstrapEpoch)
218 epochPath := filepath.Join(config.SoongOutDir(), epochFile)
219 if exists, err := fileExists(epochPath); err != nil {
220 ctx.Fatalf("failed to check if bootstrap epoch file %q exists: %q", epochPath, err)
221 } else if !exists {
222 // The tree is out of date for the current epoch, delete files used by bootstrap
223 // and force the primary builder to rerun.
224 os.Remove(filepath.Join(config.SoongOutDir(), "build.ninja"))
225 for _, globFile := range bootstrapGlobFileList(config) {
226 os.Remove(globFile)
227 }
228
229 // Mark the tree as up to date with the current epoch by writing the epoch marker file.
230 writeEmptyFile(ctx, epochPath)
231 }
232}
233
234func bootstrapGlobFileList(config Config) []string {
235 return []string{
236 config.NamedGlobFile(soongBuildTag),
237 config.NamedGlobFile(bp2buildTag),
238 config.NamedGlobFile(jsonModuleGraphTag),
239 config.NamedGlobFile(queryviewTag),
240 config.NamedGlobFile(soongDocsTag),
241 }
242}
243
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200244func bootstrapBlueprint(ctx Context, config Config) {
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100245 ctx.BeginTrace(metrics.RunSoong, "blueprint bootstrap")
246 defer ctx.EndTrace()
247
Colin Cross9191df22021-10-29 13:11:32 -0700248 // Clean up some files for incremental builds across incompatible changes.
249 bootstrapEpochCleanup(ctx, config)
250
Cole Faust65f298c2021-10-28 16:05:13 -0700251 mainSoongBuildExtraArgs := []string{"-o", config.SoongNinjaFile()}
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200252 if config.EmptyNinjaFile() {
253 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--empty-ninja-file")
Lukacs T. Berki745380c2021-04-12 12:07:44 +0200254 }
Chris Parsonsef615e52022-08-18 22:04:11 -0400255 if config.bazelProdMode {
256 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--bazel-mode")
257 }
258 if config.bazelDevMode {
259 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--bazel-mode-dev")
260 }
Lukacs T. Berki745380c2021-04-12 12:07:44 +0200261
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200262 mainSoongBuildInvocation := primaryBuilderInvocation(
263 config,
264 soongBuildTag,
Cole Faust65f298c2021-10-28 16:05:13 -0700265 config.SoongNinjaFile(),
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000266 mainSoongBuildExtraArgs,
267 fmt.Sprintf("analyzing Android.bp files and generating ninja file at %s", config.SoongNinjaFile()),
268 )
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200269
Chris Parsonsef615e52022-08-18 22:04:11 -0400270 if config.BazelBuildEnabled() {
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200271 // Mixed builds call Bazel from soong_build and they therefore need the
272 // Bazel workspace to be available. Make that so by adding a dependency on
273 // the bp2build marker file to the action that invokes soong_build .
274 mainSoongBuildInvocation.Inputs = append(mainSoongBuildInvocation.Inputs,
275 config.Bp2BuildMarkerFile())
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200276 }
277
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200278 bp2buildInvocation := primaryBuilderInvocation(
279 config,
280 bp2buildTag,
281 config.Bp2BuildMarkerFile(),
282 []string{
283 "--bp2build_marker", config.Bp2BuildMarkerFile(),
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000284 },
285 fmt.Sprintf("converting Android.bp files to BUILD files at %s/bp2build", config.SoongOutDir()),
286 )
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200287
288 jsonModuleGraphInvocation := primaryBuilderInvocation(
289 config,
290 jsonModuleGraphTag,
291 config.ModuleGraphFile(),
292 []string{
293 "--module_graph_file", config.ModuleGraphFile(),
kgui67007242022-01-25 13:50:25 +0800294 "--module_actions_file", config.ModuleActionsFile(),
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000295 },
296 fmt.Sprintf("generating the Soong module graph at %s", config.ModuleGraphFile()),
297 )
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200298
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000299 queryviewDir := filepath.Join(config.SoongOutDir(), "queryview")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200300 queryviewInvocation := primaryBuilderInvocation(
301 config,
302 queryviewTag,
303 config.QueryviewMarkerFile(),
304 []string{
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000305 "--bazel_queryview_dir", queryviewDir,
306 },
307 fmt.Sprintf("generating the Soong module graph as a Bazel workspace at %s", queryviewDir),
308 )
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200309
310 soongDocsInvocation := primaryBuilderInvocation(
311 config,
312 soongDocsTag,
313 config.SoongDocsHtml(),
314 []string{
315 "--soong_docs", config.SoongDocsHtml(),
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000316 },
317 fmt.Sprintf("generating Soong docs at %s", config.SoongDocsHtml()),
318 )
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200319
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") != "",
Usta Shrestha9b3724a2022-08-09 14:47:52 -0400342 subninjas: bootstrapGlobFileList(config),
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200343 primaryBuilderInvocations: []bootstrap.PrimaryBuilderInvocation{
344 mainSoongBuildInvocation,
345 bp2buildInvocation,
346 jsonModuleGraphInvocation,
347 queryviewInvocation,
348 soongDocsInvocation},
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100349 }
350
usta5bb4a5d2022-08-24 12:53:46 -0400351 // since `bootstrap.ninja` is regenerated unconditionally, we ignore the deps, i.e. little
352 // reason to write a `bootstrap.ninja.d` file
353 _ = bootstrap.RunBlueprint(blueprintArgs, bootstrap.DoEverything, blueprintCtx, blueprintConfig)
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100354}
355
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200356func checkEnvironmentFile(currentEnv *Environment, envFile string) {
357 getenv := func(k string) string {
358 v, _ := currentEnv.Get(k)
359 return v
360 }
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200361
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200362 if stale, _ := shared.StaleEnvFile(envFile, getenv); stale {
363 os.Remove(envFile)
364 }
365}
366
Dan Willemsen1e704462016-08-21 15:17:17 -0700367func runSoong(ctx Context, config Config) {
Nan Zhang17f27672018-12-12 16:01:49 -0800368 ctx.BeginTrace(metrics.RunSoong, "soong")
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700369 defer ctx.EndTrace()
370
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100371 // We have two environment files: .available is the one with every variable,
372 // .used with the ones that were actually used. The latter is used to
373 // determine whether Soong needs to be re-run since why re-run it if only
374 // unused variables were changed?
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200375 envFile := filepath.Join(config.SoongOutDir(), availableEnvFile)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100376
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100377 // This is done unconditionally, but does not take a measurable amount of time
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200378 bootstrapBlueprint(ctx, config)
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700379
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100380 soongBuildEnv := config.Environment().Copy()
381 soongBuildEnv.Set("TOP", os.Getenv("TOP"))
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100382 // For Bazel mixed builds.
383 soongBuildEnv.Set("BAZEL_PATH", "./tools/bazel")
Chris Parsonsa9bef142022-09-28 15:07:46 -0400384 // Bazel's HOME var is set to an output subdirectory which doesn't exist. This
385 // prevents Bazel from file I/O in the actual user HOME directory.
386 soongBuildEnv.Set("BAZEL_HOME", absPath(ctx, filepath.Join(config.BazelOutDir(), "bazelhome")))
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100387 soongBuildEnv.Set("BAZEL_OUTPUT_BASE", filepath.Join(config.BazelOutDir(), "output"))
388 soongBuildEnv.Set("BAZEL_WORKSPACE", absPath(ctx, "."))
389 soongBuildEnv.Set("BAZEL_METRICS_DIR", config.BazelMetricsDir())
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500390 soongBuildEnv.Set("LOG_DIR", config.LogsDir())
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100391
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100392 // For Soong bootstrapping tests
393 if os.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
394 soongBuildEnv.Set("ALLOW_MISSING_DEPENDENCIES", "true")
395 }
396
Paul Duffin5e85c662021-03-05 12:26:14 +0000397 err := writeEnvironmentFile(ctx, envFile, soongBuildEnv.AsMap())
398 if err != nil {
399 ctx.Fatalf("failed to write environment file %s: %s", envFile, err)
400 }
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100401
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700402 func() {
Nan Zhang17f27672018-12-12 16:01:49 -0800403 ctx.BeginTrace(metrics.RunSoong, "environment check")
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700404 defer ctx.EndTrace()
405
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200406 checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(soongBuildTag))
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200407
Chris Parsonsef615e52022-08-18 22:04:11 -0400408 if config.BazelBuildEnabled() || config.Bp2Build() {
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200409 checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(bp2buildTag))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200410 }
411
412 if config.JsonModuleGraph() {
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200413 checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(jsonModuleGraphTag))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200414 }
415
416 if config.Queryview() {
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200417 checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(queryviewTag))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200418 }
419
420 if config.SoongDocs() {
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200421 checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(soongDocsTag))
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700422 }
423 }()
424
Colin Cross9191df22021-10-29 13:11:32 -0700425 runMicrofactory(ctx, config, "bpglob", "github.com/google/blueprint/bootstrap/bpglob",
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700426 map[string]string{"github.com/google/blueprint": "build/blueprint"})
Dan Willemsen5af1cbe2018-07-05 21:46:51 -0700427
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200428 ninja := func(name, ninjaFile string, targets ...string) {
Nan Zhang17f27672018-12-12 16:01:49 -0800429 ctx.BeginTrace(metrics.RunSoong, name)
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700430 defer ctx.EndTrace()
431
Dan Willemsenb82471a2018-05-17 16:37:09 -0700432 fifo := filepath.Join(config.OutDir(), ".ninja_fifo")
Colin Crossb98d3bc2019-03-21 16:02:58 -0700433 nr := status.NewNinjaReader(ctx, ctx.Status.StartTool(), fifo)
434 defer nr.Close()
Dan Willemsenb82471a2018-05-17 16:37:09 -0700435
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200436 ninjaArgs := []string{
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700437 "-d", "keepdepfile",
Dan Willemsen08218222020-05-18 14:02:02 -0700438 "-d", "stats",
Dan Willemsen6587bed2020-04-18 20:25:59 -0700439 "-o", "usesphonyoutputs=yes",
440 "-o", "preremoveoutputs=yes",
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700441 "-w", "dupbuild=err",
Dan Willemsen6587bed2020-04-18 20:25:59 -0700442 "-w", "outputdir=err",
443 "-w", "missingoutfile=err",
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700444 "-j", strconv.Itoa(config.Parallel()),
Dan Willemsen02736672018-07-17 17:54:31 -0700445 "--frontend_file", fifo,
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200446 "-f", filepath.Join(config.SoongOutDir(), ninjaFile),
447 }
448
Usta Shrestha8dc8b0a2022-08-10 17:39:37 -0400449 if extra, ok := config.Environment().Get("SOONG_UI_NINJA_ARGS"); ok {
450 ctx.Printf(`CAUTION: arguments in $SOONG_UI_NINJA_ARGS=%q, e.g. "-n", can make soong_build FAIL or INCORRECT`, extra)
451 ninjaArgs = append(ninjaArgs, strings.Fields(extra)...)
452 }
453
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200454 ninjaArgs = append(ninjaArgs, targets...)
455 cmd := Command(ctx, config, "soong "+name,
456 config.PrebuiltBuildTool("ninja"), ninjaArgs...)
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500457
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100458 var ninjaEnv Environment
Lukacs T. Berki73ab9282021-03-10 10:48:39 +0100459
460 // This is currently how the command line to invoke soong_build finds the
461 // root of the source tree and the output root
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100462 ninjaEnv.Set("TOP", os.Getenv("TOP"))
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100463
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100464 cmd.Environment = &ninjaEnv
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700465 cmd.Sandbox = soongSandbox
Colin Cross7b97ecd2019-06-19 13:17:59 -0700466 cmd.RunAndStreamOrFatal()
Dan Willemsen1e704462016-08-21 15:17:17 -0700467 }
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200468
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200469 targets := make([]string, 0, 0)
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200470
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200471 if config.JsonModuleGraph() {
472 targets = append(targets, config.ModuleGraphFile())
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200473 }
474
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200475 if config.Bp2Build() {
476 targets = append(targets, config.Bp2BuildMarkerFile())
477 }
478
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200479 if config.Queryview() {
480 targets = append(targets, config.QueryviewMarkerFile())
481 }
482
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200483 if config.SoongDocs() {
484 targets = append(targets, config.SoongDocsHtml())
485 }
486
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200487 if config.SoongBuildInvocationNeeded() {
488 // 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 -0700489 targets = append(targets, config.SoongNinjaFile())
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200490 }
491
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100492 ninja("bootstrap", "bootstrap.ninja", targets...)
Colin Crossb72c9092020-02-10 11:23:49 -0800493
Jingwen Cheneb76c432021-01-28 08:22:12 -0500494 if shouldCollectBuildSoongMetrics(config) {
495 soongBuildMetrics := loadSoongBuildMetrics(ctx, config)
Dan Willemsende360442022-04-20 21:21:55 -0700496 if soongBuildMetrics != nil {
497 logSoongBuildMetrics(ctx, soongBuildMetrics)
498 if ctx.Metrics != nil {
499 ctx.Metrics.SetSoongBuildMetrics(soongBuildMetrics)
500 }
501 }
Jingwen Cheneb76c432021-01-28 08:22:12 -0500502 }
Colin Crossb72c9092020-02-10 11:23:49 -0800503
Colin Cross8ba7d472020-06-25 11:27:52 -0700504 distGzipFile(ctx, config, config.SoongNinjaFile(), "soong")
Jihoon Kang9f4f8a32022-08-16 00:57:30 +0000505 distFile(ctx, config, config.SoongVarsFile(), "soong")
Colin Cross8ba7d472020-06-25 11:27:52 -0700506
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000507 if !config.SkipKati() {
Colin Cross8ba7d472020-06-25 11:27:52 -0700508 distGzipFile(ctx, config, config.SoongAndroidMk(), "soong")
509 distGzipFile(ctx, config, config.SoongMakeVarsMk(), "soong")
510 }
511
Rob Seymour33cd10d2022-03-02 23:10:25 +0000512 if config.JsonModuleGraph() {
513 distGzipFile(ctx, config, config.ModuleGraphFile(), "soong")
514 }
Colin Crossb72c9092020-02-10 11:23:49 -0800515}
516
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100517func runMicrofactory(ctx Context, config Config, name string, pkg string, mapping map[string]string) {
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700518 ctx.BeginTrace(metrics.RunSoong, name)
519 defer ctx.EndTrace()
520 cfg := microfactory.Config{TrimPath: absPath(ctx, ".")}
521 for pkgPrefix, pathPrefix := range mapping {
522 cfg.Map(pkgPrefix, pathPrefix)
523 }
524
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100525 exePath := filepath.Join(config.SoongOutDir(), name)
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700526 dir := filepath.Dir(exePath)
527 if err := os.MkdirAll(dir, 0777); err != nil {
528 ctx.Fatalf("cannot create %s: %s", dir, err)
529 }
530 if _, err := microfactory.Build(&cfg, exePath, pkg); err != nil {
531 ctx.Fatalf("failed to build %s: %s", name, err)
532 }
533}
534
Jingwen Cheneb76c432021-01-28 08:22:12 -0500535func shouldCollectBuildSoongMetrics(config Config) bool {
Jingwen Chendd9725c2021-06-24 08:41:16 +0000536 // Do not collect metrics protobuf if the soong_build binary ran as the
537 // bp2build converter or the JSON graph dump.
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200538 return config.SoongBuildInvocationNeeded()
Jingwen Cheneb76c432021-01-28 08:22:12 -0500539}
540
Colin Crossb72c9092020-02-10 11:23:49 -0800541func loadSoongBuildMetrics(ctx Context, config Config) *soong_metrics_proto.SoongBuildMetrics {
Chris Parsons715b08f2022-03-22 19:23:40 -0400542 soongBuildMetricsFile := filepath.Join(config.LogsDir(), "soong_build_metrics.pb")
Dan Willemsende360442022-04-20 21:21:55 -0700543 buf, err := os.ReadFile(soongBuildMetricsFile)
544 if errors.Is(err, fs.ErrNotExist) {
545 // Soong may not have run during this invocation
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400546 ctx.Verbosef("Failed to read metrics file, %s: %s", soongBuildMetricsFile, err)
Dan Willemsende360442022-04-20 21:21:55 -0700547 return nil
548 } else if err != nil {
Colin Crossb72c9092020-02-10 11:23:49 -0800549 ctx.Fatalf("Failed to load %s: %s", soongBuildMetricsFile, err)
550 }
551 soongBuildMetrics := &soong_metrics_proto.SoongBuildMetrics{}
552 err = proto.Unmarshal(buf, soongBuildMetrics)
553 if err != nil {
554 ctx.Fatalf("Failed to unmarshal %s: %s", soongBuildMetricsFile, err)
555 }
556 return soongBuildMetrics
557}
558
559func logSoongBuildMetrics(ctx Context, metrics *soong_metrics_proto.SoongBuildMetrics) {
560 ctx.Verbosef("soong_build metrics:")
561 ctx.Verbosef(" modules: %v", metrics.GetModules())
562 ctx.Verbosef(" variants: %v", metrics.GetVariants())
563 ctx.Verbosef(" max heap size: %v MB", metrics.GetMaxHeapSize()/1e6)
564 ctx.Verbosef(" total allocation count: %v", metrics.GetTotalAllocCount())
565 ctx.Verbosef(" total allocation size: %v MB", metrics.GetTotalAllocSize()/1e6)
566
Dan Willemsen1e704462016-08-21 15:17:17 -0700567}