main.go 30 KB

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