soong.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  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. commonArgs = append(commonArgs, "-l", filepath.Join(pb.config.FileListDir(), "Android.bp.list"))
  145. invocationEnv := make(map[string]string)
  146. if pb.debugPort != "" {
  147. //debug mode
  148. commonArgs = append(commonArgs, "--delve_listen", pb.debugPort,
  149. "--delve_path", shared.ResolveDelveBinary())
  150. // GODEBUG=asyncpreemptoff=1 disables the preemption of goroutines. This
  151. // is useful because the preemption happens by sending SIGURG to the OS
  152. // thread hosting the goroutine in question and each signal results in
  153. // work that needs to be done by Delve; it uses ptrace to debug the Go
  154. // process and the tracer process must deal with every signal (it is not
  155. // possible to selectively ignore SIGURG). This makes debugging slower,
  156. // sometimes by an order of magnitude depending on luck.
  157. // The original reason for adding async preemption to Go is here:
  158. // https://github.com/golang/proposal/blob/master/design/24543-non-cooperative-preemption.md
  159. invocationEnv["GODEBUG"] = "asyncpreemptoff=1"
  160. }
  161. var allArgs []string
  162. allArgs = append(allArgs, pb.specificArgs...)
  163. allArgs = append(allArgs,
  164. "--globListDir", pb.name,
  165. "--globFile", pb.config.NamedGlobFile(pb.name))
  166. allArgs = append(allArgs, commonArgs...)
  167. allArgs = append(allArgs, environmentArgs(pb.config, pb.name)...)
  168. if profileCpu := os.Getenv("SOONG_PROFILE_CPU"); profileCpu != "" {
  169. allArgs = append(allArgs, "--cpuprofile", profileCpu+"."+pb.name)
  170. }
  171. if profileMem := os.Getenv("SOONG_PROFILE_MEM"); profileMem != "" {
  172. allArgs = append(allArgs, "--memprofile", profileMem+"."+pb.name)
  173. }
  174. allArgs = append(allArgs, "Android.bp")
  175. return bootstrap.PrimaryBuilderInvocation{
  176. Inputs: []string{"Android.bp"},
  177. Outputs: []string{pb.output},
  178. Args: allArgs,
  179. Description: pb.description,
  180. // NB: Changing the value of this environment variable will not result in a
  181. // rebuild. The bootstrap Ninja file will change, but apparently Ninja does
  182. // not consider changing the pool specified in a statement a change that's
  183. // worth rebuilding for.
  184. Console: os.Getenv("SOONG_UNBUFFERED_OUTPUT") == "1",
  185. Env: invocationEnv,
  186. }
  187. }
  188. // bootstrapEpochCleanup deletes files used by bootstrap during incremental builds across
  189. // incompatible changes. Incompatible changes are marked by incrementing the bootstrapEpoch
  190. // constant. A tree is considered out of date for the current epoch of the
  191. // .soong.bootstrap.epoch.<epoch> file doesn't exist.
  192. func bootstrapEpochCleanup(ctx Context, config Config) {
  193. epochFile := fmt.Sprintf(".soong.bootstrap.epoch.%d", bootstrapEpoch)
  194. epochPath := filepath.Join(config.SoongOutDir(), epochFile)
  195. if exists, err := fileExists(epochPath); err != nil {
  196. ctx.Fatalf("failed to check if bootstrap epoch file %q exists: %q", epochPath, err)
  197. } else if !exists {
  198. // The tree is out of date for the current epoch, delete files used by bootstrap
  199. // and force the primary builder to rerun.
  200. os.Remove(filepath.Join(config.SoongOutDir(), "build.ninja"))
  201. for _, globFile := range bootstrapGlobFileList(config) {
  202. os.Remove(globFile)
  203. }
  204. // Mark the tree as up to date with the current epoch by writing the epoch marker file.
  205. writeEmptyFile(ctx, epochPath)
  206. }
  207. }
  208. func bootstrapGlobFileList(config Config) []string {
  209. return []string{
  210. config.NamedGlobFile(soongBuildTag),
  211. config.NamedGlobFile(bp2buildFilesTag),
  212. config.NamedGlobFile(jsonModuleGraphTag),
  213. config.NamedGlobFile(queryviewTag),
  214. config.NamedGlobFile(apiBp2buildTag),
  215. config.NamedGlobFile(soongDocsTag),
  216. }
  217. }
  218. func bootstrapBlueprint(ctx Context, config Config) {
  219. ctx.BeginTrace(metrics.RunSoong, "blueprint bootstrap")
  220. defer ctx.EndTrace()
  221. // Clean up some files for incremental builds across incompatible changes.
  222. bootstrapEpochCleanup(ctx, config)
  223. mainSoongBuildExtraArgs := []string{"-o", config.SoongNinjaFile()}
  224. if config.EmptyNinjaFile() {
  225. mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--empty-ninja-file")
  226. }
  227. if config.bazelProdMode {
  228. mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--bazel-mode")
  229. }
  230. if config.bazelDevMode {
  231. mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--bazel-mode-dev")
  232. }
  233. if config.bazelStagingMode {
  234. mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--bazel-mode-staging")
  235. }
  236. if config.IsPersistentBazelEnabled() {
  237. mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--use-bazel-proxy")
  238. }
  239. if len(config.bazelForceEnabledModules) > 0 {
  240. mainSoongBuildExtraArgs = append(mainSoongBuildExtraArgs, "--bazel-force-enabled-modules="+config.bazelForceEnabledModules)
  241. }
  242. queryviewDir := filepath.Join(config.SoongOutDir(), "queryview")
  243. // The BUILD files will be generated in out/soong/.api_bp2build (no symlinks to src files)
  244. // The final workspace will be generated in out/soong/api_bp2build
  245. apiBp2buildDir := filepath.Join(config.SoongOutDir(), ".api_bp2build")
  246. pbfs := []PrimaryBuilderFactory{
  247. {
  248. name: soongBuildTag,
  249. description: fmt.Sprintf("analyzing Android.bp files and generating ninja file at %s", config.SoongNinjaFile()),
  250. config: config,
  251. output: config.SoongNinjaFile(),
  252. specificArgs: mainSoongBuildExtraArgs,
  253. },
  254. {
  255. name: bp2buildFilesTag,
  256. description: fmt.Sprintf("converting Android.bp files to BUILD files at %s/bp2build", config.SoongOutDir()),
  257. config: config,
  258. output: config.Bp2BuildFilesMarkerFile(),
  259. specificArgs: []string{"--bp2build_marker", config.Bp2BuildFilesMarkerFile()},
  260. },
  261. {
  262. name: bp2buildWorkspaceTag,
  263. description: "Creating Bazel symlink forest",
  264. config: config,
  265. output: config.Bp2BuildWorkspaceMarkerFile(),
  266. specificArgs: []string{"--symlink_forest_marker", config.Bp2BuildWorkspaceMarkerFile()},
  267. },
  268. {
  269. name: jsonModuleGraphTag,
  270. description: fmt.Sprintf("generating the Soong module graph at %s", config.ModuleGraphFile()),
  271. config: config,
  272. output: config.ModuleGraphFile(),
  273. specificArgs: []string{
  274. "--module_graph_file", config.ModuleGraphFile(),
  275. "--module_actions_file", config.ModuleActionsFile(),
  276. },
  277. },
  278. {
  279. name: queryviewTag,
  280. description: fmt.Sprintf("generating the Soong module graph as a Bazel workspace at %s", queryviewDir),
  281. config: config,
  282. output: config.QueryviewMarkerFile(),
  283. specificArgs: []string{"--bazel_queryview_dir", queryviewDir},
  284. },
  285. {
  286. name: apiBp2buildTag,
  287. description: fmt.Sprintf("generating BUILD files for API contributions at %s", apiBp2buildDir),
  288. config: config,
  289. output: config.ApiBp2buildMarkerFile(),
  290. specificArgs: []string{"--bazel_api_bp2build_dir", apiBp2buildDir},
  291. },
  292. {
  293. name: soongDocsTag,
  294. description: fmt.Sprintf("generating Soong docs at %s", config.SoongDocsHtml()),
  295. config: config,
  296. output: config.SoongDocsHtml(),
  297. specificArgs: []string{"--soong_docs", config.SoongDocsHtml()},
  298. },
  299. }
  300. // Figure out which invocations will be run under the debugger:
  301. // * SOONG_DELVE if set specifies listening port
  302. // * SOONG_DELVE_STEPS if set specifies specific invocations to be debugged, otherwise all are
  303. debuggedInvocations := make(map[string]bool)
  304. delvePort := os.Getenv("SOONG_DELVE")
  305. if delvePort != "" {
  306. if steps := os.Getenv("SOONG_DELVE_STEPS"); steps != "" {
  307. var validSteps []string
  308. for _, pbf := range pbfs {
  309. debuggedInvocations[pbf.name] = false
  310. validSteps = append(validSteps, pbf.name)
  311. }
  312. for _, step := range strings.Split(steps, ",") {
  313. if _, ok := debuggedInvocations[step]; ok {
  314. debuggedInvocations[step] = true
  315. } else {
  316. ctx.Fatalf("SOONG_DELVE_STEPS contains unknown soong_build step %s\n"+
  317. "Valid steps are %v", step, validSteps)
  318. }
  319. }
  320. } else {
  321. // SOONG_DELVE_STEPS is not set, run all steps in the debugger
  322. for _, pbf := range pbfs {
  323. debuggedInvocations[pbf.name] = true
  324. }
  325. }
  326. }
  327. var invocations []bootstrap.PrimaryBuilderInvocation
  328. for _, pbf := range pbfs {
  329. if debuggedInvocations[pbf.name] {
  330. pbf.debugPort = delvePort
  331. }
  332. pbi := pbf.primaryBuilderInvocation()
  333. // Some invocations require adjustment:
  334. switch pbf.name {
  335. case soongBuildTag:
  336. if config.BazelBuildEnabled() {
  337. // Mixed builds call Bazel from soong_build and they therefore need the
  338. // Bazel workspace to be available. Make that so by adding a dependency on
  339. // the bp2build marker file to the action that invokes soong_build .
  340. pbi.OrderOnlyInputs = append(pbi.OrderOnlyInputs, config.Bp2BuildWorkspaceMarkerFile())
  341. }
  342. case bp2buildWorkspaceTag:
  343. pbi.Inputs = append(pbi.Inputs,
  344. config.Bp2BuildFilesMarkerFile(),
  345. filepath.Join(config.FileListDir(), "bazel.list"))
  346. }
  347. invocations = append(invocations, pbi)
  348. }
  349. // The glob .ninja files are subninja'd. However, they are generated during
  350. // the build itself so we write an empty file if the file does not exist yet
  351. // so that the subninja doesn't fail on clean builds
  352. for _, globFile := range bootstrapGlobFileList(config) {
  353. writeEmptyFile(ctx, globFile)
  354. }
  355. blueprintArgs := bootstrap.Args{
  356. ModuleListFile: filepath.Join(config.FileListDir(), "Android.bp.list"),
  357. OutFile: shared.JoinPath(config.SoongOutDir(), "bootstrap.ninja"),
  358. EmptyNinjaFile: false,
  359. }
  360. blueprintCtx := blueprint.NewContext()
  361. blueprintCtx.AddIncludeTags(config.GetIncludeTags()...)
  362. blueprintCtx.SetIgnoreUnknownModuleTypes(true)
  363. blueprintConfig := BlueprintConfig{
  364. soongOutDir: config.SoongOutDir(),
  365. toolDir: config.HostToolDir(),
  366. outDir: config.OutDir(),
  367. runGoTests: !config.skipSoongTests,
  368. // If we want to debug soong_build, we need to compile it for debugging
  369. debugCompilation: delvePort != "",
  370. subninjas: bootstrapGlobFileList(config),
  371. primaryBuilderInvocations: invocations,
  372. }
  373. // since `bootstrap.ninja` is regenerated unconditionally, we ignore the deps, i.e. little
  374. // reason to write a `bootstrap.ninja.d` file
  375. _ = bootstrap.RunBlueprint(blueprintArgs, bootstrap.DoEverything, blueprintCtx, blueprintConfig)
  376. }
  377. func checkEnvironmentFile(currentEnv *Environment, envFile string) {
  378. getenv := func(k string) string {
  379. v, _ := currentEnv.Get(k)
  380. return v
  381. }
  382. if stale, _ := shared.StaleEnvFile(envFile, getenv); stale {
  383. os.Remove(envFile)
  384. }
  385. }
  386. func runSoong(ctx Context, config Config) {
  387. ctx.BeginTrace(metrics.RunSoong, "soong")
  388. defer ctx.EndTrace()
  389. // We have two environment files: .available is the one with every variable,
  390. // .used with the ones that were actually used. The latter is used to
  391. // determine whether Soong needs to be re-run since why re-run it if only
  392. // unused variables were changed?
  393. envFile := filepath.Join(config.SoongOutDir(), availableEnvFile)
  394. // This is done unconditionally, but does not take a measurable amount of time
  395. bootstrapBlueprint(ctx, config)
  396. soongBuildEnv := config.Environment().Copy()
  397. soongBuildEnv.Set("TOP", os.Getenv("TOP"))
  398. // For Bazel mixed builds.
  399. soongBuildEnv.Set("BAZEL_PATH", "./build/bazel/bin/bazel")
  400. // Bazel's HOME var is set to an output subdirectory which doesn't exist. This
  401. // prevents Bazel from file I/O in the actual user HOME directory.
  402. soongBuildEnv.Set("BAZEL_HOME", absPath(ctx, filepath.Join(config.BazelOutDir(), "bazelhome")))
  403. soongBuildEnv.Set("BAZEL_OUTPUT_BASE", config.bazelOutputBase())
  404. soongBuildEnv.Set("BAZEL_WORKSPACE", absPath(ctx, "."))
  405. soongBuildEnv.Set("BAZEL_METRICS_DIR", config.BazelMetricsDir())
  406. soongBuildEnv.Set("LOG_DIR", config.LogsDir())
  407. soongBuildEnv.Set("BAZEL_DEPS_FILE", absPath(ctx, filepath.Join(config.BazelOutDir(), "bazel.list")))
  408. // For Soong bootstrapping tests
  409. if os.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
  410. soongBuildEnv.Set("ALLOW_MISSING_DEPENDENCIES", "true")
  411. }
  412. err := writeEnvironmentFile(ctx, envFile, soongBuildEnv.AsMap())
  413. if err != nil {
  414. ctx.Fatalf("failed to write environment file %s: %s", envFile, err)
  415. }
  416. func() {
  417. ctx.BeginTrace(metrics.RunSoong, "environment check")
  418. defer ctx.EndTrace()
  419. checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(soongBuildTag))
  420. if config.BazelBuildEnabled() || config.Bp2Build() {
  421. checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(bp2buildFilesTag))
  422. }
  423. if config.JsonModuleGraph() {
  424. checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(jsonModuleGraphTag))
  425. }
  426. if config.Queryview() {
  427. checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(queryviewTag))
  428. }
  429. if config.ApiBp2build() {
  430. checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(apiBp2buildTag))
  431. }
  432. if config.SoongDocs() {
  433. checkEnvironmentFile(soongBuildEnv, config.UsedEnvFile(soongDocsTag))
  434. }
  435. }()
  436. runMicrofactory(ctx, config, "bpglob", "github.com/google/blueprint/bootstrap/bpglob",
  437. map[string]string{"github.com/google/blueprint": "build/blueprint"})
  438. ninja := func(name, ninjaFile string, targets ...string) {
  439. ctx.BeginTrace(metrics.RunSoong, name)
  440. defer ctx.EndTrace()
  441. if config.IsPersistentBazelEnabled() {
  442. bazelProxy := bazel.NewProxyServer(ctx.Logger, config.OutDir(), filepath.Join(config.SoongOutDir(), "workspace"))
  443. bazelProxy.Start()
  444. defer bazelProxy.Close()
  445. }
  446. fifo := filepath.Join(config.OutDir(), ".ninja_fifo")
  447. nr := status.NewNinjaReader(ctx, ctx.Status.StartTool(), fifo)
  448. defer nr.Close()
  449. ninjaArgs := []string{
  450. "-d", "keepdepfile",
  451. "-d", "stats",
  452. "-o", "usesphonyoutputs=yes",
  453. "-o", "preremoveoutputs=yes",
  454. "-w", "dupbuild=err",
  455. "-w", "outputdir=err",
  456. "-w", "missingoutfile=err",
  457. "-j", strconv.Itoa(config.Parallel()),
  458. "--frontend_file", fifo,
  459. "-f", filepath.Join(config.SoongOutDir(), ninjaFile),
  460. }
  461. if extra, ok := config.Environment().Get("SOONG_UI_NINJA_ARGS"); ok {
  462. ctx.Printf(`CAUTION: arguments in $SOONG_UI_NINJA_ARGS=%q, e.g. "-n", can make soong_build FAIL or INCORRECT`, extra)
  463. ninjaArgs = append(ninjaArgs, strings.Fields(extra)...)
  464. }
  465. ninjaArgs = append(ninjaArgs, targets...)
  466. cmd := Command(ctx, config, "soong "+name,
  467. config.PrebuiltBuildTool("ninja"), ninjaArgs...)
  468. var ninjaEnv Environment
  469. // This is currently how the command line to invoke soong_build finds the
  470. // root of the source tree and the output root
  471. ninjaEnv.Set("TOP", os.Getenv("TOP"))
  472. cmd.Environment = &ninjaEnv
  473. cmd.Sandbox = soongSandbox
  474. cmd.RunAndStreamOrFatal()
  475. }
  476. targets := make([]string, 0, 0)
  477. if config.JsonModuleGraph() {
  478. targets = append(targets, config.ModuleGraphFile())
  479. }
  480. if config.Bp2Build() {
  481. targets = append(targets, config.Bp2BuildWorkspaceMarkerFile())
  482. }
  483. if config.Queryview() {
  484. targets = append(targets, config.QueryviewMarkerFile())
  485. }
  486. if config.ApiBp2build() {
  487. targets = append(targets, config.ApiBp2buildMarkerFile())
  488. }
  489. if config.SoongDocs() {
  490. targets = append(targets, config.SoongDocsHtml())
  491. }
  492. if config.SoongBuildInvocationNeeded() {
  493. // This build generates <builddir>/build.ninja, which is used later by build/soong/ui/build/build.go#Build().
  494. targets = append(targets, config.SoongNinjaFile())
  495. }
  496. ninja("bootstrap", "bootstrap.ninja", targets...)
  497. distGzipFile(ctx, config, config.SoongNinjaFile(), "soong")
  498. distFile(ctx, config, config.SoongVarsFile(), "soong")
  499. if !config.SkipKati() {
  500. distGzipFile(ctx, config, config.SoongAndroidMk(), "soong")
  501. distGzipFile(ctx, config, config.SoongMakeVarsMk(), "soong")
  502. }
  503. if config.JsonModuleGraph() {
  504. distGzipFile(ctx, config, config.ModuleGraphFile(), "soong")
  505. }
  506. }
  507. func runMicrofactory(ctx Context, config Config, name string, pkg string, mapping map[string]string) {
  508. ctx.BeginTrace(metrics.RunSoong, name)
  509. defer ctx.EndTrace()
  510. cfg := microfactory.Config{TrimPath: absPath(ctx, ".")}
  511. for pkgPrefix, pathPrefix := range mapping {
  512. cfg.Map(pkgPrefix, pathPrefix)
  513. }
  514. exePath := filepath.Join(config.SoongOutDir(), name)
  515. dir := filepath.Dir(exePath)
  516. if err := os.MkdirAll(dir, 0777); err != nil {
  517. ctx.Fatalf("cannot create %s: %s", dir, err)
  518. }
  519. if _, err := microfactory.Build(&cfg, exePath, pkg); err != nil {
  520. ctx.Fatalf("failed to build %s: %s", name, err)
  521. }
  522. }