blob: ee2b7c8ab0ff05343f0919927e868f1d5c46ad36 [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
Lukacs T. Berkic541cd22022-10-26 07:26:50 +000044 soongBuildTag = "build"
45 bp2buildFilesTag = "bp2build_files"
46 bp2buildWorkspaceTag = "bp2build_workspace"
47 jsonModuleGraphTag = "modulegraph"
48 queryviewTag = "queryview"
49 apiBp2buildTag = "api_bp2build"
50 soongDocsTag = "soong_docs"
Colin Cross9191df22021-10-29 13:11:32 -070051
52 // bootstrapEpoch is used to determine if an incremental build is incompatible with the current
53 // version of bootstrap and needs cleaning before continuing the build. Increment this for
54 // incompatible changes, for example when moving the location of the bpglob binary that is
55 // executed during bootstrap before the primary builder has had a chance to update the path.
Lukacs T. Berki9985d9a2021-11-04 11:47:42 +010056 bootstrapEpoch = 1
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020057)
58
Lukacs T. Berki7690c092021-02-26 14:27:36 +010059func writeEnvironmentFile(ctx Context, envFile string, envDeps map[string]string) error {
60 data, err := shared.EnvFileContents(envDeps)
61 if err != nil {
62 return err
63 }
64
65 return ioutil.WriteFile(envFile, data, 0644)
66}
67
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000068// This uses Android.bp files and various tools to generate <builddir>/build.ninja.
69//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010070// However, the execution of <builddir>/build.ninja happens later in
71// build/soong/ui/build/build.go#Build()
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000072//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010073// We want to rely on as few prebuilts as possible, so we need to bootstrap
74// Soong. The process is as follows:
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000075//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010076// 1. We use "Microfactory", a simple tool to compile Go code, to build
77// first itself, then soong_ui from soong_ui.bash. This binary contains
78// parts of soong_build that are needed to build itself.
79// 2. This simplified version of soong_build then reads the Blueprint files
80// that describe itself and emits .bootstrap/build.ninja that describes
81// how to build its full version and use that to produce the final Ninja
82// file Soong emits.
83// 3. soong_ui executes .bootstrap/build.ninja
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000084//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010085// (After this, Kati is executed to parse the Makefiles, but that's not part of
86// bootstrapping Soong)
87
88// A tiny struct used to tell Blueprint that it's in bootstrap mode. It would
89// probably be nicer to use a flag in bootstrap.Args instead.
90type BlueprintConfig struct {
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +020091 toolDir string
92 soongOutDir string
93 outDir string
94 runGoTests bool
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +020095 debugCompilation bool
96 subninjas []string
97 primaryBuilderInvocations []bootstrap.PrimaryBuilderInvocation
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010098}
99
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200100func (c BlueprintConfig) HostToolDir() string {
101 return c.toolDir
102}
103
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200104func (c BlueprintConfig) SoongOutDir() string {
105 return c.soongOutDir
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100106}
107
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200108func (c BlueprintConfig) OutDir() string {
109 return c.outDir
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100110}
111
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +0200112func (c BlueprintConfig) RunGoTests() bool {
113 return c.runGoTests
114}
115
Lukacs T. Berki5f6cb1d2021-03-17 15:03:14 +0100116func (c BlueprintConfig) DebugCompilation() bool {
117 return c.debugCompilation
118}
119
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +0200120func (c BlueprintConfig) Subninjas() []string {
121 return c.subninjas
122}
123
124func (c BlueprintConfig) PrimaryBuilderInvocations() []bootstrap.PrimaryBuilderInvocation {
125 return c.primaryBuilderInvocations
126}
127
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200128func environmentArgs(config Config, tag string) []string {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200129 return []string{
130 "--available_env", shared.JoinPath(config.SoongOutDir(), availableEnvFile),
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200131 "--used_env", config.UsedEnvFile(tag),
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200132 }
133}
Spandan Das8f99ae62021-06-11 16:48:06 +0000134
Colin Cross9191df22021-10-29 13:11:32 -0700135func writeEmptyFile(ctx Context, path string) {
Spandan Das8f99ae62021-06-11 16:48:06 +0000136 err := os.MkdirAll(filepath.Dir(path), 0777)
137 if err != nil {
Colin Cross9191df22021-10-29 13:11:32 -0700138 ctx.Fatalf("Failed to create parent directories of empty file '%s': %s", path, err)
Spandan Das8f99ae62021-06-11 16:48:06 +0000139 }
140
Colin Cross9191df22021-10-29 13:11:32 -0700141 if exists, err := fileExists(path); err != nil {
142 ctx.Fatalf("Failed to check if file '%s' exists: %s", path, err)
143 } else if !exists {
Spandan Das8f99ae62021-06-11 16:48:06 +0000144 err = ioutil.WriteFile(path, nil, 0666)
145 if err != nil {
Colin Cross9191df22021-10-29 13:11:32 -0700146 ctx.Fatalf("Failed to create empty file '%s': %s", path, err)
Spandan Das8f99ae62021-06-11 16:48:06 +0000147 }
148 }
149}
150
Colin Cross9191df22021-10-29 13:11:32 -0700151func fileExists(path string) (bool, error) {
152 if _, err := os.Stat(path); os.IsNotExist(err) {
153 return false, nil
154 } else if err != nil {
155 return false, err
156 }
157 return true, nil
158}
159
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000160func primaryBuilderInvocation(
161 config Config,
162 name string,
163 output string,
164 specificArgs []string,
165 description string) bootstrap.PrimaryBuilderInvocation {
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200166 commonArgs := make([]string, 0, 0)
167
168 if !config.skipSoongTests {
169 commonArgs = append(commonArgs, "-t")
170 }
171
172 commonArgs = append(commonArgs, "-l", filepath.Join(config.FileListDir(), "Android.bp.list"))
Lukacs T. Berki13644272022-01-05 10:29:56 +0100173 invocationEnv := make(map[string]string)
ustafb67fd12022-08-19 19:26:00 -0400174 if os.Getenv("SOONG_DELVE") != "" {
175 //debug mode
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
ustafb67fd12022-08-19 19:26:00 -0400190 var allArgs []string
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200191 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),
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000239 config.NamedGlobFile(bp2buildFilesTag),
Colin Cross9191df22021-10-29 13:11:32 -0700240 config.NamedGlobFile(jsonModuleGraphTag),
241 config.NamedGlobFile(queryviewTag),
Spandan Das5af0bd32022-09-28 20:43:08 +0000242 config.NamedGlobFile(apiBp2buildTag),
Colin Cross9191df22021-10-29 13:11:32 -0700243 config.NamedGlobFile(soongDocsTag),
244 }
245}
246
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200247func bootstrapBlueprint(ctx Context, config Config) {
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100248 ctx.BeginTrace(metrics.RunSoong, "blueprint bootstrap")
249 defer ctx.EndTrace()
250
Colin Cross9191df22021-10-29 13:11:32 -0700251 // Clean up some files for incremental builds across incompatible changes.
252 bootstrapEpochCleanup(ctx, config)
253
Cole Faust65f298c2021-10-28 16:05:13 -0700254 mainSoongBuildExtraArgs := []string{"-o", config.SoongNinjaFile()}
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200255 if config.EmptyNinjaFile() {
256 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--empty-ninja-file")
Lukacs T. Berki745380c2021-04-12 12:07:44 +0200257 }
Chris Parsonsef615e52022-08-18 22:04:11 -0400258 if config.bazelProdMode {
259 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--bazel-mode")
260 }
261 if config.bazelDevMode {
262 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--bazel-mode-dev")
263 }
MarkDacekb78465d2022-10-18 20:10:16 +0000264 if config.bazelStagingMode {
265 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--bazel-mode-staging")
266 }
Lukacs T. Berki745380c2021-04-12 12:07:44 +0200267
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200268 mainSoongBuildInvocation := primaryBuilderInvocation(
269 config,
270 soongBuildTag,
Cole Faust65f298c2021-10-28 16:05:13 -0700271 config.SoongNinjaFile(),
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000272 mainSoongBuildExtraArgs,
273 fmt.Sprintf("analyzing Android.bp files and generating ninja file at %s", config.SoongNinjaFile()),
274 )
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200275
Chris Parsonsef615e52022-08-18 22:04:11 -0400276 if config.BazelBuildEnabled() {
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200277 // Mixed builds call Bazel from soong_build and they therefore need the
278 // Bazel workspace to be available. Make that so by adding a dependency on
279 // the bp2build marker file to the action that invokes soong_build .
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000280 mainSoongBuildInvocation.OrderOnlyInputs = append(mainSoongBuildInvocation.OrderOnlyInputs,
281 config.Bp2BuildWorkspaceMarkerFile())
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200282 }
283
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200284 bp2buildInvocation := primaryBuilderInvocation(
285 config,
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000286 bp2buildFilesTag,
287 config.Bp2BuildFilesMarkerFile(),
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200288 []string{
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000289 "--bp2build_marker", config.Bp2BuildFilesMarkerFile(),
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000290 },
291 fmt.Sprintf("converting Android.bp files to BUILD files at %s/bp2build", config.SoongOutDir()),
292 )
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200293
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000294 bp2buildWorkspaceInvocation := primaryBuilderInvocation(
295 config,
296 bp2buildWorkspaceTag,
297 config.Bp2BuildWorkspaceMarkerFile(),
298 []string{
299 "--symlink_forest_marker", config.Bp2BuildWorkspaceMarkerFile(),
300 },
301 fmt.Sprintf("Creating Bazel symlink forest"),
302 )
303
304 bp2buildWorkspaceInvocation.Inputs = append(bp2buildWorkspaceInvocation.Inputs,
305 config.Bp2BuildFilesMarkerFile())
306
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200307 jsonModuleGraphInvocation := primaryBuilderInvocation(
308 config,
309 jsonModuleGraphTag,
310 config.ModuleGraphFile(),
311 []string{
312 "--module_graph_file", config.ModuleGraphFile(),
kgui67007242022-01-25 13:50:25 +0800313 "--module_actions_file", config.ModuleActionsFile(),
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000314 },
315 fmt.Sprintf("generating the Soong module graph at %s", config.ModuleGraphFile()),
316 )
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200317
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000318 queryviewDir := filepath.Join(config.SoongOutDir(), "queryview")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200319 queryviewInvocation := primaryBuilderInvocation(
320 config,
321 queryviewTag,
322 config.QueryviewMarkerFile(),
323 []string{
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000324 "--bazel_queryview_dir", queryviewDir,
325 },
326 fmt.Sprintf("generating the Soong module graph as a Bazel workspace at %s", queryviewDir),
327 )
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200328
Spandan Das5af0bd32022-09-28 20:43:08 +0000329 // The BUILD files will be generated in out/soong/.api_bp2build (no symlinks to src files)
330 // The final workspace will be generated in out/soong/api_bp2build
331 apiBp2buildDir := filepath.Join(config.SoongOutDir(), ".api_bp2build")
332 apiBp2buildInvocation := primaryBuilderInvocation(
333 config,
334 apiBp2buildTag,
335 config.ApiBp2buildMarkerFile(),
336 []string{
337 "--bazel_api_bp2build_dir", apiBp2buildDir,
338 },
339 fmt.Sprintf("generating BUILD files for API contributions at %s", apiBp2buildDir),
340 )
341
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200342 soongDocsInvocation := primaryBuilderInvocation(
343 config,
344 soongDocsTag,
345 config.SoongDocsHtml(),
346 []string{
347 "--soong_docs", config.SoongDocsHtml(),
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000348 },
349 fmt.Sprintf("generating Soong docs at %s", config.SoongDocsHtml()),
350 )
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200351
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200352 // The glob .ninja files are subninja'd. However, they are generated during
353 // the build itself so we write an empty file if the file does not exist yet
354 // so that the subninja doesn't fail on clean builds
Colin Cross9191df22021-10-29 13:11:32 -0700355 for _, globFile := range bootstrapGlobFileList(config) {
356 writeEmptyFile(ctx, globFile)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200357 }
358
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200359 var blueprintArgs bootstrap.Args
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200360
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200361 blueprintArgs.ModuleListFile = filepath.Join(config.FileListDir(), "Android.bp.list")
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100362 blueprintArgs.OutFile = shared.JoinPath(config.SoongOutDir(), "bootstrap.ninja")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200363 blueprintArgs.EmptyNinjaFile = false
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200364
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100365 blueprintCtx := blueprint.NewContext()
366 blueprintCtx.SetIgnoreUnknownModuleTypes(true)
367 blueprintConfig := BlueprintConfig{
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200368 soongOutDir: config.SoongOutDir(),
369 toolDir: config.HostToolDir(),
370 outDir: config.OutDir(),
371 runGoTests: !config.skipSoongTests,
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200372 // If we want to debug soong_build, we need to compile it for debugging
373 debugCompilation: os.Getenv("SOONG_DELVE") != "",
Usta Shrestha9b3724a2022-08-09 14:47:52 -0400374 subninjas: bootstrapGlobFileList(config),
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200375 primaryBuilderInvocations: []bootstrap.PrimaryBuilderInvocation{
376 mainSoongBuildInvocation,
377 bp2buildInvocation,
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000378 bp2buildWorkspaceInvocation,
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200379 jsonModuleGraphInvocation,
380 queryviewInvocation,
Spandan Das5af0bd32022-09-28 20:43:08 +0000381 apiBp2buildInvocation,
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200382 soongDocsInvocation},
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100383 }
384
usta5bb4a5d2022-08-24 12:53:46 -0400385 // since `bootstrap.ninja` is regenerated unconditionally, we ignore the deps, i.e. little
386 // reason to write a `bootstrap.ninja.d` file
387 _ = bootstrap.RunBlueprint(blueprintArgs, bootstrap.DoEverything, blueprintCtx, blueprintConfig)
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100388}
389
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200390func checkEnvironmentFile(currentEnv *Environment, envFile string) {
391 getenv := func(k string) string {
392 v, _ := currentEnv.Get(k)
393 return v
394 }
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200395
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200396 if stale, _ := shared.StaleEnvFile(envFile, getenv); stale {
397 os.Remove(envFile)
398 }
399}
400
Dan Willemsen1e704462016-08-21 15:17:17 -0700401func runSoong(ctx Context, config Config) {
Nan Zhang17f27672018-12-12 16:01:49 -0800402 ctx.BeginTrace(metrics.RunSoong, "soong")
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700403 defer ctx.EndTrace()
404
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100405 // We have two environment files: .available is the one with every variable,
406 // .used with the ones that were actually used. The latter is used to
407 // determine whether Soong needs to be re-run since why re-run it if only
408 // unused variables were changed?
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200409 envFile := filepath.Join(config.SoongOutDir(), availableEnvFile)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100410
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100411 // This is done unconditionally, but does not take a measurable amount of time
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200412 bootstrapBlueprint(ctx, config)
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700413
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100414 soongBuildEnv := config.Environment().Copy()
415 soongBuildEnv.Set("TOP", os.Getenv("TOP"))
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100416 // For Bazel mixed builds.
Joe Onoratoba29f382022-10-24 06:38:11 -0700417 soongBuildEnv.Set("BAZEL_PATH", "./build/bazel/bin/bazel")
Chris Parsonsa9bef142022-09-28 15:07:46 -0400418 // Bazel's HOME var is set to an output subdirectory which doesn't exist. This
419 // prevents Bazel from file I/O in the actual user HOME directory.
420 soongBuildEnv.Set("BAZEL_HOME", absPath(ctx, filepath.Join(config.BazelOutDir(), "bazelhome")))
Liz Kammer2af5ea82022-11-11 14:21:03 -0500421 soongBuildEnv.Set("BAZEL_OUTPUT_BASE", config.bazelOutputBase())
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100422 soongBuildEnv.Set("BAZEL_WORKSPACE", absPath(ctx, "."))
423 soongBuildEnv.Set("BAZEL_METRICS_DIR", config.BazelMetricsDir())
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500424 soongBuildEnv.Set("LOG_DIR", config.LogsDir())
Jingwen Chen3b13b612022-10-17 12:14:26 +0000425 soongBuildEnv.Set("BAZEL_DEPS_FILE", absPath(ctx, filepath.Join(config.BazelOutDir(), "bazel.list")))
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100426
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100427 // For Soong bootstrapping tests
428 if os.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
429 soongBuildEnv.Set("ALLOW_MISSING_DEPENDENCIES", "true")
430 }
431
Paul Duffin5e85c662021-03-05 12:26:14 +0000432 err := writeEnvironmentFile(ctx, envFile, soongBuildEnv.AsMap())
433 if err != nil {
434 ctx.Fatalf("failed to write environment file %s: %s", envFile, err)
435 }
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100436
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700437 func() {
Nan Zhang17f27672018-12-12 16:01:49 -0800438 ctx.BeginTrace(metrics.RunSoong, "environment check")
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700439 defer ctx.EndTrace()
440
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200441 checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(soongBuildTag))
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200442
Chris Parsonsef615e52022-08-18 22:04:11 -0400443 if config.BazelBuildEnabled() || config.Bp2Build() {
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000444 checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(bp2buildFilesTag))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200445 }
446
447 if config.JsonModuleGraph() {
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200448 checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(jsonModuleGraphTag))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200449 }
450
451 if config.Queryview() {
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200452 checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(queryviewTag))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200453 }
454
Spandan Das5af0bd32022-09-28 20:43:08 +0000455 if config.ApiBp2build() {
456 checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(apiBp2buildTag))
457 }
458
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200459 if config.SoongDocs() {
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200460 checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(soongDocsTag))
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700461 }
462 }()
463
Colin Cross9191df22021-10-29 13:11:32 -0700464 runMicrofactory(ctx, config, "bpglob", "github.com/google/blueprint/bootstrap/bpglob",
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700465 map[string]string{"github.com/google/blueprint": "build/blueprint"})
Dan Willemsen5af1cbe2018-07-05 21:46:51 -0700466
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200467 ninja := func(name, ninjaFile string, targets ...string) {
Nan Zhang17f27672018-12-12 16:01:49 -0800468 ctx.BeginTrace(metrics.RunSoong, name)
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700469 defer ctx.EndTrace()
470
Dan Willemsenb82471a2018-05-17 16:37:09 -0700471 fifo := filepath.Join(config.OutDir(), ".ninja_fifo")
Colin Crossb98d3bc2019-03-21 16:02:58 -0700472 nr := status.NewNinjaReader(ctx, ctx.Status.StartTool(), fifo)
473 defer nr.Close()
Dan Willemsenb82471a2018-05-17 16:37:09 -0700474
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200475 ninjaArgs := []string{
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700476 "-d", "keepdepfile",
Dan Willemsen08218222020-05-18 14:02:02 -0700477 "-d", "stats",
Dan Willemsen6587bed2020-04-18 20:25:59 -0700478 "-o", "usesphonyoutputs=yes",
479 "-o", "preremoveoutputs=yes",
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700480 "-w", "dupbuild=err",
Dan Willemsen6587bed2020-04-18 20:25:59 -0700481 "-w", "outputdir=err",
482 "-w", "missingoutfile=err",
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700483 "-j", strconv.Itoa(config.Parallel()),
Dan Willemsen02736672018-07-17 17:54:31 -0700484 "--frontend_file", fifo,
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200485 "-f", filepath.Join(config.SoongOutDir(), ninjaFile),
486 }
487
Usta Shrestha8dc8b0a2022-08-10 17:39:37 -0400488 if extra, ok := config.Environment().Get("SOONG_UI_NINJA_ARGS"); ok {
489 ctx.Printf(`CAUTION: arguments in $SOONG_UI_NINJA_ARGS=%q, e.g. "-n", can make soong_build FAIL or INCORRECT`, extra)
490 ninjaArgs = append(ninjaArgs, strings.Fields(extra)...)
491 }
492
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200493 ninjaArgs = append(ninjaArgs, targets...)
494 cmd := Command(ctx, config, "soong "+name,
495 config.PrebuiltBuildTool("ninja"), ninjaArgs...)
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500496
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100497 var ninjaEnv Environment
Lukacs T. Berki73ab9282021-03-10 10:48:39 +0100498
499 // This is currently how the command line to invoke soong_build finds the
500 // root of the source tree and the output root
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100501 ninjaEnv.Set("TOP", os.Getenv("TOP"))
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100502
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100503 cmd.Environment = &ninjaEnv
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700504 cmd.Sandbox = soongSandbox
Colin Cross7b97ecd2019-06-19 13:17:59 -0700505 cmd.RunAndStreamOrFatal()
Dan Willemsen1e704462016-08-21 15:17:17 -0700506 }
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200507
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200508 targets := make([]string, 0, 0)
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200509
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200510 if config.JsonModuleGraph() {
511 targets = append(targets, config.ModuleGraphFile())
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200512 }
513
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200514 if config.Bp2Build() {
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000515 targets = append(targets, config.Bp2BuildWorkspaceMarkerFile())
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200516 }
517
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200518 if config.Queryview() {
519 targets = append(targets, config.QueryviewMarkerFile())
520 }
521
Spandan Das5af0bd32022-09-28 20:43:08 +0000522 if config.ApiBp2build() {
523 targets = append(targets, config.ApiBp2buildMarkerFile())
524 }
525
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200526 if config.SoongDocs() {
527 targets = append(targets, config.SoongDocsHtml())
528 }
529
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200530 if config.SoongBuildInvocationNeeded() {
531 // 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 -0700532 targets = append(targets, config.SoongNinjaFile())
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200533 }
534
Jingwen Cheneb76c432021-01-28 08:22:12 -0500535 if shouldCollectBuildSoongMetrics(config) {
usta7f56eaa2022-10-27 23:01:02 -0400536 soongBuildMetricsFile := filepath.Join(config.LogsDir(), "soong_build_metrics.pb")
537 if err := os.Remove(soongBuildMetricsFile); err != nil && !os.IsNotExist(err) {
538 ctx.Verbosef("Failed to remove %s", soongBuildMetricsFile)
Dan Willemsende360442022-04-20 21:21:55 -0700539 }
usta7f56eaa2022-10-27 23:01:02 -0400540 defer func() {
541 soongBuildMetrics := loadSoongBuildMetrics(ctx, soongBuildMetricsFile)
542 if soongBuildMetrics != nil {
543 logSoongBuildMetrics(ctx, soongBuildMetrics)
544 if ctx.Metrics != nil {
545 ctx.Metrics.SetSoongBuildMetrics(soongBuildMetrics)
546 }
547 }
548 }()
Jingwen Cheneb76c432021-01-28 08:22:12 -0500549 }
usta7f56eaa2022-10-27 23:01:02 -0400550 ninja("bootstrap", "bootstrap.ninja", targets...)
Colin Crossb72c9092020-02-10 11:23:49 -0800551
Colin Cross8ba7d472020-06-25 11:27:52 -0700552 distGzipFile(ctx, config, config.SoongNinjaFile(), "soong")
Jihoon Kang9f4f8a32022-08-16 00:57:30 +0000553 distFile(ctx, config, config.SoongVarsFile(), "soong")
Colin Cross8ba7d472020-06-25 11:27:52 -0700554
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000555 if !config.SkipKati() {
Colin Cross8ba7d472020-06-25 11:27:52 -0700556 distGzipFile(ctx, config, config.SoongAndroidMk(), "soong")
557 distGzipFile(ctx, config, config.SoongMakeVarsMk(), "soong")
558 }
559
Rob Seymour33cd10d2022-03-02 23:10:25 +0000560 if config.JsonModuleGraph() {
561 distGzipFile(ctx, config, config.ModuleGraphFile(), "soong")
562 }
Colin Crossb72c9092020-02-10 11:23:49 -0800563}
564
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100565func runMicrofactory(ctx Context, config Config, name string, pkg string, mapping map[string]string) {
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700566 ctx.BeginTrace(metrics.RunSoong, name)
567 defer ctx.EndTrace()
568 cfg := microfactory.Config{TrimPath: absPath(ctx, ".")}
569 for pkgPrefix, pathPrefix := range mapping {
570 cfg.Map(pkgPrefix, pathPrefix)
571 }
572
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100573 exePath := filepath.Join(config.SoongOutDir(), name)
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700574 dir := filepath.Dir(exePath)
575 if err := os.MkdirAll(dir, 0777); err != nil {
576 ctx.Fatalf("cannot create %s: %s", dir, err)
577 }
578 if _, err := microfactory.Build(&cfg, exePath, pkg); err != nil {
579 ctx.Fatalf("failed to build %s: %s", name, err)
580 }
581}
582
Jingwen Cheneb76c432021-01-28 08:22:12 -0500583func shouldCollectBuildSoongMetrics(config Config) bool {
Jingwen Chendd9725c2021-06-24 08:41:16 +0000584 // Do not collect metrics protobuf if the soong_build binary ran as the
585 // bp2build converter or the JSON graph dump.
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200586 return config.SoongBuildInvocationNeeded()
Jingwen Cheneb76c432021-01-28 08:22:12 -0500587}
588
usta7f56eaa2022-10-27 23:01:02 -0400589func loadSoongBuildMetrics(ctx Context, soongBuildMetricsFile string) *soong_metrics_proto.SoongBuildMetrics {
Dan Willemsende360442022-04-20 21:21:55 -0700590 buf, err := os.ReadFile(soongBuildMetricsFile)
591 if errors.Is(err, fs.ErrNotExist) {
592 // Soong may not have run during this invocation
Usta Shresthadb46a9b2022-07-11 11:29:56 -0400593 ctx.Verbosef("Failed to read metrics file, %s: %s", soongBuildMetricsFile, err)
Dan Willemsende360442022-04-20 21:21:55 -0700594 return nil
595 } else if err != nil {
Colin Crossb72c9092020-02-10 11:23:49 -0800596 ctx.Fatalf("Failed to load %s: %s", soongBuildMetricsFile, err)
597 }
598 soongBuildMetrics := &soong_metrics_proto.SoongBuildMetrics{}
599 err = proto.Unmarshal(buf, soongBuildMetrics)
600 if err != nil {
601 ctx.Fatalf("Failed to unmarshal %s: %s", soongBuildMetricsFile, err)
602 }
603 return soongBuildMetrics
604}
605
606func logSoongBuildMetrics(ctx Context, metrics *soong_metrics_proto.SoongBuildMetrics) {
607 ctx.Verbosef("soong_build metrics:")
608 ctx.Verbosef(" modules: %v", metrics.GetModules())
609 ctx.Verbosef(" variants: %v", metrics.GetVariants())
610 ctx.Verbosef(" max heap size: %v MB", metrics.GetMaxHeapSize()/1e6)
611 ctx.Verbosef(" total allocation count: %v", metrics.GetTotalAllocCount())
612 ctx.Verbosef(" total allocation size: %v MB", metrics.GetTotalAllocSize()/1e6)
613
Dan Willemsen1e704462016-08-21 15:17:17 -0700614}