blob: 6e4d6da4e82a3067b041e60433839703e97558a8 [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
Chris Parsons9402ca82023-02-23 17:28:06 -050028 "android/soong/bazel"
Dan Willemsen4591b642021-05-24 14:24:12 -070029 "android/soong/ui/metrics"
Colin Crossaa9a2732023-10-27 10:54:27 -070030 "android/soong/ui/metrics/metrics_proto"
Dan Willemsen4591b642021-05-24 14:24:12 -070031 "android/soong/ui/status"
32
33 "android/soong/shared"
34
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010035 "github.com/google/blueprint"
36 "github.com/google/blueprint/bootstrap"
Dan Willemsen99a75cd2017-08-04 16:04:04 -070037 "github.com/google/blueprint/microfactory"
Colin Crossaa9a2732023-10-27 10:54:27 -070038
39 "google.golang.org/protobuf/proto"
Dan Willemsen1e704462016-08-21 15:17:17 -070040)
41
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020042const (
43 availableEnvFile = "soong.environment.available"
44 usedEnvFile = "soong.environment.used"
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +020045
Lukacs T. Berkic541cd22022-10-26 07:26:50 +000046 soongBuildTag = "build"
47 bp2buildFilesTag = "bp2build_files"
48 bp2buildWorkspaceTag = "bp2build_workspace"
49 jsonModuleGraphTag = "modulegraph"
50 queryviewTag = "queryview"
Lukacs T. Berkic541cd22022-10-26 07:26:50 +000051 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
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800185func (pb PrimaryBuilderFactory) primaryBuilderInvocation() bootstrap.PrimaryBuilderInvocation {
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200186 commonArgs := make([]string, 0, 0)
187
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800188 if !pb.config.skipSoongTests {
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200189 commonArgs = append(commonArgs, "-t")
190 }
191
LaMont Jones80f70352023-03-20 19:58:25 +0000192 if pb.config.multitreeBuild {
LaMont Jones52a72432023-03-09 18:19:35 +0000193 commonArgs = append(commonArgs, "--multitree-build")
194 }
Sebastian Pickl1c4188c2023-10-24 11:18:34 +0000195 if pb.config.buildFromTextStub {
196 commonArgs = append(commonArgs, "--build-from-text-stub")
Jihoon Kang1bff0342023-01-17 20:40:22 +0000197 }
LaMont Jones52a72432023-03-09 18:19:35 +0000198
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800199 commonArgs = append(commonArgs, "-l", filepath.Join(pb.config.FileListDir(), "Android.bp.list"))
Lukacs T. Berki13644272022-01-05 10:29:56 +0100200 invocationEnv := make(map[string]string)
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800201 if pb.debugPort != "" {
ustafb67fd12022-08-19 19:26:00 -0400202 //debug mode
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800203 commonArgs = append(commonArgs, "--delve_listen", pb.debugPort,
204 "--delve_path", shared.ResolveDelveBinary())
Lukacs T. Berki13644272022-01-05 10:29:56 +0100205 // GODEBUG=asyncpreemptoff=1 disables the preemption of goroutines. This
206 // is useful because the preemption happens by sending SIGURG to the OS
207 // thread hosting the goroutine in question and each signal results in
208 // work that needs to be done by Delve; it uses ptrace to debug the Go
209 // process and the tracer process must deal with every signal (it is not
210 // possible to selectively ignore SIGURG). This makes debugging slower,
211 // sometimes by an order of magnitude depending on luck.
212 // The original reason for adding async preemption to Go is here:
213 // https://github.com/golang/proposal/blob/master/design/24543-non-cooperative-preemption.md
214 invocationEnv["GODEBUG"] = "asyncpreemptoff=1"
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200215 }
216
ustafb67fd12022-08-19 19:26:00 -0400217 var allArgs []string
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800218 allArgs = append(allArgs, pb.specificArgs...)
Jeongik Chaccf37002023-08-04 01:46:32 +0900219 globPathName := pb.name
220 // Glob path for soong build would be separated per product target
221 if pb.name == soongBuildTag {
222 globPathName = getGlobPathName(pb.config)
223 }
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200224 allArgs = append(allArgs,
Jeongik Chaccf37002023-08-04 01:46:32 +0900225 "--globListDir", globPathName,
226 "--globFile", pb.config.NamedGlobFile(globPathName))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200227
228 allArgs = append(allArgs, commonArgs...)
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800229 allArgs = append(allArgs, environmentArgs(pb.config, pb.name)...)
Sasha Smundakfaa97b72022-11-18 15:32:49 -0800230 if profileCpu := os.Getenv("SOONG_PROFILE_CPU"); profileCpu != "" {
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800231 allArgs = append(allArgs, "--cpuprofile", profileCpu+"."+pb.name)
Sasha Smundakfaa97b72022-11-18 15:32:49 -0800232 }
233 if profileMem := os.Getenv("SOONG_PROFILE_MEM"); profileMem != "" {
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800234 allArgs = append(allArgs, "--memprofile", profileMem+"."+pb.name)
Sasha Smundakfaa97b72022-11-18 15:32:49 -0800235 }
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200236 allArgs = append(allArgs, "Android.bp")
237
238 return bootstrap.PrimaryBuilderInvocation{
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000239 Inputs: []string{"Android.bp"},
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800240 Outputs: []string{pb.output},
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000241 Args: allArgs,
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800242 Description: pb.description,
Lukacs T. Berki2fad3412022-01-04 14:40:13 +0100243 // NB: Changing the value of this environment variable will not result in a
244 // rebuild. The bootstrap Ninja file will change, but apparently Ninja does
245 // not consider changing the pool specified in a statement a change that's
246 // worth rebuilding for.
247 Console: os.Getenv("SOONG_UNBUFFERED_OUTPUT") == "1",
Lukacs T. Berki13644272022-01-05 10:29:56 +0100248 Env: invocationEnv,
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200249 }
250}
251
Colin Cross9191df22021-10-29 13:11:32 -0700252// bootstrapEpochCleanup deletes files used by bootstrap during incremental builds across
253// incompatible changes. Incompatible changes are marked by incrementing the bootstrapEpoch
254// constant. A tree is considered out of date for the current epoch of the
255// .soong.bootstrap.epoch.<epoch> file doesn't exist.
256func bootstrapEpochCleanup(ctx Context, config Config) {
257 epochFile := fmt.Sprintf(".soong.bootstrap.epoch.%d", bootstrapEpoch)
258 epochPath := filepath.Join(config.SoongOutDir(), epochFile)
259 if exists, err := fileExists(epochPath); err != nil {
260 ctx.Fatalf("failed to check if bootstrap epoch file %q exists: %q", epochPath, err)
261 } else if !exists {
262 // The tree is out of date for the current epoch, delete files used by bootstrap
263 // and force the primary builder to rerun.
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900264 os.Remove(config.SoongNinjaFile())
Colin Cross9191df22021-10-29 13:11:32 -0700265 for _, globFile := range bootstrapGlobFileList(config) {
266 os.Remove(globFile)
267 }
268
269 // Mark the tree as up to date with the current epoch by writing the epoch marker file.
270 writeEmptyFile(ctx, epochPath)
271 }
272}
273
274func bootstrapGlobFileList(config Config) []string {
275 return []string{
Jeongik Chaccf37002023-08-04 01:46:32 +0900276 config.NamedGlobFile(getGlobPathName(config)),
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000277 config.NamedGlobFile(bp2buildFilesTag),
Colin Cross9191df22021-10-29 13:11:32 -0700278 config.NamedGlobFile(jsonModuleGraphTag),
279 config.NamedGlobFile(queryviewTag),
280 config.NamedGlobFile(soongDocsTag),
281 }
282}
283
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200284func bootstrapBlueprint(ctx Context, config Config) {
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100285 ctx.BeginTrace(metrics.RunSoong, "blueprint bootstrap")
286 defer ctx.EndTrace()
287
Colin Cross9191df22021-10-29 13:11:32 -0700288 // Clean up some files for incremental builds across incompatible changes.
289 bootstrapEpochCleanup(ctx, config)
290
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900291 baseArgs := []string{"--soong_variables", config.SoongVarsFile()}
292
293 mainSoongBuildExtraArgs := append(baseArgs, "-o", config.SoongNinjaFile())
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200294 if config.EmptyNinjaFile() {
295 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--empty-ninja-file")
Lukacs T. Berki745380c2021-04-12 12:07:44 +0200296 }
Chris Parsonsef615e52022-08-18 22:04:11 -0400297 if config.bazelProdMode {
298 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--bazel-mode")
299 }
MarkDacekb78465d2022-10-18 20:10:16 +0000300 if config.bazelStagingMode {
301 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--bazel-mode-staging")
302 }
Chris Parsons9402ca82023-02-23 17:28:06 -0500303 if config.IsPersistentBazelEnabled() {
304 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--use-bazel-proxy")
305 }
MarkDacekd06db5d2022-11-29 00:47:59 +0000306 if len(config.bazelForceEnabledModules) > 0 {
307 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--bazel-force-enabled-modules="+config.bazelForceEnabledModules)
308 }
LaMont Jones52a72432023-03-09 18:19:35 +0000309 if config.MultitreeBuild() {
310 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--multitree-build")
311 }
Sebastian Pickl1c4188c2023-10-24 11:18:34 +0000312 if config.buildFromTextStub {
313 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--build-from-text-stub")
Jihoon Kang1bff0342023-01-17 20:40:22 +0000314 }
MarkDacekf47e1422023-04-19 16:47:36 +0000315 if config.ensureAllowlistIntegrity {
316 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--ensure-allowlist-integrity")
317 }
MarkDacekd06db5d2022-11-29 00:47:59 +0000318
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000319 queryviewDir := filepath.Join(config.SoongOutDir(), "queryview")
Spandan Das5af0bd32022-09-28 20:43:08 +0000320
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800321 pbfs := []PrimaryBuilderFactory{
322 {
323 name: soongBuildTag,
324 description: fmt.Sprintf("analyzing Android.bp files and generating ninja file at %s", config.SoongNinjaFile()),
325 config: config,
326 output: config.SoongNinjaFile(),
327 specificArgs: mainSoongBuildExtraArgs,
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000328 },
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800329 {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900330 name: bp2buildFilesTag,
331 description: fmt.Sprintf("converting Android.bp files to BUILD files at %s/bp2build", config.SoongOutDir()),
332 config: config,
333 output: config.Bp2BuildFilesMarkerFile(),
334 specificArgs: append(baseArgs,
335 "--bp2build_marker", config.Bp2BuildFilesMarkerFile(),
336 ),
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800337 },
338 {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900339 name: bp2buildWorkspaceTag,
340 description: "Creating Bazel symlink forest",
341 config: config,
342 output: config.Bp2BuildWorkspaceMarkerFile(),
343 specificArgs: append(baseArgs,
344 "--symlink_forest_marker", config.Bp2BuildWorkspaceMarkerFile(),
345 ),
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800346 },
347 {
348 name: jsonModuleGraphTag,
349 description: fmt.Sprintf("generating the Soong module graph at %s", config.ModuleGraphFile()),
350 config: config,
351 output: config.ModuleGraphFile(),
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900352 specificArgs: append(baseArgs,
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800353 "--module_graph_file", config.ModuleGraphFile(),
354 "--module_actions_file", config.ModuleActionsFile(),
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900355 ),
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800356 },
357 {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900358 name: queryviewTag,
359 description: fmt.Sprintf("generating the Soong module graph as a Bazel workspace at %s", queryviewDir),
360 config: config,
361 output: config.QueryviewMarkerFile(),
362 specificArgs: append(baseArgs,
363 "--bazel_queryview_dir", queryviewDir,
364 ),
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800365 },
366 {
Kiyoung Kima37d9ba2023-04-19 13:13:45 +0900367 name: soongDocsTag,
368 description: fmt.Sprintf("generating Soong docs at %s", config.SoongDocsHtml()),
369 config: config,
370 output: config.SoongDocsHtml(),
371 specificArgs: append(baseArgs,
372 "--soong_docs", config.SoongDocsHtml(),
373 ),
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800374 },
375 }
376
377 // Figure out which invocations will be run under the debugger:
378 // * SOONG_DELVE if set specifies listening port
379 // * SOONG_DELVE_STEPS if set specifies specific invocations to be debugged, otherwise all are
380 debuggedInvocations := make(map[string]bool)
381 delvePort := os.Getenv("SOONG_DELVE")
382 if delvePort != "" {
383 if steps := os.Getenv("SOONG_DELVE_STEPS"); steps != "" {
384 var validSteps []string
385 for _, pbf := range pbfs {
386 debuggedInvocations[pbf.name] = false
387 validSteps = append(validSteps, pbf.name)
388
389 }
390 for _, step := range strings.Split(steps, ",") {
391 if _, ok := debuggedInvocations[step]; ok {
392 debuggedInvocations[step] = true
393 } else {
394 ctx.Fatalf("SOONG_DELVE_STEPS contains unknown soong_build step %s\n"+
395 "Valid steps are %v", step, validSteps)
396 }
397 }
398 } else {
399 // SOONG_DELVE_STEPS is not set, run all steps in the debugger
400 for _, pbf := range pbfs {
401 debuggedInvocations[pbf.name] = true
402 }
403 }
404 }
405
406 var invocations []bootstrap.PrimaryBuilderInvocation
407 for _, pbf := range pbfs {
408 if debuggedInvocations[pbf.name] {
409 pbf.debugPort = delvePort
410 }
411 pbi := pbf.primaryBuilderInvocation()
412 // Some invocations require adjustment:
413 switch pbf.name {
414 case soongBuildTag:
415 if config.BazelBuildEnabled() {
416 // Mixed builds call Bazel from soong_build and they therefore need the
417 // Bazel workspace to be available. Make that so by adding a dependency on
418 // the bp2build marker file to the action that invokes soong_build .
419 pbi.OrderOnlyInputs = append(pbi.OrderOnlyInputs, config.Bp2BuildWorkspaceMarkerFile())
420 }
421 case bp2buildWorkspaceTag:
422 pbi.Inputs = append(pbi.Inputs,
423 config.Bp2BuildFilesMarkerFile(),
424 filepath.Join(config.FileListDir(), "bazel.list"))
Wei Li2c9e8d62023-05-05 01:07:15 -0700425 case bp2buildFilesTag:
426 pbi.Inputs = append(pbi.Inputs, filepath.Join(config.FileListDir(), "METADATA.list"))
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800427 }
428 invocations = append(invocations, pbi)
429 }
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200430
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200431 // The glob .ninja files are subninja'd. However, they are generated during
432 // the build itself so we write an empty file if the file does not exist yet
433 // so that the subninja doesn't fail on clean builds
Colin Cross9191df22021-10-29 13:11:32 -0700434 for _, globFile := range bootstrapGlobFileList(config) {
435 writeEmptyFile(ctx, globFile)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200436 }
437
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800438 blueprintArgs := bootstrap.Args{
439 ModuleListFile: filepath.Join(config.FileListDir(), "Android.bp.list"),
440 OutFile: shared.JoinPath(config.SoongOutDir(), "bootstrap.ninja"),
441 EmptyNinjaFile: false,
442 }
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200443
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100444 blueprintCtx := blueprint.NewContext()
Spandan Dasc5763832022-11-08 18:42:16 +0000445 blueprintCtx.AddIncludeTags(config.GetIncludeTags()...)
Sam Delmerico98a73292023-02-21 11:50:29 -0500446 blueprintCtx.AddSourceRootDirs(config.GetSourceRootDirs()...)
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100447 blueprintCtx.SetIgnoreUnknownModuleTypes(true)
448 blueprintConfig := BlueprintConfig{
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200449 soongOutDir: config.SoongOutDir(),
450 toolDir: config.HostToolDir(),
451 outDir: config.OutDir(),
452 runGoTests: !config.skipSoongTests,
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200453 // If we want to debug soong_build, we need to compile it for debugging
Sasha Smundak4cbe83a2022-11-28 17:02:40 -0800454 debugCompilation: delvePort != "",
455 subninjas: bootstrapGlobFileList(config),
456 primaryBuilderInvocations: invocations,
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100457 }
458
usta5bb4a5d2022-08-24 12:53:46 -0400459 // since `bootstrap.ninja` is regenerated unconditionally, we ignore the deps, i.e. little
460 // reason to write a `bootstrap.ninja.d` file
Lukacs T. Berkic357c812023-06-20 09:30:06 +0000461 _, err := bootstrap.RunBlueprint(blueprintArgs, bootstrap.DoEverything, blueprintCtx, blueprintConfig)
462 if err != nil {
463 ctx.Fatal(err)
464 }
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100465}
466
Jason Wu2520f5e2023-05-30 19:45:36 -0400467func checkEnvironmentFile(ctx Context, currentEnv *Environment, envFile string) {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200468 getenv := func(k string) string {
469 v, _ := currentEnv.Get(k)
470 return v
471 }
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200472
Jason Wu2520f5e2023-05-30 19:45:36 -0400473 // Log the changed environment variables to ChangedEnvironmentVariable field
474 if stale, changedEnvironmentVariableList, _ := shared.StaleEnvFile(envFile, getenv); stale {
475 for _, changedEnvironmentVariable := range changedEnvironmentVariableList {
476 ctx.Metrics.AddChangedEnvironmentVariable(changedEnvironmentVariable)
477 }
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200478 os.Remove(envFile)
479 }
480}
481
Kousik Kumarca390b22023-10-04 04:14:28 +0000482func updateSymlinks(ctx Context, dir, prevCWD, cwd string) error {
483 defer symlinkWg.Done()
484
485 visit := func(path string, d fs.DirEntry, err error) error {
486 if d.IsDir() && path != dir {
487 symlinkWg.Add(1)
488 go updateSymlinks(ctx, path, prevCWD, cwd)
489 return filepath.SkipDir
490 }
491 f, err := d.Info()
492 if err != nil {
493 return err
494 }
495 // If the file is not a symlink, we don't have to update it.
496 if f.Mode()&os.ModeSymlink != os.ModeSymlink {
497 return nil
498 }
499
500 atomic.AddUint32(&numFound, 1)
501 target, err := os.Readlink(path)
502 if err != nil {
503 return err
504 }
505 if strings.HasPrefix(target, prevCWD) &&
506 (len(target) == len(prevCWD) || target[len(prevCWD)] == '/') {
507 target = filepath.Join(cwd, target[len(prevCWD):])
508 if err := os.Remove(path); err != nil {
509 return err
510 }
511 if err := os.Symlink(target, path); err != nil {
512 return err
513 }
514 atomic.AddUint32(&numUpdated, 1)
515 }
516 return nil
517 }
518
519 if err := filepath.WalkDir(dir, visit); err != nil {
520 return err
521 }
522 return nil
523}
524
525func fixOutDirSymlinks(ctx Context, config Config, outDir string) error {
526 cwd, err := os.Getwd()
527 if err != nil {
528 return err
529 }
530
531 // Record the .top as the very last thing in the function.
532 tf := filepath.Join(outDir, ".top")
533 defer func() {
534 if err := os.WriteFile(tf, []byte(cwd), 0644); err != nil {
535 fmt.Fprintf(os.Stderr, fmt.Sprintf("Unable to log CWD: %v", err))
536 }
537 }()
538
539 // Find the previous working directory if it was recorded.
540 var prevCWD string
541 pcwd, err := os.ReadFile(tf)
542 if err != nil {
543 if os.IsNotExist(err) {
544 // No previous working directory recorded, nothing to do.
545 return nil
546 }
547 return err
548 }
549 prevCWD = strings.Trim(string(pcwd), "\n")
550
551 if prevCWD == cwd {
552 // We are in the same source dir, nothing to update.
553 return nil
554 }
555
556 symlinkWg.Add(1)
557 if err := updateSymlinks(ctx, outDir, prevCWD, cwd); err != nil {
558 return err
559 }
560 symlinkWg.Wait()
561 ctx.Println(fmt.Sprintf("Updated %d/%d symlinks in dir %v", numUpdated, numFound, outDir))
562 return nil
563}
564
565func migrateOutputSymlinks(ctx Context, config Config) error {
566 // Figure out the real out directory ("out" could be a symlink).
567 outDir := config.OutDir()
568 s, err := os.Lstat(outDir)
569 if err != nil {
570 if os.IsNotExist(err) {
571 // No out dir exists, no symlinks to migrate.
572 return nil
573 }
574 return err
575 }
576 if s.Mode()&os.ModeSymlink == os.ModeSymlink {
577 target, err := filepath.EvalSymlinks(outDir)
578 if err != nil {
579 return err
580 }
581 outDir = target
582 }
583 return fixOutDirSymlinks(ctx, config, outDir)
584}
585
Dan Willemsen1e704462016-08-21 15:17:17 -0700586func runSoong(ctx Context, config Config) {
Nan Zhang17f27672018-12-12 16:01:49 -0800587 ctx.BeginTrace(metrics.RunSoong, "soong")
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700588 defer ctx.EndTrace()
589
Kousik Kumarca390b22023-10-04 04:14:28 +0000590 if err := migrateOutputSymlinks(ctx, config); err != nil {
591 ctx.Fatalf("failed to migrate output directory to current TOP dir: %v", err)
592 }
593
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100594 // We have two environment files: .available is the one with every variable,
595 // .used with the ones that were actually used. The latter is used to
596 // determine whether Soong needs to be re-run since why re-run it if only
597 // unused variables were changed?
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200598 envFile := filepath.Join(config.SoongOutDir(), availableEnvFile)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100599
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100600 // This is done unconditionally, but does not take a measurable amount of time
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200601 bootstrapBlueprint(ctx, config)
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700602
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100603 soongBuildEnv := config.Environment().Copy()
604 soongBuildEnv.Set("TOP", os.Getenv("TOP"))
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100605 // For Bazel mixed builds.
Joe Onoratoba29f382022-10-24 06:38:11 -0700606 soongBuildEnv.Set("BAZEL_PATH", "./build/bazel/bin/bazel")
Chris Parsonsa9bef142022-09-28 15:07:46 -0400607 // Bazel's HOME var is set to an output subdirectory which doesn't exist. This
608 // prevents Bazel from file I/O in the actual user HOME directory.
609 soongBuildEnv.Set("BAZEL_HOME", absPath(ctx, filepath.Join(config.BazelOutDir(), "bazelhome")))
Liz Kammer2af5ea82022-11-11 14:21:03 -0500610 soongBuildEnv.Set("BAZEL_OUTPUT_BASE", config.bazelOutputBase())
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100611 soongBuildEnv.Set("BAZEL_WORKSPACE", absPath(ctx, "."))
612 soongBuildEnv.Set("BAZEL_METRICS_DIR", config.BazelMetricsDir())
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500613 soongBuildEnv.Set("LOG_DIR", config.LogsDir())
Jingwen Chen3b13b612022-10-17 12:14:26 +0000614 soongBuildEnv.Set("BAZEL_DEPS_FILE", absPath(ctx, filepath.Join(config.BazelOutDir(), "bazel.list")))
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100615
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100616 // For Soong bootstrapping tests
617 if os.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
618 soongBuildEnv.Set("ALLOW_MISSING_DEPENDENCIES", "true")
619 }
620
Paul Duffin5e85c662021-03-05 12:26:14 +0000621 err := writeEnvironmentFile(ctx, envFile, soongBuildEnv.AsMap())
622 if err != nil {
623 ctx.Fatalf("failed to write environment file %s: %s", envFile, err)
624 }
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100625
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700626 func() {
Nan Zhang17f27672018-12-12 16:01:49 -0800627 ctx.BeginTrace(metrics.RunSoong, "environment check")
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700628 defer ctx.EndTrace()
629
Jason Wu2520f5e2023-05-30 19:45:36 -0400630 checkEnvironmentFile(ctx, soongBuildEnv, config.UsedEnvFile(soongBuildTag))
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200631
Chris Parsonsef615e52022-08-18 22:04:11 -0400632 if config.BazelBuildEnabled() || config.Bp2Build() {
Jason Wu2520f5e2023-05-30 19:45:36 -0400633 checkEnvironmentFile(ctx, soongBuildEnv, config.UsedEnvFile(bp2buildFilesTag))
Chris Parsonsb6d6fc92023-10-30 16:21:06 +0000634 } else {
635 // Remove bazel files in the event that bazel is disabled for the build.
636 // These files may have been left over from a previous bazel-enabled build.
637 cleanBazelFiles(config)
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200638 }
639
640 if config.JsonModuleGraph() {
Jason Wu2520f5e2023-05-30 19:45:36 -0400641 checkEnvironmentFile(ctx, soongBuildEnv, config.UsedEnvFile(jsonModuleGraphTag))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200642 }
643
644 if config.Queryview() {
Jason Wu2520f5e2023-05-30 19:45:36 -0400645 checkEnvironmentFile(ctx, soongBuildEnv, config.UsedEnvFile(queryviewTag))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200646 }
647
648 if config.SoongDocs() {
Jason Wu2520f5e2023-05-30 19:45:36 -0400649 checkEnvironmentFile(ctx, soongBuildEnv, config.UsedEnvFile(soongDocsTag))
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700650 }
651 }()
652
Colin Cross9191df22021-10-29 13:11:32 -0700653 runMicrofactory(ctx, config, "bpglob", "github.com/google/blueprint/bootstrap/bpglob",
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700654 map[string]string{"github.com/google/blueprint": "build/blueprint"})
Dan Willemsen5af1cbe2018-07-05 21:46:51 -0700655
usta49012ee2023-05-22 16:33:27 -0400656 ninja := func(targets ...string) {
657 ctx.BeginTrace(metrics.RunSoong, "bootstrap")
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700658 defer ctx.EndTrace()
659
Chris Parsons9402ca82023-02-23 17:28:06 -0500660 if config.IsPersistentBazelEnabled() {
Chris Parsonsc83398f2023-05-31 18:41:41 +0000661 bazelProxy := bazel.NewProxyServer(ctx.Logger, config.OutDir(), filepath.Join(config.SoongOutDir(), "workspace"), config.GetBazeliskBazelVersion())
usta49012ee2023-05-22 16:33:27 -0400662 if err := bazelProxy.Start(); err != nil {
663 ctx.Fatalf("Failed to create bazel proxy")
664 }
Chris Parsons9402ca82023-02-23 17:28:06 -0500665 defer bazelProxy.Close()
666 }
667
Dan Willemsenb82471a2018-05-17 16:37:09 -0700668 fifo := filepath.Join(config.OutDir(), ".ninja_fifo")
Colin Crossb98d3bc2019-03-21 16:02:58 -0700669 nr := status.NewNinjaReader(ctx, ctx.Status.StartTool(), fifo)
670 defer nr.Close()
Dan Willemsenb82471a2018-05-17 16:37:09 -0700671
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200672 ninjaArgs := []string{
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700673 "-d", "keepdepfile",
Dan Willemsen08218222020-05-18 14:02:02 -0700674 "-d", "stats",
Dan Willemsen6587bed2020-04-18 20:25:59 -0700675 "-o", "usesphonyoutputs=yes",
676 "-o", "preremoveoutputs=yes",
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700677 "-w", "dupbuild=err",
Dan Willemsen6587bed2020-04-18 20:25:59 -0700678 "-w", "outputdir=err",
679 "-w", "missingoutfile=err",
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700680 "-j", strconv.Itoa(config.Parallel()),
Dan Willemsen02736672018-07-17 17:54:31 -0700681 "--frontend_file", fifo,
usta49012ee2023-05-22 16:33:27 -0400682 "-f", filepath.Join(config.SoongOutDir(), "bootstrap.ninja"),
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200683 }
684
Usta Shrestha8dc8b0a2022-08-10 17:39:37 -0400685 if extra, ok := config.Environment().Get("SOONG_UI_NINJA_ARGS"); ok {
686 ctx.Printf(`CAUTION: arguments in $SOONG_UI_NINJA_ARGS=%q, e.g. "-n", can make soong_build FAIL or INCORRECT`, extra)
687 ninjaArgs = append(ninjaArgs, strings.Fields(extra)...)
688 }
689
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200690 ninjaArgs = append(ninjaArgs, targets...)
usta49012ee2023-05-22 16:33:27 -0400691 cmd := Command(ctx, config, "soong bootstrap",
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200692 config.PrebuiltBuildTool("ninja"), ninjaArgs...)
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500693
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100694 var ninjaEnv Environment
Lukacs T. Berki73ab9282021-03-10 10:48:39 +0100695
696 // This is currently how the command line to invoke soong_build finds the
697 // root of the source tree and the output root
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100698 ninjaEnv.Set("TOP", os.Getenv("TOP"))
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100699
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100700 cmd.Environment = &ninjaEnv
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700701 cmd.Sandbox = soongSandbox
Colin Cross7b97ecd2019-06-19 13:17:59 -0700702 cmd.RunAndStreamOrFatal()
Dan Willemsen1e704462016-08-21 15:17:17 -0700703 }
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200704
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200705 targets := make([]string, 0, 0)
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200706
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200707 if config.JsonModuleGraph() {
708 targets = append(targets, config.ModuleGraphFile())
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200709 }
710
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200711 if config.Bp2Build() {
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000712 targets = append(targets, config.Bp2BuildWorkspaceMarkerFile())
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200713 }
714
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200715 if config.Queryview() {
716 targets = append(targets, config.QueryviewMarkerFile())
717 }
718
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200719 if config.SoongDocs() {
720 targets = append(targets, config.SoongDocsHtml())
721 }
722
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200723 if config.SoongBuildInvocationNeeded() {
724 // 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 -0700725 targets = append(targets, config.SoongNinjaFile())
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200726 }
727
Colin Crossaa9a2732023-10-27 10:54:27 -0700728 beforeSoongTimestamp := time.Now()
729
usta49012ee2023-05-22 16:33:27 -0400730 ninja(targets...)
Colin Crossb72c9092020-02-10 11:23:49 -0800731
Colin Crossaa9a2732023-10-27 10:54:27 -0700732 loadSoongBuildMetrics(ctx, config, beforeSoongTimestamp)
733
Colin Cross8ba7d472020-06-25 11:27:52 -0700734 distGzipFile(ctx, config, config.SoongNinjaFile(), "soong")
Jihoon Kang9f4f8a32022-08-16 00:57:30 +0000735 distFile(ctx, config, config.SoongVarsFile(), "soong")
Colin Cross8ba7d472020-06-25 11:27:52 -0700736
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000737 if !config.SkipKati() {
Colin Cross8ba7d472020-06-25 11:27:52 -0700738 distGzipFile(ctx, config, config.SoongAndroidMk(), "soong")
739 distGzipFile(ctx, config, config.SoongMakeVarsMk(), "soong")
740 }
741
Rob Seymour33cd10d2022-03-02 23:10:25 +0000742 if config.JsonModuleGraph() {
743 distGzipFile(ctx, config, config.ModuleGraphFile(), "soong")
744 }
Colin Crossb72c9092020-02-10 11:23:49 -0800745}
746
Colin Crossaa9a2732023-10-27 10:54:27 -0700747// loadSoongBuildMetrics reads out/soong_build_metrics.pb if it was generated by soong_build and copies the
748// events stored in it into the soong_ui trace to provide introspection into how long the different phases of
749// soong_build are taking.
750func loadSoongBuildMetrics(ctx Context, config Config, oldTimestamp time.Time) {
751 soongBuildMetricsFile := config.SoongBuildMetrics()
752 if metricsStat, err := os.Stat(soongBuildMetricsFile); err != nil {
753 ctx.Verbosef("Failed to stat %s: %s", soongBuildMetricsFile, err)
754 return
755 } else if !metricsStat.ModTime().After(oldTimestamp) {
756 ctx.Verbosef("%s timestamp not later after running soong, expected %s > %s",
757 soongBuildMetricsFile, metricsStat.ModTime(), oldTimestamp)
758 return
759 }
760
761 metricsData, err := os.ReadFile(config.SoongBuildMetrics())
762 if err != nil {
763 ctx.Verbosef("Failed to read %s: %s", soongBuildMetricsFile, err)
764 return
765 }
766
767 soongBuildMetrics := metrics_proto.SoongBuildMetrics{}
768 err = proto.Unmarshal(metricsData, &soongBuildMetrics)
769 if err != nil {
770 ctx.Verbosef("Failed to unmarshal %s: %s", soongBuildMetricsFile, err)
771 return
772 }
773 for _, event := range soongBuildMetrics.Events {
774 desc := event.GetDescription()
775 if dot := strings.LastIndexByte(desc, '.'); dot >= 0 {
776 desc = desc[dot+1:]
777 }
778 ctx.Tracer.Complete(desc, ctx.Thread,
779 event.GetStartTime(), event.GetStartTime()+event.GetRealTime())
780 }
781}
782
Chris Parsonsb6d6fc92023-10-30 16:21:06 +0000783func cleanBazelFiles(config Config) {
784 files := []string{
785 shared.JoinPath(config.SoongOutDir(), "bp2build"),
786 shared.JoinPath(config.SoongOutDir(), "workspace"),
787 shared.JoinPath(config.SoongOutDir(), bazel.SoongInjectionDirName),
788 shared.JoinPath(config.OutDir(), "bazel")}
789
790 for _, f := range files {
791 os.RemoveAll(f)
792 }
793}
794
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100795func runMicrofactory(ctx Context, config Config, name string, pkg string, mapping map[string]string) {
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700796 ctx.BeginTrace(metrics.RunSoong, name)
797 defer ctx.EndTrace()
798 cfg := microfactory.Config{TrimPath: absPath(ctx, ".")}
799 for pkgPrefix, pathPrefix := range mapping {
800 cfg.Map(pkgPrefix, pathPrefix)
801 }
802
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100803 exePath := filepath.Join(config.SoongOutDir(), name)
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700804 dir := filepath.Dir(exePath)
805 if err := os.MkdirAll(dir, 0777); err != nil {
806 ctx.Fatalf("cannot create %s: %s", dir, err)
807 }
808 if _, err := microfactory.Build(&cfg, exePath, pkg); err != nil {
809 ctx.Fatalf("failed to build %s: %s", name, err)
810 }
811}