blob: 726b5418b4aeff4ee9ebc21e2836e7a2c49c9ca5 [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. Berki9f6c24a2021-08-26 15:07:24 +020074 soongOutDir string
75 outDir string
Lukacs T. Berki5f6cb1d2021-03-17 15:03:14 +010076 debugCompilation bool
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010077}
78
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +020079func (c BlueprintConfig) SoongOutDir() string {
80 return c.soongOutDir
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010081}
82
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +020083func (c BlueprintConfig) OutDir() string {
84 return c.outDir
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +010085}
86
Lukacs T. Berki5f6cb1d2021-03-17 15:03:14 +010087func (c BlueprintConfig) DebugCompilation() bool {
88 return c.debugCompilation
89}
90
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020091func environmentArgs(config Config, suffix string) []string {
92 return []string{
93 "--available_env", shared.JoinPath(config.SoongOutDir(), availableEnvFile),
94 "--used_env", shared.JoinPath(config.SoongOutDir(), usedEnvFile+suffix),
95 }
96}
Spandan Das8f99ae62021-06-11 16:48:06 +000097
98func writeEmptyGlobFile(ctx Context, path string) {
99 err := os.MkdirAll(filepath.Dir(path), 0777)
100 if err != nil {
101 ctx.Fatalf("Failed to create parent directories of empty ninja glob file '%s': %s", path, err)
102 }
103
104 if _, err := os.Stat(path); os.IsNotExist(err) {
105 err = ioutil.WriteFile(path, nil, 0666)
106 if err != nil {
107 ctx.Fatalf("Failed to create empty ninja glob file '%s': %s", path, err)
108 }
109 }
110}
111
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200112func bootstrapBlueprint(ctx Context, config Config) {
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100113 ctx.BeginTrace(metrics.RunSoong, "blueprint bootstrap")
114 defer ctx.EndTrace()
115
116 var args bootstrap.Args
117
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200118 bootstrapGlobFile := shared.JoinPath(config.SoongOutDir(), ".bootstrap/build-globs.ninja")
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200119 bp2buildGlobFile := shared.JoinPath(config.SoongOutDir(), ".bootstrap/build-globs.bp2build.ninja")
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200120 moduleGraphGlobFile := shared.JoinPath(config.SoongOutDir(), ".bootstrap/build-globs.modulegraph.ninja")
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200121
122 // The glob .ninja files are subninja'd. However, they are generated during
123 // the build itself so we write an empty file so that the subninja doesn't
124 // fail on clean builds
Spandan Das8f99ae62021-06-11 16:48:06 +0000125 writeEmptyGlobFile(ctx, bootstrapGlobFile)
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200126 writeEmptyGlobFile(ctx, bp2buildGlobFile)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200127 bootstrapDepFile := shared.JoinPath(config.SoongOutDir(), ".bootstrap/build.ninja.d")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200128
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100129 args.RunGoTests = !config.skipSoongTests
130 args.UseValidations = true // Use validations to depend on tests
Lukacs T. Berkib078ade2021-08-31 10:42:08 +0200131 args.SoongOutDir = config.SoongOutDir()
132 args.OutDir = config.OutDir()
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100133 args.ModuleListFile = filepath.Join(config.FileListDir(), "Android.bp.list")
134 args.OutFile = shared.JoinPath(config.SoongOutDir(), ".bootstrap/build.ninja")
Spandan Das8f99ae62021-06-11 16:48:06 +0000135 // The primary builder (aka soong_build) will use bootstrapGlobFile as the globFile to generate build.ninja(.d)
136 // Building soong_build does not require a glob file
137 // 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. Berki56ebaf32021-08-12 14:03:55 +0200138 args.Subninjas = []string{bootstrapGlobFile, bp2buildGlobFile}
Colin Crossf3bdbcb2021-06-01 11:43:55 -0700139 args.EmptyNinjaFile = config.EmptyNinjaFile()
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100140
Lukacs T. Berki745380c2021-04-12 12:07:44 +0200141 args.DelveListen = os.Getenv("SOONG_DELVE")
142 if args.DelveListen != "" {
143 args.DelvePath = shared.ResolveDelveBinary()
144 }
145
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200146 commonArgs := bootstrap.PrimaryBuilderExtraFlags(args, config.MainNinjaFile())
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200147 mainSoongBuildInputs := []string{"Android.bp"}
148
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200149 if config.bazelBuildMode() == mixedBuild {
150 mainSoongBuildInputs = append(mainSoongBuildInputs, config.Bp2BuildMarkerFile())
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200151 }
152
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200153 soongBuildArgs := []string{
154 "--globListDir", "globs",
155 "--globFile", bootstrapGlobFile,
156 }
157
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200158 soongBuildArgs = append(soongBuildArgs, commonArgs...)
159 soongBuildArgs = append(soongBuildArgs, environmentArgs(config, "")...)
160 soongBuildArgs = append(soongBuildArgs, "Android.bp")
161
162 mainSoongBuildInvocation := bootstrap.PrimaryBuilderInvocation{
163 Inputs: mainSoongBuildInputs,
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200164 Outputs: []string{config.MainNinjaFile()},
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200165 Args: soongBuildArgs,
166 }
167
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200168 bp2buildArgs := []string{
169 "--bp2build_marker", config.Bp2BuildMarkerFile(),
170 "--globListDir", "globs.bp2build",
171 "--globFile", bp2buildGlobFile,
172 }
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200173
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200174 bp2buildArgs = append(bp2buildArgs, commonArgs...)
175 bp2buildArgs = append(bp2buildArgs, environmentArgs(config, ".bp2build")...)
176 bp2buildArgs = append(bp2buildArgs, "Android.bp")
177
178 bp2buildInvocation := bootstrap.PrimaryBuilderInvocation{
179 Inputs: []string{"Android.bp"},
180 Outputs: []string{config.Bp2BuildMarkerFile()},
181 Args: bp2buildArgs,
182 }
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200183
184 moduleGraphArgs := []string{
185 "--module_graph_file", config.ModuleGraphFile(),
186 "--globListDir", "globs.modulegraph",
187 "--globFile", moduleGraphGlobFile,
188 }
189
190 moduleGraphArgs = append(moduleGraphArgs, commonArgs...)
191 moduleGraphArgs = append(moduleGraphArgs, environmentArgs(config, ".modulegraph")...)
192 moduleGraphArgs = append(moduleGraphArgs, "Android.bp")
193
194 moduleGraphInvocation := bootstrap.PrimaryBuilderInvocation{
195 Inputs: []string{"Android.bp"},
196 Outputs: []string{config.ModuleGraphFile()},
197 Args: moduleGraphArgs,
198 }
199
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200200 args.PrimaryBuilderInvocations = []bootstrap.PrimaryBuilderInvocation{
201 bp2buildInvocation,
202 mainSoongBuildInvocation,
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200203 moduleGraphInvocation,
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200204 }
205
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100206 blueprintCtx := blueprint.NewContext()
207 blueprintCtx.SetIgnoreUnknownModuleTypes(true)
208 blueprintConfig := BlueprintConfig{
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200209 soongOutDir: config.SoongOutDir(),
210 outDir: config.OutDir(),
Lukacs T. Berki5f6cb1d2021-03-17 15:03:14 +0100211 debugCompilation: os.Getenv("SOONG_DELVE") != "",
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100212 }
213
Lukacs T. Berkib078ade2021-08-31 10:42:08 +0200214 args.EmptyNinjaFile = false
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200215 bootstrapDeps := bootstrap.RunBlueprint(args, blueprintCtx, blueprintConfig)
216 err := deptools.WriteDepFile(bootstrapDepFile, args.OutFile, bootstrapDeps)
217 if err != nil {
218 ctx.Fatalf("Error writing depfile '%s': %s", bootstrapDepFile, err)
219 }
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100220}
221
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200222func checkEnvironmentFile(currentEnv *Environment, envFile string) {
223 getenv := func(k string) string {
224 v, _ := currentEnv.Get(k)
225 return v
226 }
227 if stale, _ := shared.StaleEnvFile(envFile, getenv); stale {
228 os.Remove(envFile)
229 }
230}
231
Dan Willemsen1e704462016-08-21 15:17:17 -0700232func runSoong(ctx Context, config Config) {
Nan Zhang17f27672018-12-12 16:01:49 -0800233 ctx.BeginTrace(metrics.RunSoong, "soong")
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700234 defer ctx.EndTrace()
235
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100236 // We have two environment files: .available is the one with every variable,
237 // .used with the ones that were actually used. The latter is used to
238 // determine whether Soong needs to be re-run since why re-run it if only
239 // unused variables were changed?
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200240 envFile := filepath.Join(config.SoongOutDir(), availableEnvFile)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100241
Lukacs T. Berki9d7cf6a2021-08-16 14:08:57 +0200242 dir := filepath.Join(config.SoongOutDir(), ".bootstrap")
243 if err := os.MkdirAll(dir, 0755); err != nil {
244 ctx.Fatalf("Cannot mkdir " + dir)
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100245 }
Colin Cross00a8a3f2020-10-29 14:08:31 -0700246
Chris Parsonsec1a3dc2021-04-20 15:32:07 -0400247 buildMode := config.bazelBuildMode()
248 integratedBp2Build := (buildMode == mixedBuild) || (buildMode == generateBuildFiles)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200249
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100250 // This is done unconditionally, but does not take a measurable amount of time
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200251 bootstrapBlueprint(ctx, config)
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700252
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100253 soongBuildEnv := config.Environment().Copy()
254 soongBuildEnv.Set("TOP", os.Getenv("TOP"))
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100255 // For Bazel mixed builds.
256 soongBuildEnv.Set("BAZEL_PATH", "./tools/bazel")
257 soongBuildEnv.Set("BAZEL_HOME", filepath.Join(config.BazelOutDir(), "bazelhome"))
258 soongBuildEnv.Set("BAZEL_OUTPUT_BASE", filepath.Join(config.BazelOutDir(), "output"))
259 soongBuildEnv.Set("BAZEL_WORKSPACE", absPath(ctx, "."))
260 soongBuildEnv.Set("BAZEL_METRICS_DIR", config.BazelMetricsDir())
261
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100262 // For Soong bootstrapping tests
263 if os.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
264 soongBuildEnv.Set("ALLOW_MISSING_DEPENDENCIES", "true")
265 }
266
Paul Duffin5e85c662021-03-05 12:26:14 +0000267 err := writeEnvironmentFile(ctx, envFile, soongBuildEnv.AsMap())
268 if err != nil {
269 ctx.Fatalf("failed to write environment file %s: %s", envFile, err)
270 }
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100271
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700272 func() {
Nan Zhang17f27672018-12-12 16:01:49 -0800273 ctx.BeginTrace(metrics.RunSoong, "environment check")
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700274 defer ctx.EndTrace()
275
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200276 soongBuildEnvFile := filepath.Join(config.SoongOutDir(), usedEnvFile)
277 checkEnvironmentFile(soongBuildEnv, soongBuildEnvFile)
278
279 if integratedBp2Build {
280 bp2buildEnvFile := filepath.Join(config.SoongOutDir(), usedEnvFile+".bp2build")
281 checkEnvironmentFile(soongBuildEnv, bp2buildEnvFile)
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700282 }
283 }()
284
Lukacs T. Berki9d7cf6a2021-08-16 14:08:57 +0200285 runMicrofactory(ctx, config, ".bootstrap/bpglob", "github.com/google/blueprint/bootstrap/bpglob",
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700286 map[string]string{"github.com/google/blueprint": "build/blueprint"})
Dan Willemsen5af1cbe2018-07-05 21:46:51 -0700287
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200288 ninja := func(name, ninjaFile string, targets ...string) {
Nan Zhang17f27672018-12-12 16:01:49 -0800289 ctx.BeginTrace(metrics.RunSoong, name)
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700290 defer ctx.EndTrace()
291
Dan Willemsenb82471a2018-05-17 16:37:09 -0700292 fifo := filepath.Join(config.OutDir(), ".ninja_fifo")
Colin Crossb98d3bc2019-03-21 16:02:58 -0700293 nr := status.NewNinjaReader(ctx, ctx.Status.StartTool(), fifo)
294 defer nr.Close()
Dan Willemsenb82471a2018-05-17 16:37:09 -0700295
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200296 ninjaArgs := []string{
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700297 "-d", "keepdepfile",
Dan Willemsen08218222020-05-18 14:02:02 -0700298 "-d", "stats",
Dan Willemsen6587bed2020-04-18 20:25:59 -0700299 "-o", "usesphonyoutputs=yes",
300 "-o", "preremoveoutputs=yes",
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700301 "-w", "dupbuild=err",
Dan Willemsen6587bed2020-04-18 20:25:59 -0700302 "-w", "outputdir=err",
303 "-w", "missingoutfile=err",
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700304 "-j", strconv.Itoa(config.Parallel()),
Dan Willemsen02736672018-07-17 17:54:31 -0700305 "--frontend_file", fifo,
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200306 "-f", filepath.Join(config.SoongOutDir(), ninjaFile),
307 }
308
309 ninjaArgs = append(ninjaArgs, targets...)
310 cmd := Command(ctx, config, "soong "+name,
311 config.PrebuiltBuildTool("ninja"), ninjaArgs...)
Jingwen Chen7c6089a2020-11-02 02:56:20 -0500312
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100313 var ninjaEnv Environment
Lukacs T. Berki73ab9282021-03-10 10:48:39 +0100314
315 // This is currently how the command line to invoke soong_build finds the
316 // root of the source tree and the output root
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100317 ninjaEnv.Set("TOP", os.Getenv("TOP"))
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100318
Lukacs T. Berkib14ad7b2021-03-09 10:43:57 +0100319 cmd.Environment = &ninjaEnv
Dan Willemsen99a75cd2017-08-04 16:04:04 -0700320 cmd.Sandbox = soongSandbox
Colin Cross7b97ecd2019-06-19 13:17:59 -0700321 cmd.RunAndStreamOrFatal()
Dan Willemsen1e704462016-08-21 15:17:17 -0700322 }
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200323
324 var target string
325
326 if config.bazelBuildMode() == generateBuildFiles {
327 target = config.Bp2BuildMarkerFile()
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200328 } else if config.bazelBuildMode() == generateJsonModuleGraph {
329 target = config.ModuleGraphFile()
Lukacs T. Berki56ebaf32021-08-12 14:03:55 +0200330 } else {
331 // This build generates <builddir>/build.ninja, which is used later by build/soong/ui/build/build.go#Build().
332 target = config.MainNinjaFile()
333 }
334
335 ninja("bootstrap", ".bootstrap/build.ninja", target)
Colin Crossb72c9092020-02-10 11:23:49 -0800336
Jingwen Cheneb76c432021-01-28 08:22:12 -0500337 var soongBuildMetrics *soong_metrics_proto.SoongBuildMetrics
338 if shouldCollectBuildSoongMetrics(config) {
339 soongBuildMetrics := loadSoongBuildMetrics(ctx, config)
340 logSoongBuildMetrics(ctx, soongBuildMetrics)
341 }
Colin Crossb72c9092020-02-10 11:23:49 -0800342
Colin Cross8ba7d472020-06-25 11:27:52 -0700343 distGzipFile(ctx, config, config.SoongNinjaFile(), "soong")
344
Anton Hansson5e5c48b2020-11-27 12:35:20 +0000345 if !config.SkipKati() {
Colin Cross8ba7d472020-06-25 11:27:52 -0700346 distGzipFile(ctx, config, config.SoongAndroidMk(), "soong")
347 distGzipFile(ctx, config, config.SoongMakeVarsMk(), "soong")
348 }
349
Jingwen Cheneb76c432021-01-28 08:22:12 -0500350 if shouldCollectBuildSoongMetrics(config) && ctx.Metrics != nil {
Colin Crossb72c9092020-02-10 11:23:49 -0800351 ctx.Metrics.SetSoongBuildMetrics(soongBuildMetrics)
352 }
353}
354
Sasha Smundak7ae80a72021-04-09 12:03:51 -0700355func runMicrofactory(ctx Context, config Config, relExePath string, pkg string, mapping map[string]string) {
356 name := filepath.Base(relExePath)
357 ctx.BeginTrace(metrics.RunSoong, name)
358 defer ctx.EndTrace()
359 cfg := microfactory.Config{TrimPath: absPath(ctx, ".")}
360 for pkgPrefix, pathPrefix := range mapping {
361 cfg.Map(pkgPrefix, pathPrefix)
362 }
363
364 exePath := filepath.Join(config.SoongOutDir(), relExePath)
365 dir := filepath.Dir(exePath)
366 if err := os.MkdirAll(dir, 0777); err != nil {
367 ctx.Fatalf("cannot create %s: %s", dir, err)
368 }
369 if _, err := microfactory.Build(&cfg, exePath, pkg); err != nil {
370 ctx.Fatalf("failed to build %s: %s", name, err)
371 }
372}
373
Jingwen Cheneb76c432021-01-28 08:22:12 -0500374func shouldCollectBuildSoongMetrics(config Config) bool {
Jingwen Chendd9725c2021-06-24 08:41:16 +0000375 // Do not collect metrics protobuf if the soong_build binary ran as the
376 // bp2build converter or the JSON graph dump.
377 return config.bazelBuildMode() != generateBuildFiles && config.bazelBuildMode() != generateJsonModuleGraph
Jingwen Cheneb76c432021-01-28 08:22:12 -0500378}
379
Colin Crossb72c9092020-02-10 11:23:49 -0800380func loadSoongBuildMetrics(ctx Context, config Config) *soong_metrics_proto.SoongBuildMetrics {
381 soongBuildMetricsFile := filepath.Join(config.OutDir(), "soong", "soong_build_metrics.pb")
382 buf, err := ioutil.ReadFile(soongBuildMetricsFile)
383 if err != nil {
384 ctx.Fatalf("Failed to load %s: %s", soongBuildMetricsFile, err)
385 }
386 soongBuildMetrics := &soong_metrics_proto.SoongBuildMetrics{}
387 err = proto.Unmarshal(buf, soongBuildMetrics)
388 if err != nil {
389 ctx.Fatalf("Failed to unmarshal %s: %s", soongBuildMetricsFile, err)
390 }
391 return soongBuildMetrics
392}
393
394func logSoongBuildMetrics(ctx Context, metrics *soong_metrics_proto.SoongBuildMetrics) {
395 ctx.Verbosef("soong_build metrics:")
396 ctx.Verbosef(" modules: %v", metrics.GetModules())
397 ctx.Verbosef(" variants: %v", metrics.GetVariants())
398 ctx.Verbosef(" max heap size: %v MB", metrics.GetMaxHeapSize()/1e6)
399 ctx.Verbosef(" total allocation count: %v", metrics.GetTotalAllocCount())
400 ctx.Verbosef(" total allocation size: %v MB", metrics.GetTotalAllocSize()/1e6)
401
Dan Willemsen1e704462016-08-21 15:17:17 -0700402}