blob: 99474d99d2766b516c1f190008c1412b872a20ea [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 }
MarkDacekd06db5d2022-11-29 00:47:59 +0000318
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000319 queryviewDir := filepath.Join(config.SoongOutDir(), "queryview")
Spandan Das5af0bd32022-09-28 20:43:08 +0000320
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800321 pbfs := []PrimaryBuilderFactory{
322 {
323 name: soongBuildTag,
324 description: fmt.Sprintf("analyzing Android.bp files and generating ninja file at %s", config.SoongNinjaFile()),
325 config: config,
326 output: config.SoongNinjaFile(),
327 specificArgs: mainSoongBuildExtraArgs,
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000328 },
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800329 {
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800330 name: jsonModuleGraphTag,
331 description: fmt.Sprintf("generating the Soong module graph at %s", config.ModuleGraphFile()),
332 config: config,
333 output: config.ModuleGraphFile(),
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900334 specificArgs: append(baseArgs,
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800335 "--module_graph_file", config.ModuleGraphFile(),
336 "--module_actions_file", config.ModuleActionsFile(),
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900337 ),
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800338 },
339 {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900340 name: queryviewTag,
341 description: fmt.Sprintf("generating the Soong module graph as a Bazel workspace at %s", queryviewDir),
342 config: config,
343 output: config.QueryviewMarkerFile(),
344 specificArgs: append(baseArgs,
345 "--bazel_queryview_dir", queryviewDir,
346 ),
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800347 },
348 {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900349 name: soongDocsTag,
350 description: fmt.Sprintf("generating Soong docs at %s", config.SoongDocsHtml()),
351 config: config,
352 output: config.SoongDocsHtml(),
353 specificArgs: append(baseArgs,
354 "--soong_docs", config.SoongDocsHtml(),
355 ),
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800356 },
357 }
358
359 // Figure out which invocations will be run under the debugger:
360 // * SOONG_DELVE if set specifies listening port
361 // * SOONG_DELVE_STEPS if set specifies specific invocations to be debugged, otherwise all are
362 debuggedInvocations := make(map[string]bool)
363 delvePort := os.Getenv("SOONG_DELVE")
364 if delvePort != "" {
365 if steps := os.Getenv("SOONG_DELVE_STEPS"); steps != "" {
366 var validSteps []string
367 for _, pbf := range pbfs {
368 debuggedInvocations[pbf.name] = false
369 validSteps = append(validSteps, pbf.name)
370
371 }
372 for _, step := range strings.Split(steps, ",") {
373 if _, ok := debuggedInvocations[step]; ok {
374 debuggedInvocations[step] = true
375 } else {
376 ctx.Fatalf("SOONG_DELVE_STEPS contains unknown soong_build step %s\n"+
377 "Valid steps are %v", step, validSteps)
378 }
379 }
380 } else {
381 // SOONG_DELVE_STEPS is not set, run all steps in the debugger
382 for _, pbf := range pbfs {
383 debuggedInvocations[pbf.name] = true
384 }
385 }
386 }
387
388 var invocations []bootstrap.PrimaryBuilderInvocation
389 for _, pbf := range pbfs {
390 if debuggedInvocations[pbf.name] {
391 pbf.debugPort = delvePort
392 }
Cole Faust8c0b11e2024-01-02 17:02:52 -0800393 pbi := pbf.primaryBuilderInvocation(config)
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800394 invocations = append(invocations, pbi)
395 }
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200396
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800397 blueprintArgs := bootstrap.Args{
398 ModuleListFile: filepath.Join(config.FileListDir(), "Android.bp.list"),
399 OutFile: shared.JoinPath(config.SoongOutDir(), "bootstrap.ninja"),
400 EmptyNinjaFile: false,
401 }
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200402
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100403 blueprintCtx := blueprint.NewContext()
Sam Delmerico98a73292023-02-21 11:50:29 -0500404 blueprintCtx.AddSourceRootDirs(config.GetSourceRootDirs()...)
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100405 blueprintCtx.SetIgnoreUnknownModuleTypes(true)
406 blueprintConfig := BlueprintConfig{
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200407 soongOutDir: config.SoongOutDir(),
408 toolDir: config.HostToolDir(),
409 outDir: config.OutDir(),
410 runGoTests: !config.skipSoongTests,
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200411 // If we want to debug soong_build, we need to compile it for debugging
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800412 debugCompilation: delvePort != "",
413 subninjas: bootstrapGlobFileList(config),
414 primaryBuilderInvocations: invocations,
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100415 }
416
Cole Faust8c0b11e2024-01-02 17:02:52 -0800417 // The glob ninja files are generated during the main build phase. However, the
418 // primary buildifer invocation depends on all of its glob files, even before
419 // it's been run. Generate a "empty" glob ninja file on the first run,
420 // so that the files can be there to satisfy the dependency.
421 for _, pb := range pbfs {
422 globPathName := getGlobPathNameFromPrimaryBuilderFactory(config, pb)
423 globNinjaFile := config.NamedGlobFile(globPathName)
424 if _, err := os.Stat(globNinjaFile); os.IsNotExist(err) {
425 err := bootstrap.WriteBuildGlobsNinjaFile(&bootstrap.GlobSingleton{
426 GlobLister: func() pathtools.MultipleGlobResults { return nil },
427 GlobFile: globNinjaFile,
428 GlobDir: bootstrap.GlobDirectory(config.SoongOutDir(), globPathName),
429 SrcDir: ".",
430 }, blueprintConfig)
431 if err != nil {
432 ctx.Fatal(err)
433 }
434 } else if err != nil {
435 ctx.Fatal(err)
436 }
437 }
438
usta5bb4a5d2022-08-24 12:53:46 -0400439 // since `bootstrap.ninja` is regenerated unconditionally, we ignore the deps, i.e. little
440 // reason to write a `bootstrap.ninja.d` file
Lukacs T. Berkic357c812023-06-20 09:30:06 +0000441 _, err := bootstrap.RunBlueprint(blueprintArgs, bootstrap.DoEverything, blueprintCtx, blueprintConfig)
442 if err != nil {
443 ctx.Fatal(err)
444 }
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100445}
446
Jason Wu2520f5e2023-05-30 19:45:36 -0400447func checkEnvironmentFile(ctx Context, currentEnv *Environment, envFile string) {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200448 getenv := func(k string) string {
449 v, _ := currentEnv.Get(k)
450 return v
451 }
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200452
Jason Wu2520f5e2023-05-30 19:45:36 -0400453 // Log the changed environment variables to ChangedEnvironmentVariable field
454 if stale, changedEnvironmentVariableList, _ := shared.StaleEnvFile(envFile, getenv); stale {
455 for _, changedEnvironmentVariable := range changedEnvironmentVariableList {
456 ctx.Metrics.AddChangedEnvironmentVariable(changedEnvironmentVariable)
457 }
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200458 os.Remove(envFile)
459 }
460}
461
Kousik Kumarca390b22023-10-04 04:14:28 +0000462func updateSymlinks(ctx Context, dir, prevCWD, cwd string) error {
463 defer symlinkWg.Done()
464
465 visit := func(path string, d fs.DirEntry, err error) error {
466 if d.IsDir() && path != dir {
467 symlinkWg.Add(1)
468 go updateSymlinks(ctx, path, prevCWD, cwd)
469 return filepath.SkipDir
470 }
471 f, err := d.Info()
472 if err != nil {
473 return err
474 }
475 // If the file is not a symlink, we don't have to update it.
476 if f.Mode()&os.ModeSymlink != os.ModeSymlink {
477 return nil
478 }
479
480 atomic.AddUint32(&numFound, 1)
481 target, err := os.Readlink(path)
482 if err != nil {
483 return err
484 }
485 if strings.HasPrefix(target, prevCWD) &&
486 (len(target) == len(prevCWD) || target[len(prevCWD)] == '/') {
487 target = filepath.Join(cwd, target[len(prevCWD):])
488 if err := os.Remove(path); err != nil {
489 return err
490 }
491 if err := os.Symlink(target, path); err != nil {
492 return err
493 }
494 atomic.AddUint32(&numUpdated, 1)
495 }
496 return nil
497 }
498
499 if err := filepath.WalkDir(dir, visit); err != nil {
500 return err
501 }
502 return nil
503}
504
505func fixOutDirSymlinks(ctx Context, config Config, outDir string) error {
506 cwd, err := os.Getwd()
507 if err != nil {
508 return err
509 }
510
511 // Record the .top as the very last thing in the function.
512 tf := filepath.Join(outDir, ".top")
513 defer func() {
514 if err := os.WriteFile(tf, []byte(cwd), 0644); err != nil {
515 fmt.Fprintf(os.Stderr, fmt.Sprintf("Unable to log CWD: %v", err))
516 }
517 }()
518
519 // Find the previous working directory if it was recorded.
520 var prevCWD string
521 pcwd, err := os.ReadFile(tf)
522 if err != nil {
523 if os.IsNotExist(err) {
524 // No previous working directory recorded, nothing to do.
525 return nil
526 }
527 return err
528 }
529 prevCWD = strings.Trim(string(pcwd), "\n")
530
531 if prevCWD == cwd {
532 // We are in the same source dir, nothing to update.
533 return nil
534 }
535
536 symlinkWg.Add(1)
537 if err := updateSymlinks(ctx, outDir, prevCWD, cwd); err != nil {
538 return err
539 }
540 symlinkWg.Wait()
541 ctx.Println(fmt.Sprintf("Updated %d/%d symlinks in dir %v", numUpdated, numFound, outDir))
542 return nil
543}
544
545func migrateOutputSymlinks(ctx Context, config Config) error {
546 // Figure out the real out directory ("out" could be a symlink).
547 outDir := config.OutDir()
548 s, err := os.Lstat(outDir)
549 if err != nil {
550 if os.IsNotExist(err) {
551 // No out dir exists, no symlinks to migrate.
552 return nil
553 }
554 return err
555 }
556 if s.Mode()&os.ModeSymlink == os.ModeSymlink {
557 target, err := filepath.EvalSymlinks(outDir)
558 if err != nil {
559 return err
560 }
561 outDir = target
562 }
563 return fixOutDirSymlinks(ctx, config, outDir)
564}
565
Dan Willemsen1e704462016-08-21 15:17:17 -0700566func runSoong(ctx Context, config Config) {
Nan Zhang17f27672018-12-12 16:01:49 -0800567 ctx.BeginTrace(metrics.RunSoong, "soong")
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700568 defer ctx.EndTrace()
569
Kousik Kumarca390b22023-10-04 04:14:28 +0000570 if err := migrateOutputSymlinks(ctx, config); err != nil {
571 ctx.Fatalf("failed to migrate output directory to current TOP dir: %v", err)
572 }
573
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100574 // We have two environment files: .available is the one with every variable,
575 // .used with the ones that were actually used. The latter is used to
576 // determine whether Soong needs to be re-run since why re-run it if only
577 // unused variables were changed?
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200578 envFile := filepath.Join(config.SoongOutDir(), availableEnvFile)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100579
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100580 // This is done unconditionally, but does not take a measurable amount of time
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200581 bootstrapBlueprint(ctx, config)
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700582
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100583 soongBuildEnv := config.Environment().Copy()
584 soongBuildEnv.Set("TOP", os.Getenv("TOP"))
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500585 soongBuildEnv.Set("LOG_DIR", config.LogsDir())
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100586
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100587 // For Soong bootstrapping tests
588 if os.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
589 soongBuildEnv.Set("ALLOW_MISSING_DEPENDENCIES", "true")
590 }
591
Paul Duffin5e85c662021-03-05 12:26:14 +0000592 err := writeEnvironmentFile(ctx, envFile, soongBuildEnv.AsMap())
593 if err != nil {
594 ctx.Fatalf("failed to write environment file %s: %s", envFile, err)
595 }
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100596
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700597 func() {
Nan Zhang17f27672018-12-12 16:01:49 -0800598 ctx.BeginTrace(metrics.RunSoong, "environment check")
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700599 defer ctx.EndTrace()
600
Jason Wu2520f5e2023-05-30 19:45:36 -0400601 checkEnvironmentFile(ctx, soongBuildEnv, config.UsedEnvFile(soongBuildTag))
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200602
Colin Cross8d411ff2023-12-07 10:31:24 -0800603 // Remove bazel files in the event that bazel is disabled for the build.
604 // These files may have been left over from a previous bazel-enabled build.
605 cleanBazelFiles(config)
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200606
607 if config.JsonModuleGraph() {
Jason Wu2520f5e2023-05-30 19:45:36 -0400608 checkEnvironmentFile(ctx, soongBuildEnv, config.UsedEnvFile(jsonModuleGraphTag))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200609 }
610
611 if config.Queryview() {
Jason Wu2520f5e2023-05-30 19:45:36 -0400612 checkEnvironmentFile(ctx, soongBuildEnv, config.UsedEnvFile(queryviewTag))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200613 }
614
615 if config.SoongDocs() {
Jason Wu2520f5e2023-05-30 19:45:36 -0400616 checkEnvironmentFile(ctx, soongBuildEnv, config.UsedEnvFile(soongDocsTag))
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700617 }
618 }()
619
Colin Cross9191df22021-10-29 13:11:32 -0700620 runMicrofactory(ctx, config, "bpglob", "github.com/google/blueprint/bootstrap/bpglob",
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700621 map[string]string{"github.com/google/blueprint": "build/blueprint"})
Dan Willemsen5af1cbe2018-07-05 21:46:51 -0700622
usta49012ee2023-05-22 16:33:27 -0400623 ninja := func(targets ...string) {
624 ctx.BeginTrace(metrics.RunSoong, "bootstrap")
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700625 defer ctx.EndTrace()
626
Dan Willemsenb82471a2018-05-17 16:37:09 -0700627 fifo := filepath.Join(config.OutDir(), ".ninja_fifo")
Colin Crossb98d3bc2019-03-21 16:02:58 -0700628 nr := status.NewNinjaReader(ctx, ctx.Status.StartTool(), fifo)
629 defer nr.Close()
Dan Willemsenb82471a2018-05-17 16:37:09 -0700630
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200631 ninjaArgs := []string{
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700632 "-d", "keepdepfile",
Dan Willemsen08218222020-05-18 14:02:02 -0700633 "-d", "stats",
Dan Willemsen6587bed2020-04-18 20:25:59 -0700634 "-o", "usesphonyoutputs=yes",
635 "-o", "preremoveoutputs=yes",
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700636 "-w", "dupbuild=err",
Dan Willemsen6587bed2020-04-18 20:25:59 -0700637 "-w", "outputdir=err",
638 "-w", "missingoutfile=err",
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700639 "-j", strconv.Itoa(config.Parallel()),
Dan Willemsen02736672018-07-17 17:54:31 -0700640 "--frontend_file", fifo,
usta49012ee2023-05-22 16:33:27 -0400641 "-f", filepath.Join(config.SoongOutDir(), "bootstrap.ninja"),
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200642 }
643
Usta Shrestha8dc8b0a2022-08-10 17:39:37 -0400644 if extra, ok := config.Environment().Get("SOONG_UI_NINJA_ARGS"); ok {
645 ctx.Printf(`CAUTION: arguments in $SOONG_UI_NINJA_ARGS=%q, e.g. "-n", can make soong_build FAIL or INCORRECT`, extra)
646 ninjaArgs = append(ninjaArgs, strings.Fields(extra)...)
647 }
648
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200649 ninjaArgs = append(ninjaArgs, targets...)
usta49012ee2023-05-22 16:33:27 -0400650 cmd := Command(ctx, config, "soong bootstrap",
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200651 config.PrebuiltBuildTool("ninja"), ninjaArgs...)
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500652
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100653 var ninjaEnv Environment
Lukacs T. Berki73ab9282021-03-10 10:48:39 +0100654
655 // This is currently how the command line to invoke soong_build finds the
656 // root of the source tree and the output root
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100657 ninjaEnv.Set("TOP", os.Getenv("TOP"))
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100658
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100659 cmd.Environment = &ninjaEnv
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700660 cmd.Sandbox = soongSandbox
Colin Cross7b97ecd2019-06-19 13:17:59 -0700661 cmd.RunAndStreamOrFatal()
Dan Willemsen1e704462016-08-21 15:17:17 -0700662 }
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200663
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200664 targets := make([]string, 0, 0)
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200665
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200666 if config.JsonModuleGraph() {
667 targets = append(targets, config.ModuleGraphFile())
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200668 }
669
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200670 if config.Queryview() {
671 targets = append(targets, config.QueryviewMarkerFile())
672 }
673
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200674 if config.SoongDocs() {
675 targets = append(targets, config.SoongDocsHtml())
676 }
677
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200678 if config.SoongBuildInvocationNeeded() {
679 // 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 -0700680 targets = append(targets, config.SoongNinjaFile())
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200681 }
682
Colin Crossaa9a2732023-10-27 10:54:27 -0700683 beforeSoongTimestamp := time.Now()
684
usta49012ee2023-05-22 16:33:27 -0400685 ninja(targets...)
Colin Crossb72c9092020-02-10 11:23:49 -0800686
Colin Crossaa9a2732023-10-27 10:54:27 -0700687 loadSoongBuildMetrics(ctx, config, beforeSoongTimestamp)
688
Yu Liu1b2ddc82024-05-15 19:28:56 +0000689 soongNinjaFile := config.SoongNinjaFile()
690 distGzipFile(ctx, config, soongNinjaFile, "soong")
691 for _, file := range blueprint.GetNinjaShardFiles(soongNinjaFile) {
692 if ok, _ := fileExists(file); ok {
693 distGzipFile(ctx, config, file, "soong")
694 }
695 }
Jihoon Kang9f4f8a32022-08-16 00:57:30 +0000696 distFile(ctx, config, config.SoongVarsFile(), "soong")
Inseob Kim58c802f2024-06-11 10:59:00 +0900697 distFile(ctx, config, config.SoongExtraVarsFile(), "soong")
Colin Cross8ba7d472020-06-25 11:27:52 -0700698
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000699 if !config.SkipKati() {
Colin Cross8ba7d472020-06-25 11:27:52 -0700700 distGzipFile(ctx, config, config.SoongAndroidMk(), "soong")
701 distGzipFile(ctx, config, config.SoongMakeVarsMk(), "soong")
702 }
703
Rob Seymour33cd10d2022-03-02 23:10:25 +0000704 if config.JsonModuleGraph() {
705 distGzipFile(ctx, config, config.ModuleGraphFile(), "soong")
706 }
Colin Crossb72c9092020-02-10 11:23:49 -0800707}
708
Colin Crossaa9a2732023-10-27 10:54:27 -0700709// loadSoongBuildMetrics reads out/soong_build_metrics.pb if it was generated by soong_build and copies the
710// events stored in it into the soong_ui trace to provide introspection into how long the different phases of
711// soong_build are taking.
712func loadSoongBuildMetrics(ctx Context, config Config, oldTimestamp time.Time) {
713 soongBuildMetricsFile := config.SoongBuildMetrics()
714 if metricsStat, err := os.Stat(soongBuildMetricsFile); err != nil {
715 ctx.Verbosef("Failed to stat %s: %s", soongBuildMetricsFile, err)
716 return
717 } else if !metricsStat.ModTime().After(oldTimestamp) {
718 ctx.Verbosef("%s timestamp not later after running soong, expected %s > %s",
719 soongBuildMetricsFile, metricsStat.ModTime(), oldTimestamp)
720 return
721 }
722
Colin Crossb67b0612023-10-31 10:02:45 -0700723 metricsData, err := os.ReadFile(soongBuildMetricsFile)
Colin Crossaa9a2732023-10-27 10:54:27 -0700724 if err != nil {
725 ctx.Verbosef("Failed to read %s: %s", soongBuildMetricsFile, err)
726 return
727 }
728
729 soongBuildMetrics := metrics_proto.SoongBuildMetrics{}
730 err = proto.Unmarshal(metricsData, &soongBuildMetrics)
731 if err != nil {
732 ctx.Verbosef("Failed to unmarshal %s: %s", soongBuildMetricsFile, err)
733 return
734 }
735 for _, event := range soongBuildMetrics.Events {
736 desc := event.GetDescription()
737 if dot := strings.LastIndexByte(desc, '.'); dot >= 0 {
738 desc = desc[dot+1:]
739 }
740 ctx.Tracer.Complete(desc, ctx.Thread,
741 event.GetStartTime(), event.GetStartTime()+event.GetRealTime())
742 }
Colin Cross46b0c752023-10-27 14:56:12 -0700743 for _, event := range soongBuildMetrics.PerfCounters {
744 timestamp := event.GetTime()
745 for _, group := range event.Groups {
746 counters := make([]tracer.Counter, 0, len(group.Counters))
747 for _, counter := range group.Counters {
748 counters = append(counters, tracer.Counter{
749 Name: counter.GetName(),
750 Value: counter.GetValue(),
751 })
752 }
753 ctx.Tracer.CountersAtTime(group.GetName(), ctx.Thread, timestamp, counters)
754 }
755 }
Colin Crossaa9a2732023-10-27 10:54:27 -0700756}
757
Chris Parsonsb6d6fc92023-10-30 16:21:06 +0000758func cleanBazelFiles(config Config) {
759 files := []string{
760 shared.JoinPath(config.SoongOutDir(), "bp2build"),
761 shared.JoinPath(config.SoongOutDir(), "workspace"),
762 shared.JoinPath(config.SoongOutDir(), bazel.SoongInjectionDirName),
763 shared.JoinPath(config.OutDir(), "bazel")}
764
765 for _, f := range files {
766 os.RemoveAll(f)
767 }
768}
769
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100770func runMicrofactory(ctx Context, config Config, name string, pkg string, mapping map[string]string) {
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700771 ctx.BeginTrace(metrics.RunSoong, name)
772 defer ctx.EndTrace()
773 cfg := microfactory.Config{TrimPath: absPath(ctx, ".")}
774 for pkgPrefix, pathPrefix := range mapping {
775 cfg.Map(pkgPrefix, pathPrefix)
776 }
777
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100778 exePath := filepath.Join(config.SoongOutDir(), name)
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700779 dir := filepath.Dir(exePath)
780 if err := os.MkdirAll(dir, 0777); err != nil {
781 ctx.Fatalf("cannot create %s: %s", dir, err)
782 }
783 if _, err := microfactory.Build(&cfg, exePath, pkg); err != nil {
784 ctx.Fatalf("failed to build %s: %s", name, err)
785 }
786}