blob: 725786897ed78f6886a02092fb88a3418f095130 [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
Cole Faust34592c02024-12-13 11:20:24 -0800211 // List of names of other filesystem partitions to import their aconfig flags from.
212 // This is used for the system partition to import system_ext's aconfig flags, as currently
213 // those are considered one "container": aosp/3261300
214 Import_aconfig_flags_from []string
215
Inseob Kim53391842024-03-29 17:44:07 +0900216 Fsverity fsverityProperties
Cole Faust92ccbe22024-10-03 14:38:37 -0700217
218 // If this property is set to true, the filesystem will call ctx.UncheckedModule(), causing
219 // it to not be built on checkbuilds. Used for the automatic migration from make to soong
220 // build modules, where we want to emit some not-yet-working filesystems and we don't want them
221 // to be built.
222 Unchecked_module *bool `blueprint:"mutated"`
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000223
224 Erofs ErofsProperties
Jihoon Kang0d545b82024-10-11 00:21:57 +0000225
mrziwang1a6291f2024-11-07 14:29:25 -0800226 F2fs F2fsProperties
227
Spandan Das2047a4c2024-11-11 21:24:58 +0000228 Linker_config LinkerConfigProperties
Spandan Das92631882024-10-28 22:49:38 +0000229
Jihoon Kang0d545b82024-10-11 00:21:57 +0000230 // Determines if the module is auto-generated from Soong or not. If the module is
231 // auto-generated, its deps are exempted from visibility enforcement.
232 Is_auto_generated *bool
Jihoon Kang6c03c8e2024-11-18 21:30:22 +0000233
234 // Path to the dev nodes description file. This is only needed for building the ramdisk
235 // partition and should not be explicitly specified.
236 Dev_nodes_description_file *string `android:"path" blueprint:"mutated"`
Spandan Das71be42d2024-11-20 18:34:16 +0000237
238 // Additional dependencies used for building android products
239 Android_filesystem_deps AndroidFilesystemDeps
Spandan Dasc49b85e2025-01-10 00:51:25 +0000240
241 // Name of the output. Default is $(module_name).img
242 Stem *string
Jihoon Kang983dd882025-01-13 23:14:11 +0000243
244 // The size of the partition on the device. It will be a build error if this built partition
245 // image exceeds this size.
246 Partition_size *int64
Jihoon Kang6d08d922025-01-14 18:31:57 +0000247
248 // Whether to format f2fs and ext4 in a way that supports casefolding
249 Support_casefolding *bool
250
251 // Whether to format f2fs and ext4 in a way that supports project quotas
252 Support_project_quota *bool
253
254 // Whether to enable per-file compression in f2fs
255 Enable_compression *bool
Spandan Das71be42d2024-11-20 18:34:16 +0000256}
257
258type AndroidFilesystemDeps struct {
259 System *string
260 System_ext *string
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000261}
262
263// Additional properties required to generate erofs FS partitions.
264type ErofsProperties struct {
265 // Compressor and Compression level passed to mkfs.erofs. e.g. (lz4hc,9)
266 // Please see external/erofs-utils/README for complete documentation.
267 Compressor *string
268
269 // Used as --compress-hints for mkfs.erofs
270 Compress_hints *string `android:"path"`
271
272 Sparse *bool
Jiyong Park71baa762021-01-18 21:11:03 +0900273}
274
mrziwang1a6291f2024-11-07 14:29:25 -0800275// Additional properties required to generate f2fs FS partitions.
276type F2fsProperties struct {
277 Sparse *bool
278}
279
Spandan Das173256b2024-10-31 19:59:30 +0000280type LinkerConfigProperties struct {
281
282 // Build a linker.config.pb file
283 Gen_linker_config *bool
284
285 // List of files (in .json format) that will be converted to a linker config file (in .pb format).
286 // The linker config file be installed in the filesystem at /etc/linker.config.pb
287 Linker_config_srcs []string `android:"path"`
288}
289
Jiyong Park65c49f52020-11-24 14:23:26 +0900290// android_filesystem packages a set of modules and their transitive dependencies into a filesystem
291// image. The filesystem images are expected to be mounted in the target device, which means the
292// modules in the filesystem image are built for the target device (i.e. Android, not Linux host).
293// The modules are placed in the filesystem image just like they are installed to the ordinary
294// partitions like system.img. For example, cc_library modules are placed under ./lib[64] directory.
Cole Faust92ccbe22024-10-03 14:38:37 -0700295func FilesystemFactory() android.Module {
Jiyong Park6f0f6882020-11-12 13:14:30 +0900296 module := &filesystem{}
Kiyoung Kim67118212024-11-07 13:23:44 +0900297 module.filesystemBuilder = module
Cole Faust2cfe6962024-09-17 11:31:14 -0700298 initFilesystemModule(module, module)
Jiyong Parkfa616132021-04-20 11:36:40 +0900299 return module
300}
301
Cole Faust2cfe6962024-09-17 11:31:14 -0700302func initFilesystemModule(module android.DefaultableModule, filesystemModule *filesystem) {
303 module.AddProperties(&filesystemModule.properties)
304 android.InitPackageModule(filesystemModule)
305 filesystemModule.PackagingBase.DepsCollectFirstTargetOnly = true
Jihoon Kang79196c52024-10-30 18:49:47 +0000306 filesystemModule.PackagingBase.AllowHighPriorityDeps = true
Jiyong Park6f0f6882020-11-12 13:14:30 +0900307 android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900308 android.InitDefaultableModule(module)
Jihoon Kang6c03c8e2024-11-18 21:30:22 +0000309
310 android.AddLoadHook(module, func(ctx android.LoadHookContext) {
311 filesystemModule.setDevNodesDescriptionProp()
312 })
Jiyong Park6f0f6882020-11-12 13:14:30 +0900313}
314
Jihoon Kang0d545b82024-10-11 00:21:57 +0000315type depTag struct {
Jiyong Park12a719c2021-01-07 15:31:24 +0900316 blueprint.BaseDependencyTag
Jooyung Han092ef812021-03-10 15:40:34 +0900317 android.PackagingItemAlwaysDepTag
Jihoon Kang0d545b82024-10-11 00:21:57 +0000318}
319
320var dependencyTag = depTag{}
321
322type depTagWithVisibilityEnforcementBypass struct {
323 depTag
324}
325
Spandan Das71be42d2024-11-20 18:34:16 +0000326type interPartitionDepTag struct {
327 blueprint.BaseDependencyTag
328}
329
330var interPartitionDependencyTag = interPartitionDepTag{}
331
Jihoon Kang6da80752024-12-23 18:53:32 +0000332var interPartitionInstallDependencyTag = interPartitionDepTag{}
333
Jihoon Kang0d545b82024-10-11 00:21:57 +0000334var _ android.ExcludeFromVisibilityEnforcementTag = (*depTagWithVisibilityEnforcementBypass)(nil)
335
336func (t depTagWithVisibilityEnforcementBypass) ExcludeFromVisibilityEnforcement() {}
337
338var dependencyTagWithVisibilityEnforcementBypass = depTagWithVisibilityEnforcementBypass{}
Jiyong Park65b62242020-11-25 12:44:59 +0900339
Jihoon Kang6c03c8e2024-11-18 21:30:22 +0000340// ramdiskDevNodesDescription is the name of the filegroup module that provides the file that
341// contains the description of dev nodes added to the CPIO archive for the ramdisk partition.
342const ramdiskDevNodesDescription = "ramdisk_node_list"
343
344func (f *filesystem) setDevNodesDescriptionProp() {
345 if proptools.String(f.properties.Partition_name) == "ramdisk" {
346 f.properties.Dev_nodes_description_file = proptools.StringPtr(":" + ramdiskDevNodesDescription)
347 }
348}
349
Jiyong Park6f0f6882020-11-12 13:14:30 +0900350func (f *filesystem) DepsMutator(ctx android.BottomUpMutatorContext) {
Jihoon Kang0d545b82024-10-11 00:21:57 +0000351 if proptools.Bool(f.properties.Is_auto_generated) {
352 f.AddDeps(ctx, dependencyTagWithVisibilityEnforcementBypass)
353 } else {
354 f.AddDeps(ctx, dependencyTag)
355 }
Spandan Das71be42d2024-11-20 18:34:16 +0000356 if f.properties.Android_filesystem_deps.System != nil {
357 ctx.AddDependency(ctx.Module(), interPartitionDependencyTag, proptools.String(f.properties.Android_filesystem_deps.System))
358 }
359 if f.properties.Android_filesystem_deps.System_ext != nil {
360 ctx.AddDependency(ctx.Module(), interPartitionDependencyTag, proptools.String(f.properties.Android_filesystem_deps.System_ext))
361 }
Cole Faust34592c02024-12-13 11:20:24 -0800362 for _, partition := range f.properties.Import_aconfig_flags_from {
363 ctx.AddDependency(ctx.Module(), importAconfigDependencyTag, partition)
364 }
Jihoon Kang6da80752024-12-23 18:53:32 +0000365 for _, partition := range f.properties.Include_files_of {
366 ctx.AddDependency(ctx.Module(), interPartitionInstallDependencyTag, partition)
367 }
Jiyong Park6f0f6882020-11-12 13:14:30 +0900368}
369
Jiyong Park11a65972021-02-01 21:09:38 +0900370type fsType int
371
372const (
373 ext4Type fsType = iota
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000374 erofsType
mrziwang1a6291f2024-11-07 14:29:25 -0800375 f2fsType
Jiyong Park11a65972021-02-01 21:09:38 +0900376 compressedCpioType
Jiyong Park837cdb22021-02-05 00:17:14 +0900377 cpioType // uncompressed
Jiyong Park11a65972021-02-01 21:09:38 +0900378 unknown
379)
380
Spandan Das7a46f6c2024-10-14 18:41:18 +0000381func (fs fsType) IsUnknown() bool {
382 return fs == unknown
383}
384
Jihoon Kangf67b7de2025-02-12 01:01:09 +0000385type InstalledFilesStruct struct {
386 Txt android.Path
387 Json android.Path
388}
389
Jihoon Kangabec3ec2025-02-19 00:55:10 +0000390type InstalledModuleInfo struct {
391 Name string
392 Variation string
393}
394
Cole Faust92ccbe22024-10-03 14:38:37 -0700395type FilesystemInfo struct {
Cole Faust44080412024-12-20 14:17:07 -0800396 // The built filesystem image
397 Output android.Path
Yu Liu0a37d422025-02-13 02:05:00 +0000398 // Returns the output file that is signed by avbtool. If this module is not signed, returns
399 // nil.
400 SignedOutputPath android.Path
Spandan Das1f0a5a12025-01-15 00:53:15 +0000401 // An additional hermetic filesystem image.
402 // e.g. this will contain inodes with pinned timestamps.
403 // This will be copied to target_files.zip
404 OutputHermetic android.Path
Cole Faust92ccbe22024-10-03 14:38:37 -0700405 // A text file containing the list of paths installed on the partition.
406 FileListFile android.Path
Cole Faust44080412024-12-20 14:17:07 -0800407 // The root staging directory used to build the output filesystem. If consuming this, make sure
408 // to add a dependency on the Output file, as you cannot add dependencies on directories
409 // in ninja.
410 RootDir android.Path
Cole Faustb36763e2025-02-18 15:21:44 -0800411 // Extra root directories that are also built into the partition. Currently only used for
412 // including the recovery partition files into the vendor_boot image.
413 ExtraRootDirs android.Paths
Cole Faust11fda332025-01-14 16:47:19 -0800414 // The rebased staging directory used to build the output filesystem. If consuming this, make
415 // sure to add a dependency on the Output file, as you cannot add dependencies on directories
416 // in ninja. In many cases this is the same as RootDir, only in the system partition is it
417 // different. There, it points to the "system" sub-directory of RootDir.
418 RebasedDir android.Path
Spandan Das33c9c472025-01-14 19:26:23 +0000419 // A text file with block data of the .img file
420 // This is an implicit output of `build_image`
421 MapFile android.Path
Cole Faust11fda332025-01-14 16:47:19 -0800422 // Name of the module that produced this FilesystemInfo origionally. (though it may be
423 // re-exported by super images or boot images)
424 ModuleName string
Cole Faust74ee4e02025-01-16 14:55:35 -0800425 // The property file generated by this module and passed to build_image.
426 // It's exported here so that system_other can reuse system's property file.
427 BuildImagePropFile android.Path
428 // Paths to all the tools referenced inside of the build image property file.
429 BuildImagePropFileDeps android.Paths
Cole Faustb8e280f2025-01-16 16:33:26 -0800430 // Packaging specs to be installed on the system_other image, for the initial boot's dexpreopt.
431 SpecsForSystemOther map[string]android.PackagingSpec
Cole Faust19fbb072025-01-30 18:19:29 -0800432
433 FullInstallPaths []FullInstallPathInfo
Jihoon Kangf67b7de2025-02-12 01:01:09 +0000434
435 // Installed files list
436 InstalledFiles InstalledFilesStruct
Spandan Dasd71af182025-02-12 18:03:29 +0000437
438 // Path to compress hints file for erofs filesystems
439 // This will be nil for other fileystems like ext4
440 ErofsCompressHints android.Path
Spandan Dasf12ff9b2025-02-12 22:27:43 +0000441
442 SelinuxFc android.Path
Spandan Dasdd262fb2025-02-13 00:15:59 +0000443
444 FilesystemConfig android.Path
Jihoon Kangabec3ec2025-02-19 00:55:10 +0000445
446 Owners []InstalledModuleInfo
Cole Faust19fbb072025-01-30 18:19:29 -0800447}
448
449// FullInstallPathInfo contains information about the "full install" paths of all the files
450// inside this partition. The full install paths are the files installed in
451// out/target/product/<device>/<partition>. This is essentially legacy behavior, maintained for
452// tools like adb sync and adevice, but we should update them to query the build system for the
453// installed files no matter where they are.
454type FullInstallPathInfo struct {
455 // RequiresFullInstall tells us if the origional module did the install to FullInstallPath
456 // already. If it's false, the android_device module needs to emit the install rule.
457 RequiresFullInstall bool
458 // The "full install" paths for the files in this filesystem. This is the paths in the
459 // out/target/product/<device>/<partition> folder. They're not used by this filesystem,
460 // but can be depended on by the top-level android_device module to cause the staging
461 // directories to be built.
462 FullInstallPath android.InstallPath
463
464 // The file that's copied to FullInstallPath. May be nil if SymlinkTarget is set or IsDir is
465 // true.
466 SourcePath android.Path
467
468 // The target of the symlink, if this file is a symlink.
469 SymlinkTarget string
470
471 // If this file is a directory. Only used for empty directories, which are mostly mount points.
472 IsDir bool
Cole Faust92ccbe22024-10-03 14:38:37 -0700473}
474
475var FilesystemProvider = blueprint.NewProvider[FilesystemInfo]()
476
Yu Liu71f1ea32025-02-26 23:39:20 +0000477type FilesystemDefaultsInfo struct{}
Yu Liufc8d5c12025-01-09 00:19:06 +0000478
479var FilesystemDefaultsInfoProvider = blueprint.NewProvider[FilesystemDefaultsInfo]()
480
Spandan Das7a46f6c2024-10-14 18:41:18 +0000481func GetFsTypeFromString(ctx android.EarlyModuleContext, typeStr string) fsType {
Jiyong Park11a65972021-02-01 21:09:38 +0900482 switch typeStr {
483 case "ext4":
484 return ext4Type
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000485 case "erofs":
486 return erofsType
mrziwang1a6291f2024-11-07 14:29:25 -0800487 case "f2fs":
488 return f2fsType
Jiyong Park11a65972021-02-01 21:09:38 +0900489 case "compressed_cpio":
490 return compressedCpioType
Jiyong Park837cdb22021-02-05 00:17:14 +0900491 case "cpio":
492 return cpioType
Jiyong Park11a65972021-02-01 21:09:38 +0900493 default:
Jiyong Park11a65972021-02-01 21:09:38 +0900494 return unknown
495 }
496}
497
Spandan Das7a46f6c2024-10-14 18:41:18 +0000498func (f *filesystem) fsType(ctx android.ModuleContext) fsType {
499 typeStr := proptools.StringDefault(f.properties.Type, "ext4")
500 fsType := GetFsTypeFromString(ctx, typeStr)
501 if fsType == unknown {
502 ctx.PropertyErrorf("type", "%q not supported", typeStr)
503 }
504 return fsType
505}
506
Jiyong Park65c49f52020-11-24 14:23:26 +0900507func (f *filesystem) installFileName() string {
Spandan Dasc49b85e2025-01-10 00:51:25 +0000508 return proptools.StringDefault(f.properties.Stem, f.BaseModuleName()+".img")
Jiyong Park65c49f52020-11-24 14:23:26 +0900509}
510
Inseob Kim53391842024-03-29 17:44:07 +0900511func (f *filesystem) partitionName() string {
512 return proptools.StringDefault(f.properties.Partition_name, f.Name())
513}
514
Kiyoung Kim67118212024-11-07 13:23:44 +0900515func (f *filesystem) FilterPackagingSpec(ps android.PackagingSpec) bool {
Jiyong Park7e7d4af2024-05-01 12:36:10 +0000516 // Filesystem module respects the installation semantic. A PackagingSpec from a module with
517 // IsSkipInstall() is skipped.
Cole Faust76a6e952024-11-07 16:56:45 -0800518 if ps.SkipInstall() {
519 return false
Spandan Das6d056502024-10-21 15:40:32 +0000520 }
Cole Faust0d3fd562025-01-31 13:17:58 -0800521 // "apex" is a fake partition used to install files in out/target/product/<device>/apex/.
522 // Don't include these files in the partition. We should also look into removing the following
523 // TODO to check the PackagingSpec's partition against this filesystem's partition for all
524 // modules, not just autogenerated ones, which will fix this as well.
525 if ps.Partition() == "apex" {
526 return false
527 }
Cole Faust76a6e952024-11-07 16:56:45 -0800528 if proptools.Bool(f.properties.Is_auto_generated) { // TODO (spandandas): Remove this.
529 pt := f.PartitionType()
Cole Faustc88cff12024-11-12 13:24:05 -0800530 return ps.Partition() == pt || strings.HasPrefix(ps.Partition(), pt+"/")
Cole Faust76a6e952024-11-07 16:56:45 -0800531 }
532 return true
Jiyong Park7e7d4af2024-05-01 12:36:10 +0000533}
534
Inseob Kim3c0a0422024-11-05 17:21:37 +0900535func (f *filesystem) ModifyPackagingSpec(ps *android.PackagingSpec) {
Cole Faustc88cff12024-11-12 13:24:05 -0800536 // Sometimes, android.modulePartition() returns a path with >1 path components.
537 // This makes the partition field of packagingSpecs have multiple components, like
538 // "system/product". Right now, the filesystem module doesn't look at the partition field
539 // when deciding what path to install the file under, only the RelPathInPackage field, so
540 // we move the later path components from partition to relPathInPackage. This should probably
541 // be revisited in the future.
542 prefix := f.PartitionType() + "/"
543 if strings.HasPrefix(ps.Partition(), prefix) {
544 subPartition := strings.TrimPrefix(ps.Partition(), prefix)
545 ps.SetPartition(f.PartitionType())
546 ps.SetRelPathInPackage(filepath.Join(subPartition, ps.RelPathInPackage()))
547 }
Inseob Kim3c0a0422024-11-05 17:21:37 +0900548}
549
Jihoon Kangf67b7de2025-02-12 01:01:09 +0000550func buildInstalledFiles(ctx android.ModuleContext, partition string, rootDir android.Path, image android.Path) (txt android.ModuleOutPath, json android.ModuleOutPath) {
551 fileName := "installed-files"
552 if len(partition) > 0 {
553 fileName += fmt.Sprintf("-%s", partition)
554 }
555 txt = android.PathForModuleOut(ctx, fmt.Sprintf("%s.txt", fileName))
556 json = android.PathForModuleOut(ctx, fmt.Sprintf("%s.json", fileName))
557
558 ctx.Build(pctx, android.BuildParams{
559 Rule: installedFilesJsonRule,
560 Implicit: image,
561 Output: json,
562 Description: "Installed file list json",
563 Args: map[string]string{
564 "rootDir": rootDir.String(),
565 },
566 })
567
568 ctx.Build(pctx, android.BuildParams{
569 Rule: installedFilesTxtRule,
570 Input: json,
571 Output: txt,
572 Description: "Installed file list txt",
573 })
574
575 return txt, json
576}
577
Jiyong Park6f0f6882020-11-12 13:14:30 +0900578func (f *filesystem) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900579 validatePartitionType(ctx, f)
Kiyoung Kim23be5bb2024-11-27 00:50:30 +0000580 if f.filesystemBuilder.ShouldUseVintfFragmentModuleOnly() {
581 f.validateVintfFragments(ctx)
582 }
Jihoon Kang6da80752024-12-23 18:53:32 +0000583
584 if len(f.properties.Include_files_of) > 0 && !android.InList(f.fsType(ctx), []fsType{compressedCpioType, cpioType}) {
585 ctx.PropertyErrorf("include_files_of", "include_files_of is only supported for cpio and compressed cpio filesystem types.")
586 }
587
Cole Faust62cfaeb2025-01-15 18:06:40 -0800588 rootDir := android.PathForModuleOut(ctx, f.rootDirString()).OutputPath
589 rebasedDir := rootDir
590 if f.properties.Base_dir != nil {
591 rebasedDir = rootDir.Join(ctx, *f.properties.Base_dir)
592 }
593 builder := android.NewRuleBuilder(pctx, ctx)
594
595 // Wipe the root dir to get rid of leftover files from prior builds
596 builder.Command().Textf("rm -rf %s && mkdir -p %s", rootDir, rootDir)
597 specs := f.gatherFilteredPackagingSpecs(ctx)
Cole Faust62cfaeb2025-01-15 18:06:40 -0800598
Cole Faust19fbb072025-01-30 18:19:29 -0800599 var fullInstallPaths []FullInstallPathInfo
Cole Faust5db2f3e2025-02-19 12:49:37 -0800600 for _, specRel := range android.SortedKeys(specs) {
601 spec := specs[specRel]
Cole Faust19fbb072025-01-30 18:19:29 -0800602 fullInstallPaths = append(fullInstallPaths, FullInstallPathInfo{
603 FullInstallPath: spec.FullInstallPath(),
604 RequiresFullInstall: spec.RequiresFullInstall(),
605 SourcePath: spec.SrcPath(),
606 SymlinkTarget: spec.ToGob().SymlinkTarget,
607 })
608 }
609
610 f.entries = f.copyPackagingSpecs(ctx, builder, specs, rootDir, rebasedDir)
611 f.buildNonDepsFiles(ctx, builder, rootDir, rebasedDir, &fullInstallPaths)
612 f.buildFsverityMetadataFiles(ctx, builder, specs, rootDir, rebasedDir, &fullInstallPaths)
613 f.buildEventLogtagsFile(ctx, builder, rebasedDir, &fullInstallPaths)
614 f.buildAconfigFlagsFiles(ctx, builder, specs, rebasedDir, &fullInstallPaths)
615 f.filesystemBuilder.BuildLinkerConfigFile(ctx, builder, rebasedDir, &fullInstallPaths)
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000616 // Assemeble the staging dir and output a timestamp
617 builder.Command().Text("touch").Output(f.fileystemStagingDirTimestamp(ctx))
618 builder.Build("assemble_filesystem_staging_dir", fmt.Sprintf("Assemble filesystem staging dir %s", f.BaseModuleName()))
Cole Faust62cfaeb2025-01-15 18:06:40 -0800619
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000620 // Create a new rule builder for build_image
621 builder = android.NewRuleBuilder(pctx, ctx)
Spandan Das33c9c472025-01-14 19:26:23 +0000622 var mapFile android.Path
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000623 var outputHermetic android.WritablePath
Cole Faust74ee4e02025-01-16 14:55:35 -0800624 var buildImagePropFile android.Path
625 var buildImagePropFileDeps android.Paths
Cole Faustb36763e2025-02-18 15:21:44 -0800626 var extraRootDirs android.Paths
Jiyong Park11a65972021-02-01 21:09:38 +0900627 switch f.fsType(ctx) {
mrziwang1a6291f2024-11-07 14:29:25 -0800628 case ext4Type, erofsType, f2fsType:
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000629 buildImagePropFile, buildImagePropFileDeps = f.buildPropFile(ctx)
630 output := android.PathForModuleOut(ctx, f.installFileName())
631 f.buildImageUsingBuildImage(ctx, builder, buildImageParams{rootDir, buildImagePropFile, buildImagePropFileDeps, output})
632 f.output = output
633 // Create the hermetic img file using a separate rule builder so that it can be built independently
634 hermeticBuilder := android.NewRuleBuilder(pctx, ctx)
635 outputHermetic = android.PathForModuleOut(ctx, "for_target_files", f.installFileName())
636 propFileHermetic := f.propFileForHermeticImg(ctx, hermeticBuilder, buildImagePropFile)
637 f.buildImageUsingBuildImage(ctx, hermeticBuilder, buildImageParams{rootDir, propFileHermetic, buildImagePropFileDeps, outputHermetic})
Spandan Das33c9c472025-01-14 19:26:23 +0000638 mapFile = f.getMapFile(ctx)
Jiyong Park11a65972021-02-01 21:09:38 +0900639 case compressedCpioType:
Cole Faustb36763e2025-02-18 15:21:44 -0800640 f.output, extraRootDirs = f.buildCpioImage(ctx, builder, rootDir, true)
Jiyong Park837cdb22021-02-05 00:17:14 +0900641 case cpioType:
Cole Faustb36763e2025-02-18 15:21:44 -0800642 f.output, extraRootDirs = f.buildCpioImage(ctx, builder, rootDir, false)
Jiyong Park11a65972021-02-01 21:09:38 +0900643 default:
644 return
645 }
646
647 f.installDir = android.PathForModuleInstall(ctx, "etc")
648 ctx.InstallFile(f.installDir, f.installFileName(), f.output)
mrziwang555d1332024-06-07 11:15:33 -0700649 ctx.SetOutputFiles([]android.Path{f.output}, "")
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900650
Jihoon Kang6da80752024-12-23 18:53:32 +0000651 if f.partitionName() == "recovery" {
652 rootDir = rootDir.Join(ctx, "root")
653 }
654
Cole Faust4e9f5922024-11-13 16:09:23 -0800655 fileListFile := android.PathForModuleOut(ctx, "fileList")
656 android.WriteFileRule(ctx, fileListFile, f.installedFilesList())
Cole Faust92ccbe22024-10-03 14:38:37 -0700657
Jihoon Kangf67b7de2025-02-12 01:01:09 +0000658 partitionName := f.partitionName()
659 if partitionName == "system" {
660 partitionName = ""
661 }
662 installedFileTxt, installedFileJson := buildInstalledFiles(ctx, partitionName, rootDir, f.output)
663
Spandan Dasd71af182025-02-12 18:03:29 +0000664 var erofsCompressHints android.Path
665 if f.properties.Erofs.Compress_hints != nil {
666 erofsCompressHints = android.PathForModuleSrc(ctx, *f.properties.Erofs.Compress_hints)
667 }
668
Spandan Das33c9c472025-01-14 19:26:23 +0000669 fsInfo := FilesystemInfo{
Yu Liu0a37d422025-02-13 02:05:00 +0000670 Output: f.OutputPath(),
671 SignedOutputPath: f.SignedOutputPath(),
Cole Faust74ee4e02025-01-16 14:55:35 -0800672 OutputHermetic: outputHermetic,
673 FileListFile: fileListFile,
674 RootDir: rootDir,
Cole Faustb36763e2025-02-18 15:21:44 -0800675 ExtraRootDirs: extraRootDirs,
Cole Faust74ee4e02025-01-16 14:55:35 -0800676 RebasedDir: rebasedDir,
677 MapFile: mapFile,
678 ModuleName: ctx.ModuleName(),
679 BuildImagePropFile: buildImagePropFile,
680 BuildImagePropFileDeps: buildImagePropFileDeps,
Cole Faustb8e280f2025-01-16 16:33:26 -0800681 SpecsForSystemOther: f.systemOtherFiles(ctx),
Cole Faust19fbb072025-01-30 18:19:29 -0800682 FullInstallPaths: fullInstallPaths,
Jihoon Kangf67b7de2025-02-12 01:01:09 +0000683 InstalledFiles: InstalledFilesStruct{
684 Txt: installedFileTxt,
685 Json: installedFileJson,
686 },
Spandan Dasd71af182025-02-12 18:03:29 +0000687 ErofsCompressHints: erofsCompressHints,
Spandan Dasf12ff9b2025-02-12 22:27:43 +0000688 SelinuxFc: f.selinuxFc,
Spandan Dasdd262fb2025-02-13 00:15:59 +0000689 FilesystemConfig: f.generateFilesystemConfig(ctx, rootDir, rebasedDir),
Jihoon Kangabec3ec2025-02-19 00:55:10 +0000690 Owners: f.gatherOwners(specs),
Spandan Das1f0a5a12025-01-15 00:53:15 +0000691 }
Spandan Das33c9c472025-01-14 19:26:23 +0000692
693 android.SetProvider(ctx, FilesystemProvider, fsInfo)
Spandan Das3ec6d062025-01-09 19:37:47 +0000694
Yu Liu71f1ea32025-02-26 23:39:20 +0000695 android.SetProvider(ctx, android.PartitionTypeInfoProvider, android.PartitionTypeInfo{
696 PartitionType: f.PartitionType(),
697 })
698
Cole Faust4e9f5922024-11-13 16:09:23 -0800699 f.fileListFile = fileListFile
Cole Faust92ccbe22024-10-03 14:38:37 -0700700
701 if proptools.Bool(f.properties.Unchecked_module) {
702 ctx.UncheckedModule()
703 }
Jihoon Kang2f0d1932025-01-17 19:22:44 +0000704
705 f.setVbmetaPartitionProvider(ctx)
706}
707
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000708func (f *filesystem) fileystemStagingDirTimestamp(ctx android.ModuleContext) android.WritablePath {
709 return android.PathForModuleOut(ctx, "staging_dir.timestamp")
710}
711
Spandan Dasdd262fb2025-02-13 00:15:59 +0000712func (f *filesystem) generateFilesystemConfig(ctx android.ModuleContext, rootDir android.Path, rebasedDir android.Path) android.Path {
713 rootDirString := rootDir.String()
714 prefix := f.partitionName() + "/"
715 if f.partitionName() == "system" {
716 rootDirString = rebasedDir.String()
717 }
718 if f.partitionName() == "ramdisk" || f.partitionName() == "recovery" {
719 // Hardcoded to match make behavior.
720 // https://cs.android.com/android/_/android/platform/build/+/2a0ef42a432d4da00201e8eb7697dcaa68fd2389:core/Makefile;l=6957-6962;drc=9ea8ad9232cef4d0a24d70133b1b9d2ce2defe5f;bpv=1;bpt=0
721 prefix = ""
722 }
723 out := android.PathForModuleOut(ctx, "filesystem_config.txt")
724 ctx.Build(pctx, android.BuildParams{
725 Rule: fsConfigRule,
726 Input: f.fileystemStagingDirTimestamp(ctx), // assemble the staging directory
727 Output: out,
728 Args: map[string]string{
729 "rootDir": rootDirString,
730 "prefix": prefix,
731 },
732 })
733 return out
734}
735
Jihoon Kang2f0d1932025-01-17 19:22:44 +0000736func (f *filesystem) setVbmetaPartitionProvider(ctx android.ModuleContext) {
737 var extractedPublicKey android.ModuleOutPath
738 if f.properties.Avb_private_key != nil {
739 key := android.PathForModuleSrc(ctx, proptools.String(f.properties.Avb_private_key))
740 extractedPublicKey = android.PathForModuleOut(ctx, f.partitionName()+".avbpubkey")
741 ctx.Build(pctx, android.BuildParams{
742 Rule: extractPublicKeyRule,
743 Input: key,
744 Output: extractedPublicKey,
745 })
746 }
747
748 var ril int
749 if f.properties.Rollback_index_location != nil {
750 ril = proptools.Int(f.properties.Rollback_index_location)
751 }
752
753 android.SetProvider(ctx, vbmetaPartitionProvider, vbmetaPartitionInfo{
754 Name: f.partitionName(),
755 RollbackIndexLocation: ril,
756 PublicKey: extractedPublicKey,
757 Output: f.output,
758 })
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900759}
760
Spandan Das33c9c472025-01-14 19:26:23 +0000761func (f *filesystem) getMapFile(ctx android.ModuleContext) android.WritablePath {
762 // create the filepath by replacing the extension of the corresponding img file
763 return android.PathForModuleOut(ctx, f.installFileName()).ReplaceExtension(ctx, "map")
764}
765
Kiyoung Kim23be5bb2024-11-27 00:50:30 +0000766func (f *filesystem) validateVintfFragments(ctx android.ModuleContext) {
767 visitedModule := map[string]bool{}
768 packagingSpecs := f.gatherFilteredPackagingSpecs(ctx)
769
770 moduleInFileSystem := func(mod android.Module) bool {
771 for _, ps := range android.OtherModuleProviderOrDefault(
772 ctx, mod, android.InstallFilesProvider).PackagingSpecs {
773 if _, ok := packagingSpecs[ps.RelPathInPackage()]; ok {
774 return true
775 }
776 }
777 return false
778 }
779
780 ctx.WalkDeps(func(child, parent android.Module) bool {
781 if visitedModule[child.Name()] {
782 return false
783 }
784 if !moduleInFileSystem(child) {
785 visitedModule[child.Name()] = true
786 return true
787 }
788 if vintfFragments := child.VintfFragments(ctx); vintfFragments != nil {
789 ctx.PropertyErrorf(
790 "vintf_fragments",
791 "Module %s is referenced by soong-defined filesystem %s with property vintf_fragments(%s) in use."+
792 " Use vintf_fragment_modules property instead.",
793 child.Name(),
794 f.BaseModuleName(),
795 strings.Join(vintfFragments, ", "),
796 )
797 }
798 visitedModule[child.Name()] = true
799 return true
800 })
801}
802
Cole Faust4e9f5922024-11-13 16:09:23 -0800803func (f *filesystem) appendToEntry(ctx android.ModuleContext, installedFile android.Path) {
Spandan Das420e16a2024-12-11 18:10:52 +0000804 partitionBaseDir := android.PathForModuleOut(ctx, f.rootDirString(), proptools.String(f.properties.Base_dir)).String() + "/"
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900805
806 relPath, inTargetPartition := strings.CutPrefix(installedFile.String(), partitionBaseDir)
807 if inTargetPartition {
808 f.entries = append(f.entries, relPath)
809 }
810}
811
812func (f *filesystem) installedFilesList() string {
813 installedFilePaths := android.FirstUniqueStrings(f.entries)
814 slices.Sort(installedFilePaths)
815
816 return strings.Join(installedFilePaths, "\n")
Jiyong Park11a65972021-02-01 21:09:38 +0900817}
818
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900819func validatePartitionType(ctx android.ModuleContext, p partition) {
820 if !android.InList(p.PartitionType(), validPartitions) {
821 ctx.PropertyErrorf("partition_type", "partition_type must be one of %s, found: %s", validPartitions, p.PartitionType())
822 }
823
Yu Liufc8d5c12025-01-09 00:19:06 +0000824 ctx.VisitDirectDepsProxyWithTag(android.DefaultsDepTag, func(m android.ModuleProxy) {
Yu Liu71f1ea32025-02-26 23:39:20 +0000825 if _, ok := android.OtherModuleProvider(ctx, m, FilesystemDefaultsInfoProvider); ok {
826 partitionInfo := android.OtherModuleProviderOrDefault(ctx, m, android.PartitionTypeInfoProvider)
827 if p.PartitionType() != partitionInfo.PartitionType {
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900828 ctx.PropertyErrorf("partition_type",
829 "%s doesn't match with the partition type %s of the filesystem default module %s",
Yu Liu71f1ea32025-02-26 23:39:20 +0000830 p.PartitionType(), partitionInfo.PartitionType, m.Name())
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900831 }
832 }
833 })
834}
835
Cole Faust3b806d32024-03-11 15:15:03 -0700836// Copy extra files/dirs that are not from the `deps` property to `rootDir`, checking for conflicts with files
837// already in `rootDir`.
Cole Faust19fbb072025-01-30 18:19:29 -0800838func (f *filesystem) buildNonDepsFiles(
839 ctx android.ModuleContext,
840 builder *android.RuleBuilder,
841 rootDir android.OutputPath,
842 rebasedDir android.OutputPath,
843 fullInstallPaths *[]FullInstallPathInfo,
844) {
845 rebasedPrefix, err := filepath.Rel(rootDir.String(), rebasedDir.String())
846 if err != nil || strings.HasPrefix(rebasedPrefix, "../") {
847 panic("rebasedDir could not be made relative to rootDir")
848 }
849 if !strings.HasSuffix(rebasedPrefix, "/") {
850 rebasedPrefix += "/"
851 }
852 if rebasedPrefix == "./" {
853 rebasedPrefix = ""
854 }
855
Inseob Kim14199b02021-02-09 21:18:31 +0900856 // create dirs and symlinks
Cole Faustd9c6a5b2024-05-21 14:54:00 -0700857 for _, dir := range f.properties.Dirs.GetOrDefault(ctx, nil) {
Inseob Kim14199b02021-02-09 21:18:31 +0900858 // OutputPath.Join verifies dir
859 builder.Command().Text("mkdir -p").Text(rootDir.Join(ctx, dir).String())
Cole Faust19fbb072025-01-30 18:19:29 -0800860 // Only add the fullInstallPath logic for files in the rebased dir. The root dir
861 // is harder to install to.
862 if strings.HasPrefix(dir, rebasedPrefix) {
863 *fullInstallPaths = append(*fullInstallPaths, FullInstallPathInfo{
864 FullInstallPath: android.PathForModuleInPartitionInstall(ctx, f.PartitionType(), strings.TrimPrefix(dir, rebasedPrefix)),
865 IsDir: true,
866 })
867 }
Inseob Kim14199b02021-02-09 21:18:31 +0900868 }
869
870 for _, symlink := range f.properties.Symlinks {
871 name := strings.TrimSpace(proptools.String(symlink.Name))
872 target := strings.TrimSpace(proptools.String(symlink.Target))
873
874 if name == "" {
875 ctx.PropertyErrorf("symlinks", "Name can't be empty")
876 continue
877 }
878
879 if target == "" {
880 ctx.PropertyErrorf("symlinks", "Target can't be empty")
881 continue
882 }
883
884 // OutputPath.Join verifies name. don't need to verify target.
885 dst := rootDir.Join(ctx, name)
Cole Faust3b806d32024-03-11 15:15:03 -0700886 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 +0900887 builder.Command().Text("mkdir -p").Text(filepath.Dir(dst.String()))
888 builder.Command().Text("ln -sf").Text(proptools.ShellEscape(target)).Text(dst.String())
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900889 f.appendToEntry(ctx, dst)
Cole Faust19fbb072025-01-30 18:19:29 -0800890 // Only add the fullInstallPath logic for files in the rebased dir. The root dir
891 // is harder to install to.
892 if strings.HasPrefix(name, rebasedPrefix) {
893 *fullInstallPaths = append(*fullInstallPaths, FullInstallPathInfo{
894 FullInstallPath: android.PathForModuleInPartitionInstall(ctx, f.PartitionType(), strings.TrimPrefix(name, rebasedPrefix)),
895 SymlinkTarget: target,
896 })
897 }
Inseob Kim14199b02021-02-09 21:18:31 +0900898 }
Jihoon Kang89e8a692024-12-18 19:28:33 +0000899
900 // https://cs.android.com/android/platform/superproject/main/+/main:build/make/core/Makefile;l=2835;drc=b186569ef00ff2f2a1fab28aedc75ebc32bcd67b
901 if f.partitionName() == "recovery" {
902 builder.Command().Text("mkdir -p").Text(rootDir.Join(ctx, "root/linkerconfig").String())
903 builder.Command().Text("touch").Text(rootDir.Join(ctx, "root/linkerconfig/ld.config.txt").String())
904 }
Inseob Kim2ce1b5d2021-02-15 17:01:04 +0900905}
906
Inseob Kim33f95a92024-07-11 15:44:49 +0900907func (f *filesystem) copyPackagingSpecs(ctx android.ModuleContext, builder *android.RuleBuilder, specs map[string]android.PackagingSpec, rootDir, rebasedDir android.WritablePath) []string {
908 rootDirSpecs := make(map[string]android.PackagingSpec)
909 rebasedDirSpecs := make(map[string]android.PackagingSpec)
910
911 for rel, spec := range specs {
912 if spec.Partition() == "root" {
913 rootDirSpecs[rel] = spec
914 } else {
915 rebasedDirSpecs[rel] = spec
916 }
917 }
918
919 dirsToSpecs := make(map[android.WritablePath]map[string]android.PackagingSpec)
920 dirsToSpecs[rootDir] = rootDirSpecs
921 dirsToSpecs[rebasedDir] = rebasedDirSpecs
922
Cole Fauste3845052025-02-13 12:45:35 -0800923 // Preserve timestamps for adb sync, so that this staging dir file matches the timestamp in the
924 // out/target/product staging directory.
925 return f.CopySpecsToDirs(ctx, builder, dirsToSpecs, true)
Inseob Kim33f95a92024-07-11 15:44:49 +0900926}
927
Spandan Das420e16a2024-12-11 18:10:52 +0000928func (f *filesystem) rootDirString() string {
929 return f.partitionName()
930}
931
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000932type buildImageParams struct {
933 // inputs
934 rootDir android.OutputPath
935 propFile android.Path
936 toolDeps android.Paths
937 // outputs
938 output android.WritablePath
939}
940
Cole Faust62cfaeb2025-01-15 18:06:40 -0800941func (f *filesystem) buildImageUsingBuildImage(
942 ctx android.ModuleContext,
943 builder *android.RuleBuilder,
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000944 params buildImageParams) {
Nikita Ioffe519015f2022-12-23 15:36:29 +0000945 // run host_init_verifier
946 // Ideally we should have a concept of pluggable linters that verify the generated image.
947 // While such concept is not implement this will do.
948 // TODO(b/263574231): substitute with pluggable linter.
949 builder.Command().
950 BuiltTool("host_init_verifier").
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000951 FlagWithArg("--out_system=", params.rootDir.String()+"/system")
Cole Fauste1676122024-12-03 17:32:25 -0800952
953 // Most of the time, if build_image were to call a host tool, it accepts the path to the
954 // host tool in a field in the prop file. However, it doesn't have that option for fec, which
955 // it expects to just be on the PATH. Add fec to the PATH.
956 fec := ctx.Config().HostToolPath(ctx, "fec")
957 pathToolDirs := []string{filepath.Dir(fec.String())}
958
Cole Fauste1676122024-12-03 17:32:25 -0800959 builder.Command().
960 Textf("PATH=%s:$PATH", strings.Join(pathToolDirs, ":")).
961 BuiltTool("build_image").
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000962 Text(params.rootDir.String()). // input directory
963 Input(params.propFile).
964 Implicits(params.toolDeps).
Cole Fauste1676122024-12-03 17:32:25 -0800965 Implicit(fec).
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000966 Implicit(f.fileystemStagingDirTimestamp(ctx)). // assemble the staging directory
967 Output(params.output).
968 Text(params.rootDir.String()) // directory where to find fs_config_files|dirs
Spandan Das1f0a5a12025-01-15 00:53:15 +0000969
Jihoon Kang983dd882025-01-13 23:14:11 +0000970 if f.properties.Partition_size != nil {
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000971 assertMaxImageSize(builder, params.output, *f.properties.Partition_size, false)
Jihoon Kang983dd882025-01-13 23:14:11 +0000972 }
973
Jiyong Park6f0f6882020-11-12 13:14:30 +0900974 // rootDir is not deleted. Might be useful for quick inspection.
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000975 builder.Build("build_"+params.output.String(), fmt.Sprintf("Creating filesystem %s", f.BaseModuleName()))
976}
Jiyong Park65c49f52020-11-24 14:23:26 +0900977
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000978func (f *filesystem) propFileForHermeticImg(ctx android.ModuleContext, builder *android.RuleBuilder, inputPropFile android.Path) android.Path {
979 propFilePinnedTimestamp := android.PathForModuleOut(ctx, "for_target_files", "prop")
980 builder.Command().Textf("cat").Input(inputPropFile).Flag(">").Output(propFilePinnedTimestamp).
981 Textf(" && echo use_fixed_timestamp=true >> %s", propFilePinnedTimestamp).
982 Textf(" && echo block_list=%s >> %s", f.getMapFile(ctx).String(), propFilePinnedTimestamp) // mapfile will be an implicit output
983 builder.Command().Text("touch").Output(f.getMapFile(ctx))
984 return propFilePinnedTimestamp
Jiyong Park65c49f52020-11-24 14:23:26 +0900985}
986
Cole Faust4e9f5922024-11-13 16:09:23 -0800987func (f *filesystem) buildFileContexts(ctx android.ModuleContext) android.Path {
Inseob Kimcc8e5362021-02-03 14:05:24 +0900988 builder := android.NewRuleBuilder(pctx, ctx)
989 fcBin := android.PathForModuleOut(ctx, "file_contexts.bin")
990 builder.Command().BuiltTool("sefcontext_compile").
991 FlagWithOutput("-o ", fcBin).
992 Input(android.PathForModuleSrc(ctx, proptools.String(f.properties.File_contexts)))
993 builder.Build("build_filesystem_file_contexts", fmt.Sprintf("Creating filesystem file contexts for %s", f.BaseModuleName()))
Cole Faust4e9f5922024-11-13 16:09:23 -0800994 return fcBin
Inseob Kimcc8e5362021-02-03 14:05:24 +0900995}
996
Cole Faust4e9f5922024-11-13 16:09:23 -0800997func (f *filesystem) buildPropFile(ctx android.ModuleContext) (android.Path, android.Paths) {
Jiyong Park72678312021-01-18 17:29:49 +0900998 var deps android.Paths
Cole Fauste03ab892025-01-17 13:55:04 -0800999 var lines []string
Jiyong Park72678312021-01-18 17:29:49 +09001000 addStr := func(name string, value string) {
Cole Fauste03ab892025-01-17 13:55:04 -08001001 lines = append(lines, fmt.Sprintf("%s=%s", name, value))
Jiyong Park72678312021-01-18 17:29:49 +09001002 }
1003 addPath := func(name string, path android.Path) {
Cole Faustcec230a2024-03-07 15:51:12 -08001004 addStr(name, path.String())
Jiyong Park72678312021-01-18 17:29:49 +09001005 deps = append(deps, path)
1006 }
1007
Jiyong Park11a65972021-02-01 21:09:38 +09001008 // Type string that build_image.py accepts.
1009 fsTypeStr := func(t fsType) string {
1010 switch t {
Spandan Das94668822024-10-09 20:51:33 +00001011 // TODO(372522486): add more types like f2fs, erofs, etc.
Jiyong Park11a65972021-02-01 21:09:38 +09001012 case ext4Type:
1013 return "ext4"
Spandan Dasc35d6fb2024-10-10 17:51:14 +00001014 case erofsType:
1015 return "erofs"
mrziwang1a6291f2024-11-07 14:29:25 -08001016 case f2fsType:
1017 return "f2fs"
Jiyong Park11a65972021-02-01 21:09:38 +09001018 }
1019 panic(fmt.Errorf("unsupported fs type %v", t))
1020 }
1021
1022 addStr("fs_type", fsTypeStr(f.fsType(ctx)))
Inseob Kim376d72f2023-11-01 15:40:25 +09001023 addStr("mount_point", proptools.StringDefault(f.properties.Mount_point, "/"))
Jiyong Park72678312021-01-18 17:29:49 +09001024 addStr("use_dynamic_partition_size", "true")
1025 addPath("ext_mkuserimg", ctx.Config().HostToolPath(ctx, "mkuserimg_mke2fs"))
1026 // b/177813163 deps of the host tools have to be added. Remove this.
1027 for _, t := range []string{"mke2fs", "e2fsdroid", "tune2fs"} {
1028 deps = append(deps, ctx.Config().HostToolPath(ctx, t))
1029 }
1030
Jiyong Park71baa762021-01-18 21:11:03 +09001031 if proptools.Bool(f.properties.Use_avb) {
1032 addStr("avb_hashtree_enable", "true")
1033 addPath("avb_avbtool", ctx.Config().HostToolPath(ctx, "avbtool"))
1034 algorithm := proptools.StringDefault(f.properties.Avb_algorithm, "SHA256_RSA4096")
1035 addStr("avb_algorithm", algorithm)
Cole Fauste1676122024-12-03 17:32:25 -08001036 if f.properties.Avb_private_key != nil {
1037 key := android.PathForModuleSrc(ctx, *f.properties.Avb_private_key)
1038 addPath("avb_key_path", key)
1039 }
Inseob Kim53391842024-03-29 17:44:07 +09001040 addStr("partition_name", f.partitionName())
Cole Fauste1676122024-12-03 17:32:25 -08001041 avb_add_hashtree_footer_args := ""
1042 if !proptools.BoolDefault(f.properties.Use_fec, true) {
1043 avb_add_hashtree_footer_args += " --do_not_generate_fec"
1044 }
Nikita Ioffe50fb49c2025-01-24 13:49:00 +00001045 hashAlgorithm := proptools.StringDefault(f.properties.Avb_hash_algorithm, "sha256")
1046 avb_add_hashtree_footer_args += " --hash_algorithm " + hashAlgorithm
Nikita Ioffe2c8cdc62024-03-27 22:19:30 +00001047 if f.properties.Rollback_index != nil {
1048 rollbackIndex := proptools.Int(f.properties.Rollback_index)
1049 if rollbackIndex < 0 {
1050 ctx.PropertyErrorf("rollback_index", "Rollback index must be non-negative")
1051 }
1052 avb_add_hashtree_footer_args += " --rollback_index " + strconv.Itoa(rollbackIndex)
1053 }
Cole Fauste1676122024-12-03 17:32:25 -08001054 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 -08001055 // We're not going to add BuildFingerPrintFile as a dep. If it changed, it's likely because
1056 // the build number changed, and we don't want to trigger rebuilds solely based on the build
1057 // number.
Cole Fauste1676122024-12-03 17:32:25 -08001058 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 +00001059 if f.properties.Security_patch != nil && proptools.String(f.properties.Security_patch) != "" {
1060 avb_add_hashtree_footer_args += fmt.Sprintf(" --prop com.android.build.%s.security_patch:%s", f.partitionName(), proptools.String(f.properties.Security_patch))
1061 }
Shikha Panware6f30632022-12-21 12:54:45 +00001062 addStr("avb_add_hashtree_footer_args", avb_add_hashtree_footer_args)
Jiyong Park71baa762021-01-18 21:11:03 +09001063 }
1064
Cole Faust0d467052024-12-04 17:19:19 -08001065 if f.properties.File_contexts != nil && f.properties.Precompiled_file_contexts != nil {
1066 ctx.ModuleErrorf("file_contexts and precompiled_file_contexts cannot both be set")
1067 } else if f.properties.File_contexts != nil {
Spandan Dasf12ff9b2025-02-12 22:27:43 +00001068 f.selinuxFc = f.buildFileContexts(ctx)
Cole Faust0d467052024-12-04 17:19:19 -08001069 } else if f.properties.Precompiled_file_contexts != nil {
Spandan Dasf12ff9b2025-02-12 22:27:43 +00001070 f.selinuxFc = android.PathForModuleSrc(ctx, *f.properties.Precompiled_file_contexts)
1071 }
1072 if f.selinuxFc != nil {
1073 addPath("selinux_fc", f.selinuxFc)
Inseob Kimcc8e5362021-02-03 14:05:24 +09001074 }
Jooyung Han65f402b2022-04-21 14:24:04 +09001075 if timestamp := proptools.String(f.properties.Fake_timestamp); timestamp != "" {
1076 addStr("timestamp", timestamp)
Spandan Dasa0ddc512025-01-06 20:23:55 +00001077 } else if ctx.Config().Getenv("USE_FIXED_TIMESTAMP_IMG_FILES") == "true" {
1078 addStr("use_fixed_timestamp", "true")
Jooyung Han65f402b2022-04-21 14:24:04 +09001079 }
Spandan Dasa0ddc512025-01-06 20:23:55 +00001080
Jooyung Han65f402b2022-04-21 14:24:04 +09001081 if uuid := proptools.String(f.properties.Uuid); uuid != "" {
1082 addStr("uuid", uuid)
1083 addStr("hash_seed", uuid)
1084 }
mrziwang1a6291f2024-11-07 14:29:25 -08001085
Jihoon Kang40551e62025-01-14 21:55:08 +00001086 // Disable sparse only when partition size is not defined. disable_sparse has the same
1087 // effect as <partition name>_disable_sparse.
1088 if f.properties.Partition_size == nil {
1089 addStr("disable_sparse", "true")
1090 }
Cole Faust43a52c72024-11-26 12:46:08 -08001091
mrziwang1a6291f2024-11-07 14:29:25 -08001092 fst := f.fsType(ctx)
1093 switch fst {
1094 case erofsType:
1095 // Add erofs properties
Cole Faust3e730972024-12-03 13:12:08 -08001096 addStr("erofs_default_compressor", proptools.StringDefault(f.properties.Erofs.Compressor, "lz4hc,9"))
1097 if f.properties.Erofs.Compress_hints != nil {
1098 src := android.PathForModuleSrc(ctx, *f.properties.Erofs.Compress_hints)
1099 addPath("erofs_default_compress_hints", src)
Spandan Dasc35d6fb2024-10-10 17:51:14 +00001100 }
1101 if proptools.BoolDefault(f.properties.Erofs.Sparse, true) {
1102 // https://source.corp.google.com/h/googleplex-android/platform/build/+/88b1c67239ca545b11580237242774b411f2fed9:core/Makefile;l=2292;bpv=1;bpt=0;drc=ea8f34bc1d6e63656b4ec32f2391e9d54b3ebb6b
1103 addStr("erofs_sparse_flag", "-s")
1104 }
mrziwang1a6291f2024-11-07 14:29:25 -08001105 case f2fsType:
1106 if proptools.BoolDefault(f.properties.F2fs.Sparse, true) {
1107 // https://source.corp.google.com/h/googleplex-android/platform/build/+/88b1c67239ca545b11580237242774b411f2fed9:core/Makefile;l=2294;drc=ea8f34bc1d6e63656b4ec32f2391e9d54b3ebb6b;bpv=1;bpt=0
1108 addStr("f2fs_sparse_flag", "-S")
1109 }
Spandan Dasc35d6fb2024-10-10 17:51:14 +00001110 }
mrziwang1a6291f2024-11-07 14:29:25 -08001111 f.checkFsTypePropertyError(ctx, fst, fsTypeStr(fst))
Spandan Dasc35d6fb2024-10-10 17:51:14 +00001112
Jihoon Kang983dd882025-01-13 23:14:11 +00001113 if f.properties.Partition_size != nil {
1114 addStr("partition_size", strconv.FormatInt(*f.properties.Partition_size, 10))
1115 }
1116
Jihoon Kang6d08d922025-01-14 18:31:57 +00001117 if proptools.BoolDefault(f.properties.Support_casefolding, false) {
1118 addStr("needs_casefold", "1")
1119 }
1120
1121 if proptools.BoolDefault(f.properties.Support_project_quota, false) {
1122 addStr("needs_projid", "1")
1123 }
1124
1125 if proptools.BoolDefault(f.properties.Enable_compression, false) {
1126 addStr("needs_compress", "1")
1127 }
1128
Cole Fauste03ab892025-01-17 13:55:04 -08001129 sort.Strings(lines)
1130
Cole Fauste1676122024-12-03 17:32:25 -08001131 propFilePreProcessing := android.PathForModuleOut(ctx, "prop_pre_processing")
Cole Fauste03ab892025-01-17 13:55:04 -08001132 android.WriteFileRule(ctx, propFilePreProcessing, strings.Join(lines, "\n"))
Cole Faust4e9f5922024-11-13 16:09:23 -08001133 propFile := android.PathForModuleOut(ctx, "prop")
Cole Fauste1676122024-12-03 17:32:25 -08001134 ctx.Build(pctx, android.BuildParams{
Cole Faustefeb5c42024-12-16 10:47:26 -08001135 Rule: textFileProcessorRule,
1136 Input: propFilePreProcessing,
1137 Output: propFile,
Cole Fauste1676122024-12-03 17:32:25 -08001138 })
Jiyong Park72678312021-01-18 17:29:49 +09001139 return propFile, deps
1140}
1141
mrziwang1a6291f2024-11-07 14:29:25 -08001142// This method checks if there is any property set for the fstype(s) other than
1143// the current fstype.
1144func (f *filesystem) checkFsTypePropertyError(ctx android.ModuleContext, t fsType, fs string) {
1145 raiseError := func(otherFsType, currentFsType string) {
1146 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)
1147 ctx.PropertyErrorf(otherFsType, errMsg)
1148 }
1149
1150 if t != erofsType {
1151 if f.properties.Erofs.Compressor != nil || f.properties.Erofs.Compress_hints != nil || f.properties.Erofs.Sparse != nil {
1152 raiseError("erofs", fs)
1153 }
1154 }
1155 if t != f2fsType {
1156 if f.properties.F2fs.Sparse != nil {
1157 raiseError("f2fs", fs)
1158 }
1159 }
1160}
1161
Jihoon Kang6da80752024-12-23 18:53:32 +00001162func includeFilesRootDir(ctx android.ModuleContext) (rootDirs android.Paths, partitions android.Paths) {
1163 ctx.VisitDirectDepsWithTag(interPartitionInstallDependencyTag, func(m android.Module) {
1164 if fsProvider, ok := android.OtherModuleProvider(ctx, m, FilesystemProvider); ok {
1165 rootDirs = append(rootDirs, fsProvider.RootDir)
1166 partitions = append(partitions, fsProvider.Output)
1167 } else {
1168 ctx.PropertyErrorf("include_files_of", "only filesystem modules can be listed in "+
1169 "include_files_of but %s is not a filesystem module", m.Name())
1170 }
1171 })
1172 return rootDirs, partitions
1173}
1174
Cole Faust62cfaeb2025-01-15 18:06:40 -08001175func (f *filesystem) buildCpioImage(
1176 ctx android.ModuleContext,
1177 builder *android.RuleBuilder,
1178 rootDir android.OutputPath,
1179 compressed bool,
Cole Faustb36763e2025-02-18 15:21:44 -08001180) (android.Path, android.Paths) {
Jiyong Park11a65972021-02-01 21:09:38 +09001181 if proptools.Bool(f.properties.Use_avb) {
1182 ctx.PropertyErrorf("use_avb", "signing compresed cpio image using avbtool is not supported."+
1183 "Consider adding this to bootimg module and signing the entire boot image.")
1184 }
1185
Inseob Kimcc8e5362021-02-03 14:05:24 +09001186 if proptools.String(f.properties.File_contexts) != "" {
1187 ctx.PropertyErrorf("file_contexts", "file_contexts is not supported for compressed cpio image.")
1188 }
1189
Jihoon Kang6da80752024-12-23 18:53:32 +00001190 rootDirs, partitions := includeFilesRootDir(ctx)
1191
Cole Faust4e9f5922024-11-13 16:09:23 -08001192 output := android.PathForModuleOut(ctx, f.installFileName())
Jiyong Park837cdb22021-02-05 00:17:14 +09001193 cmd := builder.Command().
Jiyong Park11a65972021-02-01 21:09:38 +09001194 BuiltTool("mkbootfs").
Spandan Das5ef1a9c2025-02-11 18:50:17 +00001195 Implicit(f.fileystemStagingDirTimestamp(ctx)).
Jiyong Park837cdb22021-02-05 00:17:14 +09001196 Text(rootDir.String()) // input directory
Jihoon Kang6da80752024-12-23 18:53:32 +00001197
1198 for i := range len(rootDirs) {
1199 cmd.Text(rootDirs[i].String())
1200 }
1201 cmd.Implicits(partitions)
1202
Jihoon Kang6c03c8e2024-11-18 21:30:22 +00001203 if nodeList := f.properties.Dev_nodes_description_file; nodeList != nil {
1204 cmd.FlagWithInput("-n ", android.PathForModuleSrc(ctx, proptools.String(nodeList)))
1205 }
Jiyong Park837cdb22021-02-05 00:17:14 +09001206 if compressed {
1207 cmd.Text("|").
1208 BuiltTool("lz4").
1209 Flag("--favor-decSpeed"). // for faster boot
1210 Flag("-12"). // maximum compression level
1211 Flag("-l"). // legacy format for kernel
1212 Text(">").Output(output)
1213 } else {
1214 cmd.Text(">").Output(output)
1215 }
Jiyong Park11a65972021-02-01 21:09:38 +09001216
1217 // rootDir is not deleted. Might be useful for quick inspection.
Jiyong Park837cdb22021-02-05 00:17:14 +09001218 builder.Build("build_cpio_image", fmt.Sprintf("Creating filesystem %s", f.BaseModuleName()))
Jiyong Park11a65972021-02-01 21:09:38 +09001219
Cole Faustb36763e2025-02-18 15:21:44 -08001220 return output, rootDirs
Jiyong Park11a65972021-02-01 21:09:38 +09001221}
1222
Cole Faust4a2a7c92024-03-12 12:44:40 -07001223var validPartitions = []string{
1224 "system",
1225 "userdata",
1226 "cache",
1227 "system_other",
1228 "vendor",
1229 "product",
1230 "system_ext",
1231 "odm",
1232 "vendor_dlkm",
1233 "odm_dlkm",
1234 "system_dlkm",
Cole Faust76a6e952024-11-07 16:56:45 -08001235 "ramdisk",
Cole Faust24938e22024-11-18 14:01:58 -08001236 "vendor_ramdisk",
Jihoon Kang3216c982024-12-02 19:42:20 +00001237 "recovery",
Cole Faust4a2a7c92024-03-12 12:44:40 -07001238}
1239
Cole Faust19fbb072025-01-30 18:19:29 -08001240func (f *filesystem) buildEventLogtagsFile(
1241 ctx android.ModuleContext,
1242 builder *android.RuleBuilder,
1243 rebasedDir android.OutputPath,
1244 fullInstallPaths *[]FullInstallPathInfo,
1245) {
Inseob Kimb7b84572024-04-30 10:51:47 +09001246 if !proptools.Bool(f.properties.Build_logtags) {
1247 return
1248 }
1249
Inseob Kimb7b84572024-04-30 10:51:47 +09001250 etcPath := rebasedDir.Join(ctx, "etc")
1251 eventLogtagsPath := etcPath.Join(ctx, "event-log-tags")
1252 builder.Command().Text("mkdir").Flag("-p").Text(etcPath.String())
Cole Fauste4506af2024-12-11 14:14:50 -08001253 builder.Command().Text("cp").Input(android.MergedLogtagsPath(ctx)).Text(eventLogtagsPath.String())
Kiyoung Kim99a954d2024-06-21 14:22:20 +09001254
Cole Faust19fbb072025-01-30 18:19:29 -08001255 *fullInstallPaths = append(*fullInstallPaths, FullInstallPathInfo{
1256 FullInstallPath: android.PathForModuleInPartitionInstall(ctx, f.PartitionType(), "etc", "event-log-tags"),
1257 SourcePath: android.MergedLogtagsPath(ctx),
1258 })
1259
Kiyoung Kim99a954d2024-06-21 14:22:20 +09001260 f.appendToEntry(ctx, eventLogtagsPath)
Inseob Kimb7b84572024-04-30 10:51:47 +09001261}
1262
Cole Faust19fbb072025-01-30 18:19:29 -08001263func (f *filesystem) BuildLinkerConfigFile(
1264 ctx android.ModuleContext,
1265 builder *android.RuleBuilder,
1266 rebasedDir android.OutputPath,
1267 fullInstallPaths *[]FullInstallPathInfo,
1268) {
Spandan Das2047a4c2024-11-11 21:24:58 +00001269 if !proptools.Bool(f.properties.Linker_config.Gen_linker_config) {
Spandan Das92631882024-10-28 22:49:38 +00001270 return
1271 }
1272
Spandan Das918191e2024-10-31 18:27:23 +00001273 provideModules, _ := f.getLibsForLinkerConfig(ctx)
Cole Faustfee27012024-12-13 14:10:31 -08001274 intermediateOutput := android.PathForModuleOut(ctx, "linker.config.pb")
1275 linkerconfig.BuildLinkerConfig(ctx, android.PathsForModuleSrc(ctx, f.properties.Linker_config.Linker_config_srcs), provideModules, nil, intermediateOutput)
Spandan Das92631882024-10-28 22:49:38 +00001276 output := rebasedDir.Join(ctx, "etc", "linker.config.pb")
Cole Faustfee27012024-12-13 14:10:31 -08001277 builder.Command().Text("cp").Input(intermediateOutput).Output(output)
Spandan Das92631882024-10-28 22:49:38 +00001278
Cole Faust19fbb072025-01-30 18:19:29 -08001279 *fullInstallPaths = append(*fullInstallPaths, FullInstallPathInfo{
1280 FullInstallPath: android.PathForModuleInPartitionInstall(ctx, f.PartitionType(), "etc", "linker.config.pb"),
1281 SourcePath: intermediateOutput,
1282 })
1283
Spandan Das92631882024-10-28 22:49:38 +00001284 f.appendToEntry(ctx, output)
1285}
1286
Kiyoung Kim23be5bb2024-11-27 00:50:30 +00001287func (f *filesystem) ShouldUseVintfFragmentModuleOnly() bool {
1288 return false
1289}
1290
Jiyong Parkf46b1af2024-04-05 18:13:33 +09001291type partition interface {
1292 PartitionType() string
1293}
1294
Cole Faust9a24d902024-03-18 15:38:12 -07001295func (f *filesystem) PartitionType() string {
1296 return proptools.StringDefault(f.properties.Partition_type, "system")
1297}
1298
Jiyong Parkf46b1af2024-04-05 18:13:33 +09001299var _ partition = (*filesystem)(nil)
1300
Jiyong Park65c49f52020-11-24 14:23:26 +09001301var _ android.AndroidMkEntriesProvider = (*filesystem)(nil)
1302
1303// Implements android.AndroidMkEntriesProvider
1304func (f *filesystem) AndroidMkEntries() []android.AndroidMkEntries {
1305 return []android.AndroidMkEntries{android.AndroidMkEntries{
1306 Class: "ETC",
1307 OutputFile: android.OptionalPathForPath(f.output),
1308 ExtraEntries: []android.AndroidMkExtraEntriesFunc{
Colin Crossaa255532020-07-03 13:18:24 -07001309 func(ctx android.AndroidMkExtraEntriesContext, entries *android.AndroidMkEntries) {
Colin Crossc68db4b2021-11-11 18:59:15 -08001310 entries.SetString("LOCAL_MODULE_PATH", f.installDir.String())
Jiyong Park65c49f52020-11-24 14:23:26 +09001311 entries.SetString("LOCAL_INSTALLED_MODULE_STEM", f.installFileName())
Kiyoung Kim99a954d2024-06-21 14:22:20 +09001312 entries.SetString("LOCAL_FILESYSTEM_FILELIST", f.fileListFile.String())
Jiyong Park65c49f52020-11-24 14:23:26 +09001313 },
1314 },
1315 }}
Jiyong Park6f0f6882020-11-12 13:14:30 +09001316}
Jiyong Park12a719c2021-01-07 15:31:24 +09001317
1318// Filesystem is the public interface for the filesystem struct. Currently, it's only for the apex
1319// package to have access to the output file.
1320type Filesystem interface {
1321 android.Module
1322 OutputPath() android.Path
Jiyong Park972e06c2021-03-15 23:32:49 +09001323
1324 // Returns the output file that is signed by avbtool. If this module is not signed, returns
1325 // nil.
1326 SignedOutputPath() android.Path
Jiyong Park12a719c2021-01-07 15:31:24 +09001327}
1328
1329var _ Filesystem = (*filesystem)(nil)
1330
1331func (f *filesystem) OutputPath() android.Path {
1332 return f.output
1333}
Jiyong Park972e06c2021-03-15 23:32:49 +09001334
1335func (f *filesystem) SignedOutputPath() android.Path {
1336 if proptools.Bool(f.properties.Use_avb) {
1337 return f.OutputPath()
1338 }
1339 return nil
1340}
Jooyung Han0fbbc2b2022-03-25 12:35:46 +09001341
1342// Filter the result of GatherPackagingSpecs to discard items targeting outside "system" partition.
1343// Note that "apex" module installs its contents to "apex"(fake partition) as well
1344// for symbol lookup by imitating "activated" paths.
1345func (f *filesystem) gatherFilteredPackagingSpecs(ctx android.ModuleContext) map[string]android.PackagingSpec {
Cole Faustb8e280f2025-01-16 16:33:26 -08001346 return f.PackagingBase.GatherPackagingSpecsWithFilterAndModifier(ctx, f.filesystemBuilder.FilterPackagingSpec, f.filesystemBuilder.ModifyPackagingSpec)
1347}
1348
Jihoon Kangabec3ec2025-02-19 00:55:10 +00001349func (f *filesystem) gatherOwners(specs map[string]android.PackagingSpec) []InstalledModuleInfo {
1350 var owners []InstalledModuleInfo
1351 for _, p := range android.SortedKeys(specs) {
1352 spec := specs[p]
1353 owners = append(owners, InstalledModuleInfo{
1354 Name: spec.Owner(),
1355 Variation: spec.Variation(),
1356 })
1357 }
1358 return owners
1359}
1360
Cole Faustb8e280f2025-01-16 16:33:26 -08001361// Dexpreopt files are installed to system_other. Collect the packaingSpecs for the dexpreopt files
1362// from this partition to export to the system_other partition later.
1363func (f *filesystem) systemOtherFiles(ctx android.ModuleContext) map[string]android.PackagingSpec {
1364 filter := func(spec android.PackagingSpec) bool {
1365 // For some reason system_other packaging specs don't set the partition field.
1366 return strings.HasPrefix(spec.RelPathInPackage(), "system_other/")
1367 }
1368 modifier := func(spec *android.PackagingSpec) {
1369 spec.SetRelPathInPackage(strings.TrimPrefix(spec.RelPathInPackage(), "system_other/"))
1370 spec.SetPartition("system_other")
1371 }
1372 return f.PackagingBase.GatherPackagingSpecsWithFilterAndModifier(ctx, filter, modifier)
Jooyung Han0fbbc2b2022-03-25 12:35:46 +09001373}
Jooyung Han65f402b2022-04-21 14:24:04 +09001374
1375func sha1sum(values []string) string {
1376 h := sha256.New()
1377 for _, value := range values {
1378 io.WriteString(h, value)
1379 }
1380 return fmt.Sprintf("%x", h.Sum(nil))
1381}
Jooyung Hane6067592023-03-16 13:11:17 +09001382
1383// Base cc.UseCoverage
1384
1385var _ cc.UseCoverage = (*filesystem)(nil)
1386
Colin Crosse1a85552024-06-14 12:17:37 -07001387func (*filesystem) IsNativeCoverageNeeded(ctx cc.IsNativeCoverageNeededContext) bool {
Jooyung Hane6067592023-03-16 13:11:17 +09001388 return ctx.Device() && ctx.DeviceConfig().NativeCoverageEnabled()
1389}
Jiyong Parkf46b1af2024-04-05 18:13:33 +09001390
1391// android_filesystem_defaults
1392
1393type filesystemDefaults struct {
1394 android.ModuleBase
1395 android.DefaultsModuleBase
1396
Inseob Kim3c0a0422024-11-05 17:21:37 +09001397 properties FilesystemProperties
Jiyong Parkf46b1af2024-04-05 18:13:33 +09001398}
1399
1400// android_filesystem_defaults is a default module for android_filesystem and android_system_image
1401func filesystemDefaultsFactory() android.Module {
1402 module := &filesystemDefaults{}
1403 module.AddProperties(&module.properties)
1404 module.AddProperties(&android.PackagingProperties{})
1405 android.InitDefaultsModule(module)
1406 return module
1407}
1408
1409func (f *filesystemDefaults) PartitionType() string {
1410 return proptools.StringDefault(f.properties.Partition_type, "system")
1411}
1412
1413var _ partition = (*filesystemDefaults)(nil)
1414
1415func (f *filesystemDefaults) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1416 validatePartitionType(ctx, f)
Yu Liu71f1ea32025-02-26 23:39:20 +00001417 android.SetProvider(ctx, FilesystemDefaultsInfoProvider, FilesystemDefaultsInfo{})
1418 android.SetProvider(ctx, android.PartitionTypeInfoProvider, android.PartitionTypeInfo{
Yu Liufc8d5c12025-01-09 00:19:06 +00001419 PartitionType: f.PartitionType(),
1420 })
Jiyong Parkf46b1af2024-04-05 18:13:33 +09001421}
Spandan Das918191e2024-10-31 18:27:23 +00001422
1423// getLibsForLinkerConfig returns
1424// 1. A list of libraries installed in this filesystem
1425// 2. A list of dep libraries _not_ installed in this filesystem
1426//
1427// `linkerconfig.BuildLinkerConfig` will convert these two to a linker.config.pb for the filesystem
1428// (1) will be added to --provideLibs if they are C libraries with a stable interface (has stubs)
1429// (2) will be added to --requireLibs if they are C libraries with a stable interface (has stubs)
Yu Liu68a70b72025-01-08 22:54:44 +00001430func (f *filesystem) getLibsForLinkerConfig(ctx android.ModuleContext) ([]android.ModuleProxy, []android.ModuleProxy) {
Spandan Das918191e2024-10-31 18:27:23 +00001431 // we need "Module"s for packaging items
Yu Liu68a70b72025-01-08 22:54:44 +00001432 modulesInPackageByModule := make(map[android.ModuleProxy]bool)
Spandan Das918191e2024-10-31 18:27:23 +00001433 modulesInPackageByName := make(map[string]bool)
1434
1435 deps := f.gatherFilteredPackagingSpecs(ctx)
Yu Liu68a70b72025-01-08 22:54:44 +00001436 ctx.WalkDepsProxy(func(child, parent android.ModuleProxy) bool {
1437 if !android.OtherModuleProviderOrDefault(ctx, child, android.CommonModuleInfoKey).Enabled {
Yu Liu9c6b6762025-01-08 22:04:35 +00001438 return false
1439 }
Spandan Das918191e2024-10-31 18:27:23 +00001440 for _, ps := range android.OtherModuleProviderOrDefault(
1441 ctx, child, android.InstallFilesProvider).PackagingSpecs {
Spandan Dasecf667f2024-12-05 00:58:56 +00001442 if _, ok := deps[ps.RelPathInPackage()]; ok && ps.Partition() == f.PartitionType() {
Spandan Das918191e2024-10-31 18:27:23 +00001443 modulesInPackageByModule[child] = true
1444 modulesInPackageByName[child.Name()] = true
1445 return true
1446 }
1447 }
1448 return true
1449 })
1450
Yu Liu68a70b72025-01-08 22:54:44 +00001451 provideModules := make([]android.ModuleProxy, 0, len(modulesInPackageByModule))
Spandan Das918191e2024-10-31 18:27:23 +00001452 for mod := range modulesInPackageByModule {
1453 provideModules = append(provideModules, mod)
1454 }
1455
Yu Liu68a70b72025-01-08 22:54:44 +00001456 var requireModules []android.ModuleProxy
1457 ctx.WalkDepsProxy(func(child, parent android.ModuleProxy) bool {
1458 if !android.OtherModuleProviderOrDefault(ctx, child, android.CommonModuleInfoKey).Enabled {
Yu Liu9c6b6762025-01-08 22:04:35 +00001459 return false
1460 }
Spandan Das918191e2024-10-31 18:27:23 +00001461 _, parentInPackage := modulesInPackageByModule[parent]
1462 _, childInPackageName := modulesInPackageByName[child.Name()]
1463
1464 // When parent is in the package, and child (or its variant) is not, this can be from an interface.
1465 if parentInPackage && !childInPackageName {
1466 requireModules = append(requireModules, child)
1467 }
1468 return true
1469 })
1470
1471 return provideModules, requireModules
1472}
Cole Faust26bdac52024-11-19 13:37:53 -08001473
1474// Checks that the given file doesn't exceed the given size, and will also print a warning
1475// if it's nearing the maximum size. Equivalent to assert-max-image-size in make:
1476// https://cs.android.com/android/platform/superproject/main/+/main:build/make/core/definitions.mk;l=3455;drc=993c4de29a02a6accd60ceaaee153307e1a18d10
1477func assertMaxImageSize(builder *android.RuleBuilder, image android.Path, maxSize int64, addAvbLater bool) {
1478 if addAvbLater {
1479 // The value 69632 is derived from MAX_VBMETA_SIZE + MAX_FOOTER_SIZE in avbtool.
1480 // Logic copied from make:
1481 // https://cs.android.com/android/platform/superproject/main/+/main:build/make/core/Makefile;l=228;drc=a6a0007ef24e16c0b79f439beac4a118416717e6
1482 maxSize -= 69632
1483 }
1484 cmd := builder.Command()
1485 cmd.Textf(`file="%s"; maxsize="%d";`+
1486 `total=$(stat -c "%%s" "$file" | tr -d '\n');`+
1487 `if [ "$total" -gt "$maxsize" ]; then `+
1488 ` echo "error: $file too large ($total > $maxsize)";`+
1489 ` false;`+
1490 `elif [ "$total" -gt $((maxsize - 32768)) ]; then `+
1491 ` echo "WARNING: $file approaching size limit ($total now; limit $maxsize)";`+
1492 `fi`,
1493 image, maxSize)
1494 cmd.Implicit(image)
1495}
Spandan Das71be42d2024-11-20 18:34:16 +00001496
1497// addAutogeneratedRroDeps walks the transitive closure of vendor and product partitions.
1498// It visits apps installed in system and system_ext partitions, and adds the autogenerated
1499// RRO modules to its own deps.
1500func addAutogeneratedRroDeps(ctx android.BottomUpMutatorContext) {
1501 f, ok := ctx.Module().(*filesystem)
1502 if !ok {
1503 return
1504 }
1505 thisPartition := f.PartitionType()
1506 if thisPartition != "vendor" && thisPartition != "product" {
Cole Faust34592c02024-12-13 11:20:24 -08001507 if f.properties.Android_filesystem_deps.System != nil {
1508 ctx.PropertyErrorf("android_filesystem_deps.system", "only vendor or product partitions can use android_filesystem_deps")
1509 }
1510 if f.properties.Android_filesystem_deps.System_ext != nil {
1511 ctx.PropertyErrorf("android_filesystem_deps.system_ext", "only vendor or product partitions can use android_filesystem_deps")
1512 }
Spandan Das71be42d2024-11-20 18:34:16 +00001513 return
1514 }
1515 ctx.WalkDeps(func(child, parent android.Module) bool {
1516 depTag := ctx.OtherModuleDependencyTag(child)
1517 if parent.Name() == f.Name() && depTag != interPartitionDependencyTag {
1518 return false // This is a module listed in deps of vendor/product filesystem
1519 }
1520 if vendorOverlay := java.AutogeneratedRroModuleName(ctx, child.Name(), "vendor"); ctx.OtherModuleExists(vendorOverlay) && thisPartition == "vendor" {
1521 ctx.AddFarVariationDependencies(nil, dependencyTagWithVisibilityEnforcementBypass, vendorOverlay)
1522 }
1523 if productOverlay := java.AutogeneratedRroModuleName(ctx, child.Name(), "product"); ctx.OtherModuleExists(productOverlay) && thisPartition == "product" {
1524 ctx.AddFarVariationDependencies(nil, dependencyTagWithVisibilityEnforcementBypass, productOverlay)
1525 }
1526 return true
1527 })
1528}
Spandan Das6ec1fcf2025-02-11 22:51:51 +00001529
Yu Liu2a815b62025-02-21 20:46:25 +00001530func (f *filesystem) MakeVars(ctx android.MakeVarsModuleContext) []android.ModuleMakeVarsValue {
Spandan Das6ec1fcf2025-02-11 22:51:51 +00001531 if f.Name() == ctx.Config().SoongDefinedSystemImage() {
Yu Liu2a815b62025-02-21 20:46:25 +00001532 return []android.ModuleMakeVarsValue{{"SOONG_DEFINED_SYSTEM_IMAGE_PATH", f.output.String()}}
Spandan Das6ec1fcf2025-02-11 22:51:51 +00001533 }
Yu Liu2a815b62025-02-21 20:46:25 +00001534 return nil
Spandan Das6ec1fcf2025-02-11 22:51:51 +00001535}
Yu Liu0a37d422025-02-13 02:05:00 +00001536
1537func setCommonFilesystemInfo(ctx android.ModuleContext, m Filesystem) {
1538 android.SetProvider(ctx, FilesystemProvider, FilesystemInfo{
1539 Output: m.OutputPath(),
1540 SignedOutputPath: m.SignedOutputPath(),
1541 })
1542}