blob: 8c59df3716ee37699a55eb4ade6a8caab875ecb0 [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) {
Cole Faust92ccbe22024-10-03 14:38:37 -070038 ctx.RegisterModuleType("android_filesystem", FilesystemFactory)
Jiyong Parkf46b1af2024-04-05 18:13:33 +090039 ctx.RegisterModuleType("android_filesystem_defaults", filesystemDefaultsFactory)
Jihoon Kang98047cf2024-10-02 17:13:54 +000040 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
Jihoon Kang98047cf2024-10-02 17:13:54 +000052 properties FilesystemProperties
Jiyong Park71baa762021-01-18 21:11:03 +090053
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
Jihoon Kang98047cf2024-10-02 17:13:54 +000074type FilesystemProperties struct {
Jiyong Park71baa762021-01-18 21:11:03 +090075 // 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
Spandan Dasc35d6fb2024-10-10 17:51:14 +000095 // Type of the filesystem. Currently, ext4, erofs, cpio, and compressed_cpio are supported. Default
Jiyong Park837cdb22021-02-05 00:17:14 +090096 // 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
Inseob Kim53391842024-03-29 17:44:07 +0900139 Fsverity fsverityProperties
Cole Faust92ccbe22024-10-03 14:38:37 -0700140
141 // If this property is set to true, the filesystem will call ctx.UncheckedModule(), causing
142 // it to not be built on checkbuilds. Used for the automatic migration from make to soong
143 // build modules, where we want to emit some not-yet-working filesystems and we don't want them
144 // to be built.
145 Unchecked_module *bool `blueprint:"mutated"`
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000146
147 Erofs ErofsProperties
148}
149
150// Additional properties required to generate erofs FS partitions.
151type ErofsProperties struct {
152 // Compressor and Compression level passed to mkfs.erofs. e.g. (lz4hc,9)
153 // Please see external/erofs-utils/README for complete documentation.
154 Compressor *string
155
156 // Used as --compress-hints for mkfs.erofs
157 Compress_hints *string `android:"path"`
158
159 Sparse *bool
Jiyong Park71baa762021-01-18 21:11:03 +0900160}
161
Jiyong Park65c49f52020-11-24 14:23:26 +0900162// android_filesystem packages a set of modules and their transitive dependencies into a filesystem
163// image. The filesystem images are expected to be mounted in the target device, which means the
164// modules in the filesystem image are built for the target device (i.e. Android, not Linux host).
165// The modules are placed in the filesystem image just like they are installed to the ordinary
166// partitions like system.img. For example, cc_library modules are placed under ./lib[64] directory.
Cole Faust92ccbe22024-10-03 14:38:37 -0700167func FilesystemFactory() android.Module {
Jiyong Park6f0f6882020-11-12 13:14:30 +0900168 module := &filesystem{}
Jiyong Park7e7d4af2024-05-01 12:36:10 +0000169 module.filterPackagingSpec = module.filterInstallablePackagingSpec
Cole Faust2cfe6962024-09-17 11:31:14 -0700170 initFilesystemModule(module, module)
Jiyong Parkfa616132021-04-20 11:36:40 +0900171 return module
172}
173
Cole Faust2cfe6962024-09-17 11:31:14 -0700174func initFilesystemModule(module android.DefaultableModule, filesystemModule *filesystem) {
175 module.AddProperties(&filesystemModule.properties)
176 android.InitPackageModule(filesystemModule)
177 filesystemModule.PackagingBase.DepsCollectFirstTargetOnly = true
Jiyong Park6f0f6882020-11-12 13:14:30 +0900178 android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900179 android.InitDefaultableModule(module)
Jiyong Park6f0f6882020-11-12 13:14:30 +0900180}
181
Jihoon Kangac2d1ba2024-10-12 01:44:47 +0000182var dependencyTag = struct {
Jiyong Park12a719c2021-01-07 15:31:24 +0900183 blueprint.BaseDependencyTag
Jooyung Han092ef812021-03-10 15:40:34 +0900184 android.PackagingItemAlwaysDepTag
Jihoon Kangac2d1ba2024-10-12 01:44:47 +0000185}{}
Jiyong Park65b62242020-11-25 12:44:59 +0900186
Jiyong Park6f0f6882020-11-12 13:14:30 +0900187func (f *filesystem) DepsMutator(ctx android.BottomUpMutatorContext) {
Jihoon Kangac2d1ba2024-10-12 01:44:47 +0000188 f.AddDeps(ctx, dependencyTag)
Jiyong Park6f0f6882020-11-12 13:14:30 +0900189}
190
Jiyong Park11a65972021-02-01 21:09:38 +0900191type fsType int
192
193const (
194 ext4Type fsType = iota
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000195 erofsType
Jiyong Park11a65972021-02-01 21:09:38 +0900196 compressedCpioType
Jiyong Park837cdb22021-02-05 00:17:14 +0900197 cpioType // uncompressed
Jiyong Park11a65972021-02-01 21:09:38 +0900198 unknown
199)
200
Spandan Das7a46f6c2024-10-14 18:41:18 +0000201func (fs fsType) IsUnknown() bool {
202 return fs == unknown
203}
204
Cole Faust92ccbe22024-10-03 14:38:37 -0700205type FilesystemInfo struct {
206 // A text file containing the list of paths installed on the partition.
207 FileListFile android.Path
208}
209
210var FilesystemProvider = blueprint.NewProvider[FilesystemInfo]()
211
Spandan Das7a46f6c2024-10-14 18:41:18 +0000212func GetFsTypeFromString(ctx android.EarlyModuleContext, typeStr string) fsType {
Jiyong Park11a65972021-02-01 21:09:38 +0900213 switch typeStr {
214 case "ext4":
215 return ext4Type
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000216 case "erofs":
217 return erofsType
Jiyong Park11a65972021-02-01 21:09:38 +0900218 case "compressed_cpio":
219 return compressedCpioType
Jiyong Park837cdb22021-02-05 00:17:14 +0900220 case "cpio":
221 return cpioType
Jiyong Park11a65972021-02-01 21:09:38 +0900222 default:
Jiyong Park11a65972021-02-01 21:09:38 +0900223 return unknown
224 }
225}
226
Spandan Das7a46f6c2024-10-14 18:41:18 +0000227func (f *filesystem) fsType(ctx android.ModuleContext) fsType {
228 typeStr := proptools.StringDefault(f.properties.Type, "ext4")
229 fsType := GetFsTypeFromString(ctx, typeStr)
230 if fsType == unknown {
231 ctx.PropertyErrorf("type", "%q not supported", typeStr)
232 }
233 return fsType
234}
235
Jiyong Park65c49f52020-11-24 14:23:26 +0900236func (f *filesystem) installFileName() string {
237 return f.BaseModuleName() + ".img"
238}
239
Inseob Kim53391842024-03-29 17:44:07 +0900240func (f *filesystem) partitionName() string {
241 return proptools.StringDefault(f.properties.Partition_name, f.Name())
242}
243
Jiyong Park7e7d4af2024-05-01 12:36:10 +0000244func (f *filesystem) filterInstallablePackagingSpec(ps android.PackagingSpec) bool {
245 // Filesystem module respects the installation semantic. A PackagingSpec from a module with
246 // IsSkipInstall() is skipped.
247 return !ps.SkipInstall()
248}
249
Jiyong Park6f0f6882020-11-12 13:14:30 +0900250var pctx = android.NewPackageContext("android/soong/filesystem")
251
252func (f *filesystem) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900253 validatePartitionType(ctx, f)
Jiyong Park11a65972021-02-01 21:09:38 +0900254 switch f.fsType(ctx) {
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000255 case ext4Type, erofsType:
Jiyong Park11a65972021-02-01 21:09:38 +0900256 f.output = f.buildImageUsingBuildImage(ctx)
257 case compressedCpioType:
Jiyong Park837cdb22021-02-05 00:17:14 +0900258 f.output = f.buildCpioImage(ctx, true)
259 case cpioType:
260 f.output = f.buildCpioImage(ctx, false)
Jiyong Park11a65972021-02-01 21:09:38 +0900261 default:
262 return
263 }
264
265 f.installDir = android.PathForModuleInstall(ctx, "etc")
266 ctx.InstallFile(f.installDir, f.installFileName(), f.output)
mrziwang555d1332024-06-07 11:15:33 -0700267 ctx.SetOutputFiles([]android.Path{f.output}, "")
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900268
269 f.fileListFile = android.PathForModuleOut(ctx, "fileList").OutputPath
270 android.WriteFileRule(ctx, f.fileListFile, f.installedFilesList())
Cole Faust92ccbe22024-10-03 14:38:37 -0700271
272 android.SetProvider(ctx, FilesystemProvider, FilesystemInfo{
273 FileListFile: f.fileListFile,
274 })
275
276 if proptools.Bool(f.properties.Unchecked_module) {
277 ctx.UncheckedModule()
278 }
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900279}
280
281func (f *filesystem) appendToEntry(ctx android.ModuleContext, installedFile android.OutputPath) {
282 partitionBaseDir := android.PathForModuleOut(ctx, "root", f.partitionName()).String() + "/"
283
284 relPath, inTargetPartition := strings.CutPrefix(installedFile.String(), partitionBaseDir)
285 if inTargetPartition {
286 f.entries = append(f.entries, relPath)
287 }
288}
289
290func (f *filesystem) installedFilesList() string {
291 installedFilePaths := android.FirstUniqueStrings(f.entries)
292 slices.Sort(installedFilePaths)
293
294 return strings.Join(installedFilePaths, "\n")
Jiyong Park11a65972021-02-01 21:09:38 +0900295}
296
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900297func validatePartitionType(ctx android.ModuleContext, p partition) {
298 if !android.InList(p.PartitionType(), validPartitions) {
299 ctx.PropertyErrorf("partition_type", "partition_type must be one of %s, found: %s", validPartitions, p.PartitionType())
300 }
301
302 ctx.VisitDirectDepsWithTag(android.DefaultsDepTag, func(m android.Module) {
303 if fdm, ok := m.(*filesystemDefaults); ok {
304 if p.PartitionType() != fdm.PartitionType() {
305 ctx.PropertyErrorf("partition_type",
306 "%s doesn't match with the partition type %s of the filesystem default module %s",
307 p.PartitionType(), fdm.PartitionType(), m.Name())
308 }
309 }
310 })
311}
312
Cole Faust3b806d32024-03-11 15:15:03 -0700313// Copy extra files/dirs that are not from the `deps` property to `rootDir`, checking for conflicts with files
314// already in `rootDir`.
315func (f *filesystem) buildNonDepsFiles(ctx android.ModuleContext, builder *android.RuleBuilder, rootDir android.OutputPath) {
Inseob Kim14199b02021-02-09 21:18:31 +0900316 // create dirs and symlinks
Cole Faustd9c6a5b2024-05-21 14:54:00 -0700317 for _, dir := range f.properties.Dirs.GetOrDefault(ctx, nil) {
Inseob Kim14199b02021-02-09 21:18:31 +0900318 // OutputPath.Join verifies dir
319 builder.Command().Text("mkdir -p").Text(rootDir.Join(ctx, dir).String())
320 }
321
322 for _, symlink := range f.properties.Symlinks {
323 name := strings.TrimSpace(proptools.String(symlink.Name))
324 target := strings.TrimSpace(proptools.String(symlink.Target))
325
326 if name == "" {
327 ctx.PropertyErrorf("symlinks", "Name can't be empty")
328 continue
329 }
330
331 if target == "" {
332 ctx.PropertyErrorf("symlinks", "Target can't be empty")
333 continue
334 }
335
336 // OutputPath.Join verifies name. don't need to verify target.
337 dst := rootDir.Join(ctx, name)
Cole Faust3b806d32024-03-11 15:15:03 -0700338 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 +0900339 builder.Command().Text("mkdir -p").Text(filepath.Dir(dst.String()))
340 builder.Command().Text("ln -sf").Text(proptools.ShellEscape(target)).Text(dst.String())
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900341 f.appendToEntry(ctx, dst)
Inseob Kim14199b02021-02-09 21:18:31 +0900342 }
Inseob Kim2ce1b5d2021-02-15 17:01:04 +0900343
Jiyong Parkfa616132021-04-20 11:36:40 +0900344 // create extra files if there's any
Jiyong Parkfa616132021-04-20 11:36:40 +0900345 if f.buildExtraFiles != nil {
Cole Faust4a2a7c92024-03-12 12:44:40 -0700346 rootForExtraFiles := android.PathForModuleGen(ctx, "root-extra").OutputPath
347 extraFiles := f.buildExtraFiles(ctx, rootForExtraFiles)
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900348 for _, extraFile := range extraFiles {
349 rel, err := filepath.Rel(rootForExtraFiles.String(), extraFile.String())
Cole Faust4a2a7c92024-03-12 12:44:40 -0700350 if err != nil || strings.HasPrefix(rel, "..") {
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900351 ctx.ModuleErrorf("can't make %q relative to %q", extraFile, rootForExtraFiles)
Cole Faust4a2a7c92024-03-12 12:44:40 -0700352 }
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900353 f.appendToEntry(ctx, rootDir.Join(ctx, rel))
Jiyong Parkfa616132021-04-20 11:36:40 +0900354 }
Cole Faust4a2a7c92024-03-12 12:44:40 -0700355 if len(extraFiles) > 0 {
356 builder.Command().BuiltTool("merge_directories").
357 Implicits(extraFiles.Paths()).
358 Text(rootDir.String()).
359 Text(rootForExtraFiles.String())
360 }
Jiyong Parkfa616132021-04-20 11:36:40 +0900361 }
Inseob Kim2ce1b5d2021-02-15 17:01:04 +0900362}
363
Inseob Kim33f95a92024-07-11 15:44:49 +0900364func (f *filesystem) copyPackagingSpecs(ctx android.ModuleContext, builder *android.RuleBuilder, specs map[string]android.PackagingSpec, rootDir, rebasedDir android.WritablePath) []string {
365 rootDirSpecs := make(map[string]android.PackagingSpec)
366 rebasedDirSpecs := make(map[string]android.PackagingSpec)
367
368 for rel, spec := range specs {
369 if spec.Partition() == "root" {
370 rootDirSpecs[rel] = spec
371 } else {
372 rebasedDirSpecs[rel] = spec
373 }
374 }
375
376 dirsToSpecs := make(map[android.WritablePath]map[string]android.PackagingSpec)
377 dirsToSpecs[rootDir] = rootDirSpecs
378 dirsToSpecs[rebasedDir] = rebasedDirSpecs
379
380 return f.CopySpecsToDirs(ctx, builder, dirsToSpecs)
381}
382
Justin Yun34baa2e2024-08-30 21:11:33 +0900383func (f *filesystem) copyFilesToProductOut(ctx android.ModuleContext, builder *android.RuleBuilder, rebasedDir android.OutputPath) {
Justin Yun2cc42502024-09-11 14:10:20 +0900384 if f.Name() != ctx.Config().SoongDefinedSystemImage() {
Justin Yun34baa2e2024-08-30 21:11:33 +0900385 return
386 }
387 installPath := android.PathForModuleInPartitionInstall(ctx, f.partitionName())
388 builder.Command().Textf("cp -prf %s/* %s", rebasedDir, installPath)
389}
390
Jiyong Park11a65972021-02-01 21:09:38 +0900391func (f *filesystem) buildImageUsingBuildImage(ctx android.ModuleContext) android.OutputPath {
Jiyong Park6f0f6882020-11-12 13:14:30 +0900392 rootDir := android.PathForModuleOut(ctx, "root").OutputPath
Cole Faust3b806d32024-03-11 15:15:03 -0700393 rebasedDir := rootDir
394 if f.properties.Base_dir != nil {
395 rebasedDir = rootDir.Join(ctx, *f.properties.Base_dir)
396 }
397 builder := android.NewRuleBuilder(pctx, ctx)
398 // Wipe the root dir to get rid of leftover files from prior builds
399 builder.Command().Textf("rm -rf %s && mkdir -p %s", rootDir, rootDir)
Inseob Kim53391842024-03-29 17:44:07 +0900400 specs := f.gatherFilteredPackagingSpecs(ctx)
Inseob Kim33f95a92024-07-11 15:44:49 +0900401 f.entries = f.copyPackagingSpecs(ctx, builder, specs, rootDir, rebasedDir)
Cole Faust3b806d32024-03-11 15:15:03 -0700402
403 f.buildNonDepsFiles(ctx, builder, rootDir)
Cole Faust4a2a7c92024-03-12 12:44:40 -0700404 f.addMakeBuiltFiles(ctx, builder, rootDir)
Inseob Kim53391842024-03-29 17:44:07 +0900405 f.buildFsverityMetadataFiles(ctx, builder, specs, rootDir, rebasedDir)
Inseob Kimb7b84572024-04-30 10:51:47 +0900406 f.buildEventLogtagsFile(ctx, builder, rebasedDir)
Justin Yun74f3f302024-05-07 14:32:14 +0900407 f.buildAconfigFlagsFiles(ctx, builder, specs, rebasedDir)
Justin Yun34baa2e2024-08-30 21:11:33 +0900408 f.copyFilesToProductOut(ctx, builder, rebasedDir)
Jiyong Park6f0f6882020-11-12 13:14:30 +0900409
Nikita Ioffe519015f2022-12-23 15:36:29 +0000410 // run host_init_verifier
411 // Ideally we should have a concept of pluggable linters that verify the generated image.
412 // While such concept is not implement this will do.
413 // TODO(b/263574231): substitute with pluggable linter.
414 builder.Command().
415 BuiltTool("host_init_verifier").
416 FlagWithArg("--out_system=", rootDir.String()+"/system")
417
Jiyong Park72678312021-01-18 17:29:49 +0900418 propFile, toolDeps := f.buildPropFile(ctx)
Jiyong Park11a65972021-02-01 21:09:38 +0900419 output := android.PathForModuleOut(ctx, f.installFileName()).OutputPath
Colin Crossf1a035e2020-11-16 17:32:30 -0800420 builder.Command().BuiltTool("build_image").
Jiyong Park6f0f6882020-11-12 13:14:30 +0900421 Text(rootDir.String()). // input directory
422 Input(propFile).
Jiyong Park72678312021-01-18 17:29:49 +0900423 Implicits(toolDeps).
Jiyong Park11a65972021-02-01 21:09:38 +0900424 Output(output).
Jiyong Park6f0f6882020-11-12 13:14:30 +0900425 Text(rootDir.String()) // directory where to find fs_config_files|dirs
426
427 // rootDir is not deleted. Might be useful for quick inspection.
Colin Crossf1a035e2020-11-16 17:32:30 -0800428 builder.Build("build_filesystem_image", fmt.Sprintf("Creating filesystem %s", f.BaseModuleName()))
Jiyong Park65c49f52020-11-24 14:23:26 +0900429
Jiyong Park11a65972021-02-01 21:09:38 +0900430 return output
Jiyong Park65c49f52020-11-24 14:23:26 +0900431}
432
Inseob Kimcc8e5362021-02-03 14:05:24 +0900433func (f *filesystem) buildFileContexts(ctx android.ModuleContext) android.OutputPath {
434 builder := android.NewRuleBuilder(pctx, ctx)
435 fcBin := android.PathForModuleOut(ctx, "file_contexts.bin")
436 builder.Command().BuiltTool("sefcontext_compile").
437 FlagWithOutput("-o ", fcBin).
438 Input(android.PathForModuleSrc(ctx, proptools.String(f.properties.File_contexts)))
439 builder.Build("build_filesystem_file_contexts", fmt.Sprintf("Creating filesystem file contexts for %s", f.BaseModuleName()))
440 return fcBin.OutputPath
441}
442
Jooyung Han65f402b2022-04-21 14:24:04 +0900443// Calculates avb_salt from entry list (sorted) for deterministic output.
444func (f *filesystem) salt() string {
445 return sha1sum(f.entries)
446}
447
Jiyong Park72678312021-01-18 17:29:49 +0900448func (f *filesystem) buildPropFile(ctx android.ModuleContext) (propFile android.OutputPath, toolDeps android.Paths) {
Jiyong Park72678312021-01-18 17:29:49 +0900449 var deps android.Paths
Cole Faustcec230a2024-03-07 15:51:12 -0800450 var propFileString strings.Builder
Jiyong Park72678312021-01-18 17:29:49 +0900451 addStr := func(name string, value string) {
Cole Faustcec230a2024-03-07 15:51:12 -0800452 propFileString.WriteString(name)
453 propFileString.WriteRune('=')
454 propFileString.WriteString(value)
455 propFileString.WriteRune('\n')
Jiyong Park72678312021-01-18 17:29:49 +0900456 }
457 addPath := func(name string, path android.Path) {
Cole Faustcec230a2024-03-07 15:51:12 -0800458 addStr(name, path.String())
Jiyong Park72678312021-01-18 17:29:49 +0900459 deps = append(deps, path)
460 }
461
Jiyong Park11a65972021-02-01 21:09:38 +0900462 // Type string that build_image.py accepts.
463 fsTypeStr := func(t fsType) string {
464 switch t {
Spandan Das94668822024-10-09 20:51:33 +0000465 // TODO(372522486): add more types like f2fs, erofs, etc.
Jiyong Park11a65972021-02-01 21:09:38 +0900466 case ext4Type:
467 return "ext4"
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000468 case erofsType:
469 return "erofs"
Jiyong Park11a65972021-02-01 21:09:38 +0900470 }
471 panic(fmt.Errorf("unsupported fs type %v", t))
472 }
473
474 addStr("fs_type", fsTypeStr(f.fsType(ctx)))
Inseob Kim376d72f2023-11-01 15:40:25 +0900475 addStr("mount_point", proptools.StringDefault(f.properties.Mount_point, "/"))
Jiyong Park72678312021-01-18 17:29:49 +0900476 addStr("use_dynamic_partition_size", "true")
477 addPath("ext_mkuserimg", ctx.Config().HostToolPath(ctx, "mkuserimg_mke2fs"))
478 // b/177813163 deps of the host tools have to be added. Remove this.
479 for _, t := range []string{"mke2fs", "e2fsdroid", "tune2fs"} {
480 deps = append(deps, ctx.Config().HostToolPath(ctx, t))
481 }
482
Jiyong Park71baa762021-01-18 21:11:03 +0900483 if proptools.Bool(f.properties.Use_avb) {
484 addStr("avb_hashtree_enable", "true")
485 addPath("avb_avbtool", ctx.Config().HostToolPath(ctx, "avbtool"))
486 algorithm := proptools.StringDefault(f.properties.Avb_algorithm, "SHA256_RSA4096")
487 addStr("avb_algorithm", algorithm)
488 key := android.PathForModuleSrc(ctx, proptools.String(f.properties.Avb_private_key))
489 addPath("avb_key_path", key)
Inseob Kim53391842024-03-29 17:44:07 +0900490 addStr("partition_name", f.partitionName())
Shikha Panware6f30632022-12-21 12:54:45 +0000491 avb_add_hashtree_footer_args := "--do_not_generate_fec"
492 if hashAlgorithm := proptools.String(f.properties.Avb_hash_algorithm); hashAlgorithm != "" {
493 avb_add_hashtree_footer_args += " --hash_algorithm " + hashAlgorithm
494 }
Nikita Ioffe2c8cdc62024-03-27 22:19:30 +0000495 if f.properties.Rollback_index != nil {
496 rollbackIndex := proptools.Int(f.properties.Rollback_index)
497 if rollbackIndex < 0 {
498 ctx.PropertyErrorf("rollback_index", "Rollback index must be non-negative")
499 }
500 avb_add_hashtree_footer_args += " --rollback_index " + strconv.Itoa(rollbackIndex)
501 }
Inseob Kim53391842024-03-29 17:44:07 +0900502 securityPatchKey := "com.android.build." + f.partitionName() + ".security_patch"
Seungjae Yooa30e4502023-11-09 14:55:44 +0900503 securityPatchValue := ctx.Config().PlatformSecurityPatch()
504 avb_add_hashtree_footer_args += " --prop " + securityPatchKey + ":" + securityPatchValue
Shikha Panware6f30632022-12-21 12:54:45 +0000505 addStr("avb_add_hashtree_footer_args", avb_add_hashtree_footer_args)
Jooyung Han65f402b2022-04-21 14:24:04 +0900506 addStr("avb_salt", f.salt())
Jiyong Park71baa762021-01-18 21:11:03 +0900507 }
508
Inseob Kimcc8e5362021-02-03 14:05:24 +0900509 if proptools.String(f.properties.File_contexts) != "" {
510 addPath("selinux_fc", f.buildFileContexts(ctx))
511 }
Jooyung Han65f402b2022-04-21 14:24:04 +0900512 if timestamp := proptools.String(f.properties.Fake_timestamp); timestamp != "" {
513 addStr("timestamp", timestamp)
514 }
515 if uuid := proptools.String(f.properties.Uuid); uuid != "" {
516 addStr("uuid", uuid)
517 addStr("hash_seed", uuid)
518 }
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000519 // Add erofs properties
520 if f.fsType(ctx) == erofsType {
521 if compressor := f.properties.Erofs.Compressor; compressor != nil {
522 addStr("erofs_default_compressor", proptools.String(compressor))
523 }
524 if compressHints := f.properties.Erofs.Compress_hints; compressHints != nil {
Cole Faust7cd4bad2024-10-11 10:31:12 -0700525 addPath("erofs_default_compress_hints", android.PathForModuleSrc(ctx, *compressHints))
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000526 }
527 if proptools.BoolDefault(f.properties.Erofs.Sparse, true) {
528 // https://source.corp.google.com/h/googleplex-android/platform/build/+/88b1c67239ca545b11580237242774b411f2fed9:core/Makefile;l=2292;bpv=1;bpt=0;drc=ea8f34bc1d6e63656b4ec32f2391e9d54b3ebb6b
529 addStr("erofs_sparse_flag", "-s")
530 }
Cole Faust7cd4bad2024-10-11 10:31:12 -0700531 } else if f.properties.Erofs.Compressor != nil || f.properties.Erofs.Compress_hints != nil || f.properties.Erofs.Sparse != nil {
532 // Raise an exception if the propfile contains erofs properties, but the fstype is not erofs
533 fs := fsTypeStr(f.fsType(ctx))
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000534 ctx.PropertyErrorf("erofs", "erofs is non-empty, but FS type is %s\n. Please delete erofs properties if this partition should use %s\n", fs, fs)
535 }
536
Jiyong Park72678312021-01-18 17:29:49 +0900537 propFile = android.PathForModuleOut(ctx, "prop").OutputPath
Cole Faustcec230a2024-03-07 15:51:12 -0800538 android.WriteFileRuleVerbatim(ctx, propFile, propFileString.String())
Jiyong Park72678312021-01-18 17:29:49 +0900539 return propFile, deps
540}
541
Jiyong Park837cdb22021-02-05 00:17:14 +0900542func (f *filesystem) buildCpioImage(ctx android.ModuleContext, compressed bool) android.OutputPath {
Jiyong Park11a65972021-02-01 21:09:38 +0900543 if proptools.Bool(f.properties.Use_avb) {
544 ctx.PropertyErrorf("use_avb", "signing compresed cpio image using avbtool is not supported."+
545 "Consider adding this to bootimg module and signing the entire boot image.")
546 }
547
Inseob Kimcc8e5362021-02-03 14:05:24 +0900548 if proptools.String(f.properties.File_contexts) != "" {
549 ctx.PropertyErrorf("file_contexts", "file_contexts is not supported for compressed cpio image.")
550 }
551
Cole Faust4a2a7c92024-03-12 12:44:40 -0700552 if f.properties.Include_make_built_files != "" {
553 ctx.PropertyErrorf("include_make_built_files", "include_make_built_files is not supported for compressed cpio image.")
554 }
555
Jiyong Park11a65972021-02-01 21:09:38 +0900556 rootDir := android.PathForModuleOut(ctx, "root").OutputPath
Cole Faust3b806d32024-03-11 15:15:03 -0700557 rebasedDir := rootDir
558 if f.properties.Base_dir != nil {
559 rebasedDir = rootDir.Join(ctx, *f.properties.Base_dir)
560 }
561 builder := android.NewRuleBuilder(pctx, ctx)
562 // Wipe the root dir to get rid of leftover files from prior builds
563 builder.Command().Textf("rm -rf %s && mkdir -p %s", rootDir, rootDir)
Inseob Kim53391842024-03-29 17:44:07 +0900564 specs := f.gatherFilteredPackagingSpecs(ctx)
Inseob Kim33f95a92024-07-11 15:44:49 +0900565 f.entries = f.copyPackagingSpecs(ctx, builder, specs, rootDir, rebasedDir)
Cole Faust3b806d32024-03-11 15:15:03 -0700566
567 f.buildNonDepsFiles(ctx, builder, rootDir)
Inseob Kim53391842024-03-29 17:44:07 +0900568 f.buildFsverityMetadataFiles(ctx, builder, specs, rootDir, rebasedDir)
Inseob Kimb7b84572024-04-30 10:51:47 +0900569 f.buildEventLogtagsFile(ctx, builder, rebasedDir)
Justin Yun74f3f302024-05-07 14:32:14 +0900570 f.buildAconfigFlagsFiles(ctx, builder, specs, rebasedDir)
Justin Yun34baa2e2024-08-30 21:11:33 +0900571 f.copyFilesToProductOut(ctx, builder, rebasedDir)
Jiyong Park11a65972021-02-01 21:09:38 +0900572
573 output := android.PathForModuleOut(ctx, f.installFileName()).OutputPath
Jiyong Park837cdb22021-02-05 00:17:14 +0900574 cmd := builder.Command().
Jiyong Park11a65972021-02-01 21:09:38 +0900575 BuiltTool("mkbootfs").
Jiyong Park837cdb22021-02-05 00:17:14 +0900576 Text(rootDir.String()) // input directory
577 if compressed {
578 cmd.Text("|").
579 BuiltTool("lz4").
580 Flag("--favor-decSpeed"). // for faster boot
581 Flag("-12"). // maximum compression level
582 Flag("-l"). // legacy format for kernel
583 Text(">").Output(output)
584 } else {
585 cmd.Text(">").Output(output)
586 }
Jiyong Park11a65972021-02-01 21:09:38 +0900587
588 // rootDir is not deleted. Might be useful for quick inspection.
Jiyong Park837cdb22021-02-05 00:17:14 +0900589 builder.Build("build_cpio_image", fmt.Sprintf("Creating filesystem %s", f.BaseModuleName()))
Jiyong Park11a65972021-02-01 21:09:38 +0900590
591 return output
592}
593
Cole Faust4a2a7c92024-03-12 12:44:40 -0700594var validPartitions = []string{
595 "system",
596 "userdata",
597 "cache",
598 "system_other",
599 "vendor",
600 "product",
601 "system_ext",
602 "odm",
603 "vendor_dlkm",
604 "odm_dlkm",
605 "system_dlkm",
606}
607
608func (f *filesystem) addMakeBuiltFiles(ctx android.ModuleContext, builder *android.RuleBuilder, rootDir android.Path) {
609 partition := f.properties.Include_make_built_files
610 if partition == "" {
611 return
612 }
613 if !slices.Contains(validPartitions, partition) {
614 ctx.PropertyErrorf("include_make_built_files", "Expected one of %#v, found %q", validPartitions, partition)
615 return
616 }
617 stampFile := fmt.Sprintf("target/product/%s/obj/PACKAGING/%s_intermediates/staging_dir.stamp", ctx.Config().DeviceName(), partition)
618 fileListFile := fmt.Sprintf("target/product/%s/obj/PACKAGING/%s_intermediates/file_list.txt", ctx.Config().DeviceName(), partition)
619 stagingDir := fmt.Sprintf("target/product/%s/%s", ctx.Config().DeviceName(), partition)
620
621 builder.Command().BuiltTool("merge_directories").
622 Implicit(android.PathForArbitraryOutput(ctx, stampFile)).
623 Text("--ignore-duplicates").
624 FlagWithInput("--file-list", android.PathForArbitraryOutput(ctx, fileListFile)).
625 Text(rootDir.String()).
626 Text(android.PathForArbitraryOutput(ctx, stagingDir).String())
627}
628
Inseob Kimb7b84572024-04-30 10:51:47 +0900629func (f *filesystem) buildEventLogtagsFile(ctx android.ModuleContext, builder *android.RuleBuilder, rebasedDir android.OutputPath) {
630 if !proptools.Bool(f.properties.Build_logtags) {
631 return
632 }
633
634 logtagsFilePaths := make(map[string]bool)
635 ctx.WalkDeps(func(child, parent android.Module) bool {
636 if logtagsInfo, ok := android.OtherModuleProvider(ctx, child, android.LogtagsProviderKey); ok {
637 for _, path := range logtagsInfo.Logtags {
638 logtagsFilePaths[path.String()] = true
639 }
640 }
641 return true
642 })
643
644 if len(logtagsFilePaths) == 0 {
645 return
646 }
647
648 etcPath := rebasedDir.Join(ctx, "etc")
649 eventLogtagsPath := etcPath.Join(ctx, "event-log-tags")
650 builder.Command().Text("mkdir").Flag("-p").Text(etcPath.String())
651 cmd := builder.Command().BuiltTool("merge-event-log-tags").
652 FlagWithArg("-o ", eventLogtagsPath.String()).
653 FlagWithInput("-m ", android.MergedLogtagsPath(ctx))
654
655 for _, path := range android.SortedKeys(logtagsFilePaths) {
656 cmd.Text(path)
657 }
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900658
659 f.appendToEntry(ctx, eventLogtagsPath)
Inseob Kimb7b84572024-04-30 10:51:47 +0900660}
661
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900662type partition interface {
663 PartitionType() string
664}
665
Cole Faust9a24d902024-03-18 15:38:12 -0700666func (f *filesystem) PartitionType() string {
667 return proptools.StringDefault(f.properties.Partition_type, "system")
668}
669
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900670var _ partition = (*filesystem)(nil)
671
Jiyong Park65c49f52020-11-24 14:23:26 +0900672var _ android.AndroidMkEntriesProvider = (*filesystem)(nil)
673
674// Implements android.AndroidMkEntriesProvider
675func (f *filesystem) AndroidMkEntries() []android.AndroidMkEntries {
676 return []android.AndroidMkEntries{android.AndroidMkEntries{
677 Class: "ETC",
678 OutputFile: android.OptionalPathForPath(f.output),
679 ExtraEntries: []android.AndroidMkExtraEntriesFunc{
Colin Crossaa255532020-07-03 13:18:24 -0700680 func(ctx android.AndroidMkExtraEntriesContext, entries *android.AndroidMkEntries) {
Colin Crossc68db4b2021-11-11 18:59:15 -0800681 entries.SetString("LOCAL_MODULE_PATH", f.installDir.String())
Jiyong Park65c49f52020-11-24 14:23:26 +0900682 entries.SetString("LOCAL_INSTALLED_MODULE_STEM", f.installFileName())
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900683 entries.SetString("LOCAL_FILESYSTEM_FILELIST", f.fileListFile.String())
Jiyong Park65c49f52020-11-24 14:23:26 +0900684 },
685 },
686 }}
Jiyong Park6f0f6882020-11-12 13:14:30 +0900687}
Jiyong Park12a719c2021-01-07 15:31:24 +0900688
689// Filesystem is the public interface for the filesystem struct. Currently, it's only for the apex
690// package to have access to the output file.
691type Filesystem interface {
692 android.Module
693 OutputPath() android.Path
Jiyong Park972e06c2021-03-15 23:32:49 +0900694
695 // Returns the output file that is signed by avbtool. If this module is not signed, returns
696 // nil.
697 SignedOutputPath() android.Path
Jiyong Park12a719c2021-01-07 15:31:24 +0900698}
699
700var _ Filesystem = (*filesystem)(nil)
701
702func (f *filesystem) OutputPath() android.Path {
703 return f.output
704}
Jiyong Park972e06c2021-03-15 23:32:49 +0900705
706func (f *filesystem) SignedOutputPath() android.Path {
707 if proptools.Bool(f.properties.Use_avb) {
708 return f.OutputPath()
709 }
710 return nil
711}
Jooyung Han0fbbc2b2022-03-25 12:35:46 +0900712
713// Filter the result of GatherPackagingSpecs to discard items targeting outside "system" partition.
714// Note that "apex" module installs its contents to "apex"(fake partition) as well
715// for symbol lookup by imitating "activated" paths.
716func (f *filesystem) gatherFilteredPackagingSpecs(ctx android.ModuleContext) map[string]android.PackagingSpec {
Jeongik Cha54bf8752024-02-08 10:44:37 +0900717 specs := f.PackagingBase.GatherPackagingSpecsWithFilter(ctx, f.filterPackagingSpec)
Jooyung Han0fbbc2b2022-03-25 12:35:46 +0900718 return specs
719}
Jooyung Han65f402b2022-04-21 14:24:04 +0900720
721func sha1sum(values []string) string {
722 h := sha256.New()
723 for _, value := range values {
724 io.WriteString(h, value)
725 }
726 return fmt.Sprintf("%x", h.Sum(nil))
727}
Jooyung Hane6067592023-03-16 13:11:17 +0900728
729// Base cc.UseCoverage
730
731var _ cc.UseCoverage = (*filesystem)(nil)
732
Colin Crosse1a85552024-06-14 12:17:37 -0700733func (*filesystem) IsNativeCoverageNeeded(ctx cc.IsNativeCoverageNeededContext) bool {
Jooyung Hane6067592023-03-16 13:11:17 +0900734 return ctx.Device() && ctx.DeviceConfig().NativeCoverageEnabled()
735}
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900736
737// android_filesystem_defaults
738
739type filesystemDefaults struct {
740 android.ModuleBase
741 android.DefaultsModuleBase
742
743 properties filesystemDefaultsProperties
744}
745
746type filesystemDefaultsProperties struct {
747 // Identifies which partition this is for //visibility:any_system_image (and others) visibility
748 // checks, and will be used in the future for API surface checks.
749 Partition_type *string
750}
751
752// android_filesystem_defaults is a default module for android_filesystem and android_system_image
753func filesystemDefaultsFactory() android.Module {
754 module := &filesystemDefaults{}
755 module.AddProperties(&module.properties)
756 module.AddProperties(&android.PackagingProperties{})
757 android.InitDefaultsModule(module)
758 return module
759}
760
761func (f *filesystemDefaults) PartitionType() string {
762 return proptools.StringDefault(f.properties.Partition_type, "system")
763}
764
765var _ partition = (*filesystemDefaults)(nil)
766
767func (f *filesystemDefaults) GenerateAndroidBuildActions(ctx android.ModuleContext) {
768 validatePartitionType(ctx, f)
769}