blob: ac9bf3a60c9b13ce54759d2e4ec6524b118569d0 [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"
Kousik Kumarca390b22023-10-04 04:14:28 +000019 "io/fs"
Dan Willemsen99a75cd2017-08-04 16:04:04 -070020 "os"
Dan Willemsen1e704462016-08-21 15:17:17 -070021 "path/filepath"
Dan Willemsen99a75cd2017-08-04 16:04:04 -070022 "strconv"
Usta Shrestha8dc8b0a2022-08-10 17:39:37 -040023 "strings"
Kousik Kumarca390b22023-10-04 04:14:28 +000024 "sync"
25 "sync/atomic"
Dan Willemsen99a75cd2017-08-04 16:04:04 -070026
Chris Parsons9402ca82023-02-23 17:28:06 -050027 "android/soong/bazel"
Dan Willemsen4591b642021-05-24 14:24:12 -070028 "android/soong/ui/metrics"
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 Willemsen1e704462016-08-21 15:17:17 -070036)
37
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020038const (
39 availableEnvFile = "soong.environment.available"
40 usedEnvFile = "soong.environment.used"
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +020041
Lukacs T. Berkic541cd22022-10-26 07:26:50 +000042 soongBuildTag = "build"
43 bp2buildFilesTag = "bp2build_files"
44 bp2buildWorkspaceTag = "bp2build_workspace"
45 jsonModuleGraphTag = "modulegraph"
46 queryviewTag = "queryview"
Lukacs T. Berkic541cd22022-10-26 07:26:50 +000047 soongDocsTag = "soong_docs"
Colin Cross9191df22021-10-29 13:11:32 -070048
49 // bootstrapEpoch is used to determine if an incremental build is incompatible with the current
50 // version of bootstrap and needs cleaning before continuing the build. Increment this for
51 // incompatible changes, for example when moving the location of the bpglob binary that is
52 // executed during bootstrap before the primary builder has had a chance to update the path.
Lukacs T. Berki9985d9a2021-11-04 11:47:42 +010053 bootstrapEpoch = 1
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020054)
55
Kousik Kumarca390b22023-10-04 04:14:28 +000056var (
57 // Used during parallel update of symlinks in out directory to reflect new
58 // TOP dir.
59 symlinkWg sync.WaitGroup
60 numFound, numUpdated uint32
61)
62
Sasha Smundak4cbe83a2022-11-28 17:02:40 -080063func writeEnvironmentFile(_ Context, envFile string, envDeps map[string]string) error {
Lukacs T. Berki7690c092021-02-26 14:27:36 +010064 data, err := shared.EnvFileContents(envDeps)
65 if err != nil {
66 return err
67 }
68
Sasha Smundak4cbe83a2022-11-28 17:02:40 -080069 return os.WriteFile(envFile, data, 0644)
Lukacs T. Berki7690c092021-02-26 14:27:36 +010070}
71
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000072// This uses Android.bp files and various tools to generate <builddir>/build.ninja.
73//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010074// However, the execution of <builddir>/build.ninja happens later in
75// build/soong/ui/build/build.go#Build()
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000076//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010077// We want to rely on as few prebuilts as possible, so we need to bootstrap
78// Soong. The process is as follows:
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000079//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010080// 1. We use "Microfactory", a simple tool to compile Go code, to build
81// first itself, then soong_ui from soong_ui.bash. This binary contains
82// parts of soong_build that are needed to build itself.
83// 2. This simplified version of soong_build then reads the Blueprint files
84// that describe itself and emits .bootstrap/build.ninja that describes
85// how to build its full version and use that to produce the final Ninja
86// file Soong emits.
87// 3. soong_ui executes .bootstrap/build.ninja
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000088//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010089// (After this, Kati is executed to parse the Makefiles, but that's not part of
90// bootstrapping Soong)
91
92// A tiny struct used to tell Blueprint that it's in bootstrap mode. It would
93// probably be nicer to use a flag in bootstrap.Args instead.
94type BlueprintConfig struct {
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +020095 toolDir string
96 soongOutDir string
97 outDir string
98 runGoTests bool
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +020099 debugCompilation bool
100 subninjas []string
101 primaryBuilderInvocations []bootstrap.PrimaryBuilderInvocation
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100102}
103
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200104func (c BlueprintConfig) HostToolDir() string {
105 return c.toolDir
106}
107
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200108func (c BlueprintConfig) SoongOutDir() string {
109 return c.soongOutDir
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100110}
111
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200112func (c BlueprintConfig) OutDir() string {
113 return c.outDir
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100114}
115
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +0200116func (c BlueprintConfig) RunGoTests() bool {
117 return c.runGoTests
118}
119
Lukacs T. Berki5f6cb1d2021-03-17 15:03:14 +0100120func (c BlueprintConfig) DebugCompilation() bool {
121 return c.debugCompilation
122}
123
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +0200124func (c BlueprintConfig) Subninjas() []string {
125 return c.subninjas
126}
127
128func (c BlueprintConfig) PrimaryBuilderInvocations() []bootstrap.PrimaryBuilderInvocation {
129 return c.primaryBuilderInvocations
130}
131
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200132func environmentArgs(config Config, tag string) []string {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200133 return []string{
134 "--available_env", shared.JoinPath(config.SoongOutDir(), availableEnvFile),
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200135 "--used_env", config.UsedEnvFile(tag),
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200136 }
137}
Spandan Das8f99ae62021-06-11 16:48:06 +0000138
Colin Cross9191df22021-10-29 13:11:32 -0700139func writeEmptyFile(ctx Context, path string) {
Spandan Das8f99ae62021-06-11 16:48:06 +0000140 err := os.MkdirAll(filepath.Dir(path), 0777)
141 if err != nil {
Colin Cross9191df22021-10-29 13:11:32 -0700142 ctx.Fatalf("Failed to create parent directories of empty file '%s': %s", path, err)
Spandan Das8f99ae62021-06-11 16:48:06 +0000143 }
144
Colin Cross9191df22021-10-29 13:11:32 -0700145 if exists, err := fileExists(path); err != nil {
146 ctx.Fatalf("Failed to check if file '%s' exists: %s", path, err)
147 } else if !exists {
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800148 err = os.WriteFile(path, nil, 0666)
Spandan Das8f99ae62021-06-11 16:48:06 +0000149 if err != nil {
Colin Cross9191df22021-10-29 13:11:32 -0700150 ctx.Fatalf("Failed to create empty file '%s': %s", path, err)
Spandan Das8f99ae62021-06-11 16:48:06 +0000151 }
152 }
153}
154
Colin Cross9191df22021-10-29 13:11:32 -0700155func fileExists(path string) (bool, error) {
156 if _, err := os.Stat(path); os.IsNotExist(err) {
157 return false, nil
158 } else if err != nil {
159 return false, err
160 }
161 return true, nil
162}
163
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800164type PrimaryBuilderFactory struct {
165 name string
166 description string
167 config Config
168 output string
169 specificArgs []string
170 debugPort string
171}
172
Jeongik Chaccf37002023-08-04 01:46:32 +0900173func getGlobPathName(config Config) string {
174 globPathName, ok := config.TargetProductOrErr()
175 if ok != nil {
176 globPathName = soongBuildTag
177 }
178 return globPathName
179}
180
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800181func (pb PrimaryBuilderFactory) primaryBuilderInvocation() bootstrap.PrimaryBuilderInvocation {
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200182 commonArgs := make([]string, 0, 0)
183
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800184 if !pb.config.skipSoongTests {
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200185 commonArgs = append(commonArgs, "-t")
186 }
187
LaMont Jones80f70352023-03-20 19:58:25 +0000188 if pb.config.multitreeBuild {
LaMont Jones52a72432023-03-09 18:19:35 +0000189 commonArgs = append(commonArgs, "--multitree-build")
190 }
Jihoon Kang1bff0342023-01-17 20:40:22 +0000191 if pb.config.buildFromTextStub {
192 commonArgs = append(commonArgs, "--build-from-text-stub")
193 }
LaMont Jones52a72432023-03-09 18:19:35 +0000194
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800195 commonArgs = append(commonArgs, "-l", filepath.Join(pb.config.FileListDir(), "Android.bp.list"))
Lukacs T. Berki13644272022-01-05 10:29:56 +0100196 invocationEnv := make(map[string]string)
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800197 if pb.debugPort != "" {
ustafb67fd12022-08-19 19:26:00 -0400198 //debug mode
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800199 commonArgs = append(commonArgs, "--delve_listen", pb.debugPort,
200 "--delve_path", shared.ResolveDelveBinary())
Lukacs T. Berki13644272022-01-05 10:29:56 +0100201 // GODEBUG=asyncpreemptoff=1 disables the preemption of goroutines. This
202 // is useful because the preemption happens by sending SIGURG to the OS
203 // thread hosting the goroutine in question and each signal results in
204 // work that needs to be done by Delve; it uses ptrace to debug the Go
205 // process and the tracer process must deal with every signal (it is not
206 // possible to selectively ignore SIGURG). This makes debugging slower,
207 // sometimes by an order of magnitude depending on luck.
208 // The original reason for adding async preemption to Go is here:
209 // https://github.com/golang/proposal/blob/master/design/24543-non-cooperative-preemption.md
210 invocationEnv["GODEBUG"] = "asyncpreemptoff=1"
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200211 }
212
ustafb67fd12022-08-19 19:26:00 -0400213 var allArgs []string
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800214 allArgs = append(allArgs, pb.specificArgs...)
Jeongik Chaccf37002023-08-04 01:46:32 +0900215 globPathName := pb.name
216 // Glob path for soong build would be separated per product target
217 if pb.name == soongBuildTag {
218 globPathName = getGlobPathName(pb.config)
219 }
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200220 allArgs = append(allArgs,
Jeongik Chaccf37002023-08-04 01:46:32 +0900221 "--globListDir", globPathName,
222 "--globFile", pb.config.NamedGlobFile(globPathName))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200223
224 allArgs = append(allArgs, commonArgs...)
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800225 allArgs = append(allArgs, environmentArgs(pb.config, pb.name)...)
Sasha Smundakfaa97b72022-11-18 15:32:49 -0800226 if profileCpu := os.Getenv("SOONG_PROFILE_CPU"); profileCpu != "" {
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800227 allArgs = append(allArgs, "--cpuprofile", profileCpu+"."+pb.name)
Sasha Smundakfaa97b72022-11-18 15:32:49 -0800228 }
229 if profileMem := os.Getenv("SOONG_PROFILE_MEM"); profileMem != "" {
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800230 allArgs = append(allArgs, "--memprofile", profileMem+"."+pb.name)
Sasha Smundakfaa97b72022-11-18 15:32:49 -0800231 }
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200232 allArgs = append(allArgs, "Android.bp")
233
234 return bootstrap.PrimaryBuilderInvocation{
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000235 Inputs: []string{"Android.bp"},
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800236 Outputs: []string{pb.output},
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000237 Args: allArgs,
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800238 Description: pb.description,
Lukacs T. Berki2fad3412022-01-04 14:40:13 +0100239 // NB: Changing the value of this environment variable will not result in a
240 // rebuild. The bootstrap Ninja file will change, but apparently Ninja does
241 // not consider changing the pool specified in a statement a change that's
242 // worth rebuilding for.
243 Console: os.Getenv("SOONG_UNBUFFERED_OUTPUT") == "1",
Lukacs T. Berki13644272022-01-05 10:29:56 +0100244 Env: invocationEnv,
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200245 }
246}
247
Colin Cross9191df22021-10-29 13:11:32 -0700248// bootstrapEpochCleanup deletes files used by bootstrap during incremental builds across
249// incompatible changes. Incompatible changes are marked by incrementing the bootstrapEpoch
250// constant. A tree is considered out of date for the current epoch of the
251// .soong.bootstrap.epoch.<epoch> file doesn't exist.
252func bootstrapEpochCleanup(ctx Context, config Config) {
253 epochFile := fmt.Sprintf(".soong.bootstrap.epoch.%d", bootstrapEpoch)
254 epochPath := filepath.Join(config.SoongOutDir(), epochFile)
255 if exists, err := fileExists(epochPath); err != nil {
256 ctx.Fatalf("failed to check if bootstrap epoch file %q exists: %q", epochPath, err)
257 } else if !exists {
258 // The tree is out of date for the current epoch, delete files used by bootstrap
259 // and force the primary builder to rerun.
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900260 os.Remove(config.SoongNinjaFile())
Colin Cross9191df22021-10-29 13:11:32 -0700261 for _, globFile := range bootstrapGlobFileList(config) {
262 os.Remove(globFile)
263 }
264
265 // Mark the tree as up to date with the current epoch by writing the epoch marker file.
266 writeEmptyFile(ctx, epochPath)
267 }
268}
269
270func bootstrapGlobFileList(config Config) []string {
271 return []string{
Jeongik Chaccf37002023-08-04 01:46:32 +0900272 config.NamedGlobFile(getGlobPathName(config)),
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000273 config.NamedGlobFile(bp2buildFilesTag),
Colin Cross9191df22021-10-29 13:11:32 -0700274 config.NamedGlobFile(jsonModuleGraphTag),
275 config.NamedGlobFile(queryviewTag),
276 config.NamedGlobFile(soongDocsTag),
277 }
278}
279
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200280func bootstrapBlueprint(ctx Context, config Config) {
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100281 ctx.BeginTrace(metrics.RunSoong, "blueprint bootstrap")
282 defer ctx.EndTrace()
283
Colin Cross9191df22021-10-29 13:11:32 -0700284 // Clean up some files for incremental builds across incompatible changes.
285 bootstrapEpochCleanup(ctx, config)
286
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900287 baseArgs := []string{"--soong_variables", config.SoongVarsFile()}
288
289 mainSoongBuildExtraArgs := append(baseArgs, "-o", config.SoongNinjaFile())
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200290 if config.EmptyNinjaFile() {
291 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--empty-ninja-file")
Lukacs T. Berki745380c2021-04-12 12:07:44 +0200292 }
Chris Parsonsef615e52022-08-18 22:04:11 -0400293 if config.bazelProdMode {
294 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--bazel-mode")
295 }
MarkDacekb78465d2022-10-18 20:10:16 +0000296 if config.bazelStagingMode {
297 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--bazel-mode-staging")
298 }
Chris Parsons9402ca82023-02-23 17:28:06 -0500299 if config.IsPersistentBazelEnabled() {
300 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--use-bazel-proxy")
301 }
MarkDacekd06db5d2022-11-29 00:47:59 +0000302 if len(config.bazelForceEnabledModules) > 0 {
303 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--bazel-force-enabled-modules="+config.bazelForceEnabledModules)
304 }
LaMont Jones52a72432023-03-09 18:19:35 +0000305 if config.MultitreeBuild() {
306 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--multitree-build")
307 }
Jihoon Kang1bff0342023-01-17 20:40:22 +0000308 if config.buildFromTextStub {
309 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--build-from-text-stub")
310 }
MarkDacekf47e1422023-04-19 16:47:36 +0000311 if config.ensureAllowlistIntegrity {
312 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--ensure-allowlist-integrity")
313 }
MarkDacekd06db5d2022-11-29 00:47:59 +0000314
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000315 queryviewDir := filepath.Join(config.SoongOutDir(), "queryview")
Spandan Das5af0bd32022-09-28 20:43:08 +0000316
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800317 pbfs := []PrimaryBuilderFactory{
318 {
319 name: soongBuildTag,
320 description: fmt.Sprintf("analyzing Android.bp files and generating ninja file at %s", config.SoongNinjaFile()),
321 config: config,
322 output: config.SoongNinjaFile(),
323 specificArgs: mainSoongBuildExtraArgs,
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000324 },
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800325 {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900326 name: bp2buildFilesTag,
327 description: fmt.Sprintf("converting Android.bp files to BUILD files at %s/bp2build", config.SoongOutDir()),
328 config: config,
329 output: config.Bp2BuildFilesMarkerFile(),
330 specificArgs: append(baseArgs,
331 "--bp2build_marker", config.Bp2BuildFilesMarkerFile(),
332 ),
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800333 },
334 {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900335 name: bp2buildWorkspaceTag,
336 description: "Creating Bazel symlink forest",
337 config: config,
338 output: config.Bp2BuildWorkspaceMarkerFile(),
339 specificArgs: append(baseArgs,
340 "--symlink_forest_marker", config.Bp2BuildWorkspaceMarkerFile(),
341 ),
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800342 },
343 {
344 name: jsonModuleGraphTag,
345 description: fmt.Sprintf("generating the Soong module graph at %s", config.ModuleGraphFile()),
346 config: config,
347 output: config.ModuleGraphFile(),
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900348 specificArgs: append(baseArgs,
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800349 "--module_graph_file", config.ModuleGraphFile(),
350 "--module_actions_file", config.ModuleActionsFile(),
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900351 ),
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800352 },
353 {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900354 name: queryviewTag,
355 description: fmt.Sprintf("generating the Soong module graph as a Bazel workspace at %s", queryviewDir),
356 config: config,
357 output: config.QueryviewMarkerFile(),
358 specificArgs: append(baseArgs,
359 "--bazel_queryview_dir", queryviewDir,
360 ),
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800361 },
362 {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900363 name: soongDocsTag,
364 description: fmt.Sprintf("generating Soong docs at %s", config.SoongDocsHtml()),
365 config: config,
366 output: config.SoongDocsHtml(),
367 specificArgs: append(baseArgs,
368 "--soong_docs", config.SoongDocsHtml(),
369 ),
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800370 },
371 }
372
373 // Figure out which invocations will be run under the debugger:
374 // * SOONG_DELVE if set specifies listening port
375 // * SOONG_DELVE_STEPS if set specifies specific invocations to be debugged, otherwise all are
376 debuggedInvocations := make(map[string]bool)
377 delvePort := os.Getenv("SOONG_DELVE")
378 if delvePort != "" {
379 if steps := os.Getenv("SOONG_DELVE_STEPS"); steps != "" {
380 var validSteps []string
381 for _, pbf := range pbfs {
382 debuggedInvocations[pbf.name] = false
383 validSteps = append(validSteps, pbf.name)
384
385 }
386 for _, step := range strings.Split(steps, ",") {
387 if _, ok := debuggedInvocations[step]; ok {
388 debuggedInvocations[step] = true
389 } else {
390 ctx.Fatalf("SOONG_DELVE_STEPS contains unknown soong_build step %s\n"+
391 "Valid steps are %v", step, validSteps)
392 }
393 }
394 } else {
395 // SOONG_DELVE_STEPS is not set, run all steps in the debugger
396 for _, pbf := range pbfs {
397 debuggedInvocations[pbf.name] = true
398 }
399 }
400 }
401
402 var invocations []bootstrap.PrimaryBuilderInvocation
403 for _, pbf := range pbfs {
404 if debuggedInvocations[pbf.name] {
405 pbf.debugPort = delvePort
406 }
407 pbi := pbf.primaryBuilderInvocation()
408 // Some invocations require adjustment:
409 switch pbf.name {
410 case soongBuildTag:
411 if config.BazelBuildEnabled() {
412 // Mixed builds call Bazel from soong_build and they therefore need the
413 // Bazel workspace to be available. Make that so by adding a dependency on
414 // the bp2build marker file to the action that invokes soong_build .
415 pbi.OrderOnlyInputs = append(pbi.OrderOnlyInputs, config.Bp2BuildWorkspaceMarkerFile())
416 }
417 case bp2buildWorkspaceTag:
418 pbi.Inputs = append(pbi.Inputs,
419 config.Bp2BuildFilesMarkerFile(),
420 filepath.Join(config.FileListDir(), "bazel.list"))
Wei Li2c9e8d62023-05-05 01:07:15 -0700421 case bp2buildFilesTag:
422 pbi.Inputs = append(pbi.Inputs, filepath.Join(config.FileListDir(), "METADATA.list"))
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800423 }
424 invocations = append(invocations, pbi)
425 }
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200426
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200427 // The glob .ninja files are subninja'd. However, they are generated during
428 // the build itself so we write an empty file if the file does not exist yet
429 // so that the subninja doesn't fail on clean builds
Colin Cross9191df22021-10-29 13:11:32 -0700430 for _, globFile := range bootstrapGlobFileList(config) {
431 writeEmptyFile(ctx, globFile)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200432 }
433
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800434 blueprintArgs := bootstrap.Args{
435 ModuleListFile: filepath.Join(config.FileListDir(), "Android.bp.list"),
436 OutFile: shared.JoinPath(config.SoongOutDir(), "bootstrap.ninja"),
437 EmptyNinjaFile: false,
438 }
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200439
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100440 blueprintCtx := blueprint.NewContext()
Spandan Dasc5763832022-11-08 18:42:16 +0000441 blueprintCtx.AddIncludeTags(config.GetIncludeTags()...)
Sam Delmerico98a73292023-02-21 11:50:29 -0500442 blueprintCtx.AddSourceRootDirs(config.GetSourceRootDirs()...)
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100443 blueprintCtx.SetIgnoreUnknownModuleTypes(true)
444 blueprintConfig := BlueprintConfig{
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200445 soongOutDir: config.SoongOutDir(),
446 toolDir: config.HostToolDir(),
447 outDir: config.OutDir(),
448 runGoTests: !config.skipSoongTests,
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200449 // If we want to debug soong_build, we need to compile it for debugging
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800450 debugCompilation: delvePort != "",
451 subninjas: bootstrapGlobFileList(config),
452 primaryBuilderInvocations: invocations,
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100453 }
454
usta5bb4a5d2022-08-24 12:53:46 -0400455 // since `bootstrap.ninja` is regenerated unconditionally, we ignore the deps, i.e. little
456 // reason to write a `bootstrap.ninja.d` file
Lukacs T. Berkic357c812023-06-20 09:30:06 +0000457 _, err := bootstrap.RunBlueprint(blueprintArgs, bootstrap.DoEverything, blueprintCtx, blueprintConfig)
458 if err != nil {
459 ctx.Fatal(err)
460 }
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100461}
462
Jason Wu2520f5e2023-05-30 19:45:36 -0400463func checkEnvironmentFile(ctx Context, currentEnv *Environment, envFile string) {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200464 getenv := func(k string) string {
465 v, _ := currentEnv.Get(k)
466 return v
467 }
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200468
Jason Wu2520f5e2023-05-30 19:45:36 -0400469 // Log the changed environment variables to ChangedEnvironmentVariable field
470 if stale, changedEnvironmentVariableList, _ := shared.StaleEnvFile(envFile, getenv); stale {
471 for _, changedEnvironmentVariable := range changedEnvironmentVariableList {
472 ctx.Metrics.AddChangedEnvironmentVariable(changedEnvironmentVariable)
473 }
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200474 os.Remove(envFile)
475 }
476}
477
Kousik Kumarca390b22023-10-04 04:14:28 +0000478func updateSymlinks(ctx Context, dir, prevCWD, cwd string) error {
479 defer symlinkWg.Done()
480
481 visit := func(path string, d fs.DirEntry, err error) error {
482 if d.IsDir() && path != dir {
483 symlinkWg.Add(1)
484 go updateSymlinks(ctx, path, prevCWD, cwd)
485 return filepath.SkipDir
486 }
487 f, err := d.Info()
488 if err != nil {
489 return err
490 }
491 // If the file is not a symlink, we don't have to update it.
492 if f.Mode()&os.ModeSymlink != os.ModeSymlink {
493 return nil
494 }
495
496 atomic.AddUint32(&numFound, 1)
497 target, err := os.Readlink(path)
498 if err != nil {
499 return err
500 }
501 if strings.HasPrefix(target, prevCWD) &&
502 (len(target) == len(prevCWD) || target[len(prevCWD)] == '/') {
503 target = filepath.Join(cwd, target[len(prevCWD):])
504 if err := os.Remove(path); err != nil {
505 return err
506 }
507 if err := os.Symlink(target, path); err != nil {
508 return err
509 }
510 atomic.AddUint32(&numUpdated, 1)
511 }
512 return nil
513 }
514
515 if err := filepath.WalkDir(dir, visit); err != nil {
516 return err
517 }
518 return nil
519}
520
521func fixOutDirSymlinks(ctx Context, config Config, outDir string) error {
522 cwd, err := os.Getwd()
523 if err != nil {
524 return err
525 }
526
527 // Record the .top as the very last thing in the function.
528 tf := filepath.Join(outDir, ".top")
529 defer func() {
530 if err := os.WriteFile(tf, []byte(cwd), 0644); err != nil {
531 fmt.Fprintf(os.Stderr, fmt.Sprintf("Unable to log CWD: %v", err))
532 }
533 }()
534
535 // Find the previous working directory if it was recorded.
536 var prevCWD string
537 pcwd, err := os.ReadFile(tf)
538 if err != nil {
539 if os.IsNotExist(err) {
540 // No previous working directory recorded, nothing to do.
541 return nil
542 }
543 return err
544 }
545 prevCWD = strings.Trim(string(pcwd), "\n")
546
547 if prevCWD == cwd {
548 // We are in the same source dir, nothing to update.
549 return nil
550 }
551
552 symlinkWg.Add(1)
553 if err := updateSymlinks(ctx, outDir, prevCWD, cwd); err != nil {
554 return err
555 }
556 symlinkWg.Wait()
557 ctx.Println(fmt.Sprintf("Updated %d/%d symlinks in dir %v", numUpdated, numFound, outDir))
558 return nil
559}
560
561func migrateOutputSymlinks(ctx Context, config Config) error {
562 // Figure out the real out directory ("out" could be a symlink).
563 outDir := config.OutDir()
564 s, err := os.Lstat(outDir)
565 if err != nil {
566 if os.IsNotExist(err) {
567 // No out dir exists, no symlinks to migrate.
568 return nil
569 }
570 return err
571 }
572 if s.Mode()&os.ModeSymlink == os.ModeSymlink {
573 target, err := filepath.EvalSymlinks(outDir)
574 if err != nil {
575 return err
576 }
577 outDir = target
578 }
579 return fixOutDirSymlinks(ctx, config, outDir)
580}
581
Dan Willemsen1e704462016-08-21 15:17:17 -0700582func runSoong(ctx Context, config Config) {
Nan Zhang17f27672018-12-12 16:01:49 -0800583 ctx.BeginTrace(metrics.RunSoong, "soong")
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700584 defer ctx.EndTrace()
585
Kousik Kumarca390b22023-10-04 04:14:28 +0000586 if err := migrateOutputSymlinks(ctx, config); err != nil {
587 ctx.Fatalf("failed to migrate output directory to current TOP dir: %v", err)
588 }
589
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100590 // We have two environment files: .available is the one with every variable,
591 // .used with the ones that were actually used. The latter is used to
592 // determine whether Soong needs to be re-run since why re-run it if only
593 // unused variables were changed?
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200594 envFile := filepath.Join(config.SoongOutDir(), availableEnvFile)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100595
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100596 // This is done unconditionally, but does not take a measurable amount of time
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200597 bootstrapBlueprint(ctx, config)
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700598
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100599 soongBuildEnv := config.Environment().Copy()
600 soongBuildEnv.Set("TOP", os.Getenv("TOP"))
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100601 // For Bazel mixed builds.
Joe Onoratoba29f382022-10-24 06:38:11 -0700602 soongBuildEnv.Set("BAZEL_PATH", "./build/bazel/bin/bazel")
Chris Parsonsa9bef142022-09-28 15:07:46 -0400603 // Bazel's HOME var is set to an output subdirectory which doesn't exist. This
604 // prevents Bazel from file I/O in the actual user HOME directory.
605 soongBuildEnv.Set("BAZEL_HOME", absPath(ctx, filepath.Join(config.BazelOutDir(), "bazelhome")))
Liz Kammer2af5ea82022-11-11 14:21:03 -0500606 soongBuildEnv.Set("BAZEL_OUTPUT_BASE", config.bazelOutputBase())
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100607 soongBuildEnv.Set("BAZEL_WORKSPACE", absPath(ctx, "."))
608 soongBuildEnv.Set("BAZEL_METRICS_DIR", config.BazelMetricsDir())
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500609 soongBuildEnv.Set("LOG_DIR", config.LogsDir())
Jingwen Chen3b13b612022-10-17 12:14:26 +0000610 soongBuildEnv.Set("BAZEL_DEPS_FILE", absPath(ctx, filepath.Join(config.BazelOutDir(), "bazel.list")))
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100611
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100612 // For Soong bootstrapping tests
613 if os.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
614 soongBuildEnv.Set("ALLOW_MISSING_DEPENDENCIES", "true")
615 }
616
Paul Duffin5e85c662021-03-05 12:26:14 +0000617 err := writeEnvironmentFile(ctx, envFile, soongBuildEnv.AsMap())
618 if err != nil {
619 ctx.Fatalf("failed to write environment file %s: %s", envFile, err)
620 }
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100621
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700622 func() {
Nan Zhang17f27672018-12-12 16:01:49 -0800623 ctx.BeginTrace(metrics.RunSoong, "environment check")
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700624 defer ctx.EndTrace()
625
Jason Wu2520f5e2023-05-30 19:45:36 -0400626 checkEnvironmentFile(ctx, soongBuildEnv, config.UsedEnvFile(soongBuildTag))
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200627
Chris Parsonsef615e52022-08-18 22:04:11 -0400628 if config.BazelBuildEnabled() || config.Bp2Build() {
Jason Wu2520f5e2023-05-30 19:45:36 -0400629 checkEnvironmentFile(ctx, soongBuildEnv, config.UsedEnvFile(bp2buildFilesTag))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200630 }
631
632 if config.JsonModuleGraph() {
Jason Wu2520f5e2023-05-30 19:45:36 -0400633 checkEnvironmentFile(ctx, soongBuildEnv, config.UsedEnvFile(jsonModuleGraphTag))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200634 }
635
636 if config.Queryview() {
Jason Wu2520f5e2023-05-30 19:45:36 -0400637 checkEnvironmentFile(ctx, soongBuildEnv, config.UsedEnvFile(queryviewTag))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200638 }
639
640 if config.SoongDocs() {
Jason Wu2520f5e2023-05-30 19:45:36 -0400641 checkEnvironmentFile(ctx, soongBuildEnv, config.UsedEnvFile(soongDocsTag))
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700642 }
643 }()
644
Colin Cross9191df22021-10-29 13:11:32 -0700645 runMicrofactory(ctx, config, "bpglob", "github.com/google/blueprint/bootstrap/bpglob",
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700646 map[string]string{"github.com/google/blueprint": "build/blueprint"})
Dan Willemsen5af1cbe2018-07-05 21:46:51 -0700647
usta49012ee2023-05-22 16:33:27 -0400648 ninja := func(targets ...string) {
649 ctx.BeginTrace(metrics.RunSoong, "bootstrap")
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700650 defer ctx.EndTrace()
651
Chris Parsons9402ca82023-02-23 17:28:06 -0500652 if config.IsPersistentBazelEnabled() {
Chris Parsonsc83398f2023-05-31 18:41:41 +0000653 bazelProxy := bazel.NewProxyServer(ctx.Logger, config.OutDir(), filepath.Join(config.SoongOutDir(), "workspace"), config.GetBazeliskBazelVersion())
usta49012ee2023-05-22 16:33:27 -0400654 if err := bazelProxy.Start(); err != nil {
655 ctx.Fatalf("Failed to create bazel proxy")
656 }
Chris Parsons9402ca82023-02-23 17:28:06 -0500657 defer bazelProxy.Close()
658 }
659
Dan Willemsenb82471a2018-05-17 16:37:09 -0700660 fifo := filepath.Join(config.OutDir(), ".ninja_fifo")
Colin Crossb98d3bc2019-03-21 16:02:58 -0700661 nr := status.NewNinjaReader(ctx, ctx.Status.StartTool(), fifo)
662 defer nr.Close()
Dan Willemsenb82471a2018-05-17 16:37:09 -0700663
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200664 ninjaArgs := []string{
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700665 "-d", "keepdepfile",
Dan Willemsen08218222020-05-18 14:02:02 -0700666 "-d", "stats",
Dan Willemsen6587bed2020-04-18 20:25:59 -0700667 "-o", "usesphonyoutputs=yes",
668 "-o", "preremoveoutputs=yes",
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700669 "-w", "dupbuild=err",
Dan Willemsen6587bed2020-04-18 20:25:59 -0700670 "-w", "outputdir=err",
671 "-w", "missingoutfile=err",
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700672 "-j", strconv.Itoa(config.Parallel()),
Dan Willemsen02736672018-07-17 17:54:31 -0700673 "--frontend_file", fifo,
usta49012ee2023-05-22 16:33:27 -0400674 "-f", filepath.Join(config.SoongOutDir(), "bootstrap.ninja"),
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200675 }
676
Usta Shrestha8dc8b0a2022-08-10 17:39:37 -0400677 if extra, ok := config.Environment().Get("SOONG_UI_NINJA_ARGS"); ok {
678 ctx.Printf(`CAUTION: arguments in $SOONG_UI_NINJA_ARGS=%q, e.g. "-n", can make soong_build FAIL or INCORRECT`, extra)
679 ninjaArgs = append(ninjaArgs, strings.Fields(extra)...)
680 }
681
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200682 ninjaArgs = append(ninjaArgs, targets...)
usta49012ee2023-05-22 16:33:27 -0400683 cmd := Command(ctx, config, "soong bootstrap",
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200684 config.PrebuiltBuildTool("ninja"), ninjaArgs...)
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500685
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100686 var ninjaEnv Environment
Lukacs T. Berki73ab9282021-03-10 10:48:39 +0100687
688 // This is currently how the command line to invoke soong_build finds the
689 // root of the source tree and the output root
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100690 ninjaEnv.Set("TOP", os.Getenv("TOP"))
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100691
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100692 cmd.Environment = &ninjaEnv
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700693 cmd.Sandbox = soongSandbox
Colin Cross7b97ecd2019-06-19 13:17:59 -0700694 cmd.RunAndStreamOrFatal()
Dan Willemsen1e704462016-08-21 15:17:17 -0700695 }
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200696
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200697 targets := make([]string, 0, 0)
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200698
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200699 if config.JsonModuleGraph() {
700 targets = append(targets, config.ModuleGraphFile())
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200701 }
702
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200703 if config.Bp2Build() {
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000704 targets = append(targets, config.Bp2BuildWorkspaceMarkerFile())
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200705 }
706
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200707 if config.Queryview() {
708 targets = append(targets, config.QueryviewMarkerFile())
709 }
710
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200711 if config.SoongDocs() {
712 targets = append(targets, config.SoongDocsHtml())
713 }
714
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200715 if config.SoongBuildInvocationNeeded() {
716 // 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 -0700717 targets = append(targets, config.SoongNinjaFile())
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200718 }
719
usta49012ee2023-05-22 16:33:27 -0400720 ninja(targets...)
Colin Crossb72c9092020-02-10 11:23:49 -0800721
Colin Cross8ba7d472020-06-25 11:27:52 -0700722 distGzipFile(ctx, config, config.SoongNinjaFile(), "soong")
Jihoon Kang9f4f8a32022-08-16 00:57:30 +0000723 distFile(ctx, config, config.SoongVarsFile(), "soong")
Colin Cross8ba7d472020-06-25 11:27:52 -0700724
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000725 if !config.SkipKati() {
Colin Cross8ba7d472020-06-25 11:27:52 -0700726 distGzipFile(ctx, config, config.SoongAndroidMk(), "soong")
727 distGzipFile(ctx, config, config.SoongMakeVarsMk(), "soong")
728 }
729
Rob Seymour33cd10d2022-03-02 23:10:25 +0000730 if config.JsonModuleGraph() {
731 distGzipFile(ctx, config, config.ModuleGraphFile(), "soong")
732 }
Colin Crossb72c9092020-02-10 11:23:49 -0800733}
734
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100735func runMicrofactory(ctx Context, config Config, name string, pkg string, mapping map[string]string) {
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700736 ctx.BeginTrace(metrics.RunSoong, name)
737 defer ctx.EndTrace()
738 cfg := microfactory.Config{TrimPath: absPath(ctx, ".")}
739 for pkgPrefix, pathPrefix := range mapping {
740 cfg.Map(pkgPrefix, pathPrefix)
741 }
742
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100743 exePath := filepath.Join(config.SoongOutDir(), name)
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700744 dir := filepath.Dir(exePath)
745 if err := os.MkdirAll(dir, 0777); err != nil {
746 ctx.Fatalf("cannot create %s: %s", dir, err)
747 }
748 if _, err := microfactory.Build(&cfg, exePath, pkg); err != nil {
749 ctx.Fatalf("failed to build %s: %s", name, err)
750 }
751}