blob: 5360342ebbaaa7060f24bb1c3dfedfe2672f7dcd [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
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000156func primaryBuilderInvocation(
157 config Config,
158 name string,
159 output string,
160 specificArgs []string,
161 description string) bootstrap.PrimaryBuilderInvocation {
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200162 commonArgs := make([]string, 0, 0)
163
164 if !config.skipSoongTests {
165 commonArgs = append(commonArgs, "-t")
166 }
167
168 commonArgs = append(commonArgs, "-l", filepath.Join(config.FileListDir(), "Android.bp.list"))
169
170 if os.Getenv("SOONG_DELVE") != "" {
171 commonArgs = append(commonArgs, "--delve_listen", os.Getenv("SOONG_DELVE"))
172 commonArgs = append(commonArgs, "--delve_path", shared.ResolveDelveBinary())
173 }
174
175 allArgs := make([]string, 0, 0)
176 allArgs = append(allArgs, specificArgs...)
177 allArgs = append(allArgs,
178 "--globListDir", name,
179 "--globFile", config.NamedGlobFile(name))
180
181 allArgs = append(allArgs, commonArgs...)
182 allArgs = append(allArgs, environmentArgs(config, name)...)
183 allArgs = append(allArgs, "Android.bp")
184
185 return bootstrap.PrimaryBuilderInvocation{
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000186 Inputs: []string{"Android.bp"},
187 Outputs: []string{output},
188 Args: allArgs,
189 Description: description,
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200190 }
191}
192
Colin Cross9191df22021-10-29 13:11:32 -0700193// bootstrapEpochCleanup deletes files used by bootstrap during incremental builds across
194// incompatible changes. Incompatible changes are marked by incrementing the bootstrapEpoch
195// constant. A tree is considered out of date for the current epoch of the
196// .soong.bootstrap.epoch.<epoch> file doesn't exist.
197func bootstrapEpochCleanup(ctx Context, config Config) {
198 epochFile := fmt.Sprintf(".soong.bootstrap.epoch.%d", bootstrapEpoch)
199 epochPath := filepath.Join(config.SoongOutDir(), epochFile)
200 if exists, err := fileExists(epochPath); err != nil {
201 ctx.Fatalf("failed to check if bootstrap epoch file %q exists: %q", epochPath, err)
202 } else if !exists {
203 // The tree is out of date for the current epoch, delete files used by bootstrap
204 // and force the primary builder to rerun.
205 os.Remove(filepath.Join(config.SoongOutDir(), "build.ninja"))
206 for _, globFile := range bootstrapGlobFileList(config) {
207 os.Remove(globFile)
208 }
209
210 // Mark the tree as up to date with the current epoch by writing the epoch marker file.
211 writeEmptyFile(ctx, epochPath)
212 }
213}
214
215func bootstrapGlobFileList(config Config) []string {
216 return []string{
217 config.NamedGlobFile(soongBuildTag),
218 config.NamedGlobFile(bp2buildTag),
219 config.NamedGlobFile(jsonModuleGraphTag),
220 config.NamedGlobFile(queryviewTag),
221 config.NamedGlobFile(soongDocsTag),
222 }
223}
224
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200225func bootstrapBlueprint(ctx Context, config Config) {
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100226 ctx.BeginTrace(metrics.RunSoong, "blueprint bootstrap")
227 defer ctx.EndTrace()
228
Colin Cross9191df22021-10-29 13:11:32 -0700229 // Clean up some files for incremental builds across incompatible changes.
230 bootstrapEpochCleanup(ctx, config)
231
Cole Faust65f298c2021-10-28 16:05:13 -0700232 mainSoongBuildExtraArgs := []string{"-o", config.SoongNinjaFile()}
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200233 if config.EmptyNinjaFile() {
234 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--empty-ninja-file")
Lukacs T. Berki745380c2021-04-12 12:07:44 +0200235 }
236
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200237 mainSoongBuildInvocation := primaryBuilderInvocation(
238 config,
239 soongBuildTag,
Cole Faust65f298c2021-10-28 16:05:13 -0700240 config.SoongNinjaFile(),
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000241 mainSoongBuildExtraArgs,
242 fmt.Sprintf("analyzing Android.bp files and generating ninja file at %s", config.SoongNinjaFile()),
243 )
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200244
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200245 if config.bazelBuildMode() == mixedBuild {
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200246 // Mixed builds call Bazel from soong_build and they therefore need the
247 // Bazel workspace to be available. Make that so by adding a dependency on
248 // the bp2build marker file to the action that invokes soong_build .
249 mainSoongBuildInvocation.Inputs = append(mainSoongBuildInvocation.Inputs,
250 config.Bp2BuildMarkerFile())
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200251 }
252
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200253 bp2buildInvocation := primaryBuilderInvocation(
254 config,
255 bp2buildTag,
256 config.Bp2BuildMarkerFile(),
257 []string{
258 "--bp2build_marker", config.Bp2BuildMarkerFile(),
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000259 },
260 fmt.Sprintf("converting Android.bp files to BUILD files at %s/bp2build", config.SoongOutDir()),
261 )
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200262
263 jsonModuleGraphInvocation := primaryBuilderInvocation(
264 config,
265 jsonModuleGraphTag,
266 config.ModuleGraphFile(),
267 []string{
268 "--module_graph_file", config.ModuleGraphFile(),
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000269 },
270 fmt.Sprintf("generating the Soong module graph at %s", config.ModuleGraphFile()),
271 )
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200272
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000273 queryviewDir := filepath.Join(config.SoongOutDir(), "queryview")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200274 queryviewInvocation := primaryBuilderInvocation(
275 config,
276 queryviewTag,
277 config.QueryviewMarkerFile(),
278 []string{
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000279 "--bazel_queryview_dir", queryviewDir,
280 },
281 fmt.Sprintf("generating the Soong module graph as a Bazel workspace at %s", queryviewDir),
282 )
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200283
284 soongDocsInvocation := primaryBuilderInvocation(
285 config,
286 soongDocsTag,
287 config.SoongDocsHtml(),
288 []string{
289 "--soong_docs", config.SoongDocsHtml(),
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000290 },
291 fmt.Sprintf("generating Soong docs at %s", config.SoongDocsHtml()),
292 )
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200293
294 globFiles := []string{
295 config.NamedGlobFile(soongBuildTag),
296 config.NamedGlobFile(bp2buildTag),
297 config.NamedGlobFile(jsonModuleGraphTag),
298 config.NamedGlobFile(queryviewTag),
299 config.NamedGlobFile(soongDocsTag),
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200300 }
301
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200302 // The glob .ninja files are subninja'd. However, they are generated during
303 // the build itself so we write an empty file if the file does not exist yet
304 // so that the subninja doesn't fail on clean builds
Colin Cross9191df22021-10-29 13:11:32 -0700305 for _, globFile := range bootstrapGlobFileList(config) {
306 writeEmptyFile(ctx, globFile)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200307 }
308
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200309 var blueprintArgs bootstrap.Args
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200310
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200311 blueprintArgs.ModuleListFile = filepath.Join(config.FileListDir(), "Android.bp.list")
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100312 blueprintArgs.OutFile = shared.JoinPath(config.SoongOutDir(), "bootstrap.ninja")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200313 blueprintArgs.EmptyNinjaFile = false
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200314
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100315 blueprintCtx := blueprint.NewContext()
316 blueprintCtx.SetIgnoreUnknownModuleTypes(true)
317 blueprintConfig := BlueprintConfig{
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200318 soongOutDir: config.SoongOutDir(),
319 toolDir: config.HostToolDir(),
320 outDir: config.OutDir(),
321 runGoTests: !config.skipSoongTests,
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200322 // If we want to debug soong_build, we need to compile it for debugging
323 debugCompilation: os.Getenv("SOONG_DELVE") != "",
324 subninjas: globFiles,
325 primaryBuilderInvocations: []bootstrap.PrimaryBuilderInvocation{
326 mainSoongBuildInvocation,
327 bp2buildInvocation,
328 jsonModuleGraphInvocation,
329 queryviewInvocation,
330 soongDocsInvocation},
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100331 }
332
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200333 bootstrapDeps := bootstrap.RunBlueprint(blueprintArgs, bootstrap.DoEverything, blueprintCtx, blueprintConfig)
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100334 bootstrapDepFile := shared.JoinPath(config.SoongOutDir(), "bootstrap.ninja.d")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200335 err := deptools.WriteDepFile(bootstrapDepFile, blueprintArgs.OutFile, bootstrapDeps)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200336 if err != nil {
337 ctx.Fatalf("Error writing depfile '%s': %s", bootstrapDepFile, err)
338 }
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100339}
340
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200341func checkEnvironmentFile(currentEnv *Environment, envFile string) {
342 getenv := func(k string) string {
343 v, _ := currentEnv.Get(k)
344 return v
345 }
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200346
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200347 if stale, _ := shared.StaleEnvFile(envFile, getenv); stale {
348 os.Remove(envFile)
349 }
350}
351
Dan Willemsen1e704462016-08-21 15:17:17 -0700352func runSoong(ctx Context, config Config) {
Nan Zhang17f27672018-12-12 16:01:49 -0800353 ctx.BeginTrace(metrics.RunSoong, "soong")
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700354 defer ctx.EndTrace()
355
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100356 // We have two environment files: .available is the one with every variable,
357 // .used with the ones that were actually used. The latter is used to
358 // determine whether Soong needs to be re-run since why re-run it if only
359 // unused variables were changed?
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200360 envFile := filepath.Join(config.SoongOutDir(), availableEnvFile)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100361
Chris Parsonsec1a3dc2021-04-20 15:32:07 -0400362 buildMode := config.bazelBuildMode()
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200363 integratedBp2Build := buildMode == mixedBuild
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200364
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100365 // This is done unconditionally, but does not take a measurable amount of time
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200366 bootstrapBlueprint(ctx, config)
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700367
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100368 soongBuildEnv := config.Environment().Copy()
369 soongBuildEnv.Set("TOP", os.Getenv("TOP"))
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100370 // For Bazel mixed builds.
371 soongBuildEnv.Set("BAZEL_PATH", "./tools/bazel")
372 soongBuildEnv.Set("BAZEL_HOME", filepath.Join(config.BazelOutDir(), "bazelhome"))
373 soongBuildEnv.Set("BAZEL_OUTPUT_BASE", filepath.Join(config.BazelOutDir(), "output"))
374 soongBuildEnv.Set("BAZEL_WORKSPACE", absPath(ctx, "."))
375 soongBuildEnv.Set("BAZEL_METRICS_DIR", config.BazelMetricsDir())
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500376 soongBuildEnv.Set("LOG_DIR", config.LogsDir())
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100377
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100378 // For Soong bootstrapping tests
379 if os.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
380 soongBuildEnv.Set("ALLOW_MISSING_DEPENDENCIES", "true")
381 }
382
Paul Duffin5e85c662021-03-05 12:26:14 +0000383 err := writeEnvironmentFile(ctx, envFile, soongBuildEnv.AsMap())
384 if err != nil {
385 ctx.Fatalf("failed to write environment file %s: %s", envFile, err)
386 }
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100387
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700388 func() {
Nan Zhang17f27672018-12-12 16:01:49 -0800389 ctx.BeginTrace(metrics.RunSoong, "environment check")
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700390 defer ctx.EndTrace()
391
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200392 checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(soongBuildTag))
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200393
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200394 if integratedBp2Build || config.Bp2Build() {
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200395 checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(bp2buildTag))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200396 }
397
398 if config.JsonModuleGraph() {
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200399 checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(jsonModuleGraphTag))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200400 }
401
402 if config.Queryview() {
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200403 checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(queryviewTag))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200404 }
405
406 if config.SoongDocs() {
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200407 checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(soongDocsTag))
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700408 }
409 }()
410
Colin Cross9191df22021-10-29 13:11:32 -0700411 runMicrofactory(ctx, config, "bpglob", "github.com/google/blueprint/bootstrap/bpglob",
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700412 map[string]string{"github.com/google/blueprint": "build/blueprint"})
Dan Willemsen5af1cbe2018-07-05 21:46:51 -0700413
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200414 ninja := func(name, ninjaFile string, targets ...string) {
Nan Zhang17f27672018-12-12 16:01:49 -0800415 ctx.BeginTrace(metrics.RunSoong, name)
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700416 defer ctx.EndTrace()
417
Dan Willemsenb82471a2018-05-17 16:37:09 -0700418 fifo := filepath.Join(config.OutDir(), ".ninja_fifo")
Colin Crossb98d3bc2019-03-21 16:02:58 -0700419 nr := status.NewNinjaReader(ctx, ctx.Status.StartTool(), fifo)
420 defer nr.Close()
Dan Willemsenb82471a2018-05-17 16:37:09 -0700421
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200422 ninjaArgs := []string{
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700423 "-d", "keepdepfile",
Dan Willemsen08218222020-05-18 14:02:02 -0700424 "-d", "stats",
Dan Willemsen6587bed2020-04-18 20:25:59 -0700425 "-o", "usesphonyoutputs=yes",
426 "-o", "preremoveoutputs=yes",
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700427 "-w", "dupbuild=err",
Dan Willemsen6587bed2020-04-18 20:25:59 -0700428 "-w", "outputdir=err",
429 "-w", "missingoutfile=err",
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700430 "-j", strconv.Itoa(config.Parallel()),
Dan Willemsen02736672018-07-17 17:54:31 -0700431 "--frontend_file", fifo,
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200432 "-f", filepath.Join(config.SoongOutDir(), ninjaFile),
433 }
434
435 ninjaArgs = append(ninjaArgs, targets...)
436 cmd := Command(ctx, config, "soong "+name,
437 config.PrebuiltBuildTool("ninja"), ninjaArgs...)
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500438
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100439 var ninjaEnv Environment
Lukacs T. Berki73ab9282021-03-10 10:48:39 +0100440
441 // This is currently how the command line to invoke soong_build finds the
442 // root of the source tree and the output root
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100443 ninjaEnv.Set("TOP", os.Getenv("TOP"))
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100444
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100445 cmd.Environment = &ninjaEnv
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700446 cmd.Sandbox = soongSandbox
Colin Cross7b97ecd2019-06-19 13:17:59 -0700447 cmd.RunAndStreamOrFatal()
Dan Willemsen1e704462016-08-21 15:17:17 -0700448 }
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200449
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200450 targets := make([]string, 0, 0)
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200451
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200452 if config.JsonModuleGraph() {
453 targets = append(targets, config.ModuleGraphFile())
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200454 }
455
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200456 if config.Bp2Build() {
457 targets = append(targets, config.Bp2BuildMarkerFile())
458 }
459
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200460 if config.Queryview() {
461 targets = append(targets, config.QueryviewMarkerFile())
462 }
463
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200464 if config.SoongDocs() {
465 targets = append(targets, config.SoongDocsHtml())
466 }
467
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200468 if config.SoongBuildInvocationNeeded() {
469 // 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 -0700470 targets = append(targets, config.SoongNinjaFile())
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200471 }
472
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100473 ninja("bootstrap", "bootstrap.ninja", targets...)
Colin Crossb72c9092020-02-10 11:23:49 -0800474
Jingwen Cheneb76c432021-01-28 08:22:12 -0500475 var soongBuildMetrics *soong_metrics_proto.SoongBuildMetrics
476 if shouldCollectBuildSoongMetrics(config) {
477 soongBuildMetrics := loadSoongBuildMetrics(ctx, config)
478 logSoongBuildMetrics(ctx, soongBuildMetrics)
479 }
Colin Crossb72c9092020-02-10 11:23:49 -0800480
Colin Cross8ba7d472020-06-25 11:27:52 -0700481 distGzipFile(ctx, config, config.SoongNinjaFile(), "soong")
482
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000483 if !config.SkipKati() {
Colin Cross8ba7d472020-06-25 11:27:52 -0700484 distGzipFile(ctx, config, config.SoongAndroidMk(), "soong")
485 distGzipFile(ctx, config, config.SoongMakeVarsMk(), "soong")
486 }
487
Jingwen Cheneb76c432021-01-28 08:22:12 -0500488 if shouldCollectBuildSoongMetrics(config) && ctx.Metrics != nil {
Colin Crossb72c9092020-02-10 11:23:49 -0800489 ctx.Metrics.SetSoongBuildMetrics(soongBuildMetrics)
490 }
491}
492
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100493func runMicrofactory(ctx Context, config Config, name string, pkg string, mapping map[string]string) {
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700494 ctx.BeginTrace(metrics.RunSoong, name)
495 defer ctx.EndTrace()
496 cfg := microfactory.Config{TrimPath: absPath(ctx, ".")}
497 for pkgPrefix, pathPrefix := range mapping {
498 cfg.Map(pkgPrefix, pathPrefix)
499 }
500
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100501 exePath := filepath.Join(config.SoongOutDir(), name)
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700502 dir := filepath.Dir(exePath)
503 if err := os.MkdirAll(dir, 0777); err != nil {
504 ctx.Fatalf("cannot create %s: %s", dir, err)
505 }
506 if _, err := microfactory.Build(&cfg, exePath, pkg); err != nil {
507 ctx.Fatalf("failed to build %s: %s", name, err)
508 }
509}
510
Jingwen Cheneb76c432021-01-28 08:22:12 -0500511func shouldCollectBuildSoongMetrics(config Config) bool {
Jingwen Chendd9725c2021-06-24 08:41:16 +0000512 // Do not collect metrics protobuf if the soong_build binary ran as the
513 // bp2build converter or the JSON graph dump.
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200514 return config.SoongBuildInvocationNeeded()
Jingwen Cheneb76c432021-01-28 08:22:12 -0500515}
516
Colin Crossb72c9092020-02-10 11:23:49 -0800517func loadSoongBuildMetrics(ctx Context, config Config) *soong_metrics_proto.SoongBuildMetrics {
518 soongBuildMetricsFile := filepath.Join(config.OutDir(), "soong", "soong_build_metrics.pb")
519 buf, err := ioutil.ReadFile(soongBuildMetricsFile)
520 if err != nil {
521 ctx.Fatalf("Failed to load %s: %s", soongBuildMetricsFile, err)
522 }
523 soongBuildMetrics := &soong_metrics_proto.SoongBuildMetrics{}
524 err = proto.Unmarshal(buf, soongBuildMetrics)
525 if err != nil {
526 ctx.Fatalf("Failed to unmarshal %s: %s", soongBuildMetricsFile, err)
527 }
528 return soongBuildMetrics
529}
530
531func logSoongBuildMetrics(ctx Context, metrics *soong_metrics_proto.SoongBuildMetrics) {
532 ctx.Verbosef("soong_build metrics:")
533 ctx.Verbosef(" modules: %v", metrics.GetModules())
534 ctx.Verbosef(" variants: %v", metrics.GetVariants())
535 ctx.Verbosef(" max heap size: %v MB", metrics.GetMaxHeapSize()/1e6)
536 ctx.Verbosef(" total allocation count: %v", metrics.GetTotalAllocCount())
537 ctx.Verbosef(" total allocation size: %v MB", metrics.GetTotalAllocSize()/1e6)
538
Dan Willemsen1e704462016-08-21 15:17:17 -0700539}