main.go 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  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. package main
  15. import (
  16. "bytes"
  17. "errors"
  18. "flag"
  19. "fmt"
  20. "os"
  21. "path/filepath"
  22. "regexp"
  23. "strings"
  24. "time"
  25. "android/soong/android"
  26. "android/soong/android/allowlists"
  27. "android/soong/bazel"
  28. "android/soong/bp2build"
  29. "android/soong/shared"
  30. "android/soong/ui/metrics/bp2build_metrics_proto"
  31. "github.com/google/blueprint"
  32. "github.com/google/blueprint/bootstrap"
  33. "github.com/google/blueprint/deptools"
  34. "github.com/google/blueprint/metrics"
  35. androidProtobuf "google.golang.org/protobuf/android"
  36. )
  37. var (
  38. topDir string
  39. availableEnvFile string
  40. usedEnvFile string
  41. globFile string
  42. globListDir string
  43. delveListen string
  44. delvePath string
  45. cmdlineArgs android.CmdArgs
  46. )
  47. func init() {
  48. // Flags that make sense in every mode
  49. flag.StringVar(&topDir, "top", "", "Top directory of the Android source tree")
  50. flag.StringVar(&cmdlineArgs.SoongOutDir, "soong_out", "", "Soong output directory (usually $TOP/out/soong)")
  51. flag.StringVar(&availableEnvFile, "available_env", "", "File containing available environment variables")
  52. flag.StringVar(&usedEnvFile, "used_env", "", "File containing used environment variables")
  53. flag.StringVar(&globFile, "globFile", "build-globs.ninja", "the Ninja file of globs to output")
  54. flag.StringVar(&globListDir, "globListDir", "", "the directory containing the glob list files")
  55. flag.StringVar(&cmdlineArgs.OutDir, "out", "", "the ninja builddir directory")
  56. flag.StringVar(&cmdlineArgs.ModuleListFile, "l", "", "file that lists filepaths to parse")
  57. // Debug flags
  58. flag.StringVar(&delveListen, "delve_listen", "", "Delve port to listen on for debugging")
  59. flag.StringVar(&delvePath, "delve_path", "", "Path to Delve. Only used if --delve_listen is set")
  60. flag.StringVar(&cmdlineArgs.Cpuprofile, "cpuprofile", "", "write cpu profile to file")
  61. flag.StringVar(&cmdlineArgs.TraceFile, "trace", "", "write trace to file")
  62. flag.StringVar(&cmdlineArgs.Memprofile, "memprofile", "", "write memory profile to file")
  63. flag.BoolVar(&cmdlineArgs.NoGC, "nogc", false, "turn off GC for debugging")
  64. // Flags representing various modes soong_build can run in
  65. flag.StringVar(&cmdlineArgs.ModuleGraphFile, "module_graph_file", "", "JSON module graph file to output")
  66. flag.StringVar(&cmdlineArgs.ModuleActionsFile, "module_actions_file", "", "JSON file to output inputs/outputs of actions of modules")
  67. flag.StringVar(&cmdlineArgs.DocFile, "soong_docs", "", "build documentation file to output")
  68. flag.StringVar(&cmdlineArgs.BazelQueryViewDir, "bazel_queryview_dir", "", "path to the bazel queryview directory relative to --top")
  69. flag.StringVar(&cmdlineArgs.BazelApiBp2buildDir, "bazel_api_bp2build_dir", "", "path to the bazel api_bp2build directory relative to --top")
  70. flag.StringVar(&cmdlineArgs.Bp2buildMarker, "bp2build_marker", "", "If set, run bp2build, touch the specified marker file then exit")
  71. flag.StringVar(&cmdlineArgs.SymlinkForestMarker, "symlink_forest_marker", "", "If set, create the bp2build symlink forest, touch the specified marker file, then exit")
  72. flag.StringVar(&cmdlineArgs.OutFile, "o", "build.ninja", "the Ninja file to output")
  73. flag.StringVar(&cmdlineArgs.SoongVariables, "soong_variables", "soong.variables", "the file contains all build variables")
  74. flag.StringVar(&cmdlineArgs.BazelForceEnabledModules, "bazel-force-enabled-modules", "", "additional modules to build with Bazel. Comma-delimited")
  75. flag.BoolVar(&cmdlineArgs.EmptyNinjaFile, "empty-ninja-file", false, "write out a 0-byte ninja file")
  76. flag.BoolVar(&cmdlineArgs.MultitreeBuild, "multitree-build", false, "this is a multitree build")
  77. flag.BoolVar(&cmdlineArgs.BazelMode, "bazel-mode", false, "use bazel for analysis of certain modules")
  78. flag.BoolVar(&cmdlineArgs.BazelModeStaging, "bazel-mode-staging", false, "use bazel for analysis of certain near-ready modules")
  79. flag.BoolVar(&cmdlineArgs.UseBazelProxy, "use-bazel-proxy", false, "communicate with bazel using unix socket proxy instead of spawning subprocesses")
  80. flag.BoolVar(&cmdlineArgs.BuildFromTextStub, "build-from-text-stub", false, "build Java stubs from API text files instead of source files")
  81. flag.BoolVar(&cmdlineArgs.EnsureAllowlistIntegrity, "ensure-allowlist-integrity", false, "verify that allowlisted modules are mixed-built")
  82. // Flags that probably shouldn't be flags of soong_build, but we haven't found
  83. // the time to remove them yet
  84. flag.BoolVar(&cmdlineArgs.RunGoTests, "t", false, "build and run go tests during bootstrap")
  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()
  90. }
  91. func newNameResolver(config android.Config) *android.NameResolver {
  92. return android.NewNameResolver(config)
  93. }
  94. func newContext(configuration android.Config) *android.Context {
  95. ctx := android.NewContext(configuration)
  96. ctx.SetNameInterface(newNameResolver(configuration))
  97. ctx.SetAllowMissingDependencies(configuration.AllowMissingDependencies())
  98. ctx.AddIncludeTags(configuration.IncludeTags()...)
  99. ctx.AddSourceRootDirs(configuration.SourceRootDirs()...)
  100. return ctx
  101. }
  102. // Bazel-enabled mode. Attaches a mutator to queue Bazel requests, adds a
  103. // BeforePrepareBuildActionsHook to invoke Bazel, and then uses Bazel metadata
  104. // for modules that should be handled by Bazel.
  105. func runMixedModeBuild(ctx *android.Context, extraNinjaDeps []string) string {
  106. ctx.EventHandler.Begin("mixed_build")
  107. defer ctx.EventHandler.End("mixed_build")
  108. bazelHook := func() error {
  109. return ctx.Config().BazelContext.InvokeBazel(ctx.Config(), ctx)
  110. }
  111. ctx.SetBeforePrepareBuildActionsHook(bazelHook)
  112. ninjaDeps, err := bootstrap.RunBlueprint(cmdlineArgs.Args, bootstrap.DoEverything, ctx.Context, ctx.Config())
  113. maybeQuit(err, "")
  114. ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
  115. bazelPaths, err := readFileLines(ctx.Config().Getenv("BAZEL_DEPS_FILE"))
  116. if err != nil {
  117. panic("Bazel deps file not found: " + err.Error())
  118. }
  119. ninjaDeps = append(ninjaDeps, bazelPaths...)
  120. ninjaDeps = append(ninjaDeps, writeBuildGlobsNinjaFile(ctx)...)
  121. writeDepFile(cmdlineArgs.OutFile, ctx.EventHandler, ninjaDeps)
  122. if needToWriteNinjaHint(ctx) {
  123. writeNinjaHint(ctx)
  124. }
  125. return cmdlineArgs.OutFile
  126. }
  127. func needToWriteNinjaHint(ctx *android.Context) bool {
  128. switch ctx.Config().GetenvWithDefault("SOONG_GENERATES_NINJA_HINT", "") {
  129. case "always":
  130. return true
  131. case "depend":
  132. if _, err := os.Stat(filepath.Join(ctx.Config().OutDir(), ".ninja_log")); errors.Is(err, os.ErrNotExist) {
  133. return true
  134. }
  135. }
  136. return false
  137. }
  138. // Run the code-generation phase to convert BazelTargetModules to BUILD files.
  139. func runQueryView(queryviewDir, queryviewMarker string, ctx *android.Context) {
  140. ctx.EventHandler.Begin("queryview")
  141. defer ctx.EventHandler.End("queryview")
  142. codegenContext := bp2build.NewCodegenContext(ctx.Config(), ctx, bp2build.QueryView, topDir)
  143. err := createBazelWorkspace(codegenContext, shared.JoinPath(topDir, queryviewDir), false)
  144. maybeQuit(err, "")
  145. touch(shared.JoinPath(topDir, queryviewMarker))
  146. }
  147. // Run the code-generation phase to convert API contributions to BUILD files.
  148. // Return marker file for the new synthetic workspace
  149. func runApiBp2build(ctx *android.Context, extraNinjaDeps []string) string {
  150. ctx.EventHandler.Begin("api_bp2build")
  151. defer ctx.EventHandler.End("api_bp2build")
  152. // api_bp2build does not run the typical pipeline of soong mutators.
  153. // Hoevever, it still runs the defaults mutator which can create dependencies.
  154. // These dependencies might not always exist (e.g. in tests)
  155. ctx.SetAllowMissingDependencies(ctx.Config().AllowMissingDependencies())
  156. ctx.RegisterForApiBazelConversion()
  157. // Register the Android.bp files in the tree
  158. // Add them to the workspace's .d file
  159. ctx.SetModuleListFile(cmdlineArgs.ModuleListFile)
  160. if paths, err := ctx.ListModulePaths("."); err == nil {
  161. extraNinjaDeps = append(extraNinjaDeps, paths...)
  162. } else {
  163. panic(err)
  164. }
  165. // Run the loading and analysis phase
  166. ninjaDeps, err := bootstrap.RunBlueprint(cmdlineArgs.Args,
  167. bootstrap.StopBeforePrepareBuildActions,
  168. ctx.Context,
  169. ctx.Config())
  170. maybeQuit(err, "")
  171. ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
  172. // Add the globbed dependencies
  173. ninjaDeps = append(ninjaDeps, writeBuildGlobsNinjaFile(ctx)...)
  174. // Run codegen to generate BUILD files
  175. codegenContext := bp2build.NewCodegenContext(ctx.Config(), ctx, bp2build.ApiBp2build, topDir)
  176. absoluteApiBp2buildDir := shared.JoinPath(topDir, cmdlineArgs.BazelApiBp2buildDir)
  177. // Always generate bp2build_all_srcs filegroups in api_bp2build.
  178. // This is necessary to force each Android.bp file to create an equivalent BUILD file
  179. // and prevent package boundray issues.
  180. // e.g.
  181. // Source
  182. // f/b/Android.bp
  183. // java_library{
  184. // name: "foo",
  185. // api: "api/current.txt",
  186. // }
  187. //
  188. // f/b/api/Android.bp <- will cause package boundary issues
  189. //
  190. // Gen
  191. // f/b/BUILD
  192. // java_contribution{
  193. // name: "foo.contribution",
  194. // api: "//f/b/api:current.txt",
  195. // }
  196. //
  197. // If we don't generate f/b/api/BUILD, foo.contribution will be unbuildable.
  198. err = createBazelWorkspace(codegenContext, absoluteApiBp2buildDir, true)
  199. maybeQuit(err, "")
  200. ninjaDeps = append(ninjaDeps, codegenContext.AdditionalNinjaDeps()...)
  201. // Create soong_injection repository
  202. soongInjectionFiles, err := bp2build.CreateSoongInjectionDirFiles(codegenContext, bp2build.CreateCodegenMetrics())
  203. maybeQuit(err, "")
  204. absoluteSoongInjectionDir := shared.JoinPath(topDir, ctx.Config().SoongOutDir(), bazel.SoongInjectionDirName)
  205. for _, file := range soongInjectionFiles {
  206. // The API targets in api_bp2build workspace do not have any dependency on api_bp2build.
  207. // But we need to create these files to prevent errors during Bazel analysis.
  208. // These need to be created in Read-Write mode.
  209. // This is because the subsequent step (bp2build in api domain analysis) creates them in Read-Write mode
  210. // to allow users to edit/experiment in the synthetic workspace.
  211. writeReadWriteFile(absoluteSoongInjectionDir, file)
  212. }
  213. workspace := shared.JoinPath(ctx.Config().SoongOutDir(), "api_bp2build")
  214. // Create the symlink forest
  215. symlinkDeps, _, _ := bp2build.PlantSymlinkForest(
  216. ctx.Config().IsEnvTrue("BP2BUILD_VERBOSE"),
  217. topDir,
  218. workspace,
  219. cmdlineArgs.BazelApiBp2buildDir,
  220. apiBuildFileExcludes(ctx))
  221. ninjaDeps = append(ninjaDeps, symlinkDeps...)
  222. workspaceMarkerFile := workspace + ".marker"
  223. writeDepFile(workspaceMarkerFile, ctx.EventHandler, ninjaDeps)
  224. touch(shared.JoinPath(topDir, workspaceMarkerFile))
  225. return workspaceMarkerFile
  226. }
  227. // With some exceptions, api_bp2build does not have any dependencies on the checked-in BUILD files
  228. // Exclude them from the generated workspace to prevent unrelated errors during the loading phase
  229. func apiBuildFileExcludes(ctx *android.Context) []string {
  230. ret := bazelArtifacts()
  231. srcs, err := getExistingBazelRelatedFiles(topDir)
  232. maybeQuit(err, "Error determining existing Bazel-related files")
  233. for _, src := range srcs {
  234. // Exclude all src BUILD files
  235. if src != "WORKSPACE" &&
  236. src != "BUILD" &&
  237. src != "BUILD.bazel" &&
  238. !strings.HasPrefix(src, "build/bazel") &&
  239. !strings.HasPrefix(src, "external/bazel-skylib") &&
  240. !strings.HasPrefix(src, "prebuilts/clang") {
  241. ret = append(ret, src)
  242. }
  243. }
  244. // Android.bp files for api surfaces are mounted to out/, but out/ should not be a
  245. // dep for api_bp2build. Otherwise, api_bp2build will be run every single time
  246. ret = append(ret, ctx.Config().OutDir())
  247. return ret
  248. }
  249. func writeNinjaHint(ctx *android.Context) error {
  250. ctx.BeginEvent("ninja_hint")
  251. defer ctx.EndEvent("ninja_hint")
  252. // The current predictor focuses on reducing false negatives.
  253. // If there are too many false positives (e.g., most modules are marked as positive),
  254. // real long-running jobs cannot run early.
  255. // Therefore, the model should be adjusted in this case.
  256. // The model should also be adjusted if there are critical false negatives.
  257. predicate := func(j *blueprint.JsonModule) (prioritized bool, weight int) {
  258. prioritized = false
  259. weight = 0
  260. for prefix, w := range allowlists.HugeModuleTypePrefixMap {
  261. if strings.HasPrefix(j.Type, prefix) {
  262. prioritized = true
  263. weight = w
  264. return
  265. }
  266. }
  267. dep_count := len(j.Deps)
  268. src_count := 0
  269. for _, a := range j.Module["Actions"].([]blueprint.JSONAction) {
  270. src_count += len(a.Inputs)
  271. }
  272. input_size := dep_count + src_count
  273. // Current threshold is an arbitrary value which only consider recall rather than accuracy.
  274. if input_size > allowlists.INPUT_SIZE_THRESHOLD {
  275. prioritized = true
  276. weight += ((input_size) / allowlists.INPUT_SIZE_THRESHOLD) * allowlists.DEFAULT_PRIORITIZED_WEIGHT
  277. // To prevent some modules from having too large a priority value.
  278. if weight > allowlists.HIGH_PRIORITIZED_WEIGHT {
  279. weight = allowlists.HIGH_PRIORITIZED_WEIGHT
  280. }
  281. }
  282. return
  283. }
  284. outputsMap := ctx.Context.GetWeightedOutputsFromPredicate(predicate)
  285. var outputBuilder strings.Builder
  286. for output, weight := range outputsMap {
  287. outputBuilder.WriteString(fmt.Sprintf("%s,%d\n", output, weight))
  288. }
  289. weightListFile := filepath.Join(topDir, ctx.Config().OutDir(), ".ninja_weight_list")
  290. err := os.WriteFile(weightListFile, []byte(outputBuilder.String()), 0644)
  291. if err != nil {
  292. return fmt.Errorf("could not write ninja weight list file %s", err)
  293. }
  294. return nil
  295. }
  296. func writeMetrics(configuration android.Config, eventHandler *metrics.EventHandler, metricsDir string) {
  297. if len(metricsDir) < 1 {
  298. fmt.Fprintf(os.Stderr, "\nMissing required env var for generating soong metrics: LOG_DIR\n")
  299. os.Exit(1)
  300. }
  301. metricsFile := filepath.Join(metricsDir, "soong_build_metrics.pb")
  302. err := android.WriteMetrics(configuration, eventHandler, metricsFile)
  303. maybeQuit(err, "error writing soong_build metrics %s", metricsFile)
  304. }
  305. // Errors out if any modules expected to be mixed_built were not, unless
  306. // the modules did not exist.
  307. func checkForAllowlistIntegrityError(configuration android.Config, isStagingMode bool) error {
  308. modules := findMisconfiguredModules(configuration, isStagingMode)
  309. if len(modules) == 0 {
  310. return nil
  311. }
  312. return fmt.Errorf("Error: expected the following modules to be mixed_built: %s", modules)
  313. }
  314. // Returns true if the given module has all of the following true:
  315. // 1. Is allowlisted to be built with Bazel.
  316. // 2. Has a variant which is *not* built with Bazel.
  317. // 3. Has no variant which is built with Bazel.
  318. //
  319. // This indicates the allowlisting of this variant had no effect.
  320. // TODO(b/280457637): Return true for nonexistent modules.
  321. func isAllowlistMisconfiguredForModule(module string, mixedBuildsEnabled map[string]struct{}, mixedBuildsDisabled map[string]struct{}) bool {
  322. _, enabled := mixedBuildsEnabled[module]
  323. if enabled {
  324. return false
  325. }
  326. _, disabled := mixedBuildsDisabled[module]
  327. return disabled
  328. }
  329. // Returns the list of modules that should have been mixed_built (per the
  330. // allowlists and cmdline flags) but were not.
  331. // Note: nonexistent modules are excluded from the list. See b/280457637
  332. func findMisconfiguredModules(configuration android.Config, isStagingMode bool) []string {
  333. retval := []string{}
  334. forceEnabledModules := configuration.BazelModulesForceEnabledByFlag()
  335. mixedBuildsEnabled := configuration.GetMixedBuildsEnabledModules()
  336. mixedBuildsDisabled := configuration.GetMixedBuildsDisabledModules()
  337. for _, module := range allowlists.ProdMixedBuildsEnabledList {
  338. if isAllowlistMisconfiguredForModule(module, mixedBuildsEnabled, mixedBuildsDisabled) {
  339. retval = append(retval, module)
  340. }
  341. }
  342. if isStagingMode {
  343. for _, module := range allowlists.StagingMixedBuildsEnabledList {
  344. if isAllowlistMisconfiguredForModule(module, mixedBuildsEnabled, mixedBuildsDisabled) {
  345. retval = append(retval, module)
  346. }
  347. }
  348. }
  349. for module, _ := range forceEnabledModules {
  350. if isAllowlistMisconfiguredForModule(module, mixedBuildsEnabled, mixedBuildsDisabled) {
  351. retval = append(retval, module)
  352. }
  353. }
  354. return retval
  355. }
  356. func writeJsonModuleGraphAndActions(ctx *android.Context, cmdArgs android.CmdArgs) {
  357. graphFile, graphErr := os.Create(shared.JoinPath(topDir, cmdArgs.ModuleGraphFile))
  358. maybeQuit(graphErr, "graph err")
  359. defer graphFile.Close()
  360. actionsFile, actionsErr := os.Create(shared.JoinPath(topDir, cmdArgs.ModuleActionsFile))
  361. maybeQuit(actionsErr, "actions err")
  362. defer actionsFile.Close()
  363. ctx.Context.PrintJSONGraphAndActions(graphFile, actionsFile)
  364. }
  365. func writeBuildGlobsNinjaFile(ctx *android.Context) []string {
  366. ctx.EventHandler.Begin("globs_ninja_file")
  367. defer ctx.EventHandler.End("globs_ninja_file")
  368. globDir := bootstrap.GlobDirectory(ctx.Config().SoongOutDir(), globListDir)
  369. err := bootstrap.WriteBuildGlobsNinjaFile(&bootstrap.GlobSingleton{
  370. GlobLister: ctx.Globs,
  371. GlobFile: globFile,
  372. GlobDir: globDir,
  373. SrcDir: ctx.SrcDir(),
  374. }, ctx.Config())
  375. maybeQuit(err, "")
  376. return bootstrap.GlobFileListFiles(globDir)
  377. }
  378. func writeDepFile(outputFile string, eventHandler *metrics.EventHandler, ninjaDeps []string) {
  379. eventHandler.Begin("ninja_deps")
  380. defer eventHandler.End("ninja_deps")
  381. depFile := shared.JoinPath(topDir, outputFile+".d")
  382. err := deptools.WriteDepFile(depFile, outputFile, ninjaDeps)
  383. maybeQuit(err, "error writing depfile '%s'", depFile)
  384. }
  385. // runSoongOnlyBuild runs the standard Soong build in a number of different modes.
  386. func runSoongOnlyBuild(ctx *android.Context, extraNinjaDeps []string) string {
  387. ctx.EventHandler.Begin("soong_build")
  388. defer ctx.EventHandler.End("soong_build")
  389. var stopBefore bootstrap.StopBefore
  390. switch ctx.Config().BuildMode {
  391. case android.GenerateModuleGraph:
  392. stopBefore = bootstrap.StopBeforeWriteNinja
  393. case android.GenerateQueryView, android.GenerateDocFile:
  394. stopBefore = bootstrap.StopBeforePrepareBuildActions
  395. default:
  396. stopBefore = bootstrap.DoEverything
  397. }
  398. ninjaDeps, err := bootstrap.RunBlueprint(cmdlineArgs.Args, stopBefore, ctx.Context, ctx.Config())
  399. maybeQuit(err, "")
  400. ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
  401. globListFiles := writeBuildGlobsNinjaFile(ctx)
  402. ninjaDeps = append(ninjaDeps, globListFiles...)
  403. // Convert the Soong module graph into Bazel BUILD files.
  404. switch ctx.Config().BuildMode {
  405. case android.GenerateQueryView:
  406. queryviewMarkerFile := cmdlineArgs.BazelQueryViewDir + ".marker"
  407. runQueryView(cmdlineArgs.BazelQueryViewDir, queryviewMarkerFile, ctx)
  408. writeDepFile(queryviewMarkerFile, ctx.EventHandler, ninjaDeps)
  409. return queryviewMarkerFile
  410. case android.GenerateModuleGraph:
  411. writeJsonModuleGraphAndActions(ctx, cmdlineArgs)
  412. writeDepFile(cmdlineArgs.ModuleGraphFile, ctx.EventHandler, ninjaDeps)
  413. return cmdlineArgs.ModuleGraphFile
  414. case android.GenerateDocFile:
  415. // TODO: we could make writeDocs() return the list of documentation files
  416. // written and add them to the .d file. Then soong_docs would be re-run
  417. // whenever one is deleted.
  418. err := writeDocs(ctx, shared.JoinPath(topDir, cmdlineArgs.DocFile))
  419. maybeQuit(err, "error building Soong documentation")
  420. writeDepFile(cmdlineArgs.DocFile, ctx.EventHandler, ninjaDeps)
  421. return cmdlineArgs.DocFile
  422. default:
  423. // The actual output (build.ninja) was written in the RunBlueprint() call
  424. // above
  425. writeDepFile(cmdlineArgs.OutFile, ctx.EventHandler, ninjaDeps)
  426. if needToWriteNinjaHint(ctx) {
  427. writeNinjaHint(ctx)
  428. }
  429. return cmdlineArgs.OutFile
  430. }
  431. }
  432. // soong_ui dumps the available environment variables to
  433. // soong.environment.available . Then soong_build itself is run with an empty
  434. // environment so that the only way environment variables can be accessed is
  435. // using Config, which tracks access to them.
  436. // At the end of the build, a file called soong.environment.used is written
  437. // containing the current value of all used environment variables. The next
  438. // time soong_ui is run, it checks whether any environment variables that was
  439. // used had changed and if so, it deletes soong.environment.used to cause a
  440. // rebuild.
  441. //
  442. // The dependency of build.ninja on soong.environment.used is declared in
  443. // build.ninja.d
  444. func parseAvailableEnv() map[string]string {
  445. if availableEnvFile == "" {
  446. fmt.Fprintf(os.Stderr, "--available_env not set\n")
  447. os.Exit(1)
  448. }
  449. result, err := shared.EnvFromFile(shared.JoinPath(topDir, availableEnvFile))
  450. maybeQuit(err, "error reading available environment file '%s'", availableEnvFile)
  451. return result
  452. }
  453. func main() {
  454. flag.Parse()
  455. shared.ReexecWithDelveMaybe(delveListen, delvePath)
  456. android.InitSandbox(topDir)
  457. availableEnv := parseAvailableEnv()
  458. configuration, err := android.NewConfig(cmdlineArgs, availableEnv)
  459. maybeQuit(err, "")
  460. if configuration.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
  461. configuration.SetAllowMissingDependencies()
  462. }
  463. extraNinjaDeps := []string{configuration.ProductVariablesFileName, usedEnvFile}
  464. if shared.IsDebugging() {
  465. // Add a non-existent file to the dependencies so that soong_build will rerun when the debugger is
  466. // enabled even if it completed successfully.
  467. extraNinjaDeps = append(extraNinjaDeps, filepath.Join(configuration.SoongOutDir(), "always_rerun_for_delve"))
  468. }
  469. // Bypass configuration.Getenv, as LOG_DIR does not need to be dependency tracked. By definition, it will
  470. // change between every CI build, so tracking it would require re-running Soong for every build.
  471. metricsDir := availableEnv["LOG_DIR"]
  472. ctx := newContext(configuration)
  473. var finalOutputFile string
  474. // Run Soong for a specific activity, like bp2build, queryview
  475. // or the actual Soong build for the build.ninja file.
  476. switch configuration.BuildMode {
  477. case android.SymlinkForest:
  478. finalOutputFile = runSymlinkForestCreation(ctx, extraNinjaDeps, metricsDir)
  479. case android.Bp2build:
  480. // Run the alternate pipeline of bp2build mutators and singleton to convert
  481. // Blueprint to BUILD files before everything else.
  482. finalOutputFile = runBp2Build(ctx, extraNinjaDeps, metricsDir)
  483. case android.ApiBp2build:
  484. finalOutputFile = runApiBp2build(ctx, extraNinjaDeps)
  485. writeMetrics(configuration, ctx.EventHandler, metricsDir)
  486. default:
  487. ctx.Register()
  488. isMixedBuildsEnabled := configuration.IsMixedBuildsEnabled()
  489. if isMixedBuildsEnabled {
  490. finalOutputFile = runMixedModeBuild(ctx, extraNinjaDeps)
  491. if cmdlineArgs.EnsureAllowlistIntegrity {
  492. if err := checkForAllowlistIntegrityError(configuration, cmdlineArgs.BazelModeStaging); err != nil {
  493. maybeQuit(err, "")
  494. }
  495. }
  496. } else {
  497. finalOutputFile = runSoongOnlyBuild(ctx, extraNinjaDeps)
  498. }
  499. writeMetrics(configuration, ctx.EventHandler, metricsDir)
  500. }
  501. // Register this environment variablesas being an implicit dependencies of
  502. // soong_build. Changes to this environment variable will result in
  503. // retriggering soong_build.
  504. configuration.Getenv("USE_BAZEL_VERSION")
  505. writeUsedEnvironmentFile(configuration)
  506. // Touch the output file so that it's the newest file created by soong_build.
  507. // This is necessary because, if soong_build generated any files which
  508. // are ninja inputs to the main output file, then ninja would superfluously
  509. // rebuild this output file on the next build invocation.
  510. touch(shared.JoinPath(topDir, finalOutputFile))
  511. }
  512. func writeUsedEnvironmentFile(configuration android.Config) {
  513. if usedEnvFile == "" {
  514. return
  515. }
  516. path := shared.JoinPath(topDir, usedEnvFile)
  517. data, err := shared.EnvFileContents(configuration.EnvDeps())
  518. maybeQuit(err, "error writing used environment file '%s'\n", usedEnvFile)
  519. if preexistingData, err := os.ReadFile(path); err != nil {
  520. if !os.IsNotExist(err) {
  521. maybeQuit(err, "error reading used environment file '%s'", usedEnvFile)
  522. }
  523. } else if bytes.Equal(preexistingData, data) {
  524. // used environment file is unchanged
  525. return
  526. }
  527. err = os.WriteFile(path, data, 0666)
  528. maybeQuit(err, "error writing used environment file '%s'", usedEnvFile)
  529. }
  530. func touch(path string) {
  531. f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
  532. maybeQuit(err, "Error touching '%s'", path)
  533. err = f.Close()
  534. maybeQuit(err, "Error touching '%s'", path)
  535. currentTime := time.Now().Local()
  536. err = os.Chtimes(path, currentTime, currentTime)
  537. maybeQuit(err, "error touching '%s'", path)
  538. }
  539. // Read the bazel.list file that the Soong Finder already dumped earlier (hopefully)
  540. // It contains the locations of BUILD files, BUILD.bazel files, etc. in the source dir
  541. func getExistingBazelRelatedFiles(topDir string) ([]string, error) {
  542. bazelFinderFile := filepath.Join(filepath.Dir(cmdlineArgs.ModuleListFile), "bazel.list")
  543. if !filepath.IsAbs(bazelFinderFile) {
  544. // Assume this was a relative path under topDir
  545. bazelFinderFile = filepath.Join(topDir, bazelFinderFile)
  546. }
  547. return readFileLines(bazelFinderFile)
  548. }
  549. func bazelArtifacts() []string {
  550. return []string{
  551. "bazel-bin",
  552. "bazel-genfiles",
  553. "bazel-out",
  554. "bazel-testlogs",
  555. "bazel-workspace",
  556. "bazel-" + filepath.Base(topDir),
  557. }
  558. }
  559. // This could in theory easily be separated into a binary that generically
  560. // merges two directories into a symlink tree. The main obstacle is that this
  561. // function currently depends on both Bazel-specific knowledge (the existence
  562. // of bazel-* symlinks) and configuration (the set of BUILD.bazel files that
  563. // should and should not be kept)
  564. //
  565. // Ideally, bp2build would write a file that contains instructions to the
  566. // symlink tree creation binary. Then the latter would not need to depend on
  567. // the very heavy-weight machinery of soong_build .
  568. func runSymlinkForestCreation(ctx *android.Context, extraNinjaDeps []string, metricsDir string) string {
  569. var ninjaDeps []string
  570. var mkdirCount, symlinkCount uint64
  571. ctx.EventHandler.Do("symlink_forest", func() {
  572. ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
  573. verbose := ctx.Config().IsEnvTrue("BP2BUILD_VERBOSE")
  574. // PlantSymlinkForest() returns all the directories that were readdir()'ed.
  575. // Such a directory SHOULD be added to `ninjaDeps` so that a child directory
  576. // or file created/deleted under it would trigger an update of the symlink forest.
  577. generatedRoot := shared.JoinPath(ctx.Config().SoongOutDir(), "bp2build")
  578. workspaceRoot := shared.JoinPath(ctx.Config().SoongOutDir(), "workspace")
  579. var symlinkForestDeps []string
  580. ctx.EventHandler.Do("plant", func() {
  581. symlinkForestDeps, mkdirCount, symlinkCount = bp2build.PlantSymlinkForest(
  582. verbose, topDir, workspaceRoot, generatedRoot, excludedFromSymlinkForest(ctx, verbose))
  583. })
  584. ninjaDeps = append(ninjaDeps, symlinkForestDeps...)
  585. })
  586. writeDepFile(cmdlineArgs.SymlinkForestMarker, ctx.EventHandler, ninjaDeps)
  587. touch(shared.JoinPath(topDir, cmdlineArgs.SymlinkForestMarker))
  588. codegenMetrics := bp2build.ReadCodegenMetrics(metricsDir)
  589. if codegenMetrics == nil {
  590. m := bp2build.CreateCodegenMetrics()
  591. codegenMetrics = &m
  592. } else {
  593. //TODO (usta) we cannot determine if we loaded a stale file, i.e. from an unrelated prior
  594. //invocation of codegen. We should simply use a separate .pb file
  595. }
  596. codegenMetrics.SetSymlinkCount(symlinkCount)
  597. codegenMetrics.SetMkDirCount(mkdirCount)
  598. writeBp2BuildMetrics(codegenMetrics, ctx.EventHandler, metricsDir)
  599. return cmdlineArgs.SymlinkForestMarker
  600. }
  601. func excludedFromSymlinkForest(ctx *android.Context, verbose bool) []string {
  602. excluded := bazelArtifacts()
  603. if cmdlineArgs.OutDir[0] != '/' {
  604. excluded = append(excluded, cmdlineArgs.OutDir)
  605. }
  606. // Find BUILD files in the srcDir which are not in the allowlist
  607. // (android.Bp2BuildConversionAllowlist#ShouldKeepExistingBuildFileForDir)
  608. // and return their paths so they can be left out of the Bazel workspace dir (i.e. ignored)
  609. existingBazelFiles, err := getExistingBazelRelatedFiles(topDir)
  610. maybeQuit(err, "Error determining existing Bazel-related files")
  611. for _, path := range existingBazelFiles {
  612. fullPath := shared.JoinPath(topDir, path)
  613. fileInfo, err2 := os.Stat(fullPath)
  614. if err2 != nil {
  615. // Warn about error, but continue trying to check files
  616. fmt.Fprintf(os.Stderr, "WARNING: Error accessing path '%s', err: %s\n", fullPath, err2)
  617. continue
  618. }
  619. // Exclude only files named 'BUILD' or 'BUILD.bazel' and unless forcibly kept
  620. if fileInfo.IsDir() ||
  621. (fileInfo.Name() != "BUILD" && fileInfo.Name() != "BUILD.bazel") ||
  622. ctx.Config().Bp2buildPackageConfig.ShouldKeepExistingBuildFileForDir(filepath.Dir(path)) {
  623. // Don't ignore this existing build file
  624. continue
  625. }
  626. if verbose {
  627. fmt.Fprintf(os.Stderr, "Ignoring existing BUILD file: %s\n", path)
  628. }
  629. excluded = append(excluded, path)
  630. }
  631. // Temporarily exclude stuff to make `bazel build //external/...` (and `bazel build //frameworks/...`) work
  632. excluded = append(excluded,
  633. // FIXME: 'autotest_lib' is a symlink back to external/autotest, and this causes an infinite
  634. // symlink expansion error for Bazel
  635. "external/autotest/venv/autotest_lib",
  636. "external/autotest/autotest_lib",
  637. "external/autotest/client/autotest_lib/client",
  638. // FIXME: The external/google-fruit/extras/bazel_root/third_party/fruit dir is poison
  639. // It contains several symlinks back to real source dirs, and those source dirs contain
  640. // BUILD files we want to ignore
  641. "external/google-fruit/extras/bazel_root/third_party/fruit",
  642. // FIXME: 'frameworks/compile/slang' has a filegroup error due to an escaping issue
  643. "frameworks/compile/slang",
  644. )
  645. return excluded
  646. }
  647. // buildTargetsByPackage parses Bazel BUILD.bazel and BUILD files under
  648. // the workspace, and returns a map containing names of Bazel targets defined in
  649. // these BUILD files.
  650. // For example, maps "//foo/bar" to ["baz", "qux"] if `//foo/bar:{baz,qux}` exist.
  651. func buildTargetsByPackage(ctx *android.Context) map[string][]string {
  652. existingBazelFiles, err := getExistingBazelRelatedFiles(topDir)
  653. maybeQuit(err, "Error determining existing Bazel-related files")
  654. result := map[string][]string{}
  655. // Search for instances of `name = "$NAME"` (with arbitrary spacing).
  656. targetNameRegex := regexp.MustCompile(`(?m)^\s*name\s*=\s*\"([^\"]+)\"`)
  657. for _, path := range existingBazelFiles {
  658. if !ctx.Config().Bp2buildPackageConfig.ShouldKeepExistingBuildFileForDir(filepath.Dir(path)) {
  659. continue
  660. }
  661. fullPath := shared.JoinPath(topDir, path)
  662. sourceDir := filepath.Dir(path)
  663. fileInfo, err := os.Stat(fullPath)
  664. maybeQuit(err, "Error accessing Bazel file '%s'", fullPath)
  665. if !fileInfo.IsDir() &&
  666. (fileInfo.Name() == "BUILD" || fileInfo.Name() == "BUILD.bazel") {
  667. // Process this BUILD file.
  668. buildFileContent, err := os.ReadFile(fullPath)
  669. maybeQuit(err, "Error reading Bazel file '%s'", fullPath)
  670. matches := targetNameRegex.FindAllStringSubmatch(string(buildFileContent), -1)
  671. for _, match := range matches {
  672. result[sourceDir] = append(result[sourceDir], match[1])
  673. }
  674. }
  675. }
  676. return result
  677. }
  678. // Run Soong in the bp2build mode. This creates a standalone context that registers
  679. // an alternate pipeline of mutators and singletons specifically for generating
  680. // Bazel BUILD files instead of Ninja files.
  681. func runBp2Build(ctx *android.Context, extraNinjaDeps []string, metricsDir string) string {
  682. var codegenMetrics *bp2build.CodegenMetrics
  683. ctx.EventHandler.Do("bp2build", func() {
  684. ctx.EventHandler.Do("read_build", func() {
  685. ctx.Config().SetBazelBuildFileTargets(buildTargetsByPackage(ctx))
  686. })
  687. // Propagate "allow misssing dependencies" bit. This is normally set in
  688. // newContext(), but we create ctx without calling that method.
  689. ctx.SetAllowMissingDependencies(ctx.Config().AllowMissingDependencies())
  690. ctx.SetNameInterface(newNameResolver(ctx.Config()))
  691. ctx.RegisterForBazelConversion()
  692. ctx.SetModuleListFile(cmdlineArgs.ModuleListFile)
  693. // Skip cloning modules during bp2build's blueprint run. Some mutators set
  694. // bp2build-related module values which should be preserved during codegen.
  695. ctx.SkipCloneModulesAfterMutators = true
  696. var ninjaDeps []string
  697. ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
  698. // Run the loading and analysis pipeline to prepare the graph of regular
  699. // Modules parsed from Android.bp files, and the BazelTargetModules mapped
  700. // from the regular Modules.
  701. ctx.EventHandler.Do("bootstrap", func() {
  702. blueprintArgs := cmdlineArgs
  703. bootstrapDeps, err := bootstrap.RunBlueprint(blueprintArgs.Args,
  704. bootstrap.StopBeforePrepareBuildActions, ctx.Context, ctx.Config())
  705. maybeQuit(err, "")
  706. ninjaDeps = append(ninjaDeps, bootstrapDeps...)
  707. })
  708. globListFiles := writeBuildGlobsNinjaFile(ctx)
  709. ninjaDeps = append(ninjaDeps, globListFiles...)
  710. // Run the code-generation phase to convert BazelTargetModules to BUILD files
  711. // and print conversion codegenMetrics to the user.
  712. codegenContext := bp2build.NewCodegenContext(ctx.Config(), ctx, bp2build.Bp2Build, topDir)
  713. ctx.EventHandler.Do("codegen", func() {
  714. codegenMetrics = bp2build.Codegen(codegenContext)
  715. })
  716. ninjaDeps = append(ninjaDeps, codegenContext.AdditionalNinjaDeps()...)
  717. writeDepFile(cmdlineArgs.Bp2buildMarker, ctx.EventHandler, ninjaDeps)
  718. touch(shared.JoinPath(topDir, cmdlineArgs.Bp2buildMarker))
  719. })
  720. // Only report metrics when in bp2build mode. The metrics aren't relevant
  721. // for queryview, since that's a total repo-wide conversion and there's a
  722. // 1:1 mapping for each module.
  723. if ctx.Config().IsEnvTrue("BP2BUILD_VERBOSE") {
  724. codegenMetrics.Print()
  725. }
  726. writeBp2BuildMetrics(codegenMetrics, ctx.EventHandler, metricsDir)
  727. return cmdlineArgs.Bp2buildMarker
  728. }
  729. // Write Bp2Build metrics into $LOG_DIR
  730. func writeBp2BuildMetrics(codegenMetrics *bp2build.CodegenMetrics, eventHandler *metrics.EventHandler, metricsDir string) {
  731. for _, event := range eventHandler.CompletedEvents() {
  732. codegenMetrics.AddEvent(&bp2build_metrics_proto.Event{
  733. Name: event.Id,
  734. StartTime: uint64(event.Start.UnixNano()),
  735. RealTime: event.RuntimeNanoseconds(),
  736. })
  737. }
  738. if len(metricsDir) < 1 {
  739. fmt.Fprintf(os.Stderr, "\nMissing required env var for generating bp2build metrics: LOG_DIR\n")
  740. os.Exit(1)
  741. }
  742. codegenMetrics.Write(metricsDir)
  743. }
  744. func readFileLines(path string) ([]string, error) {
  745. data, err := os.ReadFile(path)
  746. if err == nil {
  747. return strings.Split(strings.TrimSpace(string(data)), "\n"), nil
  748. }
  749. return nil, err
  750. }
  751. func maybeQuit(err error, format string, args ...interface{}) {
  752. if err == nil {
  753. return
  754. }
  755. if format != "" {
  756. fmt.Fprintln(os.Stderr, fmt.Sprintf(format, args...)+": "+err.Error())
  757. } else {
  758. fmt.Fprintln(os.Stderr, err)
  759. }
  760. os.Exit(1)
  761. }