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