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