blob: b94ffa574c137722fffdb460e42f5ee3d34e2132 [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
Dan Willemsen4591b642021-05-24 14:24:12 -070030 "android/soong/ui/metrics"
Colin Crossaa9a2732023-10-27 10:54:27 -070031 "android/soong/ui/metrics/metrics_proto"
Dan Willemsen4591b642021-05-24 14:24:12 -070032 "android/soong/ui/status"
33
34 "android/soong/shared"
35
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010036 "github.com/google/blueprint"
37 "github.com/google/blueprint/bootstrap"
Dan Willemsen99a75cd2017-08-04 16:04:04 -070038 "github.com/google/blueprint/microfactory"
Cole Faust8c0b11e2024-01-02 17:02:52 -080039 "github.com/google/blueprint/pathtools"
Colin Crossaa9a2732023-10-27 10:54:27 -070040
41 "google.golang.org/protobuf/proto"
Dan Willemsen1e704462016-08-21 15:17:17 -070042)
43
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020044const (
45 availableEnvFile = "soong.environment.available"
46 usedEnvFile = "soong.environment.used"
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +020047
Colin Cross8d411ff2023-12-07 10:31:24 -080048 soongBuildTag = "build"
49 jsonModuleGraphTag = "modulegraph"
50 queryviewTag = "queryview"
51 soongDocsTag = "soong_docs"
Colin Cross9191df22021-10-29 13:11:32 -070052
53 // bootstrapEpoch is used to determine if an incremental build is incompatible with the current
54 // version of bootstrap and needs cleaning before continuing the build. Increment this for
55 // incompatible changes, for example when moving the location of the bpglob binary that is
56 // executed during bootstrap before the primary builder has had a chance to update the path.
Lukacs T. Berki9985d9a2021-11-04 11:47:42 +010057 bootstrapEpoch = 1
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020058)
59
Kousik Kumarca390b22023-10-04 04:14:28 +000060var (
61 // Used during parallel update of symlinks in out directory to reflect new
62 // TOP dir.
63 symlinkWg sync.WaitGroup
64 numFound, numUpdated uint32
65)
66
Sasha Smundak4cbe83a2022-11-28 17:02:40 -080067func writeEnvironmentFile(_ Context, envFile string, envDeps map[string]string) error {
Lukacs T. Berki7690c092021-02-26 14:27:36 +010068 data, err := shared.EnvFileContents(envDeps)
69 if err != nil {
70 return err
71 }
72
Sasha Smundak4cbe83a2022-11-28 17:02:40 -080073 return os.WriteFile(envFile, data, 0644)
Lukacs T. Berki7690c092021-02-26 14:27:36 +010074}
75
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000076// This uses Android.bp files and various tools to generate <builddir>/build.ninja.
77//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010078// However, the execution of <builddir>/build.ninja happens later in
79// build/soong/ui/build/build.go#Build()
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000080//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010081// We want to rely on as few prebuilts as possible, so we need to bootstrap
82// Soong. The process is as follows:
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000083//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010084// 1. We use "Microfactory", a simple tool to compile Go code, to build
85// first itself, then soong_ui from soong_ui.bash. This binary contains
86// parts of soong_build that are needed to build itself.
87// 2. This simplified version of soong_build then reads the Blueprint files
88// that describe itself and emits .bootstrap/build.ninja that describes
89// how to build its full version and use that to produce the final Ninja
90// file Soong emits.
91// 3. soong_ui executes .bootstrap/build.ninja
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000092//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010093// (After this, Kati is executed to parse the Makefiles, but that's not part of
94// bootstrapping Soong)
95
96// A tiny struct used to tell Blueprint that it's in bootstrap mode. It would
97// probably be nicer to use a flag in bootstrap.Args instead.
98type BlueprintConfig struct {
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +020099 toolDir string
100 soongOutDir string
101 outDir string
102 runGoTests bool
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +0200103 debugCompilation bool
104 subninjas []string
105 primaryBuilderInvocations []bootstrap.PrimaryBuilderInvocation
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100106}
107
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200108func (c BlueprintConfig) HostToolDir() string {
109 return c.toolDir
110}
111
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200112func (c BlueprintConfig) SoongOutDir() string {
113 return c.soongOutDir
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100114}
115
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200116func (c BlueprintConfig) OutDir() string {
117 return c.outDir
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100118}
119
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +0200120func (c BlueprintConfig) RunGoTests() bool {
121 return c.runGoTests
122}
123
Lukacs T. Berki5f6cb1d2021-03-17 15:03:14 +0100124func (c BlueprintConfig) DebugCompilation() bool {
125 return c.debugCompilation
126}
127
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +0200128func (c BlueprintConfig) Subninjas() []string {
129 return c.subninjas
130}
131
132func (c BlueprintConfig) PrimaryBuilderInvocations() []bootstrap.PrimaryBuilderInvocation {
133 return c.primaryBuilderInvocations
134}
135
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200136func environmentArgs(config Config, tag string) []string {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200137 return []string{
138 "--available_env", shared.JoinPath(config.SoongOutDir(), availableEnvFile),
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200139 "--used_env", config.UsedEnvFile(tag),
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200140 }
141}
Spandan Das8f99ae62021-06-11 16:48:06 +0000142
Colin Cross9191df22021-10-29 13:11:32 -0700143func writeEmptyFile(ctx Context, path string) {
Spandan Das8f99ae62021-06-11 16:48:06 +0000144 err := os.MkdirAll(filepath.Dir(path), 0777)
145 if err != nil {
Colin Cross9191df22021-10-29 13:11:32 -0700146 ctx.Fatalf("Failed to create parent directories of empty file '%s': %s", path, err)
Spandan Das8f99ae62021-06-11 16:48:06 +0000147 }
148
Colin Cross9191df22021-10-29 13:11:32 -0700149 if exists, err := fileExists(path); err != nil {
150 ctx.Fatalf("Failed to check if file '%s' exists: %s", path, err)
151 } else if !exists {
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800152 err = os.WriteFile(path, nil, 0666)
Spandan Das8f99ae62021-06-11 16:48:06 +0000153 if err != nil {
Colin Cross9191df22021-10-29 13:11:32 -0700154 ctx.Fatalf("Failed to create empty file '%s': %s", path, err)
Spandan Das8f99ae62021-06-11 16:48:06 +0000155 }
156 }
157}
158
Colin Cross9191df22021-10-29 13:11:32 -0700159func fileExists(path string) (bool, error) {
160 if _, err := os.Stat(path); os.IsNotExist(err) {
161 return false, nil
162 } else if err != nil {
163 return false, err
164 }
165 return true, nil
166}
167
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800168type PrimaryBuilderFactory struct {
169 name string
170 description string
171 config Config
172 output string
173 specificArgs []string
174 debugPort string
175}
176
Jeongik Chaccf37002023-08-04 01:46:32 +0900177func getGlobPathName(config Config) string {
178 globPathName, ok := config.TargetProductOrErr()
179 if ok != nil {
180 globPathName = soongBuildTag
181 }
182 return globPathName
183}
184
Cole Faust8c0b11e2024-01-02 17:02:52 -0800185func getGlobPathNameFromPrimaryBuilderFactory(config Config, pb PrimaryBuilderFactory) string {
186 if pb.name == soongBuildTag {
187 // Glob path for soong build would be separated per product target
188 return getGlobPathName(config)
189 }
190 return pb.name
191}
192
193func (pb PrimaryBuilderFactory) primaryBuilderInvocation(config Config) bootstrap.PrimaryBuilderInvocation {
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200194 commonArgs := make([]string, 0, 0)
195
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800196 if !pb.config.skipSoongTests {
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200197 commonArgs = append(commonArgs, "-t")
198 }
199
Jihoon Kang2a929ad2023-06-08 19:02:07 +0000200 if pb.config.buildFromSourceStub {
201 commonArgs = append(commonArgs, "--build-from-source-stub")
Jihoon Kang1bff0342023-01-17 20:40:22 +0000202 }
LaMont Jones52a72432023-03-09 18:19:35 +0000203
Joe Onoratoe5ed3472024-02-02 14:52:05 -0800204 if pb.config.moduleDebugFile != "" {
205 commonArgs = append(commonArgs, "--soong_module_debug")
206 commonArgs = append(commonArgs, pb.config.moduleDebugFile)
207 }
208
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800209 commonArgs = append(commonArgs, "-l", filepath.Join(pb.config.FileListDir(), "Android.bp.list"))
Lukacs T. Berki13644272022-01-05 10:29:56 +0100210 invocationEnv := make(map[string]string)
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800211 if pb.debugPort != "" {
ustafb67fd12022-08-19 19:26:00 -0400212 //debug mode
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800213 commonArgs = append(commonArgs, "--delve_listen", pb.debugPort,
214 "--delve_path", shared.ResolveDelveBinary())
Lukacs T. Berki13644272022-01-05 10:29:56 +0100215 // GODEBUG=asyncpreemptoff=1 disables the preemption of goroutines. This
216 // is useful because the preemption happens by sending SIGURG to the OS
217 // thread hosting the goroutine in question and each signal results in
218 // work that needs to be done by Delve; it uses ptrace to debug the Go
219 // process and the tracer process must deal with every signal (it is not
220 // possible to selectively ignore SIGURG). This makes debugging slower,
221 // sometimes by an order of magnitude depending on luck.
222 // The original reason for adding async preemption to Go is here:
223 // https://github.com/golang/proposal/blob/master/design/24543-non-cooperative-preemption.md
224 invocationEnv["GODEBUG"] = "asyncpreemptoff=1"
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200225 }
226
ustafb67fd12022-08-19 19:26:00 -0400227 var allArgs []string
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800228 allArgs = append(allArgs, pb.specificArgs...)
Cole Faust8c0b11e2024-01-02 17:02:52 -0800229 globPathName := getGlobPathNameFromPrimaryBuilderFactory(config, pb)
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200230 allArgs = append(allArgs,
Jeongik Chaccf37002023-08-04 01:46:32 +0900231 "--globListDir", globPathName,
232 "--globFile", pb.config.NamedGlobFile(globPathName))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200233
234 allArgs = append(allArgs, commonArgs...)
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800235 allArgs = append(allArgs, environmentArgs(pb.config, pb.name)...)
Sasha Smundakfaa97b72022-11-18 15:32:49 -0800236 if profileCpu := os.Getenv("SOONG_PROFILE_CPU"); profileCpu != "" {
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800237 allArgs = append(allArgs, "--cpuprofile", profileCpu+"."+pb.name)
Sasha Smundakfaa97b72022-11-18 15:32:49 -0800238 }
239 if profileMem := os.Getenv("SOONG_PROFILE_MEM"); profileMem != "" {
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800240 allArgs = append(allArgs, "--memprofile", profileMem+"."+pb.name)
Sasha Smundakfaa97b72022-11-18 15:32:49 -0800241 }
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200242 allArgs = append(allArgs, "Android.bp")
243
Cole Faust8c0b11e2024-01-02 17:02:52 -0800244 globfiles := bootstrap.GlobFileListFiles(bootstrap.GlobDirectory(config.SoongOutDir(), globPathName))
245
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200246 return bootstrap.PrimaryBuilderInvocation{
Cole Faust8c0b11e2024-01-02 17:02:52 -0800247 Implicits: globfiles,
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800248 Outputs: []string{pb.output},
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000249 Args: allArgs,
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800250 Description: pb.description,
Lukacs T. Berki2fad3412022-01-04 14:40:13 +0100251 // NB: Changing the value of this environment variable will not result in a
252 // rebuild. The bootstrap Ninja file will change, but apparently Ninja does
253 // not consider changing the pool specified in a statement a change that's
254 // worth rebuilding for.
255 Console: os.Getenv("SOONG_UNBUFFERED_OUTPUT") == "1",
Lukacs T. Berki13644272022-01-05 10:29:56 +0100256 Env: invocationEnv,
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200257 }
258}
259
Colin Cross9191df22021-10-29 13:11:32 -0700260// bootstrapEpochCleanup deletes files used by bootstrap during incremental builds across
261// incompatible changes. Incompatible changes are marked by incrementing the bootstrapEpoch
262// constant. A tree is considered out of date for the current epoch of the
263// .soong.bootstrap.epoch.<epoch> file doesn't exist.
264func bootstrapEpochCleanup(ctx Context, config Config) {
265 epochFile := fmt.Sprintf(".soong.bootstrap.epoch.%d", bootstrapEpoch)
266 epochPath := filepath.Join(config.SoongOutDir(), epochFile)
267 if exists, err := fileExists(epochPath); err != nil {
268 ctx.Fatalf("failed to check if bootstrap epoch file %q exists: %q", epochPath, err)
269 } else if !exists {
270 // The tree is out of date for the current epoch, delete files used by bootstrap
271 // and force the primary builder to rerun.
Yu Liu1b2ddc82024-05-15 19:28:56 +0000272 soongNinjaFile := config.SoongNinjaFile()
273 os.Remove(soongNinjaFile)
274 for _, file := range blueprint.GetNinjaShardFiles(soongNinjaFile) {
275 if ok, _ := fileExists(file); ok {
276 os.Remove(file)
277 }
278 }
Colin Cross9191df22021-10-29 13:11:32 -0700279 for _, globFile := range bootstrapGlobFileList(config) {
280 os.Remove(globFile)
281 }
282
283 // Mark the tree as up to date with the current epoch by writing the epoch marker file.
284 writeEmptyFile(ctx, epochPath)
285 }
286}
287
288func bootstrapGlobFileList(config Config) []string {
289 return []string{
Jeongik Chaccf37002023-08-04 01:46:32 +0900290 config.NamedGlobFile(getGlobPathName(config)),
Colin Cross9191df22021-10-29 13:11:32 -0700291 config.NamedGlobFile(jsonModuleGraphTag),
292 config.NamedGlobFile(queryviewTag),
293 config.NamedGlobFile(soongDocsTag),
294 }
295}
296
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200297func bootstrapBlueprint(ctx Context, config Config) {
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100298 ctx.BeginTrace(metrics.RunSoong, "blueprint bootstrap")
299 defer ctx.EndTrace()
300
Colin Cross9191df22021-10-29 13:11:32 -0700301 // Clean up some files for incremental builds across incompatible changes.
302 bootstrapEpochCleanup(ctx, config)
303
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900304 baseArgs := []string{"--soong_variables", config.SoongVarsFile()}
305
306 mainSoongBuildExtraArgs := append(baseArgs, "-o", config.SoongNinjaFile())
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200307 if config.EmptyNinjaFile() {
308 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--empty-ninja-file")
Lukacs T. Berki745380c2021-04-12 12:07:44 +0200309 }
Jihoon Kang2a929ad2023-06-08 19:02:07 +0000310 if config.buildFromSourceStub {
311 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--build-from-source-stub")
Jihoon Kang1bff0342023-01-17 20:40:22 +0000312 }
MarkDacekf47e1422023-04-19 16:47:36 +0000313 if config.ensureAllowlistIntegrity {
314 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--ensure-allowlist-integrity")
315 }
Yu Liufa297642024-06-11 00:13:02 +0000316 if config.incrementalBuildActions {
317 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--incremental-build-actions")
318 }
MarkDacekd06db5d2022-11-29 00:47:59 +0000319
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000320 queryviewDir := filepath.Join(config.SoongOutDir(), "queryview")
Spandan Das5af0bd32022-09-28 20:43:08 +0000321
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800322 pbfs := []PrimaryBuilderFactory{
323 {
324 name: soongBuildTag,
325 description: fmt.Sprintf("analyzing Android.bp files and generating ninja file at %s", config.SoongNinjaFile()),
326 config: config,
327 output: config.SoongNinjaFile(),
328 specificArgs: mainSoongBuildExtraArgs,
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000329 },
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800330 {
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800331 name: jsonModuleGraphTag,
332 description: fmt.Sprintf("generating the Soong module graph at %s", config.ModuleGraphFile()),
333 config: config,
334 output: config.ModuleGraphFile(),
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900335 specificArgs: append(baseArgs,
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800336 "--module_graph_file", config.ModuleGraphFile(),
337 "--module_actions_file", config.ModuleActionsFile(),
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900338 ),
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800339 },
340 {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900341 name: queryviewTag,
342 description: fmt.Sprintf("generating the Soong module graph as a Bazel workspace at %s", queryviewDir),
343 config: config,
344 output: config.QueryviewMarkerFile(),
345 specificArgs: append(baseArgs,
346 "--bazel_queryview_dir", queryviewDir,
347 ),
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800348 },
349 {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900350 name: soongDocsTag,
351 description: fmt.Sprintf("generating Soong docs at %s", config.SoongDocsHtml()),
352 config: config,
353 output: config.SoongDocsHtml(),
354 specificArgs: append(baseArgs,
355 "--soong_docs", config.SoongDocsHtml(),
356 ),
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800357 },
358 }
359
360 // Figure out which invocations will be run under the debugger:
361 // * SOONG_DELVE if set specifies listening port
362 // * SOONG_DELVE_STEPS if set specifies specific invocations to be debugged, otherwise all are
363 debuggedInvocations := make(map[string]bool)
364 delvePort := os.Getenv("SOONG_DELVE")
365 if delvePort != "" {
366 if steps := os.Getenv("SOONG_DELVE_STEPS"); steps != "" {
367 var validSteps []string
368 for _, pbf := range pbfs {
369 debuggedInvocations[pbf.name] = false
370 validSteps = append(validSteps, pbf.name)
371
372 }
373 for _, step := range strings.Split(steps, ",") {
374 if _, ok := debuggedInvocations[step]; ok {
375 debuggedInvocations[step] = true
376 } else {
377 ctx.Fatalf("SOONG_DELVE_STEPS contains unknown soong_build step %s\n"+
378 "Valid steps are %v", step, validSteps)
379 }
380 }
381 } else {
382 // SOONG_DELVE_STEPS is not set, run all steps in the debugger
383 for _, pbf := range pbfs {
384 debuggedInvocations[pbf.name] = true
385 }
386 }
387 }
388
389 var invocations []bootstrap.PrimaryBuilderInvocation
390 for _, pbf := range pbfs {
391 if debuggedInvocations[pbf.name] {
392 pbf.debugPort = delvePort
393 }
Cole Faust8c0b11e2024-01-02 17:02:52 -0800394 pbi := pbf.primaryBuilderInvocation(config)
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800395 invocations = append(invocations, pbi)
396 }
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200397
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800398 blueprintArgs := bootstrap.Args{
399 ModuleListFile: filepath.Join(config.FileListDir(), "Android.bp.list"),
400 OutFile: shared.JoinPath(config.SoongOutDir(), "bootstrap.ninja"),
401 EmptyNinjaFile: false,
402 }
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200403
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100404 blueprintCtx := blueprint.NewContext()
Sam Delmerico98a73292023-02-21 11:50:29 -0500405 blueprintCtx.AddSourceRootDirs(config.GetSourceRootDirs()...)
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100406 blueprintCtx.SetIgnoreUnknownModuleTypes(true)
407 blueprintConfig := BlueprintConfig{
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200408 soongOutDir: config.SoongOutDir(),
409 toolDir: config.HostToolDir(),
410 outDir: config.OutDir(),
411 runGoTests: !config.skipSoongTests,
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200412 // If we want to debug soong_build, we need to compile it for debugging
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800413 debugCompilation: delvePort != "",
414 subninjas: bootstrapGlobFileList(config),
415 primaryBuilderInvocations: invocations,
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100416 }
417
Cole Faust8c0b11e2024-01-02 17:02:52 -0800418 // The glob ninja files are generated during the main build phase. However, the
419 // primary buildifer invocation depends on all of its glob files, even before
420 // it's been run. Generate a "empty" glob ninja file on the first run,
421 // so that the files can be there to satisfy the dependency.
422 for _, pb := range pbfs {
423 globPathName := getGlobPathNameFromPrimaryBuilderFactory(config, pb)
424 globNinjaFile := config.NamedGlobFile(globPathName)
425 if _, err := os.Stat(globNinjaFile); os.IsNotExist(err) {
426 err := bootstrap.WriteBuildGlobsNinjaFile(&bootstrap.GlobSingleton{
427 GlobLister: func() pathtools.MultipleGlobResults { return nil },
428 GlobFile: globNinjaFile,
429 GlobDir: bootstrap.GlobDirectory(config.SoongOutDir(), globPathName),
430 SrcDir: ".",
431 }, blueprintConfig)
432 if err != nil {
433 ctx.Fatal(err)
434 }
435 } else if err != nil {
436 ctx.Fatal(err)
437 }
438 }
439
usta5bb4a5d2022-08-24 12:53:46 -0400440 // since `bootstrap.ninja` is regenerated unconditionally, we ignore the deps, i.e. little
441 // reason to write a `bootstrap.ninja.d` file
Lukacs T. Berkic357c812023-06-20 09:30:06 +0000442 _, err := bootstrap.RunBlueprint(blueprintArgs, bootstrap.DoEverything, blueprintCtx, blueprintConfig)
443 if err != nil {
444 ctx.Fatal(err)
445 }
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100446}
447
Jason Wu2520f5e2023-05-30 19:45:36 -0400448func checkEnvironmentFile(ctx Context, currentEnv *Environment, envFile string) {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200449 getenv := func(k string) string {
450 v, _ := currentEnv.Get(k)
451 return v
452 }
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200453
Jason Wu2520f5e2023-05-30 19:45:36 -0400454 // Log the changed environment variables to ChangedEnvironmentVariable field
455 if stale, changedEnvironmentVariableList, _ := shared.StaleEnvFile(envFile, getenv); stale {
456 for _, changedEnvironmentVariable := range changedEnvironmentVariableList {
457 ctx.Metrics.AddChangedEnvironmentVariable(changedEnvironmentVariable)
458 }
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200459 os.Remove(envFile)
460 }
461}
462
Kousik Kumarca390b22023-10-04 04:14:28 +0000463func updateSymlinks(ctx Context, dir, prevCWD, cwd string) error {
464 defer symlinkWg.Done()
465
466 visit := func(path string, d fs.DirEntry, err error) error {
467 if d.IsDir() && path != dir {
468 symlinkWg.Add(1)
469 go updateSymlinks(ctx, path, prevCWD, cwd)
470 return filepath.SkipDir
471 }
472 f, err := d.Info()
473 if err != nil {
474 return err
475 }
476 // If the file is not a symlink, we don't have to update it.
477 if f.Mode()&os.ModeSymlink != os.ModeSymlink {
478 return nil
479 }
480
481 atomic.AddUint32(&numFound, 1)
482 target, err := os.Readlink(path)
483 if err != nil {
484 return err
485 }
486 if strings.HasPrefix(target, prevCWD) &&
487 (len(target) == len(prevCWD) || target[len(prevCWD)] == '/') {
488 target = filepath.Join(cwd, target[len(prevCWD):])
489 if err := os.Remove(path); err != nil {
490 return err
491 }
492 if err := os.Symlink(target, path); err != nil {
493 return err
494 }
495 atomic.AddUint32(&numUpdated, 1)
496 }
497 return nil
498 }
499
500 if err := filepath.WalkDir(dir, visit); err != nil {
501 return err
502 }
503 return nil
504}
505
506func fixOutDirSymlinks(ctx Context, config Config, outDir string) error {
507 cwd, err := os.Getwd()
508 if err != nil {
509 return err
510 }
511
512 // Record the .top as the very last thing in the function.
513 tf := filepath.Join(outDir, ".top")
514 defer func() {
515 if err := os.WriteFile(tf, []byte(cwd), 0644); err != nil {
516 fmt.Fprintf(os.Stderr, fmt.Sprintf("Unable to log CWD: %v", err))
517 }
518 }()
519
520 // Find the previous working directory if it was recorded.
521 var prevCWD string
522 pcwd, err := os.ReadFile(tf)
523 if err != nil {
524 if os.IsNotExist(err) {
525 // No previous working directory recorded, nothing to do.
526 return nil
527 }
528 return err
529 }
530 prevCWD = strings.Trim(string(pcwd), "\n")
531
532 if prevCWD == cwd {
533 // We are in the same source dir, nothing to update.
534 return nil
535 }
536
537 symlinkWg.Add(1)
538 if err := updateSymlinks(ctx, outDir, prevCWD, cwd); err != nil {
539 return err
540 }
541 symlinkWg.Wait()
542 ctx.Println(fmt.Sprintf("Updated %d/%d symlinks in dir %v", numUpdated, numFound, outDir))
543 return nil
544}
545
546func migrateOutputSymlinks(ctx Context, config Config) error {
547 // Figure out the real out directory ("out" could be a symlink).
548 outDir := config.OutDir()
549 s, err := os.Lstat(outDir)
550 if err != nil {
551 if os.IsNotExist(err) {
552 // No out dir exists, no symlinks to migrate.
553 return nil
554 }
555 return err
556 }
557 if s.Mode()&os.ModeSymlink == os.ModeSymlink {
558 target, err := filepath.EvalSymlinks(outDir)
559 if err != nil {
560 return err
561 }
562 outDir = target
563 }
564 return fixOutDirSymlinks(ctx, config, outDir)
565}
566
Dan Willemsen1e704462016-08-21 15:17:17 -0700567func runSoong(ctx Context, config Config) {
Nan Zhang17f27672018-12-12 16:01:49 -0800568 ctx.BeginTrace(metrics.RunSoong, "soong")
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700569 defer ctx.EndTrace()
570
Kousik Kumarca390b22023-10-04 04:14:28 +0000571 if err := migrateOutputSymlinks(ctx, config); err != nil {
572 ctx.Fatalf("failed to migrate output directory to current TOP dir: %v", err)
573 }
574
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100575 // We have two environment files: .available is the one with every variable,
576 // .used with the ones that were actually used. The latter is used to
577 // determine whether Soong needs to be re-run since why re-run it if only
578 // unused variables were changed?
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200579 envFile := filepath.Join(config.SoongOutDir(), availableEnvFile)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100580
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100581 // This is done unconditionally, but does not take a measurable amount of time
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200582 bootstrapBlueprint(ctx, config)
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700583
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100584 soongBuildEnv := config.Environment().Copy()
585 soongBuildEnv.Set("TOP", os.Getenv("TOP"))
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500586 soongBuildEnv.Set("LOG_DIR", config.LogsDir())
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100587
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100588 // For Soong bootstrapping tests
589 if os.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
590 soongBuildEnv.Set("ALLOW_MISSING_DEPENDENCIES", "true")
591 }
592
Paul Duffin5e85c662021-03-05 12:26:14 +0000593 err := writeEnvironmentFile(ctx, envFile, soongBuildEnv.AsMap())
594 if err != nil {
595 ctx.Fatalf("failed to write environment file %s: %s", envFile, err)
596 }
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100597
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700598 func() {
Nan Zhang17f27672018-12-12 16:01:49 -0800599 ctx.BeginTrace(metrics.RunSoong, "environment check")
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700600 defer ctx.EndTrace()
601
Jason Wu2520f5e2023-05-30 19:45:36 -0400602 checkEnvironmentFile(ctx, soongBuildEnv, config.UsedEnvFile(soongBuildTag))
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200603
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200604 if config.JsonModuleGraph() {
Jason Wu2520f5e2023-05-30 19:45:36 -0400605 checkEnvironmentFile(ctx, soongBuildEnv, config.UsedEnvFile(jsonModuleGraphTag))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200606 }
607
608 if config.Queryview() {
Jason Wu2520f5e2023-05-30 19:45:36 -0400609 checkEnvironmentFile(ctx, soongBuildEnv, config.UsedEnvFile(queryviewTag))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200610 }
611
612 if config.SoongDocs() {
Jason Wu2520f5e2023-05-30 19:45:36 -0400613 checkEnvironmentFile(ctx, soongBuildEnv, config.UsedEnvFile(soongDocsTag))
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700614 }
615 }()
616
Colin Cross9191df22021-10-29 13:11:32 -0700617 runMicrofactory(ctx, config, "bpglob", "github.com/google/blueprint/bootstrap/bpglob",
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700618 map[string]string{"github.com/google/blueprint": "build/blueprint"})
Dan Willemsen5af1cbe2018-07-05 21:46:51 -0700619
usta49012ee2023-05-22 16:33:27 -0400620 ninja := func(targets ...string) {
621 ctx.BeginTrace(metrics.RunSoong, "bootstrap")
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700622 defer ctx.EndTrace()
623
Dan Willemsenb82471a2018-05-17 16:37:09 -0700624 fifo := filepath.Join(config.OutDir(), ".ninja_fifo")
Colin Crossb98d3bc2019-03-21 16:02:58 -0700625 nr := status.NewNinjaReader(ctx, ctx.Status.StartTool(), fifo)
626 defer nr.Close()
Dan Willemsenb82471a2018-05-17 16:37:09 -0700627
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200628 ninjaArgs := []string{
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700629 "-d", "keepdepfile",
Dan Willemsen08218222020-05-18 14:02:02 -0700630 "-d", "stats",
Dan Willemsen6587bed2020-04-18 20:25:59 -0700631 "-o", "usesphonyoutputs=yes",
632 "-o", "preremoveoutputs=yes",
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700633 "-w", "dupbuild=err",
Dan Willemsen6587bed2020-04-18 20:25:59 -0700634 "-w", "outputdir=err",
635 "-w", "missingoutfile=err",
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700636 "-j", strconv.Itoa(config.Parallel()),
Dan Willemsen02736672018-07-17 17:54:31 -0700637 "--frontend_file", fifo,
usta49012ee2023-05-22 16:33:27 -0400638 "-f", filepath.Join(config.SoongOutDir(), "bootstrap.ninja"),
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200639 }
Cole Faustbee030d2024-01-03 13:45:48 -0800640 if config.useN2 {
641 ninjaArgs = []string{
642 // TODO: implement these features, or remove them.
643 //"-d", "keepdepfile",
644 //"-d", "stats",
645 //"-o", "usesphonyoutputs=yes",
646 //"-o", "preremoveoutputs=yes",
647 //"-w", "dupbuild=err",
648 //"-w", "outputdir=err",
649 //"-w", "missingoutfile=err",
650 "-v",
651 "-j", strconv.Itoa(config.Parallel()),
652 "--frontend-file", fifo,
653 "-f", filepath.Join(config.SoongOutDir(), "bootstrap.ninja"),
654 }
655 }
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200656
Usta Shrestha8dc8b0a2022-08-10 17:39:37 -0400657 if extra, ok := config.Environment().Get("SOONG_UI_NINJA_ARGS"); ok {
658 ctx.Printf(`CAUTION: arguments in $SOONG_UI_NINJA_ARGS=%q, e.g. "-n", can make soong_build FAIL or INCORRECT`, extra)
659 ninjaArgs = append(ninjaArgs, strings.Fields(extra)...)
660 }
661
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200662 ninjaArgs = append(ninjaArgs, targets...)
Taylor Santiago3c16e612024-05-30 14:41:31 -0700663 ninjaCmd := config.NinjaBin()
Cole Faustbee030d2024-01-03 13:45:48 -0800664 if config.useN2 {
Cole Faust4e58bba2024-08-22 14:27:03 -0700665 ninjaCmd = config.N2Bin()
Cole Faustbee030d2024-01-03 13:45:48 -0800666 }
667
usta49012ee2023-05-22 16:33:27 -0400668 cmd := Command(ctx, config, "soong bootstrap",
Cole Faustbee030d2024-01-03 13:45:48 -0800669 ninjaCmd, ninjaArgs...)
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500670
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100671 var ninjaEnv Environment
Lukacs T. Berki73ab9282021-03-10 10:48:39 +0100672
673 // This is currently how the command line to invoke soong_build finds the
674 // root of the source tree and the output root
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100675 ninjaEnv.Set("TOP", os.Getenv("TOP"))
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100676
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100677 cmd.Environment = &ninjaEnv
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700678 cmd.Sandbox = soongSandbox
Colin Cross7b97ecd2019-06-19 13:17:59 -0700679 cmd.RunAndStreamOrFatal()
Dan Willemsen1e704462016-08-21 15:17:17 -0700680 }
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200681
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200682 targets := make([]string, 0, 0)
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200683
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200684 if config.JsonModuleGraph() {
685 targets = append(targets, config.ModuleGraphFile())
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200686 }
687
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200688 if config.Queryview() {
689 targets = append(targets, config.QueryviewMarkerFile())
690 }
691
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200692 if config.SoongDocs() {
693 targets = append(targets, config.SoongDocsHtml())
694 }
695
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200696 if config.SoongBuildInvocationNeeded() {
697 // 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 -0700698 targets = append(targets, config.SoongNinjaFile())
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200699 }
700
Colin Crossaa9a2732023-10-27 10:54:27 -0700701 beforeSoongTimestamp := time.Now()
702
usta49012ee2023-05-22 16:33:27 -0400703 ninja(targets...)
Colin Crossb72c9092020-02-10 11:23:49 -0800704
Colin Crossaa9a2732023-10-27 10:54:27 -0700705 loadSoongBuildMetrics(ctx, config, beforeSoongTimestamp)
706
Yu Liu1b2ddc82024-05-15 19:28:56 +0000707 soongNinjaFile := config.SoongNinjaFile()
708 distGzipFile(ctx, config, soongNinjaFile, "soong")
709 for _, file := range blueprint.GetNinjaShardFiles(soongNinjaFile) {
710 if ok, _ := fileExists(file); ok {
711 distGzipFile(ctx, config, file, "soong")
712 }
713 }
Jihoon Kang9f4f8a32022-08-16 00:57:30 +0000714 distFile(ctx, config, config.SoongVarsFile(), "soong")
Inseob Kim58c802f2024-06-11 10:59:00 +0900715 distFile(ctx, config, config.SoongExtraVarsFile(), "soong")
Colin Cross8ba7d472020-06-25 11:27:52 -0700716
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000717 if !config.SkipKati() {
Colin Cross8ba7d472020-06-25 11:27:52 -0700718 distGzipFile(ctx, config, config.SoongAndroidMk(), "soong")
719 distGzipFile(ctx, config, config.SoongMakeVarsMk(), "soong")
720 }
721
Rob Seymour33cd10d2022-03-02 23:10:25 +0000722 if config.JsonModuleGraph() {
723 distGzipFile(ctx, config, config.ModuleGraphFile(), "soong")
724 }
Colin Crossb72c9092020-02-10 11:23:49 -0800725}
726
Colin Crossaa9a2732023-10-27 10:54:27 -0700727// loadSoongBuildMetrics reads out/soong_build_metrics.pb if it was generated by soong_build and copies the
728// events stored in it into the soong_ui trace to provide introspection into how long the different phases of
729// soong_build are taking.
730func loadSoongBuildMetrics(ctx Context, config Config, oldTimestamp time.Time) {
731 soongBuildMetricsFile := config.SoongBuildMetrics()
732 if metricsStat, err := os.Stat(soongBuildMetricsFile); err != nil {
733 ctx.Verbosef("Failed to stat %s: %s", soongBuildMetricsFile, err)
734 return
735 } else if !metricsStat.ModTime().After(oldTimestamp) {
736 ctx.Verbosef("%s timestamp not later after running soong, expected %s > %s",
737 soongBuildMetricsFile, metricsStat.ModTime(), oldTimestamp)
738 return
739 }
740
Colin Crossb67b0612023-10-31 10:02:45 -0700741 metricsData, err := os.ReadFile(soongBuildMetricsFile)
Colin Crossaa9a2732023-10-27 10:54:27 -0700742 if err != nil {
743 ctx.Verbosef("Failed to read %s: %s", soongBuildMetricsFile, err)
744 return
745 }
746
747 soongBuildMetrics := metrics_proto.SoongBuildMetrics{}
748 err = proto.Unmarshal(metricsData, &soongBuildMetrics)
749 if err != nil {
750 ctx.Verbosef("Failed to unmarshal %s: %s", soongBuildMetricsFile, err)
751 return
752 }
753 for _, event := range soongBuildMetrics.Events {
754 desc := event.GetDescription()
755 if dot := strings.LastIndexByte(desc, '.'); dot >= 0 {
756 desc = desc[dot+1:]
757 }
758 ctx.Tracer.Complete(desc, ctx.Thread,
759 event.GetStartTime(), event.GetStartTime()+event.GetRealTime())
760 }
Colin Cross46b0c752023-10-27 14:56:12 -0700761 for _, event := range soongBuildMetrics.PerfCounters {
762 timestamp := event.GetTime()
763 for _, group := range event.Groups {
764 counters := make([]tracer.Counter, 0, len(group.Counters))
765 for _, counter := range group.Counters {
766 counters = append(counters, tracer.Counter{
767 Name: counter.GetName(),
768 Value: counter.GetValue(),
769 })
770 }
771 ctx.Tracer.CountersAtTime(group.GetName(), ctx.Thread, timestamp, counters)
772 }
773 }
Colin Crossaa9a2732023-10-27 10:54:27 -0700774}
775
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100776func runMicrofactory(ctx Context, config Config, name string, pkg string, mapping map[string]string) {
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700777 ctx.BeginTrace(metrics.RunSoong, name)
778 defer ctx.EndTrace()
779 cfg := microfactory.Config{TrimPath: absPath(ctx, ".")}
780 for pkgPrefix, pathPrefix := range mapping {
781 cfg.Map(pkgPrefix, pathPrefix)
782 }
783
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100784 exePath := filepath.Join(config.SoongOutDir(), name)
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700785 dir := filepath.Dir(exePath)
786 if err := os.MkdirAll(dir, 0777); err != nil {
787 ctx.Fatalf("cannot create %s: %s", dir, err)
788 }
789 if _, err := microfactory.Build(&cfg, exePath, pkg); err != nil {
790 ctx.Fatalf("failed to build %s: %s", name, err)
791 }
792}