xref: /aosp_15_r20/build/soong/cmd/soong_build/main.go (revision 333d2b3687b3a337dbcca9d65000bca186795e39)
1// 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 (
18	"encoding/json"
19	"errors"
20	"flag"
21	"fmt"
22	"os"
23	"path/filepath"
24	"strings"
25	"time"
26
27	"android/soong/android"
28	"android/soong/android/allowlists"
29	"android/soong/shared"
30
31	"github.com/google/blueprint"
32	"github.com/google/blueprint/bootstrap"
33	"github.com/google/blueprint/deptools"
34	"github.com/google/blueprint/metrics"
35	"github.com/google/blueprint/pathtools"
36	"github.com/google/blueprint/proptools"
37	androidProtobuf "google.golang.org/protobuf/android"
38)
39
40var (
41	topDir           string
42	availableEnvFile string
43	usedEnvFile      string
44
45	delveListen string
46	delvePath   string
47
48	cmdlineArgs android.CmdArgs
49)
50
51const configCacheFile = "config.cache"
52
53type ConfigCache struct {
54	EnvDepsHash                  uint64
55	ProductVariableFileTimestamp int64
56	SoongBuildFileTimestamp      int64
57}
58
59func init() {
60	// Flags that make sense in every mode
61	flag.StringVar(&topDir, "top", "", "Top directory of the Android source tree")
62	flag.StringVar(&cmdlineArgs.SoongOutDir, "soong_out", "", "Soong output directory (usually $TOP/out/soong)")
63	flag.StringVar(&availableEnvFile, "available_env", "", "File containing available environment variables")
64	flag.StringVar(&usedEnvFile, "used_env", "", "File containing used environment variables")
65	flag.StringVar(&cmdlineArgs.OutDir, "out", "", "the ninja builddir directory")
66	flag.StringVar(&cmdlineArgs.ModuleListFile, "l", "", "file that lists filepaths to parse")
67
68	// Debug flags
69	flag.StringVar(&delveListen, "delve_listen", "", "Delve port to listen on for debugging")
70	flag.StringVar(&delvePath, "delve_path", "", "Path to Delve. Only used if --delve_listen is set")
71	flag.StringVar(&cmdlineArgs.Cpuprofile, "cpuprofile", "", "write cpu profile to file")
72	flag.StringVar(&cmdlineArgs.TraceFile, "trace", "", "write trace to file")
73	flag.StringVar(&cmdlineArgs.Memprofile, "memprofile", "", "write memory profile to file")
74	flag.BoolVar(&cmdlineArgs.NoGC, "nogc", false, "turn off GC for debugging")
75
76	// Flags representing various modes soong_build can run in
77	flag.StringVar(&cmdlineArgs.ModuleGraphFile, "module_graph_file", "", "JSON module graph file to output")
78	flag.StringVar(&cmdlineArgs.ModuleActionsFile, "module_actions_file", "", "JSON file to output inputs/outputs of actions of modules")
79	flag.StringVar(&cmdlineArgs.DocFile, "soong_docs", "", "build documentation file to output")
80	flag.StringVar(&cmdlineArgs.OutFile, "o", "build.ninja", "the Ninja file to output")
81	flag.StringVar(&cmdlineArgs.SoongVariables, "soong_variables", "soong.variables", "the file contains all build variables")
82	flag.BoolVar(&cmdlineArgs.EmptyNinjaFile, "empty-ninja-file", false, "write out a 0-byte ninja file")
83	flag.BoolVar(&cmdlineArgs.BuildFromSourceStub, "build-from-source-stub", false, "build Java stubs from source files instead of API text files")
84	flag.BoolVar(&cmdlineArgs.EnsureAllowlistIntegrity, "ensure-allowlist-integrity", false, "verify that allowlisted modules are mixed-built")
85	flag.StringVar(&cmdlineArgs.ModuleDebugFile, "soong_module_debug", "", "soong module debug info file to write")
86	// Flags that probably shouldn't be flags of soong_build, but we haven't found
87	// the time to remove them yet
88	flag.BoolVar(&cmdlineArgs.RunGoTests, "t", false, "build and run go tests during bootstrap")
89	flag.BoolVar(&cmdlineArgs.IncrementalBuildActions, "incremental-build-actions", false, "generate build actions incrementally")
90
91	// Disable deterministic randomization in the protobuf package, so incremental
92	// builds with unrelated Soong changes don't trigger large rebuilds (since we
93	// write out text protos in command lines, and command line changes trigger
94	// rebuilds).
95	androidProtobuf.DisableRand()
96}
97
98func newNameResolver(config android.Config) *android.NameResolver {
99	return android.NewNameResolver(config)
100}
101
102func newContext(configuration android.Config) *android.Context {
103	ctx := android.NewContext(configuration)
104	ctx.SetNameInterface(newNameResolver(configuration))
105	ctx.SetAllowMissingDependencies(configuration.AllowMissingDependencies())
106	ctx.AddSourceRootDirs(configuration.SourceRootDirs()...)
107	return ctx
108}
109
110func needToWriteNinjaHint(ctx *android.Context) bool {
111	switch ctx.Config().GetenvWithDefault("SOONG_GENERATES_NINJA_HINT", "") {
112	case "always":
113		return true
114	case "depend":
115		if _, err := os.Stat(filepath.Join(topDir, ctx.Config().OutDir(), ".ninja_log")); errors.Is(err, os.ErrNotExist) {
116			return true
117		}
118	}
119	return false
120}
121
122func writeNinjaHint(ctx *android.Context) error {
123	ctx.BeginEvent("ninja_hint")
124	defer ctx.EndEvent("ninja_hint")
125	// The current predictor focuses on reducing false negatives.
126	// If there are too many false positives (e.g., most modules are marked as positive),
127	// real long-running jobs cannot run early.
128	// Therefore, the model should be adjusted in this case.
129	// The model should also be adjusted if there are critical false negatives.
130	predicate := func(j *blueprint.JsonModule) (prioritized bool, weight int) {
131		prioritized = false
132		weight = 0
133		for prefix, w := range allowlists.HugeModuleTypePrefixMap {
134			if strings.HasPrefix(j.Type, prefix) {
135				prioritized = true
136				weight = w
137				return
138			}
139		}
140		dep_count := len(j.Deps)
141		src_count := 0
142		for _, a := range j.Module["Actions"].([]blueprint.JSONAction) {
143			src_count += len(a.Inputs)
144		}
145		input_size := dep_count + src_count
146
147		// Current threshold is an arbitrary value which only consider recall rather than accuracy.
148		if input_size > allowlists.INPUT_SIZE_THRESHOLD {
149			prioritized = true
150			weight += ((input_size) / allowlists.INPUT_SIZE_THRESHOLD) * allowlists.DEFAULT_PRIORITIZED_WEIGHT
151
152			// To prevent some modules from having too large a priority value.
153			if weight > allowlists.HIGH_PRIORITIZED_WEIGHT {
154				weight = allowlists.HIGH_PRIORITIZED_WEIGHT
155			}
156		}
157		return
158	}
159
160	outputsMap := ctx.Context.GetWeightedOutputsFromPredicate(predicate)
161	var outputBuilder strings.Builder
162	for output, weight := range outputsMap {
163		outputBuilder.WriteString(fmt.Sprintf("%s,%d\n", output, weight))
164	}
165	weightListFile := filepath.Join(topDir, ctx.Config().OutDir(), ".ninja_weight_list")
166
167	err := os.WriteFile(weightListFile, []byte(outputBuilder.String()), 0644)
168	if err != nil {
169		return fmt.Errorf("could not write ninja weight list file %s", err)
170	}
171	return nil
172}
173
174func writeMetrics(configuration android.Config, eventHandler *metrics.EventHandler, metricsDir string) {
175	if len(metricsDir) < 1 {
176		fmt.Fprintf(os.Stderr, "\nMissing required env var for generating soong metrics: LOG_DIR\n")
177		os.Exit(1)
178	}
179	metricsFile := filepath.Join(metricsDir, "soong_build_metrics.pb")
180	err := android.WriteMetrics(configuration, eventHandler, metricsFile)
181	maybeQuit(err, "error writing soong_build metrics %s", metricsFile)
182}
183
184func writeJsonModuleGraphAndActions(ctx *android.Context, cmdArgs android.CmdArgs) {
185	graphFile, graphErr := os.Create(shared.JoinPath(topDir, cmdArgs.ModuleGraphFile))
186	maybeQuit(graphErr, "graph err")
187	defer graphFile.Close()
188	actionsFile, actionsErr := os.Create(shared.JoinPath(topDir, cmdArgs.ModuleActionsFile))
189	maybeQuit(actionsErr, "actions err")
190	defer actionsFile.Close()
191	ctx.Context.PrintJSONGraphAndActions(graphFile, actionsFile)
192}
193
194func writeDepFile(outputFile string, eventHandler *metrics.EventHandler, ninjaDeps []string) {
195	eventHandler.Begin("ninja_deps")
196	defer eventHandler.End("ninja_deps")
197	depFile := shared.JoinPath(topDir, outputFile+".d")
198	err := deptools.WriteDepFile(depFile, outputFile, ninjaDeps)
199	maybeQuit(err, "error writing depfile '%s'", depFile)
200}
201
202// Check if there are changes to the environment file, product variable file and
203// soong_build binary, in which case no incremental will be performed. For env
204// variables we check the used env file, which will be removed in soong ui if
205// there is any changes to the env variables used last time, in which case the
206// check below will fail and a full build will be attempted. If any new env
207// variables are added in the new run, soong ui won't be able to detect it, the
208// used env file check below will pass. But unless there is a soong build code
209// change, in which case the soong build binary check will fail, otherwise the
210// new env variables shouldn't have any affect.
211func incrementalValid(config android.Config, configCacheFile string) (*ConfigCache, bool) {
212	var newConfigCache ConfigCache
213	data, err := os.ReadFile(shared.JoinPath(topDir, usedEnvFile))
214	if err != nil {
215		// Clean build
216		if os.IsNotExist(err) {
217			data = []byte{}
218		} else {
219			maybeQuit(err, "")
220		}
221	}
222
223	newConfigCache.EnvDepsHash, err = proptools.CalculateHash(data)
224	newConfigCache.ProductVariableFileTimestamp = getFileTimestamp(filepath.Join(topDir, cmdlineArgs.SoongVariables))
225	newConfigCache.SoongBuildFileTimestamp = getFileTimestamp(filepath.Join(topDir, config.HostToolDir(), "soong_build"))
226	//TODO(b/344917959): out/soong/dexpreopt.config might need to be checked as well.
227
228	file, err := os.Open(configCacheFile)
229	if err != nil && os.IsNotExist(err) {
230		return &newConfigCache, false
231	}
232	maybeQuit(err, "")
233	defer file.Close()
234
235	var configCache ConfigCache
236	decoder := json.NewDecoder(file)
237	err = decoder.Decode(&configCache)
238	maybeQuit(err, "")
239
240	return &newConfigCache, newConfigCache == configCache
241}
242
243func getFileTimestamp(file string) int64 {
244	stat, err := os.Stat(file)
245	if err == nil {
246		return stat.ModTime().UnixMilli()
247	} else if !os.IsNotExist(err) {
248		maybeQuit(err, "")
249	}
250	return 0
251}
252
253func writeConfigCache(configCache *ConfigCache, configCacheFile string) {
254	file, err := os.Create(configCacheFile)
255	maybeQuit(err, "")
256	defer file.Close()
257
258	encoder := json.NewEncoder(file)
259	err = encoder.Encode(*configCache)
260	maybeQuit(err, "")
261}
262
263// runSoongOnlyBuild runs the standard Soong build in a number of different modes.
264// It returns the path to the output file (usually the ninja file) and the deps that need
265// to trigger a soong rerun.
266func runSoongOnlyBuild(ctx *android.Context) (string, []string) {
267	ctx.EventHandler.Begin("soong_build")
268	defer ctx.EventHandler.End("soong_build")
269
270	var stopBefore bootstrap.StopBefore
271	switch ctx.Config().BuildMode {
272	case android.GenerateModuleGraph:
273		stopBefore = bootstrap.StopBeforeWriteNinja
274	case android.GenerateDocFile:
275		stopBefore = bootstrap.StopBeforePrepareBuildActions
276	default:
277		stopBefore = bootstrap.DoEverything
278	}
279
280	ninjaDeps, err := bootstrap.RunBlueprint(cmdlineArgs.Args, stopBefore, ctx.Context, ctx.Config())
281	maybeQuit(err, "")
282
283	// Convert the Soong module graph into Bazel BUILD files.
284	switch ctx.Config().BuildMode {
285	case android.GenerateModuleGraph:
286		writeJsonModuleGraphAndActions(ctx, cmdlineArgs)
287		return cmdlineArgs.ModuleGraphFile, ninjaDeps
288	case android.GenerateDocFile:
289		// TODO: we could make writeDocs() return the list of documentation files
290		// written and add them to the .d file. Then soong_docs would be re-run
291		// whenever one is deleted.
292		err := writeDocs(ctx, shared.JoinPath(topDir, cmdlineArgs.DocFile))
293		maybeQuit(err, "error building Soong documentation")
294		return cmdlineArgs.DocFile, ninjaDeps
295	default:
296		// The actual output (build.ninja) was written in the RunBlueprint() call
297		// above
298		if needToWriteNinjaHint(ctx) {
299			writeNinjaHint(ctx)
300		}
301		return cmdlineArgs.OutFile, ninjaDeps
302	}
303}
304
305// soong_ui dumps the available environment variables to
306// soong.environment.available . Then soong_build itself is run with an empty
307// environment so that the only way environment variables can be accessed is
308// using Config, which tracks access to them.
309
310// At the end of the build, a file called soong.environment.used is written
311// containing the current value of all used environment variables. The next
312// time soong_ui is run, it checks whether any environment variables that was
313// used had changed and if so, it deletes soong.environment.used to cause a
314// rebuild.
315//
316// The dependency of build.ninja on soong.environment.used is declared in
317// build.ninja.d
318func parseAvailableEnv() map[string]string {
319	if availableEnvFile == "" {
320		fmt.Fprintf(os.Stderr, "--available_env not set\n")
321		os.Exit(1)
322	}
323	result, err := shared.EnvFromFile(shared.JoinPath(topDir, availableEnvFile))
324	maybeQuit(err, "error reading available environment file '%s'", availableEnvFile)
325	return result
326}
327
328func main() {
329	flag.Parse()
330
331	soongStartTime := time.Now()
332
333	shared.ReexecWithDelveMaybe(delveListen, delvePath)
334	android.InitSandbox(topDir)
335
336	availableEnv := parseAvailableEnv()
337	configuration, err := android.NewConfig(cmdlineArgs, availableEnv)
338	maybeQuit(err, "")
339	if configuration.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
340		configuration.SetAllowMissingDependencies()
341	}
342
343	// Bypass configuration.Getenv, as LOG_DIR does not need to be dependency tracked. By definition, it will
344	// change between every CI build, so tracking it would require re-running Soong for every build.
345	metricsDir := availableEnv["LOG_DIR"]
346
347	ctx := newContext(configuration)
348	android.StartBackgroundMetrics(configuration)
349
350	var configCache *ConfigCache
351	configFile := filepath.Join(topDir, ctx.Config().OutDir(), configCacheFile)
352	incremental := false
353	ctx.SetIncrementalEnabled(cmdlineArgs.IncrementalBuildActions)
354	if cmdlineArgs.IncrementalBuildActions {
355		configCache, incremental = incrementalValid(ctx.Config(), configFile)
356	}
357	ctx.SetIncrementalAnalysis(incremental)
358
359	ctx.Register()
360	finalOutputFile, ninjaDeps := runSoongOnlyBuild(ctx)
361
362	ninjaDeps = append(ninjaDeps, configuration.ProductVariablesFileName)
363	ninjaDeps = append(ninjaDeps, usedEnvFile)
364	if shared.IsDebugging() {
365		// Add a non-existent file to the dependencies so that soong_build will rerun when the debugger is
366		// enabled even if it completed successfully.
367		ninjaDeps = append(ninjaDeps, filepath.Join(configuration.SoongOutDir(), "always_rerun_for_delve"))
368	}
369
370	writeDepFile(finalOutputFile, ctx.EventHandler, ninjaDeps)
371
372	if ctx.GetIncrementalEnabled() {
373		data, err := shared.EnvFileContents(configuration.EnvDeps())
374		maybeQuit(err, "")
375		configCache.EnvDepsHash, err = proptools.CalculateHash(data)
376		maybeQuit(err, "")
377		writeConfigCache(configCache, configFile)
378	}
379
380	writeMetrics(configuration, ctx.EventHandler, metricsDir)
381
382	writeUsedEnvironmentFile(configuration)
383
384	err = writeGlobFile(ctx.EventHandler, finalOutputFile, ctx.Globs(), soongStartTime)
385	maybeQuit(err, "")
386
387	// Touch the output file so that it's the newest file created by soong_build.
388	// This is necessary because, if soong_build generated any files which
389	// are ninja inputs to the main output file, then ninja would superfluously
390	// rebuild this output file on the next build invocation.
391	touch(shared.JoinPath(topDir, finalOutputFile))
392}
393
394func writeUsedEnvironmentFile(configuration android.Config) {
395	if usedEnvFile == "" {
396		return
397	}
398
399	path := shared.JoinPath(topDir, usedEnvFile)
400	data, err := shared.EnvFileContents(configuration.EnvDeps())
401	maybeQuit(err, "error writing used environment file '%s'\n", usedEnvFile)
402
403	err = pathtools.WriteFileIfChanged(path, data, 0666)
404	maybeQuit(err, "error writing used environment file '%s'", usedEnvFile)
405}
406
407func writeGlobFile(eventHandler *metrics.EventHandler, finalOutFile string, globs pathtools.MultipleGlobResults, soongStartTime time.Time) error {
408	eventHandler.Begin("writeGlobFile")
409	defer eventHandler.End("writeGlobFile")
410
411	globsFile, err := os.Create(shared.JoinPath(topDir, finalOutFile+".globs"))
412	if err != nil {
413		return err
414	}
415	defer globsFile.Close()
416	globsFileEncoder := json.NewEncoder(globsFile)
417	for _, glob := range globs {
418		if err := globsFileEncoder.Encode(glob); err != nil {
419			return err
420		}
421	}
422
423	return os.WriteFile(
424		shared.JoinPath(topDir, finalOutFile+".globs_time"),
425		[]byte(fmt.Sprintf("%d\n", soongStartTime.UnixMicro())),
426		0666,
427	)
428}
429
430func touch(path string) {
431	f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
432	maybeQuit(err, "Error touching '%s'", path)
433	err = f.Close()
434	maybeQuit(err, "Error touching '%s'", path)
435
436	currentTime := time.Now().Local()
437	err = os.Chtimes(path, currentTime, currentTime)
438	maybeQuit(err, "error touching '%s'", path)
439}
440
441func maybeQuit(err error, format string, args ...interface{}) {
442	if err == nil {
443		return
444	}
445	if format != "" {
446		fmt.Fprintln(os.Stderr, fmt.Sprintf(format, args...)+": "+err.Error())
447	} else {
448		fmt.Fprintln(os.Stderr, err)
449	}
450	os.Exit(1)
451}
452