blob: a8f97e3b7e3c17b98b95fffd164fbc8a30c629f9 [file] [log] [blame]
Jiyong Park6f0f6882020-11-12 13:14:30 +09001// 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 (
Jooyung Han65f402b2022-04-21 14:24:04 +090018 "crypto/sha256"
Jiyong Park6f0f6882020-11-12 13:14:30 +090019 "fmt"
Jooyung Han65f402b2022-04-21 14:24:04 +090020 "io"
Inseob Kim14199b02021-02-09 21:18:31 +090021 "path/filepath"
Cole Faust4a2a7c92024-03-12 12:44:40 -070022 "slices"
Nikita Ioffe2c8cdc62024-03-27 22:19:30 +000023 "strconv"
Inseob Kim14199b02021-02-09 21:18:31 +090024 "strings"
Jiyong Park6f0f6882020-11-12 13:14:30 +090025
26 "android/soong/android"
Jooyung Hane6067592023-03-16 13:11:17 +090027 "android/soong/cc"
Jiyong Park65b62242020-11-25 12:44:59 +090028
29 "github.com/google/blueprint"
Jiyong Park71baa762021-01-18 21:11:03 +090030 "github.com/google/blueprint/proptools"
Jiyong Park6f0f6882020-11-12 13:14:30 +090031)
32
33func init() {
Jooyung Han9706cbc2021-04-15 22:43:48 +090034 registerBuildComponents(android.InitRegistrationContext)
35}
36
37func registerBuildComponents(ctx android.RegistrationContext) {
38 ctx.RegisterModuleType("android_filesystem", filesystemFactory)
Jiyong Parkf46b1af2024-04-05 18:13:33 +090039 ctx.RegisterModuleType("android_filesystem_defaults", filesystemDefaultsFactory)
Jiyong Parkfa616132021-04-20 11:36:40 +090040 ctx.RegisterModuleType("android_system_image", systemImageFactory)
Jiyong Parkbc485482022-11-15 22:31:49 +090041 ctx.RegisterModuleType("avb_add_hash_footer", avbAddHashFooterFactory)
Inseob Kim87230e62023-11-22 18:55:07 +090042 ctx.RegisterModuleType("avb_add_hash_footer_defaults", avbAddHashFooterDefaultsFactory)
Alice Wang000e3a32023-01-03 16:11:20 +000043 ctx.RegisterModuleType("avb_gen_vbmeta_image", avbGenVbmetaImageFactory)
Inseob Kim87230e62023-11-22 18:55:07 +090044 ctx.RegisterModuleType("avb_gen_vbmeta_image_defaults", avbGenVbmetaImageDefaultsFactory)
Jiyong Park6f0f6882020-11-12 13:14:30 +090045}
46
47type filesystem struct {
48 android.ModuleBase
49 android.PackagingBase
Jiyong Parkf46b1af2024-04-05 18:13:33 +090050 android.DefaultableModuleBase
Jiyong Park65c49f52020-11-24 14:23:26 +090051
Jiyong Park71baa762021-01-18 21:11:03 +090052 properties filesystemProperties
53
Jiyong Parkfa616132021-04-20 11:36:40 +090054 // Function that builds extra files under the root directory and returns the files
55 buildExtraFiles func(ctx android.ModuleContext, root android.OutputPath) android.OutputPaths
56
Jeongik Cha54bf8752024-02-08 10:44:37 +090057 // Function that filters PackagingSpec in PackagingBase.GatherPackagingSpecs()
58 filterPackagingSpec func(spec android.PackagingSpec) bool
Jooyung Han0fbbc2b2022-03-25 12:35:46 +090059
Jiyong Park65c49f52020-11-24 14:23:26 +090060 output android.OutputPath
61 installDir android.InstallPath
Jooyung Han0fbbc2b2022-03-25 12:35:46 +090062
Kiyoung Kim99a954d2024-06-21 14:22:20 +090063 fileListFile android.OutputPath
64
65 // Keeps the entries installed from this filesystem
Jooyung Han0fbbc2b2022-03-25 12:35:46 +090066 entries []string
Jiyong Park6f0f6882020-11-12 13:14:30 +090067}
68
Inseob Kim14199b02021-02-09 21:18:31 +090069type symlinkDefinition struct {
70 Target *string
71 Name *string
72}
73
Jiyong Park71baa762021-01-18 21:11:03 +090074type filesystemProperties struct {
75 // When set to true, sign the image with avbtool. Default is false.
76 Use_avb *bool
77
78 // Path to the private key that avbtool will use to sign this filesystem image.
79 // TODO(jiyong): allow apex_key to be specified here
80 Avb_private_key *string `android:"path"`
81
Shikha Panwar01403bb2022-12-22 12:22:57 +000082 // Signing algorithm for avbtool. Default is SHA256_RSA4096.
Jiyong Park71baa762021-01-18 21:11:03 +090083 Avb_algorithm *string
Jiyong Park11a65972021-02-01 21:09:38 +090084
Shikha Panwar01403bb2022-12-22 12:22:57 +000085 // Hash algorithm used for avbtool (for descriptors). This is passed as hash_algorithm to
86 // avbtool. Default used by avbtool is sha1.
Shikha Panware6f30632022-12-21 12:54:45 +000087 Avb_hash_algorithm *string
88
Nikita Ioffe2c8cdc62024-03-27 22:19:30 +000089 // The index used to prevent rollback of the image. Only used if use_avb is true.
90 Rollback_index *int64
91
Jiyong Parkac4076d2021-03-15 23:21:30 +090092 // Name of the partition stored in vbmeta desc. Defaults to the name of this module.
93 Partition_name *string
94
Jiyong Park837cdb22021-02-05 00:17:14 +090095 // Type of the filesystem. Currently, ext4, cpio, and compressed_cpio are supported. Default
96 // is ext4.
Jiyong Park11a65972021-02-01 21:09:38 +090097 Type *string
Inseob Kimcc8e5362021-02-03 14:05:24 +090098
Cole Faust9a24d902024-03-18 15:38:12 -070099 // Identifies which partition this is for //visibility:any_system_image (and others) visibility
100 // checks, and will be used in the future for API surface checks.
101 Partition_type *string
102
Inseob Kimcc8e5362021-02-03 14:05:24 +0900103 // file_contexts file to make image. Currently, only ext4 is supported.
104 File_contexts *string `android:"path"`
Inseob Kim2ce1b5d2021-02-15 17:01:04 +0900105
106 // Base directory relative to root, to which deps are installed, e.g. "system". Default is "."
107 // (root).
108 Base_dir *string
Inseob Kim14199b02021-02-09 21:18:31 +0900109
110 // Directories to be created under root. e.g. /dev, /proc, etc.
Cole Faustd9c6a5b2024-05-21 14:54:00 -0700111 Dirs proptools.Configurable[[]string]
Inseob Kim14199b02021-02-09 21:18:31 +0900112
113 // Symbolic links to be created under root with "ln -sf <target> <name>".
114 Symlinks []symlinkDefinition
Jooyung Han65f402b2022-04-21 14:24:04 +0900115
116 // Seconds since unix epoch to override timestamps of file entries
117 Fake_timestamp *string
118
119 // When set, passed to mkuserimg_mke2fs --mke2fs_uuid & --mke2fs_hash_seed.
120 // Otherwise, they'll be set as random which might cause indeterministic build output.
121 Uuid *string
Inseob Kim376d72f2023-11-01 15:40:25 +0900122
123 // Mount point for this image. Default is "/"
124 Mount_point *string
Cole Faust4a2a7c92024-03-12 12:44:40 -0700125
126 // If set to the name of a partition ("system", "vendor", etc), this filesystem module
127 // will also include the contents of the make-built staging directories. If any soong
128 // modules would be installed to the same location as a make module, they will overwrite
129 // the make version.
130 Include_make_built_files string
Inseob Kim53391842024-03-29 17:44:07 +0900131
Inseob Kimb7b84572024-04-30 10:51:47 +0900132 // When set, builds etc/event-log-tags file by merging logtags from all dependencies.
133 // Default is false
134 Build_logtags *bool
135
Justin Yun74f3f302024-05-07 14:32:14 +0900136 // Install aconfig_flags.pb file for the modules installed in this partition.
137 Gen_aconfig_flags_pb *bool
138
Justin Yun34baa2e2024-08-30 21:11:33 +0900139 // Update the Base_dir of the $PRODUCT_OUT directory with the packaging files.
140 Update_product_out *bool
141
Inseob Kim53391842024-03-29 17:44:07 +0900142 Fsverity fsverityProperties
Jiyong Park71baa762021-01-18 21:11:03 +0900143}
144
Jiyong Park65c49f52020-11-24 14:23:26 +0900145// android_filesystem packages a set of modules and their transitive dependencies into a filesystem
146// image. The filesystem images are expected to be mounted in the target device, which means the
147// modules in the filesystem image are built for the target device (i.e. Android, not Linux host).
148// The modules are placed in the filesystem image just like they are installed to the ordinary
149// partitions like system.img. For example, cc_library modules are placed under ./lib[64] directory.
Jiyong Park6f0f6882020-11-12 13:14:30 +0900150func filesystemFactory() android.Module {
151 module := &filesystem{}
Jiyong Park7e7d4af2024-05-01 12:36:10 +0000152 module.filterPackagingSpec = module.filterInstallablePackagingSpec
Jiyong Parkfa616132021-04-20 11:36:40 +0900153 initFilesystemModule(module)
154 return module
155}
156
157func initFilesystemModule(module *filesystem) {
Jiyong Park71baa762021-01-18 21:11:03 +0900158 module.AddProperties(&module.properties)
Jiyong Park6f0f6882020-11-12 13:14:30 +0900159 android.InitPackageModule(module)
Jiyong Park3ea9b652024-05-15 23:01:54 +0900160 module.PackagingBase.DepsCollectFirstTargetOnly = true
Jiyong Park6f0f6882020-11-12 13:14:30 +0900161 android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900162 android.InitDefaultableModule(module)
Jiyong Park6f0f6882020-11-12 13:14:30 +0900163}
164
Jiyong Park12a719c2021-01-07 15:31:24 +0900165var dependencyTag = struct {
166 blueprint.BaseDependencyTag
Jooyung Han092ef812021-03-10 15:40:34 +0900167 android.PackagingItemAlwaysDepTag
Jiyong Park12a719c2021-01-07 15:31:24 +0900168}{}
Jiyong Park65b62242020-11-25 12:44:59 +0900169
Jiyong Park6f0f6882020-11-12 13:14:30 +0900170func (f *filesystem) DepsMutator(ctx android.BottomUpMutatorContext) {
Jiyong Park65b62242020-11-25 12:44:59 +0900171 f.AddDeps(ctx, dependencyTag)
Jiyong Park6f0f6882020-11-12 13:14:30 +0900172}
173
Jiyong Park11a65972021-02-01 21:09:38 +0900174type fsType int
175
176const (
177 ext4Type fsType = iota
178 compressedCpioType
Jiyong Park837cdb22021-02-05 00:17:14 +0900179 cpioType // uncompressed
Jiyong Park11a65972021-02-01 21:09:38 +0900180 unknown
181)
182
183func (f *filesystem) fsType(ctx android.ModuleContext) fsType {
184 typeStr := proptools.StringDefault(f.properties.Type, "ext4")
185 switch typeStr {
186 case "ext4":
187 return ext4Type
188 case "compressed_cpio":
189 return compressedCpioType
Jiyong Park837cdb22021-02-05 00:17:14 +0900190 case "cpio":
191 return cpioType
Jiyong Park11a65972021-02-01 21:09:38 +0900192 default:
193 ctx.PropertyErrorf("type", "%q not supported", typeStr)
194 return unknown
195 }
196}
197
Jiyong Park65c49f52020-11-24 14:23:26 +0900198func (f *filesystem) installFileName() string {
199 return f.BaseModuleName() + ".img"
200}
201
Inseob Kim53391842024-03-29 17:44:07 +0900202func (f *filesystem) partitionName() string {
203 return proptools.StringDefault(f.properties.Partition_name, f.Name())
204}
205
Jiyong Park7e7d4af2024-05-01 12:36:10 +0000206func (f *filesystem) filterInstallablePackagingSpec(ps android.PackagingSpec) bool {
207 // Filesystem module respects the installation semantic. A PackagingSpec from a module with
208 // IsSkipInstall() is skipped.
209 return !ps.SkipInstall()
210}
211
Jiyong Park6f0f6882020-11-12 13:14:30 +0900212var pctx = android.NewPackageContext("android/soong/filesystem")
213
214func (f *filesystem) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900215 validatePartitionType(ctx, f)
Jiyong Park11a65972021-02-01 21:09:38 +0900216 switch f.fsType(ctx) {
217 case ext4Type:
218 f.output = f.buildImageUsingBuildImage(ctx)
219 case compressedCpioType:
Jiyong Park837cdb22021-02-05 00:17:14 +0900220 f.output = f.buildCpioImage(ctx, true)
221 case cpioType:
222 f.output = f.buildCpioImage(ctx, false)
Jiyong Park11a65972021-02-01 21:09:38 +0900223 default:
224 return
225 }
226
227 f.installDir = android.PathForModuleInstall(ctx, "etc")
228 ctx.InstallFile(f.installDir, f.installFileName(), f.output)
mrziwang555d1332024-06-07 11:15:33 -0700229 ctx.SetOutputFiles([]android.Path{f.output}, "")
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900230
231 f.fileListFile = android.PathForModuleOut(ctx, "fileList").OutputPath
232 android.WriteFileRule(ctx, f.fileListFile, f.installedFilesList())
233}
234
235func (f *filesystem) appendToEntry(ctx android.ModuleContext, installedFile android.OutputPath) {
236 partitionBaseDir := android.PathForModuleOut(ctx, "root", f.partitionName()).String() + "/"
237
238 relPath, inTargetPartition := strings.CutPrefix(installedFile.String(), partitionBaseDir)
239 if inTargetPartition {
240 f.entries = append(f.entries, relPath)
241 }
242}
243
244func (f *filesystem) installedFilesList() string {
245 installedFilePaths := android.FirstUniqueStrings(f.entries)
246 slices.Sort(installedFilePaths)
247
248 return strings.Join(installedFilePaths, "\n")
Jiyong Park11a65972021-02-01 21:09:38 +0900249}
250
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900251func validatePartitionType(ctx android.ModuleContext, p partition) {
252 if !android.InList(p.PartitionType(), validPartitions) {
253 ctx.PropertyErrorf("partition_type", "partition_type must be one of %s, found: %s", validPartitions, p.PartitionType())
254 }
255
256 ctx.VisitDirectDepsWithTag(android.DefaultsDepTag, func(m android.Module) {
257 if fdm, ok := m.(*filesystemDefaults); ok {
258 if p.PartitionType() != fdm.PartitionType() {
259 ctx.PropertyErrorf("partition_type",
260 "%s doesn't match with the partition type %s of the filesystem default module %s",
261 p.PartitionType(), fdm.PartitionType(), m.Name())
262 }
263 }
264 })
265}
266
Cole Faust3b806d32024-03-11 15:15:03 -0700267// Copy extra files/dirs that are not from the `deps` property to `rootDir`, checking for conflicts with files
268// already in `rootDir`.
269func (f *filesystem) buildNonDepsFiles(ctx android.ModuleContext, builder *android.RuleBuilder, rootDir android.OutputPath) {
Inseob Kim14199b02021-02-09 21:18:31 +0900270 // create dirs and symlinks
Cole Faustd9c6a5b2024-05-21 14:54:00 -0700271 for _, dir := range f.properties.Dirs.GetOrDefault(ctx, nil) {
Inseob Kim14199b02021-02-09 21:18:31 +0900272 // OutputPath.Join verifies dir
273 builder.Command().Text("mkdir -p").Text(rootDir.Join(ctx, dir).String())
274 }
275
276 for _, symlink := range f.properties.Symlinks {
277 name := strings.TrimSpace(proptools.String(symlink.Name))
278 target := strings.TrimSpace(proptools.String(symlink.Target))
279
280 if name == "" {
281 ctx.PropertyErrorf("symlinks", "Name can't be empty")
282 continue
283 }
284
285 if target == "" {
286 ctx.PropertyErrorf("symlinks", "Target can't be empty")
287 continue
288 }
289
290 // OutputPath.Join verifies name. don't need to verify target.
291 dst := rootDir.Join(ctx, name)
Cole Faust3b806d32024-03-11 15:15:03 -0700292 builder.Command().Textf("(! [ -e %s -o -L %s ] || (echo \"%s already exists from an earlier stage of the build\" && exit 1))", dst, dst, dst)
Inseob Kim14199b02021-02-09 21:18:31 +0900293 builder.Command().Text("mkdir -p").Text(filepath.Dir(dst.String()))
294 builder.Command().Text("ln -sf").Text(proptools.ShellEscape(target)).Text(dst.String())
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900295 f.appendToEntry(ctx, dst)
Inseob Kim14199b02021-02-09 21:18:31 +0900296 }
Inseob Kim2ce1b5d2021-02-15 17:01:04 +0900297
Jiyong Parkfa616132021-04-20 11:36:40 +0900298 // create extra files if there's any
Jiyong Parkfa616132021-04-20 11:36:40 +0900299 if f.buildExtraFiles != nil {
Cole Faust4a2a7c92024-03-12 12:44:40 -0700300 rootForExtraFiles := android.PathForModuleGen(ctx, "root-extra").OutputPath
301 extraFiles := f.buildExtraFiles(ctx, rootForExtraFiles)
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900302 for _, extraFile := range extraFiles {
303 rel, err := filepath.Rel(rootForExtraFiles.String(), extraFile.String())
Cole Faust4a2a7c92024-03-12 12:44:40 -0700304 if err != nil || strings.HasPrefix(rel, "..") {
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900305 ctx.ModuleErrorf("can't make %q relative to %q", extraFile, rootForExtraFiles)
Cole Faust4a2a7c92024-03-12 12:44:40 -0700306 }
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900307 f.appendToEntry(ctx, rootDir.Join(ctx, rel))
Jiyong Parkfa616132021-04-20 11:36:40 +0900308 }
Cole Faust4a2a7c92024-03-12 12:44:40 -0700309 if len(extraFiles) > 0 {
310 builder.Command().BuiltTool("merge_directories").
311 Implicits(extraFiles.Paths()).
312 Text(rootDir.String()).
313 Text(rootForExtraFiles.String())
314 }
Jiyong Parkfa616132021-04-20 11:36:40 +0900315 }
Inseob Kim2ce1b5d2021-02-15 17:01:04 +0900316}
317
Inseob Kim33f95a92024-07-11 15:44:49 +0900318func (f *filesystem) copyPackagingSpecs(ctx android.ModuleContext, builder *android.RuleBuilder, specs map[string]android.PackagingSpec, rootDir, rebasedDir android.WritablePath) []string {
319 rootDirSpecs := make(map[string]android.PackagingSpec)
320 rebasedDirSpecs := make(map[string]android.PackagingSpec)
321
322 for rel, spec := range specs {
323 if spec.Partition() == "root" {
324 rootDirSpecs[rel] = spec
325 } else {
326 rebasedDirSpecs[rel] = spec
327 }
328 }
329
330 dirsToSpecs := make(map[android.WritablePath]map[string]android.PackagingSpec)
331 dirsToSpecs[rootDir] = rootDirSpecs
332 dirsToSpecs[rebasedDir] = rebasedDirSpecs
333
334 return f.CopySpecsToDirs(ctx, builder, dirsToSpecs)
335}
336
Justin Yun34baa2e2024-08-30 21:11:33 +0900337func (f *filesystem) copyFilesToProductOut(ctx android.ModuleContext, builder *android.RuleBuilder, rebasedDir android.OutputPath) {
338 if !proptools.Bool(f.properties.Update_product_out) {
339 return
340 }
341 installPath := android.PathForModuleInPartitionInstall(ctx, f.partitionName())
342 builder.Command().Textf("cp -prf %s/* %s", rebasedDir, installPath)
343}
344
Jiyong Park11a65972021-02-01 21:09:38 +0900345func (f *filesystem) buildImageUsingBuildImage(ctx android.ModuleContext) android.OutputPath {
Jiyong Park6f0f6882020-11-12 13:14:30 +0900346 rootDir := android.PathForModuleOut(ctx, "root").OutputPath
Cole Faust3b806d32024-03-11 15:15:03 -0700347 rebasedDir := rootDir
348 if f.properties.Base_dir != nil {
349 rebasedDir = rootDir.Join(ctx, *f.properties.Base_dir)
350 }
351 builder := android.NewRuleBuilder(pctx, ctx)
352 // Wipe the root dir to get rid of leftover files from prior builds
353 builder.Command().Textf("rm -rf %s && mkdir -p %s", rootDir, rootDir)
Inseob Kim53391842024-03-29 17:44:07 +0900354 specs := f.gatherFilteredPackagingSpecs(ctx)
Inseob Kim33f95a92024-07-11 15:44:49 +0900355 f.entries = f.copyPackagingSpecs(ctx, builder, specs, rootDir, rebasedDir)
Cole Faust3b806d32024-03-11 15:15:03 -0700356
357 f.buildNonDepsFiles(ctx, builder, rootDir)
Cole Faust4a2a7c92024-03-12 12:44:40 -0700358 f.addMakeBuiltFiles(ctx, builder, rootDir)
Inseob Kim53391842024-03-29 17:44:07 +0900359 f.buildFsverityMetadataFiles(ctx, builder, specs, rootDir, rebasedDir)
Inseob Kimb7b84572024-04-30 10:51:47 +0900360 f.buildEventLogtagsFile(ctx, builder, rebasedDir)
Justin Yun74f3f302024-05-07 14:32:14 +0900361 f.buildAconfigFlagsFiles(ctx, builder, specs, rebasedDir)
Justin Yun34baa2e2024-08-30 21:11:33 +0900362 f.copyFilesToProductOut(ctx, builder, rebasedDir)
Jiyong Park6f0f6882020-11-12 13:14:30 +0900363
Nikita Ioffe519015f2022-12-23 15:36:29 +0000364 // run host_init_verifier
365 // Ideally we should have a concept of pluggable linters that verify the generated image.
366 // While such concept is not implement this will do.
367 // TODO(b/263574231): substitute with pluggable linter.
368 builder.Command().
369 BuiltTool("host_init_verifier").
370 FlagWithArg("--out_system=", rootDir.String()+"/system")
371
Jiyong Park72678312021-01-18 17:29:49 +0900372 propFile, toolDeps := f.buildPropFile(ctx)
Jiyong Park11a65972021-02-01 21:09:38 +0900373 output := android.PathForModuleOut(ctx, f.installFileName()).OutputPath
Colin Crossf1a035e2020-11-16 17:32:30 -0800374 builder.Command().BuiltTool("build_image").
Jiyong Park6f0f6882020-11-12 13:14:30 +0900375 Text(rootDir.String()). // input directory
376 Input(propFile).
Jiyong Park72678312021-01-18 17:29:49 +0900377 Implicits(toolDeps).
Jiyong Park11a65972021-02-01 21:09:38 +0900378 Output(output).
Jiyong Park6f0f6882020-11-12 13:14:30 +0900379 Text(rootDir.String()) // directory where to find fs_config_files|dirs
380
381 // rootDir is not deleted. Might be useful for quick inspection.
Colin Crossf1a035e2020-11-16 17:32:30 -0800382 builder.Build("build_filesystem_image", fmt.Sprintf("Creating filesystem %s", f.BaseModuleName()))
Jiyong Park65c49f52020-11-24 14:23:26 +0900383
Jiyong Park11a65972021-02-01 21:09:38 +0900384 return output
Jiyong Park65c49f52020-11-24 14:23:26 +0900385}
386
Inseob Kimcc8e5362021-02-03 14:05:24 +0900387func (f *filesystem) buildFileContexts(ctx android.ModuleContext) android.OutputPath {
388 builder := android.NewRuleBuilder(pctx, ctx)
389 fcBin := android.PathForModuleOut(ctx, "file_contexts.bin")
390 builder.Command().BuiltTool("sefcontext_compile").
391 FlagWithOutput("-o ", fcBin).
392 Input(android.PathForModuleSrc(ctx, proptools.String(f.properties.File_contexts)))
393 builder.Build("build_filesystem_file_contexts", fmt.Sprintf("Creating filesystem file contexts for %s", f.BaseModuleName()))
394 return fcBin.OutputPath
395}
396
Jooyung Han65f402b2022-04-21 14:24:04 +0900397// Calculates avb_salt from entry list (sorted) for deterministic output.
398func (f *filesystem) salt() string {
399 return sha1sum(f.entries)
400}
401
Jiyong Park72678312021-01-18 17:29:49 +0900402func (f *filesystem) buildPropFile(ctx android.ModuleContext) (propFile android.OutputPath, toolDeps android.Paths) {
Jiyong Park72678312021-01-18 17:29:49 +0900403 var deps android.Paths
Cole Faustcec230a2024-03-07 15:51:12 -0800404 var propFileString strings.Builder
Jiyong Park72678312021-01-18 17:29:49 +0900405 addStr := func(name string, value string) {
Cole Faustcec230a2024-03-07 15:51:12 -0800406 propFileString.WriteString(name)
407 propFileString.WriteRune('=')
408 propFileString.WriteString(value)
409 propFileString.WriteRune('\n')
Jiyong Park72678312021-01-18 17:29:49 +0900410 }
411 addPath := func(name string, path android.Path) {
Cole Faustcec230a2024-03-07 15:51:12 -0800412 addStr(name, path.String())
Jiyong Park72678312021-01-18 17:29:49 +0900413 deps = append(deps, path)
414 }
415
Jiyong Park11a65972021-02-01 21:09:38 +0900416 // Type string that build_image.py accepts.
417 fsTypeStr := func(t fsType) string {
418 switch t {
419 // TODO(jiyong): add more types like f2fs, erofs, etc.
420 case ext4Type:
421 return "ext4"
422 }
423 panic(fmt.Errorf("unsupported fs type %v", t))
424 }
425
426 addStr("fs_type", fsTypeStr(f.fsType(ctx)))
Inseob Kim376d72f2023-11-01 15:40:25 +0900427 addStr("mount_point", proptools.StringDefault(f.properties.Mount_point, "/"))
Jiyong Park72678312021-01-18 17:29:49 +0900428 addStr("use_dynamic_partition_size", "true")
429 addPath("ext_mkuserimg", ctx.Config().HostToolPath(ctx, "mkuserimg_mke2fs"))
430 // b/177813163 deps of the host tools have to be added. Remove this.
431 for _, t := range []string{"mke2fs", "e2fsdroid", "tune2fs"} {
432 deps = append(deps, ctx.Config().HostToolPath(ctx, t))
433 }
434
Jiyong Park71baa762021-01-18 21:11:03 +0900435 if proptools.Bool(f.properties.Use_avb) {
436 addStr("avb_hashtree_enable", "true")
437 addPath("avb_avbtool", ctx.Config().HostToolPath(ctx, "avbtool"))
438 algorithm := proptools.StringDefault(f.properties.Avb_algorithm, "SHA256_RSA4096")
439 addStr("avb_algorithm", algorithm)
440 key := android.PathForModuleSrc(ctx, proptools.String(f.properties.Avb_private_key))
441 addPath("avb_key_path", key)
Inseob Kim53391842024-03-29 17:44:07 +0900442 addStr("partition_name", f.partitionName())
Shikha Panware6f30632022-12-21 12:54:45 +0000443 avb_add_hashtree_footer_args := "--do_not_generate_fec"
444 if hashAlgorithm := proptools.String(f.properties.Avb_hash_algorithm); hashAlgorithm != "" {
445 avb_add_hashtree_footer_args += " --hash_algorithm " + hashAlgorithm
446 }
Nikita Ioffe2c8cdc62024-03-27 22:19:30 +0000447 if f.properties.Rollback_index != nil {
448 rollbackIndex := proptools.Int(f.properties.Rollback_index)
449 if rollbackIndex < 0 {
450 ctx.PropertyErrorf("rollback_index", "Rollback index must be non-negative")
451 }
452 avb_add_hashtree_footer_args += " --rollback_index " + strconv.Itoa(rollbackIndex)
453 }
Inseob Kim53391842024-03-29 17:44:07 +0900454 securityPatchKey := "com.android.build." + f.partitionName() + ".security_patch"
Seungjae Yooa30e4502023-11-09 14:55:44 +0900455 securityPatchValue := ctx.Config().PlatformSecurityPatch()
456 avb_add_hashtree_footer_args += " --prop " + securityPatchKey + ":" + securityPatchValue
Shikha Panware6f30632022-12-21 12:54:45 +0000457 addStr("avb_add_hashtree_footer_args", avb_add_hashtree_footer_args)
Jooyung Han65f402b2022-04-21 14:24:04 +0900458 addStr("avb_salt", f.salt())
Jiyong Park71baa762021-01-18 21:11:03 +0900459 }
460
Inseob Kimcc8e5362021-02-03 14:05:24 +0900461 if proptools.String(f.properties.File_contexts) != "" {
462 addPath("selinux_fc", f.buildFileContexts(ctx))
463 }
Jooyung Han65f402b2022-04-21 14:24:04 +0900464 if timestamp := proptools.String(f.properties.Fake_timestamp); timestamp != "" {
465 addStr("timestamp", timestamp)
466 }
467 if uuid := proptools.String(f.properties.Uuid); uuid != "" {
468 addStr("uuid", uuid)
469 addStr("hash_seed", uuid)
470 }
Jiyong Park72678312021-01-18 17:29:49 +0900471 propFile = android.PathForModuleOut(ctx, "prop").OutputPath
Cole Faustcec230a2024-03-07 15:51:12 -0800472 android.WriteFileRuleVerbatim(ctx, propFile, propFileString.String())
Jiyong Park72678312021-01-18 17:29:49 +0900473 return propFile, deps
474}
475
Jiyong Park837cdb22021-02-05 00:17:14 +0900476func (f *filesystem) buildCpioImage(ctx android.ModuleContext, compressed bool) android.OutputPath {
Jiyong Park11a65972021-02-01 21:09:38 +0900477 if proptools.Bool(f.properties.Use_avb) {
478 ctx.PropertyErrorf("use_avb", "signing compresed cpio image using avbtool is not supported."+
479 "Consider adding this to bootimg module and signing the entire boot image.")
480 }
481
Inseob Kimcc8e5362021-02-03 14:05:24 +0900482 if proptools.String(f.properties.File_contexts) != "" {
483 ctx.PropertyErrorf("file_contexts", "file_contexts is not supported for compressed cpio image.")
484 }
485
Cole Faust4a2a7c92024-03-12 12:44:40 -0700486 if f.properties.Include_make_built_files != "" {
487 ctx.PropertyErrorf("include_make_built_files", "include_make_built_files is not supported for compressed cpio image.")
488 }
489
Jiyong Park11a65972021-02-01 21:09:38 +0900490 rootDir := android.PathForModuleOut(ctx, "root").OutputPath
Cole Faust3b806d32024-03-11 15:15:03 -0700491 rebasedDir := rootDir
492 if f.properties.Base_dir != nil {
493 rebasedDir = rootDir.Join(ctx, *f.properties.Base_dir)
494 }
495 builder := android.NewRuleBuilder(pctx, ctx)
496 // Wipe the root dir to get rid of leftover files from prior builds
497 builder.Command().Textf("rm -rf %s && mkdir -p %s", rootDir, rootDir)
Inseob Kim53391842024-03-29 17:44:07 +0900498 specs := f.gatherFilteredPackagingSpecs(ctx)
Inseob Kim33f95a92024-07-11 15:44:49 +0900499 f.entries = f.copyPackagingSpecs(ctx, builder, specs, rootDir, rebasedDir)
Cole Faust3b806d32024-03-11 15:15:03 -0700500
501 f.buildNonDepsFiles(ctx, builder, rootDir)
Inseob Kim53391842024-03-29 17:44:07 +0900502 f.buildFsverityMetadataFiles(ctx, builder, specs, rootDir, rebasedDir)
Inseob Kimb7b84572024-04-30 10:51:47 +0900503 f.buildEventLogtagsFile(ctx, builder, rebasedDir)
Justin Yun74f3f302024-05-07 14:32:14 +0900504 f.buildAconfigFlagsFiles(ctx, builder, specs, rebasedDir)
Justin Yun34baa2e2024-08-30 21:11:33 +0900505 f.copyFilesToProductOut(ctx, builder, rebasedDir)
Jiyong Park11a65972021-02-01 21:09:38 +0900506
507 output := android.PathForModuleOut(ctx, f.installFileName()).OutputPath
Jiyong Park837cdb22021-02-05 00:17:14 +0900508 cmd := builder.Command().
Jiyong Park11a65972021-02-01 21:09:38 +0900509 BuiltTool("mkbootfs").
Jiyong Park837cdb22021-02-05 00:17:14 +0900510 Text(rootDir.String()) // input directory
511 if compressed {
512 cmd.Text("|").
513 BuiltTool("lz4").
514 Flag("--favor-decSpeed"). // for faster boot
515 Flag("-12"). // maximum compression level
516 Flag("-l"). // legacy format for kernel
517 Text(">").Output(output)
518 } else {
519 cmd.Text(">").Output(output)
520 }
Jiyong Park11a65972021-02-01 21:09:38 +0900521
522 // rootDir is not deleted. Might be useful for quick inspection.
Jiyong Park837cdb22021-02-05 00:17:14 +0900523 builder.Build("build_cpio_image", fmt.Sprintf("Creating filesystem %s", f.BaseModuleName()))
Jiyong Park11a65972021-02-01 21:09:38 +0900524
525 return output
526}
527
Cole Faust4a2a7c92024-03-12 12:44:40 -0700528var validPartitions = []string{
529 "system",
530 "userdata",
531 "cache",
532 "system_other",
533 "vendor",
534 "product",
535 "system_ext",
536 "odm",
537 "vendor_dlkm",
538 "odm_dlkm",
539 "system_dlkm",
540}
541
542func (f *filesystem) addMakeBuiltFiles(ctx android.ModuleContext, builder *android.RuleBuilder, rootDir android.Path) {
543 partition := f.properties.Include_make_built_files
544 if partition == "" {
545 return
546 }
547 if !slices.Contains(validPartitions, partition) {
548 ctx.PropertyErrorf("include_make_built_files", "Expected one of %#v, found %q", validPartitions, partition)
549 return
550 }
551 stampFile := fmt.Sprintf("target/product/%s/obj/PACKAGING/%s_intermediates/staging_dir.stamp", ctx.Config().DeviceName(), partition)
552 fileListFile := fmt.Sprintf("target/product/%s/obj/PACKAGING/%s_intermediates/file_list.txt", ctx.Config().DeviceName(), partition)
553 stagingDir := fmt.Sprintf("target/product/%s/%s", ctx.Config().DeviceName(), partition)
554
555 builder.Command().BuiltTool("merge_directories").
556 Implicit(android.PathForArbitraryOutput(ctx, stampFile)).
557 Text("--ignore-duplicates").
558 FlagWithInput("--file-list", android.PathForArbitraryOutput(ctx, fileListFile)).
559 Text(rootDir.String()).
560 Text(android.PathForArbitraryOutput(ctx, stagingDir).String())
561}
562
Inseob Kimb7b84572024-04-30 10:51:47 +0900563func (f *filesystem) buildEventLogtagsFile(ctx android.ModuleContext, builder *android.RuleBuilder, rebasedDir android.OutputPath) {
564 if !proptools.Bool(f.properties.Build_logtags) {
565 return
566 }
567
568 logtagsFilePaths := make(map[string]bool)
569 ctx.WalkDeps(func(child, parent android.Module) bool {
570 if logtagsInfo, ok := android.OtherModuleProvider(ctx, child, android.LogtagsProviderKey); ok {
571 for _, path := range logtagsInfo.Logtags {
572 logtagsFilePaths[path.String()] = true
573 }
574 }
575 return true
576 })
577
578 if len(logtagsFilePaths) == 0 {
579 return
580 }
581
582 etcPath := rebasedDir.Join(ctx, "etc")
583 eventLogtagsPath := etcPath.Join(ctx, "event-log-tags")
584 builder.Command().Text("mkdir").Flag("-p").Text(etcPath.String())
585 cmd := builder.Command().BuiltTool("merge-event-log-tags").
586 FlagWithArg("-o ", eventLogtagsPath.String()).
587 FlagWithInput("-m ", android.MergedLogtagsPath(ctx))
588
589 for _, path := range android.SortedKeys(logtagsFilePaths) {
590 cmd.Text(path)
591 }
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900592
593 f.appendToEntry(ctx, eventLogtagsPath)
Inseob Kimb7b84572024-04-30 10:51:47 +0900594}
595
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900596type partition interface {
597 PartitionType() string
598}
599
Cole Faust9a24d902024-03-18 15:38:12 -0700600func (f *filesystem) PartitionType() string {
601 return proptools.StringDefault(f.properties.Partition_type, "system")
602}
603
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900604var _ partition = (*filesystem)(nil)
605
Jiyong Park65c49f52020-11-24 14:23:26 +0900606var _ android.AndroidMkEntriesProvider = (*filesystem)(nil)
607
608// Implements android.AndroidMkEntriesProvider
609func (f *filesystem) AndroidMkEntries() []android.AndroidMkEntries {
610 return []android.AndroidMkEntries{android.AndroidMkEntries{
611 Class: "ETC",
612 OutputFile: android.OptionalPathForPath(f.output),
613 ExtraEntries: []android.AndroidMkExtraEntriesFunc{
Colin Crossaa255532020-07-03 13:18:24 -0700614 func(ctx android.AndroidMkExtraEntriesContext, entries *android.AndroidMkEntries) {
Colin Crossc68db4b2021-11-11 18:59:15 -0800615 entries.SetString("LOCAL_MODULE_PATH", f.installDir.String())
Jiyong Park65c49f52020-11-24 14:23:26 +0900616 entries.SetString("LOCAL_INSTALLED_MODULE_STEM", f.installFileName())
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900617 entries.SetString("LOCAL_FILESYSTEM_FILELIST", f.fileListFile.String())
Jiyong Park65c49f52020-11-24 14:23:26 +0900618 },
619 },
620 }}
Jiyong Park6f0f6882020-11-12 13:14:30 +0900621}
Jiyong Park12a719c2021-01-07 15:31:24 +0900622
623// Filesystem is the public interface for the filesystem struct. Currently, it's only for the apex
624// package to have access to the output file.
625type Filesystem interface {
626 android.Module
627 OutputPath() android.Path
Jiyong Park972e06c2021-03-15 23:32:49 +0900628
629 // Returns the output file that is signed by avbtool. If this module is not signed, returns
630 // nil.
631 SignedOutputPath() android.Path
Jiyong Park12a719c2021-01-07 15:31:24 +0900632}
633
634var _ Filesystem = (*filesystem)(nil)
635
636func (f *filesystem) OutputPath() android.Path {
637 return f.output
638}
Jiyong Park972e06c2021-03-15 23:32:49 +0900639
640func (f *filesystem) SignedOutputPath() android.Path {
641 if proptools.Bool(f.properties.Use_avb) {
642 return f.OutputPath()
643 }
644 return nil
645}
Jooyung Han0fbbc2b2022-03-25 12:35:46 +0900646
647// Filter the result of GatherPackagingSpecs to discard items targeting outside "system" partition.
648// Note that "apex" module installs its contents to "apex"(fake partition) as well
649// for symbol lookup by imitating "activated" paths.
650func (f *filesystem) gatherFilteredPackagingSpecs(ctx android.ModuleContext) map[string]android.PackagingSpec {
Jeongik Cha54bf8752024-02-08 10:44:37 +0900651 specs := f.PackagingBase.GatherPackagingSpecsWithFilter(ctx, f.filterPackagingSpec)
Jooyung Han0fbbc2b2022-03-25 12:35:46 +0900652 return specs
653}
Jooyung Han65f402b2022-04-21 14:24:04 +0900654
655func sha1sum(values []string) string {
656 h := sha256.New()
657 for _, value := range values {
658 io.WriteString(h, value)
659 }
660 return fmt.Sprintf("%x", h.Sum(nil))
661}
Jooyung Hane6067592023-03-16 13:11:17 +0900662
663// Base cc.UseCoverage
664
665var _ cc.UseCoverage = (*filesystem)(nil)
666
Colin Crosse1a85552024-06-14 12:17:37 -0700667func (*filesystem) IsNativeCoverageNeeded(ctx cc.IsNativeCoverageNeededContext) bool {
Jooyung Hane6067592023-03-16 13:11:17 +0900668 return ctx.Device() && ctx.DeviceConfig().NativeCoverageEnabled()
669}
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900670
671// android_filesystem_defaults
672
673type filesystemDefaults struct {
674 android.ModuleBase
675 android.DefaultsModuleBase
676
677 properties filesystemDefaultsProperties
678}
679
680type filesystemDefaultsProperties struct {
681 // Identifies which partition this is for //visibility:any_system_image (and others) visibility
682 // checks, and will be used in the future for API surface checks.
683 Partition_type *string
684}
685
686// android_filesystem_defaults is a default module for android_filesystem and android_system_image
687func filesystemDefaultsFactory() android.Module {
688 module := &filesystemDefaults{}
689 module.AddProperties(&module.properties)
690 module.AddProperties(&android.PackagingProperties{})
691 android.InitDefaultsModule(module)
692 return module
693}
694
695func (f *filesystemDefaults) PartitionType() string {
696 return proptools.StringDefault(f.properties.Partition_type, "system")
697}
698
699var _ partition = (*filesystemDefaults)(nil)
700
701func (f *filesystemDefaults) GenerateAndroidBuildActions(ctx android.ModuleContext) {
702 validatePartitionType(ctx, f)
703}