filesystem.go 14 KB

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