blob: 9287731f1bbec1a3c6d83a887887cd695cc46c7e [file] [log] [blame]
Dan Willemsen1e704462016-08-21 15:17:17 -07001// Copyright 2017 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package build
16
17import (
Colin Cross9191df22021-10-29 13:11:32 -070018 "fmt"
Dan Willemsen99a75cd2017-08-04 16:04:04 -070019 "os"
Dan Willemsen1e704462016-08-21 15:17:17 -070020 "path/filepath"
Dan Willemsen99a75cd2017-08-04 16:04:04 -070021 "strconv"
Usta Shrestha8dc8b0a2022-08-10 17:39:37 -040022 "strings"
Dan Willemsen99a75cd2017-08-04 16:04:04 -070023
Chris Parsons9402ca82023-02-23 17:28:06 -050024 "android/soong/bazel"
Dan Willemsen4591b642021-05-24 14:24:12 -070025 "android/soong/ui/metrics"
Dan Willemsen4591b642021-05-24 14:24:12 -070026 "android/soong/ui/status"
27
28 "android/soong/shared"
29
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010030 "github.com/google/blueprint"
31 "github.com/google/blueprint/bootstrap"
Dan Willemsen99a75cd2017-08-04 16:04:04 -070032 "github.com/google/blueprint/microfactory"
Dan Willemsen1e704462016-08-21 15:17:17 -070033)
34
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020035const (
36 availableEnvFile = "soong.environment.available"
37 usedEnvFile = "soong.environment.used"
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +020038
Lukacs T. Berkic541cd22022-10-26 07:26:50 +000039 soongBuildTag = "build"
40 bp2buildFilesTag = "bp2build_files"
41 bp2buildWorkspaceTag = "bp2build_workspace"
42 jsonModuleGraphTag = "modulegraph"
43 queryviewTag = "queryview"
44 apiBp2buildTag = "api_bp2build"
45 soongDocsTag = "soong_docs"
Colin Cross9191df22021-10-29 13:11:32 -070046
47 // bootstrapEpoch is used to determine if an incremental build is incompatible with the current
48 // version of bootstrap and needs cleaning before continuing the build. Increment this for
49 // incompatible changes, for example when moving the location of the bpglob binary that is
50 // executed during bootstrap before the primary builder has had a chance to update the path.
Lukacs T. Berki9985d9a2021-11-04 11:47:42 +010051 bootstrapEpoch = 1
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020052)
53
Sasha Smundak4cbe83a2022-11-28 17:02:40 -080054func writeEnvironmentFile(_ Context, envFile string, envDeps map[string]string) error {
Lukacs T. Berki7690c092021-02-26 14:27:36 +010055 data, err := shared.EnvFileContents(envDeps)
56 if err != nil {
57 return err
58 }
59
Sasha Smundak4cbe83a2022-11-28 17:02:40 -080060 return os.WriteFile(envFile, data, 0644)
Lukacs T. Berki7690c092021-02-26 14:27:36 +010061}
62
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000063// This uses Android.bp files and various tools to generate <builddir>/build.ninja.
64//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010065// However, the execution of <builddir>/build.ninja happens later in
66// build/soong/ui/build/build.go#Build()
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000067//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010068// We want to rely on as few prebuilts as possible, so we need to bootstrap
69// Soong. The process is as follows:
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000070//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010071// 1. We use "Microfactory", a simple tool to compile Go code, to build
72// first itself, then soong_ui from soong_ui.bash. This binary contains
73// parts of soong_build that are needed to build itself.
74// 2. This simplified version of soong_build then reads the Blueprint files
75// that describe itself and emits .bootstrap/build.ninja that describes
76// how to build its full version and use that to produce the final Ninja
77// file Soong emits.
78// 3. soong_ui executes .bootstrap/build.ninja
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000079//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010080// (After this, Kati is executed to parse the Makefiles, but that's not part of
81// bootstrapping Soong)
82
83// A tiny struct used to tell Blueprint that it's in bootstrap mode. It would
84// probably be nicer to use a flag in bootstrap.Args instead.
85type BlueprintConfig struct {
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +020086 toolDir string
87 soongOutDir string
88 outDir string
89 runGoTests bool
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +020090 debugCompilation bool
91 subninjas []string
92 primaryBuilderInvocations []bootstrap.PrimaryBuilderInvocation
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010093}
94
Lukacs T. Berkia806e412021-09-01 08:57:48 +020095func (c BlueprintConfig) HostToolDir() string {
96 return c.toolDir
97}
98
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +020099func (c BlueprintConfig) SoongOutDir() string {
100 return c.soongOutDir
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100101}
102
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200103func (c BlueprintConfig) OutDir() string {
104 return c.outDir
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100105}
106
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +0200107func (c BlueprintConfig) RunGoTests() bool {
108 return c.runGoTests
109}
110
Lukacs T. Berki5f6cb1d2021-03-17 15:03:14 +0100111func (c BlueprintConfig) DebugCompilation() bool {
112 return c.debugCompilation
113}
114
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +0200115func (c BlueprintConfig) Subninjas() []string {
116 return c.subninjas
117}
118
119func (c BlueprintConfig) PrimaryBuilderInvocations() []bootstrap.PrimaryBuilderInvocation {
120 return c.primaryBuilderInvocations
121}
122
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200123func environmentArgs(config Config, tag string) []string {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200124 return []string{
125 "--available_env", shared.JoinPath(config.SoongOutDir(), availableEnvFile),
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200126 "--used_env", config.UsedEnvFile(tag),
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200127 }
128}
Spandan Das8f99ae62021-06-11 16:48:06 +0000129
Colin Cross9191df22021-10-29 13:11:32 -0700130func writeEmptyFile(ctx Context, path string) {
Spandan Das8f99ae62021-06-11 16:48:06 +0000131 err := os.MkdirAll(filepath.Dir(path), 0777)
132 if err != nil {
Colin Cross9191df22021-10-29 13:11:32 -0700133 ctx.Fatalf("Failed to create parent directories of empty file '%s': %s", path, err)
Spandan Das8f99ae62021-06-11 16:48:06 +0000134 }
135
Colin Cross9191df22021-10-29 13:11:32 -0700136 if exists, err := fileExists(path); err != nil {
137 ctx.Fatalf("Failed to check if file '%s' exists: %s", path, err)
138 } else if !exists {
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800139 err = os.WriteFile(path, nil, 0666)
Spandan Das8f99ae62021-06-11 16:48:06 +0000140 if err != nil {
Colin Cross9191df22021-10-29 13:11:32 -0700141 ctx.Fatalf("Failed to create empty file '%s': %s", path, err)
Spandan Das8f99ae62021-06-11 16:48:06 +0000142 }
143 }
144}
145
Colin Cross9191df22021-10-29 13:11:32 -0700146func fileExists(path string) (bool, error) {
147 if _, err := os.Stat(path); os.IsNotExist(err) {
148 return false, nil
149 } else if err != nil {
150 return false, err
151 }
152 return true, nil
153}
154
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800155type PrimaryBuilderFactory struct {
156 name string
157 description string
158 config Config
159 output string
160 specificArgs []string
161 debugPort string
162}
163
164func (pb PrimaryBuilderFactory) primaryBuilderInvocation() bootstrap.PrimaryBuilderInvocation {
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200165 commonArgs := make([]string, 0, 0)
166
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800167 if !pb.config.skipSoongTests {
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200168 commonArgs = append(commonArgs, "-t")
169 }
170
LaMont Jones80f70352023-03-20 19:58:25 +0000171 if pb.config.multitreeBuild {
LaMont Jones52a72432023-03-09 18:19:35 +0000172 commonArgs = append(commonArgs, "--multitree-build")
173 }
Jihoon Kang1bff0342023-01-17 20:40:22 +0000174 if pb.config.buildFromTextStub {
175 commonArgs = append(commonArgs, "--build-from-text-stub")
176 }
LaMont Jones52a72432023-03-09 18:19:35 +0000177
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800178 commonArgs = append(commonArgs, "-l", filepath.Join(pb.config.FileListDir(), "Android.bp.list"))
Lukacs T. Berki13644272022-01-05 10:29:56 +0100179 invocationEnv := make(map[string]string)
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800180 if pb.debugPort != "" {
ustafb67fd12022-08-19 19:26:00 -0400181 //debug mode
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800182 commonArgs = append(commonArgs, "--delve_listen", pb.debugPort,
183 "--delve_path", shared.ResolveDelveBinary())
Lukacs T. Berki13644272022-01-05 10:29:56 +0100184 // GODEBUG=asyncpreemptoff=1 disables the preemption of goroutines. This
185 // is useful because the preemption happens by sending SIGURG to the OS
186 // thread hosting the goroutine in question and each signal results in
187 // work that needs to be done by Delve; it uses ptrace to debug the Go
188 // process and the tracer process must deal with every signal (it is not
189 // possible to selectively ignore SIGURG). This makes debugging slower,
190 // sometimes by an order of magnitude depending on luck.
191 // The original reason for adding async preemption to Go is here:
192 // https://github.com/golang/proposal/blob/master/design/24543-non-cooperative-preemption.md
193 invocationEnv["GODEBUG"] = "asyncpreemptoff=1"
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200194 }
195
ustafb67fd12022-08-19 19:26:00 -0400196 var allArgs []string
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800197 allArgs = append(allArgs, pb.specificArgs...)
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200198 allArgs = append(allArgs,
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800199 "--globListDir", pb.name,
200 "--globFile", pb.config.NamedGlobFile(pb.name))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200201
202 allArgs = append(allArgs, commonArgs...)
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800203 allArgs = append(allArgs, environmentArgs(pb.config, pb.name)...)
Sasha Smundakfaa97b72022-11-18 15:32:49 -0800204 if profileCpu := os.Getenv("SOONG_PROFILE_CPU"); profileCpu != "" {
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800205 allArgs = append(allArgs, "--cpuprofile", profileCpu+"."+pb.name)
Sasha Smundakfaa97b72022-11-18 15:32:49 -0800206 }
207 if profileMem := os.Getenv("SOONG_PROFILE_MEM"); profileMem != "" {
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800208 allArgs = append(allArgs, "--memprofile", profileMem+"."+pb.name)
Sasha Smundakfaa97b72022-11-18 15:32:49 -0800209 }
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200210 allArgs = append(allArgs, "Android.bp")
211
212 return bootstrap.PrimaryBuilderInvocation{
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000213 Inputs: []string{"Android.bp"},
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800214 Outputs: []string{pb.output},
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000215 Args: allArgs,
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800216 Description: pb.description,
Lukacs T. Berki2fad3412022-01-04 14:40:13 +0100217 // NB: Changing the value of this environment variable will not result in a
218 // rebuild. The bootstrap Ninja file will change, but apparently Ninja does
219 // not consider changing the pool specified in a statement a change that's
220 // worth rebuilding for.
221 Console: os.Getenv("SOONG_UNBUFFERED_OUTPUT") == "1",
Lukacs T. Berki13644272022-01-05 10:29:56 +0100222 Env: invocationEnv,
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200223 }
224}
225
Colin Cross9191df22021-10-29 13:11:32 -0700226// bootstrapEpochCleanup deletes files used by bootstrap during incremental builds across
227// incompatible changes. Incompatible changes are marked by incrementing the bootstrapEpoch
228// constant. A tree is considered out of date for the current epoch of the
229// .soong.bootstrap.epoch.<epoch> file doesn't exist.
230func bootstrapEpochCleanup(ctx Context, config Config) {
231 epochFile := fmt.Sprintf(".soong.bootstrap.epoch.%d", bootstrapEpoch)
232 epochPath := filepath.Join(config.SoongOutDir(), epochFile)
233 if exists, err := fileExists(epochPath); err != nil {
234 ctx.Fatalf("failed to check if bootstrap epoch file %q exists: %q", epochPath, err)
235 } else if !exists {
236 // The tree is out of date for the current epoch, delete files used by bootstrap
237 // and force the primary builder to rerun.
238 os.Remove(filepath.Join(config.SoongOutDir(), "build.ninja"))
239 for _, globFile := range bootstrapGlobFileList(config) {
240 os.Remove(globFile)
241 }
242
243 // Mark the tree as up to date with the current epoch by writing the epoch marker file.
244 writeEmptyFile(ctx, epochPath)
245 }
246}
247
248func bootstrapGlobFileList(config Config) []string {
249 return []string{
250 config.NamedGlobFile(soongBuildTag),
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000251 config.NamedGlobFile(bp2buildFilesTag),
Colin Cross9191df22021-10-29 13:11:32 -0700252 config.NamedGlobFile(jsonModuleGraphTag),
253 config.NamedGlobFile(queryviewTag),
Spandan Das5af0bd32022-09-28 20:43:08 +0000254 config.NamedGlobFile(apiBp2buildTag),
Colin Cross9191df22021-10-29 13:11:32 -0700255 config.NamedGlobFile(soongDocsTag),
256 }
257}
258
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200259func bootstrapBlueprint(ctx Context, config Config) {
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100260 ctx.BeginTrace(metrics.RunSoong, "blueprint bootstrap")
261 defer ctx.EndTrace()
262
Colin Cross9191df22021-10-29 13:11:32 -0700263 // Clean up some files for incremental builds across incompatible changes.
264 bootstrapEpochCleanup(ctx, config)
265
Cole Faust65f298c2021-10-28 16:05:13 -0700266 mainSoongBuildExtraArgs := []string{"-o", config.SoongNinjaFile()}
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200267 if config.EmptyNinjaFile() {
268 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--empty-ninja-file")
Lukacs T. Berki745380c2021-04-12 12:07:44 +0200269 }
Chris Parsonsef615e52022-08-18 22:04:11 -0400270 if config.bazelProdMode {
271 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--bazel-mode")
272 }
273 if config.bazelDevMode {
274 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--bazel-mode-dev")
275 }
MarkDacekb78465d2022-10-18 20:10:16 +0000276 if config.bazelStagingMode {
277 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--bazel-mode-staging")
278 }
Chris Parsons9402ca82023-02-23 17:28:06 -0500279 if config.IsPersistentBazelEnabled() {
280 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--use-bazel-proxy")
281 }
MarkDacekd06db5d2022-11-29 00:47:59 +0000282 if len(config.bazelForceEnabledModules) > 0 {
283 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--bazel-force-enabled-modules="+config.bazelForceEnabledModules)
284 }
LaMont Jones52a72432023-03-09 18:19:35 +0000285 if config.MultitreeBuild() {
286 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--multitree-build")
287 }
Jihoon Kang1bff0342023-01-17 20:40:22 +0000288 if config.buildFromTextStub {
289 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--build-from-text-stub")
290 }
MarkDacekd06db5d2022-11-29 00:47:59 +0000291
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000292 queryviewDir := filepath.Join(config.SoongOutDir(), "queryview")
Spandan Das5af0bd32022-09-28 20:43:08 +0000293 // The BUILD files will be generated in out/soong/.api_bp2build (no symlinks to src files)
294 // The final workspace will be generated in out/soong/api_bp2build
295 apiBp2buildDir := filepath.Join(config.SoongOutDir(), ".api_bp2build")
Spandan Das5af0bd32022-09-28 20:43:08 +0000296
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800297 pbfs := []PrimaryBuilderFactory{
298 {
299 name: soongBuildTag,
300 description: fmt.Sprintf("analyzing Android.bp files and generating ninja file at %s", config.SoongNinjaFile()),
301 config: config,
302 output: config.SoongNinjaFile(),
303 specificArgs: mainSoongBuildExtraArgs,
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000304 },
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800305 {
306 name: bp2buildFilesTag,
307 description: fmt.Sprintf("converting Android.bp files to BUILD files at %s/bp2build", config.SoongOutDir()),
308 config: config,
309 output: config.Bp2BuildFilesMarkerFile(),
310 specificArgs: []string{"--bp2build_marker", config.Bp2BuildFilesMarkerFile()},
311 },
312 {
313 name: bp2buildWorkspaceTag,
314 description: "Creating Bazel symlink forest",
315 config: config,
316 output: config.Bp2BuildWorkspaceMarkerFile(),
317 specificArgs: []string{"--symlink_forest_marker", config.Bp2BuildWorkspaceMarkerFile()},
318 },
319 {
320 name: jsonModuleGraphTag,
321 description: fmt.Sprintf("generating the Soong module graph at %s", config.ModuleGraphFile()),
322 config: config,
323 output: config.ModuleGraphFile(),
324 specificArgs: []string{
325 "--module_graph_file", config.ModuleGraphFile(),
326 "--module_actions_file", config.ModuleActionsFile(),
327 },
328 },
329 {
330 name: queryviewTag,
331 description: fmt.Sprintf("generating the Soong module graph as a Bazel workspace at %s", queryviewDir),
332 config: config,
333 output: config.QueryviewMarkerFile(),
334 specificArgs: []string{"--bazel_queryview_dir", queryviewDir},
335 },
336 {
337 name: apiBp2buildTag,
338 description: fmt.Sprintf("generating BUILD files for API contributions at %s", apiBp2buildDir),
339 config: config,
340 output: config.ApiBp2buildMarkerFile(),
341 specificArgs: []string{"--bazel_api_bp2build_dir", apiBp2buildDir},
342 },
343 {
344 name: soongDocsTag,
345 description: fmt.Sprintf("generating Soong docs at %s", config.SoongDocsHtml()),
346 config: config,
347 output: config.SoongDocsHtml(),
348 specificArgs: []string{"--soong_docs", config.SoongDocsHtml()},
349 },
350 }
351
352 // Figure out which invocations will be run under the debugger:
353 // * SOONG_DELVE if set specifies listening port
354 // * SOONG_DELVE_STEPS if set specifies specific invocations to be debugged, otherwise all are
355 debuggedInvocations := make(map[string]bool)
356 delvePort := os.Getenv("SOONG_DELVE")
357 if delvePort != "" {
358 if steps := os.Getenv("SOONG_DELVE_STEPS"); steps != "" {
359 var validSteps []string
360 for _, pbf := range pbfs {
361 debuggedInvocations[pbf.name] = false
362 validSteps = append(validSteps, pbf.name)
363
364 }
365 for _, step := range strings.Split(steps, ",") {
366 if _, ok := debuggedInvocations[step]; ok {
367 debuggedInvocations[step] = true
368 } else {
369 ctx.Fatalf("SOONG_DELVE_STEPS contains unknown soong_build step %s\n"+
370 "Valid steps are %v", step, validSteps)
371 }
372 }
373 } else {
374 // SOONG_DELVE_STEPS is not set, run all steps in the debugger
375 for _, pbf := range pbfs {
376 debuggedInvocations[pbf.name] = true
377 }
378 }
379 }
380
381 var invocations []bootstrap.PrimaryBuilderInvocation
382 for _, pbf := range pbfs {
383 if debuggedInvocations[pbf.name] {
384 pbf.debugPort = delvePort
385 }
386 pbi := pbf.primaryBuilderInvocation()
387 // Some invocations require adjustment:
388 switch pbf.name {
389 case soongBuildTag:
390 if config.BazelBuildEnabled() {
391 // Mixed builds call Bazel from soong_build and they therefore need the
392 // Bazel workspace to be available. Make that so by adding a dependency on
393 // the bp2build marker file to the action that invokes soong_build .
394 pbi.OrderOnlyInputs = append(pbi.OrderOnlyInputs, config.Bp2BuildWorkspaceMarkerFile())
395 }
396 case bp2buildWorkspaceTag:
397 pbi.Inputs = append(pbi.Inputs,
398 config.Bp2BuildFilesMarkerFile(),
399 filepath.Join(config.FileListDir(), "bazel.list"))
400 }
401 invocations = append(invocations, pbi)
402 }
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200403
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200404 // The glob .ninja files are subninja'd. However, they are generated during
405 // the build itself so we write an empty file if the file does not exist yet
406 // so that the subninja doesn't fail on clean builds
Colin Cross9191df22021-10-29 13:11:32 -0700407 for _, globFile := range bootstrapGlobFileList(config) {
408 writeEmptyFile(ctx, globFile)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200409 }
410
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800411 blueprintArgs := bootstrap.Args{
412 ModuleListFile: filepath.Join(config.FileListDir(), "Android.bp.list"),
413 OutFile: shared.JoinPath(config.SoongOutDir(), "bootstrap.ninja"),
414 EmptyNinjaFile: false,
415 }
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200416
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100417 blueprintCtx := blueprint.NewContext()
Spandan Dasc5763832022-11-08 18:42:16 +0000418 blueprintCtx.AddIncludeTags(config.GetIncludeTags()...)
Sam Delmerico98a73292023-02-21 11:50:29 -0500419 blueprintCtx.AddSourceRootDirs(config.GetSourceRootDirs()...)
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100420 blueprintCtx.SetIgnoreUnknownModuleTypes(true)
421 blueprintConfig := BlueprintConfig{
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200422 soongOutDir: config.SoongOutDir(),
423 toolDir: config.HostToolDir(),
424 outDir: config.OutDir(),
425 runGoTests: !config.skipSoongTests,
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200426 // If we want to debug soong_build, we need to compile it for debugging
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800427 debugCompilation: delvePort != "",
428 subninjas: bootstrapGlobFileList(config),
429 primaryBuilderInvocations: invocations,
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100430 }
431
usta5bb4a5d2022-08-24 12:53:46 -0400432 // since `bootstrap.ninja` is regenerated unconditionally, we ignore the deps, i.e. little
433 // reason to write a `bootstrap.ninja.d` file
434 _ = bootstrap.RunBlueprint(blueprintArgs, bootstrap.DoEverything, blueprintCtx, blueprintConfig)
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100435}
436
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200437func checkEnvironmentFile(currentEnv *Environment, envFile string) {
438 getenv := func(k string) string {
439 v, _ := currentEnv.Get(k)
440 return v
441 }
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200442
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200443 if stale, _ := shared.StaleEnvFile(envFile, getenv); stale {
444 os.Remove(envFile)
445 }
446}
447
Dan Willemsen1e704462016-08-21 15:17:17 -0700448func runSoong(ctx Context, config Config) {
Nan Zhang17f27672018-12-12 16:01:49 -0800449 ctx.BeginTrace(metrics.RunSoong, "soong")
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700450 defer ctx.EndTrace()
451
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100452 // We have two environment files: .available is the one with every variable,
453 // .used with the ones that were actually used. The latter is used to
454 // determine whether Soong needs to be re-run since why re-run it if only
455 // unused variables were changed?
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200456 envFile := filepath.Join(config.SoongOutDir(), availableEnvFile)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100457
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100458 // This is done unconditionally, but does not take a measurable amount of time
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200459 bootstrapBlueprint(ctx, config)
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700460
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100461 soongBuildEnv := config.Environment().Copy()
462 soongBuildEnv.Set("TOP", os.Getenv("TOP"))
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100463 // For Bazel mixed builds.
Joe Onoratoba29f382022-10-24 06:38:11 -0700464 soongBuildEnv.Set("BAZEL_PATH", "./build/bazel/bin/bazel")
Chris Parsonsa9bef142022-09-28 15:07:46 -0400465 // Bazel's HOME var is set to an output subdirectory which doesn't exist. This
466 // prevents Bazel from file I/O in the actual user HOME directory.
467 soongBuildEnv.Set("BAZEL_HOME", absPath(ctx, filepath.Join(config.BazelOutDir(), "bazelhome")))
Liz Kammer2af5ea82022-11-11 14:21:03 -0500468 soongBuildEnv.Set("BAZEL_OUTPUT_BASE", config.bazelOutputBase())
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100469 soongBuildEnv.Set("BAZEL_WORKSPACE", absPath(ctx, "."))
470 soongBuildEnv.Set("BAZEL_METRICS_DIR", config.BazelMetricsDir())
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500471 soongBuildEnv.Set("LOG_DIR", config.LogsDir())
Jingwen Chen3b13b612022-10-17 12:14:26 +0000472 soongBuildEnv.Set("BAZEL_DEPS_FILE", absPath(ctx, filepath.Join(config.BazelOutDir(), "bazel.list")))
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100473
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100474 // For Soong bootstrapping tests
475 if os.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
476 soongBuildEnv.Set("ALLOW_MISSING_DEPENDENCIES", "true")
477 }
478
Paul Duffin5e85c662021-03-05 12:26:14 +0000479 err := writeEnvironmentFile(ctx, envFile, soongBuildEnv.AsMap())
480 if err != nil {
481 ctx.Fatalf("failed to write environment file %s: %s", envFile, err)
482 }
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100483
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700484 func() {
Nan Zhang17f27672018-12-12 16:01:49 -0800485 ctx.BeginTrace(metrics.RunSoong, "environment check")
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700486 defer ctx.EndTrace()
487
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200488 checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(soongBuildTag))
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200489
Chris Parsonsef615e52022-08-18 22:04:11 -0400490 if config.BazelBuildEnabled() || config.Bp2Build() {
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000491 checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(bp2buildFilesTag))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200492 }
493
494 if config.JsonModuleGraph() {
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200495 checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(jsonModuleGraphTag))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200496 }
497
498 if config.Queryview() {
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200499 checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(queryviewTag))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200500 }
501
Spandan Das5af0bd32022-09-28 20:43:08 +0000502 if config.ApiBp2build() {
503 checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(apiBp2buildTag))
504 }
505
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200506 if config.SoongDocs() {
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200507 checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(soongDocsTag))
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700508 }
509 }()
510
Colin Cross9191df22021-10-29 13:11:32 -0700511 runMicrofactory(ctx, config, "bpglob", "github.com/google/blueprint/bootstrap/bpglob",
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700512 map[string]string{"github.com/google/blueprint": "build/blueprint"})
Dan Willemsen5af1cbe2018-07-05 21:46:51 -0700513
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200514 ninja := func(name, ninjaFile string, targets ...string) {
Nan Zhang17f27672018-12-12 16:01:49 -0800515 ctx.BeginTrace(metrics.RunSoong, name)
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700516 defer ctx.EndTrace()
517
Chris Parsons9402ca82023-02-23 17:28:06 -0500518 if config.IsPersistentBazelEnabled() {
519 bazelProxy := bazel.NewProxyServer(ctx.Logger, config.OutDir(), filepath.Join(config.SoongOutDir(), "workspace"))
520 bazelProxy.Start()
521 defer bazelProxy.Close()
522 }
523
Dan Willemsenb82471a2018-05-17 16:37:09 -0700524 fifo := filepath.Join(config.OutDir(), ".ninja_fifo")
Colin Crossb98d3bc2019-03-21 16:02:58 -0700525 nr := status.NewNinjaReader(ctx, ctx.Status.StartTool(), fifo)
526 defer nr.Close()
Dan Willemsenb82471a2018-05-17 16:37:09 -0700527
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200528 ninjaArgs := []string{
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700529 "-d", "keepdepfile",
Dan Willemsen08218222020-05-18 14:02:02 -0700530 "-d", "stats",
Dan Willemsen6587bed2020-04-18 20:25:59 -0700531 "-o", "usesphonyoutputs=yes",
532 "-o", "preremoveoutputs=yes",
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700533 "-w", "dupbuild=err",
Dan Willemsen6587bed2020-04-18 20:25:59 -0700534 "-w", "outputdir=err",
535 "-w", "missingoutfile=err",
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700536 "-j", strconv.Itoa(config.Parallel()),
Dan Willemsen02736672018-07-17 17:54:31 -0700537 "--frontend_file", fifo,
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200538 "-f", filepath.Join(config.SoongOutDir(), ninjaFile),
539 }
540
Usta Shrestha8dc8b0a2022-08-10 17:39:37 -0400541 if extra, ok := config.Environment().Get("SOONG_UI_NINJA_ARGS"); ok {
542 ctx.Printf(`CAUTION: arguments in $SOONG_UI_NINJA_ARGS=%q, e.g. "-n", can make soong_build FAIL or INCORRECT`, extra)
543 ninjaArgs = append(ninjaArgs, strings.Fields(extra)...)
544 }
545
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200546 ninjaArgs = append(ninjaArgs, targets...)
547 cmd := Command(ctx, config, "soong "+name,
548 config.PrebuiltBuildTool("ninja"), ninjaArgs...)
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500549
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100550 var ninjaEnv Environment
Lukacs T. Berki73ab9282021-03-10 10:48:39 +0100551
552 // This is currently how the command line to invoke soong_build finds the
553 // root of the source tree and the output root
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100554 ninjaEnv.Set("TOP", os.Getenv("TOP"))
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100555
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100556 cmd.Environment = &ninjaEnv
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700557 cmd.Sandbox = soongSandbox
Colin Cross7b97ecd2019-06-19 13:17:59 -0700558 cmd.RunAndStreamOrFatal()
Dan Willemsen1e704462016-08-21 15:17:17 -0700559 }
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200560
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200561 targets := make([]string, 0, 0)
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200562
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200563 if config.JsonModuleGraph() {
564 targets = append(targets, config.ModuleGraphFile())
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200565 }
566
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200567 if config.Bp2Build() {
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000568 targets = append(targets, config.Bp2BuildWorkspaceMarkerFile())
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200569 }
570
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200571 if config.Queryview() {
572 targets = append(targets, config.QueryviewMarkerFile())
573 }
574
Spandan Das5af0bd32022-09-28 20:43:08 +0000575 if config.ApiBp2build() {
576 targets = append(targets, config.ApiBp2buildMarkerFile())
577 }
578
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200579 if config.SoongDocs() {
580 targets = append(targets, config.SoongDocsHtml())
581 }
582
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200583 if config.SoongBuildInvocationNeeded() {
584 // 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 -0700585 targets = append(targets, config.SoongNinjaFile())
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200586 }
587
usta7f56eaa2022-10-27 23:01:02 -0400588 ninja("bootstrap", "bootstrap.ninja", targets...)
Colin Crossb72c9092020-02-10 11:23:49 -0800589
Colin Cross8ba7d472020-06-25 11:27:52 -0700590 distGzipFile(ctx, config, config.SoongNinjaFile(), "soong")
Jihoon Kang9f4f8a32022-08-16 00:57:30 +0000591 distFile(ctx, config, config.SoongVarsFile(), "soong")
Colin Cross8ba7d472020-06-25 11:27:52 -0700592
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000593 if !config.SkipKati() {
Colin Cross8ba7d472020-06-25 11:27:52 -0700594 distGzipFile(ctx, config, config.SoongAndroidMk(), "soong")
595 distGzipFile(ctx, config, config.SoongMakeVarsMk(), "soong")
596 }
597
Rob Seymour33cd10d2022-03-02 23:10:25 +0000598 if config.JsonModuleGraph() {
599 distGzipFile(ctx, config, config.ModuleGraphFile(), "soong")
600 }
Colin Crossb72c9092020-02-10 11:23:49 -0800601}
602
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100603func runMicrofactory(ctx Context, config Config, name string, pkg string, mapping map[string]string) {
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700604 ctx.BeginTrace(metrics.RunSoong, name)
605 defer ctx.EndTrace()
606 cfg := microfactory.Config{TrimPath: absPath(ctx, ".")}
607 for pkgPrefix, pathPrefix := range mapping {
608 cfg.Map(pkgPrefix, pathPrefix)
609 }
610
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100611 exePath := filepath.Join(config.SoongOutDir(), name)
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700612 dir := filepath.Dir(exePath)
613 if err := os.MkdirAll(dir, 0777); err != nil {
614 ctx.Fatalf("cannot create %s: %s", dir, err)
615 }
616 if _, err := microfactory.Build(&cfg, exePath, pkg); err != nil {
617 ctx.Fatalf("failed to build %s: %s", name, err)
618 }
619}