blob: 26afd43ea8914a85a15f9ad89af75a4b39029c8f [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 Crossb72c9092020-02-10 11:23:49 -080018 "io/ioutil"
Dan Willemsen99a75cd2017-08-04 16:04:04 -070019 "os"
Dan Willemsen1e704462016-08-21 15:17:17 -070020 "path/filepath"
Dan Willemsen99a75cd2017-08-04 16:04:04 -070021 "strconv"
Dan Willemsen99a75cd2017-08-04 16:04:04 -070022
Dan Willemsen4591b642021-05-24 14:24:12 -070023 "android/soong/ui/metrics"
Colin Crossb72c9092020-02-10 11:23:49 -080024 soong_metrics_proto "android/soong/ui/metrics/metrics_proto"
Dan Willemsen4591b642021-05-24 14:24:12 -070025 "android/soong/ui/status"
26
27 "android/soong/shared"
28
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010029 "github.com/google/blueprint"
30 "github.com/google/blueprint/bootstrap"
Dan Willemsen4591b642021-05-24 14:24:12 -070031 "github.com/google/blueprint/deptools"
Dan Willemsen99a75cd2017-08-04 16:04:04 -070032 "github.com/google/blueprint/microfactory"
Dan Willemsenb82471a2018-05-17 16:37:09 -070033
Dan Willemsen4591b642021-05-24 14:24:12 -070034 "google.golang.org/protobuf/proto"
Dan Willemsen1e704462016-08-21 15:17:17 -070035)
36
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020037const (
38 availableEnvFile = "soong.environment.available"
39 usedEnvFile = "soong.environment.used"
40)
41
Lukacs T. Berki7690c092021-02-26 14:27:36 +010042func writeEnvironmentFile(ctx Context, envFile string, envDeps map[string]string) error {
43 data, err := shared.EnvFileContents(envDeps)
44 if err != nil {
45 return err
46 }
47
48 return ioutil.WriteFile(envFile, data, 0644)
49}
50
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000051// This uses Android.bp files and various tools to generate <builddir>/build.ninja.
52//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010053// However, the execution of <builddir>/build.ninja happens later in
54// build/soong/ui/build/build.go#Build()
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000055//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010056// We want to rely on as few prebuilts as possible, so we need to bootstrap
57// Soong. The process is as follows:
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000058//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010059// 1. We use "Microfactory", a simple tool to compile Go code, to build
60// first itself, then soong_ui from soong_ui.bash. This binary contains
61// parts of soong_build that are needed to build itself.
62// 2. This simplified version of soong_build then reads the Blueprint files
63// that describe itself and emits .bootstrap/build.ninja that describes
64// how to build its full version and use that to produce the final Ninja
65// file Soong emits.
66// 3. soong_ui executes .bootstrap/build.ninja
Rupert Shuttleworthb7d97102020-11-25 10:19:29 +000067//
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010068// (After this, Kati is executed to parse the Makefiles, but that's not part of
69// bootstrapping Soong)
70
71// A tiny struct used to tell Blueprint that it's in bootstrap mode. It would
72// probably be nicer to use a flag in bootstrap.Args instead.
73type BlueprintConfig struct {
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +020074 toolDir string
75 soongOutDir string
76 outDir string
77 runGoTests bool
78 useValidations bool
79 debugCompilation bool
80 subninjas []string
81 primaryBuilderInvocations []bootstrap.PrimaryBuilderInvocation
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010082}
83
Lukacs T. Berkia806e412021-09-01 08:57:48 +020084func (c BlueprintConfig) HostToolDir() string {
85 return c.toolDir
86}
87
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +020088func (c BlueprintConfig) SoongOutDir() string {
89 return c.soongOutDir
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010090}
91
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +020092func (c BlueprintConfig) OutDir() string {
93 return c.outDir
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010094}
95
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +020096func (c BlueprintConfig) RunGoTests() bool {
97 return c.runGoTests
98}
99
100func (c BlueprintConfig) UseValidationsForGoTests() bool {
101 return c.useValidations
102}
103
Lukacs T. Berki5f6cb1d2021-03-17 15:03:14 +0100104func (c BlueprintConfig) DebugCompilation() bool {
105 return c.debugCompilation
106}
107
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +0200108func (c BlueprintConfig) Subninjas() []string {
109 return c.subninjas
110}
111
112func (c BlueprintConfig) PrimaryBuilderInvocations() []bootstrap.PrimaryBuilderInvocation {
113 return c.primaryBuilderInvocations
114}
115
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200116func environmentArgs(config Config, suffix string) []string {
117 return []string{
118 "--available_env", shared.JoinPath(config.SoongOutDir(), availableEnvFile),
119 "--used_env", shared.JoinPath(config.SoongOutDir(), usedEnvFile+suffix),
120 }
121}
Spandan Das8f99ae62021-06-11 16:48:06 +0000122
123func writeEmptyGlobFile(ctx Context, path string) {
124 err := os.MkdirAll(filepath.Dir(path), 0777)
125 if err != nil {
126 ctx.Fatalf("Failed to create parent directories of empty ninja glob file '%s': %s", path, err)
127 }
128
129 if _, err := os.Stat(path); os.IsNotExist(err) {
130 err = ioutil.WriteFile(path, nil, 0666)
131 if err != nil {
132 ctx.Fatalf("Failed to create empty ninja glob file '%s': %s", path, err)
133 }
134 }
135}
136
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200137func bootstrapBlueprint(ctx Context, config Config) {
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100138 ctx.BeginTrace(metrics.RunSoong, "blueprint bootstrap")
139 defer ctx.EndTrace()
140
141 var args bootstrap.Args
142
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200143 bootstrapGlobFile := shared.JoinPath(config.SoongOutDir(), ".bootstrap/build-globs.ninja")
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200144 bp2buildGlobFile := shared.JoinPath(config.SoongOutDir(), ".bootstrap/build-globs.bp2build.ninja")
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200145 queryviewGlobFile := shared.JoinPath(config.SoongOutDir(), ".bootstrap/build-globs.queryview.ninja")
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200146 moduleGraphGlobFile := shared.JoinPath(config.SoongOutDir(), ".bootstrap/build-globs.modulegraph.ninja")
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200147
148 // The glob .ninja files are subninja'd. However, they are generated during
149 // the build itself so we write an empty file so that the subninja doesn't
150 // fail on clean builds
Spandan Das8f99ae62021-06-11 16:48:06 +0000151 writeEmptyGlobFile(ctx, bootstrapGlobFile)
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200152 writeEmptyGlobFile(ctx, bp2buildGlobFile)
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200153 writeEmptyGlobFile(ctx, queryviewGlobFile)
154 writeEmptyGlobFile(ctx, moduleGraphGlobFile)
155
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200156 bootstrapDepFile := shared.JoinPath(config.SoongOutDir(), ".bootstrap/build.ninja.d")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200157
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100158 args.RunGoTests = !config.skipSoongTests
159 args.UseValidations = true // Use validations to depend on tests
Lukacs T. Berkib078ade2021-08-31 10:42:08 +0200160 args.SoongOutDir = config.SoongOutDir()
161 args.OutDir = config.OutDir()
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100162 args.ModuleListFile = filepath.Join(config.FileListDir(), "Android.bp.list")
163 args.OutFile = shared.JoinPath(config.SoongOutDir(), ".bootstrap/build.ninja")
Spandan Das8f99ae62021-06-11 16:48:06 +0000164 // The primary builder (aka soong_build) will use bootstrapGlobFile as the globFile to generate build.ninja(.d)
165 // Building soong_build does not require a glob file
166 // Using "" instead of "<soong_build_glob>.ninja" will ensure that an unused glob file is not written to out/soong/.bootstrap during StagePrimary
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200167 args.Subninjas = []string{bootstrapGlobFile, bp2buildGlobFile, moduleGraphGlobFile, queryviewGlobFile}
Colin Crossf3bdbcb2021-06-01 11:43:55 -0700168 args.EmptyNinjaFile = config.EmptyNinjaFile()
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100169
Lukacs T. Berki745380c2021-04-12 12:07:44 +0200170 args.DelveListen = os.Getenv("SOONG_DELVE")
171 if args.DelveListen != "" {
172 args.DelvePath = shared.ResolveDelveBinary()
173 }
174
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200175 commonArgs := bootstrap.PrimaryBuilderExtraFlags(args, config.MainNinjaFile())
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200176 mainSoongBuildInputs := []string{"Android.bp"}
177
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200178 if config.bazelBuildMode() == mixedBuild {
179 mainSoongBuildInputs = append(mainSoongBuildInputs, config.Bp2BuildMarkerFile())
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200180 }
181
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200182 soongBuildArgs := []string{
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200183 "--globListDir", "build",
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200184 "--globFile", bootstrapGlobFile,
185 }
186
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200187 soongBuildArgs = append(soongBuildArgs, commonArgs...)
188 soongBuildArgs = append(soongBuildArgs, environmentArgs(config, "")...)
189 soongBuildArgs = append(soongBuildArgs, "Android.bp")
190
191 mainSoongBuildInvocation := bootstrap.PrimaryBuilderInvocation{
192 Inputs: mainSoongBuildInputs,
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200193 Outputs: []string{config.MainNinjaFile()},
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200194 Args: soongBuildArgs,
195 }
196
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200197 bp2buildArgs := []string{
198 "--bp2build_marker", config.Bp2BuildMarkerFile(),
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200199 "--globListDir", "bp2build",
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200200 "--globFile", bp2buildGlobFile,
201 }
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200202
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200203 bp2buildArgs = append(bp2buildArgs, commonArgs...)
204 bp2buildArgs = append(bp2buildArgs, environmentArgs(config, ".bp2build")...)
205 bp2buildArgs = append(bp2buildArgs, "Android.bp")
206
207 bp2buildInvocation := bootstrap.PrimaryBuilderInvocation{
208 Inputs: []string{"Android.bp"},
209 Outputs: []string{config.Bp2BuildMarkerFile()},
210 Args: bp2buildArgs,
211 }
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200212
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200213 queryviewArgs := []string{
214 "--bazel_queryview_dir", filepath.Join(config.SoongOutDir(), "queryview"),
215 "--globListDir", "queryview",
216 "--globFile", queryviewGlobFile,
217 }
218
219 queryviewArgs = append(queryviewArgs, commonArgs...)
220 queryviewArgs = append(queryviewArgs, environmentArgs(config, ".queryview")...)
221 queryviewArgs = append(queryviewArgs, "Android.bp")
222
223 queryviewInvocation := bootstrap.PrimaryBuilderInvocation{
224 Inputs: []string{"Android.bp"},
225 Outputs: []string{config.QueryviewMarkerFile()},
226 Args: queryviewArgs,
227 }
228
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200229 moduleGraphArgs := []string{
230 "--module_graph_file", config.ModuleGraphFile(),
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200231 "--globListDir", "modulegraph",
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200232 "--globFile", moduleGraphGlobFile,
233 }
234
235 moduleGraphArgs = append(moduleGraphArgs, commonArgs...)
236 moduleGraphArgs = append(moduleGraphArgs, environmentArgs(config, ".modulegraph")...)
237 moduleGraphArgs = append(moduleGraphArgs, "Android.bp")
238
239 moduleGraphInvocation := bootstrap.PrimaryBuilderInvocation{
240 Inputs: []string{"Android.bp"},
241 Outputs: []string{config.ModuleGraphFile()},
242 Args: moduleGraphArgs,
243 }
244
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200245 args.PrimaryBuilderInvocations = []bootstrap.PrimaryBuilderInvocation{
246 bp2buildInvocation,
247 mainSoongBuildInvocation,
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200248 moduleGraphInvocation,
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200249 queryviewInvocation,
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200250 }
251
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100252 blueprintCtx := blueprint.NewContext()
253 blueprintCtx.SetIgnoreUnknownModuleTypes(true)
254 blueprintConfig := BlueprintConfig{
Lukacs T. Berkiea1a31c2021-09-02 09:58:09 +0200255 soongOutDir: config.SoongOutDir(),
256 toolDir: config.HostToolDir(),
257 outDir: config.OutDir(),
258 runGoTests: !config.skipSoongTests,
259 useValidations: true,
260 debugCompilation: os.Getenv("SOONG_DELVE") != "",
261 subninjas: args.Subninjas,
262 primaryBuilderInvocations: args.PrimaryBuilderInvocations,
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100263 }
264
Lukacs T. Berkib078ade2021-08-31 10:42:08 +0200265 args.EmptyNinjaFile = false
Lukacs T. Berkiffc9e8d2021-09-07 17:54:38 +0200266 bootstrapDeps := bootstrap.RunBlueprint(args, bootstrap.DoEverything, blueprintCtx, blueprintConfig)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200267 err := deptools.WriteDepFile(bootstrapDepFile, args.OutFile, bootstrapDeps)
268 if err != nil {
269 ctx.Fatalf("Error writing depfile '%s': %s", bootstrapDepFile, err)
270 }
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100271}
272
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200273func checkEnvironmentFile(currentEnv *Environment, envFile string) {
274 getenv := func(k string) string {
275 v, _ := currentEnv.Get(k)
276 return v
277 }
278 if stale, _ := shared.StaleEnvFile(envFile, getenv); stale {
279 os.Remove(envFile)
280 }
281}
282
Dan Willemsen1e704462016-08-21 15:17:17 -0700283func runSoong(ctx Context, config Config) {
Nan Zhang17f27672018-12-12 16:01:49 -0800284 ctx.BeginTrace(metrics.RunSoong, "soong")
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700285 defer ctx.EndTrace()
286
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100287 // We have two environment files: .available is the one with every variable,
288 // .used with the ones that were actually used. The latter is used to
289 // determine whether Soong needs to be re-run since why re-run it if only
290 // unused variables were changed?
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200291 envFile := filepath.Join(config.SoongOutDir(), availableEnvFile)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100292
Lukacs T. Berki9d7cf6a2021-08-16 14:08:57 +0200293 dir := filepath.Join(config.SoongOutDir(), ".bootstrap")
294 if err := os.MkdirAll(dir, 0755); err != nil {
295 ctx.Fatalf("Cannot mkdir " + dir)
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100296 }
Colin Cross00a8a3f2020-10-29 14:08:31 -0700297
Chris Parsonsec1a3dc2021-04-20 15:32:07 -0400298 buildMode := config.bazelBuildMode()
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200299 integratedBp2Build := buildMode == mixedBuild
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200300
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100301 // This is done unconditionally, but does not take a measurable amount of time
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200302 bootstrapBlueprint(ctx, config)
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700303
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100304 soongBuildEnv := config.Environment().Copy()
305 soongBuildEnv.Set("TOP", os.Getenv("TOP"))
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100306 // For Bazel mixed builds.
307 soongBuildEnv.Set("BAZEL_PATH", "./tools/bazel")
308 soongBuildEnv.Set("BAZEL_HOME", filepath.Join(config.BazelOutDir(), "bazelhome"))
309 soongBuildEnv.Set("BAZEL_OUTPUT_BASE", filepath.Join(config.BazelOutDir(), "output"))
310 soongBuildEnv.Set("BAZEL_WORKSPACE", absPath(ctx, "."))
311 soongBuildEnv.Set("BAZEL_METRICS_DIR", config.BazelMetricsDir())
312
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100313 // For Soong bootstrapping tests
314 if os.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
315 soongBuildEnv.Set("ALLOW_MISSING_DEPENDENCIES", "true")
316 }
317
Paul Duffin5e85c662021-03-05 12:26:14 +0000318 err := writeEnvironmentFile(ctx, envFile, soongBuildEnv.AsMap())
319 if err != nil {
320 ctx.Fatalf("failed to write environment file %s: %s", envFile, err)
321 }
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100322
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700323 func() {
Nan Zhang17f27672018-12-12 16:01:49 -0800324 ctx.BeginTrace(metrics.RunSoong, "environment check")
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700325 defer ctx.EndTrace()
326
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200327 soongBuildEnvFile := filepath.Join(config.SoongOutDir(), usedEnvFile)
328 checkEnvironmentFile(soongBuildEnv, soongBuildEnvFile)
329
330 if integratedBp2Build {
331 bp2buildEnvFile := filepath.Join(config.SoongOutDir(), usedEnvFile+".bp2build")
332 checkEnvironmentFile(soongBuildEnv, bp2buildEnvFile)
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700333 }
334 }()
335
Lukacs T. Berkia806e412021-09-01 08:57:48 +0200336 runMicrofactory(ctx, config, filepath.Join(config.HostToolDir(), "bpglob"), "github.com/google/blueprint/bootstrap/bpglob",
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700337 map[string]string{"github.com/google/blueprint": "build/blueprint"})
Dan Willemsen5af1cbe2018-07-05 21:46:51 -0700338
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200339 ninja := func(name, ninjaFile string, targets ...string) {
Nan Zhang17f27672018-12-12 16:01:49 -0800340 ctx.BeginTrace(metrics.RunSoong, name)
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700341 defer ctx.EndTrace()
342
Dan Willemsenb82471a2018-05-17 16:37:09 -0700343 fifo := filepath.Join(config.OutDir(), ".ninja_fifo")
Colin Crossb98d3bc2019-03-21 16:02:58 -0700344 nr := status.NewNinjaReader(ctx, ctx.Status.StartTool(), fifo)
345 defer nr.Close()
Dan Willemsenb82471a2018-05-17 16:37:09 -0700346
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200347 ninjaArgs := []string{
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700348 "-d", "keepdepfile",
Dan Willemsen08218222020-05-18 14:02:02 -0700349 "-d", "stats",
Dan Willemsen6587bed2020-04-18 20:25:59 -0700350 "-o", "usesphonyoutputs=yes",
351 "-o", "preremoveoutputs=yes",
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700352 "-w", "dupbuild=err",
Dan Willemsen6587bed2020-04-18 20:25:59 -0700353 "-w", "outputdir=err",
354 "-w", "missingoutfile=err",
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700355 "-j", strconv.Itoa(config.Parallel()),
Dan Willemsen02736672018-07-17 17:54:31 -0700356 "--frontend_file", fifo,
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200357 "-f", filepath.Join(config.SoongOutDir(), ninjaFile),
358 }
359
360 ninjaArgs = append(ninjaArgs, targets...)
361 cmd := Command(ctx, config, "soong "+name,
362 config.PrebuiltBuildTool("ninja"), ninjaArgs...)
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500363
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100364 var ninjaEnv Environment
Lukacs T. Berki73ab9282021-03-10 10:48:39 +0100365
366 // This is currently how the command line to invoke soong_build finds the
367 // root of the source tree and the output root
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100368 ninjaEnv.Set("TOP", os.Getenv("TOP"))
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100369
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100370 cmd.Environment = &ninjaEnv
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700371 cmd.Sandbox = soongSandbox
Colin Cross7b97ecd2019-06-19 13:17:59 -0700372 cmd.RunAndStreamOrFatal()
Dan Willemsen1e704462016-08-21 15:17:17 -0700373 }
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200374
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200375 targets := make([]string, 0, 0)
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200376
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200377 if config.JsonModuleGraph() {
378 targets = append(targets, config.ModuleGraphFile())
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200379 }
380
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200381 if config.Bp2Build() {
382 targets = append(targets, config.Bp2BuildMarkerFile())
383 }
384
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200385 if config.Queryview() {
386 targets = append(targets, config.QueryviewMarkerFile())
387 }
388
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200389 if config.SoongBuildInvocationNeeded() {
390 // This build generates <builddir>/build.ninja, which is used later by build/soong/ui/build/build.go#Build().
391 targets = append(targets, config.MainNinjaFile())
392 }
393
394 ninja("bootstrap", ".bootstrap/build.ninja", targets...)
Colin Crossb72c9092020-02-10 11:23:49 -0800395
Jingwen Cheneb76c432021-01-28 08:22:12 -0500396 var soongBuildMetrics *soong_metrics_proto.SoongBuildMetrics
397 if shouldCollectBuildSoongMetrics(config) {
398 soongBuildMetrics := loadSoongBuildMetrics(ctx, config)
399 logSoongBuildMetrics(ctx, soongBuildMetrics)
400 }
Colin Crossb72c9092020-02-10 11:23:49 -0800401
Colin Cross8ba7d472020-06-25 11:27:52 -0700402 distGzipFile(ctx, config, config.SoongNinjaFile(), "soong")
403
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000404 if !config.SkipKati() {
Colin Cross8ba7d472020-06-25 11:27:52 -0700405 distGzipFile(ctx, config, config.SoongAndroidMk(), "soong")
406 distGzipFile(ctx, config, config.SoongMakeVarsMk(), "soong")
407 }
408
Jingwen Cheneb76c432021-01-28 08:22:12 -0500409 if shouldCollectBuildSoongMetrics(config) && ctx.Metrics != nil {
Colin Crossb72c9092020-02-10 11:23:49 -0800410 ctx.Metrics.SetSoongBuildMetrics(soongBuildMetrics)
411 }
412}
413
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700414func runMicrofactory(ctx Context, config Config, relExePath string, pkg string, mapping map[string]string) {
415 name := filepath.Base(relExePath)
416 ctx.BeginTrace(metrics.RunSoong, name)
417 defer ctx.EndTrace()
418 cfg := microfactory.Config{TrimPath: absPath(ctx, ".")}
419 for pkgPrefix, pathPrefix := range mapping {
420 cfg.Map(pkgPrefix, pathPrefix)
421 }
422
423 exePath := filepath.Join(config.SoongOutDir(), relExePath)
424 dir := filepath.Dir(exePath)
425 if err := os.MkdirAll(dir, 0777); err != nil {
426 ctx.Fatalf("cannot create %s: %s", dir, err)
427 }
428 if _, err := microfactory.Build(&cfg, exePath, pkg); err != nil {
429 ctx.Fatalf("failed to build %s: %s", name, err)
430 }
431}
432
Jingwen Cheneb76c432021-01-28 08:22:12 -0500433func shouldCollectBuildSoongMetrics(config Config) bool {
Jingwen Chendd9725c2021-06-24 08:41:16 +0000434 // Do not collect metrics protobuf if the soong_build binary ran as the
435 // bp2build converter or the JSON graph dump.
Lukacs T. Berkia1b93722021-09-02 17:23:06 +0200436 return config.SoongBuildInvocationNeeded()
Jingwen Cheneb76c432021-01-28 08:22:12 -0500437}
438
Colin Crossb72c9092020-02-10 11:23:49 -0800439func loadSoongBuildMetrics(ctx Context, config Config) *soong_metrics_proto.SoongBuildMetrics {
440 soongBuildMetricsFile := filepath.Join(config.OutDir(), "soong", "soong_build_metrics.pb")
441 buf, err := ioutil.ReadFile(soongBuildMetricsFile)
442 if err != nil {
443 ctx.Fatalf("Failed to load %s: %s", soongBuildMetricsFile, err)
444 }
445 soongBuildMetrics := &soong_metrics_proto.SoongBuildMetrics{}
446 err = proto.Unmarshal(buf, soongBuildMetrics)
447 if err != nil {
448 ctx.Fatalf("Failed to unmarshal %s: %s", soongBuildMetricsFile, err)
449 }
450 return soongBuildMetrics
451}
452
453func logSoongBuildMetrics(ctx Context, metrics *soong_metrics_proto.SoongBuildMetrics) {
454 ctx.Verbosef("soong_build metrics:")
455 ctx.Verbosef(" modules: %v", metrics.GetModules())
456 ctx.Verbosef(" variants: %v", metrics.GetVariants())
457 ctx.Verbosef(" max heap size: %v MB", metrics.GetMaxHeapSize()/1e6)
458 ctx.Verbosef(" total allocation count: %v", metrics.GetTotalAllocCount())
459 ctx.Verbosef(" total allocation size: %v MB", metrics.GetTotalAllocSize()/1e6)
460
Dan Willemsen1e704462016-08-21 15:17:17 -0700461}