blob: 9d5c9962c01baa163aae33dec26e166087e64691 [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"
Colin Crossb72c9092020-02-10 11:23:49 -080019 "io/ioutil"
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"
Dan Willemsen99a75cd2017-08-04 16:04:04 -070023
Dan Willemsen4591b642021-05-24 14:24:12 -070024 "android/soong/ui/metrics"
Colin Crossb72c9092020-02-10 11:23:49 -080025 soong_metrics_proto "android/soong/ui/metrics/metrics_proto"
Dan Willemsen4591b642021-05-24 14:24:12 -070026 "android/soong/ui/status"
27
28 "android/soong/shared"
29
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010030 "github.com/google/blueprint"
31 "github.com/google/blueprint/bootstrap"
Dan Willemsen4591b642021-05-24 14:24:12 -070032 "github.com/google/blueprint/deptools"
Dan Willemsen99a75cd2017-08-04 16:04:04 -070033 "github.com/google/blueprint/microfactory"
Dan Willemsenb82471a2018-05-17 16:37:09 -070034
Dan Willemsen4591b642021-05-24 14:24:12 -070035 "google.golang.org/protobuf/proto"
Dan Willemsen1e704462016-08-21 15:17:17 -070036)
37
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020038const (
39 availableEnvFile = "soong.environment.available"
40 usedEnvFile = "soong.environment.used"
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +020041
42 soongBuildTag = "build"
43 bp2buildTag = "bp2build"
44 jsonModuleGraphTag = "modulegraph"
45 queryviewTag = "queryview"
46 soongDocsTag = "soong_docs"
Colin Cross9191df22021-10-29 13:11:32 -070047
48 // bootstrapEpoch is used to determine if an incremental build is incompatible with the current
49 // version of bootstrap and needs cleaning before continuing the build. Increment this for
50 // incompatible changes, for example when moving the location of the bpglob binary that is
51 // executed during bootstrap before the primary builder has had a chance to update the path.
Lukacs T. Berki9985d9a2021-11-04 11:47:42 +010052 bootstrapEpoch = 1
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020053)
54
Lukacs T. Berki7690c092021-02-26 14:27:36 +010055func writeEnvironmentFile(ctx Context, envFile string, envDeps map[string]string) error {
56 data, err := shared.EnvFileContents(envDeps)
57 if err != nil {
58 return err
59 }
60
61 return ioutil.WriteFile(envFile, data, 0644)
62}
63
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000064// This uses Android.bp files and various tools to generate <builddir>/build.ninja.
65//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010066// However, the execution of <builddir>/build.ninja happens later in
67// build/soong/ui/build/build.go#Build()
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000068//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010069// We want to rely on as few prebuilts as possible, so we need to bootstrap
70// Soong. The process is as follows:
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000071//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010072// 1. We use "Microfactory", a simple tool to compile Go code, to build
73// first itself, then soong_ui from soong_ui.bash. This binary contains
74// parts of soong_build that are needed to build itself.
75// 2. This simplified version of soong_build then reads the Blueprint files
76// that describe itself and emits .bootstrap/build.ninja that describes
77// how to build its full version and use that to produce the final Ninja
78// file Soong emits.
79// 3. soong_ui executes .bootstrap/build.ninja
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000080//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010081// (After this, Kati is executed to parse the Makefiles, but that's not part of
82// bootstrapping Soong)
83
84// A tiny struct used to tell Blueprint that it's in bootstrap mode. It would
85// probably be nicer to use a flag in bootstrap.Args instead.
86type BlueprintConfig struct {
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +020087 toolDir string
88 soongOutDir string
89 outDir string
90 runGoTests bool
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +020091 debugCompilation bool
92 subninjas []string
93 primaryBuilderInvocations []bootstrap.PrimaryBuilderInvocation
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010094}
95
Lukacs T. Berkia806e412021-09-01 08:57:48 +020096func (c BlueprintConfig) HostToolDir() string {
97 return c.toolDir
98}
99
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200100func (c BlueprintConfig) SoongOutDir() string {
101 return c.soongOutDir
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100102}
103
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200104func (c BlueprintConfig) OutDir() string {
105 return c.outDir
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100106}
107
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +0200108func (c BlueprintConfig) RunGoTests() bool {
109 return c.runGoTests
110}
111
Lukacs T. Berki5f6cb1d2021-03-17 15:03:14 +0100112func (c BlueprintConfig) DebugCompilation() bool {
113 return c.debugCompilation
114}
115
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +0200116func (c BlueprintConfig) Subninjas() []string {
117 return c.subninjas
118}
119
120func (c BlueprintConfig) PrimaryBuilderInvocations() []bootstrap.PrimaryBuilderInvocation {
121 return c.primaryBuilderInvocations
122}
123
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200124func environmentArgs(config Config, tag string) []string {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200125 return []string{
126 "--available_env", shared.JoinPath(config.SoongOutDir(), availableEnvFile),
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200127 "--used_env", config.UsedEnvFile(tag),
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200128 }
129}
Spandan Das8f99ae62021-06-11 16:48:06 +0000130
Colin Cross9191df22021-10-29 13:11:32 -0700131func writeEmptyFile(ctx Context, path string) {
Spandan Das8f99ae62021-06-11 16:48:06 +0000132 err := os.MkdirAll(filepath.Dir(path), 0777)
133 if err != nil {
Colin Cross9191df22021-10-29 13:11:32 -0700134 ctx.Fatalf("Failed to create parent directories of empty file '%s': %s", path, err)
Spandan Das8f99ae62021-06-11 16:48:06 +0000135 }
136
Colin Cross9191df22021-10-29 13:11:32 -0700137 if exists, err := fileExists(path); err != nil {
138 ctx.Fatalf("Failed to check if file '%s' exists: %s", path, err)
139 } else if !exists {
Spandan Das8f99ae62021-06-11 16:48:06 +0000140 err = ioutil.WriteFile(path, nil, 0666)
141 if err != nil {
Colin Cross9191df22021-10-29 13:11:32 -0700142 ctx.Fatalf("Failed to create empty file '%s': %s", path, err)
Spandan Das8f99ae62021-06-11 16:48:06 +0000143 }
144 }
145}
146
Colin Cross9191df22021-10-29 13:11:32 -0700147func fileExists(path string) (bool, error) {
148 if _, err := os.Stat(path); os.IsNotExist(err) {
149 return false, nil
150 } else if err != nil {
151 return false, err
152 }
153 return true, nil
154}
155
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200156func primaryBuilderInvocation(config Config, name string, output string, specificArgs []string) bootstrap.PrimaryBuilderInvocation {
157 commonArgs := make([]string, 0, 0)
158
159 if !config.skipSoongTests {
160 commonArgs = append(commonArgs, "-t")
161 }
162
163 commonArgs = append(commonArgs, "-l", filepath.Join(config.FileListDir(), "Android.bp.list"))
164
165 if os.Getenv("SOONG_DELVE") != "" {
166 commonArgs = append(commonArgs, "--delve_listen", os.Getenv("SOONG_DELVE"))
167 commonArgs = append(commonArgs, "--delve_path", shared.ResolveDelveBinary())
168 }
169
170 allArgs := make([]string, 0, 0)
171 allArgs = append(allArgs, specificArgs...)
172 allArgs = append(allArgs,
173 "--globListDir", name,
174 "--globFile", config.NamedGlobFile(name))
175
176 allArgs = append(allArgs, commonArgs...)
177 allArgs = append(allArgs, environmentArgs(config, name)...)
178 allArgs = append(allArgs, "Android.bp")
179
180 return bootstrap.PrimaryBuilderInvocation{
181 Inputs: []string{"Android.bp"},
182 Outputs: []string{output},
183 Args: allArgs,
184 }
185}
186
Colin Cross9191df22021-10-29 13:11:32 -0700187// bootstrapEpochCleanup deletes files used by bootstrap during incremental builds across
188// incompatible changes. Incompatible changes are marked by incrementing the bootstrapEpoch
189// constant. A tree is considered out of date for the current epoch of the
190// .soong.bootstrap.epoch.<epoch> file doesn't exist.
191func bootstrapEpochCleanup(ctx Context, config Config) {
192 epochFile := fmt.Sprintf(".soong.bootstrap.epoch.%d", bootstrapEpoch)
193 epochPath := filepath.Join(config.SoongOutDir(), epochFile)
194 if exists, err := fileExists(epochPath); err != nil {
195 ctx.Fatalf("failed to check if bootstrap epoch file %q exists: %q", epochPath, err)
196 } else if !exists {
197 // The tree is out of date for the current epoch, delete files used by bootstrap
198 // and force the primary builder to rerun.
199 os.Remove(filepath.Join(config.SoongOutDir(), "build.ninja"))
200 for _, globFile := range bootstrapGlobFileList(config) {
201 os.Remove(globFile)
202 }
203
204 // Mark the tree as up to date with the current epoch by writing the epoch marker file.
205 writeEmptyFile(ctx, epochPath)
206 }
207}
208
209func bootstrapGlobFileList(config Config) []string {
210 return []string{
211 config.NamedGlobFile(soongBuildTag),
212 config.NamedGlobFile(bp2buildTag),
213 config.NamedGlobFile(jsonModuleGraphTag),
214 config.NamedGlobFile(queryviewTag),
215 config.NamedGlobFile(soongDocsTag),
216 }
217}
218
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200219func bootstrapBlueprint(ctx Context, config Config) {
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100220 ctx.BeginTrace(metrics.RunSoong, "blueprint bootstrap")
221 defer ctx.EndTrace()
222
Colin Cross9191df22021-10-29 13:11:32 -0700223 // Clean up some files for incremental builds across incompatible changes.
224 bootstrapEpochCleanup(ctx, config)
225
Cole Faust65f298c2021-10-28 16:05:13 -0700226 mainSoongBuildExtraArgs := []string{"-o", config.SoongNinjaFile()}
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200227 if config.EmptyNinjaFile() {
228 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--empty-ninja-file")
Lukacs T. Berki745380c2021-04-12 12:07:44 +0200229 }
230
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200231 mainSoongBuildInvocation := primaryBuilderInvocation(
232 config,
233 soongBuildTag,
Cole Faust65f298c2021-10-28 16:05:13 -0700234 config.SoongNinjaFile(),
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200235 mainSoongBuildExtraArgs)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200236
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200237 if config.bazelBuildMode() == mixedBuild {
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200238 // Mixed builds call Bazel from soong_build and they therefore need the
239 // Bazel workspace to be available. Make that so by adding a dependency on
240 // the bp2build marker file to the action that invokes soong_build .
241 mainSoongBuildInvocation.Inputs = append(mainSoongBuildInvocation.Inputs,
242 config.Bp2BuildMarkerFile())
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200243 }
244
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200245 bp2buildInvocation := primaryBuilderInvocation(
246 config,
247 bp2buildTag,
248 config.Bp2BuildMarkerFile(),
249 []string{
250 "--bp2build_marker", config.Bp2BuildMarkerFile(),
251 })
252
253 jsonModuleGraphInvocation := primaryBuilderInvocation(
254 config,
255 jsonModuleGraphTag,
256 config.ModuleGraphFile(),
257 []string{
258 "--module_graph_file", config.ModuleGraphFile(),
259 })
260
261 queryviewInvocation := primaryBuilderInvocation(
262 config,
263 queryviewTag,
264 config.QueryviewMarkerFile(),
265 []string{
266 "--bazel_queryview_dir", filepath.Join(config.SoongOutDir(), "queryview"),
267 })
268
269 soongDocsInvocation := primaryBuilderInvocation(
270 config,
271 soongDocsTag,
272 config.SoongDocsHtml(),
273 []string{
274 "--soong_docs", config.SoongDocsHtml(),
275 })
276
277 globFiles := []string{
278 config.NamedGlobFile(soongBuildTag),
279 config.NamedGlobFile(bp2buildTag),
280 config.NamedGlobFile(jsonModuleGraphTag),
281 config.NamedGlobFile(queryviewTag),
282 config.NamedGlobFile(soongDocsTag),
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200283 }
284
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200285 // The glob .ninja files are subninja'd. However, they are generated during
286 // the build itself so we write an empty file if the file does not exist yet
287 // so that the subninja doesn't fail on clean builds
Colin Cross9191df22021-10-29 13:11:32 -0700288 for _, globFile := range bootstrapGlobFileList(config) {
289 writeEmptyFile(ctx, globFile)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200290 }
291
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200292 var blueprintArgs bootstrap.Args
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200293
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200294 blueprintArgs.ModuleListFile = filepath.Join(config.FileListDir(), "Android.bp.list")
295 blueprintArgs.OutFile = shared.JoinPath(config.SoongOutDir(), ".bootstrap/build.ninja")
296 blueprintArgs.EmptyNinjaFile = false
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200297
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100298 blueprintCtx := blueprint.NewContext()
299 blueprintCtx.SetIgnoreUnknownModuleTypes(true)
300 blueprintConfig := BlueprintConfig{
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200301 soongOutDir: config.SoongOutDir(),
302 toolDir: config.HostToolDir(),
303 outDir: config.OutDir(),
304 runGoTests: !config.skipSoongTests,
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200305 // If we want to debug soong_build, we need to compile it for debugging
306 debugCompilation: os.Getenv("SOONG_DELVE") != "",
307 subninjas: globFiles,
308 primaryBuilderInvocations: []bootstrap.PrimaryBuilderInvocation{
309 mainSoongBuildInvocation,
310 bp2buildInvocation,
311 jsonModuleGraphInvocation,
312 queryviewInvocation,
313 soongDocsInvocation},
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100314 }
315
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200316 bootstrapDeps := bootstrap.RunBlueprint(blueprintArgs, bootstrap.DoEverything, blueprintCtx, blueprintConfig)
317 bootstrapDepFile := shared.JoinPath(config.SoongOutDir(), ".bootstrap/build.ninja.d")
318 err := deptools.WriteDepFile(bootstrapDepFile, blueprintArgs.OutFile, bootstrapDeps)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200319 if err != nil {
320 ctx.Fatalf("Error writing depfile '%s': %s", bootstrapDepFile, err)
321 }
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100322}
323
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200324func checkEnvironmentFile(currentEnv *Environment, envFile string) {
325 getenv := func(k string) string {
326 v, _ := currentEnv.Get(k)
327 return v
328 }
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200329
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200330 if stale, _ := shared.StaleEnvFile(envFile, getenv); stale {
331 os.Remove(envFile)
332 }
333}
334
Dan Willemsen1e704462016-08-21 15:17:17 -0700335func runSoong(ctx Context, config Config) {
Nan Zhang17f27672018-12-12 16:01:49 -0800336 ctx.BeginTrace(metrics.RunSoong, "soong")
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700337 defer ctx.EndTrace()
338
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100339 // We have two environment files: .available is the one with every variable,
340 // .used with the ones that were actually used. The latter is used to
341 // determine whether Soong needs to be re-run since why re-run it if only
342 // unused variables were changed?
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200343 envFile := filepath.Join(config.SoongOutDir(), availableEnvFile)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100344
Lukacs T. Berki9d7cf6a2021-08-16 14:08:57 +0200345 dir := filepath.Join(config.SoongOutDir(), ".bootstrap")
346 if err := os.MkdirAll(dir, 0755); err != nil {
347 ctx.Fatalf("Cannot mkdir " + dir)
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100348 }
Colin Cross00a8a3f2020-10-29 14:08:31 -0700349
Chris Parsonsec1a3dc2021-04-20 15:32:07 -0400350 buildMode := config.bazelBuildMode()
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200351 integratedBp2Build := buildMode == mixedBuild
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200352
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100353 // This is done unconditionally, but does not take a measurable amount of time
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200354 bootstrapBlueprint(ctx, config)
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700355
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100356 soongBuildEnv := config.Environment().Copy()
357 soongBuildEnv.Set("TOP", os.Getenv("TOP"))
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100358 // For Bazel mixed builds.
359 soongBuildEnv.Set("BAZEL_PATH", "./tools/bazel")
360 soongBuildEnv.Set("BAZEL_HOME", filepath.Join(config.BazelOutDir(), "bazelhome"))
361 soongBuildEnv.Set("BAZEL_OUTPUT_BASE", filepath.Join(config.BazelOutDir(), "output"))
362 soongBuildEnv.Set("BAZEL_WORKSPACE", absPath(ctx, "."))
363 soongBuildEnv.Set("BAZEL_METRICS_DIR", config.BazelMetricsDir())
364
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100365 // For Soong bootstrapping tests
366 if os.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
367 soongBuildEnv.Set("ALLOW_MISSING_DEPENDENCIES", "true")
368 }
369
Paul Duffin5e85c662021-03-05 12:26:14 +0000370 err := writeEnvironmentFile(ctx, envFile, soongBuildEnv.AsMap())
371 if err != nil {
372 ctx.Fatalf("failed to write environment file %s: %s", envFile, err)
373 }
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100374
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700375 func() {
Nan Zhang17f27672018-12-12 16:01:49 -0800376 ctx.BeginTrace(metrics.RunSoong, "environment check")
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700377 defer ctx.EndTrace()
378
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200379 checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(soongBuildTag))
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200380
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200381 if integratedBp2Build || config.Bp2Build() {
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200382 checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(bp2buildTag))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200383 }
384
385 if config.JsonModuleGraph() {
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200386 checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(jsonModuleGraphTag))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200387 }
388
389 if config.Queryview() {
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200390 checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(queryviewTag))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200391 }
392
393 if config.SoongDocs() {
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200394 checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(soongDocsTag))
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700395 }
396 }()
397
Colin Cross9191df22021-10-29 13:11:32 -0700398 runMicrofactory(ctx, config, "bpglob", "github.com/google/blueprint/bootstrap/bpglob",
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700399 map[string]string{"github.com/google/blueprint": "build/blueprint"})
Dan Willemsen5af1cbe2018-07-05 21:46:51 -0700400
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200401 ninja := func(name, ninjaFile string, targets ...string) {
Nan Zhang17f27672018-12-12 16:01:49 -0800402 ctx.BeginTrace(metrics.RunSoong, name)
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700403 defer ctx.EndTrace()
404
Dan Willemsenb82471a2018-05-17 16:37:09 -0700405 fifo := filepath.Join(config.OutDir(), ".ninja_fifo")
Colin Crossb98d3bc2019-03-21 16:02:58 -0700406 nr := status.NewNinjaReader(ctx, ctx.Status.StartTool(), fifo)
407 defer nr.Close()
Dan Willemsenb82471a2018-05-17 16:37:09 -0700408
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200409 ninjaArgs := []string{
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700410 "-d", "keepdepfile",
Dan Willemsen08218222020-05-18 14:02:02 -0700411 "-d", "stats",
Dan Willemsen6587bed2020-04-18 20:25:59 -0700412 "-o", "usesphonyoutputs=yes",
413 "-o", "preremoveoutputs=yes",
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700414 "-w", "dupbuild=err",
Dan Willemsen6587bed2020-04-18 20:25:59 -0700415 "-w", "outputdir=err",
416 "-w", "missingoutfile=err",
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700417 "-j", strconv.Itoa(config.Parallel()),
Dan Willemsen02736672018-07-17 17:54:31 -0700418 "--frontend_file", fifo,
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200419 "-f", filepath.Join(config.SoongOutDir(), ninjaFile),
420 }
421
422 ninjaArgs = append(ninjaArgs, targets...)
423 cmd := Command(ctx, config, "soong "+name,
424 config.PrebuiltBuildTool("ninja"), ninjaArgs...)
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500425
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100426 var ninjaEnv Environment
Lukacs T. Berki73ab9282021-03-10 10:48:39 +0100427
428 // This is currently how the command line to invoke soong_build finds the
429 // root of the source tree and the output root
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100430 ninjaEnv.Set("TOP", os.Getenv("TOP"))
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100431
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100432 cmd.Environment = &ninjaEnv
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700433 cmd.Sandbox = soongSandbox
Colin Cross7b97ecd2019-06-19 13:17:59 -0700434 cmd.RunAndStreamOrFatal()
Dan Willemsen1e704462016-08-21 15:17:17 -0700435 }
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200436
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200437 targets := make([]string, 0, 0)
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200438
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200439 if config.JsonModuleGraph() {
440 targets = append(targets, config.ModuleGraphFile())
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200441 }
442
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200443 if config.Bp2Build() {
444 targets = append(targets, config.Bp2BuildMarkerFile())
445 }
446
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200447 if config.Queryview() {
448 targets = append(targets, config.QueryviewMarkerFile())
449 }
450
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200451 if config.SoongDocs() {
452 targets = append(targets, config.SoongDocsHtml())
453 }
454
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200455 if config.SoongBuildInvocationNeeded() {
456 // 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 -0700457 targets = append(targets, config.SoongNinjaFile())
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200458 }
459
460 ninja("bootstrap", ".bootstrap/build.ninja", targets...)
Colin Crossb72c9092020-02-10 11:23:49 -0800461
Jingwen Cheneb76c432021-01-28 08:22:12 -0500462 var soongBuildMetrics *soong_metrics_proto.SoongBuildMetrics
463 if shouldCollectBuildSoongMetrics(config) {
464 soongBuildMetrics := loadSoongBuildMetrics(ctx, config)
465 logSoongBuildMetrics(ctx, soongBuildMetrics)
466 }
Colin Crossb72c9092020-02-10 11:23:49 -0800467
Colin Cross8ba7d472020-06-25 11:27:52 -0700468 distGzipFile(ctx, config, config.SoongNinjaFile(), "soong")
469
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000470 if !config.SkipKati() {
Colin Cross8ba7d472020-06-25 11:27:52 -0700471 distGzipFile(ctx, config, config.SoongAndroidMk(), "soong")
472 distGzipFile(ctx, config, config.SoongMakeVarsMk(), "soong")
473 }
474
Jingwen Cheneb76c432021-01-28 08:22:12 -0500475 if shouldCollectBuildSoongMetrics(config) && ctx.Metrics != nil {
Colin Crossb72c9092020-02-10 11:23:49 -0800476 ctx.Metrics.SetSoongBuildMetrics(soongBuildMetrics)
477 }
478}
479
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700480func runMicrofactory(ctx Context, config Config, relExePath string, pkg string, mapping map[string]string) {
481 name := filepath.Base(relExePath)
482 ctx.BeginTrace(metrics.RunSoong, name)
483 defer ctx.EndTrace()
484 cfg := microfactory.Config{TrimPath: absPath(ctx, ".")}
485 for pkgPrefix, pathPrefix := range mapping {
486 cfg.Map(pkgPrefix, pathPrefix)
487 }
488
489 exePath := filepath.Join(config.SoongOutDir(), relExePath)
490 dir := filepath.Dir(exePath)
491 if err := os.MkdirAll(dir, 0777); err != nil {
492 ctx.Fatalf("cannot create %s: %s", dir, err)
493 }
494 if _, err := microfactory.Build(&cfg, exePath, pkg); err != nil {
495 ctx.Fatalf("failed to build %s: %s", name, err)
496 }
497}
498
Jingwen Cheneb76c432021-01-28 08:22:12 -0500499func shouldCollectBuildSoongMetrics(config Config) bool {
Jingwen Chendd9725c2021-06-24 08:41:16 +0000500 // Do not collect metrics protobuf if the soong_build binary ran as the
501 // bp2build converter or the JSON graph dump.
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200502 return config.SoongBuildInvocationNeeded()
Jingwen Cheneb76c432021-01-28 08:22:12 -0500503}
504
Colin Crossb72c9092020-02-10 11:23:49 -0800505func loadSoongBuildMetrics(ctx Context, config Config) *soong_metrics_proto.SoongBuildMetrics {
506 soongBuildMetricsFile := filepath.Join(config.OutDir(), "soong", "soong_build_metrics.pb")
507 buf, err := ioutil.ReadFile(soongBuildMetricsFile)
508 if err != nil {
509 ctx.Fatalf("Failed to load %s: %s", soongBuildMetricsFile, err)
510 }
511 soongBuildMetrics := &soong_metrics_proto.SoongBuildMetrics{}
512 err = proto.Unmarshal(buf, soongBuildMetrics)
513 if err != nil {
514 ctx.Fatalf("Failed to unmarshal %s: %s", soongBuildMetricsFile, err)
515 }
516 return soongBuildMetrics
517}
518
519func logSoongBuildMetrics(ctx Context, metrics *soong_metrics_proto.SoongBuildMetrics) {
520 ctx.Verbosef("soong_build metrics:")
521 ctx.Verbosef(" modules: %v", metrics.GetModules())
522 ctx.Verbosef(" variants: %v", metrics.GetVariants())
523 ctx.Verbosef(" max heap size: %v MB", metrics.GetMaxHeapSize()/1e6)
524 ctx.Verbosef(" total allocation count: %v", metrics.GetTotalAllocCount())
525 ctx.Verbosef(" total allocation size: %v MB", metrics.GetTotalAllocSize()/1e6)
526
Dan Willemsen1e704462016-08-21 15:17:17 -0700527}