genrule.go 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001
  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. // A genrule module takes a list of source files ("srcs" property), an optional
  15. // list of tools ("tools" property), and a command line ("cmd" property), to
  16. // generate output files ("out" property).
  17. package genrule
  18. import (
  19. "fmt"
  20. "io"
  21. "path/filepath"
  22. "strconv"
  23. "strings"
  24. "android/soong/bazel/cquery"
  25. "github.com/google/blueprint"
  26. "github.com/google/blueprint/bootstrap"
  27. "github.com/google/blueprint/proptools"
  28. "android/soong/android"
  29. "android/soong/bazel"
  30. )
  31. func init() {
  32. RegisterGenruleBuildComponents(android.InitRegistrationContext)
  33. }
  34. // Test fixture preparer that will register most genrule build components.
  35. //
  36. // Singletons and mutators should only be added here if they are needed for a majority of genrule
  37. // module types, otherwise they should be added under a separate preparer to allow them to be
  38. // selected only when needed to reduce test execution time.
  39. //
  40. // Module types do not have much of an overhead unless they are used so this should include as many
  41. // module types as possible. The exceptions are those module types that require mutators and/or
  42. // singletons in order to function in which case they should be kept together in a separate
  43. // preparer.
  44. var PrepareForTestWithGenRuleBuildComponents = android.GroupFixturePreparers(
  45. android.FixtureRegisterWithContext(RegisterGenruleBuildComponents),
  46. )
  47. // Prepare a fixture to use all genrule module types, mutators and singletons fully.
  48. //
  49. // This should only be used by tests that want to run with as much of the build enabled as possible.
  50. var PrepareForIntegrationTestWithGenrule = android.GroupFixturePreparers(
  51. PrepareForTestWithGenRuleBuildComponents,
  52. )
  53. func RegisterGenruleBuildComponents(ctx android.RegistrationContext) {
  54. ctx.RegisterModuleType("genrule_defaults", defaultsFactory)
  55. ctx.RegisterModuleType("gensrcs", GenSrcsFactory)
  56. ctx.RegisterModuleType("genrule", GenRuleFactory)
  57. ctx.FinalDepsMutators(func(ctx android.RegisterMutatorsContext) {
  58. ctx.BottomUp("genrule_tool_deps", toolDepsMutator).Parallel()
  59. })
  60. }
  61. var (
  62. pctx = android.NewPackageContext("android/soong/genrule")
  63. // Used by gensrcs when there is more than 1 shard to merge the outputs
  64. // of each shard into a zip file.
  65. gensrcsMerge = pctx.AndroidStaticRule("gensrcsMerge", blueprint.RuleParams{
  66. Command: "${soongZip} -o ${tmpZip} @${tmpZip}.rsp && ${zipSync} -d ${genDir} ${tmpZip}",
  67. CommandDeps: []string{"${soongZip}", "${zipSync}"},
  68. Rspfile: "${tmpZip}.rsp",
  69. RspfileContent: "${zipArgs}",
  70. }, "tmpZip", "genDir", "zipArgs")
  71. )
  72. func init() {
  73. pctx.Import("android/soong/android")
  74. pctx.HostBinToolVariable("soongZip", "soong_zip")
  75. pctx.HostBinToolVariable("zipSync", "zipsync")
  76. }
  77. type SourceFileGenerator interface {
  78. GeneratedSourceFiles() android.Paths
  79. GeneratedHeaderDirs() android.Paths
  80. GeneratedDeps() android.Paths
  81. }
  82. // Alias for android.HostToolProvider
  83. // Deprecated: use android.HostToolProvider instead.
  84. type HostToolProvider interface {
  85. android.HostToolProvider
  86. }
  87. type hostToolDependencyTag struct {
  88. blueprint.BaseDependencyTag
  89. android.LicenseAnnotationToolchainDependencyTag
  90. label string
  91. }
  92. func (t hostToolDependencyTag) AllowDisabledModuleDependency(target android.Module) bool {
  93. // Allow depending on a disabled module if it's replaced by a prebuilt
  94. // counterpart. We get the prebuilt through android.PrebuiltGetPreferred in
  95. // GenerateAndroidBuildActions.
  96. return target.IsReplacedByPrebuilt()
  97. }
  98. var _ android.AllowDisabledModuleDependency = (*hostToolDependencyTag)(nil)
  99. type generatorProperties struct {
  100. // The command to run on one or more input files. Cmd supports substitution of a few variables.
  101. //
  102. // Available variables for substitution:
  103. //
  104. // $(location): the path to the first entry in tools or tool_files.
  105. // $(location <label>): the path to the tool, tool_file, input or output with name <label>. Use $(location) if <label> refers to a rule that outputs exactly one file.
  106. // $(locations <label>): the paths to the tools, tool_files, inputs or outputs with name <label>. Use $(locations) if <label> refers to a rule that outputs two or more files.
  107. // $(in): one or more input files.
  108. // $(out): a single output file.
  109. // $(depfile): a file to which dependencies will be written, if the depfile property is set to true.
  110. // $(genDir): the sandbox directory for this tool; contains $(out).
  111. // $$: a literal $
  112. Cmd *string
  113. // Enable reading a file containing dependencies in gcc format after the command completes
  114. Depfile *bool
  115. // name of the modules (if any) that produces the host executable. Leave empty for
  116. // prebuilts or scripts that do not need a module to build them.
  117. Tools []string
  118. // Local file that is used as the tool
  119. Tool_files []string `android:"path"`
  120. // List of directories to export generated headers from
  121. Export_include_dirs []string
  122. // list of input files
  123. Srcs []string `android:"path,arch_variant"`
  124. // input files to exclude
  125. Exclude_srcs []string `android:"path,arch_variant"`
  126. }
  127. type Module struct {
  128. android.ModuleBase
  129. android.DefaultableModuleBase
  130. android.BazelModuleBase
  131. android.ApexModuleBase
  132. // For other packages to make their own genrules with extra
  133. // properties
  134. Extra interface{}
  135. // CmdModifier can be set by wrappers around genrule to modify the command, for example to
  136. // prefix environment variables to it.
  137. CmdModifier func(ctx android.ModuleContext, cmd string) string
  138. android.ImageInterface
  139. properties generatorProperties
  140. // For the different tasks that genrule and gensrc generate. genrule will
  141. // generate 1 task, and gensrc will generate 1 or more tasks based on the
  142. // number of shards the input files are sharded into.
  143. taskGenerator taskFunc
  144. rule blueprint.Rule
  145. rawCommands []string
  146. exportedIncludeDirs android.Paths
  147. outputFiles android.Paths
  148. outputDeps android.Paths
  149. subName string
  150. subDir string
  151. // Collect the module directory for IDE info in java/jdeps.go.
  152. modulePaths []string
  153. }
  154. var _ android.MixedBuildBuildable = (*Module)(nil)
  155. type taskFunc func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask
  156. type generateTask struct {
  157. in android.Paths
  158. out android.WritablePaths
  159. depFile android.WritablePath
  160. copyTo android.WritablePaths // For gensrcs to set on gensrcsMerge rule.
  161. genDir android.WritablePath
  162. extraTools android.Paths // dependencies on tools used by the generator
  163. cmd string
  164. // For gensrsc sharding.
  165. shard int
  166. shards int
  167. }
  168. func (g *Module) GeneratedSourceFiles() android.Paths {
  169. return g.outputFiles
  170. }
  171. func (g *Module) Srcs() android.Paths {
  172. return append(android.Paths{}, g.outputFiles...)
  173. }
  174. func (g *Module) GeneratedHeaderDirs() android.Paths {
  175. return g.exportedIncludeDirs
  176. }
  177. func (g *Module) GeneratedDeps() android.Paths {
  178. return g.outputDeps
  179. }
  180. func (g *Module) OutputFiles(tag string) (android.Paths, error) {
  181. if tag == "" {
  182. return append(android.Paths{}, g.outputFiles...), nil
  183. }
  184. // otherwise, tag should match one of outputs
  185. for _, outputFile := range g.outputFiles {
  186. if outputFile.Rel() == tag {
  187. return android.Paths{outputFile}, nil
  188. }
  189. }
  190. return nil, fmt.Errorf("unsupported module reference tag %q", tag)
  191. }
  192. var _ android.SourceFileProducer = (*Module)(nil)
  193. var _ android.OutputFileProducer = (*Module)(nil)
  194. func toolDepsMutator(ctx android.BottomUpMutatorContext) {
  195. if g, ok := ctx.Module().(*Module); ok {
  196. for _, tool := range g.properties.Tools {
  197. tag := hostToolDependencyTag{label: tool}
  198. if m := android.SrcIsModule(tool); m != "" {
  199. tool = m
  200. }
  201. ctx.AddFarVariationDependencies(ctx.Config().BuildOSTarget.Variations(), tag, tool)
  202. }
  203. }
  204. }
  205. func (g *Module) ProcessBazelQueryResponse(ctx android.ModuleContext) {
  206. g.generateCommonBuildActions(ctx)
  207. label := g.GetBazelLabel(ctx, g)
  208. bazelCtx := ctx.Config().BazelContext
  209. filePaths, err := bazelCtx.GetOutputFiles(label, android.GetConfigKey(ctx))
  210. if err != nil {
  211. ctx.ModuleErrorf(err.Error())
  212. return
  213. }
  214. var bazelOutputFiles android.Paths
  215. exportIncludeDirs := map[string]bool{}
  216. for _, bazelOutputFile := range filePaths {
  217. bazelOutputFiles = append(bazelOutputFiles, android.PathForBazelOutRelative(ctx, ctx.ModuleDir(), bazelOutputFile))
  218. exportIncludeDirs[filepath.Dir(bazelOutputFile)] = true
  219. }
  220. g.outputFiles = bazelOutputFiles
  221. g.outputDeps = bazelOutputFiles
  222. for includePath, _ := range exportIncludeDirs {
  223. g.exportedIncludeDirs = append(g.exportedIncludeDirs, android.PathForBazelOut(ctx, includePath))
  224. }
  225. }
  226. // generateCommonBuildActions contains build action generation logic
  227. // common to both the mixed build case and the legacy case of genrule processing.
  228. // To fully support genrule in mixed builds, the contents of this function should
  229. // approach zero; there should be no genrule action registration done directly
  230. // by Soong logic in the mixed-build case.
  231. func (g *Module) generateCommonBuildActions(ctx android.ModuleContext) {
  232. g.subName = ctx.ModuleSubDir()
  233. // Collect the module directory for IDE info in java/jdeps.go.
  234. g.modulePaths = append(g.modulePaths, ctx.ModuleDir())
  235. if len(g.properties.Export_include_dirs) > 0 {
  236. for _, dir := range g.properties.Export_include_dirs {
  237. g.exportedIncludeDirs = append(g.exportedIncludeDirs,
  238. android.PathForModuleGen(ctx, g.subDir, ctx.ModuleDir(), dir))
  239. }
  240. } else {
  241. g.exportedIncludeDirs = append(g.exportedIncludeDirs, android.PathForModuleGen(ctx, g.subDir))
  242. }
  243. locationLabels := map[string]location{}
  244. firstLabel := ""
  245. addLocationLabel := func(label string, loc location) {
  246. if firstLabel == "" {
  247. firstLabel = label
  248. }
  249. if _, exists := locationLabels[label]; !exists {
  250. locationLabels[label] = loc
  251. } else {
  252. ctx.ModuleErrorf("multiple locations for label %q: %q and %q (do you have duplicate srcs entries?)",
  253. label, locationLabels[label], loc)
  254. }
  255. }
  256. var tools android.Paths
  257. var packagedTools []android.PackagingSpec
  258. if len(g.properties.Tools) > 0 {
  259. seenTools := make(map[string]bool)
  260. ctx.VisitDirectDepsBlueprint(func(module blueprint.Module) {
  261. switch tag := ctx.OtherModuleDependencyTag(module).(type) {
  262. case hostToolDependencyTag:
  263. tool := ctx.OtherModuleName(module)
  264. if m, ok := module.(android.Module); ok {
  265. // Necessary to retrieve any prebuilt replacement for the tool, since
  266. // toolDepsMutator runs too late for the prebuilt mutators to have
  267. // replaced the dependency.
  268. module = android.PrebuiltGetPreferred(ctx, m)
  269. }
  270. switch t := module.(type) {
  271. case android.HostToolProvider:
  272. // A HostToolProvider provides the path to a tool, which will be copied
  273. // into the sandbox.
  274. if !t.(android.Module).Enabled() {
  275. if ctx.Config().AllowMissingDependencies() {
  276. ctx.AddMissingDependencies([]string{tool})
  277. } else {
  278. ctx.ModuleErrorf("depends on disabled module %q", tool)
  279. }
  280. return
  281. }
  282. path := t.HostToolPath()
  283. if !path.Valid() {
  284. ctx.ModuleErrorf("host tool %q missing output file", tool)
  285. return
  286. }
  287. if specs := t.TransitivePackagingSpecs(); specs != nil {
  288. // If the HostToolProvider has PackgingSpecs, which are definitions of the
  289. // required relative locations of the tool and its dependencies, use those
  290. // instead. They will be copied to those relative locations in the sbox
  291. // sandbox.
  292. packagedTools = append(packagedTools, specs...)
  293. // Assume that the first PackagingSpec of the module is the tool.
  294. addLocationLabel(tag.label, packagedToolLocation{specs[0]})
  295. } else {
  296. tools = append(tools, path.Path())
  297. addLocationLabel(tag.label, toolLocation{android.Paths{path.Path()}})
  298. }
  299. case bootstrap.GoBinaryTool:
  300. // A GoBinaryTool provides the install path to a tool, which will be copied.
  301. p := android.PathForGoBinary(ctx, t)
  302. tools = append(tools, p)
  303. addLocationLabel(tag.label, toolLocation{android.Paths{p}})
  304. default:
  305. ctx.ModuleErrorf("%q is not a host tool provider", tool)
  306. return
  307. }
  308. seenTools[tag.label] = true
  309. }
  310. })
  311. // If AllowMissingDependencies is enabled, the build will not have stopped when
  312. // AddFarVariationDependencies was called on a missing tool, which will result in nonsensical
  313. // "cmd: unknown location label ..." errors later. Add a placeholder file to the local label.
  314. // The command that uses this placeholder file will never be executed because the rule will be
  315. // replaced with an android.Error rule reporting the missing dependencies.
  316. if ctx.Config().AllowMissingDependencies() {
  317. for _, tool := range g.properties.Tools {
  318. if !seenTools[tool] {
  319. addLocationLabel(tool, errorLocation{"***missing tool " + tool + "***"})
  320. }
  321. }
  322. }
  323. }
  324. if ctx.Failed() {
  325. return
  326. }
  327. for _, toolFile := range g.properties.Tool_files {
  328. paths := android.PathsForModuleSrc(ctx, []string{toolFile})
  329. tools = append(tools, paths...)
  330. addLocationLabel(toolFile, toolLocation{paths})
  331. }
  332. includeDirInPaths := ctx.DeviceConfig().BuildBrokenInputDir(g.Name())
  333. var srcFiles android.Paths
  334. for _, in := range g.properties.Srcs {
  335. paths, missingDeps := android.PathsAndMissingDepsRelativeToModuleSourceDir(android.SourceInput{
  336. Context: ctx, Paths: []string{in}, ExcludePaths: g.properties.Exclude_srcs, IncludeDirs: includeDirInPaths,
  337. })
  338. if len(missingDeps) > 0 {
  339. if !ctx.Config().AllowMissingDependencies() {
  340. panic(fmt.Errorf("should never get here, the missing dependencies %q should have been reported in DepsMutator",
  341. missingDeps))
  342. }
  343. // If AllowMissingDependencies is enabled, the build will not have stopped when
  344. // the dependency was added on a missing SourceFileProducer module, which will result in nonsensical
  345. // "cmd: label ":..." has no files" errors later. Add a placeholder file to the local label.
  346. // The command that uses this placeholder file will never be executed because the rule will be
  347. // replaced with an android.Error rule reporting the missing dependencies.
  348. ctx.AddMissingDependencies(missingDeps)
  349. addLocationLabel(in, errorLocation{"***missing srcs " + in + "***"})
  350. } else {
  351. srcFiles = append(srcFiles, paths...)
  352. addLocationLabel(in, inputLocation{paths})
  353. }
  354. }
  355. var copyFrom android.Paths
  356. var outputFiles android.WritablePaths
  357. var zipArgs strings.Builder
  358. cmd := String(g.properties.Cmd)
  359. if g.CmdModifier != nil {
  360. cmd = g.CmdModifier(ctx, cmd)
  361. }
  362. // Generate tasks, either from genrule or gensrcs.
  363. for _, task := range g.taskGenerator(ctx, cmd, srcFiles) {
  364. if len(task.out) == 0 {
  365. ctx.ModuleErrorf("must have at least one output file")
  366. return
  367. }
  368. // Pick a unique path outside the task.genDir for the sbox manifest textproto,
  369. // a unique rule name, and the user-visible description.
  370. manifestName := "genrule.sbox.textproto"
  371. desc := "generate"
  372. name := "generator"
  373. if task.shards > 0 {
  374. manifestName = "genrule_" + strconv.Itoa(task.shard) + ".sbox.textproto"
  375. desc += " " + strconv.Itoa(task.shard)
  376. name += strconv.Itoa(task.shard)
  377. } else if len(task.out) == 1 {
  378. desc += " " + task.out[0].Base()
  379. }
  380. manifestPath := android.PathForModuleOut(ctx, manifestName)
  381. // Use a RuleBuilder to create a rule that runs the command inside an sbox sandbox.
  382. rule := android.NewRuleBuilder(pctx, ctx).Sbox(task.genDir, manifestPath).SandboxTools()
  383. cmd := rule.Command()
  384. for _, out := range task.out {
  385. addLocationLabel(out.Rel(), outputLocation{out})
  386. }
  387. referencedDepfile := false
  388. rawCommand, err := android.Expand(task.cmd, func(name string) (string, error) {
  389. // report the error directly without returning an error to android.Expand to catch multiple errors in a
  390. // single run
  391. reportError := func(fmt string, args ...interface{}) (string, error) {
  392. ctx.PropertyErrorf("cmd", fmt, args...)
  393. return "SOONG_ERROR", nil
  394. }
  395. switch name {
  396. case "location":
  397. if len(g.properties.Tools) == 0 && len(g.properties.Tool_files) == 0 {
  398. return reportError("at least one `tools` or `tool_files` is required if $(location) is used")
  399. }
  400. loc := locationLabels[firstLabel]
  401. paths := loc.Paths(cmd)
  402. if len(paths) == 0 {
  403. return reportError("default label %q has no files", firstLabel)
  404. } else if len(paths) > 1 {
  405. return reportError("default label %q has multiple files, use $(locations %s) to reference it",
  406. firstLabel, firstLabel)
  407. }
  408. return paths[0], nil
  409. case "in":
  410. return strings.Join(cmd.PathsForInputs(srcFiles), " "), nil
  411. case "out":
  412. var sandboxOuts []string
  413. for _, out := range task.out {
  414. sandboxOuts = append(sandboxOuts, cmd.PathForOutput(out))
  415. }
  416. return strings.Join(sandboxOuts, " "), nil
  417. case "depfile":
  418. referencedDepfile = true
  419. if !Bool(g.properties.Depfile) {
  420. return reportError("$(depfile) used without depfile property")
  421. }
  422. return "__SBOX_DEPFILE__", nil
  423. case "genDir":
  424. return cmd.PathForOutput(task.genDir), nil
  425. default:
  426. if strings.HasPrefix(name, "location ") {
  427. label := strings.TrimSpace(strings.TrimPrefix(name, "location "))
  428. if loc, ok := locationLabels[label]; ok {
  429. paths := loc.Paths(cmd)
  430. if len(paths) == 0 {
  431. return reportError("label %q has no files", label)
  432. } else if len(paths) > 1 {
  433. return reportError("label %q has multiple files, use $(locations %s) to reference it",
  434. label, label)
  435. }
  436. return paths[0], nil
  437. } else {
  438. return reportError("unknown location label %q is not in srcs, out, tools or tool_files.", label)
  439. }
  440. } else if strings.HasPrefix(name, "locations ") {
  441. label := strings.TrimSpace(strings.TrimPrefix(name, "locations "))
  442. if loc, ok := locationLabels[label]; ok {
  443. paths := loc.Paths(cmd)
  444. if len(paths) == 0 {
  445. return reportError("label %q has no files", label)
  446. }
  447. return strings.Join(paths, " "), nil
  448. } else {
  449. return reportError("unknown locations label %q is not in srcs, out, tools or tool_files.", label)
  450. }
  451. } else {
  452. return reportError("unknown variable '$(%s)'", name)
  453. }
  454. }
  455. })
  456. if err != nil {
  457. ctx.PropertyErrorf("cmd", "%s", err.Error())
  458. return
  459. }
  460. if Bool(g.properties.Depfile) && !referencedDepfile {
  461. ctx.PropertyErrorf("cmd", "specified depfile=true but did not include a reference to '${depfile}' in cmd")
  462. return
  463. }
  464. g.rawCommands = append(g.rawCommands, rawCommand)
  465. cmd.Text(rawCommand)
  466. cmd.ImplicitOutputs(task.out)
  467. cmd.Implicits(task.in)
  468. cmd.ImplicitTools(tools)
  469. cmd.ImplicitTools(task.extraTools)
  470. cmd.ImplicitPackagedTools(packagedTools)
  471. if Bool(g.properties.Depfile) {
  472. cmd.ImplicitDepFile(task.depFile)
  473. }
  474. // Create the rule to run the genrule command inside sbox.
  475. rule.Build(name, desc)
  476. if len(task.copyTo) > 0 {
  477. // If copyTo is set, multiple shards need to be copied into a single directory.
  478. // task.out contains the per-shard paths, and copyTo contains the corresponding
  479. // final path. The files need to be copied into the final directory by a
  480. // single rule so it can remove the directory before it starts to ensure no
  481. // old files remain. zipsync already does this, so build up zipArgs that
  482. // zip all the per-shard directories into a single zip.
  483. outputFiles = append(outputFiles, task.copyTo...)
  484. copyFrom = append(copyFrom, task.out.Paths()...)
  485. zipArgs.WriteString(" -C " + task.genDir.String())
  486. zipArgs.WriteString(android.JoinWithPrefix(task.out.Strings(), " -f "))
  487. } else {
  488. outputFiles = append(outputFiles, task.out...)
  489. }
  490. }
  491. if len(copyFrom) > 0 {
  492. // Create a rule that zips all the per-shard directories into a single zip and then
  493. // uses zipsync to unzip it into the final directory.
  494. ctx.Build(pctx, android.BuildParams{
  495. Rule: gensrcsMerge,
  496. Implicits: copyFrom,
  497. Outputs: outputFiles,
  498. Description: "merge shards",
  499. Args: map[string]string{
  500. "zipArgs": zipArgs.String(),
  501. "tmpZip": android.PathForModuleGen(ctx, g.subDir+".zip").String(),
  502. "genDir": android.PathForModuleGen(ctx, g.subDir).String(),
  503. },
  504. })
  505. }
  506. g.outputFiles = outputFiles.Paths()
  507. }
  508. func (g *Module) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  509. // Allowlist genrule to use depfile until we have a solution to remove it.
  510. // TODO(b/235582219): Remove allowlist for genrule
  511. if ctx.ModuleType() == "gensrcs" &&
  512. !ctx.DeviceConfig().BuildBrokenDepfile() &&
  513. Bool(g.properties.Depfile) {
  514. ctx.PropertyErrorf(
  515. "depfile",
  516. "Deprecated to ensure the module type is convertible to Bazel. "+
  517. "Try specifying the dependencies explicitly so that there is no need to use depfile. "+
  518. "If not possible, the escape hatch is to use BUILD_BROKEN_DEPFILE to bypass the error.")
  519. }
  520. g.generateCommonBuildActions(ctx)
  521. // For <= 6 outputs, just embed those directly in the users. Right now, that covers >90% of
  522. // the genrules on AOSP. That will make things simpler to look at the graph in the common
  523. // case. For larger sets of outputs, inject a phony target in between to limit ninja file
  524. // growth.
  525. if len(g.outputFiles) <= 6 {
  526. g.outputDeps = g.outputFiles
  527. } else {
  528. phonyFile := android.PathForModuleGen(ctx, "genrule-phony")
  529. ctx.Build(pctx, android.BuildParams{
  530. Rule: blueprint.Phony,
  531. Output: phonyFile,
  532. Inputs: g.outputFiles,
  533. })
  534. g.outputDeps = android.Paths{phonyFile}
  535. }
  536. }
  537. func (g *Module) QueueBazelCall(ctx android.BaseModuleContext) {
  538. bazelCtx := ctx.Config().BazelContext
  539. bazelCtx.QueueBazelRequest(g.GetBazelLabel(ctx, g), cquery.GetOutputFiles, android.GetConfigKey(ctx))
  540. }
  541. func (g *Module) IsMixedBuildSupported(ctx android.BaseModuleContext) bool {
  542. return true
  543. }
  544. // Collect information for opening IDE project files in java/jdeps.go.
  545. func (g *Module) IDEInfo(dpInfo *android.IdeInfo) {
  546. dpInfo.Srcs = append(dpInfo.Srcs, g.Srcs().Strings()...)
  547. for _, src := range g.properties.Srcs {
  548. if strings.HasPrefix(src, ":") {
  549. src = strings.Trim(src, ":")
  550. dpInfo.Deps = append(dpInfo.Deps, src)
  551. }
  552. }
  553. dpInfo.Paths = append(dpInfo.Paths, g.modulePaths...)
  554. }
  555. func (g *Module) AndroidMk() android.AndroidMkData {
  556. return android.AndroidMkData{
  557. Class: "ETC",
  558. OutputFile: android.OptionalPathForPath(g.outputFiles[0]),
  559. SubName: g.subName,
  560. Extra: []android.AndroidMkExtraFunc{
  561. func(w io.Writer, outputFile android.Path) {
  562. fmt.Fprintln(w, "LOCAL_UNINSTALLABLE_MODULE := true")
  563. },
  564. },
  565. Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
  566. android.WriteAndroidMkData(w, data)
  567. if data.SubName != "" {
  568. fmt.Fprintln(w, ".PHONY:", name)
  569. fmt.Fprintln(w, name, ":", name+g.subName)
  570. }
  571. },
  572. }
  573. }
  574. var _ android.ApexModule = (*Module)(nil)
  575. // Implements android.ApexModule
  576. func (g *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
  577. sdkVersion android.ApiLevel) error {
  578. // Because generated outputs are checked by client modules(e.g. cc_library, ...)
  579. // we can safely ignore the check here.
  580. return nil
  581. }
  582. func generatorFactory(taskGenerator taskFunc, props ...interface{}) *Module {
  583. module := &Module{
  584. taskGenerator: taskGenerator,
  585. }
  586. module.AddProperties(props...)
  587. module.AddProperties(&module.properties)
  588. module.ImageInterface = noopImageInterface{}
  589. return module
  590. }
  591. type noopImageInterface struct{}
  592. func (x noopImageInterface) ImageMutatorBegin(android.BaseModuleContext) {}
  593. func (x noopImageInterface) CoreVariantNeeded(android.BaseModuleContext) bool { return false }
  594. func (x noopImageInterface) RamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
  595. func (x noopImageInterface) VendorRamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
  596. func (x noopImageInterface) DebugRamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
  597. func (x noopImageInterface) RecoveryVariantNeeded(android.BaseModuleContext) bool { return false }
  598. func (x noopImageInterface) ExtraImageVariations(ctx android.BaseModuleContext) []string { return nil }
  599. func (x noopImageInterface) SetImageVariation(ctx android.BaseModuleContext, variation string, module android.Module) {
  600. }
  601. func NewGenSrcs() *Module {
  602. properties := &genSrcsProperties{}
  603. // finalSubDir is the name of the subdirectory that output files will be generated into.
  604. // It is used so that per-shard directories can be placed alongside it an then finally
  605. // merged into it.
  606. const finalSubDir = "gensrcs"
  607. taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
  608. shardSize := defaultShardSize
  609. if s := properties.Shard_size; s != nil {
  610. shardSize = int(*s)
  611. }
  612. // gensrcs rules can easily hit command line limits by repeating the command for
  613. // every input file. Shard the input files into groups.
  614. shards := android.ShardPaths(srcFiles, shardSize)
  615. var generateTasks []generateTask
  616. for i, shard := range shards {
  617. var commands []string
  618. var outFiles android.WritablePaths
  619. var commandDepFiles []string
  620. var copyTo android.WritablePaths
  621. // When sharding is enabled (i.e. len(shards) > 1), the sbox rules for each
  622. // shard will be write to their own directories and then be merged together
  623. // into finalSubDir. If sharding is not enabled (i.e. len(shards) == 1),
  624. // the sbox rule will write directly to finalSubDir.
  625. genSubDir := finalSubDir
  626. if len(shards) > 1 {
  627. genSubDir = strconv.Itoa(i)
  628. }
  629. genDir := android.PathForModuleGen(ctx, genSubDir)
  630. // TODO(ccross): this RuleBuilder is a hack to be able to call
  631. // rule.Command().PathForOutput. Replace this with passing the rule into the
  632. // generator.
  633. rule := android.NewRuleBuilder(pctx, ctx).Sbox(genDir, nil).SandboxTools()
  634. for _, in := range shard {
  635. outFile := android.GenPathWithExt(ctx, finalSubDir, in, String(properties.Output_extension))
  636. // If sharding is enabled, then outFile is the path to the output file in
  637. // the shard directory, and copyTo is the path to the output file in the
  638. // final directory.
  639. if len(shards) > 1 {
  640. shardFile := android.GenPathWithExt(ctx, genSubDir, in, String(properties.Output_extension))
  641. copyTo = append(copyTo, outFile)
  642. outFile = shardFile
  643. }
  644. outFiles = append(outFiles, outFile)
  645. // pre-expand the command line to replace $in and $out with references to
  646. // a single input and output file.
  647. command, err := android.Expand(rawCommand, func(name string) (string, error) {
  648. switch name {
  649. case "in":
  650. return in.String(), nil
  651. case "out":
  652. return rule.Command().PathForOutput(outFile), nil
  653. case "depfile":
  654. // Generate a depfile for each output file. Store the list for
  655. // later in order to combine them all into a single depfile.
  656. depFile := rule.Command().PathForOutput(outFile.ReplaceExtension(ctx, "d"))
  657. commandDepFiles = append(commandDepFiles, depFile)
  658. return depFile, nil
  659. default:
  660. return "$(" + name + ")", nil
  661. }
  662. })
  663. if err != nil {
  664. ctx.PropertyErrorf("cmd", err.Error())
  665. }
  666. // escape the command in case for example it contains '#', an odd number of '"', etc
  667. command = fmt.Sprintf("bash -c %v", proptools.ShellEscape(command))
  668. commands = append(commands, command)
  669. }
  670. fullCommand := strings.Join(commands, " && ")
  671. var outputDepfile android.WritablePath
  672. var extraTools android.Paths
  673. if len(commandDepFiles) > 0 {
  674. // Each command wrote to a depfile, but ninja can only handle one
  675. // depfile per rule. Use the dep_fixer tool at the end of the
  676. // command to combine all the depfiles into a single output depfile.
  677. outputDepfile = android.PathForModuleGen(ctx, genSubDir, "gensrcs.d")
  678. depFixerTool := ctx.Config().HostToolPath(ctx, "dep_fixer")
  679. fullCommand += fmt.Sprintf(" && %s -o $(depfile) %s",
  680. rule.Command().PathForTool(depFixerTool),
  681. strings.Join(commandDepFiles, " "))
  682. extraTools = append(extraTools, depFixerTool)
  683. }
  684. generateTasks = append(generateTasks, generateTask{
  685. in: shard,
  686. out: outFiles,
  687. depFile: outputDepfile,
  688. copyTo: copyTo,
  689. genDir: genDir,
  690. cmd: fullCommand,
  691. shard: i,
  692. shards: len(shards),
  693. extraTools: extraTools,
  694. })
  695. }
  696. return generateTasks
  697. }
  698. g := generatorFactory(taskGenerator, properties)
  699. g.subDir = finalSubDir
  700. return g
  701. }
  702. func GenSrcsFactory() android.Module {
  703. m := NewGenSrcs()
  704. android.InitAndroidModule(m)
  705. android.InitBazelModule(m)
  706. return m
  707. }
  708. type genSrcsProperties struct {
  709. // extension that will be substituted for each output file
  710. Output_extension *string
  711. // maximum number of files that will be passed on a single command line.
  712. Shard_size *int64
  713. }
  714. type bazelGensrcsAttributes struct {
  715. Srcs bazel.LabelListAttribute
  716. Output_extension *string
  717. Tools bazel.LabelListAttribute
  718. Cmd string
  719. }
  720. const defaultShardSize = 50
  721. func NewGenRule() *Module {
  722. properties := &genRuleProperties{}
  723. taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
  724. outs := make(android.WritablePaths, len(properties.Out))
  725. var depFile android.WritablePath
  726. for i, out := range properties.Out {
  727. outPath := android.PathForModuleGen(ctx, out)
  728. if i == 0 {
  729. depFile = outPath.ReplaceExtension(ctx, "d")
  730. }
  731. outs[i] = outPath
  732. }
  733. return []generateTask{{
  734. in: srcFiles,
  735. out: outs,
  736. depFile: depFile,
  737. genDir: android.PathForModuleGen(ctx),
  738. cmd: rawCommand,
  739. }}
  740. }
  741. return generatorFactory(taskGenerator, properties)
  742. }
  743. func GenRuleFactory() android.Module {
  744. m := NewGenRule()
  745. android.InitAndroidModule(m)
  746. android.InitDefaultableModule(m)
  747. android.InitBazelModule(m)
  748. return m
  749. }
  750. type genRuleProperties struct {
  751. // names of the output files that will be generated
  752. Out []string `android:"arch_variant"`
  753. }
  754. type bazelGenruleAttributes struct {
  755. Srcs bazel.LabelListAttribute
  756. Outs []string
  757. Tools bazel.LabelListAttribute
  758. Cmd string
  759. }
  760. // ConvertWithBp2build converts a Soong module -> Bazel target.
  761. func (m *Module) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
  762. // Bazel only has the "tools" attribute.
  763. tools_prop := android.BazelLabelForModuleDeps(ctx, m.properties.Tools)
  764. tool_files_prop := android.BazelLabelForModuleSrc(ctx, m.properties.Tool_files)
  765. tools_prop.Append(tool_files_prop)
  766. tools := bazel.MakeLabelListAttribute(tools_prop)
  767. srcs := bazel.MakeLabelListAttribute(android.BazelLabelForModuleSrc(ctx, m.properties.Srcs))
  768. var allReplacements bazel.LabelList
  769. allReplacements.Append(tools.Value)
  770. allReplacements.Append(srcs.Value)
  771. // Replace in and out variables with $< and $@
  772. var cmd string
  773. if m.properties.Cmd != nil {
  774. if ctx.ModuleType() == "gensrcs" {
  775. cmd = strings.ReplaceAll(*m.properties.Cmd, "$(in)", "$(SRC)")
  776. cmd = strings.ReplaceAll(cmd, "$(out)", "$(OUT)")
  777. } else {
  778. cmd = strings.Replace(*m.properties.Cmd, "$(in)", "$(SRCS)", -1)
  779. cmd = strings.Replace(cmd, "$(out)", "$(OUTS)", -1)
  780. }
  781. genDir := "$(GENDIR)"
  782. if t := ctx.ModuleType(); t == "cc_genrule" || t == "java_genrule" || t == "java_genrule_host" {
  783. genDir = "$(RULEDIR)"
  784. }
  785. cmd = strings.Replace(cmd, "$(genDir)", genDir, -1)
  786. if len(tools.Value.Includes) > 0 {
  787. cmd = strings.Replace(cmd, "$(location)", fmt.Sprintf("$(location %s)", tools.Value.Includes[0].Label), -1)
  788. cmd = strings.Replace(cmd, "$(locations)", fmt.Sprintf("$(locations %s)", tools.Value.Includes[0].Label), -1)
  789. }
  790. for _, l := range allReplacements.Includes {
  791. bpLoc := fmt.Sprintf("$(location %s)", l.OriginalModuleName)
  792. bpLocs := fmt.Sprintf("$(locations %s)", l.OriginalModuleName)
  793. bazelLoc := fmt.Sprintf("$(location %s)", l.Label)
  794. bazelLocs := fmt.Sprintf("$(locations %s)", l.Label)
  795. cmd = strings.Replace(cmd, bpLoc, bazelLoc, -1)
  796. cmd = strings.Replace(cmd, bpLocs, bazelLocs, -1)
  797. }
  798. }
  799. if ctx.ModuleType() == "gensrcs" {
  800. // The Output_extension prop is not in an immediately accessible field
  801. // in the Module struct, so use GetProperties and cast it
  802. // to the known struct prop.
  803. var outputExtension *string
  804. for _, propIntf := range m.GetProperties() {
  805. if props, ok := propIntf.(*genSrcsProperties); ok {
  806. outputExtension = props.Output_extension
  807. break
  808. }
  809. }
  810. props := bazel.BazelTargetModuleProperties{
  811. Rule_class: "gensrcs",
  812. Bzl_load_location: "//build/bazel/rules:gensrcs.bzl",
  813. }
  814. attrs := &bazelGensrcsAttributes{
  815. Srcs: srcs,
  816. Output_extension: outputExtension,
  817. Cmd: cmd,
  818. Tools: tools,
  819. }
  820. ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: m.Name()}, attrs)
  821. } else {
  822. // The Out prop is not in an immediately accessible field
  823. // in the Module struct, so use GetProperties and cast it
  824. // to the known struct prop.
  825. var outs []string
  826. for _, propIntf := range m.GetProperties() {
  827. if props, ok := propIntf.(*genRuleProperties); ok {
  828. outs = props.Out
  829. break
  830. }
  831. }
  832. attrs := &bazelGenruleAttributes{
  833. Srcs: srcs,
  834. Outs: outs,
  835. Cmd: cmd,
  836. Tools: tools,
  837. }
  838. props := bazel.BazelTargetModuleProperties{
  839. Rule_class: "genrule",
  840. }
  841. ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: m.Name()}, attrs)
  842. }
  843. }
  844. var Bool = proptools.Bool
  845. var String = proptools.String
  846. // Defaults
  847. type Defaults struct {
  848. android.ModuleBase
  849. android.DefaultsModuleBase
  850. }
  851. func defaultsFactory() android.Module {
  852. return DefaultsFactory()
  853. }
  854. func DefaultsFactory(props ...interface{}) android.Module {
  855. module := &Defaults{}
  856. module.AddProperties(props...)
  857. module.AddProperties(
  858. &generatorProperties{},
  859. &genRuleProperties{},
  860. )
  861. android.InitDefaultsModule(module)
  862. return module
  863. }