blob: 55004fa05c74cbfd9ec2568067c3df450520414c [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. Berki2fad3412022-01-04 14:40:13 +0100190 // NB: Changing the value of this environment variable will not result in a
191 // rebuild. The bootstrap Ninja file will change, but apparently Ninja does
192 // not consider changing the pool specified in a statement a change that's
193 // worth rebuilding for.
194 Console: os.Getenv("SOONG_UNBUFFERED_OUTPUT") == "1",
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200195 }
196}
197
Colin Cross9191df22021-10-29 13:11:32 -0700198// bootstrapEpochCleanup deletes files used by bootstrap during incremental builds across
199// incompatible changes. Incompatible changes are marked by incrementing the bootstrapEpoch
200// constant. A tree is considered out of date for the current epoch of the
201// .soong.bootstrap.epoch.<epoch> file doesn't exist.
202func bootstrapEpochCleanup(ctx Context, config Config) {
203 epochFile := fmt.Sprintf(".soong.bootstrap.epoch.%d", bootstrapEpoch)
204 epochPath := filepath.Join(config.SoongOutDir(), epochFile)
205 if exists, err := fileExists(epochPath); err != nil {
206 ctx.Fatalf("failed to check if bootstrap epoch file %q exists: %q", epochPath, err)
207 } else if !exists {
208 // The tree is out of date for the current epoch, delete files used by bootstrap
209 // and force the primary builder to rerun.
210 os.Remove(filepath.Join(config.SoongOutDir(), "build.ninja"))
211 for _, globFile := range bootstrapGlobFileList(config) {
212 os.Remove(globFile)
213 }
214
215 // Mark the tree as up to date with the current epoch by writing the epoch marker file.
216 writeEmptyFile(ctx, epochPath)
217 }
218}
219
220func bootstrapGlobFileList(config Config) []string {
221 return []string{
222 config.NamedGlobFile(soongBuildTag),
223 config.NamedGlobFile(bp2buildTag),
224 config.NamedGlobFile(jsonModuleGraphTag),
225 config.NamedGlobFile(queryviewTag),
226 config.NamedGlobFile(soongDocsTag),
227 }
228}
229
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200230func bootstrapBlueprint(ctx Context, config Config) {
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100231 ctx.BeginTrace(metrics.RunSoong, "blueprint bootstrap")
232 defer ctx.EndTrace()
233
Colin Cross9191df22021-10-29 13:11:32 -0700234 // Clean up some files for incremental builds across incompatible changes.
235 bootstrapEpochCleanup(ctx, config)
236
Cole Faust65f298c2021-10-28 16:05:13 -0700237 mainSoongBuildExtraArgs := []string{"-o", config.SoongNinjaFile()}
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200238 if config.EmptyNinjaFile() {
239 mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--empty-ninja-file")
Lukacs T. Berki745380c2021-04-12 12:07:44 +0200240 }
241
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200242 mainSoongBuildInvocation := primaryBuilderInvocation(
243 config,
244 soongBuildTag,
Cole Faust65f298c2021-10-28 16:05:13 -0700245 config.SoongNinjaFile(),
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000246 mainSoongBuildExtraArgs,
247 fmt.Sprintf("analyzing Android.bp files and generating ninja file at %s", config.SoongNinjaFile()),
248 )
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200249
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200250 if config.bazelBuildMode() == mixedBuild {
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200251 // Mixed builds call Bazel from soong_build and they therefore need the
252 // Bazel workspace to be available. Make that so by adding a dependency on
253 // the bp2build marker file to the action that invokes soong_build .
254 mainSoongBuildInvocation.Inputs = append(mainSoongBuildInvocation.Inputs,
255 config.Bp2BuildMarkerFile())
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200256 }
257
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200258 bp2buildInvocation := primaryBuilderInvocation(
259 config,
260 bp2buildTag,
261 config.Bp2BuildMarkerFile(),
262 []string{
263 "--bp2build_marker", config.Bp2BuildMarkerFile(),
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000264 },
265 fmt.Sprintf("converting Android.bp files to BUILD files at %s/bp2build", config.SoongOutDir()),
266 )
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200267
268 jsonModuleGraphInvocation := primaryBuilderInvocation(
269 config,
270 jsonModuleGraphTag,
271 config.ModuleGraphFile(),
272 []string{
273 "--module_graph_file", config.ModuleGraphFile(),
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000274 },
275 fmt.Sprintf("generating the Soong module graph at %s", config.ModuleGraphFile()),
276 )
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200277
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000278 queryviewDir := filepath.Join(config.SoongOutDir(), "queryview")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200279 queryviewInvocation := primaryBuilderInvocation(
280 config,
281 queryviewTag,
282 config.QueryviewMarkerFile(),
283 []string{
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000284 "--bazel_queryview_dir", queryviewDir,
285 },
286 fmt.Sprintf("generating the Soong module graph as a Bazel workspace at %s", queryviewDir),
287 )
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200288
289 soongDocsInvocation := primaryBuilderInvocation(
290 config,
291 soongDocsTag,
292 config.SoongDocsHtml(),
293 []string{
294 "--soong_docs", config.SoongDocsHtml(),
Jingwen Chen78fd87f2021-12-06 13:27:43 +0000295 },
296 fmt.Sprintf("generating Soong docs at %s", config.SoongDocsHtml()),
297 )
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200298
299 globFiles := []string{
300 config.NamedGlobFile(soongBuildTag),
301 config.NamedGlobFile(bp2buildTag),
302 config.NamedGlobFile(jsonModuleGraphTag),
303 config.NamedGlobFile(queryviewTag),
304 config.NamedGlobFile(soongDocsTag),
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200305 }
306
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200307 // The glob .ninja files are subninja'd. However, they are generated during
308 // the build itself so we write an empty file if the file does not exist yet
309 // so that the subninja doesn't fail on clean builds
Colin Cross9191df22021-10-29 13:11:32 -0700310 for _, globFile := range bootstrapGlobFileList(config) {
311 writeEmptyFile(ctx, globFile)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200312 }
313
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200314 var blueprintArgs bootstrap.Args
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200315
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200316 blueprintArgs.ModuleListFile = filepath.Join(config.FileListDir(), "Android.bp.list")
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100317 blueprintArgs.OutFile = shared.JoinPath(config.SoongOutDir(), "bootstrap.ninja")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200318 blueprintArgs.EmptyNinjaFile = false
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200319
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100320 blueprintCtx := blueprint.NewContext()
321 blueprintCtx.SetIgnoreUnknownModuleTypes(true)
322 blueprintConfig := BlueprintConfig{
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200323 soongOutDir: config.SoongOutDir(),
324 toolDir: config.HostToolDir(),
325 outDir: config.OutDir(),
326 runGoTests: !config.skipSoongTests,
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200327 // If we want to debug soong_build, we need to compile it for debugging
328 debugCompilation: os.Getenv("SOONG_DELVE") != "",
329 subninjas: globFiles,
330 primaryBuilderInvocations: []bootstrap.PrimaryBuilderInvocation{
331 mainSoongBuildInvocation,
332 bp2buildInvocation,
333 jsonModuleGraphInvocation,
334 queryviewInvocation,
335 soongDocsInvocation},
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100336 }
337
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200338 bootstrapDeps := bootstrap.RunBlueprint(blueprintArgs, bootstrap.DoEverything, blueprintCtx, blueprintConfig)
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100339 bootstrapDepFile := shared.JoinPath(config.SoongOutDir(), "bootstrap.ninja.d")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200340 err := deptools.WriteDepFile(bootstrapDepFile, blueprintArgs.OutFile, bootstrapDeps)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200341 if err != nil {
342 ctx.Fatalf("Error writing depfile '%s': %s", bootstrapDepFile, err)
343 }
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100344}
345
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200346func checkEnvironmentFile(currentEnv *Environment, envFile string) {
347 getenv := func(k string) string {
348 v, _ := currentEnv.Get(k)
349 return v
350 }
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200351
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200352 if stale, _ := shared.StaleEnvFile(envFile, getenv); stale {
353 os.Remove(envFile)
354 }
355}
356
Dan Willemsen1e704462016-08-21 15:17:17 -0700357func runSoong(ctx Context, config Config) {
Nan Zhang17f27672018-12-12 16:01:49 -0800358 ctx.BeginTrace(metrics.RunSoong, "soong")
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700359 defer ctx.EndTrace()
360
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100361 // We have two environment files: .available is the one with every variable,
362 // .used with the ones that were actually used. The latter is used to
363 // determine whether Soong needs to be re-run since why re-run it if only
364 // unused variables were changed?
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200365 envFile := filepath.Join(config.SoongOutDir(), availableEnvFile)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100366
Chris Parsonsec1a3dc2021-04-20 15:32:07 -0400367 buildMode := config.bazelBuildMode()
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200368 integratedBp2Build := buildMode == mixedBuild
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200369
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100370 // This is done unconditionally, but does not take a measurable amount of time
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200371 bootstrapBlueprint(ctx, config)
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700372
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100373 soongBuildEnv := config.Environment().Copy()
374 soongBuildEnv.Set("TOP", os.Getenv("TOP"))
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100375 // For Bazel mixed builds.
376 soongBuildEnv.Set("BAZEL_PATH", "./tools/bazel")
377 soongBuildEnv.Set("BAZEL_HOME", filepath.Join(config.BazelOutDir(), "bazelhome"))
378 soongBuildEnv.Set("BAZEL_OUTPUT_BASE", filepath.Join(config.BazelOutDir(), "output"))
379 soongBuildEnv.Set("BAZEL_WORKSPACE", absPath(ctx, "."))
380 soongBuildEnv.Set("BAZEL_METRICS_DIR", config.BazelMetricsDir())
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500381 soongBuildEnv.Set("LOG_DIR", config.LogsDir())
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100382
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100383 // For Soong bootstrapping tests
384 if os.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
385 soongBuildEnv.Set("ALLOW_MISSING_DEPENDENCIES", "true")
386 }
387
Paul Duffin5e85c662021-03-05 12:26:14 +0000388 err := writeEnvironmentFile(ctx, envFile, soongBuildEnv.AsMap())
389 if err != nil {
390 ctx.Fatalf("failed to write environment file %s: %s", envFile, err)
391 }
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100392
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700393 func() {
Nan Zhang17f27672018-12-12 16:01:49 -0800394 ctx.BeginTrace(metrics.RunSoong, "environment check")
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700395 defer ctx.EndTrace()
396
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200397 checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(soongBuildTag))
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200398
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200399 if integratedBp2Build || config.Bp2Build() {
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200400 checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(bp2buildTag))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200401 }
402
403 if config.JsonModuleGraph() {
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200404 checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(jsonModuleGraphTag))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200405 }
406
407 if config.Queryview() {
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200408 checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(queryviewTag))
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200409 }
410
411 if config.SoongDocs() {
Lukacs T. Berkie1df43f2021-09-08 15:31:14 +0200412 checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(soongDocsTag))
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700413 }
414 }()
415
Colin Cross9191df22021-10-29 13:11:32 -0700416 runMicrofactory(ctx, config, "bpglob", "github.com/google/blueprint/bootstrap/bpglob",
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700417 map[string]string{"github.com/google/blueprint": "build/blueprint"})
Dan Willemsen5af1cbe2018-07-05 21:46:51 -0700418
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200419 ninja := func(name, ninjaFile string, targets ...string) {
Nan Zhang17f27672018-12-12 16:01:49 -0800420 ctx.BeginTrace(metrics.RunSoong, name)
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700421 defer ctx.EndTrace()
422
Dan Willemsenb82471a2018-05-17 16:37:09 -0700423 fifo := filepath.Join(config.OutDir(), ".ninja_fifo")
Colin Crossb98d3bc2019-03-21 16:02:58 -0700424 nr := status.NewNinjaReader(ctx, ctx.Status.StartTool(), fifo)
425 defer nr.Close()
Dan Willemsenb82471a2018-05-17 16:37:09 -0700426
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200427 ninjaArgs := []string{
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700428 "-d", "keepdepfile",
Dan Willemsen08218222020-05-18 14:02:02 -0700429 "-d", "stats",
Dan Willemsen6587bed2020-04-18 20:25:59 -0700430 "-o", "usesphonyoutputs=yes",
431 "-o", "preremoveoutputs=yes",
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700432 "-w", "dupbuild=err",
Dan Willemsen6587bed2020-04-18 20:25:59 -0700433 "-w", "outputdir=err",
434 "-w", "missingoutfile=err",
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700435 "-j", strconv.Itoa(config.Parallel()),
Dan Willemsen02736672018-07-17 17:54:31 -0700436 "--frontend_file", fifo,
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200437 "-f", filepath.Join(config.SoongOutDir(), ninjaFile),
438 }
439
440 ninjaArgs = append(ninjaArgs, targets...)
441 cmd := Command(ctx, config, "soong "+name,
442 config.PrebuiltBuildTool("ninja"), ninjaArgs...)
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500443
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100444 var ninjaEnv Environment
Lukacs T. Berki73ab9282021-03-10 10:48:39 +0100445
446 // This is currently how the command line to invoke soong_build finds the
447 // root of the source tree and the output root
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100448 ninjaEnv.Set("TOP", os.Getenv("TOP"))
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100449
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100450 cmd.Environment = &ninjaEnv
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700451 cmd.Sandbox = soongSandbox
Colin Cross7b97ecd2019-06-19 13:17:59 -0700452 cmd.RunAndStreamOrFatal()
Dan Willemsen1e704462016-08-21 15:17:17 -0700453 }
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200454
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200455 targets := make([]string, 0, 0)
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200456
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200457 if config.JsonModuleGraph() {
458 targets = append(targets, config.ModuleGraphFile())
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200459 }
460
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200461 if config.Bp2Build() {
462 targets = append(targets, config.Bp2BuildMarkerFile())
463 }
464
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200465 if config.Queryview() {
466 targets = append(targets, config.QueryviewMarkerFile())
467 }
468
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200469 if config.SoongDocs() {
470 targets = append(targets, config.SoongDocsHtml())
471 }
472
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200473 if config.SoongBuildInvocationNeeded() {
474 // 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 -0700475 targets = append(targets, config.SoongNinjaFile())
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200476 }
477
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100478 ninja("bootstrap", "bootstrap.ninja", targets...)
Colin Crossb72c9092020-02-10 11:23:49 -0800479
Jingwen Cheneb76c432021-01-28 08:22:12 -0500480 var soongBuildMetrics *soong_metrics_proto.SoongBuildMetrics
481 if shouldCollectBuildSoongMetrics(config) {
482 soongBuildMetrics := loadSoongBuildMetrics(ctx, config)
483 logSoongBuildMetrics(ctx, soongBuildMetrics)
484 }
Colin Crossb72c9092020-02-10 11:23:49 -0800485
Colin Cross8ba7d472020-06-25 11:27:52 -0700486 distGzipFile(ctx, config, config.SoongNinjaFile(), "soong")
487
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000488 if !config.SkipKati() {
Colin Cross8ba7d472020-06-25 11:27:52 -0700489 distGzipFile(ctx, config, config.SoongAndroidMk(), "soong")
490 distGzipFile(ctx, config, config.SoongMakeVarsMk(), "soong")
491 }
492
Jingwen Cheneb76c432021-01-28 08:22:12 -0500493 if shouldCollectBuildSoongMetrics(config) && ctx.Metrics != nil {
Colin Crossb72c9092020-02-10 11:23:49 -0800494 ctx.Metrics.SetSoongBuildMetrics(soongBuildMetrics)
495 }
496}
497
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100498func runMicrofactory(ctx Context, config Config, name string, pkg string, mapping map[string]string) {
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700499 ctx.BeginTrace(metrics.RunSoong, name)
500 defer ctx.EndTrace()
501 cfg := microfactory.Config{TrimPath: absPath(ctx, ".")}
502 for pkgPrefix, pathPrefix := range mapping {
503 cfg.Map(pkgPrefix, pathPrefix)
504 }
505
Lukacs T. Berki90b43342021-11-02 14:42:04 +0100506 exePath := filepath.Join(config.SoongOutDir(), name)
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700507 dir := filepath.Dir(exePath)
508 if err := os.MkdirAll(dir, 0777); err != nil {
509 ctx.Fatalf("cannot create %s: %s", dir, err)
510 }
511 if _, err := microfactory.Build(&cfg, exePath, pkg); err != nil {
512 ctx.Fatalf("failed to build %s: %s", name, err)
513 }
514}
515
Jingwen Cheneb76c432021-01-28 08:22:12 -0500516func shouldCollectBuildSoongMetrics(config Config) bool {
Jingwen Chendd9725c2021-06-24 08:41:16 +0000517 // Do not collect metrics protobuf if the soong_build binary ran as the
518 // bp2build converter or the JSON graph dump.
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200519 return config.SoongBuildInvocationNeeded()
Jingwen Cheneb76c432021-01-28 08:22:12 -0500520}
521
Colin Crossb72c9092020-02-10 11:23:49 -0800522func loadSoongBuildMetrics(ctx Context, config Config) *soong_metrics_proto.SoongBuildMetrics {
523 soongBuildMetricsFile := filepath.Join(config.OutDir(), "soong", "soong_build_metrics.pb")
524 buf, err := ioutil.ReadFile(soongBuildMetricsFile)
525 if err != nil {
526 ctx.Fatalf("Failed to load %s: %s", soongBuildMetricsFile, err)
527 }
528 soongBuildMetrics := &soong_metrics_proto.SoongBuildMetrics{}
529 err = proto.Unmarshal(buf, soongBuildMetrics)
530 if err != nil {
531 ctx.Fatalf("Failed to unmarshal %s: %s", soongBuildMetricsFile, err)
532 }
533 return soongBuildMetrics
534}
535
536func logSoongBuildMetrics(ctx Context, metrics *soong_metrics_proto.SoongBuildMetrics) {
537 ctx.Verbosef("soong_build metrics:")
538 ctx.Verbosef(" modules: %v", metrics.GetModules())
539 ctx.Verbosef(" variants: %v", metrics.GetVariants())
540 ctx.Verbosef(" max heap size: %v MB", metrics.GetMaxHeapSize()/1e6)
541 ctx.Verbosef(" total allocation count: %v", metrics.GetTotalAllocCount())
542 ctx.Verbosef(" total allocation size: %v MB", metrics.GetTotalAllocSize()/1e6)
543
Dan Willemsen1e704462016-08-21 15:17:17 -0700544}