filesystem.go 16 KB

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