blob: 35fdd00a32fd0dba9cafeb1099b454b434683284 [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"
Cole Fauste03ab892025-01-17 13:55:04 -080023 "sort"
Nikita Ioffe2c8cdc62024-03-27 22:19:30 +000024 "strconv"
Inseob Kim14199b02021-02-09 21:18:31 +090025 "strings"
Jiyong Park6f0f6882020-11-12 13:14:30 +090026
27 "android/soong/android"
Jooyung Hane6067592023-03-16 13:11:17 +090028 "android/soong/cc"
Spandan Das71be42d2024-11-20 18:34:16 +000029 "android/soong/java"
Spandan Das92631882024-10-28 22:49:38 +000030 "android/soong/linkerconfig"
Jiyong Park65b62242020-11-25 12:44:59 +090031
32 "github.com/google/blueprint"
Jiyong Park71baa762021-01-18 21:11:03 +090033 "github.com/google/blueprint/proptools"
Jiyong Park6f0f6882020-11-12 13:14:30 +090034)
35
Cole Faust1dcf9e42025-02-19 17:23:34 -080036var pctx = android.NewPackageContext("android/soong/filesystem")
37
Jiyong Park6f0f6882020-11-12 13:14:30 +090038func init() {
Jooyung Han9706cbc2021-04-15 22:43:48 +090039 registerBuildComponents(android.InitRegistrationContext)
Spandan Das71be42d2024-11-20 18:34:16 +000040 registerMutators(android.InitRegistrationContext)
Jihoon Kangf67b7de2025-02-12 01:01:09 +000041 pctx.HostBinToolVariable("fileslist", "fileslist")
Spandan Dasdd262fb2025-02-13 00:15:59 +000042 pctx.HostBinToolVariable("fs_config", "fs_config")
Cole Faust1dcf9e42025-02-19 17:23:34 -080043 pctx.HostBinToolVariable("symbols_map", "symbols_map")
Jooyung Han9706cbc2021-04-15 22:43:48 +090044}
45
46func registerBuildComponents(ctx android.RegistrationContext) {
Cole Faust92ccbe22024-10-03 14:38:37 -070047 ctx.RegisterModuleType("android_filesystem", FilesystemFactory)
Jiyong Parkf46b1af2024-04-05 18:13:33 +090048 ctx.RegisterModuleType("android_filesystem_defaults", filesystemDefaultsFactory)
Jihoon Kang98047cf2024-10-02 17:13:54 +000049 ctx.RegisterModuleType("android_system_image", SystemImageFactory)
Jiyong Parkbc485482022-11-15 22:31:49 +090050 ctx.RegisterModuleType("avb_add_hash_footer", avbAddHashFooterFactory)
Inseob Kim87230e62023-11-22 18:55:07 +090051 ctx.RegisterModuleType("avb_add_hash_footer_defaults", avbAddHashFooterDefaultsFactory)
Alice Wang000e3a32023-01-03 16:11:20 +000052 ctx.RegisterModuleType("avb_gen_vbmeta_image", avbGenVbmetaImageFactory)
Inseob Kim87230e62023-11-22 18:55:07 +090053 ctx.RegisterModuleType("avb_gen_vbmeta_image_defaults", avbGenVbmetaImageDefaultsFactory)
Jiyong Park6f0f6882020-11-12 13:14:30 +090054}
55
Spandan Das71be42d2024-11-20 18:34:16 +000056func registerMutators(ctx android.RegistrationContext) {
57 ctx.PostDepsMutators(func(ctx android.RegisterMutatorsContext) {
58 ctx.BottomUp("add_autogenerated_rro_deps", addAutogeneratedRroDeps)
59 })
60}
61
Jihoon Kangf67b7de2025-02-12 01:01:09 +000062var (
63 // Remember to add referenced files to implicits!
64 textFileProcessorRule = pctx.AndroidStaticRule("text_file_processing", blueprint.RuleParams{
65 Command: "build/soong/scripts/text_file_processor.py $in $out",
66 CommandDeps: []string{"build/soong/scripts/text_file_processor.py"},
67 })
68
69 // Remember to add the output image file as an implicit dependency!
70 installedFilesJsonRule = pctx.AndroidStaticRule("installed_files_json", blueprint.RuleParams{
71 Command: `${fileslist} ${rootDir} > ${out}`,
72 CommandDeps: []string{"${fileslist}"},
73 }, "rootDir")
74
75 installedFilesTxtRule = pctx.AndroidStaticRule("installed_files_txt", blueprint.RuleParams{
76 Command: `build/make/tools/fileslist_util.py -c ${in} > ${out}`,
77 CommandDeps: []string{"build/make/tools/fileslist_util.py"},
78 })
Spandan Dasdd262fb2025-02-13 00:15:59 +000079 fsConfigRule = pctx.AndroidStaticRule("fs_config_rule", blueprint.RuleParams{
80 Command: `(cd ${rootDir}; find . -type d | sed 's,$$,/,'; find . \! -type d) | cut -c 3- | sort | sed 's,^,${prefix},' | ${fs_config} -C -D ${rootDir} -R "${prefix}" > ${out}`,
81 CommandDeps: []string{"${fs_config}"},
82 }, "rootDir", "prefix")
Jihoon Kangf67b7de2025-02-12 01:01:09 +000083)
Cole Fauste1676122024-12-03 17:32:25 -080084
Jiyong Park6f0f6882020-11-12 13:14:30 +090085type filesystem struct {
86 android.ModuleBase
87 android.PackagingBase
Jiyong Parkf46b1af2024-04-05 18:13:33 +090088 android.DefaultableModuleBase
Jiyong Park65c49f52020-11-24 14:23:26 +090089
Jihoon Kang98047cf2024-10-02 17:13:54 +000090 properties FilesystemProperties
Jiyong Park71baa762021-01-18 21:11:03 +090091
Cole Faust4e9f5922024-11-13 16:09:23 -080092 output android.Path
Jiyong Park65c49f52020-11-24 14:23:26 +090093 installDir android.InstallPath
Jooyung Han0fbbc2b2022-03-25 12:35:46 +090094
Cole Faust4e9f5922024-11-13 16:09:23 -080095 fileListFile android.Path
Kiyoung Kim99a954d2024-06-21 14:22:20 +090096
97 // Keeps the entries installed from this filesystem
Jooyung Han0fbbc2b2022-03-25 12:35:46 +090098 entries []string
Kiyoung Kim67118212024-11-07 13:23:44 +090099
100 filesystemBuilder filesystemBuilder
Spandan Dasf12ff9b2025-02-12 22:27:43 +0000101
102 selinuxFc android.Path
Jiyong Park6f0f6882020-11-12 13:14:30 +0900103}
104
Kiyoung Kim67118212024-11-07 13:23:44 +0900105type filesystemBuilder interface {
Cole Faust19fbb072025-01-30 18:19:29 -0800106 BuildLinkerConfigFile(ctx android.ModuleContext, builder *android.RuleBuilder, rebasedDir android.OutputPath, fullInstallPaths *[]FullInstallPathInfo)
Kiyoung Kim67118212024-11-07 13:23:44 +0900107 // Function that filters PackagingSpec in PackagingBase.GatherPackagingSpecs()
108 FilterPackagingSpec(spec android.PackagingSpec) bool
Inseob Kim3c0a0422024-11-05 17:21:37 +0900109 // Function that modifies PackagingSpec in PackagingBase.GatherPackagingSpecs() to customize.
110 // For example, GSI system.img contains system_ext and product artifacts and their
111 // relPathInPackage need to be rebased to system/system_ext and system/system_product.
112 ModifyPackagingSpec(spec *android.PackagingSpec)
Kiyoung Kim23be5bb2024-11-27 00:50:30 +0000113
114 // Function to check if the filesystem should not use `vintf_fragments` property,
115 // but use `vintf_fragment` module type instead
116 ShouldUseVintfFragmentModuleOnly() bool
Kiyoung Kim67118212024-11-07 13:23:44 +0900117}
118
119var _ filesystemBuilder = (*filesystem)(nil)
120
Spandan Das69464c32024-10-25 20:08:06 +0000121type SymlinkDefinition struct {
Inseob Kim14199b02021-02-09 21:18:31 +0900122 Target *string
123 Name *string
124}
125
Jihoon Kang0a453892024-12-09 22:16:26 +0000126// CopyWithNamePrefix returns a new [SymlinkDefinition] with prefix added to Name.
127func (s *SymlinkDefinition) CopyWithNamePrefix(prefix string) SymlinkDefinition {
128 return SymlinkDefinition{
129 Target: s.Target,
130 Name: proptools.StringPtr(filepath.Join(prefix, proptools.String(s.Name))),
131 }
132}
133
Jihoon Kang98047cf2024-10-02 17:13:54 +0000134type FilesystemProperties struct {
Jiyong Park71baa762021-01-18 21:11:03 +0900135 // When set to true, sign the image with avbtool. Default is false.
136 Use_avb *bool
137
138 // Path to the private key that avbtool will use to sign this filesystem image.
139 // TODO(jiyong): allow apex_key to be specified here
140 Avb_private_key *string `android:"path"`
141
Shikha Panwar01403bb2022-12-22 12:22:57 +0000142 // Signing algorithm for avbtool. Default is SHA256_RSA4096.
Jiyong Park71baa762021-01-18 21:11:03 +0900143 Avb_algorithm *string
Jiyong Park11a65972021-02-01 21:09:38 +0900144
Shikha Panwar01403bb2022-12-22 12:22:57 +0000145 // Hash algorithm used for avbtool (for descriptors). This is passed as hash_algorithm to
Nikita Ioffe50fb49c2025-01-24 13:49:00 +0000146 // avbtool. Default is sha256.
Shikha Panware6f30632022-12-21 12:54:45 +0000147 Avb_hash_algorithm *string
148
Spandan Dase5c393c2024-12-12 19:25:07 +0000149 // The security patch passed to as the com.android.build.<type>.security_patch avb property.
150 Security_patch *string
151
Cole Fauste1676122024-12-03 17:32:25 -0800152 // Whether or not to use forward-error-correction codes when signing with AVB. Defaults to true.
153 Use_fec *bool
154
Nikita Ioffe2c8cdc62024-03-27 22:19:30 +0000155 // The index used to prevent rollback of the image. Only used if use_avb is true.
156 Rollback_index *int64
157
Luca Stefani9235f4c2025-02-08 12:09:34 +0100158 // Rollback index location of this image. Must be 1, 2, 3, etc.
Jihoon Kang2f0d1932025-01-17 19:22:44 +0000159 Rollback_index_location *int64
160
Jiyong Parkac4076d2021-03-15 23:21:30 +0900161 // Name of the partition stored in vbmeta desc. Defaults to the name of this module.
162 Partition_name *string
163
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000164 // Type of the filesystem. Currently, ext4, erofs, cpio, and compressed_cpio are supported. Default
Jiyong Park837cdb22021-02-05 00:17:14 +0900165 // is ext4.
Jiyong Park11a65972021-02-01 21:09:38 +0900166 Type *string
Inseob Kimcc8e5362021-02-03 14:05:24 +0900167
Cole Faust9a24d902024-03-18 15:38:12 -0700168 // Identifies which partition this is for //visibility:any_system_image (and others) visibility
169 // checks, and will be used in the future for API surface checks.
170 Partition_type *string
171
Cole Faust0d467052024-12-04 17:19:19 -0800172 // file_contexts file to make image. Currently, only ext4 is supported. These file contexts
173 // will be compiled with sefcontext_compile
Inseob Kimcc8e5362021-02-03 14:05:24 +0900174 File_contexts *string `android:"path"`
Inseob Kim2ce1b5d2021-02-15 17:01:04 +0900175
Cole Faust0d467052024-12-04 17:19:19 -0800176 // The selinux file contexts, after having already run them through sefcontext_compile
177 Precompiled_file_contexts *string `android:"path"`
178
Inseob Kim2ce1b5d2021-02-15 17:01:04 +0900179 // Base directory relative to root, to which deps are installed, e.g. "system". Default is "."
180 // (root).
181 Base_dir *string
Inseob Kim14199b02021-02-09 21:18:31 +0900182
183 // Directories to be created under root. e.g. /dev, /proc, etc.
Cole Faustd9c6a5b2024-05-21 14:54:00 -0700184 Dirs proptools.Configurable[[]string]
Inseob Kim14199b02021-02-09 21:18:31 +0900185
Jihoon Kang6da80752024-12-23 18:53:32 +0000186 // List of filesystem modules to include in creating the partition. The root directory of
187 // the provided filesystem modules are included in creating the partition.
188 // This is only supported for cpio and compressed cpio filesystem types.
189 Include_files_of []string
190
Inseob Kim14199b02021-02-09 21:18:31 +0900191 // Symbolic links to be created under root with "ln -sf <target> <name>".
Spandan Das69464c32024-10-25 20:08:06 +0000192 Symlinks []SymlinkDefinition
Jooyung Han65f402b2022-04-21 14:24:04 +0900193
194 // Seconds since unix epoch to override timestamps of file entries
195 Fake_timestamp *string
196
197 // When set, passed to mkuserimg_mke2fs --mke2fs_uuid & --mke2fs_hash_seed.
198 // Otherwise, they'll be set as random which might cause indeterministic build output.
199 Uuid *string
Inseob Kim376d72f2023-11-01 15:40:25 +0900200
201 // Mount point for this image. Default is "/"
202 Mount_point *string
Cole Faust4a2a7c92024-03-12 12:44:40 -0700203
Inseob Kimb7b84572024-04-30 10:51:47 +0900204 // When set, builds etc/event-log-tags file by merging logtags from all dependencies.
205 // Default is false
206 Build_logtags *bool
207
Justin Yun74f3f302024-05-07 14:32:14 +0900208 // Install aconfig_flags.pb file for the modules installed in this partition.
209 Gen_aconfig_flags_pb *bool
210
Inseob Kim53391842024-03-29 17:44:07 +0900211 Fsverity fsverityProperties
Cole Faust92ccbe22024-10-03 14:38:37 -0700212
213 // If this property is set to true, the filesystem will call ctx.UncheckedModule(), causing
214 // it to not be built on checkbuilds. Used for the automatic migration from make to soong
215 // build modules, where we want to emit some not-yet-working filesystems and we don't want them
216 // to be built.
217 Unchecked_module *bool `blueprint:"mutated"`
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000218
219 Erofs ErofsProperties
Jihoon Kang0d545b82024-10-11 00:21:57 +0000220
mrziwang1a6291f2024-11-07 14:29:25 -0800221 F2fs F2fsProperties
222
Spandan Das2047a4c2024-11-11 21:24:58 +0000223 Linker_config LinkerConfigProperties
Spandan Das92631882024-10-28 22:49:38 +0000224
Jihoon Kang0d545b82024-10-11 00:21:57 +0000225 // Determines if the module is auto-generated from Soong or not. If the module is
226 // auto-generated, its deps are exempted from visibility enforcement.
227 Is_auto_generated *bool
Jihoon Kang6c03c8e2024-11-18 21:30:22 +0000228
229 // Path to the dev nodes description file. This is only needed for building the ramdisk
230 // partition and should not be explicitly specified.
231 Dev_nodes_description_file *string `android:"path" blueprint:"mutated"`
Spandan Das71be42d2024-11-20 18:34:16 +0000232
233 // Additional dependencies used for building android products
234 Android_filesystem_deps AndroidFilesystemDeps
Spandan Dasc49b85e2025-01-10 00:51:25 +0000235
236 // Name of the output. Default is $(module_name).img
237 Stem *string
Jihoon Kang983dd882025-01-13 23:14:11 +0000238
239 // The size of the partition on the device. It will be a build error if this built partition
240 // image exceeds this size.
241 Partition_size *int64
Jihoon Kang6d08d922025-01-14 18:31:57 +0000242
243 // Whether to format f2fs and ext4 in a way that supports casefolding
244 Support_casefolding *bool
245
246 // Whether to format f2fs and ext4 in a way that supports project quotas
247 Support_project_quota *bool
248
249 // Whether to enable per-file compression in f2fs
250 Enable_compression *bool
Spandan Das71be42d2024-11-20 18:34:16 +0000251}
252
253type AndroidFilesystemDeps struct {
254 System *string
255 System_ext *string
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000256}
257
258// Additional properties required to generate erofs FS partitions.
259type ErofsProperties struct {
260 // Compressor and Compression level passed to mkfs.erofs. e.g. (lz4hc,9)
261 // Please see external/erofs-utils/README for complete documentation.
262 Compressor *string
263
264 // Used as --compress-hints for mkfs.erofs
265 Compress_hints *string `android:"path"`
266
267 Sparse *bool
Jiyong Park71baa762021-01-18 21:11:03 +0900268}
269
mrziwang1a6291f2024-11-07 14:29:25 -0800270// Additional properties required to generate f2fs FS partitions.
271type F2fsProperties struct {
272 Sparse *bool
273}
274
Spandan Das173256b2024-10-31 19:59:30 +0000275type LinkerConfigProperties struct {
276
277 // Build a linker.config.pb file
278 Gen_linker_config *bool
279
280 // List of files (in .json format) that will be converted to a linker config file (in .pb format).
281 // The linker config file be installed in the filesystem at /etc/linker.config.pb
282 Linker_config_srcs []string `android:"path"`
283}
284
Jiyong Park65c49f52020-11-24 14:23:26 +0900285// android_filesystem packages a set of modules and their transitive dependencies into a filesystem
286// image. The filesystem images are expected to be mounted in the target device, which means the
287// modules in the filesystem image are built for the target device (i.e. Android, not Linux host).
288// The modules are placed in the filesystem image just like they are installed to the ordinary
289// partitions like system.img. For example, cc_library modules are placed under ./lib[64] directory.
Cole Faust92ccbe22024-10-03 14:38:37 -0700290func FilesystemFactory() android.Module {
Jiyong Park6f0f6882020-11-12 13:14:30 +0900291 module := &filesystem{}
Kiyoung Kim67118212024-11-07 13:23:44 +0900292 module.filesystemBuilder = module
Cole Faust2cfe6962024-09-17 11:31:14 -0700293 initFilesystemModule(module, module)
Jiyong Parkfa616132021-04-20 11:36:40 +0900294 return module
295}
296
Cole Faust2cfe6962024-09-17 11:31:14 -0700297func initFilesystemModule(module android.DefaultableModule, filesystemModule *filesystem) {
298 module.AddProperties(&filesystemModule.properties)
299 android.InitPackageModule(filesystemModule)
300 filesystemModule.PackagingBase.DepsCollectFirstTargetOnly = true
Jihoon Kang79196c52024-10-30 18:49:47 +0000301 filesystemModule.PackagingBase.AllowHighPriorityDeps = true
Jiyong Park6f0f6882020-11-12 13:14:30 +0900302 android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900303 android.InitDefaultableModule(module)
Jihoon Kang6c03c8e2024-11-18 21:30:22 +0000304
305 android.AddLoadHook(module, func(ctx android.LoadHookContext) {
306 filesystemModule.setDevNodesDescriptionProp()
307 })
Jiyong Park6f0f6882020-11-12 13:14:30 +0900308}
309
Jihoon Kang0d545b82024-10-11 00:21:57 +0000310type depTag struct {
Jiyong Park12a719c2021-01-07 15:31:24 +0900311 blueprint.BaseDependencyTag
Jooyung Han092ef812021-03-10 15:40:34 +0900312 android.PackagingItemAlwaysDepTag
Jihoon Kang0d545b82024-10-11 00:21:57 +0000313}
314
315var dependencyTag = depTag{}
316
317type depTagWithVisibilityEnforcementBypass struct {
318 depTag
319}
320
Spandan Das71be42d2024-11-20 18:34:16 +0000321type interPartitionDepTag struct {
322 blueprint.BaseDependencyTag
323}
324
325var interPartitionDependencyTag = interPartitionDepTag{}
326
Jihoon Kang6da80752024-12-23 18:53:32 +0000327var interPartitionInstallDependencyTag = interPartitionDepTag{}
328
Jihoon Kang0d545b82024-10-11 00:21:57 +0000329var _ android.ExcludeFromVisibilityEnforcementTag = (*depTagWithVisibilityEnforcementBypass)(nil)
330
331func (t depTagWithVisibilityEnforcementBypass) ExcludeFromVisibilityEnforcement() {}
332
333var dependencyTagWithVisibilityEnforcementBypass = depTagWithVisibilityEnforcementBypass{}
Jiyong Park65b62242020-11-25 12:44:59 +0900334
Jihoon Kang6c03c8e2024-11-18 21:30:22 +0000335// ramdiskDevNodesDescription is the name of the filegroup module that provides the file that
336// contains the description of dev nodes added to the CPIO archive for the ramdisk partition.
337const ramdiskDevNodesDescription = "ramdisk_node_list"
338
339func (f *filesystem) setDevNodesDescriptionProp() {
340 if proptools.String(f.properties.Partition_name) == "ramdisk" {
341 f.properties.Dev_nodes_description_file = proptools.StringPtr(":" + ramdiskDevNodesDescription)
342 }
343}
344
Jiyong Park6f0f6882020-11-12 13:14:30 +0900345func (f *filesystem) DepsMutator(ctx android.BottomUpMutatorContext) {
Jihoon Kang0d545b82024-10-11 00:21:57 +0000346 if proptools.Bool(f.properties.Is_auto_generated) {
347 f.AddDeps(ctx, dependencyTagWithVisibilityEnforcementBypass)
348 } else {
349 f.AddDeps(ctx, dependencyTag)
350 }
Spandan Das71be42d2024-11-20 18:34:16 +0000351 if f.properties.Android_filesystem_deps.System != nil {
352 ctx.AddDependency(ctx.Module(), interPartitionDependencyTag, proptools.String(f.properties.Android_filesystem_deps.System))
353 }
354 if f.properties.Android_filesystem_deps.System_ext != nil {
355 ctx.AddDependency(ctx.Module(), interPartitionDependencyTag, proptools.String(f.properties.Android_filesystem_deps.System_ext))
356 }
Jihoon Kang6da80752024-12-23 18:53:32 +0000357 for _, partition := range f.properties.Include_files_of {
358 ctx.AddDependency(ctx.Module(), interPartitionInstallDependencyTag, partition)
359 }
Jiyong Park6f0f6882020-11-12 13:14:30 +0900360}
361
Jiyong Park11a65972021-02-01 21:09:38 +0900362type fsType int
363
364const (
365 ext4Type fsType = iota
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000366 erofsType
mrziwang1a6291f2024-11-07 14:29:25 -0800367 f2fsType
Jiyong Park11a65972021-02-01 21:09:38 +0900368 compressedCpioType
Jiyong Park837cdb22021-02-05 00:17:14 +0900369 cpioType // uncompressed
Jiyong Park11a65972021-02-01 21:09:38 +0900370 unknown
371)
372
Spandan Das7a46f6c2024-10-14 18:41:18 +0000373func (fs fsType) IsUnknown() bool {
374 return fs == unknown
375}
376
Jihoon Kangf67b7de2025-02-12 01:01:09 +0000377type InstalledFilesStruct struct {
378 Txt android.Path
379 Json android.Path
380}
381
Jihoon Kangabec3ec2025-02-19 00:55:10 +0000382type InstalledModuleInfo struct {
383 Name string
384 Variation string
385}
386
Cole Faust92ccbe22024-10-03 14:38:37 -0700387type FilesystemInfo struct {
Cole Faust44080412024-12-20 14:17:07 -0800388 // The built filesystem image
389 Output android.Path
Yu Liu0a37d422025-02-13 02:05:00 +0000390 // Returns the output file that is signed by avbtool. If this module is not signed, returns
391 // nil.
392 SignedOutputPath android.Path
Spandan Das1f0a5a12025-01-15 00:53:15 +0000393 // An additional hermetic filesystem image.
394 // e.g. this will contain inodes with pinned timestamps.
395 // This will be copied to target_files.zip
396 OutputHermetic android.Path
Cole Faust92ccbe22024-10-03 14:38:37 -0700397 // A text file containing the list of paths installed on the partition.
398 FileListFile android.Path
Cole Faust44080412024-12-20 14:17:07 -0800399 // The root staging directory used to build the output filesystem. If consuming this, make sure
400 // to add a dependency on the Output file, as you cannot add dependencies on directories
401 // in ninja.
402 RootDir android.Path
Cole Faustb36763e2025-02-18 15:21:44 -0800403 // Extra root directories that are also built into the partition. Currently only used for
404 // including the recovery partition files into the vendor_boot image.
405 ExtraRootDirs android.Paths
Cole Faust11fda332025-01-14 16:47:19 -0800406 // The rebased staging directory used to build the output filesystem. If consuming this, make
407 // sure to add a dependency on the Output file, as you cannot add dependencies on directories
408 // in ninja. In many cases this is the same as RootDir, only in the system partition is it
409 // different. There, it points to the "system" sub-directory of RootDir.
410 RebasedDir android.Path
Spandan Das33c9c472025-01-14 19:26:23 +0000411 // A text file with block data of the .img file
412 // This is an implicit output of `build_image`
413 MapFile android.Path
Cole Faust11fda332025-01-14 16:47:19 -0800414 // Name of the module that produced this FilesystemInfo origionally. (though it may be
415 // re-exported by super images or boot images)
416 ModuleName string
Cole Faust74ee4e02025-01-16 14:55:35 -0800417 // The property file generated by this module and passed to build_image.
418 // It's exported here so that system_other can reuse system's property file.
419 BuildImagePropFile android.Path
420 // Paths to all the tools referenced inside of the build image property file.
421 BuildImagePropFileDeps android.Paths
Cole Faustb8e280f2025-01-16 16:33:26 -0800422 // Packaging specs to be installed on the system_other image, for the initial boot's dexpreopt.
423 SpecsForSystemOther map[string]android.PackagingSpec
Cole Faust19fbb072025-01-30 18:19:29 -0800424
425 FullInstallPaths []FullInstallPathInfo
Jihoon Kangf67b7de2025-02-12 01:01:09 +0000426
427 // Installed files list
428 InstalledFiles InstalledFilesStruct
Spandan Dasd71af182025-02-12 18:03:29 +0000429
430 // Path to compress hints file for erofs filesystems
431 // This will be nil for other fileystems like ext4
432 ErofsCompressHints android.Path
Spandan Dasf12ff9b2025-02-12 22:27:43 +0000433
434 SelinuxFc android.Path
Spandan Dasdd262fb2025-02-13 00:15:59 +0000435
436 FilesystemConfig android.Path
Jihoon Kangabec3ec2025-02-19 00:55:10 +0000437
438 Owners []InstalledModuleInfo
Spandan Das447a0ab2025-03-04 23:10:19 +0000439
440 UseAvb bool
Cole Faust19fbb072025-01-30 18:19:29 -0800441}
442
443// FullInstallPathInfo contains information about the "full install" paths of all the files
444// inside this partition. The full install paths are the files installed in
445// out/target/product/<device>/<partition>. This is essentially legacy behavior, maintained for
446// tools like adb sync and adevice, but we should update them to query the build system for the
447// installed files no matter where they are.
448type FullInstallPathInfo struct {
449 // RequiresFullInstall tells us if the origional module did the install to FullInstallPath
450 // already. If it's false, the android_device module needs to emit the install rule.
451 RequiresFullInstall bool
452 // The "full install" paths for the files in this filesystem. This is the paths in the
453 // out/target/product/<device>/<partition> folder. They're not used by this filesystem,
454 // but can be depended on by the top-level android_device module to cause the staging
455 // directories to be built.
456 FullInstallPath android.InstallPath
457
458 // The file that's copied to FullInstallPath. May be nil if SymlinkTarget is set or IsDir is
459 // true.
460 SourcePath android.Path
461
462 // The target of the symlink, if this file is a symlink.
463 SymlinkTarget string
464
465 // If this file is a directory. Only used for empty directories, which are mostly mount points.
466 IsDir bool
Cole Faust92ccbe22024-10-03 14:38:37 -0700467}
468
469var FilesystemProvider = blueprint.NewProvider[FilesystemInfo]()
470
Yu Liu71f1ea32025-02-26 23:39:20 +0000471type FilesystemDefaultsInfo struct{}
Yu Liufc8d5c12025-01-09 00:19:06 +0000472
473var FilesystemDefaultsInfoProvider = blueprint.NewProvider[FilesystemDefaultsInfo]()
474
Spandan Das7a46f6c2024-10-14 18:41:18 +0000475func GetFsTypeFromString(ctx android.EarlyModuleContext, typeStr string) fsType {
Jiyong Park11a65972021-02-01 21:09:38 +0900476 switch typeStr {
477 case "ext4":
478 return ext4Type
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000479 case "erofs":
480 return erofsType
mrziwang1a6291f2024-11-07 14:29:25 -0800481 case "f2fs":
482 return f2fsType
Jiyong Park11a65972021-02-01 21:09:38 +0900483 case "compressed_cpio":
484 return compressedCpioType
Jiyong Park837cdb22021-02-05 00:17:14 +0900485 case "cpio":
486 return cpioType
Jiyong Park11a65972021-02-01 21:09:38 +0900487 default:
Jiyong Park11a65972021-02-01 21:09:38 +0900488 return unknown
489 }
490}
491
Spandan Das7a46f6c2024-10-14 18:41:18 +0000492func (f *filesystem) fsType(ctx android.ModuleContext) fsType {
493 typeStr := proptools.StringDefault(f.properties.Type, "ext4")
494 fsType := GetFsTypeFromString(ctx, typeStr)
495 if fsType == unknown {
496 ctx.PropertyErrorf("type", "%q not supported", typeStr)
497 }
498 return fsType
499}
500
Jiyong Park65c49f52020-11-24 14:23:26 +0900501func (f *filesystem) installFileName() string {
Spandan Dasc49b85e2025-01-10 00:51:25 +0000502 return proptools.StringDefault(f.properties.Stem, f.BaseModuleName()+".img")
Jiyong Park65c49f52020-11-24 14:23:26 +0900503}
504
Inseob Kim53391842024-03-29 17:44:07 +0900505func (f *filesystem) partitionName() string {
506 return proptools.StringDefault(f.properties.Partition_name, f.Name())
507}
508
Kiyoung Kim67118212024-11-07 13:23:44 +0900509func (f *filesystem) FilterPackagingSpec(ps android.PackagingSpec) bool {
Jiyong Park7e7d4af2024-05-01 12:36:10 +0000510 // Filesystem module respects the installation semantic. A PackagingSpec from a module with
511 // IsSkipInstall() is skipped.
Cole Faust76a6e952024-11-07 16:56:45 -0800512 if ps.SkipInstall() {
513 return false
Spandan Das6d056502024-10-21 15:40:32 +0000514 }
Cole Faust0d3fd562025-01-31 13:17:58 -0800515 // "apex" is a fake partition used to install files in out/target/product/<device>/apex/.
516 // Don't include these files in the partition. We should also look into removing the following
517 // TODO to check the PackagingSpec's partition against this filesystem's partition for all
518 // modules, not just autogenerated ones, which will fix this as well.
519 if ps.Partition() == "apex" {
520 return false
521 }
Cole Faust76a6e952024-11-07 16:56:45 -0800522 if proptools.Bool(f.properties.Is_auto_generated) { // TODO (spandandas): Remove this.
523 pt := f.PartitionType()
Cole Faustc88cff12024-11-12 13:24:05 -0800524 return ps.Partition() == pt || strings.HasPrefix(ps.Partition(), pt+"/")
Cole Faust76a6e952024-11-07 16:56:45 -0800525 }
526 return true
Jiyong Park7e7d4af2024-05-01 12:36:10 +0000527}
528
Inseob Kim3c0a0422024-11-05 17:21:37 +0900529func (f *filesystem) ModifyPackagingSpec(ps *android.PackagingSpec) {
Cole Faustc88cff12024-11-12 13:24:05 -0800530 // Sometimes, android.modulePartition() returns a path with >1 path components.
531 // This makes the partition field of packagingSpecs have multiple components, like
532 // "system/product". Right now, the filesystem module doesn't look at the partition field
533 // when deciding what path to install the file under, only the RelPathInPackage field, so
534 // we move the later path components from partition to relPathInPackage. This should probably
535 // be revisited in the future.
536 prefix := f.PartitionType() + "/"
537 if strings.HasPrefix(ps.Partition(), prefix) {
538 subPartition := strings.TrimPrefix(ps.Partition(), prefix)
539 ps.SetPartition(f.PartitionType())
540 ps.SetRelPathInPackage(filepath.Join(subPartition, ps.RelPathInPackage()))
541 }
Inseob Kim3c0a0422024-11-05 17:21:37 +0900542}
543
Jihoon Kangf67b7de2025-02-12 01:01:09 +0000544func buildInstalledFiles(ctx android.ModuleContext, partition string, rootDir android.Path, image android.Path) (txt android.ModuleOutPath, json android.ModuleOutPath) {
545 fileName := "installed-files"
546 if len(partition) > 0 {
547 fileName += fmt.Sprintf("-%s", partition)
548 }
549 txt = android.PathForModuleOut(ctx, fmt.Sprintf("%s.txt", fileName))
550 json = android.PathForModuleOut(ctx, fmt.Sprintf("%s.json", fileName))
551
552 ctx.Build(pctx, android.BuildParams{
553 Rule: installedFilesJsonRule,
554 Implicit: image,
555 Output: json,
556 Description: "Installed file list json",
557 Args: map[string]string{
558 "rootDir": rootDir.String(),
559 },
560 })
561
562 ctx.Build(pctx, android.BuildParams{
563 Rule: installedFilesTxtRule,
564 Input: json,
565 Output: txt,
566 Description: "Installed file list txt",
567 })
568
569 return txt, json
570}
571
Jiyong Park6f0f6882020-11-12 13:14:30 +0900572func (f *filesystem) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900573 validatePartitionType(ctx, f)
Kiyoung Kim23be5bb2024-11-27 00:50:30 +0000574 if f.filesystemBuilder.ShouldUseVintfFragmentModuleOnly() {
575 f.validateVintfFragments(ctx)
576 }
Jihoon Kang6da80752024-12-23 18:53:32 +0000577
578 if len(f.properties.Include_files_of) > 0 && !android.InList(f.fsType(ctx), []fsType{compressedCpioType, cpioType}) {
579 ctx.PropertyErrorf("include_files_of", "include_files_of is only supported for cpio and compressed cpio filesystem types.")
580 }
581
Cole Faust62cfaeb2025-01-15 18:06:40 -0800582 rootDir := android.PathForModuleOut(ctx, f.rootDirString()).OutputPath
583 rebasedDir := rootDir
584 if f.properties.Base_dir != nil {
585 rebasedDir = rootDir.Join(ctx, *f.properties.Base_dir)
586 }
587 builder := android.NewRuleBuilder(pctx, ctx)
588
589 // Wipe the root dir to get rid of leftover files from prior builds
590 builder.Command().Textf("rm -rf %s && mkdir -p %s", rootDir, rootDir)
591 specs := f.gatherFilteredPackagingSpecs(ctx)
Cole Faust62cfaeb2025-01-15 18:06:40 -0800592
Cole Faust19fbb072025-01-30 18:19:29 -0800593 var fullInstallPaths []FullInstallPathInfo
Cole Faust5db2f3e2025-02-19 12:49:37 -0800594 for _, specRel := range android.SortedKeys(specs) {
595 spec := specs[specRel]
Cole Faust19fbb072025-01-30 18:19:29 -0800596 fullInstallPaths = append(fullInstallPaths, FullInstallPathInfo{
597 FullInstallPath: spec.FullInstallPath(),
598 RequiresFullInstall: spec.RequiresFullInstall(),
599 SourcePath: spec.SrcPath(),
600 SymlinkTarget: spec.ToGob().SymlinkTarget,
601 })
602 }
603
604 f.entries = f.copyPackagingSpecs(ctx, builder, specs, rootDir, rebasedDir)
605 f.buildNonDepsFiles(ctx, builder, rootDir, rebasedDir, &fullInstallPaths)
606 f.buildFsverityMetadataFiles(ctx, builder, specs, rootDir, rebasedDir, &fullInstallPaths)
607 f.buildEventLogtagsFile(ctx, builder, rebasedDir, &fullInstallPaths)
608 f.buildAconfigFlagsFiles(ctx, builder, specs, rebasedDir, &fullInstallPaths)
609 f.filesystemBuilder.BuildLinkerConfigFile(ctx, builder, rebasedDir, &fullInstallPaths)
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000610 // Assemeble the staging dir and output a timestamp
611 builder.Command().Text("touch").Output(f.fileystemStagingDirTimestamp(ctx))
612 builder.Build("assemble_filesystem_staging_dir", fmt.Sprintf("Assemble filesystem staging dir %s", f.BaseModuleName()))
Cole Faust62cfaeb2025-01-15 18:06:40 -0800613
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000614 // Create a new rule builder for build_image
615 builder = android.NewRuleBuilder(pctx, ctx)
Spandan Das33c9c472025-01-14 19:26:23 +0000616 var mapFile android.Path
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000617 var outputHermetic android.WritablePath
Cole Faust74ee4e02025-01-16 14:55:35 -0800618 var buildImagePropFile android.Path
619 var buildImagePropFileDeps android.Paths
Cole Faustb36763e2025-02-18 15:21:44 -0800620 var extraRootDirs android.Paths
Jiyong Park11a65972021-02-01 21:09:38 +0900621 switch f.fsType(ctx) {
mrziwang1a6291f2024-11-07 14:29:25 -0800622 case ext4Type, erofsType, f2fsType:
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000623 buildImagePropFile, buildImagePropFileDeps = f.buildPropFile(ctx)
624 output := android.PathForModuleOut(ctx, f.installFileName())
625 f.buildImageUsingBuildImage(ctx, builder, buildImageParams{rootDir, buildImagePropFile, buildImagePropFileDeps, output})
626 f.output = output
627 // Create the hermetic img file using a separate rule builder so that it can be built independently
628 hermeticBuilder := android.NewRuleBuilder(pctx, ctx)
629 outputHermetic = android.PathForModuleOut(ctx, "for_target_files", f.installFileName())
630 propFileHermetic := f.propFileForHermeticImg(ctx, hermeticBuilder, buildImagePropFile)
631 f.buildImageUsingBuildImage(ctx, hermeticBuilder, buildImageParams{rootDir, propFileHermetic, buildImagePropFileDeps, outputHermetic})
Spandan Das33c9c472025-01-14 19:26:23 +0000632 mapFile = f.getMapFile(ctx)
Jiyong Park11a65972021-02-01 21:09:38 +0900633 case compressedCpioType:
Cole Faustb36763e2025-02-18 15:21:44 -0800634 f.output, extraRootDirs = f.buildCpioImage(ctx, builder, rootDir, true)
Jiyong Park837cdb22021-02-05 00:17:14 +0900635 case cpioType:
Cole Faustb36763e2025-02-18 15:21:44 -0800636 f.output, extraRootDirs = f.buildCpioImage(ctx, builder, rootDir, false)
Jiyong Park11a65972021-02-01 21:09:38 +0900637 default:
638 return
639 }
640
641 f.installDir = android.PathForModuleInstall(ctx, "etc")
642 ctx.InstallFile(f.installDir, f.installFileName(), f.output)
mrziwang555d1332024-06-07 11:15:33 -0700643 ctx.SetOutputFiles([]android.Path{f.output}, "")
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900644
Jihoon Kang6da80752024-12-23 18:53:32 +0000645 if f.partitionName() == "recovery" {
646 rootDir = rootDir.Join(ctx, "root")
647 }
648
Cole Faust4e9f5922024-11-13 16:09:23 -0800649 fileListFile := android.PathForModuleOut(ctx, "fileList")
650 android.WriteFileRule(ctx, fileListFile, f.installedFilesList())
Cole Faust92ccbe22024-10-03 14:38:37 -0700651
Jihoon Kangf67b7de2025-02-12 01:01:09 +0000652 partitionName := f.partitionName()
653 if partitionName == "system" {
654 partitionName = ""
655 }
656 installedFileTxt, installedFileJson := buildInstalledFiles(ctx, partitionName, rootDir, f.output)
657
Spandan Dasd71af182025-02-12 18:03:29 +0000658 var erofsCompressHints android.Path
659 if f.properties.Erofs.Compress_hints != nil {
660 erofsCompressHints = android.PathForModuleSrc(ctx, *f.properties.Erofs.Compress_hints)
661 }
662
Spandan Das33c9c472025-01-14 19:26:23 +0000663 fsInfo := FilesystemInfo{
Yu Liu0a37d422025-02-13 02:05:00 +0000664 Output: f.OutputPath(),
665 SignedOutputPath: f.SignedOutputPath(),
Cole Faust74ee4e02025-01-16 14:55:35 -0800666 OutputHermetic: outputHermetic,
667 FileListFile: fileListFile,
668 RootDir: rootDir,
Cole Faustb36763e2025-02-18 15:21:44 -0800669 ExtraRootDirs: extraRootDirs,
Cole Faust74ee4e02025-01-16 14:55:35 -0800670 RebasedDir: rebasedDir,
671 MapFile: mapFile,
672 ModuleName: ctx.ModuleName(),
673 BuildImagePropFile: buildImagePropFile,
674 BuildImagePropFileDeps: buildImagePropFileDeps,
Cole Faustb8e280f2025-01-16 16:33:26 -0800675 SpecsForSystemOther: f.systemOtherFiles(ctx),
Cole Faust19fbb072025-01-30 18:19:29 -0800676 FullInstallPaths: fullInstallPaths,
Jihoon Kangf67b7de2025-02-12 01:01:09 +0000677 InstalledFiles: InstalledFilesStruct{
678 Txt: installedFileTxt,
679 Json: installedFileJson,
680 },
Spandan Dasd71af182025-02-12 18:03:29 +0000681 ErofsCompressHints: erofsCompressHints,
Spandan Dasf12ff9b2025-02-12 22:27:43 +0000682 SelinuxFc: f.selinuxFc,
Spandan Dasdd262fb2025-02-13 00:15:59 +0000683 FilesystemConfig: f.generateFilesystemConfig(ctx, rootDir, rebasedDir),
Jihoon Kangabec3ec2025-02-19 00:55:10 +0000684 Owners: f.gatherOwners(specs),
Spandan Das447a0ab2025-03-04 23:10:19 +0000685 UseAvb: proptools.Bool(f.properties.Use_avb),
Spandan Das1f0a5a12025-01-15 00:53:15 +0000686 }
Spandan Das33c9c472025-01-14 19:26:23 +0000687
688 android.SetProvider(ctx, FilesystemProvider, fsInfo)
Spandan Das3ec6d062025-01-09 19:37:47 +0000689
Yu Liu71f1ea32025-02-26 23:39:20 +0000690 android.SetProvider(ctx, android.PartitionTypeInfoProvider, android.PartitionTypeInfo{
691 PartitionType: f.PartitionType(),
692 })
693
Cole Faust4e9f5922024-11-13 16:09:23 -0800694 f.fileListFile = fileListFile
Cole Faust92ccbe22024-10-03 14:38:37 -0700695
696 if proptools.Bool(f.properties.Unchecked_module) {
697 ctx.UncheckedModule()
698 }
Jihoon Kang2f0d1932025-01-17 19:22:44 +0000699
700 f.setVbmetaPartitionProvider(ctx)
701}
702
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000703func (f *filesystem) fileystemStagingDirTimestamp(ctx android.ModuleContext) android.WritablePath {
704 return android.PathForModuleOut(ctx, "staging_dir.timestamp")
705}
706
Spandan Dasdd262fb2025-02-13 00:15:59 +0000707func (f *filesystem) generateFilesystemConfig(ctx android.ModuleContext, rootDir android.Path, rebasedDir android.Path) android.Path {
708 rootDirString := rootDir.String()
709 prefix := f.partitionName() + "/"
710 if f.partitionName() == "system" {
711 rootDirString = rebasedDir.String()
712 }
713 if f.partitionName() == "ramdisk" || f.partitionName() == "recovery" {
714 // Hardcoded to match make behavior.
715 // https://cs.android.com/android/_/android/platform/build/+/2a0ef42a432d4da00201e8eb7697dcaa68fd2389:core/Makefile;l=6957-6962;drc=9ea8ad9232cef4d0a24d70133b1b9d2ce2defe5f;bpv=1;bpt=0
716 prefix = ""
717 }
718 out := android.PathForModuleOut(ctx, "filesystem_config.txt")
719 ctx.Build(pctx, android.BuildParams{
720 Rule: fsConfigRule,
721 Input: f.fileystemStagingDirTimestamp(ctx), // assemble the staging directory
722 Output: out,
723 Args: map[string]string{
724 "rootDir": rootDirString,
725 "prefix": prefix,
726 },
727 })
728 return out
729}
730
Jihoon Kang2f0d1932025-01-17 19:22:44 +0000731func (f *filesystem) setVbmetaPartitionProvider(ctx android.ModuleContext) {
732 var extractedPublicKey android.ModuleOutPath
733 if f.properties.Avb_private_key != nil {
734 key := android.PathForModuleSrc(ctx, proptools.String(f.properties.Avb_private_key))
735 extractedPublicKey = android.PathForModuleOut(ctx, f.partitionName()+".avbpubkey")
736 ctx.Build(pctx, android.BuildParams{
737 Rule: extractPublicKeyRule,
738 Input: key,
739 Output: extractedPublicKey,
740 })
741 }
742
743 var ril int
744 if f.properties.Rollback_index_location != nil {
745 ril = proptools.Int(f.properties.Rollback_index_location)
746 }
747
748 android.SetProvider(ctx, vbmetaPartitionProvider, vbmetaPartitionInfo{
749 Name: f.partitionName(),
750 RollbackIndexLocation: ril,
751 PublicKey: extractedPublicKey,
752 Output: f.output,
753 })
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900754}
755
Spandan Das33c9c472025-01-14 19:26:23 +0000756func (f *filesystem) getMapFile(ctx android.ModuleContext) android.WritablePath {
757 // create the filepath by replacing the extension of the corresponding img file
758 return android.PathForModuleOut(ctx, f.installFileName()).ReplaceExtension(ctx, "map")
759}
760
Kiyoung Kim23be5bb2024-11-27 00:50:30 +0000761func (f *filesystem) validateVintfFragments(ctx android.ModuleContext) {
762 visitedModule := map[string]bool{}
763 packagingSpecs := f.gatherFilteredPackagingSpecs(ctx)
764
765 moduleInFileSystem := func(mod android.Module) bool {
766 for _, ps := range android.OtherModuleProviderOrDefault(
767 ctx, mod, android.InstallFilesProvider).PackagingSpecs {
768 if _, ok := packagingSpecs[ps.RelPathInPackage()]; ok {
769 return true
770 }
771 }
772 return false
773 }
774
775 ctx.WalkDeps(func(child, parent android.Module) bool {
776 if visitedModule[child.Name()] {
777 return false
778 }
779 if !moduleInFileSystem(child) {
780 visitedModule[child.Name()] = true
781 return true
782 }
783 if vintfFragments := child.VintfFragments(ctx); vintfFragments != nil {
784 ctx.PropertyErrorf(
785 "vintf_fragments",
786 "Module %s is referenced by soong-defined filesystem %s with property vintf_fragments(%s) in use."+
787 " Use vintf_fragment_modules property instead.",
788 child.Name(),
789 f.BaseModuleName(),
790 strings.Join(vintfFragments, ", "),
791 )
792 }
793 visitedModule[child.Name()] = true
794 return true
795 })
796}
797
Cole Faust4e9f5922024-11-13 16:09:23 -0800798func (f *filesystem) appendToEntry(ctx android.ModuleContext, installedFile android.Path) {
Spandan Das420e16a2024-12-11 18:10:52 +0000799 partitionBaseDir := android.PathForModuleOut(ctx, f.rootDirString(), proptools.String(f.properties.Base_dir)).String() + "/"
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900800
801 relPath, inTargetPartition := strings.CutPrefix(installedFile.String(), partitionBaseDir)
802 if inTargetPartition {
803 f.entries = append(f.entries, relPath)
804 }
805}
806
807func (f *filesystem) installedFilesList() string {
808 installedFilePaths := android.FirstUniqueStrings(f.entries)
809 slices.Sort(installedFilePaths)
810
811 return strings.Join(installedFilePaths, "\n")
Jiyong Park11a65972021-02-01 21:09:38 +0900812}
813
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900814func validatePartitionType(ctx android.ModuleContext, p partition) {
815 if !android.InList(p.PartitionType(), validPartitions) {
816 ctx.PropertyErrorf("partition_type", "partition_type must be one of %s, found: %s", validPartitions, p.PartitionType())
817 }
818
Yu Liufc8d5c12025-01-09 00:19:06 +0000819 ctx.VisitDirectDepsProxyWithTag(android.DefaultsDepTag, func(m android.ModuleProxy) {
Yu Liu71f1ea32025-02-26 23:39:20 +0000820 if _, ok := android.OtherModuleProvider(ctx, m, FilesystemDefaultsInfoProvider); ok {
821 partitionInfo := android.OtherModuleProviderOrDefault(ctx, m, android.PartitionTypeInfoProvider)
822 if p.PartitionType() != partitionInfo.PartitionType {
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900823 ctx.PropertyErrorf("partition_type",
824 "%s doesn't match with the partition type %s of the filesystem default module %s",
Yu Liu71f1ea32025-02-26 23:39:20 +0000825 p.PartitionType(), partitionInfo.PartitionType, m.Name())
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900826 }
827 }
828 })
829}
830
Cole Faust3b806d32024-03-11 15:15:03 -0700831// Copy extra files/dirs that are not from the `deps` property to `rootDir`, checking for conflicts with files
832// already in `rootDir`.
Cole Faust19fbb072025-01-30 18:19:29 -0800833func (f *filesystem) buildNonDepsFiles(
834 ctx android.ModuleContext,
835 builder *android.RuleBuilder,
836 rootDir android.OutputPath,
837 rebasedDir android.OutputPath,
838 fullInstallPaths *[]FullInstallPathInfo,
839) {
840 rebasedPrefix, err := filepath.Rel(rootDir.String(), rebasedDir.String())
841 if err != nil || strings.HasPrefix(rebasedPrefix, "../") {
842 panic("rebasedDir could not be made relative to rootDir")
843 }
844 if !strings.HasSuffix(rebasedPrefix, "/") {
845 rebasedPrefix += "/"
846 }
847 if rebasedPrefix == "./" {
848 rebasedPrefix = ""
849 }
850
Inseob Kim14199b02021-02-09 21:18:31 +0900851 // create dirs and symlinks
Cole Faustd9c6a5b2024-05-21 14:54:00 -0700852 for _, dir := range f.properties.Dirs.GetOrDefault(ctx, nil) {
Inseob Kim14199b02021-02-09 21:18:31 +0900853 // OutputPath.Join verifies dir
854 builder.Command().Text("mkdir -p").Text(rootDir.Join(ctx, dir).String())
Cole Faust19fbb072025-01-30 18:19:29 -0800855 // Only add the fullInstallPath logic for files in the rebased dir. The root dir
856 // is harder to install to.
857 if strings.HasPrefix(dir, rebasedPrefix) {
858 *fullInstallPaths = append(*fullInstallPaths, FullInstallPathInfo{
859 FullInstallPath: android.PathForModuleInPartitionInstall(ctx, f.PartitionType(), strings.TrimPrefix(dir, rebasedPrefix)),
860 IsDir: true,
861 })
862 }
Inseob Kim14199b02021-02-09 21:18:31 +0900863 }
864
865 for _, symlink := range f.properties.Symlinks {
866 name := strings.TrimSpace(proptools.String(symlink.Name))
867 target := strings.TrimSpace(proptools.String(symlink.Target))
868
869 if name == "" {
870 ctx.PropertyErrorf("symlinks", "Name can't be empty")
871 continue
872 }
873
874 if target == "" {
875 ctx.PropertyErrorf("symlinks", "Target can't be empty")
876 continue
877 }
878
879 // OutputPath.Join verifies name. don't need to verify target.
880 dst := rootDir.Join(ctx, name)
Cole Faust3b806d32024-03-11 15:15:03 -0700881 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 +0900882 builder.Command().Text("mkdir -p").Text(filepath.Dir(dst.String()))
883 builder.Command().Text("ln -sf").Text(proptools.ShellEscape(target)).Text(dst.String())
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900884 f.appendToEntry(ctx, dst)
Cole Faust19fbb072025-01-30 18:19:29 -0800885 // Only add the fullInstallPath logic for files in the rebased dir. The root dir
886 // is harder to install to.
887 if strings.HasPrefix(name, rebasedPrefix) {
888 *fullInstallPaths = append(*fullInstallPaths, FullInstallPathInfo{
889 FullInstallPath: android.PathForModuleInPartitionInstall(ctx, f.PartitionType(), strings.TrimPrefix(name, rebasedPrefix)),
890 SymlinkTarget: target,
891 })
892 }
Inseob Kim14199b02021-02-09 21:18:31 +0900893 }
Jihoon Kang89e8a692024-12-18 19:28:33 +0000894
895 // https://cs.android.com/android/platform/superproject/main/+/main:build/make/core/Makefile;l=2835;drc=b186569ef00ff2f2a1fab28aedc75ebc32bcd67b
896 if f.partitionName() == "recovery" {
897 builder.Command().Text("mkdir -p").Text(rootDir.Join(ctx, "root/linkerconfig").String())
898 builder.Command().Text("touch").Text(rootDir.Join(ctx, "root/linkerconfig/ld.config.txt").String())
899 }
Inseob Kim2ce1b5d2021-02-15 17:01:04 +0900900}
901
Inseob Kim33f95a92024-07-11 15:44:49 +0900902func (f *filesystem) copyPackagingSpecs(ctx android.ModuleContext, builder *android.RuleBuilder, specs map[string]android.PackagingSpec, rootDir, rebasedDir android.WritablePath) []string {
903 rootDirSpecs := make(map[string]android.PackagingSpec)
904 rebasedDirSpecs := make(map[string]android.PackagingSpec)
905
906 for rel, spec := range specs {
907 if spec.Partition() == "root" {
908 rootDirSpecs[rel] = spec
909 } else {
910 rebasedDirSpecs[rel] = spec
911 }
912 }
913
914 dirsToSpecs := make(map[android.WritablePath]map[string]android.PackagingSpec)
915 dirsToSpecs[rootDir] = rootDirSpecs
916 dirsToSpecs[rebasedDir] = rebasedDirSpecs
917
Cole Fauste3845052025-02-13 12:45:35 -0800918 // Preserve timestamps for adb sync, so that this staging dir file matches the timestamp in the
919 // out/target/product staging directory.
920 return f.CopySpecsToDirs(ctx, builder, dirsToSpecs, true)
Inseob Kim33f95a92024-07-11 15:44:49 +0900921}
922
Spandan Das420e16a2024-12-11 18:10:52 +0000923func (f *filesystem) rootDirString() string {
924 return f.partitionName()
925}
926
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000927type buildImageParams struct {
928 // inputs
929 rootDir android.OutputPath
930 propFile android.Path
931 toolDeps android.Paths
932 // outputs
933 output android.WritablePath
934}
935
Cole Faust62cfaeb2025-01-15 18:06:40 -0800936func (f *filesystem) buildImageUsingBuildImage(
937 ctx android.ModuleContext,
938 builder *android.RuleBuilder,
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000939 params buildImageParams) {
Nikita Ioffe519015f2022-12-23 15:36:29 +0000940 // run host_init_verifier
941 // Ideally we should have a concept of pluggable linters that verify the generated image.
942 // While such concept is not implement this will do.
943 // TODO(b/263574231): substitute with pluggable linter.
944 builder.Command().
945 BuiltTool("host_init_verifier").
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000946 FlagWithArg("--out_system=", params.rootDir.String()+"/system")
Cole Fauste1676122024-12-03 17:32:25 -0800947
948 // Most of the time, if build_image were to call a host tool, it accepts the path to the
949 // host tool in a field in the prop file. However, it doesn't have that option for fec, which
950 // it expects to just be on the PATH. Add fec to the PATH.
951 fec := ctx.Config().HostToolPath(ctx, "fec")
952 pathToolDirs := []string{filepath.Dir(fec.String())}
953
Cole Fauste1676122024-12-03 17:32:25 -0800954 builder.Command().
955 Textf("PATH=%s:$PATH", strings.Join(pathToolDirs, ":")).
956 BuiltTool("build_image").
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000957 Text(params.rootDir.String()). // input directory
958 Input(params.propFile).
959 Implicits(params.toolDeps).
Cole Fauste1676122024-12-03 17:32:25 -0800960 Implicit(fec).
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000961 Implicit(f.fileystemStagingDirTimestamp(ctx)). // assemble the staging directory
962 Output(params.output).
963 Text(params.rootDir.String()) // directory where to find fs_config_files|dirs
Spandan Das1f0a5a12025-01-15 00:53:15 +0000964
Jihoon Kang983dd882025-01-13 23:14:11 +0000965 if f.properties.Partition_size != nil {
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000966 assertMaxImageSize(builder, params.output, *f.properties.Partition_size, false)
Jihoon Kang983dd882025-01-13 23:14:11 +0000967 }
968
Jiyong Park6f0f6882020-11-12 13:14:30 +0900969 // rootDir is not deleted. Might be useful for quick inspection.
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000970 builder.Build("build_"+params.output.String(), fmt.Sprintf("Creating filesystem %s", f.BaseModuleName()))
971}
Jiyong Park65c49f52020-11-24 14:23:26 +0900972
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000973func (f *filesystem) propFileForHermeticImg(ctx android.ModuleContext, builder *android.RuleBuilder, inputPropFile android.Path) android.Path {
974 propFilePinnedTimestamp := android.PathForModuleOut(ctx, "for_target_files", "prop")
975 builder.Command().Textf("cat").Input(inputPropFile).Flag(">").Output(propFilePinnedTimestamp).
976 Textf(" && echo use_fixed_timestamp=true >> %s", propFilePinnedTimestamp).
977 Textf(" && echo block_list=%s >> %s", f.getMapFile(ctx).String(), propFilePinnedTimestamp) // mapfile will be an implicit output
978 builder.Command().Text("touch").Output(f.getMapFile(ctx))
979 return propFilePinnedTimestamp
Jiyong Park65c49f52020-11-24 14:23:26 +0900980}
981
Cole Faust4e9f5922024-11-13 16:09:23 -0800982func (f *filesystem) buildFileContexts(ctx android.ModuleContext) android.Path {
Inseob Kimcc8e5362021-02-03 14:05:24 +0900983 builder := android.NewRuleBuilder(pctx, ctx)
984 fcBin := android.PathForModuleOut(ctx, "file_contexts.bin")
985 builder.Command().BuiltTool("sefcontext_compile").
986 FlagWithOutput("-o ", fcBin).
987 Input(android.PathForModuleSrc(ctx, proptools.String(f.properties.File_contexts)))
988 builder.Build("build_filesystem_file_contexts", fmt.Sprintf("Creating filesystem file contexts for %s", f.BaseModuleName()))
Cole Faust4e9f5922024-11-13 16:09:23 -0800989 return fcBin
Inseob Kimcc8e5362021-02-03 14:05:24 +0900990}
991
Cole Faust4e9f5922024-11-13 16:09:23 -0800992func (f *filesystem) buildPropFile(ctx android.ModuleContext) (android.Path, android.Paths) {
Jiyong Park72678312021-01-18 17:29:49 +0900993 var deps android.Paths
Cole Fauste03ab892025-01-17 13:55:04 -0800994 var lines []string
Jiyong Park72678312021-01-18 17:29:49 +0900995 addStr := func(name string, value string) {
Cole Fauste03ab892025-01-17 13:55:04 -0800996 lines = append(lines, fmt.Sprintf("%s=%s", name, value))
Jiyong Park72678312021-01-18 17:29:49 +0900997 }
998 addPath := func(name string, path android.Path) {
Cole Faustcec230a2024-03-07 15:51:12 -0800999 addStr(name, path.String())
Jiyong Park72678312021-01-18 17:29:49 +09001000 deps = append(deps, path)
1001 }
1002
Jiyong Park11a65972021-02-01 21:09:38 +09001003 // Type string that build_image.py accepts.
1004 fsTypeStr := func(t fsType) string {
1005 switch t {
Spandan Das94668822024-10-09 20:51:33 +00001006 // TODO(372522486): add more types like f2fs, erofs, etc.
Jiyong Park11a65972021-02-01 21:09:38 +09001007 case ext4Type:
1008 return "ext4"
Spandan Dasc35d6fb2024-10-10 17:51:14 +00001009 case erofsType:
1010 return "erofs"
mrziwang1a6291f2024-11-07 14:29:25 -08001011 case f2fsType:
1012 return "f2fs"
Jiyong Park11a65972021-02-01 21:09:38 +09001013 }
1014 panic(fmt.Errorf("unsupported fs type %v", t))
1015 }
1016
1017 addStr("fs_type", fsTypeStr(f.fsType(ctx)))
Inseob Kim376d72f2023-11-01 15:40:25 +09001018 addStr("mount_point", proptools.StringDefault(f.properties.Mount_point, "/"))
Jiyong Park72678312021-01-18 17:29:49 +09001019 addStr("use_dynamic_partition_size", "true")
1020 addPath("ext_mkuserimg", ctx.Config().HostToolPath(ctx, "mkuserimg_mke2fs"))
1021 // b/177813163 deps of the host tools have to be added. Remove this.
1022 for _, t := range []string{"mke2fs", "e2fsdroid", "tune2fs"} {
1023 deps = append(deps, ctx.Config().HostToolPath(ctx, t))
1024 }
1025
Jiyong Park71baa762021-01-18 21:11:03 +09001026 if proptools.Bool(f.properties.Use_avb) {
1027 addStr("avb_hashtree_enable", "true")
1028 addPath("avb_avbtool", ctx.Config().HostToolPath(ctx, "avbtool"))
1029 algorithm := proptools.StringDefault(f.properties.Avb_algorithm, "SHA256_RSA4096")
1030 addStr("avb_algorithm", algorithm)
Cole Fauste1676122024-12-03 17:32:25 -08001031 if f.properties.Avb_private_key != nil {
1032 key := android.PathForModuleSrc(ctx, *f.properties.Avb_private_key)
1033 addPath("avb_key_path", key)
1034 }
Inseob Kim53391842024-03-29 17:44:07 +09001035 addStr("partition_name", f.partitionName())
Cole Fauste1676122024-12-03 17:32:25 -08001036 avb_add_hashtree_footer_args := ""
1037 if !proptools.BoolDefault(f.properties.Use_fec, true) {
1038 avb_add_hashtree_footer_args += " --do_not_generate_fec"
1039 }
Nikita Ioffe50fb49c2025-01-24 13:49:00 +00001040 hashAlgorithm := proptools.StringDefault(f.properties.Avb_hash_algorithm, "sha256")
1041 avb_add_hashtree_footer_args += " --hash_algorithm " + hashAlgorithm
Nikita Ioffe2c8cdc62024-03-27 22:19:30 +00001042 if f.properties.Rollback_index != nil {
1043 rollbackIndex := proptools.Int(f.properties.Rollback_index)
1044 if rollbackIndex < 0 {
1045 ctx.PropertyErrorf("rollback_index", "Rollback index must be non-negative")
1046 }
1047 avb_add_hashtree_footer_args += " --rollback_index " + strconv.Itoa(rollbackIndex)
1048 }
Cole Fauste1676122024-12-03 17:32:25 -08001049 avb_add_hashtree_footer_args += fmt.Sprintf(" --prop com.android.build.%s.os_version:%s", f.partitionName(), ctx.Config().PlatformVersionLastStable())
Cole Faustefeb5c42024-12-16 10:47:26 -08001050 // We're not going to add BuildFingerPrintFile as a dep. If it changed, it's likely because
1051 // the build number changed, and we don't want to trigger rebuilds solely based on the build
1052 // number.
Cole Fauste1676122024-12-03 17:32:25 -08001053 avb_add_hashtree_footer_args += fmt.Sprintf(" --prop com.android.build.%s.fingerprint:{CONTENTS_OF:%s}", f.partitionName(), ctx.Config().BuildFingerprintFile(ctx))
Spandan Dase5c393c2024-12-12 19:25:07 +00001054 if f.properties.Security_patch != nil && proptools.String(f.properties.Security_patch) != "" {
1055 avb_add_hashtree_footer_args += fmt.Sprintf(" --prop com.android.build.%s.security_patch:%s", f.partitionName(), proptools.String(f.properties.Security_patch))
1056 }
Shikha Panware6f30632022-12-21 12:54:45 +00001057 addStr("avb_add_hashtree_footer_args", avb_add_hashtree_footer_args)
Jiyong Park71baa762021-01-18 21:11:03 +09001058 }
1059
Cole Faust0d467052024-12-04 17:19:19 -08001060 if f.properties.File_contexts != nil && f.properties.Precompiled_file_contexts != nil {
1061 ctx.ModuleErrorf("file_contexts and precompiled_file_contexts cannot both be set")
1062 } else if f.properties.File_contexts != nil {
Spandan Dasf12ff9b2025-02-12 22:27:43 +00001063 f.selinuxFc = f.buildFileContexts(ctx)
Cole Faust0d467052024-12-04 17:19:19 -08001064 } else if f.properties.Precompiled_file_contexts != nil {
Spandan Dasf12ff9b2025-02-12 22:27:43 +00001065 f.selinuxFc = android.PathForModuleSrc(ctx, *f.properties.Precompiled_file_contexts)
1066 }
1067 if f.selinuxFc != nil {
1068 addPath("selinux_fc", f.selinuxFc)
Inseob Kimcc8e5362021-02-03 14:05:24 +09001069 }
Jooyung Han65f402b2022-04-21 14:24:04 +09001070 if timestamp := proptools.String(f.properties.Fake_timestamp); timestamp != "" {
1071 addStr("timestamp", timestamp)
Spandan Dasa0ddc512025-01-06 20:23:55 +00001072 } else if ctx.Config().Getenv("USE_FIXED_TIMESTAMP_IMG_FILES") == "true" {
1073 addStr("use_fixed_timestamp", "true")
Jooyung Han65f402b2022-04-21 14:24:04 +09001074 }
Spandan Dasa0ddc512025-01-06 20:23:55 +00001075
Jooyung Han65f402b2022-04-21 14:24:04 +09001076 if uuid := proptools.String(f.properties.Uuid); uuid != "" {
1077 addStr("uuid", uuid)
1078 addStr("hash_seed", uuid)
1079 }
mrziwang1a6291f2024-11-07 14:29:25 -08001080
Jihoon Kang40551e62025-01-14 21:55:08 +00001081 // Disable sparse only when partition size is not defined. disable_sparse has the same
1082 // effect as <partition name>_disable_sparse.
1083 if f.properties.Partition_size == nil {
1084 addStr("disable_sparse", "true")
1085 }
Cole Faust43a52c72024-11-26 12:46:08 -08001086
mrziwang1a6291f2024-11-07 14:29:25 -08001087 fst := f.fsType(ctx)
1088 switch fst {
1089 case erofsType:
1090 // Add erofs properties
Cole Faust3e730972024-12-03 13:12:08 -08001091 addStr("erofs_default_compressor", proptools.StringDefault(f.properties.Erofs.Compressor, "lz4hc,9"))
1092 if f.properties.Erofs.Compress_hints != nil {
1093 src := android.PathForModuleSrc(ctx, *f.properties.Erofs.Compress_hints)
1094 addPath("erofs_default_compress_hints", src)
Spandan Dasc35d6fb2024-10-10 17:51:14 +00001095 }
1096 if proptools.BoolDefault(f.properties.Erofs.Sparse, true) {
1097 // https://source.corp.google.com/h/googleplex-android/platform/build/+/88b1c67239ca545b11580237242774b411f2fed9:core/Makefile;l=2292;bpv=1;bpt=0;drc=ea8f34bc1d6e63656b4ec32f2391e9d54b3ebb6b
1098 addStr("erofs_sparse_flag", "-s")
1099 }
mrziwang1a6291f2024-11-07 14:29:25 -08001100 case f2fsType:
1101 if proptools.BoolDefault(f.properties.F2fs.Sparse, true) {
1102 // https://source.corp.google.com/h/googleplex-android/platform/build/+/88b1c67239ca545b11580237242774b411f2fed9:core/Makefile;l=2294;drc=ea8f34bc1d6e63656b4ec32f2391e9d54b3ebb6b;bpv=1;bpt=0
1103 addStr("f2fs_sparse_flag", "-S")
1104 }
Spandan Dasc35d6fb2024-10-10 17:51:14 +00001105 }
mrziwang1a6291f2024-11-07 14:29:25 -08001106 f.checkFsTypePropertyError(ctx, fst, fsTypeStr(fst))
Spandan Dasc35d6fb2024-10-10 17:51:14 +00001107
Jihoon Kang983dd882025-01-13 23:14:11 +00001108 if f.properties.Partition_size != nil {
1109 addStr("partition_size", strconv.FormatInt(*f.properties.Partition_size, 10))
1110 }
1111
Jihoon Kang6d08d922025-01-14 18:31:57 +00001112 if proptools.BoolDefault(f.properties.Support_casefolding, false) {
1113 addStr("needs_casefold", "1")
1114 }
1115
1116 if proptools.BoolDefault(f.properties.Support_project_quota, false) {
1117 addStr("needs_projid", "1")
1118 }
1119
1120 if proptools.BoolDefault(f.properties.Enable_compression, false) {
1121 addStr("needs_compress", "1")
1122 }
1123
Cole Fauste03ab892025-01-17 13:55:04 -08001124 sort.Strings(lines)
1125
Cole Fauste1676122024-12-03 17:32:25 -08001126 propFilePreProcessing := android.PathForModuleOut(ctx, "prop_pre_processing")
Cole Fauste03ab892025-01-17 13:55:04 -08001127 android.WriteFileRule(ctx, propFilePreProcessing, strings.Join(lines, "\n"))
Cole Faust4e9f5922024-11-13 16:09:23 -08001128 propFile := android.PathForModuleOut(ctx, "prop")
Cole Fauste1676122024-12-03 17:32:25 -08001129 ctx.Build(pctx, android.BuildParams{
Cole Faustefeb5c42024-12-16 10:47:26 -08001130 Rule: textFileProcessorRule,
1131 Input: propFilePreProcessing,
1132 Output: propFile,
Cole Fauste1676122024-12-03 17:32:25 -08001133 })
Jiyong Park72678312021-01-18 17:29:49 +09001134 return propFile, deps
1135}
1136
mrziwang1a6291f2024-11-07 14:29:25 -08001137// This method checks if there is any property set for the fstype(s) other than
1138// the current fstype.
1139func (f *filesystem) checkFsTypePropertyError(ctx android.ModuleContext, t fsType, fs string) {
1140 raiseError := func(otherFsType, currentFsType string) {
1141 errMsg := fmt.Sprintf("%s is non-empty, but FS type is %s\n. Please delete %s properties if this partition should use %s\n", otherFsType, currentFsType, otherFsType, currentFsType)
1142 ctx.PropertyErrorf(otherFsType, errMsg)
1143 }
1144
1145 if t != erofsType {
1146 if f.properties.Erofs.Compressor != nil || f.properties.Erofs.Compress_hints != nil || f.properties.Erofs.Sparse != nil {
1147 raiseError("erofs", fs)
1148 }
1149 }
1150 if t != f2fsType {
1151 if f.properties.F2fs.Sparse != nil {
1152 raiseError("f2fs", fs)
1153 }
1154 }
1155}
1156
Jihoon Kang6da80752024-12-23 18:53:32 +00001157func includeFilesRootDir(ctx android.ModuleContext) (rootDirs android.Paths, partitions android.Paths) {
1158 ctx.VisitDirectDepsWithTag(interPartitionInstallDependencyTag, func(m android.Module) {
1159 if fsProvider, ok := android.OtherModuleProvider(ctx, m, FilesystemProvider); ok {
1160 rootDirs = append(rootDirs, fsProvider.RootDir)
1161 partitions = append(partitions, fsProvider.Output)
1162 } else {
1163 ctx.PropertyErrorf("include_files_of", "only filesystem modules can be listed in "+
1164 "include_files_of but %s is not a filesystem module", m.Name())
1165 }
1166 })
1167 return rootDirs, partitions
1168}
1169
Cole Faust62cfaeb2025-01-15 18:06:40 -08001170func (f *filesystem) buildCpioImage(
1171 ctx android.ModuleContext,
1172 builder *android.RuleBuilder,
1173 rootDir android.OutputPath,
1174 compressed bool,
Cole Faustb36763e2025-02-18 15:21:44 -08001175) (android.Path, android.Paths) {
Jiyong Park11a65972021-02-01 21:09:38 +09001176 if proptools.Bool(f.properties.Use_avb) {
1177 ctx.PropertyErrorf("use_avb", "signing compresed cpio image using avbtool is not supported."+
1178 "Consider adding this to bootimg module and signing the entire boot image.")
1179 }
1180
Inseob Kimcc8e5362021-02-03 14:05:24 +09001181 if proptools.String(f.properties.File_contexts) != "" {
1182 ctx.PropertyErrorf("file_contexts", "file_contexts is not supported for compressed cpio image.")
1183 }
1184
Jihoon Kang6da80752024-12-23 18:53:32 +00001185 rootDirs, partitions := includeFilesRootDir(ctx)
1186
Cole Faust4e9f5922024-11-13 16:09:23 -08001187 output := android.PathForModuleOut(ctx, f.installFileName())
Jiyong Park837cdb22021-02-05 00:17:14 +09001188 cmd := builder.Command().
Jiyong Park11a65972021-02-01 21:09:38 +09001189 BuiltTool("mkbootfs").
Spandan Das5ef1a9c2025-02-11 18:50:17 +00001190 Implicit(f.fileystemStagingDirTimestamp(ctx)).
Jiyong Park837cdb22021-02-05 00:17:14 +09001191 Text(rootDir.String()) // input directory
Jihoon Kang6da80752024-12-23 18:53:32 +00001192
1193 for i := range len(rootDirs) {
1194 cmd.Text(rootDirs[i].String())
1195 }
1196 cmd.Implicits(partitions)
1197
Jihoon Kang6c03c8e2024-11-18 21:30:22 +00001198 if nodeList := f.properties.Dev_nodes_description_file; nodeList != nil {
1199 cmd.FlagWithInput("-n ", android.PathForModuleSrc(ctx, proptools.String(nodeList)))
1200 }
Jiyong Park837cdb22021-02-05 00:17:14 +09001201 if compressed {
1202 cmd.Text("|").
1203 BuiltTool("lz4").
1204 Flag("--favor-decSpeed"). // for faster boot
1205 Flag("-12"). // maximum compression level
1206 Flag("-l"). // legacy format for kernel
1207 Text(">").Output(output)
1208 } else {
1209 cmd.Text(">").Output(output)
1210 }
Jiyong Park11a65972021-02-01 21:09:38 +09001211
1212 // rootDir is not deleted. Might be useful for quick inspection.
Jiyong Park837cdb22021-02-05 00:17:14 +09001213 builder.Build("build_cpio_image", fmt.Sprintf("Creating filesystem %s", f.BaseModuleName()))
Jiyong Park11a65972021-02-01 21:09:38 +09001214
Cole Faustb36763e2025-02-18 15:21:44 -08001215 return output, rootDirs
Jiyong Park11a65972021-02-01 21:09:38 +09001216}
1217
Cole Faust4a2a7c92024-03-12 12:44:40 -07001218var validPartitions = []string{
1219 "system",
1220 "userdata",
1221 "cache",
1222 "system_other",
1223 "vendor",
1224 "product",
1225 "system_ext",
1226 "odm",
1227 "vendor_dlkm",
1228 "odm_dlkm",
1229 "system_dlkm",
Cole Faust76a6e952024-11-07 16:56:45 -08001230 "ramdisk",
Cole Faust24938e22024-11-18 14:01:58 -08001231 "vendor_ramdisk",
Jihoon Kang3216c982024-12-02 19:42:20 +00001232 "recovery",
Cole Faust4a2a7c92024-03-12 12:44:40 -07001233}
1234
Cole Faust19fbb072025-01-30 18:19:29 -08001235func (f *filesystem) buildEventLogtagsFile(
1236 ctx android.ModuleContext,
1237 builder *android.RuleBuilder,
1238 rebasedDir android.OutputPath,
1239 fullInstallPaths *[]FullInstallPathInfo,
1240) {
Inseob Kimb7b84572024-04-30 10:51:47 +09001241 if !proptools.Bool(f.properties.Build_logtags) {
1242 return
1243 }
1244
Inseob Kimb7b84572024-04-30 10:51:47 +09001245 etcPath := rebasedDir.Join(ctx, "etc")
1246 eventLogtagsPath := etcPath.Join(ctx, "event-log-tags")
1247 builder.Command().Text("mkdir").Flag("-p").Text(etcPath.String())
Cole Fauste4506af2024-12-11 14:14:50 -08001248 builder.Command().Text("cp").Input(android.MergedLogtagsPath(ctx)).Text(eventLogtagsPath.String())
Kiyoung Kim99a954d2024-06-21 14:22:20 +09001249
Cole Faust19fbb072025-01-30 18:19:29 -08001250 *fullInstallPaths = append(*fullInstallPaths, FullInstallPathInfo{
1251 FullInstallPath: android.PathForModuleInPartitionInstall(ctx, f.PartitionType(), "etc", "event-log-tags"),
1252 SourcePath: android.MergedLogtagsPath(ctx),
1253 })
1254
Kiyoung Kim99a954d2024-06-21 14:22:20 +09001255 f.appendToEntry(ctx, eventLogtagsPath)
Inseob Kimb7b84572024-04-30 10:51:47 +09001256}
1257
Cole Faust19fbb072025-01-30 18:19:29 -08001258func (f *filesystem) BuildLinkerConfigFile(
1259 ctx android.ModuleContext,
1260 builder *android.RuleBuilder,
1261 rebasedDir android.OutputPath,
1262 fullInstallPaths *[]FullInstallPathInfo,
1263) {
Spandan Das2047a4c2024-11-11 21:24:58 +00001264 if !proptools.Bool(f.properties.Linker_config.Gen_linker_config) {
Spandan Das92631882024-10-28 22:49:38 +00001265 return
1266 }
1267
Spandan Das918191e2024-10-31 18:27:23 +00001268 provideModules, _ := f.getLibsForLinkerConfig(ctx)
Cole Faustfee27012024-12-13 14:10:31 -08001269 intermediateOutput := android.PathForModuleOut(ctx, "linker.config.pb")
1270 linkerconfig.BuildLinkerConfig(ctx, android.PathsForModuleSrc(ctx, f.properties.Linker_config.Linker_config_srcs), provideModules, nil, intermediateOutput)
Spandan Das92631882024-10-28 22:49:38 +00001271 output := rebasedDir.Join(ctx, "etc", "linker.config.pb")
Cole Faustfee27012024-12-13 14:10:31 -08001272 builder.Command().Text("cp").Input(intermediateOutput).Output(output)
Spandan Das92631882024-10-28 22:49:38 +00001273
Cole Faust19fbb072025-01-30 18:19:29 -08001274 *fullInstallPaths = append(*fullInstallPaths, FullInstallPathInfo{
1275 FullInstallPath: android.PathForModuleInPartitionInstall(ctx, f.PartitionType(), "etc", "linker.config.pb"),
1276 SourcePath: intermediateOutput,
1277 })
1278
Spandan Das92631882024-10-28 22:49:38 +00001279 f.appendToEntry(ctx, output)
1280}
1281
Kiyoung Kim23be5bb2024-11-27 00:50:30 +00001282func (f *filesystem) ShouldUseVintfFragmentModuleOnly() bool {
1283 return false
1284}
1285
Jiyong Parkf46b1af2024-04-05 18:13:33 +09001286type partition interface {
1287 PartitionType() string
1288}
1289
Cole Faust9a24d902024-03-18 15:38:12 -07001290func (f *filesystem) PartitionType() string {
1291 return proptools.StringDefault(f.properties.Partition_type, "system")
1292}
1293
Jiyong Parkf46b1af2024-04-05 18:13:33 +09001294var _ partition = (*filesystem)(nil)
1295
Jiyong Park65c49f52020-11-24 14:23:26 +09001296var _ android.AndroidMkEntriesProvider = (*filesystem)(nil)
1297
1298// Implements android.AndroidMkEntriesProvider
1299func (f *filesystem) AndroidMkEntries() []android.AndroidMkEntries {
1300 return []android.AndroidMkEntries{android.AndroidMkEntries{
1301 Class: "ETC",
1302 OutputFile: android.OptionalPathForPath(f.output),
1303 ExtraEntries: []android.AndroidMkExtraEntriesFunc{
Colin Crossaa255532020-07-03 13:18:24 -07001304 func(ctx android.AndroidMkExtraEntriesContext, entries *android.AndroidMkEntries) {
Colin Crossc68db4b2021-11-11 18:59:15 -08001305 entries.SetString("LOCAL_MODULE_PATH", f.installDir.String())
Jiyong Park65c49f52020-11-24 14:23:26 +09001306 entries.SetString("LOCAL_INSTALLED_MODULE_STEM", f.installFileName())
Kiyoung Kim99a954d2024-06-21 14:22:20 +09001307 entries.SetString("LOCAL_FILESYSTEM_FILELIST", f.fileListFile.String())
Jiyong Park65c49f52020-11-24 14:23:26 +09001308 },
1309 },
1310 }}
Jiyong Park6f0f6882020-11-12 13:14:30 +09001311}
Jiyong Park12a719c2021-01-07 15:31:24 +09001312
1313// Filesystem is the public interface for the filesystem struct. Currently, it's only for the apex
1314// package to have access to the output file.
1315type Filesystem interface {
1316 android.Module
1317 OutputPath() android.Path
Jiyong Park972e06c2021-03-15 23:32:49 +09001318
1319 // Returns the output file that is signed by avbtool. If this module is not signed, returns
1320 // nil.
1321 SignedOutputPath() android.Path
Jiyong Park12a719c2021-01-07 15:31:24 +09001322}
1323
1324var _ Filesystem = (*filesystem)(nil)
1325
1326func (f *filesystem) OutputPath() android.Path {
1327 return f.output
1328}
Jiyong Park972e06c2021-03-15 23:32:49 +09001329
1330func (f *filesystem) SignedOutputPath() android.Path {
1331 if proptools.Bool(f.properties.Use_avb) {
1332 return f.OutputPath()
1333 }
1334 return nil
1335}
Jooyung Han0fbbc2b2022-03-25 12:35:46 +09001336
1337// Filter the result of GatherPackagingSpecs to discard items targeting outside "system" partition.
1338// Note that "apex" module installs its contents to "apex"(fake partition) as well
1339// for symbol lookup by imitating "activated" paths.
1340func (f *filesystem) gatherFilteredPackagingSpecs(ctx android.ModuleContext) map[string]android.PackagingSpec {
Cole Faustb8e280f2025-01-16 16:33:26 -08001341 return f.PackagingBase.GatherPackagingSpecsWithFilterAndModifier(ctx, f.filesystemBuilder.FilterPackagingSpec, f.filesystemBuilder.ModifyPackagingSpec)
1342}
1343
Jihoon Kangabec3ec2025-02-19 00:55:10 +00001344func (f *filesystem) gatherOwners(specs map[string]android.PackagingSpec) []InstalledModuleInfo {
1345 var owners []InstalledModuleInfo
1346 for _, p := range android.SortedKeys(specs) {
1347 spec := specs[p]
1348 owners = append(owners, InstalledModuleInfo{
1349 Name: spec.Owner(),
1350 Variation: spec.Variation(),
1351 })
1352 }
1353 return owners
1354}
1355
Cole Faustb8e280f2025-01-16 16:33:26 -08001356// Dexpreopt files are installed to system_other. Collect the packaingSpecs for the dexpreopt files
1357// from this partition to export to the system_other partition later.
1358func (f *filesystem) systemOtherFiles(ctx android.ModuleContext) map[string]android.PackagingSpec {
1359 filter := func(spec android.PackagingSpec) bool {
1360 // For some reason system_other packaging specs don't set the partition field.
1361 return strings.HasPrefix(spec.RelPathInPackage(), "system_other/")
1362 }
1363 modifier := func(spec *android.PackagingSpec) {
1364 spec.SetRelPathInPackage(strings.TrimPrefix(spec.RelPathInPackage(), "system_other/"))
1365 spec.SetPartition("system_other")
1366 }
1367 return f.PackagingBase.GatherPackagingSpecsWithFilterAndModifier(ctx, filter, modifier)
Jooyung Han0fbbc2b2022-03-25 12:35:46 +09001368}
Jooyung Han65f402b2022-04-21 14:24:04 +09001369
1370func sha1sum(values []string) string {
1371 h := sha256.New()
1372 for _, value := range values {
1373 io.WriteString(h, value)
1374 }
1375 return fmt.Sprintf("%x", h.Sum(nil))
1376}
Jooyung Hane6067592023-03-16 13:11:17 +09001377
1378// Base cc.UseCoverage
1379
1380var _ cc.UseCoverage = (*filesystem)(nil)
1381
Colin Crosse1a85552024-06-14 12:17:37 -07001382func (*filesystem) IsNativeCoverageNeeded(ctx cc.IsNativeCoverageNeededContext) bool {
Jooyung Hane6067592023-03-16 13:11:17 +09001383 return ctx.Device() && ctx.DeviceConfig().NativeCoverageEnabled()
1384}
Jiyong Parkf46b1af2024-04-05 18:13:33 +09001385
1386// android_filesystem_defaults
1387
1388type filesystemDefaults struct {
1389 android.ModuleBase
1390 android.DefaultsModuleBase
1391
Inseob Kim3c0a0422024-11-05 17:21:37 +09001392 properties FilesystemProperties
Jiyong Parkf46b1af2024-04-05 18:13:33 +09001393}
1394
1395// android_filesystem_defaults is a default module for android_filesystem and android_system_image
1396func filesystemDefaultsFactory() android.Module {
1397 module := &filesystemDefaults{}
1398 module.AddProperties(&module.properties)
1399 module.AddProperties(&android.PackagingProperties{})
1400 android.InitDefaultsModule(module)
1401 return module
1402}
1403
1404func (f *filesystemDefaults) PartitionType() string {
1405 return proptools.StringDefault(f.properties.Partition_type, "system")
1406}
1407
1408var _ partition = (*filesystemDefaults)(nil)
1409
1410func (f *filesystemDefaults) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1411 validatePartitionType(ctx, f)
Yu Liu71f1ea32025-02-26 23:39:20 +00001412 android.SetProvider(ctx, FilesystemDefaultsInfoProvider, FilesystemDefaultsInfo{})
1413 android.SetProvider(ctx, android.PartitionTypeInfoProvider, android.PartitionTypeInfo{
Yu Liufc8d5c12025-01-09 00:19:06 +00001414 PartitionType: f.PartitionType(),
1415 })
Jiyong Parkf46b1af2024-04-05 18:13:33 +09001416}
Spandan Das918191e2024-10-31 18:27:23 +00001417
1418// getLibsForLinkerConfig returns
1419// 1. A list of libraries installed in this filesystem
1420// 2. A list of dep libraries _not_ installed in this filesystem
1421//
1422// `linkerconfig.BuildLinkerConfig` will convert these two to a linker.config.pb for the filesystem
1423// (1) will be added to --provideLibs if they are C libraries with a stable interface (has stubs)
1424// (2) will be added to --requireLibs if they are C libraries with a stable interface (has stubs)
Yu Liu68a70b72025-01-08 22:54:44 +00001425func (f *filesystem) getLibsForLinkerConfig(ctx android.ModuleContext) ([]android.ModuleProxy, []android.ModuleProxy) {
Spandan Das918191e2024-10-31 18:27:23 +00001426 // we need "Module"s for packaging items
Yu Liu68a70b72025-01-08 22:54:44 +00001427 modulesInPackageByModule := make(map[android.ModuleProxy]bool)
Spandan Das918191e2024-10-31 18:27:23 +00001428 modulesInPackageByName := make(map[string]bool)
1429
1430 deps := f.gatherFilteredPackagingSpecs(ctx)
Yu Liu68a70b72025-01-08 22:54:44 +00001431 ctx.WalkDepsProxy(func(child, parent android.ModuleProxy) bool {
1432 if !android.OtherModuleProviderOrDefault(ctx, child, android.CommonModuleInfoKey).Enabled {
Yu Liu9c6b6762025-01-08 22:04:35 +00001433 return false
1434 }
Spandan Das918191e2024-10-31 18:27:23 +00001435 for _, ps := range android.OtherModuleProviderOrDefault(
1436 ctx, child, android.InstallFilesProvider).PackagingSpecs {
Spandan Dasecf667f2024-12-05 00:58:56 +00001437 if _, ok := deps[ps.RelPathInPackage()]; ok && ps.Partition() == f.PartitionType() {
Spandan Das918191e2024-10-31 18:27:23 +00001438 modulesInPackageByModule[child] = true
1439 modulesInPackageByName[child.Name()] = true
1440 return true
1441 }
1442 }
1443 return true
1444 })
1445
Yu Liu68a70b72025-01-08 22:54:44 +00001446 provideModules := make([]android.ModuleProxy, 0, len(modulesInPackageByModule))
Spandan Das918191e2024-10-31 18:27:23 +00001447 for mod := range modulesInPackageByModule {
1448 provideModules = append(provideModules, mod)
1449 }
1450
Yu Liu68a70b72025-01-08 22:54:44 +00001451 var requireModules []android.ModuleProxy
1452 ctx.WalkDepsProxy(func(child, parent android.ModuleProxy) bool {
1453 if !android.OtherModuleProviderOrDefault(ctx, child, android.CommonModuleInfoKey).Enabled {
Yu Liu9c6b6762025-01-08 22:04:35 +00001454 return false
1455 }
Spandan Das918191e2024-10-31 18:27:23 +00001456 _, parentInPackage := modulesInPackageByModule[parent]
1457 _, childInPackageName := modulesInPackageByName[child.Name()]
1458
1459 // When parent is in the package, and child (or its variant) is not, this can be from an interface.
1460 if parentInPackage && !childInPackageName {
1461 requireModules = append(requireModules, child)
1462 }
1463 return true
1464 })
1465
1466 return provideModules, requireModules
1467}
Cole Faust26bdac52024-11-19 13:37:53 -08001468
1469// Checks that the given file doesn't exceed the given size, and will also print a warning
1470// if it's nearing the maximum size. Equivalent to assert-max-image-size in make:
1471// https://cs.android.com/android/platform/superproject/main/+/main:build/make/core/definitions.mk;l=3455;drc=993c4de29a02a6accd60ceaaee153307e1a18d10
1472func assertMaxImageSize(builder *android.RuleBuilder, image android.Path, maxSize int64, addAvbLater bool) {
1473 if addAvbLater {
1474 // The value 69632 is derived from MAX_VBMETA_SIZE + MAX_FOOTER_SIZE in avbtool.
1475 // Logic copied from make:
1476 // https://cs.android.com/android/platform/superproject/main/+/main:build/make/core/Makefile;l=228;drc=a6a0007ef24e16c0b79f439beac4a118416717e6
1477 maxSize -= 69632
1478 }
1479 cmd := builder.Command()
1480 cmd.Textf(`file="%s"; maxsize="%d";`+
1481 `total=$(stat -c "%%s" "$file" | tr -d '\n');`+
1482 `if [ "$total" -gt "$maxsize" ]; then `+
1483 ` echo "error: $file too large ($total > $maxsize)";`+
1484 ` false;`+
1485 `elif [ "$total" -gt $((maxsize - 32768)) ]; then `+
1486 ` echo "WARNING: $file approaching size limit ($total now; limit $maxsize)";`+
1487 `fi`,
1488 image, maxSize)
1489 cmd.Implicit(image)
1490}
Spandan Das71be42d2024-11-20 18:34:16 +00001491
1492// addAutogeneratedRroDeps walks the transitive closure of vendor and product partitions.
1493// It visits apps installed in system and system_ext partitions, and adds the autogenerated
1494// RRO modules to its own deps.
1495func addAutogeneratedRroDeps(ctx android.BottomUpMutatorContext) {
1496 f, ok := ctx.Module().(*filesystem)
1497 if !ok {
1498 return
1499 }
1500 thisPartition := f.PartitionType()
1501 if thisPartition != "vendor" && thisPartition != "product" {
Cole Faust34592c02024-12-13 11:20:24 -08001502 if f.properties.Android_filesystem_deps.System != nil {
1503 ctx.PropertyErrorf("android_filesystem_deps.system", "only vendor or product partitions can use android_filesystem_deps")
1504 }
1505 if f.properties.Android_filesystem_deps.System_ext != nil {
1506 ctx.PropertyErrorf("android_filesystem_deps.system_ext", "only vendor or product partitions can use android_filesystem_deps")
1507 }
Spandan Das71be42d2024-11-20 18:34:16 +00001508 return
1509 }
1510 ctx.WalkDeps(func(child, parent android.Module) bool {
1511 depTag := ctx.OtherModuleDependencyTag(child)
1512 if parent.Name() == f.Name() && depTag != interPartitionDependencyTag {
1513 return false // This is a module listed in deps of vendor/product filesystem
1514 }
1515 if vendorOverlay := java.AutogeneratedRroModuleName(ctx, child.Name(), "vendor"); ctx.OtherModuleExists(vendorOverlay) && thisPartition == "vendor" {
1516 ctx.AddFarVariationDependencies(nil, dependencyTagWithVisibilityEnforcementBypass, vendorOverlay)
1517 }
1518 if productOverlay := java.AutogeneratedRroModuleName(ctx, child.Name(), "product"); ctx.OtherModuleExists(productOverlay) && thisPartition == "product" {
1519 ctx.AddFarVariationDependencies(nil, dependencyTagWithVisibilityEnforcementBypass, productOverlay)
1520 }
1521 return true
1522 })
1523}
Spandan Das6ec1fcf2025-02-11 22:51:51 +00001524
Yu Liu2a815b62025-02-21 20:46:25 +00001525func (f *filesystem) MakeVars(ctx android.MakeVarsModuleContext) []android.ModuleMakeVarsValue {
Spandan Das6ec1fcf2025-02-11 22:51:51 +00001526 if f.Name() == ctx.Config().SoongDefinedSystemImage() {
Yu Liu2a815b62025-02-21 20:46:25 +00001527 return []android.ModuleMakeVarsValue{{"SOONG_DEFINED_SYSTEM_IMAGE_PATH", f.output.String()}}
Spandan Das6ec1fcf2025-02-11 22:51:51 +00001528 }
Yu Liu2a815b62025-02-21 20:46:25 +00001529 return nil
Spandan Das6ec1fcf2025-02-11 22:51:51 +00001530}
Yu Liu0a37d422025-02-13 02:05:00 +00001531
1532func setCommonFilesystemInfo(ctx android.ModuleContext, m Filesystem) {
1533 android.SetProvider(ctx, FilesystemProvider, FilesystemInfo{
1534 Output: m.OutputPath(),
1535 SignedOutputPath: m.SignedOutputPath(),
1536 })
1537}