blob: 2e94a46b104d7c5801fae3469eab34522974f673 [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 Willemsen4591b642021-05-24 14:24:12 -070035 "github.com/google/blueprint/deptools"
Dan Willemsen99a75cd2017-08-04 16:04:04 -070036 "github.com/google/blueprint/microfactory"
Dan Willemsenb82471a2018-05-17 16:37:09 -070037
Dan Willemsen4591b642021-05-24 14:24:12 -070038 "google.golang.org/protobuf/proto"
Dan Willemsen1e704462016-08-21 15:17:17 -070039)
40
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020041const (
42 availableEnvFile = "soong.environment.available"
43 usedEnvFile = "soong.environment.used"
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +020044
45 soongBuildTag = "build"
46 bp2buildTag = "bp2build"
47 jsonModuleGraphTag = "modulegraph"
48 queryviewTag = "queryview"
49 soongDocsTag = "soong_docs"
Colin Cross9191df22021-10-29 13:11:32 -070050
51 // bootstrapEpoch is used to determine if an incremental build is incompatible with the current
52 // version of bootstrap and needs cleaning before continuing the build. Increment this for
53 // incompatible changes, for example when moving the location of the bpglob binary that is
54 // executed during bootstrap before the primary builder has had a chance to update the path.
Lukacs T. Berki9985d9a2021-11-04 11:47:42 +010055 bootstrapEpoch = 1
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020056)
57
Lukacs T. Berki7690c092021-02-26 14:27:36 +010058func writeEnvironmentFile(ctx Context, envFile string, envDeps map[string]string) error {
59 data, err := shared.EnvFileContents(envDeps)
60 if err != nil {
61 return err
62 }
63
64 return ioutil.WriteFile(envFile, data, 0644)
65}
66
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000067// This uses Android.bp files and various tools to generate <builddir>/build.ninja.
68//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010069// However, the execution of <builddir>/build.ninja happens later in
70// build/soong/ui/build/build.go#Build()
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000071//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010072// We want to rely on as few prebuilts as possible, so we need to bootstrap
73// Soong. The process is as follows:
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000074//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010075// 1. We use "Microfactory", a simple tool to compile Go code, to build
76// first itself, then soong_ui from soong_ui.bash. This binary contains
77// parts of soong_build that are needed to build itself.
78// 2. This simplified version of soong_build then reads the Blueprint files
79// that describe itself and emits .bootstrap/build.ninja that describes
80// how to build its full version and use that to produce the final Ninja
81// file Soong emits.
82// 3. soong_ui executes .bootstrap/build.ninja
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000083//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010084// (After this, Kati is executed to parse the Makefiles, but that's not part of
85// bootstrapping Soong)
86
87// A tiny struct used to tell Blueprint that it's in bootstrap mode. It would
88// probably be nicer to use a flag in bootstrap.Args instead.
89type BlueprintConfig struct {
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +020090 toolDir string
91 soongOutDir string
92 outDir string
93 runGoTests bool
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +020094 debugCompilation bool
95 subninjas []string
96 primaryBuilderInvocations []bootstrap.PrimaryBuilderInvocation
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010097}
98
Lukacs T. Berkia806e412021-09-01 08:57:48 +020099func (c BlueprintConfig) HostToolDir() string {
100 return c.toolDir
101}
102
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200103func (c BlueprintConfig) SoongOutDir() string {
104 return c.soongOutDir
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100105}
106
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200107func (c BlueprintConfig) OutDir() string {
108 return c.outDir
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100109}
110
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +0200111func (c BlueprintConfig) RunGoTests() bool {
112 return c.runGoTests
113}
114
Lukacs T. Berki5f6cb1d2021-03-17 15:03:14 +0100115func (c BlueprintConfig) DebugCompilation() bool {
116 return c.debugCompilation
117}
118
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +0200119func (c BlueprintConfig) Subninjas() []string {
120 return c.subninjas
121}
122
123func (c BlueprintConfig) PrimaryBuilderInvocations() []bootstrap.PrimaryBuilderInvocation {
124 return c.primaryBuilderInvocations
125}
126
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200127func environmentArgs(config Config, tag string) []string {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200128 return []string{
129 "--available_env", shared.JoinPath(config.SoongOutDir(), availableEnvFile),
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200130 "--used_env", config.UsedEnvFile(tag),
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200131 }
132}
Spandan Das8f99ae62021-06-11 16:48:06 +0000133
Colin Cross9191df22021-10-29 13:11:32 -0700134func writeEmptyFile(ctx Context, path string) {
Spandan Das8f99ae62021-06-11 16:48:06 +0000135 err := os.MkdirAll(filepath.Dir(path), 0777)
136 if err != nil {
Colin Cross9191df22021-10-29 13:11:32 -0700137 ctx.Fatalf("Failed to create parent directories of empty file '%s': %s", path, err)
Spandan Das8f99ae62021-06-11 16:48:06 +0000138 }
139
Colin Cross9191df22021-10-29 13:11:32 -0700140 if exists, err := fileExists(path); err != nil {
141 ctx.Fatalf("Failed to check if file '%s' exists: %s", path, err)
142 } else if !exists {
Spandan Das8f99ae62021-06-11 16:48:06 +0000143 err = ioutil.WriteFile(path, nil, 0666)
144 if err != nil {
Colin Cross9191df22021-10-29 13:11:32 -0700145 ctx.Fatalf("Failed to create empty file '%s': %s", path, err)
Spandan Das8f99ae62021-06-11 16:48:06 +0000146 }
147 }
148}
149
Colin Cross9191df22021-10-29 13:11:32 -0700150func fileExists(path string) (bool, error) {
151 if _, err := os.Stat(path); os.IsNotExist(err) {
152 return false, nil
153 } else if err != nil {
154 return false, err
155 }
156 return true, nil
157}
158
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000159func primaryBuilderInvocation(
160 config Config,
161 name string,
162 output string,
163 specificArgs []string,
164 description string) bootstrap.PrimaryBuilderInvocation {
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200165 commonArgs := make([]string, 0, 0)
166
167 if !config.skipSoongTests {
168 commonArgs = append(commonArgs, "-t")
169 }
170
171 commonArgs = append(commonArgs, "-l", filepath.Join(config.FileListDir(), "Android.bp.list"))
Lukacs T. Berki13644272022-01-05 10:29:56 +0100172 invocationEnv := make(map[string]string)
173 debugMode := os.Getenv("SOONG_DELVE") != ""
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200174
Lukacs T. Berki13644272022-01-05 10:29:56 +0100175 if debugMode {
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200176 commonArgs = append(commonArgs, "--delve_listen", os.Getenv("SOONG_DELVE"))
177 commonArgs = append(commonArgs, "--delve_path", shared.ResolveDelveBinary())
Lukacs T. Berki13644272022-01-05 10:29:56 +0100178 // GODEBUG=asyncpreemptoff=1 disables the preemption of goroutines. This
179 // is useful because the preemption happens by sending SIGURG to the OS
180 // thread hosting the goroutine in question and each signal results in
181 // work that needs to be done by Delve; it uses ptrace to debug the Go
182 // process and the tracer process must deal with every signal (it is not
183 // possible to selectively ignore SIGURG). This makes debugging slower,
184 // sometimes by an order of magnitude depending on luck.
185 // The original reason for adding async preemption to Go is here:
186 // https://github.com/golang/proposal/blob/master/design/24543-non-cooperative-preemption.md
187 invocationEnv["GODEBUG"] = "asyncpreemptoff=1"
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200188 }
189
190 allArgs := make([]string, 0, 0)
191 allArgs = append(allArgs, specificArgs...)
192 allArgs = append(allArgs,
193 "--globListDir", name,
194 "--globFile", config.NamedGlobFile(name))
195
196 allArgs = append(allArgs, commonArgs...)
197 allArgs = append(allArgs, environmentArgs(config, name)...)
198 allArgs = append(allArgs, "Android.bp")
199
200 return bootstrap.PrimaryBuilderInvocation{
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000201 Inputs: []string{"Android.bp"},
202 Outputs: []string{output},
203 Args: allArgs,
204 Description: description,
Lukacs T. Berki2fad3412022-01-04 14:40:13 +0100205 // NB: Changing the value of this environment variable will not result in a
206 // rebuild. The bootstrap Ninja file will change, but apparently Ninja does
207 // not consider changing the pool specified in a statement a change that's
208 // worth rebuilding for.
209 Console: os.Getenv("SOONG_UNBUFFERED_OUTPUT") == "1",
Lukacs T. Berki13644272022-01-05 10:29:56 +0100210 Env: invocationEnv,
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200211 }
212}
213
Colin Cross9191df22021-10-29 13:11:32 -0700214// bootstrapEpochCleanup deletes files used by bootstrap during incremental builds across
215// incompatible changes. Incompatible changes are marked by incrementing the bootstrapEpoch
216// constant. A tree is considered out of date for the current epoch of the
217// .soong.bootstrap.epoch.<epoch> file doesn't exist.
218func bootstrapEpochCleanup(ctx Context, config Config) {
219 epochFile := fmt.Sprintf(".soong.bootstrap.epoch.%d", bootstrapEpoch)
220 epochPath := filepath.Join(config.SoongOutDir(), epochFile)
221 if exists, err := fileExists(epochPath); err != nil {
222 ctx.Fatalf("failed to check if bootstrap epoch file %q exists: %q", epochPath, err)
223 } else if !exists {
224 // The tree is out of date for the current epoch, delete files used by bootstrap
225 // and force the primary builder to rerun.
226 os.Remove(filepath.Join(config.SoongOutDir(), "build.ninja"))
227 for _, globFile := range bootstrapGlobFileList(config) {
228 os.Remove(globFile)
229 }
230
231 // Mark the tree as up to date with the current epoch by writing the epoch marker file.
232 writeEmptyFile(ctx, epochPath)
233 }
234}
235
236func bootstrapGlobFileList(config Config) []string {
237 return []string{
238 config.NamedGlobFile(soongBuildTag),
239 config.NamedGlobFile(bp2buildTag),
240 config.NamedGlobFile(jsonModuleGraphTag),
241 config.NamedGlobFile(queryviewTag),
242 config.NamedGlobFile(soongDocsTag),
243 }
244}
245
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200246func bootstrapBlueprint(ctx Context, config Config) {
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100247 ctx.BeginTrace(metrics.RunSoong, "blueprint bootstrap")
248 defer ctx.EndTrace()
249
Colin Cross9191df22021-10-29 13:11:32 -0700250 // Clean up some files for incremental builds across incompatible changes.
251 bootstrapEpochCleanup(ctx, config)
252
Cole Faust65f298c2021-10-28 16:05:13 -0700253 mainSoongBuildExtraArgs := []string{"-o", config.SoongNinjaFile()}
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200254 if config.EmptyNinjaFile() {
255 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--empty-ninja-file")
Lukacs T. Berki745380c2021-04-12 12:07:44 +0200256 }
Chris Parsonsef615e52022-08-18 22:04:11 -0400257 if config.bazelProdMode {
258 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--bazel-mode")
259 }
260 if config.bazelDevMode {
261 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--bazel-mode-dev")
262 }
Lukacs T. Berki745380c2021-04-12 12:07:44 +0200263
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200264 mainSoongBuildInvocation := primaryBuilderInvocation(
265 config,
266 soongBuildTag,
Cole Faust65f298c2021-10-28 16:05:13 -0700267 config.SoongNinjaFile(),
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000268 mainSoongBuildExtraArgs,
269 fmt.Sprintf("analyzing Android.bp files and generating ninja file at %s", config.SoongNinjaFile()),
270 )
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200271
Chris Parsonsef615e52022-08-18 22:04:11 -0400272 if config.BazelBuildEnabled() {
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200273 // Mixed builds call Bazel from soong_build and they therefore need the
274 // Bazel workspace to be available. Make that so by adding a dependency on
275 // the bp2build marker file to the action that invokes soong_build .
276 mainSoongBuildInvocation.Inputs = append(mainSoongBuildInvocation.Inputs,
277 config.Bp2BuildMarkerFile())
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200278 }
279
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200280 bp2buildInvocation := primaryBuilderInvocation(
281 config,
282 bp2buildTag,
283 config.Bp2BuildMarkerFile(),
284 []string{
285 "--bp2build_marker", config.Bp2BuildMarkerFile(),
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000286 },
287 fmt.Sprintf("converting Android.bp files to BUILD files at %s/bp2build", config.SoongOutDir()),
288 )
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200289
290 jsonModuleGraphInvocation := primaryBuilderInvocation(
291 config,
292 jsonModuleGraphTag,
293 config.ModuleGraphFile(),
294 []string{
295 "--module_graph_file", config.ModuleGraphFile(),
kgui67007242022-01-25 13:50:25 +0800296 "--module_actions_file", config.ModuleActionsFile(),
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000297 },
298 fmt.Sprintf("generating the Soong module graph at %s", config.ModuleGraphFile()),
299 )
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200300
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000301 queryviewDir := filepath.Join(config.SoongOutDir(), "queryview")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200302 queryviewInvocation := primaryBuilderInvocation(
303 config,
304 queryviewTag,
305 config.QueryviewMarkerFile(),
306 []string{
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000307 "--bazel_queryview_dir", queryviewDir,
308 },
309 fmt.Sprintf("generating the Soong module graph as a Bazel workspace at %s", queryviewDir),
310 )
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200311
312 soongDocsInvocation := primaryBuilderInvocation(
313 config,
314 soongDocsTag,
315 config.SoongDocsHtml(),
316 []string{
317 "--soong_docs", config.SoongDocsHtml(),
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000318 },
319 fmt.Sprintf("generating Soong docs at %s", config.SoongDocsHtml()),
320 )
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200321
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200322 // The glob .ninja files are subninja'd. However, they are generated during
323 // the build itself so we write an empty file if the file does not exist yet
324 // so that the subninja doesn't fail on clean builds
Colin Cross9191df22021-10-29 13:11:32 -0700325 for _, globFile := range bootstrapGlobFileList(config) {
326 writeEmptyFile(ctx, globFile)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200327 }
328
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200329 var blueprintArgs bootstrap.Args
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200330
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200331 blueprintArgs.ModuleListFile = filepath.Join(config.FileListDir(), "Android.bp.list")
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100332 blueprintArgs.OutFile = shared.JoinPath(config.SoongOutDir(), "bootstrap.ninja")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200333 blueprintArgs.EmptyNinjaFile = false
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200334
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100335 blueprintCtx := blueprint.NewContext()
336 blueprintCtx.SetIgnoreUnknownModuleTypes(true)
337 blueprintConfig := BlueprintConfig{
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200338 soongOutDir: config.SoongOutDir(),
339 toolDir: config.HostToolDir(),
340 outDir: config.OutDir(),
341 runGoTests: !config.skipSoongTests,
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200342 // If we want to debug soong_build, we need to compile it for debugging
343 debugCompilation: os.Getenv("SOONG_DELVE") != "",
Usta Shrestha9b3724a2022-08-09 14:47:52 -0400344 subninjas: bootstrapGlobFileList(config),
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200345 primaryBuilderInvocations: []bootstrap.PrimaryBuilderInvocation{
346 mainSoongBuildInvocation,
347 bp2buildInvocation,
348 jsonModuleGraphInvocation,
349 queryviewInvocation,
350 soongDocsInvocation},
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100351 }
352
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200353 bootstrapDeps := bootstrap.RunBlueprint(blueprintArgs, bootstrap.DoEverything, blueprintCtx, blueprintConfig)
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100354 bootstrapDepFile := shared.JoinPath(config.SoongOutDir(), "bootstrap.ninja.d")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200355 err := deptools.WriteDepFile(bootstrapDepFile, blueprintArgs.OutFile, bootstrapDeps)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200356 if err != nil {
357 ctx.Fatalf("Error writing depfile '%s': %s", bootstrapDepFile, err)
358 }
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100359}
360
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200361func checkEnvironmentFile(currentEnv *Environment, envFile string) {
362 getenv := func(k string) string {
363 v, _ := currentEnv.Get(k)
364 return v
365 }
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200366
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200367 if stale, _ := shared.StaleEnvFile(envFile, getenv); stale {
368 os.Remove(envFile)
369 }
370}
371
Dan Willemsen1e704462016-08-21 15:17:17 -0700372func runSoong(ctx Context, config Config) {
Nan Zhang17f27672018-12-12 16:01:49 -0800373 ctx.BeginTrace(metrics.RunSoong, "soong")
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700374 defer ctx.EndTrace()
375
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100376 // We have two environment files: .available is the one with every variable,
377 // .used with the ones that were actually used. The latter is used to
378 // determine whether Soong needs to be re-run since why re-run it if only
379 // unused variables were changed?
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200380 envFile := filepath.Join(config.SoongOutDir(), availableEnvFile)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100381
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100382 // This is done unconditionally, but does not take a measurable amount of time
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200383 bootstrapBlueprint(ctx, config)
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700384
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100385 soongBuildEnv := config.Environment().Copy()
386 soongBuildEnv.Set("TOP", os.Getenv("TOP"))
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100387 // For Bazel mixed builds.
388 soongBuildEnv.Set("BAZEL_PATH", "./tools/bazel")
389 soongBuildEnv.Set("BAZEL_HOME", filepath.Join(config.BazelOutDir(), "bazelhome"))
390 soongBuildEnv.Set("BAZEL_OUTPUT_BASE", filepath.Join(config.BazelOutDir(), "output"))
391 soongBuildEnv.Set("BAZEL_WORKSPACE", absPath(ctx, "."))
392 soongBuildEnv.Set("BAZEL_METRICS_DIR", config.BazelMetricsDir())
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500393 soongBuildEnv.Set("LOG_DIR", config.LogsDir())
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100394
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100395 // For Soong bootstrapping tests
396 if os.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
397 soongBuildEnv.Set("ALLOW_MISSING_DEPENDENCIES", "true")
398 }
399
Paul Duffin5e85c662021-03-05 12:26:14 +0000400 err := writeEnvironmentFile(ctx, envFile, soongBuildEnv.AsMap())
401 if err != nil {
402 ctx.Fatalf("failed to write environment file %s: %s", envFile, err)
403 }
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100404
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700405 func() {
Nan Zhang17f27672018-12-12 16:01:49 -0800406 ctx.BeginTrace(metrics.RunSoong, "environment check")
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700407 defer ctx.EndTrace()
408
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200409 checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(soongBuildTag))
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200410
Chris Parsonsef615e52022-08-18 22:04:11 -0400411 if config.BazelBuildEnabled() || config.Bp2Build() {
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200412 checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(bp2buildTag))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200413 }
414
415 if config.JsonModuleGraph() {
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200416 checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(jsonModuleGraphTag))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200417 }
418
419 if config.Queryview() {
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200420 checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(queryviewTag))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200421 }
422
423 if config.SoongDocs() {
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200424 checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(soongDocsTag))
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700425 }
426 }()
427
Colin Cross9191df22021-10-29 13:11:32 -0700428 runMicrofactory(ctx, config, "bpglob", "github.com/google/blueprint/bootstrap/bpglob",
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700429 map[string]string{"github.com/google/blueprint": "build/blueprint"})
Dan Willemsen5af1cbe2018-07-05 21:46:51 -0700430
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200431 ninja := func(name, ninjaFile string, targets ...string) {
Nan Zhang17f27672018-12-12 16:01:49 -0800432 ctx.BeginTrace(metrics.RunSoong, name)
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700433 defer ctx.EndTrace()
434
Dan Willemsenb82471a2018-05-17 16:37:09 -0700435 fifo := filepath.Join(config.OutDir(), ".ninja_fifo")
Colin Crossb98d3bc2019-03-21 16:02:58 -0700436 nr := status.NewNinjaReader(ctx, ctx.Status.StartTool(), fifo)
437 defer nr.Close()
Dan Willemsenb82471a2018-05-17 16:37:09 -0700438
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200439 ninjaArgs := []string{
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700440 "-d", "keepdepfile",
Dan Willemsen08218222020-05-18 14:02:02 -0700441 "-d", "stats",
Dan Willemsen6587bed2020-04-18 20:25:59 -0700442 "-o", "usesphonyoutputs=yes",
443 "-o", "preremoveoutputs=yes",
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700444 "-w", "dupbuild=err",
Dan Willemsen6587bed2020-04-18 20:25:59 -0700445 "-w", "outputdir=err",
446 "-w", "missingoutfile=err",
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700447 "-j", strconv.Itoa(config.Parallel()),
Dan Willemsen02736672018-07-17 17:54:31 -0700448 "--frontend_file", fifo,
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200449 "-f", filepath.Join(config.SoongOutDir(), ninjaFile),
450 }
451
Usta Shrestha8dc8b0a2022-08-10 17:39:37 -0400452 if extra, ok := config.Environment().Get("SOONG_UI_NINJA_ARGS"); ok {
453 ctx.Printf(`CAUTION: arguments in $SOONG_UI_NINJA_ARGS=%q, e.g. "-n", can make soong_build FAIL or INCORRECT`, extra)
454 ninjaArgs = append(ninjaArgs, strings.Fields(extra)...)
455 }
456
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200457 ninjaArgs = append(ninjaArgs, targets...)
458 cmd := Command(ctx, config, "soong "+name,
459 config.PrebuiltBuildTool("ninja"), ninjaArgs...)
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500460
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100461 var ninjaEnv Environment
Lukacs T. Berki73ab9282021-03-10 10:48:39 +0100462
463 // This is currently how the command line to invoke soong_build finds the
464 // root of the source tree and the output root
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100465 ninjaEnv.Set("TOP", os.Getenv("TOP"))
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100466
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100467 cmd.Environment = &ninjaEnv
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700468 cmd.Sandbox = soongSandbox
Colin Cross7b97ecd2019-06-19 13:17:59 -0700469 cmd.RunAndStreamOrFatal()
Dan Willemsen1e704462016-08-21 15:17:17 -0700470 }
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200471
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200472 targets := make([]string, 0, 0)
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200473
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200474 if config.JsonModuleGraph() {
475 targets = append(targets, config.ModuleGraphFile())
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200476 }
477
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200478 if config.Bp2Build() {
479 targets = append(targets, config.Bp2BuildMarkerFile())
480 }
481
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200482 if config.Queryview() {
483 targets = append(targets, config.QueryviewMarkerFile())
484 }
485
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200486 if config.SoongDocs() {
487 targets = append(targets, config.SoongDocsHtml())
488 }
489
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200490 if config.SoongBuildInvocationNeeded() {
491 // 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 -0700492 targets = append(targets, config.SoongNinjaFile())
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200493 }
494
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100495 ninja("bootstrap", "bootstrap.ninja", targets...)
Colin Crossb72c9092020-02-10 11:23:49 -0800496
Jingwen Cheneb76c432021-01-28 08:22:12 -0500497 if shouldCollectBuildSoongMetrics(config) {
498 soongBuildMetrics := loadSoongBuildMetrics(ctx, config)
Dan Willemsende360442022-04-20 21:21:55 -0700499 if soongBuildMetrics != nil {
500 logSoongBuildMetrics(ctx, soongBuildMetrics)
501 if ctx.Metrics != nil {
502 ctx.Metrics.SetSoongBuildMetrics(soongBuildMetrics)
503 }
504 }
Jingwen Cheneb76c432021-01-28 08:22:12 -0500505 }
Colin Crossb72c9092020-02-10 11:23:49 -0800506
Colin Cross8ba7d472020-06-25 11:27:52 -0700507 distGzipFile(ctx, config, config.SoongNinjaFile(), "soong")
Jihoon Kang9f4f8a32022-08-16 00:57:30 +0000508 distFile(ctx, config, config.SoongVarsFile(), "soong")
Colin Cross8ba7d472020-06-25 11:27:52 -0700509
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000510 if !config.SkipKati() {
Colin Cross8ba7d472020-06-25 11:27:52 -0700511 distGzipFile(ctx, config, config.SoongAndroidMk(), "soong")
512 distGzipFile(ctx, config, config.SoongMakeVarsMk(), "soong")
513 }
514
Rob Seymour33cd10d2022-03-02 23:10:25 +0000515 if config.JsonModuleGraph() {
516 distGzipFile(ctx, config, config.ModuleGraphFile(), "soong")
517 }
Colin Crossb72c9092020-02-10 11:23:49 -0800518}
519
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100520func runMicrofactory(ctx Context, config Config, name string, pkg string, mapping map[string]string) {
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700521 ctx.BeginTrace(metrics.RunSoong, name)
522 defer ctx.EndTrace()
523 cfg := microfactory.Config{TrimPath: absPath(ctx, ".")}
524 for pkgPrefix, pathPrefix := range mapping {
525 cfg.Map(pkgPrefix, pathPrefix)
526 }
527
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100528 exePath := filepath.Join(config.SoongOutDir(), name)
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700529 dir := filepath.Dir(exePath)
530 if err := os.MkdirAll(dir, 0777); err != nil {
531 ctx.Fatalf("cannot create %s: %s", dir, err)
532 }
533 if _, err := microfactory.Build(&cfg, exePath, pkg); err != nil {
534 ctx.Fatalf("failed to build %s: %s", name, err)
535 }
536}
537
Jingwen Cheneb76c432021-01-28 08:22:12 -0500538func shouldCollectBuildSoongMetrics(config Config) bool {
Jingwen Chendd9725c2021-06-24 08:41:16 +0000539 // Do not collect metrics protobuf if the soong_build binary ran as the
540 // bp2build converter or the JSON graph dump.
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200541 return config.SoongBuildInvocationNeeded()
Jingwen Cheneb76c432021-01-28 08:22:12 -0500542}
543
Colin Crossb72c9092020-02-10 11:23:49 -0800544func loadSoongBuildMetrics(ctx Context, config Config) *soong_metrics_proto.SoongBuildMetrics {
Chris Parsons715b08f2022-03-22 19:23:40 -0400545 soongBuildMetricsFile := filepath.Join(config.LogsDir(), "soong_build_metrics.pb")
Dan Willemsende360442022-04-20 21:21:55 -0700546 buf, err := os.ReadFile(soongBuildMetricsFile)
547 if errors.Is(err, fs.ErrNotExist) {
548 // Soong may not have run during this invocation
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400549 ctx.Verbosef("Failed to read metrics file, %s: %s", soongBuildMetricsFile, err)
Dan Willemsende360442022-04-20 21:21:55 -0700550 return nil
551 } else if err != nil {
Colin Crossb72c9092020-02-10 11:23:49 -0800552 ctx.Fatalf("Failed to load %s: %s", soongBuildMetricsFile, err)
553 }
554 soongBuildMetrics := &soong_metrics_proto.SoongBuildMetrics{}
555 err = proto.Unmarshal(buf, soongBuildMetrics)
556 if err != nil {
557 ctx.Fatalf("Failed to unmarshal %s: %s", soongBuildMetricsFile, err)
558 }
559 return soongBuildMetrics
560}
561
562func logSoongBuildMetrics(ctx Context, metrics *soong_metrics_proto.SoongBuildMetrics) {
563 ctx.Verbosef("soong_build metrics:")
564 ctx.Verbosef(" modules: %v", metrics.GetModules())
565 ctx.Verbosef(" variants: %v", metrics.GetVariants())
566 ctx.Verbosef(" max heap size: %v MB", metrics.GetMaxHeapSize()/1e6)
567 ctx.Verbosef(" total allocation count: %v", metrics.GetTotalAllocCount())
568 ctx.Verbosef(" total allocation size: %v MB", metrics.GetTotalAllocSize()/1e6)
569
Dan Willemsen1e704462016-08-21 15:17:17 -0700570}