main.go 33 KB

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