blob: 44c20a01342a5aa6ffd9a04518628b359412152e [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"
Lukacs T. Berkic541cd22022-10-26 07:26:50 +000044 soongDocsTag = "soong_docs"
Colin Cross9191df22021-10-29 13:11:32 -070045
46 // bootstrapEpoch is used to determine if an incremental build is incompatible with the current
47 // version of bootstrap and needs cleaning before continuing the build. Increment this for
48 // incompatible changes, for example when moving the location of the bpglob binary that is
49 // executed during bootstrap before the primary builder has had a chance to update the path.
Lukacs T. Berki9985d9a2021-11-04 11:47:42 +010050 bootstrapEpoch = 1
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020051)
52
Sasha Smundak4cbe83a2022-11-28 17:02:40 -080053func writeEnvironmentFile(_ Context, envFile string, envDeps map[string]string) error {
Lukacs T. Berki7690c092021-02-26 14:27:36 +010054 data, err := shared.EnvFileContents(envDeps)
55 if err != nil {
56 return err
57 }
58
Sasha Smundak4cbe83a2022-11-28 17:02:40 -080059 return os.WriteFile(envFile, data, 0644)
Lukacs T. Berki7690c092021-02-26 14:27:36 +010060}
61
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000062// This uses Android.bp files and various tools to generate <builddir>/build.ninja.
63//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010064// However, the execution of <builddir>/build.ninja happens later in
65// build/soong/ui/build/build.go#Build()
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000066//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010067// We want to rely on as few prebuilts as possible, so we need to bootstrap
68// Soong. The process is as follows:
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000069//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010070// 1. We use "Microfactory", a simple tool to compile Go code, to build
71// first itself, then soong_ui from soong_ui.bash. This binary contains
72// parts of soong_build that are needed to build itself.
73// 2. This simplified version of soong_build then reads the Blueprint files
74// that describe itself and emits .bootstrap/build.ninja that describes
75// how to build its full version and use that to produce the final Ninja
76// file Soong emits.
77// 3. soong_ui executes .bootstrap/build.ninja
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000078//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010079// (After this, Kati is executed to parse the Makefiles, but that's not part of
80// bootstrapping Soong)
81
82// A tiny struct used to tell Blueprint that it's in bootstrap mode. It would
83// probably be nicer to use a flag in bootstrap.Args instead.
84type BlueprintConfig struct {
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +020085 toolDir string
86 soongOutDir string
87 outDir string
88 runGoTests bool
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +020089 debugCompilation bool
90 subninjas []string
91 primaryBuilderInvocations []bootstrap.PrimaryBuilderInvocation
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010092}
93
Lukacs T. Berkia806e412021-09-01 08:57:48 +020094func (c BlueprintConfig) HostToolDir() string {
95 return c.toolDir
96}
97
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +020098func (c BlueprintConfig) SoongOutDir() string {
99 return c.soongOutDir
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100100}
101
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200102func (c BlueprintConfig) OutDir() string {
103 return c.outDir
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100104}
105
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +0200106func (c BlueprintConfig) RunGoTests() bool {
107 return c.runGoTests
108}
109
Lukacs T. Berki5f6cb1d2021-03-17 15:03:14 +0100110func (c BlueprintConfig) DebugCompilation() bool {
111 return c.debugCompilation
112}
113
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +0200114func (c BlueprintConfig) Subninjas() []string {
115 return c.subninjas
116}
117
118func (c BlueprintConfig) PrimaryBuilderInvocations() []bootstrap.PrimaryBuilderInvocation {
119 return c.primaryBuilderInvocations
120}
121
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200122func environmentArgs(config Config, tag string) []string {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200123 return []string{
124 "--available_env", shared.JoinPath(config.SoongOutDir(), availableEnvFile),
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200125 "--used_env", config.UsedEnvFile(tag),
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200126 }
127}
Spandan Das8f99ae62021-06-11 16:48:06 +0000128
Colin Cross9191df22021-10-29 13:11:32 -0700129func writeEmptyFile(ctx Context, path string) {
Spandan Das8f99ae62021-06-11 16:48:06 +0000130 err := os.MkdirAll(filepath.Dir(path), 0777)
131 if err != nil {
Colin Cross9191df22021-10-29 13:11:32 -0700132 ctx.Fatalf("Failed to create parent directories of empty file '%s': %s", path, err)
Spandan Das8f99ae62021-06-11 16:48:06 +0000133 }
134
Colin Cross9191df22021-10-29 13:11:32 -0700135 if exists, err := fileExists(path); err != nil {
136 ctx.Fatalf("Failed to check if file '%s' exists: %s", path, err)
137 } else if !exists {
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800138 err = os.WriteFile(path, nil, 0666)
Spandan Das8f99ae62021-06-11 16:48:06 +0000139 if err != nil {
Colin Cross9191df22021-10-29 13:11:32 -0700140 ctx.Fatalf("Failed to create empty file '%s': %s", path, err)
Spandan Das8f99ae62021-06-11 16:48:06 +0000141 }
142 }
143}
144
Colin Cross9191df22021-10-29 13:11:32 -0700145func fileExists(path string) (bool, error) {
146 if _, err := os.Stat(path); os.IsNotExist(err) {
147 return false, nil
148 } else if err != nil {
149 return false, err
150 }
151 return true, nil
152}
153
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800154type PrimaryBuilderFactory struct {
155 name string
156 description string
157 config Config
158 output string
159 specificArgs []string
160 debugPort string
161}
162
Jeongik Chaccf37002023-08-04 01:46:32 +0900163func getGlobPathName(config Config) string {
164 globPathName, ok := config.TargetProductOrErr()
165 if ok != nil {
166 globPathName = soongBuildTag
167 }
168 return globPathName
169}
170
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800171func (pb PrimaryBuilderFactory) primaryBuilderInvocation() bootstrap.PrimaryBuilderInvocation {
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200172 commonArgs := make([]string, 0, 0)
173
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800174 if !pb.config.skipSoongTests {
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200175 commonArgs = append(commonArgs, "-t")
176 }
177
LaMont Jones80f70352023-03-20 19:58:25 +0000178 if pb.config.multitreeBuild {
LaMont Jones52a72432023-03-09 18:19:35 +0000179 commonArgs = append(commonArgs, "--multitree-build")
180 }
Jihoon Kang1bff0342023-01-17 20:40:22 +0000181 if pb.config.buildFromTextStub {
182 commonArgs = append(commonArgs, "--build-from-text-stub")
183 }
LaMont Jones52a72432023-03-09 18:19:35 +0000184
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800185 commonArgs = append(commonArgs, "-l", filepath.Join(pb.config.FileListDir(), "Android.bp.list"))
Lukacs T. Berki13644272022-01-05 10:29:56 +0100186 invocationEnv := make(map[string]string)
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800187 if pb.debugPort != "" {
ustafb67fd12022-08-19 19:26:00 -0400188 //debug mode
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800189 commonArgs = append(commonArgs, "--delve_listen", pb.debugPort,
190 "--delve_path", shared.ResolveDelveBinary())
Lukacs T. Berki13644272022-01-05 10:29:56 +0100191 // GODEBUG=asyncpreemptoff=1 disables the preemption of goroutines. This
192 // is useful because the preemption happens by sending SIGURG to the OS
193 // thread hosting the goroutine in question and each signal results in
194 // work that needs to be done by Delve; it uses ptrace to debug the Go
195 // process and the tracer process must deal with every signal (it is not
196 // possible to selectively ignore SIGURG). This makes debugging slower,
197 // sometimes by an order of magnitude depending on luck.
198 // The original reason for adding async preemption to Go is here:
199 // https://github.com/golang/proposal/blob/master/design/24543-non-cooperative-preemption.md
200 invocationEnv["GODEBUG"] = "asyncpreemptoff=1"
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200201 }
202
ustafb67fd12022-08-19 19:26:00 -0400203 var allArgs []string
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800204 allArgs = append(allArgs, pb.specificArgs...)
Jeongik Chaccf37002023-08-04 01:46:32 +0900205 globPathName := pb.name
206 // Glob path for soong build would be separated per product target
207 if pb.name == soongBuildTag {
208 globPathName = getGlobPathName(pb.config)
209 }
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200210 allArgs = append(allArgs,
Jeongik Chaccf37002023-08-04 01:46:32 +0900211 "--globListDir", globPathName,
212 "--globFile", pb.config.NamedGlobFile(globPathName))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200213
214 allArgs = append(allArgs, commonArgs...)
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800215 allArgs = append(allArgs, environmentArgs(pb.config, pb.name)...)
Sasha Smundakfaa97b72022-11-18 15:32:49 -0800216 if profileCpu := os.Getenv("SOONG_PROFILE_CPU"); profileCpu != "" {
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800217 allArgs = append(allArgs, "--cpuprofile", profileCpu+"."+pb.name)
Sasha Smundakfaa97b72022-11-18 15:32:49 -0800218 }
219 if profileMem := os.Getenv("SOONG_PROFILE_MEM"); profileMem != "" {
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800220 allArgs = append(allArgs, "--memprofile", profileMem+"."+pb.name)
Sasha Smundakfaa97b72022-11-18 15:32:49 -0800221 }
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200222 allArgs = append(allArgs, "Android.bp")
223
224 return bootstrap.PrimaryBuilderInvocation{
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000225 Inputs: []string{"Android.bp"},
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800226 Outputs: []string{pb.output},
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000227 Args: allArgs,
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800228 Description: pb.description,
Lukacs T. Berki2fad3412022-01-04 14:40:13 +0100229 // NB: Changing the value of this environment variable will not result in a
230 // rebuild. The bootstrap Ninja file will change, but apparently Ninja does
231 // not consider changing the pool specified in a statement a change that's
232 // worth rebuilding for.
233 Console: os.Getenv("SOONG_UNBUFFERED_OUTPUT") == "1",
Lukacs T. Berki13644272022-01-05 10:29:56 +0100234 Env: invocationEnv,
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200235 }
236}
237
Colin Cross9191df22021-10-29 13:11:32 -0700238// bootstrapEpochCleanup deletes files used by bootstrap during incremental builds across
239// incompatible changes. Incompatible changes are marked by incrementing the bootstrapEpoch
240// constant. A tree is considered out of date for the current epoch of the
241// .soong.bootstrap.epoch.<epoch> file doesn't exist.
242func bootstrapEpochCleanup(ctx Context, config Config) {
243 epochFile := fmt.Sprintf(".soong.bootstrap.epoch.%d", bootstrapEpoch)
244 epochPath := filepath.Join(config.SoongOutDir(), epochFile)
245 if exists, err := fileExists(epochPath); err != nil {
246 ctx.Fatalf("failed to check if bootstrap epoch file %q exists: %q", epochPath, err)
247 } else if !exists {
248 // The tree is out of date for the current epoch, delete files used by bootstrap
249 // and force the primary builder to rerun.
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900250 os.Remove(config.SoongNinjaFile())
Colin Cross9191df22021-10-29 13:11:32 -0700251 for _, globFile := range bootstrapGlobFileList(config) {
252 os.Remove(globFile)
253 }
254
255 // Mark the tree as up to date with the current epoch by writing the epoch marker file.
256 writeEmptyFile(ctx, epochPath)
257 }
258}
259
260func bootstrapGlobFileList(config Config) []string {
261 return []string{
Jeongik Chaccf37002023-08-04 01:46:32 +0900262 config.NamedGlobFile(getGlobPathName(config)),
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000263 config.NamedGlobFile(bp2buildFilesTag),
Colin Cross9191df22021-10-29 13:11:32 -0700264 config.NamedGlobFile(jsonModuleGraphTag),
265 config.NamedGlobFile(queryviewTag),
266 config.NamedGlobFile(soongDocsTag),
267 }
268}
269
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200270func bootstrapBlueprint(ctx Context, config Config) {
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100271 ctx.BeginTrace(metrics.RunSoong, "blueprint bootstrap")
272 defer ctx.EndTrace()
273
Colin Cross9191df22021-10-29 13:11:32 -0700274 // Clean up some files for incremental builds across incompatible changes.
275 bootstrapEpochCleanup(ctx, config)
276
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900277 baseArgs := []string{"--soong_variables", config.SoongVarsFile()}
278
279 mainSoongBuildExtraArgs := append(baseArgs, "-o", config.SoongNinjaFile())
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200280 if config.EmptyNinjaFile() {
281 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--empty-ninja-file")
Lukacs T. Berki745380c2021-04-12 12:07:44 +0200282 }
Chris Parsonsef615e52022-08-18 22:04:11 -0400283 if config.bazelProdMode {
284 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--bazel-mode")
285 }
MarkDacekb78465d2022-10-18 20:10:16 +0000286 if config.bazelStagingMode {
287 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--bazel-mode-staging")
288 }
Chris Parsons9402ca82023-02-23 17:28:06 -0500289 if config.IsPersistentBazelEnabled() {
290 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--use-bazel-proxy")
291 }
MarkDacekd06db5d2022-11-29 00:47:59 +0000292 if len(config.bazelForceEnabledModules) > 0 {
293 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--bazel-force-enabled-modules="+config.bazelForceEnabledModules)
294 }
LaMont Jones52a72432023-03-09 18:19:35 +0000295 if config.MultitreeBuild() {
296 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--multitree-build")
297 }
Jihoon Kang1bff0342023-01-17 20:40:22 +0000298 if config.buildFromTextStub {
299 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--build-from-text-stub")
300 }
MarkDacekf47e1422023-04-19 16:47:36 +0000301 if config.ensureAllowlistIntegrity {
302 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--ensure-allowlist-integrity")
303 }
MarkDacekd06db5d2022-11-29 00:47:59 +0000304
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000305 queryviewDir := filepath.Join(config.SoongOutDir(), "queryview")
Spandan Das5af0bd32022-09-28 20:43:08 +0000306
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800307 pbfs := []PrimaryBuilderFactory{
308 {
309 name: soongBuildTag,
310 description: fmt.Sprintf("analyzing Android.bp files and generating ninja file at %s", config.SoongNinjaFile()),
311 config: config,
312 output: config.SoongNinjaFile(),
313 specificArgs: mainSoongBuildExtraArgs,
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000314 },
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800315 {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900316 name: bp2buildFilesTag,
317 description: fmt.Sprintf("converting Android.bp files to BUILD files at %s/bp2build", config.SoongOutDir()),
318 config: config,
319 output: config.Bp2BuildFilesMarkerFile(),
320 specificArgs: append(baseArgs,
321 "--bp2build_marker", config.Bp2BuildFilesMarkerFile(),
322 ),
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800323 },
324 {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900325 name: bp2buildWorkspaceTag,
326 description: "Creating Bazel symlink forest",
327 config: config,
328 output: config.Bp2BuildWorkspaceMarkerFile(),
329 specificArgs: append(baseArgs,
330 "--symlink_forest_marker", config.Bp2BuildWorkspaceMarkerFile(),
331 ),
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800332 },
333 {
334 name: jsonModuleGraphTag,
335 description: fmt.Sprintf("generating the Soong module graph at %s", config.ModuleGraphFile()),
336 config: config,
337 output: config.ModuleGraphFile(),
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900338 specificArgs: append(baseArgs,
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800339 "--module_graph_file", config.ModuleGraphFile(),
340 "--module_actions_file", config.ModuleActionsFile(),
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900341 ),
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800342 },
343 {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900344 name: queryviewTag,
345 description: fmt.Sprintf("generating the Soong module graph as a Bazel workspace at %s", queryviewDir),
346 config: config,
347 output: config.QueryviewMarkerFile(),
348 specificArgs: append(baseArgs,
349 "--bazel_queryview_dir", queryviewDir,
350 ),
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800351 },
352 {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900353 name: soongDocsTag,
354 description: fmt.Sprintf("generating Soong docs at %s", config.SoongDocsHtml()),
355 config: config,
356 output: config.SoongDocsHtml(),
357 specificArgs: append(baseArgs,
358 "--soong_docs", config.SoongDocsHtml(),
359 ),
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800360 },
361 }
362
363 // Figure out which invocations will be run under the debugger:
364 // * SOONG_DELVE if set specifies listening port
365 // * SOONG_DELVE_STEPS if set specifies specific invocations to be debugged, otherwise all are
366 debuggedInvocations := make(map[string]bool)
367 delvePort := os.Getenv("SOONG_DELVE")
368 if delvePort != "" {
369 if steps := os.Getenv("SOONG_DELVE_STEPS"); steps != "" {
370 var validSteps []string
371 for _, pbf := range pbfs {
372 debuggedInvocations[pbf.name] = false
373 validSteps = append(validSteps, pbf.name)
374
375 }
376 for _, step := range strings.Split(steps, ",") {
377 if _, ok := debuggedInvocations[step]; ok {
378 debuggedInvocations[step] = true
379 } else {
380 ctx.Fatalf("SOONG_DELVE_STEPS contains unknown soong_build step %s\n"+
381 "Valid steps are %v", step, validSteps)
382 }
383 }
384 } else {
385 // SOONG_DELVE_STEPS is not set, run all steps in the debugger
386 for _, pbf := range pbfs {
387 debuggedInvocations[pbf.name] = true
388 }
389 }
390 }
391
392 var invocations []bootstrap.PrimaryBuilderInvocation
393 for _, pbf := range pbfs {
394 if debuggedInvocations[pbf.name] {
395 pbf.debugPort = delvePort
396 }
397 pbi := pbf.primaryBuilderInvocation()
398 // Some invocations require adjustment:
399 switch pbf.name {
400 case soongBuildTag:
401 if config.BazelBuildEnabled() {
402 // Mixed builds call Bazel from soong_build and they therefore need the
403 // Bazel workspace to be available. Make that so by adding a dependency on
404 // the bp2build marker file to the action that invokes soong_build .
405 pbi.OrderOnlyInputs = append(pbi.OrderOnlyInputs, config.Bp2BuildWorkspaceMarkerFile())
406 }
407 case bp2buildWorkspaceTag:
408 pbi.Inputs = append(pbi.Inputs,
409 config.Bp2BuildFilesMarkerFile(),
410 filepath.Join(config.FileListDir(), "bazel.list"))
Wei Li2c9e8d62023-05-05 01:07:15 -0700411 case bp2buildFilesTag:
412 pbi.Inputs = append(pbi.Inputs, filepath.Join(config.FileListDir(), "METADATA.list"))
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800413 }
414 invocations = append(invocations, pbi)
415 }
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200416
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200417 // The glob .ninja files are subninja'd. However, they are generated during
418 // the build itself so we write an empty file if the file does not exist yet
419 // so that the subninja doesn't fail on clean builds
Colin Cross9191df22021-10-29 13:11:32 -0700420 for _, globFile := range bootstrapGlobFileList(config) {
421 writeEmptyFile(ctx, globFile)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200422 }
423
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800424 blueprintArgs := bootstrap.Args{
425 ModuleListFile: filepath.Join(config.FileListDir(), "Android.bp.list"),
426 OutFile: shared.JoinPath(config.SoongOutDir(), "bootstrap.ninja"),
427 EmptyNinjaFile: false,
428 }
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200429
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100430 blueprintCtx := blueprint.NewContext()
Spandan Dasc5763832022-11-08 18:42:16 +0000431 blueprintCtx.AddIncludeTags(config.GetIncludeTags()...)
Sam Delmerico98a73292023-02-21 11:50:29 -0500432 blueprintCtx.AddSourceRootDirs(config.GetSourceRootDirs()...)
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100433 blueprintCtx.SetIgnoreUnknownModuleTypes(true)
434 blueprintConfig := BlueprintConfig{
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200435 soongOutDir: config.SoongOutDir(),
436 toolDir: config.HostToolDir(),
437 outDir: config.OutDir(),
438 runGoTests: !config.skipSoongTests,
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200439 // If we want to debug soong_build, we need to compile it for debugging
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800440 debugCompilation: delvePort != "",
441 subninjas: bootstrapGlobFileList(config),
442 primaryBuilderInvocations: invocations,
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100443 }
444
usta5bb4a5d2022-08-24 12:53:46 -0400445 // since `bootstrap.ninja` is regenerated unconditionally, we ignore the deps, i.e. little
446 // reason to write a `bootstrap.ninja.d` file
Lukacs T. Berkic357c812023-06-20 09:30:06 +0000447 _, err := bootstrap.RunBlueprint(blueprintArgs, bootstrap.DoEverything, blueprintCtx, blueprintConfig)
448 if err != nil {
449 ctx.Fatal(err)
450 }
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100451}
452
Jason Wu2520f5e2023-05-30 19:45:36 -0400453func checkEnvironmentFile(ctx Context, currentEnv *Environment, envFile string) {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200454 getenv := func(k string) string {
455 v, _ := currentEnv.Get(k)
456 return v
457 }
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200458
Jason Wu2520f5e2023-05-30 19:45:36 -0400459 // Log the changed environment variables to ChangedEnvironmentVariable field
460 if stale, changedEnvironmentVariableList, _ := shared.StaleEnvFile(envFile, getenv); stale {
461 for _, changedEnvironmentVariable := range changedEnvironmentVariableList {
462 ctx.Metrics.AddChangedEnvironmentVariable(changedEnvironmentVariable)
463 }
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200464 os.Remove(envFile)
465 }
466}
467
Dan Willemsen1e704462016-08-21 15:17:17 -0700468func runSoong(ctx Context, config Config) {
Nan Zhang17f27672018-12-12 16:01:49 -0800469 ctx.BeginTrace(metrics.RunSoong, "soong")
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700470 defer ctx.EndTrace()
471
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100472 // We have two environment files: .available is the one with every variable,
473 // .used with the ones that were actually used. The latter is used to
474 // determine whether Soong needs to be re-run since why re-run it if only
475 // unused variables were changed?
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200476 envFile := filepath.Join(config.SoongOutDir(), availableEnvFile)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100477
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100478 // This is done unconditionally, but does not take a measurable amount of time
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200479 bootstrapBlueprint(ctx, config)
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700480
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100481 soongBuildEnv := config.Environment().Copy()
482 soongBuildEnv.Set("TOP", os.Getenv("TOP"))
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100483 // For Bazel mixed builds.
Joe Onoratoba29f382022-10-24 06:38:11 -0700484 soongBuildEnv.Set("BAZEL_PATH", "./build/bazel/bin/bazel")
Chris Parsonsa9bef142022-09-28 15:07:46 -0400485 // Bazel's HOME var is set to an output subdirectory which doesn't exist. This
486 // prevents Bazel from file I/O in the actual user HOME directory.
487 soongBuildEnv.Set("BAZEL_HOME", absPath(ctx, filepath.Join(config.BazelOutDir(), "bazelhome")))
Liz Kammer2af5ea82022-11-11 14:21:03 -0500488 soongBuildEnv.Set("BAZEL_OUTPUT_BASE", config.bazelOutputBase())
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100489 soongBuildEnv.Set("BAZEL_WORKSPACE", absPath(ctx, "."))
490 soongBuildEnv.Set("BAZEL_METRICS_DIR", config.BazelMetricsDir())
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500491 soongBuildEnv.Set("LOG_DIR", config.LogsDir())
Jingwen Chen3b13b612022-10-17 12:14:26 +0000492 soongBuildEnv.Set("BAZEL_DEPS_FILE", absPath(ctx, filepath.Join(config.BazelOutDir(), "bazel.list")))
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100493
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100494 // For Soong bootstrapping tests
495 if os.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
496 soongBuildEnv.Set("ALLOW_MISSING_DEPENDENCIES", "true")
497 }
498
Paul Duffin5e85c662021-03-05 12:26:14 +0000499 err := writeEnvironmentFile(ctx, envFile, soongBuildEnv.AsMap())
500 if err != nil {
501 ctx.Fatalf("failed to write environment file %s: %s", envFile, err)
502 }
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100503
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700504 func() {
Nan Zhang17f27672018-12-12 16:01:49 -0800505 ctx.BeginTrace(metrics.RunSoong, "environment check")
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700506 defer ctx.EndTrace()
507
Jason Wu2520f5e2023-05-30 19:45:36 -0400508 checkEnvironmentFile(ctx, soongBuildEnv, config.UsedEnvFile(soongBuildTag))
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200509
Chris Parsonsef615e52022-08-18 22:04:11 -0400510 if config.BazelBuildEnabled() || config.Bp2Build() {
Jason Wu2520f5e2023-05-30 19:45:36 -0400511 checkEnvironmentFile(ctx, soongBuildEnv, config.UsedEnvFile(bp2buildFilesTag))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200512 }
513
514 if config.JsonModuleGraph() {
Jason Wu2520f5e2023-05-30 19:45:36 -0400515 checkEnvironmentFile(ctx, soongBuildEnv, config.UsedEnvFile(jsonModuleGraphTag))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200516 }
517
518 if config.Queryview() {
Jason Wu2520f5e2023-05-30 19:45:36 -0400519 checkEnvironmentFile(ctx, soongBuildEnv, config.UsedEnvFile(queryviewTag))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200520 }
521
522 if config.SoongDocs() {
Jason Wu2520f5e2023-05-30 19:45:36 -0400523 checkEnvironmentFile(ctx, soongBuildEnv, config.UsedEnvFile(soongDocsTag))
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700524 }
525 }()
526
Colin Cross9191df22021-10-29 13:11:32 -0700527 runMicrofactory(ctx, config, "bpglob", "github.com/google/blueprint/bootstrap/bpglob",
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700528 map[string]string{"github.com/google/blueprint": "build/blueprint"})
Dan Willemsen5af1cbe2018-07-05 21:46:51 -0700529
usta49012ee2023-05-22 16:33:27 -0400530 ninja := func(targets ...string) {
531 ctx.BeginTrace(metrics.RunSoong, "bootstrap")
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700532 defer ctx.EndTrace()
533
Chris Parsons9402ca82023-02-23 17:28:06 -0500534 if config.IsPersistentBazelEnabled() {
Chris Parsonsc83398f2023-05-31 18:41:41 +0000535 bazelProxy := bazel.NewProxyServer(ctx.Logger, config.OutDir(), filepath.Join(config.SoongOutDir(), "workspace"), config.GetBazeliskBazelVersion())
usta49012ee2023-05-22 16:33:27 -0400536 if err := bazelProxy.Start(); err != nil {
537 ctx.Fatalf("Failed to create bazel proxy")
538 }
Chris Parsons9402ca82023-02-23 17:28:06 -0500539 defer bazelProxy.Close()
540 }
541
Dan Willemsenb82471a2018-05-17 16:37:09 -0700542 fifo := filepath.Join(config.OutDir(), ".ninja_fifo")
Colin Crossb98d3bc2019-03-21 16:02:58 -0700543 nr := status.NewNinjaReader(ctx, ctx.Status.StartTool(), fifo)
544 defer nr.Close()
Dan Willemsenb82471a2018-05-17 16:37:09 -0700545
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200546 ninjaArgs := []string{
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700547 "-d", "keepdepfile",
Dan Willemsen08218222020-05-18 14:02:02 -0700548 "-d", "stats",
Dan Willemsen6587bed2020-04-18 20:25:59 -0700549 "-o", "usesphonyoutputs=yes",
550 "-o", "preremoveoutputs=yes",
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700551 "-w", "dupbuild=err",
Dan Willemsen6587bed2020-04-18 20:25:59 -0700552 "-w", "outputdir=err",
553 "-w", "missingoutfile=err",
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700554 "-j", strconv.Itoa(config.Parallel()),
Dan Willemsen02736672018-07-17 17:54:31 -0700555 "--frontend_file", fifo,
usta49012ee2023-05-22 16:33:27 -0400556 "-f", filepath.Join(config.SoongOutDir(), "bootstrap.ninja"),
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200557 }
558
Usta Shrestha8dc8b0a2022-08-10 17:39:37 -0400559 if extra, ok := config.Environment().Get("SOONG_UI_NINJA_ARGS"); ok {
560 ctx.Printf(`CAUTION: arguments in $SOONG_UI_NINJA_ARGS=%q, e.g. "-n", can make soong_build FAIL or INCORRECT`, extra)
561 ninjaArgs = append(ninjaArgs, strings.Fields(extra)...)
562 }
563
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200564 ninjaArgs = append(ninjaArgs, targets...)
usta49012ee2023-05-22 16:33:27 -0400565 cmd := Command(ctx, config, "soong bootstrap",
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200566 config.PrebuiltBuildTool("ninja"), ninjaArgs...)
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500567
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100568 var ninjaEnv Environment
Lukacs T. Berki73ab9282021-03-10 10:48:39 +0100569
570 // This is currently how the command line to invoke soong_build finds the
571 // root of the source tree and the output root
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100572 ninjaEnv.Set("TOP", os.Getenv("TOP"))
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100573
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100574 cmd.Environment = &ninjaEnv
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700575 cmd.Sandbox = soongSandbox
Colin Cross7b97ecd2019-06-19 13:17:59 -0700576 cmd.RunAndStreamOrFatal()
Dan Willemsen1e704462016-08-21 15:17:17 -0700577 }
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200578
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200579 targets := make([]string, 0, 0)
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200580
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200581 if config.JsonModuleGraph() {
582 targets = append(targets, config.ModuleGraphFile())
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200583 }
584
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200585 if config.Bp2Build() {
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000586 targets = append(targets, config.Bp2BuildWorkspaceMarkerFile())
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200587 }
588
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200589 if config.Queryview() {
590 targets = append(targets, config.QueryviewMarkerFile())
591 }
592
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200593 if config.SoongDocs() {
594 targets = append(targets, config.SoongDocsHtml())
595 }
596
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200597 if config.SoongBuildInvocationNeeded() {
598 // 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 -0700599 targets = append(targets, config.SoongNinjaFile())
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200600 }
601
usta49012ee2023-05-22 16:33:27 -0400602 ninja(targets...)
Colin Crossb72c9092020-02-10 11:23:49 -0800603
Colin Cross8ba7d472020-06-25 11:27:52 -0700604 distGzipFile(ctx, config, config.SoongNinjaFile(), "soong")
Jihoon Kang9f4f8a32022-08-16 00:57:30 +0000605 distFile(ctx, config, config.SoongVarsFile(), "soong")
Colin Cross8ba7d472020-06-25 11:27:52 -0700606
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000607 if !config.SkipKati() {
Colin Cross8ba7d472020-06-25 11:27:52 -0700608 distGzipFile(ctx, config, config.SoongAndroidMk(), "soong")
609 distGzipFile(ctx, config, config.SoongMakeVarsMk(), "soong")
610 }
611
Rob Seymour33cd10d2022-03-02 23:10:25 +0000612 if config.JsonModuleGraph() {
613 distGzipFile(ctx, config, config.ModuleGraphFile(), "soong")
614 }
Colin Crossb72c9092020-02-10 11:23:49 -0800615}
616
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100617func runMicrofactory(ctx Context, config Config, name string, pkg string, mapping map[string]string) {
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700618 ctx.BeginTrace(metrics.RunSoong, name)
619 defer ctx.EndTrace()
620 cfg := microfactory.Config{TrimPath: absPath(ctx, ".")}
621 for pkgPrefix, pathPrefix := range mapping {
622 cfg.Map(pkgPrefix, pathPrefix)
623 }
624
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100625 exePath := filepath.Join(config.SoongOutDir(), name)
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700626 dir := filepath.Dir(exePath)
627 if err := os.MkdirAll(dir, 0777); err != nil {
628 ctx.Fatalf("cannot create %s: %s", dir, err)
629 }
630 if _, err := microfactory.Build(&cfg, exePath, pkg); err != nil {
631 ctx.Fatalf("failed to build %s: %s", name, err)
632 }
633}