blob: 7742492bfdb98642645dc076ba23bf8a0dbffe80 [file] [log] [blame]
Colin Cross3f40fa42015-01-30 17:27:36 -08001// Copyright 2015 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 main
16
17import (
Usta Shrestha2ba28a32022-10-24 11:33:09 -040018 "bytes"
Jeongik Chaa87506f2023-06-01 23:16:41 +090019 "errors"
Colin Cross3f40fa42015-01-30 17:27:36 -080020 "flag"
21 "fmt"
22 "os"
23 "path/filepath"
Jingwen Cheneb76c432021-01-28 08:22:12 -050024 "strings"
Lukacs T. Berkic99c9472021-03-24 10:50:06 +010025 "time"
Colin Cross3f40fa42015-01-30 17:27:36 -080026
Dan Willemsen66213a62021-09-21 17:50:30 -070027 "android/soong/android"
Jeongik Chae114e602023-03-19 00:12:39 +090028 "android/soong/android/allowlists"
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020029 "android/soong/bp2build"
Lukacs T. Berki7690c092021-02-26 14:27:36 +010030 "android/soong/shared"
Jeongik Chab745e2e2023-04-11 14:28:43 +090031 "github.com/google/blueprint"
Colin Cross70b40592015-03-23 12:57:34 -070032 "github.com/google/blueprint/bootstrap"
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +020033 "github.com/google/blueprint/deptools"
Chris Parsons715b08f2022-03-22 19:23:40 -040034 "github.com/google/blueprint/metrics"
Dan Willemsen66213a62021-09-21 17:50:30 -070035 androidProtobuf "google.golang.org/protobuf/android"
Colin Cross3f40fa42015-01-30 17:27:36 -080036)
37
Colin Crosse87040b2017-12-11 15:52:26 -080038var (
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020039 topDir string
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020040 availableEnvFile string
41 usedEnvFile string
42
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +020043 globFile string
44 globListDir string
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020045 delveListen string
46 delvePath string
47
Sasha Smundakaf5ca922022-12-12 21:23:34 -080048 cmdlineArgs android.CmdArgs
Colin Crosse87040b2017-12-11 15:52:26 -080049)
50
51func init() {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020052 // Flags that make sense in every mode
Lukacs T. Berki7690c092021-02-26 14:27:36 +010053 flag.StringVar(&topDir, "top", "", "Top directory of the Android source tree")
Sasha Smundakaf5ca922022-12-12 21:23:34 -080054 flag.StringVar(&cmdlineArgs.SoongOutDir, "soong_out", "", "Soong output directory (usually $TOP/out/soong)")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020055 flag.StringVar(&availableEnvFile, "available_env", "", "File containing available environment variables")
56 flag.StringVar(&usedEnvFile, "used_env", "", "File containing used environment variables")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020057 flag.StringVar(&globFile, "globFile", "build-globs.ninja", "the Ninja file of globs to output")
58 flag.StringVar(&globListDir, "globListDir", "", "the directory containing the glob list files")
Sasha Smundakaf5ca922022-12-12 21:23:34 -080059 flag.StringVar(&cmdlineArgs.OutDir, "out", "", "the ninja builddir directory")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020060 flag.StringVar(&cmdlineArgs.ModuleListFile, "l", "", "file that lists filepaths to parse")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020061
62 // Debug flags
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +010063 flag.StringVar(&delveListen, "delve_listen", "", "Delve port to listen on for debugging")
64 flag.StringVar(&delvePath, "delve_path", "", "Path to Delve. Only used if --delve_listen is set")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020065 flag.StringVar(&cmdlineArgs.Cpuprofile, "cpuprofile", "", "write cpu profile to file")
66 flag.StringVar(&cmdlineArgs.TraceFile, "trace", "", "write trace to file")
67 flag.StringVar(&cmdlineArgs.Memprofile, "memprofile", "", "write memory profile to file")
68 flag.BoolVar(&cmdlineArgs.NoGC, "nogc", false, "turn off GC for debugging")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020069
70 // Flags representing various modes soong_build can run in
Sasha Smundakaf5ca922022-12-12 21:23:34 -080071 flag.StringVar(&cmdlineArgs.ModuleGraphFile, "module_graph_file", "", "JSON module graph file to output")
72 flag.StringVar(&cmdlineArgs.ModuleActionsFile, "module_actions_file", "", "JSON file to output inputs/outputs of actions of modules")
73 flag.StringVar(&cmdlineArgs.DocFile, "soong_docs", "", "build documentation file to output")
74 flag.StringVar(&cmdlineArgs.BazelQueryViewDir, "bazel_queryview_dir", "", "path to the bazel queryview directory relative to --top")
Lukacs T. Berkif9008072021-08-16 15:24:48 +020075 flag.StringVar(&cmdlineArgs.OutFile, "o", "build.ninja", "the Ninja file to output")
Kiyoung Kima37d9ba2023-04-19 13:13:45 +090076 flag.StringVar(&cmdlineArgs.SoongVariables, "soong_variables", "soong.variables", "the file contains all build variables")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020077 flag.BoolVar(&cmdlineArgs.EmptyNinjaFile, "empty-ninja-file", false, "write out a 0-byte ninja file")
LaMont Jones52a72432023-03-09 18:19:35 +000078 flag.BoolVar(&cmdlineArgs.MultitreeBuild, "multitree-build", false, "this is a multitree build")
Jihoon Kang2a929ad2023-06-08 19:02:07 +000079 flag.BoolVar(&cmdlineArgs.BuildFromSourceStub, "build-from-source-stub", false, "build Java stubs from source files instead of API text files")
MarkDacekf47e1422023-04-19 16:47:36 +000080 flag.BoolVar(&cmdlineArgs.EnsureAllowlistIntegrity, "ensure-allowlist-integrity", false, "verify that allowlisted modules are mixed-built")
Sasha Smundakaf5ca922022-12-12 21:23:34 -080081 // Flags that probably shouldn't be flags of soong_build, but we haven't found
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020082 // the time to remove them yet
Sasha Smundakaf5ca922022-12-12 21:23:34 -080083 flag.BoolVar(&cmdlineArgs.RunGoTests, "t", false, "build and run go tests during bootstrap")
Dan Willemsen66213a62021-09-21 17:50:30 -070084
85 // Disable deterministic randomization in the protobuf package, so incremental
86 // builds with unrelated Soong changes don't trigger large rebuilds (since we
87 // write out text protos in command lines, and command line changes trigger
88 // rebuilds).
89 androidProtobuf.DisableRand()
Colin Crosse87040b2017-12-11 15:52:26 -080090}
91
Jeff Gaston088e29e2017-11-29 16:47:17 -080092func newNameResolver(config android.Config) *android.NameResolver {
Paul Duffin3f7bf9f2022-11-08 12:21:15 +000093 return android.NewNameResolver(config)
Jeff Gaston088e29e2017-11-29 16:47:17 -080094}
95
Lukacs T. Berkiffc9e8d2021-09-07 17:54:38 +020096func newContext(configuration android.Config) *android.Context {
Colin Crossae8600b2020-10-29 17:09:13 -070097 ctx := android.NewContext(configuration)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040098 ctx.SetNameInterface(newNameResolver(configuration))
99 ctx.SetAllowMissingDependencies(configuration.AllowMissingDependencies())
Spandan Dasc5763832022-11-08 18:42:16 +0000100 ctx.AddIncludeTags(configuration.IncludeTags()...)
Sam Delmerico98a73292023-02-21 11:50:29 -0500101 ctx.AddSourceRootDirs(configuration.SourceRootDirs()...)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400102 return ctx
103}
104
Jeongik Chaa87506f2023-06-01 23:16:41 +0900105func needToWriteNinjaHint(ctx *android.Context) bool {
106 switch ctx.Config().GetenvWithDefault("SOONG_GENERATES_NINJA_HINT", "") {
107 case "always":
108 return true
109 case "depend":
110 if _, err := os.Stat(filepath.Join(ctx.Config().OutDir(), ".ninja_log")); errors.Is(err, os.ErrNotExist) {
111 return true
112 }
113 }
114 return false
115}
116
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200117// Run the code-generation phase to convert BazelTargetModules to BUILD files.
Sasha Smundak1845f422022-12-13 14:18:58 -0800118func runQueryView(queryviewDir, queryviewMarker string, ctx *android.Context) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400119 ctx.EventHandler.Begin("queryview")
120 defer ctx.EventHandler.End("queryview")
Cole Faustb85d1a12022-11-08 18:14:01 -0800121 codegenContext := bp2build.NewCodegenContext(ctx.Config(), ctx, bp2build.QueryView, topDir)
Spandan Das98cb8562023-03-09 23:05:47 +0000122 err := createBazelWorkspace(codegenContext, shared.JoinPath(topDir, queryviewDir), false)
Sasha Smundak1845f422022-12-13 14:18:58 -0800123 maybeQuit(err, "")
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200124 touch(shared.JoinPath(topDir, queryviewMarker))
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200125}
126
Jeongik Chae114e602023-03-19 00:12:39 +0900127func writeNinjaHint(ctx *android.Context) error {
Jeongik Cha73d49112023-05-04 18:16:11 +0900128 ctx.BeginEvent("ninja_hint")
129 defer ctx.EndEvent("ninja_hint")
Jeongik Chab745e2e2023-04-11 14:28:43 +0900130 // The current predictor focuses on reducing false negatives.
131 // If there are too many false positives (e.g., most modules are marked as positive),
132 // real long-running jobs cannot run early.
133 // Therefore, the model should be adjusted in this case.
134 // The model should also be adjusted if there are critical false negatives.
135 predicate := func(j *blueprint.JsonModule) (prioritized bool, weight int) {
136 prioritized = false
137 weight = 0
138 for prefix, w := range allowlists.HugeModuleTypePrefixMap {
139 if strings.HasPrefix(j.Type, prefix) {
140 prioritized = true
141 weight = w
142 return
143 }
Jeongik Chae114e602023-03-19 00:12:39 +0900144 }
Jeongik Chab745e2e2023-04-11 14:28:43 +0900145 dep_count := len(j.Deps)
146 src_count := 0
147 for _, a := range j.Module["Actions"].([]blueprint.JSONAction) {
148 src_count += len(a.Inputs)
149 }
150 input_size := dep_count + src_count
151
152 // Current threshold is an arbitrary value which only consider recall rather than accuracy.
153 if input_size > allowlists.INPUT_SIZE_THRESHOLD {
154 prioritized = true
155 weight += ((input_size) / allowlists.INPUT_SIZE_THRESHOLD) * allowlists.DEFAULT_PRIORITIZED_WEIGHT
156
157 // To prevent some modules from having too large a priority value.
158 if weight > allowlists.HIGH_PRIORITIZED_WEIGHT {
159 weight = allowlists.HIGH_PRIORITIZED_WEIGHT
160 }
161 }
162 return
163 }
164
165 outputsMap := ctx.Context.GetWeightedOutputsFromPredicate(predicate)
166 var outputBuilder strings.Builder
167 for output, weight := range outputsMap {
168 outputBuilder.WriteString(fmt.Sprintf("%s,%d\n", output, weight))
Jeongik Chae114e602023-03-19 00:12:39 +0900169 }
170 weightListFile := filepath.Join(topDir, ctx.Config().OutDir(), ".ninja_weight_list")
171
172 err := os.WriteFile(weightListFile, []byte(outputBuilder.String()), 0644)
173 if err != nil {
174 return fmt.Errorf("could not write ninja weight list file %s", err)
175 }
176 return nil
177}
178
Paul Duffin780a1852022-11-05 10:17:12 +0000179func writeMetrics(configuration android.Config, eventHandler *metrics.EventHandler, metricsDir string) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400180 if len(metricsDir) < 1 {
181 fmt.Fprintf(os.Stderr, "\nMissing required env var for generating soong metrics: LOG_DIR\n")
182 os.Exit(1)
183 }
184 metricsFile := filepath.Join(metricsDir, "soong_build_metrics.pb")
185 err := android.WriteMetrics(configuration, eventHandler, metricsFile)
Sasha Smundak1845f422022-12-13 14:18:58 -0800186 maybeQuit(err, "error writing soong_build metrics %s", metricsFile)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200187}
188
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800189func writeJsonModuleGraphAndActions(ctx *android.Context, cmdArgs android.CmdArgs) {
190 graphFile, graphErr := os.Create(shared.JoinPath(topDir, cmdArgs.ModuleGraphFile))
Sasha Smundak1845f422022-12-13 14:18:58 -0800191 maybeQuit(graphErr, "graph err")
kgui67007242022-01-25 13:50:25 +0800192 defer graphFile.Close()
Sasha Smundak1845f422022-12-13 14:18:58 -0800193 actionsFile, actionsErr := os.Create(shared.JoinPath(topDir, cmdArgs.ModuleActionsFile))
194 maybeQuit(actionsErr, "actions err")
kgui67007242022-01-25 13:50:25 +0800195 defer actionsFile.Close()
196 ctx.Context.PrintJSONGraphAndActions(graphFile, actionsFile)
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200197}
198
Sasha Smundak1845f422022-12-13 14:18:58 -0800199func writeBuildGlobsNinjaFile(ctx *android.Context) []string {
Chris Parsons715b08f2022-03-22 19:23:40 -0400200 ctx.EventHandler.Begin("globs_ninja_file")
201 defer ctx.EventHandler.End("globs_ninja_file")
202
Sasha Smundak1845f422022-12-13 14:18:58 -0800203 globDir := bootstrap.GlobDirectory(ctx.Config().SoongOutDir(), globListDir)
Lukacs T. Berkic357c812023-06-20 09:30:06 +0000204 err := bootstrap.WriteBuildGlobsNinjaFile(&bootstrap.GlobSingleton{
Chris Parsons715b08f2022-03-22 19:23:40 -0400205 GlobLister: ctx.Globs,
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200206 GlobFile: globFile,
207 GlobDir: globDir,
Chris Parsons715b08f2022-03-22 19:23:40 -0400208 SrcDir: ctx.SrcDir(),
Sasha Smundak1845f422022-12-13 14:18:58 -0800209 }, ctx.Config())
Lukacs T. Berkic357c812023-06-20 09:30:06 +0000210 maybeQuit(err, "")
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200211 return bootstrap.GlobFileListFiles(globDir)
212}
213
Paul Duffin780a1852022-11-05 10:17:12 +0000214func writeDepFile(outputFile string, eventHandler *metrics.EventHandler, ninjaDeps []string) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400215 eventHandler.Begin("ninja_deps")
216 defer eventHandler.End("ninja_deps")
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200217 depFile := shared.JoinPath(topDir, outputFile+".d")
218 err := deptools.WriteDepFile(depFile, outputFile, ninjaDeps)
Sasha Smundak1845f422022-12-13 14:18:58 -0800219 maybeQuit(err, "error writing depfile '%s'", depFile)
Paul Duffin0c09a432022-11-05 15:28:04 +0000220}
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200221
Paul Duffin0c09a432022-11-05 15:28:04 +0000222// runSoongOnlyBuild runs the standard Soong build in a number of different modes.
Sasha Smundak1845f422022-12-13 14:18:58 -0800223func runSoongOnlyBuild(ctx *android.Context, extraNinjaDeps []string) string {
Paul Duffin39eae8f2022-11-05 14:59:52 +0000224 ctx.EventHandler.Begin("soong_build")
225 defer ctx.EventHandler.End("soong_build")
226
Paul Duffin0c09a432022-11-05 15:28:04 +0000227 var stopBefore bootstrap.StopBefore
Sasha Smundak1845f422022-12-13 14:18:58 -0800228 switch ctx.Config().BuildMode {
229 case android.GenerateModuleGraph:
Paul Duffin0c09a432022-11-05 15:28:04 +0000230 stopBefore = bootstrap.StopBeforeWriteNinja
Usta Shrestha7fae6952022-12-21 11:46:28 -0500231 case android.GenerateQueryView, android.GenerateDocFile:
Paul Duffin0c09a432022-11-05 15:28:04 +0000232 stopBefore = bootstrap.StopBeforePrepareBuildActions
Sasha Smundak1845f422022-12-13 14:18:58 -0800233 default:
Paul Duffin0c09a432022-11-05 15:28:04 +0000234 stopBefore = bootstrap.DoEverything
235 }
236
Lukacs T. Berkic357c812023-06-20 09:30:06 +0000237 ninjaDeps, err := bootstrap.RunBlueprint(cmdlineArgs.Args, stopBefore, ctx.Context, ctx.Config())
238 maybeQuit(err, "")
Paul Duffin0c09a432022-11-05 15:28:04 +0000239 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
240
Sasha Smundak1845f422022-12-13 14:18:58 -0800241 globListFiles := writeBuildGlobsNinjaFile(ctx)
Paul Duffin0c09a432022-11-05 15:28:04 +0000242 ninjaDeps = append(ninjaDeps, globListFiles...)
243
244 // Convert the Soong module graph into Bazel BUILD files.
Sasha Smundak1845f422022-12-13 14:18:58 -0800245 switch ctx.Config().BuildMode {
246 case android.GenerateQueryView:
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800247 queryviewMarkerFile := cmdlineArgs.BazelQueryViewDir + ".marker"
Sasha Smundak1845f422022-12-13 14:18:58 -0800248 runQueryView(cmdlineArgs.BazelQueryViewDir, queryviewMarkerFile, ctx)
Paul Duffin0c09a432022-11-05 15:28:04 +0000249 writeDepFile(queryviewMarkerFile, ctx.EventHandler, ninjaDeps)
250 return queryviewMarkerFile
Sasha Smundak1845f422022-12-13 14:18:58 -0800251 case android.GenerateModuleGraph:
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800252 writeJsonModuleGraphAndActions(ctx, cmdlineArgs)
253 writeDepFile(cmdlineArgs.ModuleGraphFile, ctx.EventHandler, ninjaDeps)
254 return cmdlineArgs.ModuleGraphFile
Sasha Smundak1845f422022-12-13 14:18:58 -0800255 case android.GenerateDocFile:
Paul Duffin0c09a432022-11-05 15:28:04 +0000256 // TODO: we could make writeDocs() return the list of documentation files
257 // written and add them to the .d file. Then soong_docs would be re-run
258 // whenever one is deleted.
Sasha Smundak1845f422022-12-13 14:18:58 -0800259 err := writeDocs(ctx, shared.JoinPath(topDir, cmdlineArgs.DocFile))
260 maybeQuit(err, "error building Soong documentation")
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800261 writeDepFile(cmdlineArgs.DocFile, ctx.EventHandler, ninjaDeps)
262 return cmdlineArgs.DocFile
Sasha Smundak1845f422022-12-13 14:18:58 -0800263 default:
Paul Duffin0c09a432022-11-05 15:28:04 +0000264 // The actual output (build.ninja) was written in the RunBlueprint() call
265 // above
266 writeDepFile(cmdlineArgs.OutFile, ctx.EventHandler, ninjaDeps)
Jeongik Chaa87506f2023-06-01 23:16:41 +0900267 if needToWriteNinjaHint(ctx) {
Jeongik Cha591366d2023-05-08 11:32:52 +0900268 writeNinjaHint(ctx)
269 }
Paul Duffinb713ddf2022-11-05 16:14:30 +0000270 return cmdlineArgs.OutFile
Paul Duffin0c09a432022-11-05 15:28:04 +0000271 }
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200272}
273
274// soong_ui dumps the available environment variables to
275// soong.environment.available . Then soong_build itself is run with an empty
276// environment so that the only way environment variables can be accessed is
277// using Config, which tracks access to them.
278
279// At the end of the build, a file called soong.environment.used is written
280// containing the current value of all used environment variables. The next
281// time soong_ui is run, it checks whether any environment variables that was
282// used had changed and if so, it deletes soong.environment.used to cause a
283// rebuild.
284//
285// The dependency of build.ninja on soong.environment.used is declared in
286// build.ninja.d
287func parseAvailableEnv() map[string]string {
288 if availableEnvFile == "" {
289 fmt.Fprintf(os.Stderr, "--available_env not set\n")
290 os.Exit(1)
291 }
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200292 result, err := shared.EnvFromFile(shared.JoinPath(topDir, availableEnvFile))
Sasha Smundak1845f422022-12-13 14:18:58 -0800293 maybeQuit(err, "error reading available environment file '%s'", availableEnvFile)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200294 return result
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200295}
296
Colin Cross3f40fa42015-01-30 17:27:36 -0800297func main() {
298 flag.Parse()
299
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100300 shared.ReexecWithDelveMaybe(delveListen, delvePath)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100301 android.InitSandbox(topDir)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100302
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200303 availableEnv := parseAvailableEnv()
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800304 configuration, err := android.NewConfig(cmdlineArgs, availableEnv)
Sasha Smundak1845f422022-12-13 14:18:58 -0800305 maybeQuit(err, "")
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100306 if configuration.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
307 configuration.SetAllowMissingDependencies()
308 }
309
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800310 extraNinjaDeps := []string{configuration.ProductVariablesFileName, usedEnvFile}
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100311 if shared.IsDebugging() {
Colin Crossaa812d12019-06-19 13:33:24 -0700312 // Add a non-existent file to the dependencies so that soong_build will rerun when the debugger is
313 // enabled even if it completed successfully.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200314 extraNinjaDeps = append(extraNinjaDeps, filepath.Join(configuration.SoongOutDir(), "always_rerun_for_delve"))
Colin Crossaa812d12019-06-19 13:33:24 -0700315 }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500316
Dan Willemsenccf36aa2022-04-20 23:11:43 -0700317 // Bypass configuration.Getenv, as LOG_DIR does not need to be dependency tracked. By definition, it will
318 // change between every CI build, so tracking it would require re-running Soong for every build.
Sasha Smundak1845f422022-12-13 14:18:58 -0800319 metricsDir := availableEnv["LOG_DIR"]
Dan Willemsenccf36aa2022-04-20 23:11:43 -0700320
Joe Onorato2e5e4012022-06-07 17:16:08 -0700321 ctx := newContext(configuration)
Colin Cross46b0c752023-10-27 14:56:12 -0700322 android.StartBackgroundMetrics(configuration)
Joe Onorato2e5e4012022-06-07 17:16:08 -0700323
Colin Crossb63d7b32023-12-07 16:54:51 -0800324 ctx.Register()
325 finalOutputFile := runSoongOnlyBuild(ctx, extraNinjaDeps)
326 writeMetrics(configuration, ctx.EventHandler, metricsDir)
Chris Parsonsc83398f2023-05-31 18:41:41 +0000327
Chris Parsonsa3ae0072023-05-10 21:10:08 +0000328 writeUsedEnvironmentFile(configuration)
329
330 // Touch the output file so that it's the newest file created by soong_build.
331 // This is necessary because, if soong_build generated any files which
332 // are ninja inputs to the main output file, then ninja would superfluously
333 // rebuild this output file on the next build invocation.
334 touch(shared.JoinPath(topDir, finalOutputFile))
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100335}
336
Chris Parsonsa3ae0072023-05-10 21:10:08 +0000337func writeUsedEnvironmentFile(configuration android.Config) {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200338 if usedEnvFile == "" {
339 return
340 }
341
342 path := shared.JoinPath(topDir, usedEnvFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100343 data, err := shared.EnvFileContents(configuration.EnvDeps())
Sasha Smundak1845f422022-12-13 14:18:58 -0800344 maybeQuit(err, "error writing used environment file '%s'\n", usedEnvFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100345
Usta Shrestha2ba28a32022-10-24 11:33:09 -0400346 if preexistingData, err := os.ReadFile(path); err != nil {
347 if !os.IsNotExist(err) {
Sasha Smundak1845f422022-12-13 14:18:58 -0800348 maybeQuit(err, "error reading used environment file '%s'", usedEnvFile)
Usta Shrestha2ba28a32022-10-24 11:33:09 -0400349 }
350 } else if bytes.Equal(preexistingData, data) {
351 // used environment file is unchanged
352 return
353 }
Sasha Smundak1845f422022-12-13 14:18:58 -0800354 err = os.WriteFile(path, data, 0666)
355 maybeQuit(err, "error writing used environment file '%s'", usedEnvFile)
Colin Cross3f40fa42015-01-30 17:27:36 -0800356}
Jingwen Chen5ba7e472020-07-15 10:06:41 +0000357
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200358func touch(path string) {
359 f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
Sasha Smundak1845f422022-12-13 14:18:58 -0800360 maybeQuit(err, "Error touching '%s'", path)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200361 err = f.Close()
Sasha Smundak1845f422022-12-13 14:18:58 -0800362 maybeQuit(err, "Error touching '%s'", path)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200363
364 currentTime := time.Now().Local()
365 err = os.Chtimes(path, currentTime, currentTime)
Sasha Smundak1845f422022-12-13 14:18:58 -0800366 maybeQuit(err, "error touching '%s'", path)
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400367}
368
Sasha Smundak1845f422022-12-13 14:18:58 -0800369func maybeQuit(err error, format string, args ...interface{}) {
370 if err == nil {
371 return
372 }
373 if format != "" {
374 fmt.Fprintln(os.Stderr, fmt.Sprintf(format, args...)+": "+err.Error())
375 } else {
376 fmt.Fprintln(os.Stderr, err)
377 }
378 os.Exit(1)
MarkDacek0d5bca52022-10-10 20:07:48 +0000379}