blob: 24a44b4dac08f844e3ad6970e18d759ba3bb2cc2 [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 (
Yu Liufa297642024-06-11 00:13:02 +000018 "encoding/json"
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"
Cole Faust2fec4122024-09-07 17:28:11 -070031
Jeongik Chab745e2e2023-04-11 14:28:43 +090032 "github.com/google/blueprint"
Colin Cross70b40592015-03-23 12:57:34 -070033 "github.com/google/blueprint/bootstrap"
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +020034 "github.com/google/blueprint/deptools"
Chris Parsons715b08f2022-03-22 19:23:40 -040035 "github.com/google/blueprint/metrics"
Cole Faust2fec4122024-09-07 17:28:11 -070036 "github.com/google/blueprint/pathtools"
Yu Liufa297642024-06-11 00:13:02 +000037 "github.com/google/blueprint/proptools"
Dan Willemsen66213a62021-09-21 17:50:30 -070038 androidProtobuf "google.golang.org/protobuf/android"
Colin Cross3f40fa42015-01-30 17:27:36 -080039)
40
Colin Crosse87040b2017-12-11 15:52:26 -080041var (
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020042 topDir string
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020043 availableEnvFile string
44 usedEnvFile string
45
46 delveListen string
47 delvePath string
48
Sasha Smundakaf5ca922022-12-12 21:23:34 -080049 cmdlineArgs android.CmdArgs
Colin Crosse87040b2017-12-11 15:52:26 -080050)
51
Yu Liufa297642024-06-11 00:13:02 +000052const configCacheFile = "config.cache"
53
54type ConfigCache struct {
55 EnvDepsHash uint64
56 ProductVariableFileTimestamp int64
57 SoongBuildFileTimestamp int64
58}
59
Colin Crosse87040b2017-12-11 15:52:26 -080060func init() {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020061 // Flags that make sense in every mode
Lukacs T. Berki7690c092021-02-26 14:27:36 +010062 flag.StringVar(&topDir, "top", "", "Top directory of the Android source tree")
Sasha Smundakaf5ca922022-12-12 21:23:34 -080063 flag.StringVar(&cmdlineArgs.SoongOutDir, "soong_out", "", "Soong output directory (usually $TOP/out/soong)")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020064 flag.StringVar(&availableEnvFile, "available_env", "", "File containing available environment variables")
65 flag.StringVar(&usedEnvFile, "used_env", "", "File containing used environment variables")
Sasha Smundakaf5ca922022-12-12 21:23:34 -080066 flag.StringVar(&cmdlineArgs.OutDir, "out", "", "the ninja builddir directory")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020067 flag.StringVar(&cmdlineArgs.ModuleListFile, "l", "", "file that lists filepaths to parse")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020068
69 // Debug flags
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +010070 flag.StringVar(&delveListen, "delve_listen", "", "Delve port to listen on for debugging")
71 flag.StringVar(&delvePath, "delve_path", "", "Path to Delve. Only used if --delve_listen is set")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020072 flag.StringVar(&cmdlineArgs.Cpuprofile, "cpuprofile", "", "write cpu profile to file")
73 flag.StringVar(&cmdlineArgs.TraceFile, "trace", "", "write trace to file")
74 flag.StringVar(&cmdlineArgs.Memprofile, "memprofile", "", "write memory profile to file")
75 flag.BoolVar(&cmdlineArgs.NoGC, "nogc", false, "turn off GC for debugging")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020076
77 // Flags representing various modes soong_build can run in
Sasha Smundakaf5ca922022-12-12 21:23:34 -080078 flag.StringVar(&cmdlineArgs.ModuleGraphFile, "module_graph_file", "", "JSON module graph file to output")
79 flag.StringVar(&cmdlineArgs.ModuleActionsFile, "module_actions_file", "", "JSON file to output inputs/outputs of actions of modules")
80 flag.StringVar(&cmdlineArgs.DocFile, "soong_docs", "", "build documentation file to output")
81 flag.StringVar(&cmdlineArgs.BazelQueryViewDir, "bazel_queryview_dir", "", "path to the bazel queryview directory relative to --top")
Lukacs T. Berkif9008072021-08-16 15:24:48 +020082 flag.StringVar(&cmdlineArgs.OutFile, "o", "build.ninja", "the Ninja file to output")
Kiyoung Kima37d9ba2023-04-19 13:13:45 +090083 flag.StringVar(&cmdlineArgs.SoongVariables, "soong_variables", "soong.variables", "the file contains all build variables")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020084 flag.BoolVar(&cmdlineArgs.EmptyNinjaFile, "empty-ninja-file", false, "write out a 0-byte ninja file")
Jihoon Kang2a929ad2023-06-08 19:02:07 +000085 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 +000086 flag.BoolVar(&cmdlineArgs.EnsureAllowlistIntegrity, "ensure-allowlist-integrity", false, "verify that allowlisted modules are mixed-built")
Joe Onoratoe5ed3472024-02-02 14:52:05 -080087 flag.StringVar(&cmdlineArgs.ModuleDebugFile, "soong_module_debug", "", "soong module debug info file to write")
Sasha Smundakaf5ca922022-12-12 21:23:34 -080088 // Flags that probably shouldn't be flags of soong_build, but we haven't found
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020089 // the time to remove them yet
Sasha Smundakaf5ca922022-12-12 21:23:34 -080090 flag.BoolVar(&cmdlineArgs.RunGoTests, "t", false, "build and run go tests during bootstrap")
Yu Liufa297642024-06-11 00:13:02 +000091 flag.BoolVar(&cmdlineArgs.IncrementalBuildActions, "incremental-build-actions", false, "generate build actions incrementally")
Dan Willemsen66213a62021-09-21 17:50:30 -070092
93 // Disable deterministic randomization in the protobuf package, so incremental
94 // builds with unrelated Soong changes don't trigger large rebuilds (since we
95 // write out text protos in command lines, and command line changes trigger
96 // rebuilds).
97 androidProtobuf.DisableRand()
Colin Crosse87040b2017-12-11 15:52:26 -080098}
99
Jeff Gaston088e29e2017-11-29 16:47:17 -0800100func newNameResolver(config android.Config) *android.NameResolver {
Paul Duffin3f7bf9f2022-11-08 12:21:15 +0000101 return android.NewNameResolver(config)
Jeff Gaston088e29e2017-11-29 16:47:17 -0800102}
103
Lukacs T. Berkiffc9e8d2021-09-07 17:54:38 +0200104func newContext(configuration android.Config) *android.Context {
Colin Crossae8600b2020-10-29 17:09:13 -0700105 ctx := android.NewContext(configuration)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400106 ctx.SetNameInterface(newNameResolver(configuration))
107 ctx.SetAllowMissingDependencies(configuration.AllowMissingDependencies())
Sam Delmerico98a73292023-02-21 11:50:29 -0500108 ctx.AddSourceRootDirs(configuration.SourceRootDirs()...)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400109 return ctx
110}
111
Jeongik Chaa87506f2023-06-01 23:16:41 +0900112func needToWriteNinjaHint(ctx *android.Context) bool {
113 switch ctx.Config().GetenvWithDefault("SOONG_GENERATES_NINJA_HINT", "") {
114 case "always":
115 return true
116 case "depend":
Cole Faust6bb28322024-05-13 11:57:16 -0700117 if _, err := os.Stat(filepath.Join(topDir, ctx.Config().OutDir(), ".ninja_log")); errors.Is(err, os.ErrNotExist) {
Jeongik Chaa87506f2023-06-01 23:16:41 +0900118 return true
119 }
120 }
121 return false
122}
123
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200124// Run the code-generation phase to convert BazelTargetModules to BUILD files.
Sasha Smundak1845f422022-12-13 14:18:58 -0800125func runQueryView(queryviewDir, queryviewMarker string, ctx *android.Context) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400126 ctx.EventHandler.Begin("queryview")
127 defer ctx.EventHandler.End("queryview")
Cole Faustb85d1a12022-11-08 18:14:01 -0800128 codegenContext := bp2build.NewCodegenContext(ctx.Config(), ctx, bp2build.QueryView, topDir)
Spandan Das98cb8562023-03-09 23:05:47 +0000129 err := createBazelWorkspace(codegenContext, shared.JoinPath(topDir, queryviewDir), false)
Sasha Smundak1845f422022-12-13 14:18:58 -0800130 maybeQuit(err, "")
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200131 touch(shared.JoinPath(topDir, queryviewMarker))
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200132}
133
Jeongik Chae114e602023-03-19 00:12:39 +0900134func writeNinjaHint(ctx *android.Context) error {
Jeongik Cha73d49112023-05-04 18:16:11 +0900135 ctx.BeginEvent("ninja_hint")
136 defer ctx.EndEvent("ninja_hint")
Jeongik Chab745e2e2023-04-11 14:28:43 +0900137 // The current predictor focuses on reducing false negatives.
138 // If there are too many false positives (e.g., most modules are marked as positive),
139 // real long-running jobs cannot run early.
140 // Therefore, the model should be adjusted in this case.
141 // The model should also be adjusted if there are critical false negatives.
142 predicate := func(j *blueprint.JsonModule) (prioritized bool, weight int) {
143 prioritized = false
144 weight = 0
145 for prefix, w := range allowlists.HugeModuleTypePrefixMap {
146 if strings.HasPrefix(j.Type, prefix) {
147 prioritized = true
148 weight = w
149 return
150 }
Jeongik Chae114e602023-03-19 00:12:39 +0900151 }
Jeongik Chab745e2e2023-04-11 14:28:43 +0900152 dep_count := len(j.Deps)
153 src_count := 0
154 for _, a := range j.Module["Actions"].([]blueprint.JSONAction) {
155 src_count += len(a.Inputs)
156 }
157 input_size := dep_count + src_count
158
159 // Current threshold is an arbitrary value which only consider recall rather than accuracy.
160 if input_size > allowlists.INPUT_SIZE_THRESHOLD {
161 prioritized = true
162 weight += ((input_size) / allowlists.INPUT_SIZE_THRESHOLD) * allowlists.DEFAULT_PRIORITIZED_WEIGHT
163
164 // To prevent some modules from having too large a priority value.
165 if weight > allowlists.HIGH_PRIORITIZED_WEIGHT {
166 weight = allowlists.HIGH_PRIORITIZED_WEIGHT
167 }
168 }
169 return
170 }
171
172 outputsMap := ctx.Context.GetWeightedOutputsFromPredicate(predicate)
173 var outputBuilder strings.Builder
174 for output, weight := range outputsMap {
175 outputBuilder.WriteString(fmt.Sprintf("%s,%d\n", output, weight))
Jeongik Chae114e602023-03-19 00:12:39 +0900176 }
177 weightListFile := filepath.Join(topDir, ctx.Config().OutDir(), ".ninja_weight_list")
178
179 err := os.WriteFile(weightListFile, []byte(outputBuilder.String()), 0644)
180 if err != nil {
181 return fmt.Errorf("could not write ninja weight list file %s", err)
182 }
183 return nil
184}
185
Paul Duffin780a1852022-11-05 10:17:12 +0000186func writeMetrics(configuration android.Config, eventHandler *metrics.EventHandler, metricsDir string) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400187 if len(metricsDir) < 1 {
188 fmt.Fprintf(os.Stderr, "\nMissing required env var for generating soong metrics: LOG_DIR\n")
189 os.Exit(1)
190 }
191 metricsFile := filepath.Join(metricsDir, "soong_build_metrics.pb")
192 err := android.WriteMetrics(configuration, eventHandler, metricsFile)
Sasha Smundak1845f422022-12-13 14:18:58 -0800193 maybeQuit(err, "error writing soong_build metrics %s", metricsFile)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200194}
195
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800196func writeJsonModuleGraphAndActions(ctx *android.Context, cmdArgs android.CmdArgs) {
197 graphFile, graphErr := os.Create(shared.JoinPath(topDir, cmdArgs.ModuleGraphFile))
Sasha Smundak1845f422022-12-13 14:18:58 -0800198 maybeQuit(graphErr, "graph err")
kgui67007242022-01-25 13:50:25 +0800199 defer graphFile.Close()
Sasha Smundak1845f422022-12-13 14:18:58 -0800200 actionsFile, actionsErr := os.Create(shared.JoinPath(topDir, cmdArgs.ModuleActionsFile))
201 maybeQuit(actionsErr, "actions err")
kgui67007242022-01-25 13:50:25 +0800202 defer actionsFile.Close()
203 ctx.Context.PrintJSONGraphAndActions(graphFile, actionsFile)
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200204}
205
Paul Duffin780a1852022-11-05 10:17:12 +0000206func writeDepFile(outputFile string, eventHandler *metrics.EventHandler, ninjaDeps []string) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400207 eventHandler.Begin("ninja_deps")
208 defer eventHandler.End("ninja_deps")
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200209 depFile := shared.JoinPath(topDir, outputFile+".d")
210 err := deptools.WriteDepFile(depFile, outputFile, ninjaDeps)
Sasha Smundak1845f422022-12-13 14:18:58 -0800211 maybeQuit(err, "error writing depfile '%s'", depFile)
Paul Duffin0c09a432022-11-05 15:28:04 +0000212}
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200213
Yu Liufa297642024-06-11 00:13:02 +0000214// Check if there are changes to the environment file, product variable file and
215// soong_build binary, in which case no incremental will be performed.
216func incrementalValid(config android.Config, configCacheFile string) (*ConfigCache, bool) {
217 var newConfigCache ConfigCache
218 data, err := os.ReadFile(shared.JoinPath(topDir, usedEnvFile))
219 if err != nil {
220 // Clean build
221 if os.IsNotExist(err) {
222 data = []byte{}
223 } else {
224 maybeQuit(err, "")
225 }
226 }
227
228 newConfigCache.EnvDepsHash, err = proptools.CalculateHash(data)
229 newConfigCache.ProductVariableFileTimestamp = getFileTimestamp(filepath.Join(topDir, cmdlineArgs.SoongVariables))
230 newConfigCache.SoongBuildFileTimestamp = getFileTimestamp(filepath.Join(topDir, config.HostToolDir(), "soong_build"))
231 //TODO(b/344917959): out/soong/dexpreopt.config might need to be checked as well.
232
233 file, err := os.Open(configCacheFile)
234 if err != nil && os.IsNotExist(err) {
235 return &newConfigCache, false
236 }
237 maybeQuit(err, "")
238 defer file.Close()
239
240 var configCache ConfigCache
241 decoder := json.NewDecoder(file)
242 err = decoder.Decode(&configCache)
243 maybeQuit(err, "")
244
245 return &newConfigCache, newConfigCache == configCache
246}
247
248func getFileTimestamp(file string) int64 {
249 stat, err := os.Stat(file)
250 if err == nil {
251 return stat.ModTime().UnixMilli()
252 } else if !os.IsNotExist(err) {
253 maybeQuit(err, "")
254 }
255 return 0
256}
257
258func writeConfigCache(configCache *ConfigCache, configCacheFile string) {
259 file, err := os.Create(configCacheFile)
260 maybeQuit(err, "")
261 defer file.Close()
262
263 encoder := json.NewEncoder(file)
264 err = encoder.Encode(*configCache)
265 maybeQuit(err, "")
266}
267
Paul Duffin0c09a432022-11-05 15:28:04 +0000268// runSoongOnlyBuild runs the standard Soong build in a number of different modes.
Cole Faust2fec4122024-09-07 17:28:11 -0700269// It returns the path to the output file (usually the ninja file) and the deps that need
270// to trigger a soong rerun.
271func runSoongOnlyBuild(ctx *android.Context) (string, []string) {
Paul Duffin39eae8f2022-11-05 14:59:52 +0000272 ctx.EventHandler.Begin("soong_build")
273 defer ctx.EventHandler.End("soong_build")
274
Paul Duffin0c09a432022-11-05 15:28:04 +0000275 var stopBefore bootstrap.StopBefore
Sasha Smundak1845f422022-12-13 14:18:58 -0800276 switch ctx.Config().BuildMode {
277 case android.GenerateModuleGraph:
Paul Duffin0c09a432022-11-05 15:28:04 +0000278 stopBefore = bootstrap.StopBeforeWriteNinja
Usta Shrestha7fae6952022-12-21 11:46:28 -0500279 case android.GenerateQueryView, android.GenerateDocFile:
Paul Duffin0c09a432022-11-05 15:28:04 +0000280 stopBefore = bootstrap.StopBeforePrepareBuildActions
Sasha Smundak1845f422022-12-13 14:18:58 -0800281 default:
Paul Duffin0c09a432022-11-05 15:28:04 +0000282 stopBefore = bootstrap.DoEverything
283 }
284
Lukacs T. Berkic357c812023-06-20 09:30:06 +0000285 ninjaDeps, err := bootstrap.RunBlueprint(cmdlineArgs.Args, stopBefore, ctx.Context, ctx.Config())
286 maybeQuit(err, "")
Paul Duffin0c09a432022-11-05 15:28:04 +0000287
288 // Convert the Soong module graph into Bazel BUILD files.
Sasha Smundak1845f422022-12-13 14:18:58 -0800289 switch ctx.Config().BuildMode {
290 case android.GenerateQueryView:
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800291 queryviewMarkerFile := cmdlineArgs.BazelQueryViewDir + ".marker"
Sasha Smundak1845f422022-12-13 14:18:58 -0800292 runQueryView(cmdlineArgs.BazelQueryViewDir, queryviewMarkerFile, ctx)
Cole Faust2fec4122024-09-07 17:28:11 -0700293 return queryviewMarkerFile, ninjaDeps
Sasha Smundak1845f422022-12-13 14:18:58 -0800294 case android.GenerateModuleGraph:
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800295 writeJsonModuleGraphAndActions(ctx, cmdlineArgs)
Cole Faust2fec4122024-09-07 17:28:11 -0700296 return cmdlineArgs.ModuleGraphFile, ninjaDeps
Sasha Smundak1845f422022-12-13 14:18:58 -0800297 case android.GenerateDocFile:
Paul Duffin0c09a432022-11-05 15:28:04 +0000298 // TODO: we could make writeDocs() return the list of documentation files
299 // written and add them to the .d file. Then soong_docs would be re-run
300 // whenever one is deleted.
Sasha Smundak1845f422022-12-13 14:18:58 -0800301 err := writeDocs(ctx, shared.JoinPath(topDir, cmdlineArgs.DocFile))
302 maybeQuit(err, "error building Soong documentation")
Cole Faust2fec4122024-09-07 17:28:11 -0700303 return cmdlineArgs.DocFile, ninjaDeps
Sasha Smundak1845f422022-12-13 14:18:58 -0800304 default:
Paul Duffin0c09a432022-11-05 15:28:04 +0000305 // The actual output (build.ninja) was written in the RunBlueprint() call
306 // above
Jeongik Chaa87506f2023-06-01 23:16:41 +0900307 if needToWriteNinjaHint(ctx) {
Jeongik Cha591366d2023-05-08 11:32:52 +0900308 writeNinjaHint(ctx)
309 }
Cole Faust2fec4122024-09-07 17:28:11 -0700310 return cmdlineArgs.OutFile, ninjaDeps
Paul Duffin0c09a432022-11-05 15:28:04 +0000311 }
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200312}
313
314// soong_ui dumps the available environment variables to
315// soong.environment.available . Then soong_build itself is run with an empty
316// environment so that the only way environment variables can be accessed is
317// using Config, which tracks access to them.
318
319// At the end of the build, a file called soong.environment.used is written
320// containing the current value of all used environment variables. The next
321// time soong_ui is run, it checks whether any environment variables that was
322// used had changed and if so, it deletes soong.environment.used to cause a
323// rebuild.
324//
325// The dependency of build.ninja on soong.environment.used is declared in
326// build.ninja.d
327func parseAvailableEnv() map[string]string {
328 if availableEnvFile == "" {
329 fmt.Fprintf(os.Stderr, "--available_env not set\n")
330 os.Exit(1)
331 }
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200332 result, err := shared.EnvFromFile(shared.JoinPath(topDir, availableEnvFile))
Sasha Smundak1845f422022-12-13 14:18:58 -0800333 maybeQuit(err, "error reading available environment file '%s'", availableEnvFile)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200334 return result
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200335}
336
Colin Cross3f40fa42015-01-30 17:27:36 -0800337func main() {
338 flag.Parse()
339
Cole Faust2fec4122024-09-07 17:28:11 -0700340 soongStartTime := time.Now()
341
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100342 shared.ReexecWithDelveMaybe(delveListen, delvePath)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100343 android.InitSandbox(topDir)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100344
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200345 availableEnv := parseAvailableEnv()
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800346 configuration, err := android.NewConfig(cmdlineArgs, availableEnv)
Sasha Smundak1845f422022-12-13 14:18:58 -0800347 maybeQuit(err, "")
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100348 if configuration.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
349 configuration.SetAllowMissingDependencies()
350 }
351
Dan Willemsenccf36aa2022-04-20 23:11:43 -0700352 // Bypass configuration.Getenv, as LOG_DIR does not need to be dependency tracked. By definition, it will
353 // change between every CI build, so tracking it would require re-running Soong for every build.
Sasha Smundak1845f422022-12-13 14:18:58 -0800354 metricsDir := availableEnv["LOG_DIR"]
Dan Willemsenccf36aa2022-04-20 23:11:43 -0700355
Joe Onorato2e5e4012022-06-07 17:16:08 -0700356 ctx := newContext(configuration)
Colin Cross46b0c752023-10-27 14:56:12 -0700357 android.StartBackgroundMetrics(configuration)
Joe Onorato2e5e4012022-06-07 17:16:08 -0700358
Yu Liufa297642024-06-11 00:13:02 +0000359 var configCache *ConfigCache
360 configFile := filepath.Join(topDir, ctx.Config().OutDir(), configCacheFile)
361 incremental := false
362 ctx.SetIncrementalEnabled(cmdlineArgs.IncrementalBuildActions)
363 if cmdlineArgs.IncrementalBuildActions {
364 configCache, incremental = incrementalValid(ctx.Config(), configFile)
365 }
366 ctx.SetIncrementalAnalysis(incremental)
367
Colin Crossb63d7b32023-12-07 16:54:51 -0800368 ctx.Register()
Cole Faust2fec4122024-09-07 17:28:11 -0700369 finalOutputFile, ninjaDeps := runSoongOnlyBuild(ctx)
370
371 ninjaDeps = append(ninjaDeps, usedEnvFile)
372 if shared.IsDebugging() {
373 // Add a non-existent file to the dependencies so that soong_build will rerun when the debugger is
374 // enabled even if it completed successfully.
375 ninjaDeps = append(ninjaDeps, filepath.Join(configuration.SoongOutDir(), "always_rerun_for_delve"))
376 }
377
378 writeDepFile(finalOutputFile, ctx.EventHandler, ninjaDeps)
Yu Liufa297642024-06-11 00:13:02 +0000379
380 if ctx.GetIncrementalEnabled() {
381 data, err := shared.EnvFileContents(configuration.EnvDeps())
382 maybeQuit(err, "")
383 configCache.EnvDepsHash, err = proptools.CalculateHash(data)
384 maybeQuit(err, "")
385 writeConfigCache(configCache, configFile)
386 }
387
Colin Crossb63d7b32023-12-07 16:54:51 -0800388 writeMetrics(configuration, ctx.EventHandler, metricsDir)
Chris Parsonsc83398f2023-05-31 18:41:41 +0000389
Chris Parsonsa3ae0072023-05-10 21:10:08 +0000390 writeUsedEnvironmentFile(configuration)
391
Cole Faust2fec4122024-09-07 17:28:11 -0700392 err = writeGlobFile(ctx.EventHandler, finalOutputFile, ctx.Globs(), soongStartTime)
393 maybeQuit(err, "")
394
Chris Parsonsa3ae0072023-05-10 21:10:08 +0000395 // Touch the output file so that it's the newest file created by soong_build.
396 // This is necessary because, if soong_build generated any files which
397 // are ninja inputs to the main output file, then ninja would superfluously
398 // rebuild this output file on the next build invocation.
399 touch(shared.JoinPath(topDir, finalOutputFile))
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100400}
401
Chris Parsonsa3ae0072023-05-10 21:10:08 +0000402func writeUsedEnvironmentFile(configuration android.Config) {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200403 if usedEnvFile == "" {
404 return
405 }
406
407 path := shared.JoinPath(topDir, usedEnvFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100408 data, err := shared.EnvFileContents(configuration.EnvDeps())
Sasha Smundak1845f422022-12-13 14:18:58 -0800409 maybeQuit(err, "error writing used environment file '%s'\n", usedEnvFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100410
Cole Faust2fec4122024-09-07 17:28:11 -0700411 err = pathtools.WriteFileIfChanged(path, data, 0666)
Sasha Smundak1845f422022-12-13 14:18:58 -0800412 maybeQuit(err, "error writing used environment file '%s'", usedEnvFile)
Colin Cross3f40fa42015-01-30 17:27:36 -0800413}
Jingwen Chen5ba7e472020-07-15 10:06:41 +0000414
Cole Faust2fec4122024-09-07 17:28:11 -0700415func writeGlobFile(eventHandler *metrics.EventHandler, finalOutFile string, globs pathtools.MultipleGlobResults, soongStartTime time.Time) error {
416 eventHandler.Begin("writeGlobFile")
417 defer eventHandler.End("writeGlobFile")
418
419 globsFile, err := os.Create(shared.JoinPath(topDir, finalOutFile+".globs"))
420 if err != nil {
421 return err
422 }
423 defer globsFile.Close()
424 globsFileEncoder := json.NewEncoder(globsFile)
425 for _, glob := range globs {
426 if err := globsFileEncoder.Encode(glob); err != nil {
427 return err
428 }
429 }
430
431 return os.WriteFile(
432 shared.JoinPath(topDir, finalOutFile+".globs_time"),
433 []byte(fmt.Sprintf("%d\n", soongStartTime.UnixMicro())),
434 0666,
435 )
436}
437
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200438func touch(path string) {
439 f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
Sasha Smundak1845f422022-12-13 14:18:58 -0800440 maybeQuit(err, "Error touching '%s'", path)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200441 err = f.Close()
Sasha Smundak1845f422022-12-13 14:18:58 -0800442 maybeQuit(err, "Error touching '%s'", path)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200443
444 currentTime := time.Now().Local()
445 err = os.Chtimes(path, currentTime, currentTime)
Sasha Smundak1845f422022-12-13 14:18:58 -0800446 maybeQuit(err, "error touching '%s'", path)
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400447}
448
Sasha Smundak1845f422022-12-13 14:18:58 -0800449func maybeQuit(err error, format string, args ...interface{}) {
450 if err == nil {
451 return
452 }
453 if format != "" {
454 fmt.Fprintln(os.Stderr, fmt.Sprintf(format, args...)+": "+err.Error())
455 } else {
456 fmt.Fprintln(os.Stderr, err)
457 }
458 os.Exit(1)
MarkDacek0d5bca52022-10-10 20:07:48 +0000459}