soong.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  1. // Copyright 2017 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 build
  15. import (
  16. "fmt"
  17. "os"
  18. "path/filepath"
  19. "strconv"
  20. "strings"
  21. "android/soong/bazel"
  22. "android/soong/ui/metrics"
  23. "android/soong/ui/status"
  24. "android/soong/shared"
  25. "github.com/google/blueprint"
  26. "github.com/google/blueprint/bootstrap"
  27. "github.com/google/blueprint/microfactory"
  28. )
  29. const (
  30. availableEnvFile = "soong.environment.available"
  31. usedEnvFile = "soong.environment.used"
  32. soongBuildTag = "build"
  33. bp2buildFilesTag = "bp2build_files"
  34. bp2buildWorkspaceTag = "bp2build_workspace"
  35. jsonModuleGraphTag = "modulegraph"
  36. queryviewTag = "queryview"
  37. apiBp2buildTag = "api_bp2build"
  38. soongDocsTag = "soong_docs"
  39. // bootstrapEpoch is used to determine if an incremental build is incompatible with the current
  40. // version of bootstrap and needs cleaning before continuing the build. Increment this for
  41. // incompatible changes, for example when moving the location of the bpglob binary that is
  42. // executed during bootstrap before the primary builder has had a chance to update the path.
  43. bootstrapEpoch = 1
  44. )
  45. func writeEnvironmentFile(_ Context, envFile string, envDeps map[string]string) error {
  46. data, err := shared.EnvFileContents(envDeps)
  47. if err != nil {
  48. return err
  49. }
  50. return os.WriteFile(envFile, data, 0644)
  51. }
  52. // This uses Android.bp files and various tools to generate <builddir>/build.ninja.
  53. //
  54. // However, the execution of <builddir>/build.ninja happens later in
  55. // build/soong/ui/build/build.go#Build()
  56. //
  57. // We want to rely on as few prebuilts as possible, so we need to bootstrap
  58. // Soong. The process is as follows:
  59. //
  60. // 1. We use "Microfactory", a simple tool to compile Go code, to build
  61. // first itself, then soong_ui from soong_ui.bash. This binary contains
  62. // parts of soong_build that are needed to build itself.
  63. // 2. This simplified version of soong_build then reads the Blueprint files
  64. // that describe itself and emits .bootstrap/build.ninja that describes
  65. // how to build its full version and use that to produce the final Ninja
  66. // file Soong emits.
  67. // 3. soong_ui executes .bootstrap/build.ninja
  68. //
  69. // (After this, Kati is executed to parse the Makefiles, but that's not part of
  70. // bootstrapping Soong)
  71. // A tiny struct used to tell Blueprint that it's in bootstrap mode. It would
  72. // probably be nicer to use a flag in bootstrap.Args instead.
  73. type BlueprintConfig struct {
  74. toolDir string
  75. soongOutDir string
  76. outDir string
  77. runGoTests bool
  78. debugCompilation bool
  79. subninjas []string
  80. primaryBuilderInvocations []bootstrap.PrimaryBuilderInvocation
  81. }
  82. func (c BlueprintConfig) HostToolDir() string {
  83. return c.toolDir
  84. }
  85. func (c BlueprintConfig) SoongOutDir() string {
  86. return c.soongOutDir
  87. }
  88. func (c BlueprintConfig) OutDir() string {
  89. return c.outDir
  90. }
  91. func (c BlueprintConfig) RunGoTests() bool {
  92. return c.runGoTests
  93. }
  94. func (c BlueprintConfig) DebugCompilation() bool {
  95. return c.debugCompilation
  96. }
  97. func (c BlueprintConfig) Subninjas() []string {
  98. return c.subninjas
  99. }
  100. func (c BlueprintConfig) PrimaryBuilderInvocations() []bootstrap.PrimaryBuilderInvocation {
  101. return c.primaryBuilderInvocations
  102. }
  103. func environmentArgs(config Config, tag string) []string {
  104. return []string{
  105. "--available_env", shared.JoinPath(config.SoongOutDir(), availableEnvFile),
  106. "--used_env", config.UsedEnvFile(tag),
  107. }
  108. }
  109. func writeEmptyFile(ctx Context, path string) {
  110. err := os.MkdirAll(filepath.Dir(path), 0777)
  111. if err != nil {
  112. ctx.Fatalf("Failed to create parent directories of empty file '%s': %s", path, err)
  113. }
  114. if exists, err := fileExists(path); err != nil {
  115. ctx.Fatalf("Failed to check if file '%s' exists: %s", path, err)
  116. } else if !exists {
  117. err = os.WriteFile(path, nil, 0666)
  118. if err != nil {
  119. ctx.Fatalf("Failed to create empty file '%s': %s", path, err)
  120. }
  121. }
  122. }
  123. func fileExists(path string) (bool, error) {
  124. if _, err := os.Stat(path); os.IsNotExist(err) {
  125. return false, nil
  126. } else if err != nil {
  127. return false, err
  128. }
  129. return true, nil
  130. }
  131. type PrimaryBuilderFactory struct {
  132. name string
  133. description string
  134. config Config
  135. output string
  136. specificArgs []string
  137. debugPort string
  138. }
  139. func (pb PrimaryBuilderFactory) primaryBuilderInvocation() bootstrap.PrimaryBuilderInvocation {
  140. commonArgs := make([]string, 0, 0)
  141. if !pb.config.skipSoongTests {
  142. commonArgs = append(commonArgs, "-t")
  143. }
  144. if pb.config.multitreeBuild {
  145. commonArgs = append(commonArgs, "--multitree-build")
  146. }
  147. if pb.config.buildFromTextStub {
  148. commonArgs = append(commonArgs, "--build-from-text-stub")
  149. }
  150. commonArgs = append(commonArgs, "-l", filepath.Join(pb.config.FileListDir(), "Android.bp.list"))
  151. invocationEnv := make(map[string]string)
  152. if pb.debugPort != "" {
  153. //debug mode
  154. commonArgs = append(commonArgs, "--delve_listen", pb.debugPort,
  155. "--delve_path", shared.ResolveDelveBinary())
  156. // GODEBUG=asyncpreemptoff=1 disables the preemption of goroutines. This
  157. // is useful because the preemption happens by sending SIGURG to the OS
  158. // thread hosting the goroutine in question and each signal results in
  159. // work that needs to be done by Delve; it uses ptrace to debug the Go
  160. // process and the tracer process must deal with every signal (it is not
  161. // possible to selectively ignore SIGURG). This makes debugging slower,
  162. // sometimes by an order of magnitude depending on luck.
  163. // The original reason for adding async preemption to Go is here:
  164. // https://github.com/golang/proposal/blob/master/design/24543-non-cooperative-preemption.md
  165. invocationEnv["GODEBUG"] = "asyncpreemptoff=1"
  166. }
  167. var allArgs []string
  168. allArgs = append(allArgs, pb.specificArgs...)
  169. allArgs = append(allArgs,
  170. "--globListDir", pb.name,
  171. "--globFile", pb.config.NamedGlobFile(pb.name))
  172. allArgs = append(allArgs, commonArgs...)
  173. allArgs = append(allArgs, environmentArgs(pb.config, pb.name)...)
  174. if profileCpu := os.Getenv("SOONG_PROFILE_CPU"); profileCpu != "" {
  175. allArgs = append(allArgs, "--cpuprofile", profileCpu+"."+pb.name)
  176. }
  177. if profileMem := os.Getenv("SOONG_PROFILE_MEM"); profileMem != "" {
  178. allArgs = append(allArgs, "--memprofile", profileMem+"."+pb.name)
  179. }
  180. allArgs = append(allArgs, "Android.bp")
  181. return bootstrap.PrimaryBuilderInvocation{
  182. Inputs: []string{"Android.bp"},
  183. Outputs: []string{pb.output},
  184. Args: allArgs,
  185. Description: pb.description,
  186. // NB: Changing the value of this environment variable will not result in a
  187. // rebuild. The bootstrap Ninja file will change, but apparently Ninja does
  188. // not consider changing the pool specified in a statement a change that's
  189. // worth rebuilding for.
  190. Console: os.Getenv("SOONG_UNBUFFERED_OUTPUT") == "1",
  191. Env: invocationEnv,
  192. }
  193. }
  194. // bootstrapEpochCleanup deletes files used by bootstrap during incremental builds across
  195. // incompatible changes. Incompatible changes are marked by incrementing the bootstrapEpoch
  196. // constant. A tree is considered out of date for the current epoch of the
  197. // .soong.bootstrap.epoch.<epoch> file doesn't exist.
  198. func bootstrapEpochCleanup(ctx Context, config Config) {
  199. epochFile := fmt.Sprintf(".soong.bootstrap.epoch.%d", bootstrapEpoch)
  200. epochPath := filepath.Join(config.SoongOutDir(), epochFile)
  201. if exists, err := fileExists(epochPath); err != nil {
  202. ctx.Fatalf("failed to check if bootstrap epoch file %q exists: %q", epochPath, err)
  203. } else if !exists {
  204. // The tree is out of date for the current epoch, delete files used by bootstrap
  205. // and force the primary builder to rerun.
  206. os.Remove(filepath.Join(config.SoongOutDir(), "build.ninja"))
  207. for _, globFile := range bootstrapGlobFileList(config) {
  208. os.Remove(globFile)
  209. }
  210. // Mark the tree as up to date with the current epoch by writing the epoch marker file.
  211. writeEmptyFile(ctx, epochPath)
  212. }
  213. }
  214. func bootstrapGlobFileList(config Config) []string {
  215. return []string{
  216. config.NamedGlobFile(soongBuildTag),
  217. config.NamedGlobFile(bp2buildFilesTag),
  218. config.NamedGlobFile(jsonModuleGraphTag),
  219. config.NamedGlobFile(queryviewTag),
  220. config.NamedGlobFile(apiBp2buildTag),
  221. config.NamedGlobFile(soongDocsTag),
  222. }
  223. }
  224. func bootstrapBlueprint(ctx Context, config Config) {
  225. ctx.BeginTrace(metrics.RunSoong, "blueprint bootstrap")
  226. defer ctx.EndTrace()
  227. // Clean up some files for incremental builds across incompatible changes.
  228. bootstrapEpochCleanup(ctx, config)
  229. mainSoongBuildExtraArgs := []string{"-o", config.SoongNinjaFile()}
  230. if config.EmptyNinjaFile() {
  231. mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--empty-ninja-file")
  232. }
  233. if config.bazelProdMode {
  234. mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--bazel-mode")
  235. }
  236. if config.bazelDevMode {
  237. mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--bazel-mode-dev")
  238. }
  239. if config.bazelStagingMode {
  240. mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--bazel-mode-staging")
  241. }
  242. if config.IsPersistentBazelEnabled() {
  243. mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--use-bazel-proxy")
  244. }
  245. if len(config.bazelForceEnabledModules) > 0 {
  246. mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--bazel-force-enabled-modules="+config.bazelForceEnabledModules)
  247. }
  248. if config.MultitreeBuild() {
  249. mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--multitree-build")
  250. }
  251. if config.buildFromTextStub {
  252. mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--build-from-text-stub")
  253. }
  254. if config.ensureAllowlistIntegrity {
  255. mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--ensure-allowlist-integrity")
  256. }
  257. queryviewDir := filepath.Join(config.SoongOutDir(), "queryview")
  258. // The BUILD files will be generated in out/soong/.api_bp2build (no symlinks to src files)
  259. // The final workspace will be generated in out/soong/api_bp2build
  260. apiBp2buildDir := filepath.Join(config.SoongOutDir(), ".api_bp2build")
  261. pbfs := []PrimaryBuilderFactory{
  262. {
  263. name: soongBuildTag,
  264. description: fmt.Sprintf("analyzing Android.bp files and generating ninja file at %s", config.SoongNinjaFile()),
  265. config: config,
  266. output: config.SoongNinjaFile(),
  267. specificArgs: mainSoongBuildExtraArgs,
  268. },
  269. {
  270. name: bp2buildFilesTag,
  271. description: fmt.Sprintf("converting Android.bp files to BUILD files at %s/bp2build", config.SoongOutDir()),
  272. config: config,
  273. output: config.Bp2BuildFilesMarkerFile(),
  274. specificArgs: []string{"--bp2build_marker", config.Bp2BuildFilesMarkerFile()},
  275. },
  276. {
  277. name: bp2buildWorkspaceTag,
  278. description: "Creating Bazel symlink forest",
  279. config: config,
  280. output: config.Bp2BuildWorkspaceMarkerFile(),
  281. specificArgs: []string{"--symlink_forest_marker", config.Bp2BuildWorkspaceMarkerFile()},
  282. },
  283. {
  284. name: jsonModuleGraphTag,
  285. description: fmt.Sprintf("generating the Soong module graph at %s", config.ModuleGraphFile()),
  286. config: config,
  287. output: config.ModuleGraphFile(),
  288. specificArgs: []string{
  289. "--module_graph_file", config.ModuleGraphFile(),
  290. "--module_actions_file", config.ModuleActionsFile(),
  291. },
  292. },
  293. {
  294. name: queryviewTag,
  295. description: fmt.Sprintf("generating the Soong module graph as a Bazel workspace at %s", queryviewDir),
  296. config: config,
  297. output: config.QueryviewMarkerFile(),
  298. specificArgs: []string{"--bazel_queryview_dir", queryviewDir},
  299. },
  300. {
  301. name: apiBp2buildTag,
  302. description: fmt.Sprintf("generating BUILD files for API contributions at %s", apiBp2buildDir),
  303. config: config,
  304. output: config.ApiBp2buildMarkerFile(),
  305. specificArgs: []string{"--bazel_api_bp2build_dir", apiBp2buildDir},
  306. },
  307. {
  308. name: soongDocsTag,
  309. description: fmt.Sprintf("generating Soong docs at %s", config.SoongDocsHtml()),
  310. config: config,
  311. output: config.SoongDocsHtml(),
  312. specificArgs: []string{"--soong_docs", config.SoongDocsHtml()},
  313. },
  314. }
  315. // Figure out which invocations will be run under the debugger:
  316. // * SOONG_DELVE if set specifies listening port
  317. // * SOONG_DELVE_STEPS if set specifies specific invocations to be debugged, otherwise all are
  318. debuggedInvocations := make(map[string]bool)
  319. delvePort := os.Getenv("SOONG_DELVE")
  320. if delvePort != "" {
  321. if steps := os.Getenv("SOONG_DELVE_STEPS"); steps != "" {
  322. var validSteps []string
  323. for _, pbf := range pbfs {
  324. debuggedInvocations[pbf.name] = false
  325. validSteps = append(validSteps, pbf.name)
  326. }
  327. for _, step := range strings.Split(steps, ",") {
  328. if _, ok := debuggedInvocations[step]; ok {
  329. debuggedInvocations[step] = true
  330. } else {
  331. ctx.Fatalf("SOONG_DELVE_STEPS contains unknown soong_build step %s\n"+
  332. "Valid steps are %v", step, validSteps)
  333. }
  334. }
  335. } else {
  336. // SOONG_DELVE_STEPS is not set, run all steps in the debugger
  337. for _, pbf := range pbfs {
  338. debuggedInvocations[pbf.name] = true
  339. }
  340. }
  341. }
  342. var invocations []bootstrap.PrimaryBuilderInvocation
  343. for _, pbf := range pbfs {
  344. if debuggedInvocations[pbf.name] {
  345. pbf.debugPort = delvePort
  346. }
  347. pbi := pbf.primaryBuilderInvocation()
  348. // Some invocations require adjustment:
  349. switch pbf.name {
  350. case soongBuildTag:
  351. if config.BazelBuildEnabled() {
  352. // Mixed builds call Bazel from soong_build and they therefore need the
  353. // Bazel workspace to be available. Make that so by adding a dependency on
  354. // the bp2build marker file to the action that invokes soong_build .
  355. pbi.OrderOnlyInputs = append(pbi.OrderOnlyInputs, config.Bp2BuildWorkspaceMarkerFile())
  356. }
  357. case bp2buildWorkspaceTag:
  358. pbi.Inputs = append(pbi.Inputs,
  359. config.Bp2BuildFilesMarkerFile(),
  360. filepath.Join(config.FileListDir(), "bazel.list"))
  361. case bp2buildFilesTag:
  362. pbi.Inputs = append(pbi.Inputs, filepath.Join(config.FileListDir(), "METADATA.list"))
  363. }
  364. invocations = append(invocations, pbi)
  365. }
  366. // The glob .ninja files are subninja'd. However, they are generated during
  367. // the build itself so we write an empty file if the file does not exist yet
  368. // so that the subninja doesn't fail on clean builds
  369. for _, globFile := range bootstrapGlobFileList(config) {
  370. writeEmptyFile(ctx, globFile)
  371. }
  372. blueprintArgs := bootstrap.Args{
  373. ModuleListFile: filepath.Join(config.FileListDir(), "Android.bp.list"),
  374. OutFile: shared.JoinPath(config.SoongOutDir(), "bootstrap.ninja"),
  375. EmptyNinjaFile: false,
  376. }
  377. blueprintCtx := blueprint.NewContext()
  378. blueprintCtx.AddIncludeTags(config.GetIncludeTags()...)
  379. blueprintCtx.AddSourceRootDirs(config.GetSourceRootDirs()...)
  380. blueprintCtx.SetIgnoreUnknownModuleTypes(true)
  381. blueprintConfig := BlueprintConfig{
  382. soongOutDir: config.SoongOutDir(),
  383. toolDir: config.HostToolDir(),
  384. outDir: config.OutDir(),
  385. runGoTests: !config.skipSoongTests,
  386. // If we want to debug soong_build, we need to compile it for debugging
  387. debugCompilation: delvePort != "",
  388. subninjas: bootstrapGlobFileList(config),
  389. primaryBuilderInvocations: invocations,
  390. }
  391. // since `bootstrap.ninja` is regenerated unconditionally, we ignore the deps, i.e. little
  392. // reason to write a `bootstrap.ninja.d` file
  393. _ = bootstrap.RunBlueprint(blueprintArgs, bootstrap.DoEverything, blueprintCtx, blueprintConfig)
  394. }
  395. func checkEnvironmentFile(currentEnv *Environment, envFile string) {
  396. getenv := func(k string) string {
  397. v, _ := currentEnv.Get(k)
  398. return v
  399. }
  400. if stale, _ := shared.StaleEnvFile(envFile, getenv); stale {
  401. os.Remove(envFile)
  402. }
  403. }
  404. func runSoong(ctx Context, config Config) {
  405. ctx.BeginTrace(metrics.RunSoong, "soong")
  406. defer ctx.EndTrace()
  407. // We have two environment files: .available is the one with every variable,
  408. // .used with the ones that were actually used. The latter is used to
  409. // determine whether Soong needs to be re-run since why re-run it if only
  410. // unused variables were changed?
  411. envFile := filepath.Join(config.SoongOutDir(), availableEnvFile)
  412. // This is done unconditionally, but does not take a measurable amount of time
  413. bootstrapBlueprint(ctx, config)
  414. soongBuildEnv := config.Environment().Copy()
  415. soongBuildEnv.Set("TOP", os.Getenv("TOP"))
  416. // For Bazel mixed builds.
  417. soongBuildEnv.Set("BAZEL_PATH", "./build/bazel/bin/bazel")
  418. // Bazel's HOME var is set to an output subdirectory which doesn't exist. This
  419. // prevents Bazel from file I/O in the actual user HOME directory.
  420. soongBuildEnv.Set("BAZEL_HOME", absPath(ctx, filepath.Join(config.BazelOutDir(), "bazelhome")))
  421. soongBuildEnv.Set("BAZEL_OUTPUT_BASE", config.bazelOutputBase())
  422. soongBuildEnv.Set("BAZEL_WORKSPACE", absPath(ctx, "."))
  423. soongBuildEnv.Set("BAZEL_METRICS_DIR", config.BazelMetricsDir())
  424. soongBuildEnv.Set("LOG_DIR", config.LogsDir())
  425. soongBuildEnv.Set("BAZEL_DEPS_FILE", absPath(ctx, filepath.Join(config.BazelOutDir(), "bazel.list")))
  426. // For Soong bootstrapping tests
  427. if os.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
  428. soongBuildEnv.Set("ALLOW_MISSING_DEPENDENCIES", "true")
  429. }
  430. err := writeEnvironmentFile(ctx, envFile, soongBuildEnv.AsMap())
  431. if err != nil {
  432. ctx.Fatalf("failed to write environment file %s: %s", envFile, err)
  433. }
  434. func() {
  435. ctx.BeginTrace(metrics.RunSoong, "environment check")
  436. defer ctx.EndTrace()
  437. checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(soongBuildTag))
  438. if config.BazelBuildEnabled() || config.Bp2Build() {
  439. checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(bp2buildFilesTag))
  440. }
  441. if config.JsonModuleGraph() {
  442. checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(jsonModuleGraphTag))
  443. }
  444. if config.Queryview() {
  445. checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(queryviewTag))
  446. }
  447. if config.ApiBp2build() {
  448. checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(apiBp2buildTag))
  449. }
  450. if config.SoongDocs() {
  451. checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(soongDocsTag))
  452. }
  453. }()
  454. runMicrofactory(ctx, config, "bpglob", "github.com/google/blueprint/bootstrap/bpglob",
  455. map[string]string{"github.com/google/blueprint": "build/blueprint"})
  456. ninja := func(name, ninjaFile string, targets ...string) {
  457. ctx.BeginTrace(metrics.RunSoong, name)
  458. defer ctx.EndTrace()
  459. if config.IsPersistentBazelEnabled() {
  460. bazelProxy := bazel.NewProxyServer(ctx.Logger, config.OutDir(), filepath.Join(config.SoongOutDir(), "workspace"), config.GetBazeliskBazelVersion())
  461. bazelProxy.Start()
  462. defer bazelProxy.Close()
  463. }
  464. fifo := filepath.Join(config.OutDir(), ".ninja_fifo")
  465. nr := status.NewNinjaReader(ctx, ctx.Status.StartTool(), fifo)
  466. defer nr.Close()
  467. ninjaArgs := []string{
  468. "-d", "keepdepfile",
  469. "-d", "stats",
  470. "-o", "usesphonyoutputs=yes",
  471. "-o", "preremoveoutputs=yes",
  472. "-w", "dupbuild=err",
  473. "-w", "outputdir=err",
  474. "-w", "missingoutfile=err",
  475. "-j", strconv.Itoa(config.Parallel()),
  476. "--frontend_file", fifo,
  477. "-f", filepath.Join(config.SoongOutDir(), ninjaFile),
  478. }
  479. if extra, ok := config.Environment().Get("SOONG_UI_NINJA_ARGS"); ok {
  480. ctx.Printf(`CAUTION: arguments in $SOONG_UI_NINJA_ARGS=%q, e.g. "-n", can make soong_build FAIL or INCORRECT`, extra)
  481. ninjaArgs = append(ninjaArgs, strings.Fields(extra)...)
  482. }
  483. ninjaArgs = append(ninjaArgs, targets...)
  484. cmd := Command(ctx, config, "soong "+name,
  485. config.PrebuiltBuildTool("ninja"), ninjaArgs...)
  486. var ninjaEnv Environment
  487. // This is currently how the command line to invoke soong_build finds the
  488. // root of the source tree and the output root
  489. ninjaEnv.Set("TOP", os.Getenv("TOP"))
  490. cmd.Environment = &ninjaEnv
  491. cmd.Sandbox = soongSandbox
  492. cmd.RunAndStreamOrFatal()
  493. }
  494. targets := make([]string, 0, 0)
  495. if config.JsonModuleGraph() {
  496. targets = append(targets, config.ModuleGraphFile())
  497. }
  498. if config.Bp2Build() {
  499. targets = append(targets, config.Bp2BuildWorkspaceMarkerFile())
  500. }
  501. if config.Queryview() {
  502. targets = append(targets, config.QueryviewMarkerFile())
  503. }
  504. if config.ApiBp2build() {
  505. targets = append(targets, config.ApiBp2buildMarkerFile())
  506. }
  507. if config.SoongDocs() {
  508. targets = append(targets, config.SoongDocsHtml())
  509. }
  510. if config.SoongBuildInvocationNeeded() {
  511. // This build generates <builddir>/build.ninja, which is used later by build/soong/ui/build/build.go#Build().
  512. targets = append(targets, config.SoongNinjaFile())
  513. }
  514. ninja("bootstrap", "bootstrap.ninja", targets...)
  515. distGzipFile(ctx, config, config.SoongNinjaFile(), "soong")
  516. distFile(ctx, config, config.SoongVarsFile(), "soong")
  517. if !config.SkipKati() {
  518. distGzipFile(ctx, config, config.SoongAndroidMk(), "soong")
  519. distGzipFile(ctx, config, config.SoongMakeVarsMk(), "soong")
  520. }
  521. if config.JsonModuleGraph() {
  522. distGzipFile(ctx, config, config.ModuleGraphFile(), "soong")
  523. }
  524. }
  525. func runMicrofactory(ctx Context, config Config, name string, pkg string, mapping map[string]string) {
  526. ctx.BeginTrace(metrics.RunSoong, name)
  527. defer ctx.EndTrace()
  528. cfg := microfactory.Config{TrimPath: absPath(ctx, ".")}
  529. for pkgPrefix, pathPrefix := range mapping {
  530. cfg.Map(pkgPrefix, pathPrefix)
  531. }
  532. exePath := filepath.Join(config.SoongOutDir(), name)
  533. dir := filepath.Dir(exePath)
  534. if err := os.MkdirAll(dir, 0777); err != nil {
  535. ctx.Fatalf("cannot create %s: %s", dir, err)
  536. }
  537. if _, err := microfactory.Build(&cfg, exePath, pkg); err != nil {
  538. ctx.Fatalf("failed to build %s: %s", name, err)
  539. }
  540. }