filesystem.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. // Copyright (C) 2020 The Android Open Source Project
  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 filesystem
  15. import (
  16. "fmt"
  17. "path/filepath"
  18. "strings"
  19. "android/soong/android"
  20. "github.com/google/blueprint"
  21. "github.com/google/blueprint/proptools"
  22. )
  23. func init() {
  24. registerBuildComponents(android.InitRegistrationContext)
  25. }
  26. func registerBuildComponents(ctx android.RegistrationContext) {
  27. ctx.RegisterModuleType("android_filesystem", filesystemFactory)
  28. ctx.RegisterModuleType("android_system_image", systemImageFactory)
  29. }
  30. type filesystem struct {
  31. android.ModuleBase
  32. android.PackagingBase
  33. properties filesystemProperties
  34. // Function that builds extra files under the root directory and returns the files
  35. buildExtraFiles func(ctx android.ModuleContext, root android.OutputPath) android.OutputPaths
  36. // Function that filters PackagingSpecs returned by PackagingBase.GatherPackagingSpecs()
  37. filterPackagingSpecs func(specs map[string]android.PackagingSpec)
  38. output android.OutputPath
  39. installDir android.InstallPath
  40. // For testing. Keeps the result of CopyDepsToZip()
  41. entries []string
  42. }
  43. type symlinkDefinition struct {
  44. Target *string
  45. Name *string
  46. }
  47. type filesystemProperties struct {
  48. // When set to true, sign the image with avbtool. Default is false.
  49. Use_avb *bool
  50. // Path to the private key that avbtool will use to sign this filesystem image.
  51. // TODO(jiyong): allow apex_key to be specified here
  52. Avb_private_key *string `android:"path"`
  53. // Hash and signing algorithm for avbtool. Default is SHA256_RSA4096.
  54. Avb_algorithm *string
  55. // Name of the partition stored in vbmeta desc. Defaults to the name of this module.
  56. Partition_name *string
  57. // Type of the filesystem. Currently, ext4, cpio, and compressed_cpio are supported. Default
  58. // is ext4.
  59. Type *string
  60. // file_contexts file to make image. Currently, only ext4 is supported.
  61. File_contexts *string `android:"path"`
  62. // Base directory relative to root, to which deps are installed, e.g. "system". Default is "."
  63. // (root).
  64. Base_dir *string
  65. // Directories to be created under root. e.g. /dev, /proc, etc.
  66. Dirs []string
  67. // Symbolic links to be created under root with "ln -sf <target> <name>".
  68. Symlinks []symlinkDefinition
  69. }
  70. // android_filesystem packages a set of modules and their transitive dependencies into a filesystem
  71. // image. The filesystem images are expected to be mounted in the target device, which means the
  72. // modules in the filesystem image are built for the target device (i.e. Android, not Linux host).
  73. // The modules are placed in the filesystem image just like they are installed to the ordinary
  74. // partitions like system.img. For example, cc_library modules are placed under ./lib[64] directory.
  75. func filesystemFactory() android.Module {
  76. module := &filesystem{}
  77. initFilesystemModule(module)
  78. return module
  79. }
  80. func initFilesystemModule(module *filesystem) {
  81. module.AddProperties(&module.properties)
  82. android.InitPackageModule(module)
  83. android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
  84. }
  85. var dependencyTag = struct {
  86. blueprint.BaseDependencyTag
  87. android.PackagingItemAlwaysDepTag
  88. }{}
  89. func (f *filesystem) DepsMutator(ctx android.BottomUpMutatorContext) {
  90. f.AddDeps(ctx, dependencyTag)
  91. }
  92. type fsType int
  93. const (
  94. ext4Type fsType = iota
  95. compressedCpioType
  96. cpioType // uncompressed
  97. unknown
  98. )
  99. func (f *filesystem) fsType(ctx android.ModuleContext) fsType {
  100. typeStr := proptools.StringDefault(f.properties.Type, "ext4")
  101. switch typeStr {
  102. case "ext4":
  103. return ext4Type
  104. case "compressed_cpio":
  105. return compressedCpioType
  106. case "cpio":
  107. return cpioType
  108. default:
  109. ctx.PropertyErrorf("type", "%q not supported", typeStr)
  110. return unknown
  111. }
  112. }
  113. func (f *filesystem) installFileName() string {
  114. return f.BaseModuleName() + ".img"
  115. }
  116. var pctx = android.NewPackageContext("android/soong/filesystem")
  117. func (f *filesystem) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  118. switch f.fsType(ctx) {
  119. case ext4Type:
  120. f.output = f.buildImageUsingBuildImage(ctx)
  121. case compressedCpioType:
  122. f.output = f.buildCpioImage(ctx, true)
  123. case cpioType:
  124. f.output = f.buildCpioImage(ctx, false)
  125. default:
  126. return
  127. }
  128. f.installDir = android.PathForModuleInstall(ctx, "etc")
  129. ctx.InstallFile(f.installDir, f.installFileName(), f.output)
  130. }
  131. // root zip will contain extra files/dirs that are not from the `deps` property.
  132. func (f *filesystem) buildRootZip(ctx android.ModuleContext) android.OutputPath {
  133. rootDir := android.PathForModuleGen(ctx, "root").OutputPath
  134. builder := android.NewRuleBuilder(pctx, ctx)
  135. builder.Command().Text("rm -rf").Text(rootDir.String())
  136. builder.Command().Text("mkdir -p").Text(rootDir.String())
  137. // create dirs and symlinks
  138. for _, dir := range f.properties.Dirs {
  139. // OutputPath.Join verifies dir
  140. builder.Command().Text("mkdir -p").Text(rootDir.Join(ctx, dir).String())
  141. }
  142. for _, symlink := range f.properties.Symlinks {
  143. name := strings.TrimSpace(proptools.String(symlink.Name))
  144. target := strings.TrimSpace(proptools.String(symlink.Target))
  145. if name == "" {
  146. ctx.PropertyErrorf("symlinks", "Name can't be empty")
  147. continue
  148. }
  149. if target == "" {
  150. ctx.PropertyErrorf("symlinks", "Target can't be empty")
  151. continue
  152. }
  153. // OutputPath.Join verifies name. don't need to verify target.
  154. dst := rootDir.Join(ctx, name)
  155. builder.Command().Text("mkdir -p").Text(filepath.Dir(dst.String()))
  156. builder.Command().Text("ln -sf").Text(proptools.ShellEscape(target)).Text(dst.String())
  157. }
  158. // create extra files if there's any
  159. rootForExtraFiles := android.PathForModuleGen(ctx, "root-extra").OutputPath
  160. var extraFiles android.OutputPaths
  161. if f.buildExtraFiles != nil {
  162. extraFiles = f.buildExtraFiles(ctx, rootForExtraFiles)
  163. for _, f := range extraFiles {
  164. rel, _ := filepath.Rel(rootForExtraFiles.String(), f.String())
  165. if strings.HasPrefix(rel, "..") {
  166. panic(fmt.Errorf("%q is not under %q\n", f, rootForExtraFiles))
  167. }
  168. }
  169. }
  170. // Zip them all
  171. zipOut := android.PathForModuleGen(ctx, "root.zip").OutputPath
  172. zipCommand := builder.Command().BuiltTool("soong_zip")
  173. zipCommand.FlagWithOutput("-o ", zipOut).
  174. FlagWithArg("-C ", rootDir.String()).
  175. Flag("-L 0"). // no compression because this will be unzipped soon
  176. FlagWithArg("-D ", rootDir.String()).
  177. Flag("-d") // include empty directories
  178. if len(extraFiles) > 0 {
  179. zipCommand.FlagWithArg("-C ", rootForExtraFiles.String())
  180. for _, f := range extraFiles {
  181. zipCommand.FlagWithInput("-f ", f)
  182. }
  183. }
  184. builder.Command().Text("rm -rf").Text(rootDir.String())
  185. builder.Build("zip_root", fmt.Sprintf("zipping root contents for %s", ctx.ModuleName()))
  186. return zipOut
  187. }
  188. func (f *filesystem) buildImageUsingBuildImage(ctx android.ModuleContext) android.OutputPath {
  189. depsZipFile := android.PathForModuleOut(ctx, "deps.zip").OutputPath
  190. f.entries = f.CopyDepsToZip(ctx, f.gatherFilteredPackagingSpecs(ctx), depsZipFile)
  191. builder := android.NewRuleBuilder(pctx, ctx)
  192. depsBase := proptools.StringDefault(f.properties.Base_dir, ".")
  193. rebasedDepsZip := android.PathForModuleOut(ctx, "rebased_deps.zip").OutputPath
  194. builder.Command().
  195. BuiltTool("zip2zip").
  196. FlagWithInput("-i ", depsZipFile).
  197. FlagWithOutput("-o ", rebasedDepsZip).
  198. Text("**/*:" + proptools.ShellEscape(depsBase)) // zip2zip verifies depsBase
  199. rootDir := android.PathForModuleOut(ctx, "root").OutputPath
  200. rootZip := f.buildRootZip(ctx)
  201. builder.Command().
  202. BuiltTool("zipsync").
  203. FlagWithArg("-d ", rootDir.String()). // zipsync wipes this. No need to clear.
  204. Input(rootZip).
  205. Input(rebasedDepsZip)
  206. propFile, toolDeps := f.buildPropFile(ctx)
  207. output := android.PathForModuleOut(ctx, f.installFileName()).OutputPath
  208. builder.Command().BuiltTool("build_image").
  209. Text(rootDir.String()). // input directory
  210. Input(propFile).
  211. Implicits(toolDeps).
  212. Output(output).
  213. Text(rootDir.String()) // directory where to find fs_config_files|dirs
  214. // rootDir is not deleted. Might be useful for quick inspection.
  215. builder.Build("build_filesystem_image", fmt.Sprintf("Creating filesystem %s", f.BaseModuleName()))
  216. return output
  217. }
  218. func (f *filesystem) buildFileContexts(ctx android.ModuleContext) android.OutputPath {
  219. builder := android.NewRuleBuilder(pctx, ctx)
  220. fcBin := android.PathForModuleOut(ctx, "file_contexts.bin")
  221. builder.Command().BuiltTool("sefcontext_compile").
  222. FlagWithOutput("-o ", fcBin).
  223. Input(android.PathForModuleSrc(ctx, proptools.String(f.properties.File_contexts)))
  224. builder.Build("build_filesystem_file_contexts", fmt.Sprintf("Creating filesystem file contexts for %s", f.BaseModuleName()))
  225. return fcBin.OutputPath
  226. }
  227. func (f *filesystem) buildPropFile(ctx android.ModuleContext) (propFile android.OutputPath, toolDeps android.Paths) {
  228. type prop struct {
  229. name string
  230. value string
  231. }
  232. var props []prop
  233. var deps android.Paths
  234. addStr := func(name string, value string) {
  235. props = append(props, prop{name, value})
  236. }
  237. addPath := func(name string, path android.Path) {
  238. props = append(props, prop{name, path.String()})
  239. deps = append(deps, path)
  240. }
  241. // Type string that build_image.py accepts.
  242. fsTypeStr := func(t fsType) string {
  243. switch t {
  244. // TODO(jiyong): add more types like f2fs, erofs, etc.
  245. case ext4Type:
  246. return "ext4"
  247. }
  248. panic(fmt.Errorf("unsupported fs type %v", t))
  249. }
  250. addStr("fs_type", fsTypeStr(f.fsType(ctx)))
  251. addStr("mount_point", "/")
  252. addStr("use_dynamic_partition_size", "true")
  253. addPath("ext_mkuserimg", ctx.Config().HostToolPath(ctx, "mkuserimg_mke2fs"))
  254. // b/177813163 deps of the host tools have to be added. Remove this.
  255. for _, t := range []string{"mke2fs", "e2fsdroid", "tune2fs"} {
  256. deps = append(deps, ctx.Config().HostToolPath(ctx, t))
  257. }
  258. if proptools.Bool(f.properties.Use_avb) {
  259. addStr("avb_hashtree_enable", "true")
  260. addPath("avb_avbtool", ctx.Config().HostToolPath(ctx, "avbtool"))
  261. algorithm := proptools.StringDefault(f.properties.Avb_algorithm, "SHA256_RSA4096")
  262. addStr("avb_algorithm", algorithm)
  263. key := android.PathForModuleSrc(ctx, proptools.String(f.properties.Avb_private_key))
  264. addPath("avb_key_path", key)
  265. addStr("avb_add_hashtree_footer_args", "--do_not_generate_fec")
  266. partitionName := proptools.StringDefault(f.properties.Partition_name, f.Name())
  267. addStr("partition_name", partitionName)
  268. }
  269. if proptools.String(f.properties.File_contexts) != "" {
  270. addPath("selinux_fc", f.buildFileContexts(ctx))
  271. }
  272. propFile = android.PathForModuleOut(ctx, "prop").OutputPath
  273. builder := android.NewRuleBuilder(pctx, ctx)
  274. builder.Command().Text("rm").Flag("-rf").Output(propFile)
  275. for _, p := range props {
  276. builder.Command().
  277. Text("echo").
  278. Flag(`"` + p.name + "=" + p.value + `"`).
  279. Text(">>").Output(propFile)
  280. }
  281. builder.Build("build_filesystem_prop", fmt.Sprintf("Creating filesystem props for %s", f.BaseModuleName()))
  282. return propFile, deps
  283. }
  284. func (f *filesystem) buildCpioImage(ctx android.ModuleContext, compressed bool) android.OutputPath {
  285. if proptools.Bool(f.properties.Use_avb) {
  286. ctx.PropertyErrorf("use_avb", "signing compresed cpio image using avbtool is not supported."+
  287. "Consider adding this to bootimg module and signing the entire boot image.")
  288. }
  289. if proptools.String(f.properties.File_contexts) != "" {
  290. ctx.PropertyErrorf("file_contexts", "file_contexts is not supported for compressed cpio image.")
  291. }
  292. depsZipFile := android.PathForModuleOut(ctx, "deps.zip").OutputPath
  293. f.entries = f.CopyDepsToZip(ctx, f.gatherFilteredPackagingSpecs(ctx), depsZipFile)
  294. builder := android.NewRuleBuilder(pctx, ctx)
  295. depsBase := proptools.StringDefault(f.properties.Base_dir, ".")
  296. rebasedDepsZip := android.PathForModuleOut(ctx, "rebased_deps.zip").OutputPath
  297. builder.Command().
  298. BuiltTool("zip2zip").
  299. FlagWithInput("-i ", depsZipFile).
  300. FlagWithOutput("-o ", rebasedDepsZip).
  301. Text("**/*:" + proptools.ShellEscape(depsBase)) // zip2zip verifies depsBase
  302. rootDir := android.PathForModuleOut(ctx, "root").OutputPath
  303. rootZip := f.buildRootZip(ctx)
  304. builder.Command().
  305. BuiltTool("zipsync").
  306. FlagWithArg("-d ", rootDir.String()). // zipsync wipes this. No need to clear.
  307. Input(rootZip).
  308. Input(rebasedDepsZip)
  309. output := android.PathForModuleOut(ctx, f.installFileName()).OutputPath
  310. cmd := builder.Command().
  311. BuiltTool("mkbootfs").
  312. Text(rootDir.String()) // input directory
  313. if compressed {
  314. cmd.Text("|").
  315. BuiltTool("lz4").
  316. Flag("--favor-decSpeed"). // for faster boot
  317. Flag("-12"). // maximum compression level
  318. Flag("-l"). // legacy format for kernel
  319. Text(">").Output(output)
  320. } else {
  321. cmd.Text(">").Output(output)
  322. }
  323. // rootDir is not deleted. Might be useful for quick inspection.
  324. builder.Build("build_cpio_image", fmt.Sprintf("Creating filesystem %s", f.BaseModuleName()))
  325. return output
  326. }
  327. var _ android.AndroidMkEntriesProvider = (*filesystem)(nil)
  328. // Implements android.AndroidMkEntriesProvider
  329. func (f *filesystem) AndroidMkEntries() []android.AndroidMkEntries {
  330. return []android.AndroidMkEntries{android.AndroidMkEntries{
  331. Class: "ETC",
  332. OutputFile: android.OptionalPathForPath(f.output),
  333. ExtraEntries: []android.AndroidMkExtraEntriesFunc{
  334. func(ctx android.AndroidMkExtraEntriesContext, entries *android.AndroidMkEntries) {
  335. entries.SetString("LOCAL_MODULE_PATH", f.installDir.String())
  336. entries.SetString("LOCAL_INSTALLED_MODULE_STEM", f.installFileName())
  337. },
  338. },
  339. }}
  340. }
  341. var _ android.OutputFileProducer = (*filesystem)(nil)
  342. // Implements android.OutputFileProducer
  343. func (f *filesystem) OutputFiles(tag string) (android.Paths, error) {
  344. if tag == "" {
  345. return []android.Path{f.output}, nil
  346. }
  347. return nil, fmt.Errorf("unsupported module reference tag %q", tag)
  348. }
  349. // Filesystem is the public interface for the filesystem struct. Currently, it's only for the apex
  350. // package to have access to the output file.
  351. type Filesystem interface {
  352. android.Module
  353. OutputPath() android.Path
  354. // Returns the output file that is signed by avbtool. If this module is not signed, returns
  355. // nil.
  356. SignedOutputPath() android.Path
  357. }
  358. var _ Filesystem = (*filesystem)(nil)
  359. func (f *filesystem) OutputPath() android.Path {
  360. return f.output
  361. }
  362. func (f *filesystem) SignedOutputPath() android.Path {
  363. if proptools.Bool(f.properties.Use_avb) {
  364. return f.OutputPath()
  365. }
  366. return nil
  367. }
  368. // Filter the result of GatherPackagingSpecs to discard items targeting outside "system" partition.
  369. // Note that "apex" module installs its contents to "apex"(fake partition) as well
  370. // for symbol lookup by imitating "activated" paths.
  371. func (f *filesystem) gatherFilteredPackagingSpecs(ctx android.ModuleContext) map[string]android.PackagingSpec {
  372. specs := f.PackagingBase.GatherPackagingSpecs(ctx)
  373. if f.filterPackagingSpecs != nil {
  374. f.filterPackagingSpecs(specs)
  375. }
  376. return specs
  377. }