blob: eb51022af4f7689db20d2db2d87ba7e978f4b998 [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 Crossaa9a2732023-10-27 10:54:27 -070030 "time"
Dan Willemsen99a75cd2017-08-04 16:04:04 -070031
Yu Liu1b2ddc82024-05-15 19:28:56 +000032 "android/soong/ui/tracer"
33
Dan Willemsen4591b642021-05-24 14:24:12 -070034 "android/soong/ui/metrics"
Colin Crossaa9a2732023-10-27 10:54:27 -070035 "android/soong/ui/metrics/metrics_proto"
Dan Willemsen4591b642021-05-24 14:24:12 -070036 "android/soong/ui/status"
37
38 "android/soong/shared"
39
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010040 "github.com/google/blueprint"
41 "github.com/google/blueprint/bootstrap"
Dan Willemsen99a75cd2017-08-04 16:04:04 -070042 "github.com/google/blueprint/microfactory"
Cole Faust8c0b11e2024-01-02 17:02:52 -080043 "github.com/google/blueprint/pathtools"
Colin Crossaa9a2732023-10-27 10:54:27 -070044
45 "google.golang.org/protobuf/proto"
Dan Willemsen1e704462016-08-21 15:17:17 -070046)
47
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020048const (
49 availableEnvFile = "soong.environment.available"
50 usedEnvFile = "soong.environment.used"
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +020051
Colin Cross8d411ff2023-12-07 10:31:24 -080052 soongBuildTag = "build"
53 jsonModuleGraphTag = "modulegraph"
54 queryviewTag = "queryview"
55 soongDocsTag = "soong_docs"
Colin Cross9191df22021-10-29 13:11:32 -070056
57 // bootstrapEpoch is used to determine if an incremental build is incompatible with the current
58 // version of bootstrap and needs cleaning before continuing the build. Increment this for
Cole Faust2fec4122024-09-07 17:28:11 -070059 // incompatible changes, for example when moving the location of a microfactory binary that is
Colin Cross9191df22021-10-29 13:11:32 -070060 // executed during bootstrap before the primary builder has had a chance to update the path.
Lukacs T. Berki9985d9a2021-11-04 11:47:42 +010061 bootstrapEpoch = 1
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020062)
63
Kousik Kumarca390b22023-10-04 04:14:28 +000064var (
65 // Used during parallel update of symlinks in out directory to reflect new
66 // TOP dir.
67 symlinkWg sync.WaitGroup
68 numFound, numUpdated uint32
69)
70
Sasha Smundak4cbe83a2022-11-28 17:02:40 -080071func writeEnvironmentFile(_ Context, envFile string, envDeps map[string]string) error {
Lukacs T. Berki7690c092021-02-26 14:27:36 +010072 data, err := shared.EnvFileContents(envDeps)
73 if err != nil {
74 return err
75 }
76
Sasha Smundak4cbe83a2022-11-28 17:02:40 -080077 return os.WriteFile(envFile, data, 0644)
Lukacs T. Berki7690c092021-02-26 14:27:36 +010078}
79
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000080// This uses Android.bp files and various tools to generate <builddir>/build.ninja.
81//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010082// However, the execution of <builddir>/build.ninja happens later in
83// build/soong/ui/build/build.go#Build()
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000084//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010085// We want to rely on as few prebuilts as possible, so we need to bootstrap
86// Soong. The process is as follows:
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000087//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010088// 1. We use "Microfactory", a simple tool to compile Go code, to build
89// first itself, then soong_ui from soong_ui.bash. This binary contains
90// parts of soong_build that are needed to build itself.
91// 2. This simplified version of soong_build then reads the Blueprint files
92// that describe itself and emits .bootstrap/build.ninja that describes
93// how to build its full version and use that to produce the final Ninja
94// file Soong emits.
95// 3. soong_ui executes .bootstrap/build.ninja
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000096//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010097// (After this, Kati is executed to parse the Makefiles, but that's not part of
98// bootstrapping Soong)
99
100// A tiny struct used to tell Blueprint that it's in bootstrap mode. It would
101// probably be nicer to use a flag in bootstrap.Args instead.
102type BlueprintConfig struct {
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +0200103 toolDir string
104 soongOutDir string
105 outDir string
106 runGoTests bool
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +0200107 debugCompilation bool
108 subninjas []string
109 primaryBuilderInvocations []bootstrap.PrimaryBuilderInvocation
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100110}
111
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200112func (c BlueprintConfig) HostToolDir() string {
113 return c.toolDir
114}
115
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200116func (c BlueprintConfig) SoongOutDir() string {
117 return c.soongOutDir
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100118}
119
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200120func (c BlueprintConfig) OutDir() string {
121 return c.outDir
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100122}
123
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +0200124func (c BlueprintConfig) RunGoTests() bool {
125 return c.runGoTests
126}
127
Lukacs T. Berki5f6cb1d2021-03-17 15:03:14 +0100128func (c BlueprintConfig) DebugCompilation() bool {
129 return c.debugCompilation
130}
131
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +0200132func (c BlueprintConfig) Subninjas() []string {
133 return c.subninjas
134}
135
136func (c BlueprintConfig) PrimaryBuilderInvocations() []bootstrap.PrimaryBuilderInvocation {
137 return c.primaryBuilderInvocations
138}
139
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200140func environmentArgs(config Config, tag string) []string {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200141 return []string{
142 "--available_env", shared.JoinPath(config.SoongOutDir(), availableEnvFile),
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200143 "--used_env", config.UsedEnvFile(tag),
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200144 }
145}
Spandan Das8f99ae62021-06-11 16:48:06 +0000146
Colin Cross9191df22021-10-29 13:11:32 -0700147func writeEmptyFile(ctx Context, path string) {
Spandan Das8f99ae62021-06-11 16:48:06 +0000148 err := os.MkdirAll(filepath.Dir(path), 0777)
149 if err != nil {
Colin Cross9191df22021-10-29 13:11:32 -0700150 ctx.Fatalf("Failed to create parent directories of empty file '%s': %s", path, err)
Spandan Das8f99ae62021-06-11 16:48:06 +0000151 }
152
Colin Cross9191df22021-10-29 13:11:32 -0700153 if exists, err := fileExists(path); err != nil {
154 ctx.Fatalf("Failed to check if file '%s' exists: %s", path, err)
155 } else if !exists {
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800156 err = os.WriteFile(path, nil, 0666)
Spandan Das8f99ae62021-06-11 16:48:06 +0000157 if err != nil {
Colin Cross9191df22021-10-29 13:11:32 -0700158 ctx.Fatalf("Failed to create empty file '%s': %s", path, err)
Spandan Das8f99ae62021-06-11 16:48:06 +0000159 }
160 }
161}
162
Colin Cross9191df22021-10-29 13:11:32 -0700163func fileExists(path string) (bool, error) {
164 if _, err := os.Stat(path); os.IsNotExist(err) {
165 return false, nil
166 } else if err != nil {
167 return false, err
168 }
169 return true, nil
170}
171
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800172type PrimaryBuilderFactory struct {
173 name string
174 description string
175 config Config
176 output string
177 specificArgs []string
178 debugPort string
179}
180
Jeongik Chaccf37002023-08-04 01:46:32 +0900181func getGlobPathName(config Config) string {
182 globPathName, ok := config.TargetProductOrErr()
183 if ok != nil {
184 globPathName = soongBuildTag
185 }
186 return globPathName
187}
188
Cole Faust8c0b11e2024-01-02 17:02:52 -0800189func getGlobPathNameFromPrimaryBuilderFactory(config Config, pb PrimaryBuilderFactory) string {
190 if pb.name == soongBuildTag {
191 // Glob path for soong build would be separated per product target
192 return getGlobPathName(config)
193 }
194 return pb.name
195}
196
197func (pb PrimaryBuilderFactory) primaryBuilderInvocation(config Config) bootstrap.PrimaryBuilderInvocation {
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200198 commonArgs := make([]string, 0, 0)
199
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800200 if !pb.config.skipSoongTests {
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200201 commonArgs = append(commonArgs, "-t")
202 }
203
Jihoon Kang2a929ad2023-06-08 19:02:07 +0000204 if pb.config.buildFromSourceStub {
205 commonArgs = append(commonArgs, "--build-from-source-stub")
Jihoon Kang1bff0342023-01-17 20:40:22 +0000206 }
LaMont Jones52a72432023-03-09 18:19:35 +0000207
Joe Onoratoe5ed3472024-02-02 14:52:05 -0800208 if pb.config.moduleDebugFile != "" {
209 commonArgs = append(commonArgs, "--soong_module_debug")
210 commonArgs = append(commonArgs, pb.config.moduleDebugFile)
211 }
212
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800213 commonArgs = append(commonArgs, "-l", filepath.Join(pb.config.FileListDir(), "Android.bp.list"))
Lukacs T. Berki13644272022-01-05 10:29:56 +0100214 invocationEnv := make(map[string]string)
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800215 if pb.debugPort != "" {
ustafb67fd12022-08-19 19:26:00 -0400216 //debug mode
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800217 commonArgs = append(commonArgs, "--delve_listen", pb.debugPort,
218 "--delve_path", shared.ResolveDelveBinary())
Lukacs T. Berki13644272022-01-05 10:29:56 +0100219 // GODEBUG=asyncpreemptoff=1 disables the preemption of goroutines. This
220 // is useful because the preemption happens by sending SIGURG to the OS
221 // thread hosting the goroutine in question and each signal results in
222 // work that needs to be done by Delve; it uses ptrace to debug the Go
223 // process and the tracer process must deal with every signal (it is not
224 // possible to selectively ignore SIGURG). This makes debugging slower,
225 // sometimes by an order of magnitude depending on luck.
226 // The original reason for adding async preemption to Go is here:
227 // https://github.com/golang/proposal/blob/master/design/24543-non-cooperative-preemption.md
228 invocationEnv["GODEBUG"] = "asyncpreemptoff=1"
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200229 }
230
ustafb67fd12022-08-19 19:26:00 -0400231 var allArgs []string
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800232 allArgs = append(allArgs, pb.specificArgs...)
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
244 return bootstrap.PrimaryBuilderInvocation{
Cole Faust2fec4122024-09-07 17:28:11 -0700245 Implicits: []string{pb.output + ".glob_results"},
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800246 Outputs: []string{pb.output},
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000247 Args: allArgs,
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800248 Description: pb.description,
Lukacs T. Berki2fad3412022-01-04 14:40:13 +0100249 // NB: Changing the value of this environment variable will not result in a
250 // rebuild. The bootstrap Ninja file will change, but apparently Ninja does
251 // not consider changing the pool specified in a statement a change that's
252 // worth rebuilding for.
253 Console: os.Getenv("SOONG_UNBUFFERED_OUTPUT") == "1",
Lukacs T. Berki13644272022-01-05 10:29:56 +0100254 Env: invocationEnv,
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200255 }
256}
257
Colin Cross9191df22021-10-29 13:11:32 -0700258// bootstrapEpochCleanup deletes files used by bootstrap during incremental builds across
259// incompatible changes. Incompatible changes are marked by incrementing the bootstrapEpoch
260// constant. A tree is considered out of date for the current epoch of the
261// .soong.bootstrap.epoch.<epoch> file doesn't exist.
262func bootstrapEpochCleanup(ctx Context, config Config) {
263 epochFile := fmt.Sprintf(".soong.bootstrap.epoch.%d", bootstrapEpoch)
264 epochPath := filepath.Join(config.SoongOutDir(), epochFile)
265 if exists, err := fileExists(epochPath); err != nil {
266 ctx.Fatalf("failed to check if bootstrap epoch file %q exists: %q", epochPath, err)
267 } else if !exists {
268 // The tree is out of date for the current epoch, delete files used by bootstrap
269 // and force the primary builder to rerun.
Yu Liu1b2ddc82024-05-15 19:28:56 +0000270 soongNinjaFile := config.SoongNinjaFile()
271 os.Remove(soongNinjaFile)
272 for _, file := range blueprint.GetNinjaShardFiles(soongNinjaFile) {
273 if ok, _ := fileExists(file); ok {
274 os.Remove(file)
275 }
276 }
Cole Faust2fec4122024-09-07 17:28:11 -0700277 os.Remove(soongNinjaFile + ".globs")
278 os.Remove(soongNinjaFile + ".globs_time")
279 os.Remove(soongNinjaFile + ".glob_results")
Colin Cross9191df22021-10-29 13:11:32 -0700280
281 // Mark the tree as up to date with the current epoch by writing the epoch marker file.
282 writeEmptyFile(ctx, epochPath)
283 }
284}
285
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200286func bootstrapBlueprint(ctx Context, config Config) {
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100287 ctx.BeginTrace(metrics.RunSoong, "blueprint bootstrap")
288 defer ctx.EndTrace()
289
Colin Cross9191df22021-10-29 13:11:32 -0700290 // Clean up some files for incremental builds across incompatible changes.
291 bootstrapEpochCleanup(ctx, config)
292
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900293 baseArgs := []string{"--soong_variables", config.SoongVarsFile()}
294
295 mainSoongBuildExtraArgs := append(baseArgs, "-o", config.SoongNinjaFile())
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200296 if config.EmptyNinjaFile() {
297 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--empty-ninja-file")
Lukacs T. Berki745380c2021-04-12 12:07:44 +0200298 }
Jihoon Kang2a929ad2023-06-08 19:02:07 +0000299 if config.buildFromSourceStub {
300 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--build-from-source-stub")
Jihoon Kang1bff0342023-01-17 20:40:22 +0000301 }
MarkDacekf47e1422023-04-19 16:47:36 +0000302 if config.ensureAllowlistIntegrity {
303 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--ensure-allowlist-integrity")
304 }
Yu Liufa297642024-06-11 00:13:02 +0000305 if config.incrementalBuildActions {
306 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--incremental-build-actions")
307 }
MarkDacekd06db5d2022-11-29 00:47:59 +0000308
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000309 queryviewDir := filepath.Join(config.SoongOutDir(), "queryview")
Spandan Das5af0bd32022-09-28 20:43:08 +0000310
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800311 pbfs := []PrimaryBuilderFactory{
312 {
313 name: soongBuildTag,
314 description: fmt.Sprintf("analyzing Android.bp files and generating ninja file at %s", config.SoongNinjaFile()),
315 config: config,
316 output: config.SoongNinjaFile(),
317 specificArgs: mainSoongBuildExtraArgs,
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000318 },
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800319 {
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800320 name: jsonModuleGraphTag,
321 description: fmt.Sprintf("generating the Soong module graph at %s", config.ModuleGraphFile()),
322 config: config,
323 output: config.ModuleGraphFile(),
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900324 specificArgs: append(baseArgs,
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800325 "--module_graph_file", config.ModuleGraphFile(),
326 "--module_actions_file", config.ModuleActionsFile(),
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900327 ),
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800328 },
329 {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900330 name: queryviewTag,
331 description: fmt.Sprintf("generating the Soong module graph as a Bazel workspace at %s", queryviewDir),
332 config: config,
333 output: config.QueryviewMarkerFile(),
334 specificArgs: append(baseArgs,
335 "--bazel_queryview_dir", queryviewDir,
336 ),
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800337 },
338 {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900339 name: soongDocsTag,
340 description: fmt.Sprintf("generating Soong docs at %s", config.SoongDocsHtml()),
341 config: config,
342 output: config.SoongDocsHtml(),
343 specificArgs: append(baseArgs,
344 "--soong_docs", config.SoongDocsHtml(),
345 ),
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800346 },
347 }
348
349 // Figure out which invocations will be run under the debugger:
350 // * SOONG_DELVE if set specifies listening port
351 // * SOONG_DELVE_STEPS if set specifies specific invocations to be debugged, otherwise all are
352 debuggedInvocations := make(map[string]bool)
353 delvePort := os.Getenv("SOONG_DELVE")
354 if delvePort != "" {
355 if steps := os.Getenv("SOONG_DELVE_STEPS"); steps != "" {
356 var validSteps []string
357 for _, pbf := range pbfs {
358 debuggedInvocations[pbf.name] = false
359 validSteps = append(validSteps, pbf.name)
360
361 }
362 for _, step := range strings.Split(steps, ",") {
363 if _, ok := debuggedInvocations[step]; ok {
364 debuggedInvocations[step] = true
365 } else {
366 ctx.Fatalf("SOONG_DELVE_STEPS contains unknown soong_build step %s\n"+
367 "Valid steps are %v", step, validSteps)
368 }
369 }
370 } else {
371 // SOONG_DELVE_STEPS is not set, run all steps in the debugger
372 for _, pbf := range pbfs {
373 debuggedInvocations[pbf.name] = true
374 }
375 }
376 }
377
378 var invocations []bootstrap.PrimaryBuilderInvocation
379 for _, pbf := range pbfs {
380 if debuggedInvocations[pbf.name] {
381 pbf.debugPort = delvePort
382 }
Cole Faust8c0b11e2024-01-02 17:02:52 -0800383 pbi := pbf.primaryBuilderInvocation(config)
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800384 invocations = append(invocations, pbi)
385 }
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200386
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800387 blueprintArgs := bootstrap.Args{
388 ModuleListFile: filepath.Join(config.FileListDir(), "Android.bp.list"),
389 OutFile: shared.JoinPath(config.SoongOutDir(), "bootstrap.ninja"),
390 EmptyNinjaFile: false,
391 }
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200392
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100393 blueprintCtx := blueprint.NewContext()
Sam Delmerico98a73292023-02-21 11:50:29 -0500394 blueprintCtx.AddSourceRootDirs(config.GetSourceRootDirs()...)
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100395 blueprintCtx.SetIgnoreUnknownModuleTypes(true)
396 blueprintConfig := BlueprintConfig{
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200397 soongOutDir: config.SoongOutDir(),
398 toolDir: config.HostToolDir(),
399 outDir: config.OutDir(),
400 runGoTests: !config.skipSoongTests,
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200401 // If we want to debug soong_build, we need to compile it for debugging
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800402 debugCompilation: delvePort != "",
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800403 primaryBuilderInvocations: invocations,
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100404 }
405
usta5bb4a5d2022-08-24 12:53:46 -0400406 // since `bootstrap.ninja` is regenerated unconditionally, we ignore the deps, i.e. little
407 // reason to write a `bootstrap.ninja.d` file
Lukacs T. Berkic357c812023-06-20 09:30:06 +0000408 _, err := bootstrap.RunBlueprint(blueprintArgs, bootstrap.DoEverything, blueprintCtx, blueprintConfig)
409 if err != nil {
410 ctx.Fatal(err)
411 }
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100412}
413
Jason Wu2520f5e2023-05-30 19:45:36 -0400414func checkEnvironmentFile(ctx Context, currentEnv *Environment, envFile string) {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200415 getenv := func(k string) string {
416 v, _ := currentEnv.Get(k)
417 return v
418 }
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200419
Jason Wu2520f5e2023-05-30 19:45:36 -0400420 // Log the changed environment variables to ChangedEnvironmentVariable field
421 if stale, changedEnvironmentVariableList, _ := shared.StaleEnvFile(envFile, getenv); stale {
422 for _, changedEnvironmentVariable := range changedEnvironmentVariableList {
423 ctx.Metrics.AddChangedEnvironmentVariable(changedEnvironmentVariable)
424 }
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200425 os.Remove(envFile)
426 }
427}
428
Kousik Kumarca390b22023-10-04 04:14:28 +0000429func updateSymlinks(ctx Context, dir, prevCWD, cwd string) error {
430 defer symlinkWg.Done()
431
432 visit := func(path string, d fs.DirEntry, err error) error {
433 if d.IsDir() && path != dir {
434 symlinkWg.Add(1)
435 go updateSymlinks(ctx, path, prevCWD, cwd)
436 return filepath.SkipDir
437 }
438 f, err := d.Info()
439 if err != nil {
440 return err
441 }
442 // If the file is not a symlink, we don't have to update it.
443 if f.Mode()&os.ModeSymlink != os.ModeSymlink {
444 return nil
445 }
446
447 atomic.AddUint32(&numFound, 1)
448 target, err := os.Readlink(path)
449 if err != nil {
450 return err
451 }
452 if strings.HasPrefix(target, prevCWD) &&
453 (len(target) == len(prevCWD) || target[len(prevCWD)] == '/') {
454 target = filepath.Join(cwd, target[len(prevCWD):])
455 if err := os.Remove(path); err != nil {
456 return err
457 }
458 if err := os.Symlink(target, path); err != nil {
459 return err
460 }
461 atomic.AddUint32(&numUpdated, 1)
462 }
463 return nil
464 }
465
466 if err := filepath.WalkDir(dir, visit); err != nil {
467 return err
468 }
469 return nil
470}
471
472func fixOutDirSymlinks(ctx Context, config Config, outDir string) error {
473 cwd, err := os.Getwd()
474 if err != nil {
475 return err
476 }
477
478 // Record the .top as the very last thing in the function.
479 tf := filepath.Join(outDir, ".top")
480 defer func() {
481 if err := os.WriteFile(tf, []byte(cwd), 0644); err != nil {
482 fmt.Fprintf(os.Stderr, fmt.Sprintf("Unable to log CWD: %v", err))
483 }
484 }()
485
486 // Find the previous working directory if it was recorded.
487 var prevCWD string
488 pcwd, err := os.ReadFile(tf)
489 if err != nil {
490 if os.IsNotExist(err) {
491 // No previous working directory recorded, nothing to do.
492 return nil
493 }
494 return err
495 }
496 prevCWD = strings.Trim(string(pcwd), "\n")
497
498 if prevCWD == cwd {
499 // We are in the same source dir, nothing to update.
500 return nil
501 }
502
503 symlinkWg.Add(1)
504 if err := updateSymlinks(ctx, outDir, prevCWD, cwd); err != nil {
505 return err
506 }
507 symlinkWg.Wait()
508 ctx.Println(fmt.Sprintf("Updated %d/%d symlinks in dir %v", numUpdated, numFound, outDir))
509 return nil
510}
511
512func migrateOutputSymlinks(ctx Context, config Config) error {
513 // Figure out the real out directory ("out" could be a symlink).
514 outDir := config.OutDir()
515 s, err := os.Lstat(outDir)
516 if err != nil {
517 if os.IsNotExist(err) {
518 // No out dir exists, no symlinks to migrate.
519 return nil
520 }
521 return err
522 }
523 if s.Mode()&os.ModeSymlink == os.ModeSymlink {
524 target, err := filepath.EvalSymlinks(outDir)
525 if err != nil {
526 return err
527 }
528 outDir = target
529 }
530 return fixOutDirSymlinks(ctx, config, outDir)
531}
532
Dan Willemsen1e704462016-08-21 15:17:17 -0700533func runSoong(ctx Context, config Config) {
Nan Zhang17f27672018-12-12 16:01:49 -0800534 ctx.BeginTrace(metrics.RunSoong, "soong")
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700535 defer ctx.EndTrace()
536
Kousik Kumarca390b22023-10-04 04:14:28 +0000537 if err := migrateOutputSymlinks(ctx, config); err != nil {
538 ctx.Fatalf("failed to migrate output directory to current TOP dir: %v", err)
539 }
540
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100541 // We have two environment files: .available is the one with every variable,
542 // .used with the ones that were actually used. The latter is used to
543 // determine whether Soong needs to be re-run since why re-run it if only
544 // unused variables were changed?
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200545 envFile := filepath.Join(config.SoongOutDir(), availableEnvFile)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100546
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100547 // This is done unconditionally, but does not take a measurable amount of time
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200548 bootstrapBlueprint(ctx, config)
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700549
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100550 soongBuildEnv := config.Environment().Copy()
551 soongBuildEnv.Set("TOP", os.Getenv("TOP"))
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500552 soongBuildEnv.Set("LOG_DIR", config.LogsDir())
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100553
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100554 // For Soong bootstrapping tests
555 if os.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
556 soongBuildEnv.Set("ALLOW_MISSING_DEPENDENCIES", "true")
557 }
558
Paul Duffin5e85c662021-03-05 12:26:14 +0000559 err := writeEnvironmentFile(ctx, envFile, soongBuildEnv.AsMap())
560 if err != nil {
561 ctx.Fatalf("failed to write environment file %s: %s", envFile, err)
562 }
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100563
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700564 func() {
Nan Zhang17f27672018-12-12 16:01:49 -0800565 ctx.BeginTrace(metrics.RunSoong, "environment check")
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700566 defer ctx.EndTrace()
567
Jason Wu2520f5e2023-05-30 19:45:36 -0400568 checkEnvironmentFile(ctx, soongBuildEnv, config.UsedEnvFile(soongBuildTag))
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200569
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200570 if config.JsonModuleGraph() {
Jason Wu2520f5e2023-05-30 19:45:36 -0400571 checkEnvironmentFile(ctx, soongBuildEnv, config.UsedEnvFile(jsonModuleGraphTag))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200572 }
573
574 if config.Queryview() {
Jason Wu2520f5e2023-05-30 19:45:36 -0400575 checkEnvironmentFile(ctx, soongBuildEnv, config.UsedEnvFile(queryviewTag))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200576 }
577
578 if config.SoongDocs() {
Jason Wu2520f5e2023-05-30 19:45:36 -0400579 checkEnvironmentFile(ctx, soongBuildEnv, config.UsedEnvFile(soongDocsTag))
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700580 }
581 }()
582
usta49012ee2023-05-22 16:33:27 -0400583 ninja := func(targets ...string) {
584 ctx.BeginTrace(metrics.RunSoong, "bootstrap")
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700585 defer ctx.EndTrace()
586
Dan Willemsenb82471a2018-05-17 16:37:09 -0700587 fifo := filepath.Join(config.OutDir(), ".ninja_fifo")
Colin Crossb98d3bc2019-03-21 16:02:58 -0700588 nr := status.NewNinjaReader(ctx, ctx.Status.StartTool(), fifo)
589 defer nr.Close()
Dan Willemsenb82471a2018-05-17 16:37:09 -0700590
LaMont Jonesece626c2024-09-03 11:19:31 -0700591 var ninjaCmd string
592 var ninjaArgs []string
593 switch config.ninjaCommand {
594 case NINJA_N2:
595 ninjaCmd = config.N2Bin()
Cole Faustbee030d2024-01-03 13:45:48 -0800596 ninjaArgs = []string{
597 // TODO: implement these features, or remove them.
598 //"-d", "keepdepfile",
599 //"-d", "stats",
600 //"-o", "usesphonyoutputs=yes",
601 //"-o", "preremoveoutputs=yes",
602 //"-w", "dupbuild=err",
603 //"-w", "outputdir=err",
604 //"-w", "missingoutfile=err",
605 "-v",
606 "-j", strconv.Itoa(config.Parallel()),
607 "--frontend-file", fifo,
608 "-f", filepath.Join(config.SoongOutDir(), "bootstrap.ninja"),
609 }
LaMont Jonesece626c2024-09-03 11:19:31 -0700610 case NINJA_SISO:
611 ninjaCmd = config.SisoBin()
612 ninjaArgs = []string{
613 "ninja",
614 // TODO: implement these features, or remove them.
615 //"-d", "keepdepfile",
616 //"-d", "stats",
617 //"-o", "usesphonyoutputs=yes",
618 //"-o", "preremoveoutputs=yes",
619 //"-w", "dupbuild=err",
620 //"-w", "outputdir=err",
621 //"-w", "missingoutfile=err",
622 "-v",
623 "-j", strconv.Itoa(config.Parallel()),
624 //"--frontend-file", fifo,
625 "--log_dir", config.SoongOutDir(),
626 "-f", filepath.Join(config.SoongOutDir(), "bootstrap.ninja"),
627 }
628 default:
629 // NINJA_NINJA is the default.
630 ninjaCmd = config.NinjaBin()
631 ninjaArgs = []string{
632 "-d", "keepdepfile",
633 "-d", "stats",
634 "-o", "usesphonyoutputs=yes",
635 "-o", "preremoveoutputs=yes",
636 "-w", "dupbuild=err",
637 "-w", "outputdir=err",
638 "-w", "missingoutfile=err",
639 "-j", strconv.Itoa(config.Parallel()),
640 "--frontend_file", fifo,
641 "-f", filepath.Join(config.SoongOutDir(), "bootstrap.ninja"),
642 }
Cole Faustbee030d2024-01-03 13:45:48 -0800643 }
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200644
Usta Shrestha8dc8b0a2022-08-10 17:39:37 -0400645 if extra, ok := config.Environment().Get("SOONG_UI_NINJA_ARGS"); ok {
646 ctx.Printf(`CAUTION: arguments in $SOONG_UI_NINJA_ARGS=%q, e.g. "-n", can make soong_build FAIL or INCORRECT`, extra)
647 ninjaArgs = append(ninjaArgs, strings.Fields(extra)...)
648 }
649
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200650 ninjaArgs = append(ninjaArgs, targets...)
Cole Faustbee030d2024-01-03 13:45:48 -0800651
usta49012ee2023-05-22 16:33:27 -0400652 cmd := Command(ctx, config, "soong bootstrap",
Cole Faustbee030d2024-01-03 13:45:48 -0800653 ninjaCmd, ninjaArgs...)
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500654
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100655 var ninjaEnv Environment
Lukacs T. Berki73ab9282021-03-10 10:48:39 +0100656
657 // This is currently how the command line to invoke soong_build finds the
658 // root of the source tree and the output root
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100659 ninjaEnv.Set("TOP", os.Getenv("TOP"))
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100660
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100661 cmd.Environment = &ninjaEnv
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700662 cmd.Sandbox = soongSandbox
Colin Cross7b97ecd2019-06-19 13:17:59 -0700663 cmd.RunAndStreamOrFatal()
Dan Willemsen1e704462016-08-21 15:17:17 -0700664 }
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200665
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200666 targets := make([]string, 0, 0)
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200667
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200668 if config.JsonModuleGraph() {
669 targets = append(targets, config.ModuleGraphFile())
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200670 }
671
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200672 if config.Queryview() {
673 targets = append(targets, config.QueryviewMarkerFile())
674 }
675
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200676 if config.SoongDocs() {
677 targets = append(targets, config.SoongDocsHtml())
678 }
679
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200680 if config.SoongBuildInvocationNeeded() {
681 // 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 -0700682 targets = append(targets, config.SoongNinjaFile())
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200683 }
684
Cole Faust2fec4122024-09-07 17:28:11 -0700685 for _, target := range targets {
686 if err := checkGlobs(ctx, target); err != nil {
687 ctx.Fatalf("Error checking globs: %s", err.Error())
688 }
689 }
690
Colin Crossaa9a2732023-10-27 10:54:27 -0700691 beforeSoongTimestamp := time.Now()
692
usta49012ee2023-05-22 16:33:27 -0400693 ninja(targets...)
Colin Crossb72c9092020-02-10 11:23:49 -0800694
Colin Crossaa9a2732023-10-27 10:54:27 -0700695 loadSoongBuildMetrics(ctx, config, beforeSoongTimestamp)
696
Yu Liu1b2ddc82024-05-15 19:28:56 +0000697 soongNinjaFile := config.SoongNinjaFile()
698 distGzipFile(ctx, config, soongNinjaFile, "soong")
699 for _, file := range blueprint.GetNinjaShardFiles(soongNinjaFile) {
700 if ok, _ := fileExists(file); ok {
701 distGzipFile(ctx, config, file, "soong")
702 }
703 }
Jihoon Kang9f4f8a32022-08-16 00:57:30 +0000704 distFile(ctx, config, config.SoongVarsFile(), "soong")
Inseob Kim58c802f2024-06-11 10:59:00 +0900705 distFile(ctx, config, config.SoongExtraVarsFile(), "soong")
Colin Cross8ba7d472020-06-25 11:27:52 -0700706
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000707 if !config.SkipKati() {
Colin Cross8ba7d472020-06-25 11:27:52 -0700708 distGzipFile(ctx, config, config.SoongAndroidMk(), "soong")
709 distGzipFile(ctx, config, config.SoongMakeVarsMk(), "soong")
710 }
711
Rob Seymour33cd10d2022-03-02 23:10:25 +0000712 if config.JsonModuleGraph() {
713 distGzipFile(ctx, config, config.ModuleGraphFile(), "soong")
714 }
Colin Crossb72c9092020-02-10 11:23:49 -0800715}
716
Cole Faust2fec4122024-09-07 17:28:11 -0700717// checkGlobs manages the globs that cause soong to rerun.
718//
719// When soong_build runs, it will run globs. It will write all the globs
720// it ran into the "{finalOutFile}.globs" file. Then every build,
721// soong_ui will check that file, rerun the globs, and if they changed
722// from the results that soong_build got, update the ".glob_results"
723// file, causing soong_build to rerun. The ".glob_results" file will
724// be empty on the first run of soong_build, because we don't know
725// what the globs are yet, but also remain empty until the globs change
726// so that we don't run soong_build a second time unnecessarily.
727// Both soong_build and soong_ui will also update a ".globs_time" file
728// with the time that they ran at every build. When soong_ui checks
729// globs, it only reruns globs whose dependencies are newer than the
730// time in the ".globs_time" file.
731func checkGlobs(ctx Context, finalOutFile string) error {
732 ctx.BeginTrace(metrics.RunSoong, "check_globs")
733 defer ctx.EndTrace()
734 st := ctx.Status.StartTool()
735 st.Status("Running globs...")
736 defer st.Finish()
737
738 globsFile, err := os.Open(finalOutFile + ".globs")
739 if errors.Is(err, fs.ErrNotExist) {
740 // if the glob file doesn't exist, make sure the glob_results file exists and is empty.
741 if err := os.MkdirAll(filepath.Dir(finalOutFile), 0777); err != nil {
742 return err
743 }
744 f, err := os.Create(finalOutFile + ".glob_results")
745 if err != nil {
746 return err
747 }
748 return f.Close()
749 } else if err != nil {
750 return err
751 }
752 defer globsFile.Close()
753 globsFileDecoder := json.NewDecoder(globsFile)
754
755 globsTimeBytes, err := os.ReadFile(finalOutFile + ".globs_time")
756 if err != nil {
757 return err
758 }
759 globsTimeMicros, err := strconv.ParseInt(strings.TrimSpace(string(globsTimeBytes)), 10, 64)
760 if err != nil {
761 return err
762 }
763 globCheckStartTime := time.Now().UnixMicro()
764
765 globsChan := make(chan pathtools.GlobResult)
766 errorsChan := make(chan error)
767 wg := sync.WaitGroup{}
768 hasChangedGlobs := false
769 for i := 0; i < runtime.NumCPU()*2; i++ {
770 wg.Add(1)
771 go func() {
772 for cachedGlob := range globsChan {
773 // If we've already determined we have changed globs, just finish consuming
774 // the channel without doing any more checks.
775 if hasChangedGlobs {
776 continue
777 }
778 // First, check if any of the deps are newer than the last time globs were checked.
779 // If not, we don't need to rerun the glob.
780 hasNewDep := false
781 for _, dep := range cachedGlob.Deps {
782 info, err := os.Stat(dep)
Cole Faust69c78e92024-09-10 16:46:06 -0700783 if errors.Is(err, fs.ErrNotExist) {
784 hasNewDep = true
785 break
786 } else if err != nil {
Cole Faust2fec4122024-09-07 17:28:11 -0700787 errorsChan <- err
788 continue
789 }
790 if info.ModTime().UnixMicro() > globsTimeMicros {
791 hasNewDep = true
792 break
793 }
794 }
795 if !hasNewDep {
796 continue
797 }
798
799 // Then rerun the glob and check if we got the same result as before.
800 result, err := pathtools.Glob(cachedGlob.Pattern, cachedGlob.Excludes, pathtools.FollowSymlinks)
801 if err != nil {
802 errorsChan <- err
803 } else {
804 if !slices.Equal(result.Matches, cachedGlob.Matches) {
805 hasChangedGlobs = true
806 }
807 }
808 }
809 wg.Done()
810 }()
811 }
812 go func() {
813 wg.Wait()
814 close(errorsChan)
815 }()
816
817 errorsWg := sync.WaitGroup{}
818 errorsWg.Add(1)
819 var errFromGoRoutines error
820 go func() {
821 for result := range errorsChan {
822 if errFromGoRoutines == nil {
823 errFromGoRoutines = result
824 }
825 }
826 errorsWg.Done()
827 }()
828
829 var cachedGlob pathtools.GlobResult
830 for globsFileDecoder.More() {
831 if err := globsFileDecoder.Decode(&cachedGlob); err != nil {
832 return err
833 }
834 // Need to clone the GlobResult because the json decoder will
835 // reuse the same slice allocations.
836 globsChan <- cachedGlob.Clone()
837 }
838 close(globsChan)
839 errorsWg.Wait()
840 if errFromGoRoutines != nil {
841 return errFromGoRoutines
842 }
843
844 // Update the globs_time file whether or not we found changed globs,
845 // so that we don't rerun globs in the future that we just saw didn't change.
846 err = os.WriteFile(
847 finalOutFile+".globs_time",
848 []byte(fmt.Sprintf("%d\n", globCheckStartTime)),
849 0666,
850 )
851 if err != nil {
852 return err
853 }
854
855 if hasChangedGlobs {
856 fmt.Fprintf(os.Stdout, "Globs changed, rerunning soong...\n")
857 // Write the current time to the glob_results file. We just need
858 // some unique value to trigger a rerun, it doesn't matter what it is.
859 err = os.WriteFile(
860 finalOutFile+".glob_results",
861 []byte(fmt.Sprintf("%d\n", globCheckStartTime)),
862 0666,
863 )
864 if err != nil {
865 return err
866 }
867 }
868 return nil
869}
870
Colin Crossaa9a2732023-10-27 10:54:27 -0700871// loadSoongBuildMetrics reads out/soong_build_metrics.pb if it was generated by soong_build and copies the
872// events stored in it into the soong_ui trace to provide introspection into how long the different phases of
873// soong_build are taking.
874func loadSoongBuildMetrics(ctx Context, config Config, oldTimestamp time.Time) {
875 soongBuildMetricsFile := config.SoongBuildMetrics()
876 if metricsStat, err := os.Stat(soongBuildMetricsFile); err != nil {
877 ctx.Verbosef("Failed to stat %s: %s", soongBuildMetricsFile, err)
878 return
879 } else if !metricsStat.ModTime().After(oldTimestamp) {
880 ctx.Verbosef("%s timestamp not later after running soong, expected %s > %s",
881 soongBuildMetricsFile, metricsStat.ModTime(), oldTimestamp)
882 return
883 }
884
Colin Crossb67b0612023-10-31 10:02:45 -0700885 metricsData, err := os.ReadFile(soongBuildMetricsFile)
Colin Crossaa9a2732023-10-27 10:54:27 -0700886 if err != nil {
887 ctx.Verbosef("Failed to read %s: %s", soongBuildMetricsFile, err)
888 return
889 }
890
891 soongBuildMetrics := metrics_proto.SoongBuildMetrics{}
892 err = proto.Unmarshal(metricsData, &soongBuildMetrics)
893 if err != nil {
894 ctx.Verbosef("Failed to unmarshal %s: %s", soongBuildMetricsFile, err)
895 return
896 }
897 for _, event := range soongBuildMetrics.Events {
898 desc := event.GetDescription()
899 if dot := strings.LastIndexByte(desc, '.'); dot >= 0 {
900 desc = desc[dot+1:]
901 }
902 ctx.Tracer.Complete(desc, ctx.Thread,
903 event.GetStartTime(), event.GetStartTime()+event.GetRealTime())
904 }
Colin Cross46b0c752023-10-27 14:56:12 -0700905 for _, event := range soongBuildMetrics.PerfCounters {
906 timestamp := event.GetTime()
907 for _, group := range event.Groups {
908 counters := make([]tracer.Counter, 0, len(group.Counters))
909 for _, counter := range group.Counters {
910 counters = append(counters, tracer.Counter{
911 Name: counter.GetName(),
912 Value: counter.GetValue(),
913 })
914 }
915 ctx.Tracer.CountersAtTime(group.GetName(), ctx.Thread, timestamp, counters)
916 }
917 }
Colin Crossaa9a2732023-10-27 10:54:27 -0700918}
919
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100920func runMicrofactory(ctx Context, config Config, name string, pkg string, mapping map[string]string) {
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700921 ctx.BeginTrace(metrics.RunSoong, name)
922 defer ctx.EndTrace()
923 cfg := microfactory.Config{TrimPath: absPath(ctx, ".")}
924 for pkgPrefix, pathPrefix := range mapping {
925 cfg.Map(pkgPrefix, pathPrefix)
926 }
927
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100928 exePath := filepath.Join(config.SoongOutDir(), name)
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700929 dir := filepath.Dir(exePath)
930 if err := os.MkdirAll(dir, 0777); err != nil {
931 ctx.Fatalf("cannot create %s: %s", dir, err)
932 }
933 if _, err := microfactory.Build(&cfg, exePath, pkg); err != nil {
934 ctx.Fatalf("failed to build %s: %s", name, err)
935 }
936}