blob: 6bf34c4005260536131b09e4ab0581961fc58ba5 [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"
Colin Crossaa9a2732023-10-27 10:54:27 -070026 "time"
Dan Willemsen99a75cd2017-08-04 16:04:04 -070027
Yu Liu1b2ddc82024-05-15 19:28:56 +000028 "android/soong/ui/tracer"
29
Chris Parsons9402ca82023-02-23 17:28:06 -050030 "android/soong/bazel"
Dan Willemsen4591b642021-05-24 14:24:12 -070031 "android/soong/ui/metrics"
Colin Crossaa9a2732023-10-27 10:54:27 -070032 "android/soong/ui/metrics/metrics_proto"
Dan Willemsen4591b642021-05-24 14:24:12 -070033 "android/soong/ui/status"
34
35 "android/soong/shared"
36
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010037 "github.com/google/blueprint"
38 "github.com/google/blueprint/bootstrap"
Dan Willemsen99a75cd2017-08-04 16:04:04 -070039 "github.com/google/blueprint/microfactory"
Cole Faust8c0b11e2024-01-02 17:02:52 -080040 "github.com/google/blueprint/pathtools"
Colin Crossaa9a2732023-10-27 10:54:27 -070041
42 "google.golang.org/protobuf/proto"
Dan Willemsen1e704462016-08-21 15:17:17 -070043)
44
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020045const (
46 availableEnvFile = "soong.environment.available"
47 usedEnvFile = "soong.environment.used"
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +020048
Colin Cross8d411ff2023-12-07 10:31:24 -080049 soongBuildTag = "build"
50 jsonModuleGraphTag = "modulegraph"
51 queryviewTag = "queryview"
52 soongDocsTag = "soong_docs"
Colin Cross9191df22021-10-29 13:11:32 -070053
54 // bootstrapEpoch is used to determine if an incremental build is incompatible with the current
55 // version of bootstrap and needs cleaning before continuing the build. Increment this for
56 // incompatible changes, for example when moving the location of the bpglob binary that is
57 // executed during bootstrap before the primary builder has had a chance to update the path.
Lukacs T. Berki9985d9a2021-11-04 11:47:42 +010058 bootstrapEpoch = 1
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020059)
60
Kousik Kumarca390b22023-10-04 04:14:28 +000061var (
62 // Used during parallel update of symlinks in out directory to reflect new
63 // TOP dir.
64 symlinkWg sync.WaitGroup
65 numFound, numUpdated uint32
66)
67
Sasha Smundak4cbe83a2022-11-28 17:02:40 -080068func writeEnvironmentFile(_ Context, envFile string, envDeps map[string]string) error {
Lukacs T. Berki7690c092021-02-26 14:27:36 +010069 data, err := shared.EnvFileContents(envDeps)
70 if err != nil {
71 return err
72 }
73
Sasha Smundak4cbe83a2022-11-28 17:02:40 -080074 return os.WriteFile(envFile, data, 0644)
Lukacs T. Berki7690c092021-02-26 14:27:36 +010075}
76
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000077// This uses Android.bp files and various tools to generate <builddir>/build.ninja.
78//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010079// However, the execution of <builddir>/build.ninja happens later in
80// build/soong/ui/build/build.go#Build()
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000081//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010082// We want to rely on as few prebuilts as possible, so we need to bootstrap
83// Soong. The process is as follows:
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000084//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010085// 1. We use "Microfactory", a simple tool to compile Go code, to build
86// first itself, then soong_ui from soong_ui.bash. This binary contains
87// parts of soong_build that are needed to build itself.
88// 2. This simplified version of soong_build then reads the Blueprint files
89// that describe itself and emits .bootstrap/build.ninja that describes
90// how to build its full version and use that to produce the final Ninja
91// file Soong emits.
92// 3. soong_ui executes .bootstrap/build.ninja
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000093//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010094// (After this, Kati is executed to parse the Makefiles, but that's not part of
95// bootstrapping Soong)
96
97// A tiny struct used to tell Blueprint that it's in bootstrap mode. It would
98// probably be nicer to use a flag in bootstrap.Args instead.
99type BlueprintConfig struct {
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +0200100 toolDir string
101 soongOutDir string
102 outDir string
103 runGoTests bool
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +0200104 debugCompilation bool
105 subninjas []string
106 primaryBuilderInvocations []bootstrap.PrimaryBuilderInvocation
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100107}
108
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200109func (c BlueprintConfig) HostToolDir() string {
110 return c.toolDir
111}
112
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200113func (c BlueprintConfig) SoongOutDir() string {
114 return c.soongOutDir
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100115}
116
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200117func (c BlueprintConfig) OutDir() string {
118 return c.outDir
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100119}
120
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +0200121func (c BlueprintConfig) RunGoTests() bool {
122 return c.runGoTests
123}
124
Lukacs T. Berki5f6cb1d2021-03-17 15:03:14 +0100125func (c BlueprintConfig) DebugCompilation() bool {
126 return c.debugCompilation
127}
128
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +0200129func (c BlueprintConfig) Subninjas() []string {
130 return c.subninjas
131}
132
133func (c BlueprintConfig) PrimaryBuilderInvocations() []bootstrap.PrimaryBuilderInvocation {
134 return c.primaryBuilderInvocations
135}
136
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200137func environmentArgs(config Config, tag string) []string {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200138 return []string{
139 "--available_env", shared.JoinPath(config.SoongOutDir(), availableEnvFile),
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200140 "--used_env", config.UsedEnvFile(tag),
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200141 }
142}
Spandan Das8f99ae62021-06-11 16:48:06 +0000143
Colin Cross9191df22021-10-29 13:11:32 -0700144func writeEmptyFile(ctx Context, path string) {
Spandan Das8f99ae62021-06-11 16:48:06 +0000145 err := os.MkdirAll(filepath.Dir(path), 0777)
146 if err != nil {
Colin Cross9191df22021-10-29 13:11:32 -0700147 ctx.Fatalf("Failed to create parent directories of empty file '%s': %s", path, err)
Spandan Das8f99ae62021-06-11 16:48:06 +0000148 }
149
Colin Cross9191df22021-10-29 13:11:32 -0700150 if exists, err := fileExists(path); err != nil {
151 ctx.Fatalf("Failed to check if file '%s' exists: %s", path, err)
152 } else if !exists {
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800153 err = os.WriteFile(path, nil, 0666)
Spandan Das8f99ae62021-06-11 16:48:06 +0000154 if err != nil {
Colin Cross9191df22021-10-29 13:11:32 -0700155 ctx.Fatalf("Failed to create empty file '%s': %s", path, err)
Spandan Das8f99ae62021-06-11 16:48:06 +0000156 }
157 }
158}
159
Colin Cross9191df22021-10-29 13:11:32 -0700160func fileExists(path string) (bool, error) {
161 if _, err := os.Stat(path); os.IsNotExist(err) {
162 return false, nil
163 } else if err != nil {
164 return false, err
165 }
166 return true, nil
167}
168
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800169type PrimaryBuilderFactory struct {
170 name string
171 description string
172 config Config
173 output string
174 specificArgs []string
175 debugPort string
176}
177
Jeongik Chaccf37002023-08-04 01:46:32 +0900178func getGlobPathName(config Config) string {
179 globPathName, ok := config.TargetProductOrErr()
180 if ok != nil {
181 globPathName = soongBuildTag
182 }
183 return globPathName
184}
185
Cole Faust8c0b11e2024-01-02 17:02:52 -0800186func getGlobPathNameFromPrimaryBuilderFactory(config Config, pb PrimaryBuilderFactory) string {
187 if pb.name == soongBuildTag {
188 // Glob path for soong build would be separated per product target
189 return getGlobPathName(config)
190 }
191 return pb.name
192}
193
194func (pb PrimaryBuilderFactory) primaryBuilderInvocation(config Config) bootstrap.PrimaryBuilderInvocation {
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200195 commonArgs := make([]string, 0, 0)
196
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800197 if !pb.config.skipSoongTests {
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200198 commonArgs = append(commonArgs, "-t")
199 }
200
Jihoon Kang2a929ad2023-06-08 19:02:07 +0000201 if pb.config.buildFromSourceStub {
202 commonArgs = append(commonArgs, "--build-from-source-stub")
Jihoon Kang1bff0342023-01-17 20:40:22 +0000203 }
LaMont Jones52a72432023-03-09 18:19:35 +0000204
Joe Onoratoe5ed3472024-02-02 14:52:05 -0800205 if pb.config.moduleDebugFile != "" {
206 commonArgs = append(commonArgs, "--soong_module_debug")
207 commonArgs = append(commonArgs, pb.config.moduleDebugFile)
208 }
209
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800210 commonArgs = append(commonArgs, "-l", filepath.Join(pb.config.FileListDir(), "Android.bp.list"))
Lukacs T. Berki13644272022-01-05 10:29:56 +0100211 invocationEnv := make(map[string]string)
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800212 if pb.debugPort != "" {
ustafb67fd12022-08-19 19:26:00 -0400213 //debug mode
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800214 commonArgs = append(commonArgs, "--delve_listen", pb.debugPort,
215 "--delve_path", shared.ResolveDelveBinary())
Lukacs T. Berki13644272022-01-05 10:29:56 +0100216 // GODEBUG=asyncpreemptoff=1 disables the preemption of goroutines. This
217 // is useful because the preemption happens by sending SIGURG to the OS
218 // thread hosting the goroutine in question and each signal results in
219 // work that needs to be done by Delve; it uses ptrace to debug the Go
220 // process and the tracer process must deal with every signal (it is not
221 // possible to selectively ignore SIGURG). This makes debugging slower,
222 // sometimes by an order of magnitude depending on luck.
223 // The original reason for adding async preemption to Go is here:
224 // https://github.com/golang/proposal/blob/master/design/24543-non-cooperative-preemption.md
225 invocationEnv["GODEBUG"] = "asyncpreemptoff=1"
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200226 }
227
ustafb67fd12022-08-19 19:26:00 -0400228 var allArgs []string
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800229 allArgs = append(allArgs, pb.specificArgs...)
Cole Faust8c0b11e2024-01-02 17:02:52 -0800230 globPathName := getGlobPathNameFromPrimaryBuilderFactory(config, pb)
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200231 allArgs = append(allArgs,
Jeongik Chaccf37002023-08-04 01:46:32 +0900232 "--globListDir", globPathName,
233 "--globFile", pb.config.NamedGlobFile(globPathName))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200234
235 allArgs = append(allArgs, commonArgs...)
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800236 allArgs = append(allArgs, environmentArgs(pb.config, pb.name)...)
Sasha Smundakfaa97b72022-11-18 15:32:49 -0800237 if profileCpu := os.Getenv("SOONG_PROFILE_CPU"); profileCpu != "" {
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800238 allArgs = append(allArgs, "--cpuprofile", profileCpu+"."+pb.name)
Sasha Smundakfaa97b72022-11-18 15:32:49 -0800239 }
240 if profileMem := os.Getenv("SOONG_PROFILE_MEM"); profileMem != "" {
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800241 allArgs = append(allArgs, "--memprofile", profileMem+"."+pb.name)
Sasha Smundakfaa97b72022-11-18 15:32:49 -0800242 }
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200243 allArgs = append(allArgs, "Android.bp")
244
Cole Faust8c0b11e2024-01-02 17:02:52 -0800245 globfiles := bootstrap.GlobFileListFiles(bootstrap.GlobDirectory(config.SoongOutDir(), globPathName))
246
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200247 return bootstrap.PrimaryBuilderInvocation{
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000248 Inputs: []string{"Android.bp"},
Cole Faust8c0b11e2024-01-02 17:02:52 -0800249 Implicits: globfiles,
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800250 Outputs: []string{pb.output},
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000251 Args: allArgs,
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800252 Description: pb.description,
Lukacs T. Berki2fad3412022-01-04 14:40:13 +0100253 // NB: Changing the value of this environment variable will not result in a
254 // rebuild. The bootstrap Ninja file will change, but apparently Ninja does
255 // not consider changing the pool specified in a statement a change that's
256 // worth rebuilding for.
257 Console: os.Getenv("SOONG_UNBUFFERED_OUTPUT") == "1",
Lukacs T. Berki13644272022-01-05 10:29:56 +0100258 Env: invocationEnv,
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200259 }
260}
261
Colin Cross9191df22021-10-29 13:11:32 -0700262// bootstrapEpochCleanup deletes files used by bootstrap during incremental builds across
263// incompatible changes. Incompatible changes are marked by incrementing the bootstrapEpoch
264// constant. A tree is considered out of date for the current epoch of the
265// .soong.bootstrap.epoch.<epoch> file doesn't exist.
266func bootstrapEpochCleanup(ctx Context, config Config) {
267 epochFile := fmt.Sprintf(".soong.bootstrap.epoch.%d", bootstrapEpoch)
268 epochPath := filepath.Join(config.SoongOutDir(), epochFile)
269 if exists, err := fileExists(epochPath); err != nil {
270 ctx.Fatalf("failed to check if bootstrap epoch file %q exists: %q", epochPath, err)
271 } else if !exists {
272 // The tree is out of date for the current epoch, delete files used by bootstrap
273 // and force the primary builder to rerun.
Yu Liu1b2ddc82024-05-15 19:28:56 +0000274 soongNinjaFile := config.SoongNinjaFile()
275 os.Remove(soongNinjaFile)
276 for _, file := range blueprint.GetNinjaShardFiles(soongNinjaFile) {
277 if ok, _ := fileExists(file); ok {
278 os.Remove(file)
279 }
280 }
Colin Cross9191df22021-10-29 13:11:32 -0700281 for _, globFile := range bootstrapGlobFileList(config) {
282 os.Remove(globFile)
283 }
284
285 // Mark the tree as up to date with the current epoch by writing the epoch marker file.
286 writeEmptyFile(ctx, epochPath)
287 }
288}
289
290func bootstrapGlobFileList(config Config) []string {
291 return []string{
Jeongik Chaccf37002023-08-04 01:46:32 +0900292 config.NamedGlobFile(getGlobPathName(config)),
Colin Cross9191df22021-10-29 13:11:32 -0700293 config.NamedGlobFile(jsonModuleGraphTag),
294 config.NamedGlobFile(queryviewTag),
295 config.NamedGlobFile(soongDocsTag),
296 }
297}
298
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200299func bootstrapBlueprint(ctx Context, config Config) {
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100300 ctx.BeginTrace(metrics.RunSoong, "blueprint bootstrap")
301 defer ctx.EndTrace()
302
Colin Cross9191df22021-10-29 13:11:32 -0700303 // Clean up some files for incremental builds across incompatible changes.
304 bootstrapEpochCleanup(ctx, config)
305
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900306 baseArgs := []string{"--soong_variables", config.SoongVarsFile()}
307
308 mainSoongBuildExtraArgs := append(baseArgs, "-o", config.SoongNinjaFile())
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200309 if config.EmptyNinjaFile() {
310 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--empty-ninja-file")
Lukacs T. Berki745380c2021-04-12 12:07:44 +0200311 }
Jihoon Kang2a929ad2023-06-08 19:02:07 +0000312 if config.buildFromSourceStub {
313 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--build-from-source-stub")
Jihoon Kang1bff0342023-01-17 20:40:22 +0000314 }
MarkDacekf47e1422023-04-19 16:47:36 +0000315 if config.ensureAllowlistIntegrity {
316 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--ensure-allowlist-integrity")
317 }
Yu Liufa297642024-06-11 00:13:02 +0000318 if config.incrementalBuildActions {
319 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--incremental-build-actions")
320 }
MarkDacekd06db5d2022-11-29 00:47:59 +0000321
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000322 queryviewDir := filepath.Join(config.SoongOutDir(), "queryview")
Spandan Das5af0bd32022-09-28 20:43:08 +0000323
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800324 pbfs := []PrimaryBuilderFactory{
325 {
326 name: soongBuildTag,
327 description: fmt.Sprintf("analyzing Android.bp files and generating ninja file at %s", config.SoongNinjaFile()),
328 config: config,
329 output: config.SoongNinjaFile(),
330 specificArgs: mainSoongBuildExtraArgs,
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000331 },
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800332 {
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800333 name: jsonModuleGraphTag,
334 description: fmt.Sprintf("generating the Soong module graph at %s", config.ModuleGraphFile()),
335 config: config,
336 output: config.ModuleGraphFile(),
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900337 specificArgs: append(baseArgs,
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800338 "--module_graph_file", config.ModuleGraphFile(),
339 "--module_actions_file", config.ModuleActionsFile(),
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900340 ),
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800341 },
342 {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900343 name: queryviewTag,
344 description: fmt.Sprintf("generating the Soong module graph as a Bazel workspace at %s", queryviewDir),
345 config: config,
346 output: config.QueryviewMarkerFile(),
347 specificArgs: append(baseArgs,
348 "--bazel_queryview_dir", queryviewDir,
349 ),
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800350 },
351 {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900352 name: soongDocsTag,
353 description: fmt.Sprintf("generating Soong docs at %s", config.SoongDocsHtml()),
354 config: config,
355 output: config.SoongDocsHtml(),
356 specificArgs: append(baseArgs,
357 "--soong_docs", config.SoongDocsHtml(),
358 ),
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800359 },
360 }
361
362 // Figure out which invocations will be run under the debugger:
363 // * SOONG_DELVE if set specifies listening port
364 // * SOONG_DELVE_STEPS if set specifies specific invocations to be debugged, otherwise all are
365 debuggedInvocations := make(map[string]bool)
366 delvePort := os.Getenv("SOONG_DELVE")
367 if delvePort != "" {
368 if steps := os.Getenv("SOONG_DELVE_STEPS"); steps != "" {
369 var validSteps []string
370 for _, pbf := range pbfs {
371 debuggedInvocations[pbf.name] = false
372 validSteps = append(validSteps, pbf.name)
373
374 }
375 for _, step := range strings.Split(steps, ",") {
376 if _, ok := debuggedInvocations[step]; ok {
377 debuggedInvocations[step] = true
378 } else {
379 ctx.Fatalf("SOONG_DELVE_STEPS contains unknown soong_build step %s\n"+
380 "Valid steps are %v", step, validSteps)
381 }
382 }
383 } else {
384 // SOONG_DELVE_STEPS is not set, run all steps in the debugger
385 for _, pbf := range pbfs {
386 debuggedInvocations[pbf.name] = true
387 }
388 }
389 }
390
391 var invocations []bootstrap.PrimaryBuilderInvocation
392 for _, pbf := range pbfs {
393 if debuggedInvocations[pbf.name] {
394 pbf.debugPort = delvePort
395 }
Cole Faust8c0b11e2024-01-02 17:02:52 -0800396 pbi := pbf.primaryBuilderInvocation(config)
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800397 invocations = append(invocations, pbi)
398 }
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200399
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800400 blueprintArgs := bootstrap.Args{
401 ModuleListFile: filepath.Join(config.FileListDir(), "Android.bp.list"),
402 OutFile: shared.JoinPath(config.SoongOutDir(), "bootstrap.ninja"),
403 EmptyNinjaFile: false,
404 }
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200405
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100406 blueprintCtx := blueprint.NewContext()
Sam Delmerico98a73292023-02-21 11:50:29 -0500407 blueprintCtx.AddSourceRootDirs(config.GetSourceRootDirs()...)
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100408 blueprintCtx.SetIgnoreUnknownModuleTypes(true)
409 blueprintConfig := BlueprintConfig{
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200410 soongOutDir: config.SoongOutDir(),
411 toolDir: config.HostToolDir(),
412 outDir: config.OutDir(),
413 runGoTests: !config.skipSoongTests,
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200414 // If we want to debug soong_build, we need to compile it for debugging
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800415 debugCompilation: delvePort != "",
416 subninjas: bootstrapGlobFileList(config),
417 primaryBuilderInvocations: invocations,
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100418 }
419
Cole Faust8c0b11e2024-01-02 17:02:52 -0800420 // The glob ninja files are generated during the main build phase. However, the
421 // primary buildifer invocation depends on all of its glob files, even before
422 // it's been run. Generate a "empty" glob ninja file on the first run,
423 // so that the files can be there to satisfy the dependency.
424 for _, pb := range pbfs {
425 globPathName := getGlobPathNameFromPrimaryBuilderFactory(config, pb)
426 globNinjaFile := config.NamedGlobFile(globPathName)
427 if _, err := os.Stat(globNinjaFile); os.IsNotExist(err) {
428 err := bootstrap.WriteBuildGlobsNinjaFile(&bootstrap.GlobSingleton{
429 GlobLister: func() pathtools.MultipleGlobResults { return nil },
430 GlobFile: globNinjaFile,
431 GlobDir: bootstrap.GlobDirectory(config.SoongOutDir(), globPathName),
432 SrcDir: ".",
433 }, blueprintConfig)
434 if err != nil {
435 ctx.Fatal(err)
436 }
437 } else if err != nil {
438 ctx.Fatal(err)
439 }
440 }
441
usta5bb4a5d2022-08-24 12:53:46 -0400442 // since `bootstrap.ninja` is regenerated unconditionally, we ignore the deps, i.e. little
443 // reason to write a `bootstrap.ninja.d` file
Lukacs T. Berkic357c812023-06-20 09:30:06 +0000444 _, err := bootstrap.RunBlueprint(blueprintArgs, bootstrap.DoEverything, blueprintCtx, blueprintConfig)
445 if err != nil {
446 ctx.Fatal(err)
447 }
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100448}
449
Jason Wu2520f5e2023-05-30 19:45:36 -0400450func checkEnvironmentFile(ctx Context, currentEnv *Environment, envFile string) {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200451 getenv := func(k string) string {
452 v, _ := currentEnv.Get(k)
453 return v
454 }
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200455
Jason Wu2520f5e2023-05-30 19:45:36 -0400456 // Log the changed environment variables to ChangedEnvironmentVariable field
457 if stale, changedEnvironmentVariableList, _ := shared.StaleEnvFile(envFile, getenv); stale {
458 for _, changedEnvironmentVariable := range changedEnvironmentVariableList {
459 ctx.Metrics.AddChangedEnvironmentVariable(changedEnvironmentVariable)
460 }
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200461 os.Remove(envFile)
462 }
463}
464
Kousik Kumarca390b22023-10-04 04:14:28 +0000465func updateSymlinks(ctx Context, dir, prevCWD, cwd string) error {
466 defer symlinkWg.Done()
467
468 visit := func(path string, d fs.DirEntry, err error) error {
469 if d.IsDir() && path != dir {
470 symlinkWg.Add(1)
471 go updateSymlinks(ctx, path, prevCWD, cwd)
472 return filepath.SkipDir
473 }
474 f, err := d.Info()
475 if err != nil {
476 return err
477 }
478 // If the file is not a symlink, we don't have to update it.
479 if f.Mode()&os.ModeSymlink != os.ModeSymlink {
480 return nil
481 }
482
483 atomic.AddUint32(&numFound, 1)
484 target, err := os.Readlink(path)
485 if err != nil {
486 return err
487 }
488 if strings.HasPrefix(target, prevCWD) &&
489 (len(target) == len(prevCWD) || target[len(prevCWD)] == '/') {
490 target = filepath.Join(cwd, target[len(prevCWD):])
491 if err := os.Remove(path); err != nil {
492 return err
493 }
494 if err := os.Symlink(target, path); err != nil {
495 return err
496 }
497 atomic.AddUint32(&numUpdated, 1)
498 }
499 return nil
500 }
501
502 if err := filepath.WalkDir(dir, visit); err != nil {
503 return err
504 }
505 return nil
506}
507
508func fixOutDirSymlinks(ctx Context, config Config, outDir string) error {
509 cwd, err := os.Getwd()
510 if err != nil {
511 return err
512 }
513
514 // Record the .top as the very last thing in the function.
515 tf := filepath.Join(outDir, ".top")
516 defer func() {
517 if err := os.WriteFile(tf, []byte(cwd), 0644); err != nil {
518 fmt.Fprintf(os.Stderr, fmt.Sprintf("Unable to log CWD: %v", err))
519 }
520 }()
521
522 // Find the previous working directory if it was recorded.
523 var prevCWD string
524 pcwd, err := os.ReadFile(tf)
525 if err != nil {
526 if os.IsNotExist(err) {
527 // No previous working directory recorded, nothing to do.
528 return nil
529 }
530 return err
531 }
532 prevCWD = strings.Trim(string(pcwd), "\n")
533
534 if prevCWD == cwd {
535 // We are in the same source dir, nothing to update.
536 return nil
537 }
538
539 symlinkWg.Add(1)
540 if err := updateSymlinks(ctx, outDir, prevCWD, cwd); err != nil {
541 return err
542 }
543 symlinkWg.Wait()
544 ctx.Println(fmt.Sprintf("Updated %d/%d symlinks in dir %v", numUpdated, numFound, outDir))
545 return nil
546}
547
548func migrateOutputSymlinks(ctx Context, config Config) error {
549 // Figure out the real out directory ("out" could be a symlink).
550 outDir := config.OutDir()
551 s, err := os.Lstat(outDir)
552 if err != nil {
553 if os.IsNotExist(err) {
554 // No out dir exists, no symlinks to migrate.
555 return nil
556 }
557 return err
558 }
559 if s.Mode()&os.ModeSymlink == os.ModeSymlink {
560 target, err := filepath.EvalSymlinks(outDir)
561 if err != nil {
562 return err
563 }
564 outDir = target
565 }
566 return fixOutDirSymlinks(ctx, config, outDir)
567}
568
Dan Willemsen1e704462016-08-21 15:17:17 -0700569func runSoong(ctx Context, config Config) {
Nan Zhang17f27672018-12-12 16:01:49 -0800570 ctx.BeginTrace(metrics.RunSoong, "soong")
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700571 defer ctx.EndTrace()
572
Kousik Kumarca390b22023-10-04 04:14:28 +0000573 if err := migrateOutputSymlinks(ctx, config); err != nil {
574 ctx.Fatalf("failed to migrate output directory to current TOP dir: %v", err)
575 }
576
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100577 // We have two environment files: .available is the one with every variable,
578 // .used with the ones that were actually used. The latter is used to
579 // determine whether Soong needs to be re-run since why re-run it if only
580 // unused variables were changed?
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200581 envFile := filepath.Join(config.SoongOutDir(), availableEnvFile)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100582
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100583 // This is done unconditionally, but does not take a measurable amount of time
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200584 bootstrapBlueprint(ctx, config)
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700585
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100586 soongBuildEnv := config.Environment().Copy()
587 soongBuildEnv.Set("TOP", os.Getenv("TOP"))
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500588 soongBuildEnv.Set("LOG_DIR", config.LogsDir())
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100589
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100590 // For Soong bootstrapping tests
591 if os.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
592 soongBuildEnv.Set("ALLOW_MISSING_DEPENDENCIES", "true")
593 }
594
Paul Duffin5e85c662021-03-05 12:26:14 +0000595 err := writeEnvironmentFile(ctx, envFile, soongBuildEnv.AsMap())
596 if err != nil {
597 ctx.Fatalf("failed to write environment file %s: %s", envFile, err)
598 }
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100599
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700600 func() {
Nan Zhang17f27672018-12-12 16:01:49 -0800601 ctx.BeginTrace(metrics.RunSoong, "environment check")
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700602 defer ctx.EndTrace()
603
Jason Wu2520f5e2023-05-30 19:45:36 -0400604 checkEnvironmentFile(ctx, soongBuildEnv, config.UsedEnvFile(soongBuildTag))
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200605
Colin Cross8d411ff2023-12-07 10:31:24 -0800606 // Remove bazel files in the event that bazel is disabled for the build.
607 // These files may have been left over from a previous bazel-enabled build.
608 cleanBazelFiles(config)
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200609
610 if config.JsonModuleGraph() {
Jason Wu2520f5e2023-05-30 19:45:36 -0400611 checkEnvironmentFile(ctx, soongBuildEnv, config.UsedEnvFile(jsonModuleGraphTag))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200612 }
613
614 if config.Queryview() {
Jason Wu2520f5e2023-05-30 19:45:36 -0400615 checkEnvironmentFile(ctx, soongBuildEnv, config.UsedEnvFile(queryviewTag))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200616 }
617
618 if config.SoongDocs() {
Jason Wu2520f5e2023-05-30 19:45:36 -0400619 checkEnvironmentFile(ctx, soongBuildEnv, config.UsedEnvFile(soongDocsTag))
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700620 }
621 }()
622
Colin Cross9191df22021-10-29 13:11:32 -0700623 runMicrofactory(ctx, config, "bpglob", "github.com/google/blueprint/bootstrap/bpglob",
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700624 map[string]string{"github.com/google/blueprint": "build/blueprint"})
Dan Willemsen5af1cbe2018-07-05 21:46:51 -0700625
usta49012ee2023-05-22 16:33:27 -0400626 ninja := func(targets ...string) {
627 ctx.BeginTrace(metrics.RunSoong, "bootstrap")
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700628 defer ctx.EndTrace()
629
Dan Willemsenb82471a2018-05-17 16:37:09 -0700630 fifo := filepath.Join(config.OutDir(), ".ninja_fifo")
Colin Crossb98d3bc2019-03-21 16:02:58 -0700631 nr := status.NewNinjaReader(ctx, ctx.Status.StartTool(), fifo)
632 defer nr.Close()
Dan Willemsenb82471a2018-05-17 16:37:09 -0700633
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200634 ninjaArgs := []string{
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700635 "-d", "keepdepfile",
Dan Willemsen08218222020-05-18 14:02:02 -0700636 "-d", "stats",
Dan Willemsen6587bed2020-04-18 20:25:59 -0700637 "-o", "usesphonyoutputs=yes",
638 "-o", "preremoveoutputs=yes",
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700639 "-w", "dupbuild=err",
Dan Willemsen6587bed2020-04-18 20:25:59 -0700640 "-w", "outputdir=err",
641 "-w", "missingoutfile=err",
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700642 "-j", strconv.Itoa(config.Parallel()),
Dan Willemsen02736672018-07-17 17:54:31 -0700643 "--frontend_file", fifo,
usta49012ee2023-05-22 16:33:27 -0400644 "-f", filepath.Join(config.SoongOutDir(), "bootstrap.ninja"),
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200645 }
646
Usta Shrestha8dc8b0a2022-08-10 17:39:37 -0400647 if extra, ok := config.Environment().Get("SOONG_UI_NINJA_ARGS"); ok {
648 ctx.Printf(`CAUTION: arguments in $SOONG_UI_NINJA_ARGS=%q, e.g. "-n", can make soong_build FAIL or INCORRECT`, extra)
649 ninjaArgs = append(ninjaArgs, strings.Fields(extra)...)
650 }
651
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200652 ninjaArgs = append(ninjaArgs, targets...)
usta49012ee2023-05-22 16:33:27 -0400653 cmd := Command(ctx, config, "soong bootstrap",
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200654 config.PrebuiltBuildTool("ninja"), ninjaArgs...)
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500655
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100656 var ninjaEnv Environment
Lukacs T. Berki73ab9282021-03-10 10:48:39 +0100657
658 // This is currently how the command line to invoke soong_build finds the
659 // root of the source tree and the output root
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100660 ninjaEnv.Set("TOP", os.Getenv("TOP"))
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100661
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100662 cmd.Environment = &ninjaEnv
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700663 cmd.Sandbox = soongSandbox
Colin Cross7b97ecd2019-06-19 13:17:59 -0700664 cmd.RunAndStreamOrFatal()
Dan Willemsen1e704462016-08-21 15:17:17 -0700665 }
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200666
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200667 targets := make([]string, 0, 0)
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200668
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200669 if config.JsonModuleGraph() {
670 targets = append(targets, config.ModuleGraphFile())
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200671 }
672
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200673 if config.Queryview() {
674 targets = append(targets, config.QueryviewMarkerFile())
675 }
676
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200677 if config.SoongDocs() {
678 targets = append(targets, config.SoongDocsHtml())
679 }
680
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200681 if config.SoongBuildInvocationNeeded() {
682 // 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 -0700683 targets = append(targets, config.SoongNinjaFile())
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200684 }
685
Colin Crossaa9a2732023-10-27 10:54:27 -0700686 beforeSoongTimestamp := time.Now()
687
usta49012ee2023-05-22 16:33:27 -0400688 ninja(targets...)
Colin Crossb72c9092020-02-10 11:23:49 -0800689
Colin Crossaa9a2732023-10-27 10:54:27 -0700690 loadSoongBuildMetrics(ctx, config, beforeSoongTimestamp)
691
Yu Liu1b2ddc82024-05-15 19:28:56 +0000692 soongNinjaFile := config.SoongNinjaFile()
693 distGzipFile(ctx, config, soongNinjaFile, "soong")
694 for _, file := range blueprint.GetNinjaShardFiles(soongNinjaFile) {
695 if ok, _ := fileExists(file); ok {
696 distGzipFile(ctx, config, file, "soong")
697 }
698 }
Jihoon Kang9f4f8a32022-08-16 00:57:30 +0000699 distFile(ctx, config, config.SoongVarsFile(), "soong")
Colin Cross8ba7d472020-06-25 11:27:52 -0700700
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000701 if !config.SkipKati() {
Colin Cross8ba7d472020-06-25 11:27:52 -0700702 distGzipFile(ctx, config, config.SoongAndroidMk(), "soong")
703 distGzipFile(ctx, config, config.SoongMakeVarsMk(), "soong")
704 }
705
Rob Seymour33cd10d2022-03-02 23:10:25 +0000706 if config.JsonModuleGraph() {
707 distGzipFile(ctx, config, config.ModuleGraphFile(), "soong")
708 }
Colin Crossb72c9092020-02-10 11:23:49 -0800709}
710
Colin Crossaa9a2732023-10-27 10:54:27 -0700711// loadSoongBuildMetrics reads out/soong_build_metrics.pb if it was generated by soong_build and copies the
712// events stored in it into the soong_ui trace to provide introspection into how long the different phases of
713// soong_build are taking.
714func loadSoongBuildMetrics(ctx Context, config Config, oldTimestamp time.Time) {
715 soongBuildMetricsFile := config.SoongBuildMetrics()
716 if metricsStat, err := os.Stat(soongBuildMetricsFile); err != nil {
717 ctx.Verbosef("Failed to stat %s: %s", soongBuildMetricsFile, err)
718 return
719 } else if !metricsStat.ModTime().After(oldTimestamp) {
720 ctx.Verbosef("%s timestamp not later after running soong, expected %s > %s",
721 soongBuildMetricsFile, metricsStat.ModTime(), oldTimestamp)
722 return
723 }
724
Colin Crossb67b0612023-10-31 10:02:45 -0700725 metricsData, err := os.ReadFile(soongBuildMetricsFile)
Colin Crossaa9a2732023-10-27 10:54:27 -0700726 if err != nil {
727 ctx.Verbosef("Failed to read %s: %s", soongBuildMetricsFile, err)
728 return
729 }
730
731 soongBuildMetrics := metrics_proto.SoongBuildMetrics{}
732 err = proto.Unmarshal(metricsData, &soongBuildMetrics)
733 if err != nil {
734 ctx.Verbosef("Failed to unmarshal %s: %s", soongBuildMetricsFile, err)
735 return
736 }
737 for _, event := range soongBuildMetrics.Events {
738 desc := event.GetDescription()
739 if dot := strings.LastIndexByte(desc, '.'); dot >= 0 {
740 desc = desc[dot+1:]
741 }
742 ctx.Tracer.Complete(desc, ctx.Thread,
743 event.GetStartTime(), event.GetStartTime()+event.GetRealTime())
744 }
Colin Cross46b0c752023-10-27 14:56:12 -0700745 for _, event := range soongBuildMetrics.PerfCounters {
746 timestamp := event.GetTime()
747 for _, group := range event.Groups {
748 counters := make([]tracer.Counter, 0, len(group.Counters))
749 for _, counter := range group.Counters {
750 counters = append(counters, tracer.Counter{
751 Name: counter.GetName(),
752 Value: counter.GetValue(),
753 })
754 }
755 ctx.Tracer.CountersAtTime(group.GetName(), ctx.Thread, timestamp, counters)
756 }
757 }
Colin Crossaa9a2732023-10-27 10:54:27 -0700758}
759
Chris Parsonsb6d6fc92023-10-30 16:21:06 +0000760func cleanBazelFiles(config Config) {
761 files := []string{
762 shared.JoinPath(config.SoongOutDir(), "bp2build"),
763 shared.JoinPath(config.SoongOutDir(), "workspace"),
764 shared.JoinPath(config.SoongOutDir(), bazel.SoongInjectionDirName),
765 shared.JoinPath(config.OutDir(), "bazel")}
766
767 for _, f := range files {
768 os.RemoveAll(f)
769 }
770}
771
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100772func runMicrofactory(ctx Context, config Config, name string, pkg string, mapping map[string]string) {
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700773 ctx.BeginTrace(metrics.RunSoong, name)
774 defer ctx.EndTrace()
775 cfg := microfactory.Config{TrimPath: absPath(ctx, ".")}
776 for pkgPrefix, pathPrefix := range mapping {
777 cfg.Map(pkgPrefix, pathPrefix)
778 }
779
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100780 exePath := filepath.Join(config.SoongOutDir(), name)
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700781 dir := filepath.Dir(exePath)
782 if err := os.MkdirAll(dir, 0777); err != nil {
783 ctx.Fatalf("cannot create %s: %s", dir, err)
784 }
785 if _, err := microfactory.Build(&cfg, exePath, pkg); err != nil {
786 ctx.Fatalf("failed to build %s: %s", name, err)
787 }
788}