blob: ab18dbaf1aae6c781bf322968cb01e5fb7fc47f3 [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 (
Cole Faust2fec4122024-09-07 17:28:11 -070018 "encoding/json"
19 "errors"
Colin Cross9191df22021-10-29 13:11:32 -070020 "fmt"
Kousik Kumarca390b22023-10-04 04:14:28 +000021 "io/fs"
Dan Willemsen99a75cd2017-08-04 16:04:04 -070022 "os"
Dan Willemsen1e704462016-08-21 15:17:17 -070023 "path/filepath"
Cole Faust2fec4122024-09-07 17:28:11 -070024 "runtime"
25 "slices"
Dan Willemsen99a75cd2017-08-04 16:04:04 -070026 "strconv"
Usta Shrestha8dc8b0a2022-08-10 17:39:37 -040027 "strings"
Kousik Kumarca390b22023-10-04 04:14:28 +000028 "sync"
29 "sync/atomic"
Colin Cross117af422024-09-25 09:14:21 -070030 "syscall"
Colin Crossaa9a2732023-10-27 10:54:27 -070031 "time"
Dan Willemsen99a75cd2017-08-04 16:04:04 -070032
Yu Liu1b2ddc82024-05-15 19:28:56 +000033 "android/soong/ui/tracer"
34
Dan Willemsen4591b642021-05-24 14:24:12 -070035 "android/soong/ui/metrics"
Colin Crossaa9a2732023-10-27 10:54:27 -070036 "android/soong/ui/metrics/metrics_proto"
Dan Willemsen4591b642021-05-24 14:24:12 -070037 "android/soong/ui/status"
38
39 "android/soong/shared"
40
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010041 "github.com/google/blueprint"
42 "github.com/google/blueprint/bootstrap"
Dan Willemsen99a75cd2017-08-04 16:04:04 -070043 "github.com/google/blueprint/microfactory"
Cole Faust8c0b11e2024-01-02 17:02:52 -080044 "github.com/google/blueprint/pathtools"
Colin Crossaa9a2732023-10-27 10:54:27 -070045
46 "google.golang.org/protobuf/proto"
Dan Willemsen1e704462016-08-21 15:17:17 -070047)
48
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020049const (
50 availableEnvFile = "soong.environment.available"
51 usedEnvFile = "soong.environment.used"
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +020052
Colin Cross8d411ff2023-12-07 10:31:24 -080053 soongBuildTag = "build"
54 jsonModuleGraphTag = "modulegraph"
55 queryviewTag = "queryview"
56 soongDocsTag = "soong_docs"
Colin Cross9191df22021-10-29 13:11:32 -070057
58 // bootstrapEpoch is used to determine if an incremental build is incompatible with the current
59 // version of bootstrap and needs cleaning before continuing the build. Increment this for
Cole Faust2fec4122024-09-07 17:28:11 -070060 // incompatible changes, for example when moving the location of a microfactory binary that is
Colin Cross9191df22021-10-29 13:11:32 -070061 // executed during bootstrap before the primary builder has had a chance to update the path.
Lukacs T. Berki9985d9a2021-11-04 11:47:42 +010062 bootstrapEpoch = 1
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020063)
64
Kousik Kumarca390b22023-10-04 04:14:28 +000065var (
66 // Used during parallel update of symlinks in out directory to reflect new
67 // TOP dir.
68 symlinkWg sync.WaitGroup
69 numFound, numUpdated uint32
70)
71
Sasha Smundak4cbe83a2022-11-28 17:02:40 -080072func writeEnvironmentFile(_ Context, envFile string, envDeps map[string]string) error {
Lukacs T. Berki7690c092021-02-26 14:27:36 +010073 data, err := shared.EnvFileContents(envDeps)
74 if err != nil {
75 return err
76 }
77
Sasha Smundak4cbe83a2022-11-28 17:02:40 -080078 return os.WriteFile(envFile, data, 0644)
Lukacs T. Berki7690c092021-02-26 14:27:36 +010079}
80
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000081// This uses Android.bp files and various tools to generate <builddir>/build.ninja.
82//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010083// However, the execution of <builddir>/build.ninja happens later in
84// build/soong/ui/build/build.go#Build()
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000085//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010086// We want to rely on as few prebuilts as possible, so we need to bootstrap
87// Soong. The process is as follows:
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000088//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010089// 1. We use "Microfactory", a simple tool to compile Go code, to build
90// first itself, then soong_ui from soong_ui.bash. This binary contains
91// parts of soong_build that are needed to build itself.
92// 2. This simplified version of soong_build then reads the Blueprint files
93// that describe itself and emits .bootstrap/build.ninja that describes
94// how to build its full version and use that to produce the final Ninja
95// file Soong emits.
96// 3. soong_ui executes .bootstrap/build.ninja
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000097//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010098// (After this, Kati is executed to parse the Makefiles, but that's not part of
99// bootstrapping Soong)
100
101// A tiny struct used to tell Blueprint that it's in bootstrap mode. It would
102// probably be nicer to use a flag in bootstrap.Args instead.
103type BlueprintConfig struct {
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +0200104 toolDir string
105 soongOutDir string
106 outDir string
107 runGoTests bool
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +0200108 debugCompilation bool
109 subninjas []string
110 primaryBuilderInvocations []bootstrap.PrimaryBuilderInvocation
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100111}
112
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200113func (c BlueprintConfig) HostToolDir() string {
114 return c.toolDir
115}
116
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200117func (c BlueprintConfig) SoongOutDir() string {
118 return c.soongOutDir
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100119}
120
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200121func (c BlueprintConfig) OutDir() string {
122 return c.outDir
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100123}
124
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +0200125func (c BlueprintConfig) RunGoTests() bool {
126 return c.runGoTests
127}
128
Lukacs T. Berki5f6cb1d2021-03-17 15:03:14 +0100129func (c BlueprintConfig) DebugCompilation() bool {
130 return c.debugCompilation
131}
132
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +0200133func (c BlueprintConfig) Subninjas() []string {
134 return c.subninjas
135}
136
137func (c BlueprintConfig) PrimaryBuilderInvocations() []bootstrap.PrimaryBuilderInvocation {
138 return c.primaryBuilderInvocations
139}
140
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200141func environmentArgs(config Config, tag string) []string {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200142 return []string{
143 "--available_env", shared.JoinPath(config.SoongOutDir(), availableEnvFile),
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200144 "--used_env", config.UsedEnvFile(tag),
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200145 }
146}
Spandan Das8f99ae62021-06-11 16:48:06 +0000147
Colin Cross9191df22021-10-29 13:11:32 -0700148func writeEmptyFile(ctx Context, path string) {
Spandan Das8f99ae62021-06-11 16:48:06 +0000149 err := os.MkdirAll(filepath.Dir(path), 0777)
150 if err != nil {
Colin Cross9191df22021-10-29 13:11:32 -0700151 ctx.Fatalf("Failed to create parent directories of empty file '%s': %s", path, err)
Spandan Das8f99ae62021-06-11 16:48:06 +0000152 }
153
Colin Cross9191df22021-10-29 13:11:32 -0700154 if exists, err := fileExists(path); err != nil {
155 ctx.Fatalf("Failed to check if file '%s' exists: %s", path, err)
156 } else if !exists {
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800157 err = os.WriteFile(path, nil, 0666)
Spandan Das8f99ae62021-06-11 16:48:06 +0000158 if err != nil {
Colin Cross9191df22021-10-29 13:11:32 -0700159 ctx.Fatalf("Failed to create empty file '%s': %s", path, err)
Spandan Das8f99ae62021-06-11 16:48:06 +0000160 }
161 }
162}
163
Colin Cross9191df22021-10-29 13:11:32 -0700164func fileExists(path string) (bool, error) {
165 if _, err := os.Stat(path); os.IsNotExist(err) {
166 return false, nil
167 } else if err != nil {
168 return false, err
169 }
170 return true, nil
171}
172
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800173type PrimaryBuilderFactory struct {
174 name string
175 description string
176 config Config
177 output string
178 specificArgs []string
179 debugPort string
180}
181
Jeongik Chaccf37002023-08-04 01:46:32 +0900182func getGlobPathName(config Config) string {
183 globPathName, ok := config.TargetProductOrErr()
184 if ok != nil {
185 globPathName = soongBuildTag
186 }
187 return globPathName
188}
189
Cole Faust8c0b11e2024-01-02 17:02:52 -0800190func getGlobPathNameFromPrimaryBuilderFactory(config Config, pb PrimaryBuilderFactory) string {
191 if pb.name == soongBuildTag {
192 // Glob path for soong build would be separated per product target
193 return getGlobPathName(config)
194 }
195 return pb.name
196}
197
198func (pb PrimaryBuilderFactory) primaryBuilderInvocation(config Config) bootstrap.PrimaryBuilderInvocation {
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200199 commonArgs := make([]string, 0, 0)
200
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800201 if !pb.config.skipSoongTests {
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200202 commonArgs = append(commonArgs, "-t")
203 }
204
Jihoon Kang2a929ad2023-06-08 19:02:07 +0000205 if pb.config.buildFromSourceStub {
206 commonArgs = append(commonArgs, "--build-from-source-stub")
Jihoon Kang1bff0342023-01-17 20:40:22 +0000207 }
LaMont Jones52a72432023-03-09 18:19:35 +0000208
Joe Onoratoe5ed3472024-02-02 14:52:05 -0800209 if pb.config.moduleDebugFile != "" {
210 commonArgs = append(commonArgs, "--soong_module_debug")
211 commonArgs = append(commonArgs, pb.config.moduleDebugFile)
212 }
213
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800214 commonArgs = append(commonArgs, "-l", filepath.Join(pb.config.FileListDir(), "Android.bp.list"))
Lukacs T. Berki13644272022-01-05 10:29:56 +0100215 invocationEnv := make(map[string]string)
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800216 if pb.debugPort != "" {
ustafb67fd12022-08-19 19:26:00 -0400217 //debug mode
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800218 commonArgs = append(commonArgs, "--delve_listen", pb.debugPort,
219 "--delve_path", shared.ResolveDelveBinary())
Lukacs T. Berki13644272022-01-05 10:29:56 +0100220 // GODEBUG=asyncpreemptoff=1 disables the preemption of goroutines. This
221 // is useful because the preemption happens by sending SIGURG to the OS
222 // thread hosting the goroutine in question and each signal results in
223 // work that needs to be done by Delve; it uses ptrace to debug the Go
224 // process and the tracer process must deal with every signal (it is not
225 // possible to selectively ignore SIGURG). This makes debugging slower,
226 // sometimes by an order of magnitude depending on luck.
227 // The original reason for adding async preemption to Go is here:
228 // https://github.com/golang/proposal/blob/master/design/24543-non-cooperative-preemption.md
229 invocationEnv["GODEBUG"] = "asyncpreemptoff=1"
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200230 }
231
ustafb67fd12022-08-19 19:26:00 -0400232 var allArgs []string
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800233 allArgs = append(allArgs, pb.specificArgs...)
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
245 return bootstrap.PrimaryBuilderInvocation{
Cole Faust2fec4122024-09-07 17:28:11 -0700246 Implicits: []string{pb.output + ".glob_results"},
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800247 Outputs: []string{pb.output},
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000248 Args: allArgs,
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800249 Description: pb.description,
Lukacs T. Berki2fad3412022-01-04 14:40:13 +0100250 // NB: Changing the value of this environment variable will not result in a
251 // rebuild. The bootstrap Ninja file will change, but apparently Ninja does
252 // not consider changing the pool specified in a statement a change that's
253 // worth rebuilding for.
254 Console: os.Getenv("SOONG_UNBUFFERED_OUTPUT") == "1",
Lukacs T. Berki13644272022-01-05 10:29:56 +0100255 Env: invocationEnv,
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200256 }
257}
258
Colin Cross9191df22021-10-29 13:11:32 -0700259// bootstrapEpochCleanup deletes files used by bootstrap during incremental builds across
260// incompatible changes. Incompatible changes are marked by incrementing the bootstrapEpoch
261// constant. A tree is considered out of date for the current epoch of the
262// .soong.bootstrap.epoch.<epoch> file doesn't exist.
263func bootstrapEpochCleanup(ctx Context, config Config) {
264 epochFile := fmt.Sprintf(".soong.bootstrap.epoch.%d", bootstrapEpoch)
265 epochPath := filepath.Join(config.SoongOutDir(), epochFile)
266 if exists, err := fileExists(epochPath); err != nil {
267 ctx.Fatalf("failed to check if bootstrap epoch file %q exists: %q", epochPath, err)
268 } else if !exists {
269 // The tree is out of date for the current epoch, delete files used by bootstrap
270 // and force the primary builder to rerun.
Yu Liu1b2ddc82024-05-15 19:28:56 +0000271 soongNinjaFile := config.SoongNinjaFile()
272 os.Remove(soongNinjaFile)
273 for _, file := range blueprint.GetNinjaShardFiles(soongNinjaFile) {
274 if ok, _ := fileExists(file); ok {
275 os.Remove(file)
276 }
277 }
Cole Faust2fec4122024-09-07 17:28:11 -0700278 os.Remove(soongNinjaFile + ".globs")
279 os.Remove(soongNinjaFile + ".globs_time")
280 os.Remove(soongNinjaFile + ".glob_results")
Colin Cross9191df22021-10-29 13:11:32 -0700281
282 // Mark the tree as up to date with the current epoch by writing the epoch marker file.
283 writeEmptyFile(ctx, epochPath)
284 }
285}
286
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200287func bootstrapBlueprint(ctx Context, config Config) {
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100288 ctx.BeginTrace(metrics.RunSoong, "blueprint bootstrap")
289 defer ctx.EndTrace()
290
Colin Cross98bb3b82024-10-25 14:45:07 -0700291 st := ctx.Status.StartTool()
292 defer st.Finish()
293 st.SetTotalActions(1)
294 action := &status.Action{
295 Description: "bootstrap blueprint",
296 Outputs: []string{"bootstrap blueprint"},
297 }
298 st.StartAction(action)
299
Colin Cross9191df22021-10-29 13:11:32 -0700300 // Clean up some files for incremental builds across incompatible changes.
301 bootstrapEpochCleanup(ctx, config)
302
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900303 baseArgs := []string{"--soong_variables", config.SoongVarsFile()}
304
305 mainSoongBuildExtraArgs := append(baseArgs, "-o", config.SoongNinjaFile())
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200306 if config.EmptyNinjaFile() {
307 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--empty-ninja-file")
Lukacs T. Berki745380c2021-04-12 12:07:44 +0200308 }
Jihoon Kang2a929ad2023-06-08 19:02:07 +0000309 if config.buildFromSourceStub {
310 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--build-from-source-stub")
Jihoon Kang1bff0342023-01-17 20:40:22 +0000311 }
MarkDacekf47e1422023-04-19 16:47:36 +0000312 if config.ensureAllowlistIntegrity {
313 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--ensure-allowlist-integrity")
314 }
Yu Liufa297642024-06-11 00:13:02 +0000315 if config.incrementalBuildActions {
316 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--incremental-build-actions")
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 != "",
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800413 primaryBuilderInvocations: invocations,
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100414 }
415
usta5bb4a5d2022-08-24 12:53:46 -0400416 // since `bootstrap.ninja` is regenerated unconditionally, we ignore the deps, i.e. little
417 // reason to write a `bootstrap.ninja.d` file
Lukacs T. Berkic357c812023-06-20 09:30:06 +0000418 _, err := bootstrap.RunBlueprint(blueprintArgs, bootstrap.DoEverything, blueprintCtx, blueprintConfig)
Colin Cross98bb3b82024-10-25 14:45:07 -0700419
420 result := status.ActionResult{
421 Action: action,
422 }
Lukacs T. Berkic357c812023-06-20 09:30:06 +0000423 if err != nil {
Colin Cross98bb3b82024-10-25 14:45:07 -0700424 result.Error = err
425 result.Output = err.Error()
426 }
427 st.FinishAction(result)
428 if err != nil {
429 ctx.Fatalf("bootstrap failed")
Lukacs T. Berkic357c812023-06-20 09:30:06 +0000430 }
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100431}
432
Jason Wu2520f5e2023-05-30 19:45:36 -0400433func checkEnvironmentFile(ctx Context, currentEnv *Environment, envFile string) {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200434 getenv := func(k string) string {
435 v, _ := currentEnv.Get(k)
436 return v
437 }
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200438
Jason Wu2520f5e2023-05-30 19:45:36 -0400439 // Log the changed environment variables to ChangedEnvironmentVariable field
440 if stale, changedEnvironmentVariableList, _ := shared.StaleEnvFile(envFile, getenv); stale {
441 for _, changedEnvironmentVariable := range changedEnvironmentVariableList {
442 ctx.Metrics.AddChangedEnvironmentVariable(changedEnvironmentVariable)
443 }
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200444 os.Remove(envFile)
445 }
446}
447
Kousik Kumarca390b22023-10-04 04:14:28 +0000448func updateSymlinks(ctx Context, dir, prevCWD, cwd string) error {
449 defer symlinkWg.Done()
450
451 visit := func(path string, d fs.DirEntry, err error) error {
452 if d.IsDir() && path != dir {
453 symlinkWg.Add(1)
454 go updateSymlinks(ctx, path, prevCWD, cwd)
455 return filepath.SkipDir
456 }
457 f, err := d.Info()
458 if err != nil {
459 return err
460 }
461 // If the file is not a symlink, we don't have to update it.
462 if f.Mode()&os.ModeSymlink != os.ModeSymlink {
463 return nil
464 }
465
466 atomic.AddUint32(&numFound, 1)
467 target, err := os.Readlink(path)
468 if err != nil {
469 return err
470 }
471 if strings.HasPrefix(target, prevCWD) &&
472 (len(target) == len(prevCWD) || target[len(prevCWD)] == '/') {
473 target = filepath.Join(cwd, target[len(prevCWD):])
474 if err := os.Remove(path); err != nil {
475 return err
476 }
477 if err := os.Symlink(target, path); err != nil {
478 return err
479 }
480 atomic.AddUint32(&numUpdated, 1)
481 }
482 return nil
483 }
484
485 if err := filepath.WalkDir(dir, visit); err != nil {
486 return err
487 }
488 return nil
489}
490
491func fixOutDirSymlinks(ctx Context, config Config, outDir string) error {
492 cwd, err := os.Getwd()
493 if err != nil {
494 return err
495 }
496
497 // Record the .top as the very last thing in the function.
498 tf := filepath.Join(outDir, ".top")
499 defer func() {
500 if err := os.WriteFile(tf, []byte(cwd), 0644); err != nil {
501 fmt.Fprintf(os.Stderr, fmt.Sprintf("Unable to log CWD: %v", err))
502 }
503 }()
504
505 // Find the previous working directory if it was recorded.
506 var prevCWD string
507 pcwd, err := os.ReadFile(tf)
508 if err != nil {
509 if os.IsNotExist(err) {
510 // No previous working directory recorded, nothing to do.
511 return nil
512 }
513 return err
514 }
515 prevCWD = strings.Trim(string(pcwd), "\n")
516
517 if prevCWD == cwd {
518 // We are in the same source dir, nothing to update.
519 return nil
520 }
521
522 symlinkWg.Add(1)
523 if err := updateSymlinks(ctx, outDir, prevCWD, cwd); err != nil {
524 return err
525 }
526 symlinkWg.Wait()
527 ctx.Println(fmt.Sprintf("Updated %d/%d symlinks in dir %v", numUpdated, numFound, outDir))
528 return nil
529}
530
531func migrateOutputSymlinks(ctx Context, config Config) error {
532 // Figure out the real out directory ("out" could be a symlink).
533 outDir := config.OutDir()
534 s, err := os.Lstat(outDir)
535 if err != nil {
536 if os.IsNotExist(err) {
537 // No out dir exists, no symlinks to migrate.
538 return nil
539 }
540 return err
541 }
542 if s.Mode()&os.ModeSymlink == os.ModeSymlink {
543 target, err := filepath.EvalSymlinks(outDir)
544 if err != nil {
545 return err
546 }
547 outDir = target
548 }
549 return fixOutDirSymlinks(ctx, config, outDir)
550}
551
Dan Willemsen1e704462016-08-21 15:17:17 -0700552func runSoong(ctx Context, config Config) {
Nan Zhang17f27672018-12-12 16:01:49 -0800553 ctx.BeginTrace(metrics.RunSoong, "soong")
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700554 defer ctx.EndTrace()
555
Kousik Kumarca390b22023-10-04 04:14:28 +0000556 if err := migrateOutputSymlinks(ctx, config); err != nil {
557 ctx.Fatalf("failed to migrate output directory to current TOP dir: %v", err)
558 }
559
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100560 // We have two environment files: .available is the one with every variable,
561 // .used with the ones that were actually used. The latter is used to
562 // determine whether Soong needs to be re-run since why re-run it if only
563 // unused variables were changed?
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200564 envFile := filepath.Join(config.SoongOutDir(), availableEnvFile)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100565
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100566 // This is done unconditionally, but does not take a measurable amount of time
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200567 bootstrapBlueprint(ctx, config)
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700568
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100569 soongBuildEnv := config.Environment().Copy()
570 soongBuildEnv.Set("TOP", os.Getenv("TOP"))
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500571 soongBuildEnv.Set("LOG_DIR", config.LogsDir())
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100572
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100573 // For Soong bootstrapping tests
574 if os.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
575 soongBuildEnv.Set("ALLOW_MISSING_DEPENDENCIES", "true")
576 }
577
Paul Duffin5e85c662021-03-05 12:26:14 +0000578 err := writeEnvironmentFile(ctx, envFile, soongBuildEnv.AsMap())
579 if err != nil {
580 ctx.Fatalf("failed to write environment file %s: %s", envFile, err)
581 }
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100582
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700583 func() {
Nan Zhang17f27672018-12-12 16:01:49 -0800584 ctx.BeginTrace(metrics.RunSoong, "environment check")
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700585 defer ctx.EndTrace()
586
Jason Wu2520f5e2023-05-30 19:45:36 -0400587 checkEnvironmentFile(ctx, soongBuildEnv, config.UsedEnvFile(soongBuildTag))
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200588
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200589 if config.JsonModuleGraph() {
Jason Wu2520f5e2023-05-30 19:45:36 -0400590 checkEnvironmentFile(ctx, soongBuildEnv, config.UsedEnvFile(jsonModuleGraphTag))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200591 }
592
593 if config.Queryview() {
Jason Wu2520f5e2023-05-30 19:45:36 -0400594 checkEnvironmentFile(ctx, soongBuildEnv, config.UsedEnvFile(queryviewTag))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200595 }
596
597 if config.SoongDocs() {
Jason Wu2520f5e2023-05-30 19:45:36 -0400598 checkEnvironmentFile(ctx, soongBuildEnv, config.UsedEnvFile(soongDocsTag))
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700599 }
600 }()
601
usta49012ee2023-05-22 16:33:27 -0400602 ninja := func(targets ...string) {
603 ctx.BeginTrace(metrics.RunSoong, "bootstrap")
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700604 defer ctx.EndTrace()
605
Dan Willemsenb82471a2018-05-17 16:37:09 -0700606 fifo := filepath.Join(config.OutDir(), ".ninja_fifo")
Colin Crossb98d3bc2019-03-21 16:02:58 -0700607 nr := status.NewNinjaReader(ctx, ctx.Status.StartTool(), fifo)
608 defer nr.Close()
Dan Willemsenb82471a2018-05-17 16:37:09 -0700609
LaMont Jonesece626c2024-09-03 11:19:31 -0700610 var ninjaCmd string
611 var ninjaArgs []string
612 switch config.ninjaCommand {
613 case NINJA_N2:
614 ninjaCmd = config.N2Bin()
Cole Faustbee030d2024-01-03 13:45:48 -0800615 ninjaArgs = []string{
616 // TODO: implement these features, or remove them.
617 //"-d", "keepdepfile",
618 //"-d", "stats",
619 //"-o", "usesphonyoutputs=yes",
620 //"-o", "preremoveoutputs=yes",
621 //"-w", "dupbuild=err",
622 //"-w", "outputdir=err",
623 //"-w", "missingoutfile=err",
624 "-v",
625 "-j", strconv.Itoa(config.Parallel()),
626 "--frontend-file", fifo,
627 "-f", filepath.Join(config.SoongOutDir(), "bootstrap.ninja"),
628 }
LaMont Jonesece626c2024-09-03 11:19:31 -0700629 case NINJA_SISO:
630 ninjaCmd = config.SisoBin()
631 ninjaArgs = []string{
632 "ninja",
633 // TODO: implement these features, or remove them.
634 //"-d", "keepdepfile",
635 //"-d", "stats",
636 //"-o", "usesphonyoutputs=yes",
637 //"-o", "preremoveoutputs=yes",
638 //"-w", "dupbuild=err",
639 //"-w", "outputdir=err",
640 //"-w", "missingoutfile=err",
641 "-v",
642 "-j", strconv.Itoa(config.Parallel()),
643 //"--frontend-file", fifo,
644 "--log_dir", config.SoongOutDir(),
645 "-f", filepath.Join(config.SoongOutDir(), "bootstrap.ninja"),
646 }
647 default:
648 // NINJA_NINJA is the default.
649 ninjaCmd = config.NinjaBin()
650 ninjaArgs = []string{
651 "-d", "keepdepfile",
652 "-d", "stats",
653 "-o", "usesphonyoutputs=yes",
654 "-o", "preremoveoutputs=yes",
655 "-w", "dupbuild=err",
656 "-w", "outputdir=err",
657 "-w", "missingoutfile=err",
658 "-j", strconv.Itoa(config.Parallel()),
659 "--frontend_file", fifo,
660 "-f", filepath.Join(config.SoongOutDir(), "bootstrap.ninja"),
661 }
Cole Faustbee030d2024-01-03 13:45:48 -0800662 }
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200663
Usta Shrestha8dc8b0a2022-08-10 17:39:37 -0400664 if extra, ok := config.Environment().Get("SOONG_UI_NINJA_ARGS"); ok {
665 ctx.Printf(`CAUTION: arguments in $SOONG_UI_NINJA_ARGS=%q, e.g. "-n", can make soong_build FAIL or INCORRECT`, extra)
666 ninjaArgs = append(ninjaArgs, strings.Fields(extra)...)
667 }
668
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200669 ninjaArgs = append(ninjaArgs, targets...)
Cole Faustbee030d2024-01-03 13:45:48 -0800670
usta49012ee2023-05-22 16:33:27 -0400671 cmd := Command(ctx, config, "soong bootstrap",
Cole Faustbee030d2024-01-03 13:45:48 -0800672 ninjaCmd, ninjaArgs...)
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500673
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100674 var ninjaEnv Environment
Lukacs T. Berki73ab9282021-03-10 10:48:39 +0100675
676 // This is currently how the command line to invoke soong_build finds the
677 // root of the source tree and the output root
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100678 ninjaEnv.Set("TOP", os.Getenv("TOP"))
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100679
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100680 cmd.Environment = &ninjaEnv
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700681 cmd.Sandbox = soongSandbox
Colin Cross7b97ecd2019-06-19 13:17:59 -0700682 cmd.RunAndStreamOrFatal()
Dan Willemsen1e704462016-08-21 15:17:17 -0700683 }
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200684
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200685 targets := make([]string, 0, 0)
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200686
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200687 if config.JsonModuleGraph() {
688 targets = append(targets, config.ModuleGraphFile())
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200689 }
690
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200691 if config.Queryview() {
692 targets = append(targets, config.QueryviewMarkerFile())
693 }
694
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200695 if config.SoongDocs() {
696 targets = append(targets, config.SoongDocsHtml())
697 }
698
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200699 if config.SoongBuildInvocationNeeded() {
700 // 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 -0700701 targets = append(targets, config.SoongNinjaFile())
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200702 }
703
Cole Faust2fec4122024-09-07 17:28:11 -0700704 for _, target := range targets {
705 if err := checkGlobs(ctx, target); err != nil {
706 ctx.Fatalf("Error checking globs: %s", err.Error())
707 }
708 }
709
Colin Crossaa9a2732023-10-27 10:54:27 -0700710 beforeSoongTimestamp := time.Now()
711
usta49012ee2023-05-22 16:33:27 -0400712 ninja(targets...)
Colin Crossb72c9092020-02-10 11:23:49 -0800713
Colin Crossaa9a2732023-10-27 10:54:27 -0700714 loadSoongBuildMetrics(ctx, config, beforeSoongTimestamp)
715
Yu Liu1b2ddc82024-05-15 19:28:56 +0000716 soongNinjaFile := config.SoongNinjaFile()
717 distGzipFile(ctx, config, soongNinjaFile, "soong")
718 for _, file := range blueprint.GetNinjaShardFiles(soongNinjaFile) {
719 if ok, _ := fileExists(file); ok {
720 distGzipFile(ctx, config, file, "soong")
721 }
722 }
Jihoon Kang9f4f8a32022-08-16 00:57:30 +0000723 distFile(ctx, config, config.SoongVarsFile(), "soong")
Inseob Kim58c802f2024-06-11 10:59:00 +0900724 distFile(ctx, config, config.SoongExtraVarsFile(), "soong")
Colin Cross8ba7d472020-06-25 11:27:52 -0700725
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000726 if !config.SkipKati() {
Colin Cross8ba7d472020-06-25 11:27:52 -0700727 distGzipFile(ctx, config, config.SoongAndroidMk(), "soong")
728 distGzipFile(ctx, config, config.SoongMakeVarsMk(), "soong")
729 }
730
Rob Seymour33cd10d2022-03-02 23:10:25 +0000731 if config.JsonModuleGraph() {
732 distGzipFile(ctx, config, config.ModuleGraphFile(), "soong")
733 }
Colin Crossb72c9092020-02-10 11:23:49 -0800734}
735
Cole Faust2fec4122024-09-07 17:28:11 -0700736// checkGlobs manages the globs that cause soong to rerun.
737//
738// When soong_build runs, it will run globs. It will write all the globs
739// it ran into the "{finalOutFile}.globs" file. Then every build,
740// soong_ui will check that file, rerun the globs, and if they changed
741// from the results that soong_build got, update the ".glob_results"
742// file, causing soong_build to rerun. The ".glob_results" file will
743// be empty on the first run of soong_build, because we don't know
744// what the globs are yet, but also remain empty until the globs change
745// so that we don't run soong_build a second time unnecessarily.
746// Both soong_build and soong_ui will also update a ".globs_time" file
747// with the time that they ran at every build. When soong_ui checks
748// globs, it only reruns globs whose dependencies are newer than the
749// time in the ".globs_time" file.
750func checkGlobs(ctx Context, finalOutFile string) error {
751 ctx.BeginTrace(metrics.RunSoong, "check_globs")
752 defer ctx.EndTrace()
753 st := ctx.Status.StartTool()
754 st.Status("Running globs...")
755 defer st.Finish()
756
757 globsFile, err := os.Open(finalOutFile + ".globs")
758 if errors.Is(err, fs.ErrNotExist) {
759 // if the glob file doesn't exist, make sure the glob_results file exists and is empty.
760 if err := os.MkdirAll(filepath.Dir(finalOutFile), 0777); err != nil {
761 return err
762 }
763 f, err := os.Create(finalOutFile + ".glob_results")
764 if err != nil {
765 return err
766 }
767 return f.Close()
768 } else if err != nil {
769 return err
770 }
771 defer globsFile.Close()
772 globsFileDecoder := json.NewDecoder(globsFile)
773
774 globsTimeBytes, err := os.ReadFile(finalOutFile + ".globs_time")
775 if err != nil {
776 return err
777 }
778 globsTimeMicros, err := strconv.ParseInt(strings.TrimSpace(string(globsTimeBytes)), 10, 64)
779 if err != nil {
780 return err
781 }
782 globCheckStartTime := time.Now().UnixMicro()
783
784 globsChan := make(chan pathtools.GlobResult)
785 errorsChan := make(chan error)
786 wg := sync.WaitGroup{}
Steven Moreland8e47abc2024-10-01 23:38:15 +0000787
Cole Faust2fec4122024-09-07 17:28:11 -0700788 hasChangedGlobs := false
Steven Moreland8e47abc2024-10-01 23:38:15 +0000789 var changedGlobNameMutex sync.Mutex
790 var changedGlobName string
791
Cole Faust2fec4122024-09-07 17:28:11 -0700792 for i := 0; i < runtime.NumCPU()*2; i++ {
793 wg.Add(1)
794 go func() {
795 for cachedGlob := range globsChan {
796 // If we've already determined we have changed globs, just finish consuming
797 // the channel without doing any more checks.
798 if hasChangedGlobs {
799 continue
800 }
801 // First, check if any of the deps are newer than the last time globs were checked.
802 // If not, we don't need to rerun the glob.
803 hasNewDep := false
804 for _, dep := range cachedGlob.Deps {
805 info, err := os.Stat(dep)
Colin Cross117af422024-09-25 09:14:21 -0700806 if errors.Is(err, fs.ErrNotExist) || errors.Is(err, syscall.ENOTDIR) {
Cole Faust69c78e92024-09-10 16:46:06 -0700807 hasNewDep = true
808 break
809 } else if err != nil {
Cole Faust2fec4122024-09-07 17:28:11 -0700810 errorsChan <- err
811 continue
812 }
813 if info.ModTime().UnixMicro() > globsTimeMicros {
814 hasNewDep = true
815 break
816 }
817 }
818 if !hasNewDep {
819 continue
820 }
821
822 // Then rerun the glob and check if we got the same result as before.
823 result, err := pathtools.Glob(cachedGlob.Pattern, cachedGlob.Excludes, pathtools.FollowSymlinks)
824 if err != nil {
825 errorsChan <- err
826 } else {
827 if !slices.Equal(result.Matches, cachedGlob.Matches) {
828 hasChangedGlobs = true
Steven Moreland8e47abc2024-10-01 23:38:15 +0000829
830 changedGlobNameMutex.Lock()
831 defer changedGlobNameMutex.Unlock()
832 changedGlobName = result.Pattern
833 if len(result.Excludes) > 0 {
834 changedGlobName += " (excluding " + strings.Join(result.Excludes, ", ") + ")"
835 }
Cole Faust2fec4122024-09-07 17:28:11 -0700836 }
837 }
838 }
839 wg.Done()
840 }()
841 }
842 go func() {
843 wg.Wait()
844 close(errorsChan)
845 }()
846
847 errorsWg := sync.WaitGroup{}
848 errorsWg.Add(1)
849 var errFromGoRoutines error
850 go func() {
851 for result := range errorsChan {
852 if errFromGoRoutines == nil {
853 errFromGoRoutines = result
854 }
855 }
856 errorsWg.Done()
857 }()
858
859 var cachedGlob pathtools.GlobResult
860 for globsFileDecoder.More() {
861 if err := globsFileDecoder.Decode(&cachedGlob); err != nil {
862 return err
863 }
864 // Need to clone the GlobResult because the json decoder will
865 // reuse the same slice allocations.
866 globsChan <- cachedGlob.Clone()
867 }
868 close(globsChan)
869 errorsWg.Wait()
870 if errFromGoRoutines != nil {
871 return errFromGoRoutines
872 }
873
874 // Update the globs_time file whether or not we found changed globs,
875 // so that we don't rerun globs in the future that we just saw didn't change.
876 err = os.WriteFile(
877 finalOutFile+".globs_time",
878 []byte(fmt.Sprintf("%d\n", globCheckStartTime)),
879 0666,
880 )
881 if err != nil {
882 return err
883 }
884
885 if hasChangedGlobs {
886 fmt.Fprintf(os.Stdout, "Globs changed, rerunning soong...\n")
Steven Moreland8e47abc2024-10-01 23:38:15 +0000887 fmt.Fprintf(os.Stdout, "One culprit glob (may be more): %s\n", changedGlobName)
Cole Faust2fec4122024-09-07 17:28:11 -0700888 // Write the current time to the glob_results file. We just need
889 // some unique value to trigger a rerun, it doesn't matter what it is.
890 err = os.WriteFile(
891 finalOutFile+".glob_results",
892 []byte(fmt.Sprintf("%d\n", globCheckStartTime)),
893 0666,
894 )
895 if err != nil {
896 return err
897 }
898 }
899 return nil
900}
901
Colin Crossaa9a2732023-10-27 10:54:27 -0700902// loadSoongBuildMetrics reads out/soong_build_metrics.pb if it was generated by soong_build and copies the
903// events stored in it into the soong_ui trace to provide introspection into how long the different phases of
904// soong_build are taking.
905func loadSoongBuildMetrics(ctx Context, config Config, oldTimestamp time.Time) {
906 soongBuildMetricsFile := config.SoongBuildMetrics()
907 if metricsStat, err := os.Stat(soongBuildMetricsFile); err != nil {
908 ctx.Verbosef("Failed to stat %s: %s", soongBuildMetricsFile, err)
909 return
910 } else if !metricsStat.ModTime().After(oldTimestamp) {
911 ctx.Verbosef("%s timestamp not later after running soong, expected %s > %s",
912 soongBuildMetricsFile, metricsStat.ModTime(), oldTimestamp)
913 return
914 }
915
Colin Crossb67b0612023-10-31 10:02:45 -0700916 metricsData, err := os.ReadFile(soongBuildMetricsFile)
Colin Crossaa9a2732023-10-27 10:54:27 -0700917 if err != nil {
918 ctx.Verbosef("Failed to read %s: %s", soongBuildMetricsFile, err)
919 return
920 }
921
922 soongBuildMetrics := metrics_proto.SoongBuildMetrics{}
923 err = proto.Unmarshal(metricsData, &soongBuildMetrics)
924 if err != nil {
925 ctx.Verbosef("Failed to unmarshal %s: %s", soongBuildMetricsFile, err)
926 return
927 }
928 for _, event := range soongBuildMetrics.Events {
929 desc := event.GetDescription()
930 if dot := strings.LastIndexByte(desc, '.'); dot >= 0 {
931 desc = desc[dot+1:]
932 }
933 ctx.Tracer.Complete(desc, ctx.Thread,
934 event.GetStartTime(), event.GetStartTime()+event.GetRealTime())
935 }
Colin Cross46b0c752023-10-27 14:56:12 -0700936 for _, event := range soongBuildMetrics.PerfCounters {
937 timestamp := event.GetTime()
938 for _, group := range event.Groups {
939 counters := make([]tracer.Counter, 0, len(group.Counters))
940 for _, counter := range group.Counters {
941 counters = append(counters, tracer.Counter{
942 Name: counter.GetName(),
943 Value: counter.GetValue(),
944 })
945 }
946 ctx.Tracer.CountersAtTime(group.GetName(), ctx.Thread, timestamp, counters)
947 }
948 }
Colin Crossaa9a2732023-10-27 10:54:27 -0700949}
950
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100951func runMicrofactory(ctx Context, config Config, name string, pkg string, mapping map[string]string) {
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700952 ctx.BeginTrace(metrics.RunSoong, name)
953 defer ctx.EndTrace()
954 cfg := microfactory.Config{TrimPath: absPath(ctx, ".")}
955 for pkgPrefix, pathPrefix := range mapping {
956 cfg.Map(pkgPrefix, pathPrefix)
957 }
958
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100959 exePath := filepath.Join(config.SoongOutDir(), name)
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700960 dir := filepath.Dir(exePath)
961 if err := os.MkdirAll(dir, 0777); err != nil {
962 ctx.Fatalf("cannot create %s: %s", dir, err)
963 }
964 if _, err := microfactory.Build(&cfg, exePath, pkg); err != nil {
965 ctx.Fatalf("failed to build %s: %s", name, err)
966 }
967}