blob: aadb76262e644be855d34da47d559d6502d5845a [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
36func init() {
Jooyung Han9706cbc2021-04-15 22:43:48 +090037 registerBuildComponents(android.InitRegistrationContext)
Spandan Das71be42d2024-11-20 18:34:16 +000038 registerMutators(android.InitRegistrationContext)
Jihoon Kangf67b7de2025-02-12 01:01:09 +000039 pctx.HostBinToolVariable("fileslist", "fileslist")
Spandan Dasdd262fb2025-02-13 00:15:59 +000040 pctx.HostBinToolVariable("fs_config", "fs_config")
Jooyung Han9706cbc2021-04-15 22:43:48 +090041}
42
43func registerBuildComponents(ctx android.RegistrationContext) {
Cole Faust92ccbe22024-10-03 14:38:37 -070044 ctx.RegisterModuleType("android_filesystem", FilesystemFactory)
Jiyong Parkf46b1af2024-04-05 18:13:33 +090045 ctx.RegisterModuleType("android_filesystem_defaults", filesystemDefaultsFactory)
Jihoon Kang98047cf2024-10-02 17:13:54 +000046 ctx.RegisterModuleType("android_system_image", SystemImageFactory)
Jiyong Parkbc485482022-11-15 22:31:49 +090047 ctx.RegisterModuleType("avb_add_hash_footer", avbAddHashFooterFactory)
Inseob Kim87230e62023-11-22 18:55:07 +090048 ctx.RegisterModuleType("avb_add_hash_footer_defaults", avbAddHashFooterDefaultsFactory)
Alice Wang000e3a32023-01-03 16:11:20 +000049 ctx.RegisterModuleType("avb_gen_vbmeta_image", avbGenVbmetaImageFactory)
Inseob Kim87230e62023-11-22 18:55:07 +090050 ctx.RegisterModuleType("avb_gen_vbmeta_image_defaults", avbGenVbmetaImageDefaultsFactory)
Jiyong Park6f0f6882020-11-12 13:14:30 +090051}
52
Spandan Das71be42d2024-11-20 18:34:16 +000053func registerMutators(ctx android.RegistrationContext) {
54 ctx.PostDepsMutators(func(ctx android.RegisterMutatorsContext) {
55 ctx.BottomUp("add_autogenerated_rro_deps", addAutogeneratedRroDeps)
56 })
57}
58
Jihoon Kangf67b7de2025-02-12 01:01:09 +000059var (
60 // Remember to add referenced files to implicits!
61 textFileProcessorRule = pctx.AndroidStaticRule("text_file_processing", blueprint.RuleParams{
62 Command: "build/soong/scripts/text_file_processor.py $in $out",
63 CommandDeps: []string{"build/soong/scripts/text_file_processor.py"},
64 })
65
66 // Remember to add the output image file as an implicit dependency!
67 installedFilesJsonRule = pctx.AndroidStaticRule("installed_files_json", blueprint.RuleParams{
68 Command: `${fileslist} ${rootDir} > ${out}`,
69 CommandDeps: []string{"${fileslist}"},
70 }, "rootDir")
71
72 installedFilesTxtRule = pctx.AndroidStaticRule("installed_files_txt", blueprint.RuleParams{
73 Command: `build/make/tools/fileslist_util.py -c ${in} > ${out}`,
74 CommandDeps: []string{"build/make/tools/fileslist_util.py"},
75 })
Spandan Dasdd262fb2025-02-13 00:15:59 +000076 fsConfigRule = pctx.AndroidStaticRule("fs_config_rule", blueprint.RuleParams{
77 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}`,
78 CommandDeps: []string{"${fs_config}"},
79 }, "rootDir", "prefix")
Jihoon Kangf67b7de2025-02-12 01:01:09 +000080)
Cole Fauste1676122024-12-03 17:32:25 -080081
Jiyong Park6f0f6882020-11-12 13:14:30 +090082type filesystem struct {
83 android.ModuleBase
84 android.PackagingBase
Jiyong Parkf46b1af2024-04-05 18:13:33 +090085 android.DefaultableModuleBase
Jiyong Park65c49f52020-11-24 14:23:26 +090086
Jihoon Kang98047cf2024-10-02 17:13:54 +000087 properties FilesystemProperties
Jiyong Park71baa762021-01-18 21:11:03 +090088
Cole Faust4e9f5922024-11-13 16:09:23 -080089 output android.Path
Jiyong Park65c49f52020-11-24 14:23:26 +090090 installDir android.InstallPath
Jooyung Han0fbbc2b2022-03-25 12:35:46 +090091
Cole Faust4e9f5922024-11-13 16:09:23 -080092 fileListFile android.Path
Kiyoung Kim99a954d2024-06-21 14:22:20 +090093
94 // Keeps the entries installed from this filesystem
Jooyung Han0fbbc2b2022-03-25 12:35:46 +090095 entries []string
Kiyoung Kim67118212024-11-07 13:23:44 +090096
97 filesystemBuilder filesystemBuilder
Spandan Dasf12ff9b2025-02-12 22:27:43 +000098
99 selinuxFc android.Path
Jiyong Park6f0f6882020-11-12 13:14:30 +0900100}
101
Kiyoung Kim67118212024-11-07 13:23:44 +0900102type filesystemBuilder interface {
Cole Faust19fbb072025-01-30 18:19:29 -0800103 BuildLinkerConfigFile(ctx android.ModuleContext, builder *android.RuleBuilder, rebasedDir android.OutputPath, fullInstallPaths *[]FullInstallPathInfo)
Kiyoung Kim67118212024-11-07 13:23:44 +0900104 // Function that filters PackagingSpec in PackagingBase.GatherPackagingSpecs()
105 FilterPackagingSpec(spec android.PackagingSpec) bool
Inseob Kim3c0a0422024-11-05 17:21:37 +0900106 // Function that modifies PackagingSpec in PackagingBase.GatherPackagingSpecs() to customize.
107 // For example, GSI system.img contains system_ext and product artifacts and their
108 // relPathInPackage need to be rebased to system/system_ext and system/system_product.
109 ModifyPackagingSpec(spec *android.PackagingSpec)
Kiyoung Kim23be5bb2024-11-27 00:50:30 +0000110
111 // Function to check if the filesystem should not use `vintf_fragments` property,
112 // but use `vintf_fragment` module type instead
113 ShouldUseVintfFragmentModuleOnly() bool
Kiyoung Kim67118212024-11-07 13:23:44 +0900114}
115
116var _ filesystemBuilder = (*filesystem)(nil)
117
Spandan Das69464c32024-10-25 20:08:06 +0000118type SymlinkDefinition struct {
Inseob Kim14199b02021-02-09 21:18:31 +0900119 Target *string
120 Name *string
121}
122
Jihoon Kang0a453892024-12-09 22:16:26 +0000123// CopyWithNamePrefix returns a new [SymlinkDefinition] with prefix added to Name.
124func (s *SymlinkDefinition) CopyWithNamePrefix(prefix string) SymlinkDefinition {
125 return SymlinkDefinition{
126 Target: s.Target,
127 Name: proptools.StringPtr(filepath.Join(prefix, proptools.String(s.Name))),
128 }
129}
130
Jihoon Kang98047cf2024-10-02 17:13:54 +0000131type FilesystemProperties struct {
Jiyong Park71baa762021-01-18 21:11:03 +0900132 // When set to true, sign the image with avbtool. Default is false.
133 Use_avb *bool
134
135 // Path to the private key that avbtool will use to sign this filesystem image.
136 // TODO(jiyong): allow apex_key to be specified here
137 Avb_private_key *string `android:"path"`
138
Shikha Panwar01403bb2022-12-22 12:22:57 +0000139 // Signing algorithm for avbtool. Default is SHA256_RSA4096.
Jiyong Park71baa762021-01-18 21:11:03 +0900140 Avb_algorithm *string
Jiyong Park11a65972021-02-01 21:09:38 +0900141
Shikha Panwar01403bb2022-12-22 12:22:57 +0000142 // Hash algorithm used for avbtool (for descriptors). This is passed as hash_algorithm to
Nikita Ioffe50fb49c2025-01-24 13:49:00 +0000143 // avbtool. Default is sha256.
Shikha Panware6f30632022-12-21 12:54:45 +0000144 Avb_hash_algorithm *string
145
Spandan Dase5c393c2024-12-12 19:25:07 +0000146 // The security patch passed to as the com.android.build.<type>.security_patch avb property.
147 Security_patch *string
148
Cole Fauste1676122024-12-03 17:32:25 -0800149 // Whether or not to use forward-error-correction codes when signing with AVB. Defaults to true.
150 Use_fec *bool
151
Nikita Ioffe2c8cdc62024-03-27 22:19:30 +0000152 // The index used to prevent rollback of the image. Only used if use_avb is true.
153 Rollback_index *int64
154
Luca Stefani9235f4c2025-02-08 12:09:34 +0100155 // Rollback index location of this image. Must be 1, 2, 3, etc.
Jihoon Kang2f0d1932025-01-17 19:22:44 +0000156 Rollback_index_location *int64
157
Jiyong Parkac4076d2021-03-15 23:21:30 +0900158 // Name of the partition stored in vbmeta desc. Defaults to the name of this module.
159 Partition_name *string
160
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000161 // Type of the filesystem. Currently, ext4, erofs, cpio, and compressed_cpio are supported. Default
Jiyong Park837cdb22021-02-05 00:17:14 +0900162 // is ext4.
Jiyong Park11a65972021-02-01 21:09:38 +0900163 Type *string
Inseob Kimcc8e5362021-02-03 14:05:24 +0900164
Cole Faust9a24d902024-03-18 15:38:12 -0700165 // Identifies which partition this is for //visibility:any_system_image (and others) visibility
166 // checks, and will be used in the future for API surface checks.
167 Partition_type *string
168
Cole Faust0d467052024-12-04 17:19:19 -0800169 // file_contexts file to make image. Currently, only ext4 is supported. These file contexts
170 // will be compiled with sefcontext_compile
Inseob Kimcc8e5362021-02-03 14:05:24 +0900171 File_contexts *string `android:"path"`
Inseob Kim2ce1b5d2021-02-15 17:01:04 +0900172
Cole Faust0d467052024-12-04 17:19:19 -0800173 // The selinux file contexts, after having already run them through sefcontext_compile
174 Precompiled_file_contexts *string `android:"path"`
175
Inseob Kim2ce1b5d2021-02-15 17:01:04 +0900176 // Base directory relative to root, to which deps are installed, e.g. "system". Default is "."
177 // (root).
178 Base_dir *string
Inseob Kim14199b02021-02-09 21:18:31 +0900179
180 // Directories to be created under root. e.g. /dev, /proc, etc.
Cole Faustd9c6a5b2024-05-21 14:54:00 -0700181 Dirs proptools.Configurable[[]string]
Inseob Kim14199b02021-02-09 21:18:31 +0900182
Jihoon Kang6da80752024-12-23 18:53:32 +0000183 // List of filesystem modules to include in creating the partition. The root directory of
184 // the provided filesystem modules are included in creating the partition.
185 // This is only supported for cpio and compressed cpio filesystem types.
186 Include_files_of []string
187
Inseob Kim14199b02021-02-09 21:18:31 +0900188 // Symbolic links to be created under root with "ln -sf <target> <name>".
Spandan Das69464c32024-10-25 20:08:06 +0000189 Symlinks []SymlinkDefinition
Jooyung Han65f402b2022-04-21 14:24:04 +0900190
191 // Seconds since unix epoch to override timestamps of file entries
192 Fake_timestamp *string
193
194 // When set, passed to mkuserimg_mke2fs --mke2fs_uuid & --mke2fs_hash_seed.
195 // Otherwise, they'll be set as random which might cause indeterministic build output.
196 Uuid *string
Inseob Kim376d72f2023-11-01 15:40:25 +0900197
198 // Mount point for this image. Default is "/"
199 Mount_point *string
Cole Faust4a2a7c92024-03-12 12:44:40 -0700200
Inseob Kimb7b84572024-04-30 10:51:47 +0900201 // When set, builds etc/event-log-tags file by merging logtags from all dependencies.
202 // Default is false
203 Build_logtags *bool
204
Justin Yun74f3f302024-05-07 14:32:14 +0900205 // Install aconfig_flags.pb file for the modules installed in this partition.
206 Gen_aconfig_flags_pb *bool
207
Cole Faust34592c02024-12-13 11:20:24 -0800208 // List of names of other filesystem partitions to import their aconfig flags from.
209 // This is used for the system partition to import system_ext's aconfig flags, as currently
210 // those are considered one "container": aosp/3261300
211 Import_aconfig_flags_from []string
212
Inseob Kim53391842024-03-29 17:44:07 +0900213 Fsverity fsverityProperties
Cole Faust92ccbe22024-10-03 14:38:37 -0700214
215 // If this property is set to true, the filesystem will call ctx.UncheckedModule(), causing
216 // it to not be built on checkbuilds. Used for the automatic migration from make to soong
217 // build modules, where we want to emit some not-yet-working filesystems and we don't want them
218 // to be built.
219 Unchecked_module *bool `blueprint:"mutated"`
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000220
221 Erofs ErofsProperties
Jihoon Kang0d545b82024-10-11 00:21:57 +0000222
mrziwang1a6291f2024-11-07 14:29:25 -0800223 F2fs F2fsProperties
224
Spandan Das2047a4c2024-11-11 21:24:58 +0000225 Linker_config LinkerConfigProperties
Spandan Das92631882024-10-28 22:49:38 +0000226
Jihoon Kang0d545b82024-10-11 00:21:57 +0000227 // Determines if the module is auto-generated from Soong or not. If the module is
228 // auto-generated, its deps are exempted from visibility enforcement.
229 Is_auto_generated *bool
Jihoon Kang6c03c8e2024-11-18 21:30:22 +0000230
231 // Path to the dev nodes description file. This is only needed for building the ramdisk
232 // partition and should not be explicitly specified.
233 Dev_nodes_description_file *string `android:"path" blueprint:"mutated"`
Spandan Das71be42d2024-11-20 18:34:16 +0000234
235 // Additional dependencies used for building android products
236 Android_filesystem_deps AndroidFilesystemDeps
Spandan Dasc49b85e2025-01-10 00:51:25 +0000237
238 // Name of the output. Default is $(module_name).img
239 Stem *string
Jihoon Kang983dd882025-01-13 23:14:11 +0000240
241 // The size of the partition on the device. It will be a build error if this built partition
242 // image exceeds this size.
243 Partition_size *int64
Jihoon Kang6d08d922025-01-14 18:31:57 +0000244
245 // Whether to format f2fs and ext4 in a way that supports casefolding
246 Support_casefolding *bool
247
248 // Whether to format f2fs and ext4 in a way that supports project quotas
249 Support_project_quota *bool
250
251 // Whether to enable per-file compression in f2fs
252 Enable_compression *bool
Spandan Das71be42d2024-11-20 18:34:16 +0000253}
254
255type AndroidFilesystemDeps struct {
256 System *string
257 System_ext *string
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000258}
259
260// Additional properties required to generate erofs FS partitions.
261type ErofsProperties struct {
262 // Compressor and Compression level passed to mkfs.erofs. e.g. (lz4hc,9)
263 // Please see external/erofs-utils/README for complete documentation.
264 Compressor *string
265
266 // Used as --compress-hints for mkfs.erofs
267 Compress_hints *string `android:"path"`
268
269 Sparse *bool
Jiyong Park71baa762021-01-18 21:11:03 +0900270}
271
mrziwang1a6291f2024-11-07 14:29:25 -0800272// Additional properties required to generate f2fs FS partitions.
273type F2fsProperties struct {
274 Sparse *bool
275}
276
Spandan Das173256b2024-10-31 19:59:30 +0000277type LinkerConfigProperties struct {
278
279 // Build a linker.config.pb file
280 Gen_linker_config *bool
281
282 // List of files (in .json format) that will be converted to a linker config file (in .pb format).
283 // The linker config file be installed in the filesystem at /etc/linker.config.pb
284 Linker_config_srcs []string `android:"path"`
285}
286
Jiyong Park65c49f52020-11-24 14:23:26 +0900287// android_filesystem packages a set of modules and their transitive dependencies into a filesystem
288// image. The filesystem images are expected to be mounted in the target device, which means the
289// modules in the filesystem image are built for the target device (i.e. Android, not Linux host).
290// The modules are placed in the filesystem image just like they are installed to the ordinary
291// partitions like system.img. For example, cc_library modules are placed under ./lib[64] directory.
Cole Faust92ccbe22024-10-03 14:38:37 -0700292func FilesystemFactory() android.Module {
Jiyong Park6f0f6882020-11-12 13:14:30 +0900293 module := &filesystem{}
Kiyoung Kim67118212024-11-07 13:23:44 +0900294 module.filesystemBuilder = module
Cole Faust2cfe6962024-09-17 11:31:14 -0700295 initFilesystemModule(module, module)
Jiyong Parkfa616132021-04-20 11:36:40 +0900296 return module
297}
298
Cole Faust2cfe6962024-09-17 11:31:14 -0700299func initFilesystemModule(module android.DefaultableModule, filesystemModule *filesystem) {
300 module.AddProperties(&filesystemModule.properties)
301 android.InitPackageModule(filesystemModule)
302 filesystemModule.PackagingBase.DepsCollectFirstTargetOnly = true
Jihoon Kang79196c52024-10-30 18:49:47 +0000303 filesystemModule.PackagingBase.AllowHighPriorityDeps = true
Jiyong Park6f0f6882020-11-12 13:14:30 +0900304 android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900305 android.InitDefaultableModule(module)
Jihoon Kang6c03c8e2024-11-18 21:30:22 +0000306
307 android.AddLoadHook(module, func(ctx android.LoadHookContext) {
308 filesystemModule.setDevNodesDescriptionProp()
309 })
Jiyong Park6f0f6882020-11-12 13:14:30 +0900310}
311
Jihoon Kang0d545b82024-10-11 00:21:57 +0000312type depTag struct {
Jiyong Park12a719c2021-01-07 15:31:24 +0900313 blueprint.BaseDependencyTag
Jooyung Han092ef812021-03-10 15:40:34 +0900314 android.PackagingItemAlwaysDepTag
Jihoon Kang0d545b82024-10-11 00:21:57 +0000315}
316
317var dependencyTag = depTag{}
318
319type depTagWithVisibilityEnforcementBypass struct {
320 depTag
321}
322
Spandan Das71be42d2024-11-20 18:34:16 +0000323type interPartitionDepTag struct {
324 blueprint.BaseDependencyTag
325}
326
327var interPartitionDependencyTag = interPartitionDepTag{}
328
Jihoon Kang6da80752024-12-23 18:53:32 +0000329var interPartitionInstallDependencyTag = interPartitionDepTag{}
330
Jihoon Kang0d545b82024-10-11 00:21:57 +0000331var _ android.ExcludeFromVisibilityEnforcementTag = (*depTagWithVisibilityEnforcementBypass)(nil)
332
333func (t depTagWithVisibilityEnforcementBypass) ExcludeFromVisibilityEnforcement() {}
334
335var dependencyTagWithVisibilityEnforcementBypass = depTagWithVisibilityEnforcementBypass{}
Jiyong Park65b62242020-11-25 12:44:59 +0900336
Jihoon Kang6c03c8e2024-11-18 21:30:22 +0000337// ramdiskDevNodesDescription is the name of the filegroup module that provides the file that
338// contains the description of dev nodes added to the CPIO archive for the ramdisk partition.
339const ramdiskDevNodesDescription = "ramdisk_node_list"
340
341func (f *filesystem) setDevNodesDescriptionProp() {
342 if proptools.String(f.properties.Partition_name) == "ramdisk" {
343 f.properties.Dev_nodes_description_file = proptools.StringPtr(":" + ramdiskDevNodesDescription)
344 }
345}
346
Jiyong Park6f0f6882020-11-12 13:14:30 +0900347func (f *filesystem) DepsMutator(ctx android.BottomUpMutatorContext) {
Jihoon Kang0d545b82024-10-11 00:21:57 +0000348 if proptools.Bool(f.properties.Is_auto_generated) {
349 f.AddDeps(ctx, dependencyTagWithVisibilityEnforcementBypass)
350 } else {
351 f.AddDeps(ctx, dependencyTag)
352 }
Spandan Das71be42d2024-11-20 18:34:16 +0000353 if f.properties.Android_filesystem_deps.System != nil {
354 ctx.AddDependency(ctx.Module(), interPartitionDependencyTag, proptools.String(f.properties.Android_filesystem_deps.System))
355 }
356 if f.properties.Android_filesystem_deps.System_ext != nil {
357 ctx.AddDependency(ctx.Module(), interPartitionDependencyTag, proptools.String(f.properties.Android_filesystem_deps.System_ext))
358 }
Cole Faust34592c02024-12-13 11:20:24 -0800359 for _, partition := range f.properties.Import_aconfig_flags_from {
360 ctx.AddDependency(ctx.Module(), importAconfigDependencyTag, partition)
361 }
Jihoon Kang6da80752024-12-23 18:53:32 +0000362 for _, partition := range f.properties.Include_files_of {
363 ctx.AddDependency(ctx.Module(), interPartitionInstallDependencyTag, partition)
364 }
Jiyong Park6f0f6882020-11-12 13:14:30 +0900365}
366
Jiyong Park11a65972021-02-01 21:09:38 +0900367type fsType int
368
369const (
370 ext4Type fsType = iota
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000371 erofsType
mrziwang1a6291f2024-11-07 14:29:25 -0800372 f2fsType
Jiyong Park11a65972021-02-01 21:09:38 +0900373 compressedCpioType
Jiyong Park837cdb22021-02-05 00:17:14 +0900374 cpioType // uncompressed
Jiyong Park11a65972021-02-01 21:09:38 +0900375 unknown
376)
377
Spandan Das7a46f6c2024-10-14 18:41:18 +0000378func (fs fsType) IsUnknown() bool {
379 return fs == unknown
380}
381
Jihoon Kangf67b7de2025-02-12 01:01:09 +0000382type InstalledFilesStruct struct {
383 Txt android.Path
384 Json android.Path
385}
386
Jihoon Kangabec3ec2025-02-19 00:55:10 +0000387type InstalledModuleInfo struct {
388 Name string
389 Variation string
390}
391
Cole Faust92ccbe22024-10-03 14:38:37 -0700392type FilesystemInfo struct {
Cole Faust44080412024-12-20 14:17:07 -0800393 // The built filesystem image
394 Output android.Path
Spandan Das1f0a5a12025-01-15 00:53:15 +0000395 // An additional hermetic filesystem image.
396 // e.g. this will contain inodes with pinned timestamps.
397 // This will be copied to target_files.zip
398 OutputHermetic android.Path
Cole Faust92ccbe22024-10-03 14:38:37 -0700399 // A text file containing the list of paths installed on the partition.
400 FileListFile android.Path
Cole Faust44080412024-12-20 14:17:07 -0800401 // The root staging directory used to build the output filesystem. If consuming this, make sure
402 // to add a dependency on the Output file, as you cannot add dependencies on directories
403 // in ninja.
404 RootDir android.Path
Cole Faust11fda332025-01-14 16:47:19 -0800405 // The rebased staging directory used to build the output filesystem. If consuming this, make
406 // sure to add a dependency on the Output file, as you cannot add dependencies on directories
407 // in ninja. In many cases this is the same as RootDir, only in the system partition is it
408 // different. There, it points to the "system" sub-directory of RootDir.
409 RebasedDir android.Path
Spandan Das33c9c472025-01-14 19:26:23 +0000410 // A text file with block data of the .img file
411 // This is an implicit output of `build_image`
412 MapFile android.Path
Cole Faust11fda332025-01-14 16:47:19 -0800413 // Name of the module that produced this FilesystemInfo origionally. (though it may be
414 // re-exported by super images or boot images)
415 ModuleName string
Cole Faust74ee4e02025-01-16 14:55:35 -0800416 // The property file generated by this module and passed to build_image.
417 // It's exported here so that system_other can reuse system's property file.
418 BuildImagePropFile android.Path
419 // Paths to all the tools referenced inside of the build image property file.
420 BuildImagePropFileDeps android.Paths
Cole Faustb8e280f2025-01-16 16:33:26 -0800421 // Packaging specs to be installed on the system_other image, for the initial boot's dexpreopt.
422 SpecsForSystemOther map[string]android.PackagingSpec
Cole Faust19fbb072025-01-30 18:19:29 -0800423
424 FullInstallPaths []FullInstallPathInfo
Jihoon Kangf67b7de2025-02-12 01:01:09 +0000425
426 // Installed files list
427 InstalledFiles InstalledFilesStruct
Spandan Dasd71af182025-02-12 18:03:29 +0000428
429 // Path to compress hints file for erofs filesystems
430 // This will be nil for other fileystems like ext4
431 ErofsCompressHints android.Path
Spandan Dasf12ff9b2025-02-12 22:27:43 +0000432
433 SelinuxFc android.Path
Spandan Dasdd262fb2025-02-13 00:15:59 +0000434
435 FilesystemConfig android.Path
Jihoon Kangabec3ec2025-02-19 00:55:10 +0000436
437 Owners []InstalledModuleInfo
Cole Faust19fbb072025-01-30 18:19:29 -0800438}
439
440// FullInstallPathInfo contains information about the "full install" paths of all the files
441// inside this partition. The full install paths are the files installed in
442// out/target/product/<device>/<partition>. This is essentially legacy behavior, maintained for
443// tools like adb sync and adevice, but we should update them to query the build system for the
444// installed files no matter where they are.
445type FullInstallPathInfo struct {
446 // RequiresFullInstall tells us if the origional module did the install to FullInstallPath
447 // already. If it's false, the android_device module needs to emit the install rule.
448 RequiresFullInstall bool
449 // The "full install" paths for the files in this filesystem. This is the paths in the
450 // out/target/product/<device>/<partition> folder. They're not used by this filesystem,
451 // but can be depended on by the top-level android_device module to cause the staging
452 // directories to be built.
453 FullInstallPath android.InstallPath
454
455 // The file that's copied to FullInstallPath. May be nil if SymlinkTarget is set or IsDir is
456 // true.
457 SourcePath android.Path
458
459 // The target of the symlink, if this file is a symlink.
460 SymlinkTarget string
461
462 // If this file is a directory. Only used for empty directories, which are mostly mount points.
463 IsDir bool
Cole Faust92ccbe22024-10-03 14:38:37 -0700464}
465
466var FilesystemProvider = blueprint.NewProvider[FilesystemInfo]()
467
Yu Liufc8d5c12025-01-09 00:19:06 +0000468type FilesystemDefaultsInfo struct {
469 // Identifies which partition this is for //visibility:any_system_image (and others) visibility
470 // checks, and will be used in the future for API surface checks.
471 PartitionType string
472}
473
474var FilesystemDefaultsInfoProvider = blueprint.NewProvider[FilesystemDefaultsInfo]()
475
Spandan Das7a46f6c2024-10-14 18:41:18 +0000476func GetFsTypeFromString(ctx android.EarlyModuleContext, typeStr string) fsType {
Jiyong Park11a65972021-02-01 21:09:38 +0900477 switch typeStr {
478 case "ext4":
479 return ext4Type
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000480 case "erofs":
481 return erofsType
mrziwang1a6291f2024-11-07 14:29:25 -0800482 case "f2fs":
483 return f2fsType
Jiyong Park11a65972021-02-01 21:09:38 +0900484 case "compressed_cpio":
485 return compressedCpioType
Jiyong Park837cdb22021-02-05 00:17:14 +0900486 case "cpio":
487 return cpioType
Jiyong Park11a65972021-02-01 21:09:38 +0900488 default:
Jiyong Park11a65972021-02-01 21:09:38 +0900489 return unknown
490 }
491}
492
Spandan Das7a46f6c2024-10-14 18:41:18 +0000493func (f *filesystem) fsType(ctx android.ModuleContext) fsType {
494 typeStr := proptools.StringDefault(f.properties.Type, "ext4")
495 fsType := GetFsTypeFromString(ctx, typeStr)
496 if fsType == unknown {
497 ctx.PropertyErrorf("type", "%q not supported", typeStr)
498 }
499 return fsType
500}
501
Jiyong Park65c49f52020-11-24 14:23:26 +0900502func (f *filesystem) installFileName() string {
Spandan Dasc49b85e2025-01-10 00:51:25 +0000503 return proptools.StringDefault(f.properties.Stem, f.BaseModuleName()+".img")
Jiyong Park65c49f52020-11-24 14:23:26 +0900504}
505
Inseob Kim53391842024-03-29 17:44:07 +0900506func (f *filesystem) partitionName() string {
507 return proptools.StringDefault(f.properties.Partition_name, f.Name())
508}
509
Kiyoung Kim67118212024-11-07 13:23:44 +0900510func (f *filesystem) FilterPackagingSpec(ps android.PackagingSpec) bool {
Jiyong Park7e7d4af2024-05-01 12:36:10 +0000511 // Filesystem module respects the installation semantic. A PackagingSpec from a module with
512 // IsSkipInstall() is skipped.
Cole Faust76a6e952024-11-07 16:56:45 -0800513 if ps.SkipInstall() {
514 return false
Spandan Das6d056502024-10-21 15:40:32 +0000515 }
Cole Faust0d3fd562025-01-31 13:17:58 -0800516 // "apex" is a fake partition used to install files in out/target/product/<device>/apex/.
517 // Don't include these files in the partition. We should also look into removing the following
518 // TODO to check the PackagingSpec's partition against this filesystem's partition for all
519 // modules, not just autogenerated ones, which will fix this as well.
520 if ps.Partition() == "apex" {
521 return false
522 }
Cole Faust76a6e952024-11-07 16:56:45 -0800523 if proptools.Bool(f.properties.Is_auto_generated) { // TODO (spandandas): Remove this.
524 pt := f.PartitionType()
Cole Faustc88cff12024-11-12 13:24:05 -0800525 return ps.Partition() == pt || strings.HasPrefix(ps.Partition(), pt+"/")
Cole Faust76a6e952024-11-07 16:56:45 -0800526 }
527 return true
Jiyong Park7e7d4af2024-05-01 12:36:10 +0000528}
529
Inseob Kim3c0a0422024-11-05 17:21:37 +0900530func (f *filesystem) ModifyPackagingSpec(ps *android.PackagingSpec) {
Cole Faustc88cff12024-11-12 13:24:05 -0800531 // Sometimes, android.modulePartition() returns a path with >1 path components.
532 // This makes the partition field of packagingSpecs have multiple components, like
533 // "system/product". Right now, the filesystem module doesn't look at the partition field
534 // when deciding what path to install the file under, only the RelPathInPackage field, so
535 // we move the later path components from partition to relPathInPackage. This should probably
536 // be revisited in the future.
537 prefix := f.PartitionType() + "/"
538 if strings.HasPrefix(ps.Partition(), prefix) {
539 subPartition := strings.TrimPrefix(ps.Partition(), prefix)
540 ps.SetPartition(f.PartitionType())
541 ps.SetRelPathInPackage(filepath.Join(subPartition, ps.RelPathInPackage()))
542 }
Inseob Kim3c0a0422024-11-05 17:21:37 +0900543}
544
Jihoon Kangf67b7de2025-02-12 01:01:09 +0000545func buildInstalledFiles(ctx android.ModuleContext, partition string, rootDir android.Path, image android.Path) (txt android.ModuleOutPath, json android.ModuleOutPath) {
546 fileName := "installed-files"
547 if len(partition) > 0 {
548 fileName += fmt.Sprintf("-%s", partition)
549 }
550 txt = android.PathForModuleOut(ctx, fmt.Sprintf("%s.txt", fileName))
551 json = android.PathForModuleOut(ctx, fmt.Sprintf("%s.json", fileName))
552
553 ctx.Build(pctx, android.BuildParams{
554 Rule: installedFilesJsonRule,
555 Implicit: image,
556 Output: json,
557 Description: "Installed file list json",
558 Args: map[string]string{
559 "rootDir": rootDir.String(),
560 },
561 })
562
563 ctx.Build(pctx, android.BuildParams{
564 Rule: installedFilesTxtRule,
565 Input: json,
566 Output: txt,
567 Description: "Installed file list txt",
568 })
569
570 return txt, json
571}
572
Jiyong Park6f0f6882020-11-12 13:14:30 +0900573var pctx = android.NewPackageContext("android/soong/filesystem")
574
575func (f *filesystem) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900576 validatePartitionType(ctx, f)
Kiyoung Kim23be5bb2024-11-27 00:50:30 +0000577 if f.filesystemBuilder.ShouldUseVintfFragmentModuleOnly() {
578 f.validateVintfFragments(ctx)
579 }
Jihoon Kang6da80752024-12-23 18:53:32 +0000580
581 if len(f.properties.Include_files_of) > 0 && !android.InList(f.fsType(ctx), []fsType{compressedCpioType, cpioType}) {
582 ctx.PropertyErrorf("include_files_of", "include_files_of is only supported for cpio and compressed cpio filesystem types.")
583 }
584
Cole Faust62cfaeb2025-01-15 18:06:40 -0800585 rootDir := android.PathForModuleOut(ctx, f.rootDirString()).OutputPath
586 rebasedDir := rootDir
587 if f.properties.Base_dir != nil {
588 rebasedDir = rootDir.Join(ctx, *f.properties.Base_dir)
589 }
590 builder := android.NewRuleBuilder(pctx, ctx)
591
592 // Wipe the root dir to get rid of leftover files from prior builds
593 builder.Command().Textf("rm -rf %s && mkdir -p %s", rootDir, rootDir)
594 specs := f.gatherFilteredPackagingSpecs(ctx)
Cole Faust62cfaeb2025-01-15 18:06:40 -0800595
Cole Faust19fbb072025-01-30 18:19:29 -0800596 var fullInstallPaths []FullInstallPathInfo
597 for _, spec := range specs {
598 fullInstallPaths = append(fullInstallPaths, FullInstallPathInfo{
599 FullInstallPath: spec.FullInstallPath(),
600 RequiresFullInstall: spec.RequiresFullInstall(),
601 SourcePath: spec.SrcPath(),
602 SymlinkTarget: spec.ToGob().SymlinkTarget,
603 })
604 }
605
606 f.entries = f.copyPackagingSpecs(ctx, builder, specs, rootDir, rebasedDir)
607 f.buildNonDepsFiles(ctx, builder, rootDir, rebasedDir, &fullInstallPaths)
608 f.buildFsverityMetadataFiles(ctx, builder, specs, rootDir, rebasedDir, &fullInstallPaths)
609 f.buildEventLogtagsFile(ctx, builder, rebasedDir, &fullInstallPaths)
610 f.buildAconfigFlagsFiles(ctx, builder, specs, rebasedDir, &fullInstallPaths)
611 f.filesystemBuilder.BuildLinkerConfigFile(ctx, builder, rebasedDir, &fullInstallPaths)
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000612 // Assemeble the staging dir and output a timestamp
613 builder.Command().Text("touch").Output(f.fileystemStagingDirTimestamp(ctx))
614 builder.Build("assemble_filesystem_staging_dir", fmt.Sprintf("Assemble filesystem staging dir %s", f.BaseModuleName()))
Cole Faust62cfaeb2025-01-15 18:06:40 -0800615
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000616 // Create a new rule builder for build_image
617 builder = android.NewRuleBuilder(pctx, ctx)
Spandan Das33c9c472025-01-14 19:26:23 +0000618 var mapFile android.Path
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000619 var outputHermetic android.WritablePath
Cole Faust74ee4e02025-01-16 14:55:35 -0800620 var buildImagePropFile android.Path
621 var buildImagePropFileDeps android.Paths
Jiyong Park11a65972021-02-01 21:09:38 +0900622 switch f.fsType(ctx) {
mrziwang1a6291f2024-11-07 14:29:25 -0800623 case ext4Type, erofsType, f2fsType:
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000624 buildImagePropFile, buildImagePropFileDeps = f.buildPropFile(ctx)
625 output := android.PathForModuleOut(ctx, f.installFileName())
626 f.buildImageUsingBuildImage(ctx, builder, buildImageParams{rootDir, buildImagePropFile, buildImagePropFileDeps, output})
627 f.output = output
628 // Create the hermetic img file using a separate rule builder so that it can be built independently
629 hermeticBuilder := android.NewRuleBuilder(pctx, ctx)
630 outputHermetic = android.PathForModuleOut(ctx, "for_target_files", f.installFileName())
631 propFileHermetic := f.propFileForHermeticImg(ctx, hermeticBuilder, buildImagePropFile)
632 f.buildImageUsingBuildImage(ctx, hermeticBuilder, buildImageParams{rootDir, propFileHermetic, buildImagePropFileDeps, outputHermetic})
Spandan Das33c9c472025-01-14 19:26:23 +0000633 mapFile = f.getMapFile(ctx)
Jiyong Park11a65972021-02-01 21:09:38 +0900634 case compressedCpioType:
Cole Faust62cfaeb2025-01-15 18:06:40 -0800635 f.output = f.buildCpioImage(ctx, builder, rootDir, true)
Jiyong Park837cdb22021-02-05 00:17:14 +0900636 case cpioType:
Cole Faust62cfaeb2025-01-15 18:06:40 -0800637 f.output = f.buildCpioImage(ctx, builder, rootDir, false)
Jiyong Park11a65972021-02-01 21:09:38 +0900638 default:
639 return
640 }
641
642 f.installDir = android.PathForModuleInstall(ctx, "etc")
643 ctx.InstallFile(f.installDir, f.installFileName(), f.output)
mrziwang555d1332024-06-07 11:15:33 -0700644 ctx.SetOutputFiles([]android.Path{f.output}, "")
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900645
Jihoon Kang6da80752024-12-23 18:53:32 +0000646 if f.partitionName() == "recovery" {
647 rootDir = rootDir.Join(ctx, "root")
648 }
649
Cole Faust4e9f5922024-11-13 16:09:23 -0800650 fileListFile := android.PathForModuleOut(ctx, "fileList")
651 android.WriteFileRule(ctx, fileListFile, f.installedFilesList())
Cole Faust92ccbe22024-10-03 14:38:37 -0700652
Jihoon Kangf67b7de2025-02-12 01:01:09 +0000653 partitionName := f.partitionName()
654 if partitionName == "system" {
655 partitionName = ""
656 }
657 installedFileTxt, installedFileJson := buildInstalledFiles(ctx, partitionName, rootDir, f.output)
658
Spandan Dasd71af182025-02-12 18:03:29 +0000659 var erofsCompressHints android.Path
660 if f.properties.Erofs.Compress_hints != nil {
661 erofsCompressHints = android.PathForModuleSrc(ctx, *f.properties.Erofs.Compress_hints)
662 }
663
Spandan Das33c9c472025-01-14 19:26:23 +0000664 fsInfo := FilesystemInfo{
Cole Faust74ee4e02025-01-16 14:55:35 -0800665 Output: f.output,
666 OutputHermetic: outputHermetic,
667 FileListFile: fileListFile,
668 RootDir: rootDir,
669 RebasedDir: rebasedDir,
670 MapFile: mapFile,
671 ModuleName: ctx.ModuleName(),
672 BuildImagePropFile: buildImagePropFile,
673 BuildImagePropFileDeps: buildImagePropFileDeps,
Cole Faustb8e280f2025-01-16 16:33:26 -0800674 SpecsForSystemOther: f.systemOtherFiles(ctx),
Cole Faust19fbb072025-01-30 18:19:29 -0800675 FullInstallPaths: fullInstallPaths,
Jihoon Kangf67b7de2025-02-12 01:01:09 +0000676 InstalledFiles: InstalledFilesStruct{
677 Txt: installedFileTxt,
678 Json: installedFileJson,
679 },
Spandan Dasd71af182025-02-12 18:03:29 +0000680 ErofsCompressHints: erofsCompressHints,
Spandan Dasf12ff9b2025-02-12 22:27:43 +0000681 SelinuxFc: f.selinuxFc,
Spandan Dasdd262fb2025-02-13 00:15:59 +0000682 FilesystemConfig: f.generateFilesystemConfig(ctx, rootDir, rebasedDir),
Jihoon Kangabec3ec2025-02-19 00:55:10 +0000683 Owners: f.gatherOwners(specs),
Spandan Das1f0a5a12025-01-15 00:53:15 +0000684 }
Spandan Das33c9c472025-01-14 19:26:23 +0000685
686 android.SetProvider(ctx, FilesystemProvider, fsInfo)
Spandan Das3ec6d062025-01-09 19:37:47 +0000687
Cole Faust4e9f5922024-11-13 16:09:23 -0800688 f.fileListFile = fileListFile
Cole Faust92ccbe22024-10-03 14:38:37 -0700689
690 if proptools.Bool(f.properties.Unchecked_module) {
691 ctx.UncheckedModule()
692 }
Jihoon Kang2f0d1932025-01-17 19:22:44 +0000693
694 f.setVbmetaPartitionProvider(ctx)
695}
696
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000697func (f *filesystem) fileystemStagingDirTimestamp(ctx android.ModuleContext) android.WritablePath {
698 return android.PathForModuleOut(ctx, "staging_dir.timestamp")
699}
700
Spandan Dasdd262fb2025-02-13 00:15:59 +0000701func (f *filesystem) generateFilesystemConfig(ctx android.ModuleContext, rootDir android.Path, rebasedDir android.Path) android.Path {
702 rootDirString := rootDir.String()
703 prefix := f.partitionName() + "/"
704 if f.partitionName() == "system" {
705 rootDirString = rebasedDir.String()
706 }
707 if f.partitionName() == "ramdisk" || f.partitionName() == "recovery" {
708 // Hardcoded to match make behavior.
709 // https://cs.android.com/android/_/android/platform/build/+/2a0ef42a432d4da00201e8eb7697dcaa68fd2389:core/Makefile;l=6957-6962;drc=9ea8ad9232cef4d0a24d70133b1b9d2ce2defe5f;bpv=1;bpt=0
710 prefix = ""
711 }
712 out := android.PathForModuleOut(ctx, "filesystem_config.txt")
713 ctx.Build(pctx, android.BuildParams{
714 Rule: fsConfigRule,
715 Input: f.fileystemStagingDirTimestamp(ctx), // assemble the staging directory
716 Output: out,
717 Args: map[string]string{
718 "rootDir": rootDirString,
719 "prefix": prefix,
720 },
721 })
722 return out
723}
724
Jihoon Kang2f0d1932025-01-17 19:22:44 +0000725func (f *filesystem) setVbmetaPartitionProvider(ctx android.ModuleContext) {
726 var extractedPublicKey android.ModuleOutPath
727 if f.properties.Avb_private_key != nil {
728 key := android.PathForModuleSrc(ctx, proptools.String(f.properties.Avb_private_key))
729 extractedPublicKey = android.PathForModuleOut(ctx, f.partitionName()+".avbpubkey")
730 ctx.Build(pctx, android.BuildParams{
731 Rule: extractPublicKeyRule,
732 Input: key,
733 Output: extractedPublicKey,
734 })
735 }
736
737 var ril int
738 if f.properties.Rollback_index_location != nil {
739 ril = proptools.Int(f.properties.Rollback_index_location)
740 }
741
742 android.SetProvider(ctx, vbmetaPartitionProvider, vbmetaPartitionInfo{
743 Name: f.partitionName(),
744 RollbackIndexLocation: ril,
745 PublicKey: extractedPublicKey,
746 Output: f.output,
747 })
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900748}
749
Spandan Das33c9c472025-01-14 19:26:23 +0000750func (f *filesystem) getMapFile(ctx android.ModuleContext) android.WritablePath {
751 // create the filepath by replacing the extension of the corresponding img file
752 return android.PathForModuleOut(ctx, f.installFileName()).ReplaceExtension(ctx, "map")
753}
754
Kiyoung Kim23be5bb2024-11-27 00:50:30 +0000755func (f *filesystem) validateVintfFragments(ctx android.ModuleContext) {
756 visitedModule := map[string]bool{}
757 packagingSpecs := f.gatherFilteredPackagingSpecs(ctx)
758
759 moduleInFileSystem := func(mod android.Module) bool {
760 for _, ps := range android.OtherModuleProviderOrDefault(
761 ctx, mod, android.InstallFilesProvider).PackagingSpecs {
762 if _, ok := packagingSpecs[ps.RelPathInPackage()]; ok {
763 return true
764 }
765 }
766 return false
767 }
768
769 ctx.WalkDeps(func(child, parent android.Module) bool {
770 if visitedModule[child.Name()] {
771 return false
772 }
773 if !moduleInFileSystem(child) {
774 visitedModule[child.Name()] = true
775 return true
776 }
777 if vintfFragments := child.VintfFragments(ctx); vintfFragments != nil {
778 ctx.PropertyErrorf(
779 "vintf_fragments",
780 "Module %s is referenced by soong-defined filesystem %s with property vintf_fragments(%s) in use."+
781 " Use vintf_fragment_modules property instead.",
782 child.Name(),
783 f.BaseModuleName(),
784 strings.Join(vintfFragments, ", "),
785 )
786 }
787 visitedModule[child.Name()] = true
788 return true
789 })
790}
791
Cole Faust4e9f5922024-11-13 16:09:23 -0800792func (f *filesystem) appendToEntry(ctx android.ModuleContext, installedFile android.Path) {
Spandan Das420e16a2024-12-11 18:10:52 +0000793 partitionBaseDir := android.PathForModuleOut(ctx, f.rootDirString(), proptools.String(f.properties.Base_dir)).String() + "/"
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900794
795 relPath, inTargetPartition := strings.CutPrefix(installedFile.String(), partitionBaseDir)
796 if inTargetPartition {
797 f.entries = append(f.entries, relPath)
798 }
799}
800
801func (f *filesystem) installedFilesList() string {
802 installedFilePaths := android.FirstUniqueStrings(f.entries)
803 slices.Sort(installedFilePaths)
804
805 return strings.Join(installedFilePaths, "\n")
Jiyong Park11a65972021-02-01 21:09:38 +0900806}
807
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900808func validatePartitionType(ctx android.ModuleContext, p partition) {
809 if !android.InList(p.PartitionType(), validPartitions) {
810 ctx.PropertyErrorf("partition_type", "partition_type must be one of %s, found: %s", validPartitions, p.PartitionType())
811 }
812
Yu Liufc8d5c12025-01-09 00:19:06 +0000813 ctx.VisitDirectDepsProxyWithTag(android.DefaultsDepTag, func(m android.ModuleProxy) {
814 if fdm, ok := android.OtherModuleProvider(ctx, m, FilesystemDefaultsInfoProvider); ok {
815 if p.PartitionType() != fdm.PartitionType {
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900816 ctx.PropertyErrorf("partition_type",
817 "%s doesn't match with the partition type %s of the filesystem default module %s",
Yu Liufc8d5c12025-01-09 00:19:06 +0000818 p.PartitionType(), fdm.PartitionType, m.Name())
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900819 }
820 }
821 })
822}
823
Cole Faust3b806d32024-03-11 15:15:03 -0700824// Copy extra files/dirs that are not from the `deps` property to `rootDir`, checking for conflicts with files
825// already in `rootDir`.
Cole Faust19fbb072025-01-30 18:19:29 -0800826func (f *filesystem) buildNonDepsFiles(
827 ctx android.ModuleContext,
828 builder *android.RuleBuilder,
829 rootDir android.OutputPath,
830 rebasedDir android.OutputPath,
831 fullInstallPaths *[]FullInstallPathInfo,
832) {
833 rebasedPrefix, err := filepath.Rel(rootDir.String(), rebasedDir.String())
834 if err != nil || strings.HasPrefix(rebasedPrefix, "../") {
835 panic("rebasedDir could not be made relative to rootDir")
836 }
837 if !strings.HasSuffix(rebasedPrefix, "/") {
838 rebasedPrefix += "/"
839 }
840 if rebasedPrefix == "./" {
841 rebasedPrefix = ""
842 }
843
Inseob Kim14199b02021-02-09 21:18:31 +0900844 // create dirs and symlinks
Cole Faustd9c6a5b2024-05-21 14:54:00 -0700845 for _, dir := range f.properties.Dirs.GetOrDefault(ctx, nil) {
Inseob Kim14199b02021-02-09 21:18:31 +0900846 // OutputPath.Join verifies dir
847 builder.Command().Text("mkdir -p").Text(rootDir.Join(ctx, dir).String())
Cole Faust19fbb072025-01-30 18:19:29 -0800848 // Only add the fullInstallPath logic for files in the rebased dir. The root dir
849 // is harder to install to.
850 if strings.HasPrefix(dir, rebasedPrefix) {
851 *fullInstallPaths = append(*fullInstallPaths, FullInstallPathInfo{
852 FullInstallPath: android.PathForModuleInPartitionInstall(ctx, f.PartitionType(), strings.TrimPrefix(dir, rebasedPrefix)),
853 IsDir: true,
854 })
855 }
Inseob Kim14199b02021-02-09 21:18:31 +0900856 }
857
858 for _, symlink := range f.properties.Symlinks {
859 name := strings.TrimSpace(proptools.String(symlink.Name))
860 target := strings.TrimSpace(proptools.String(symlink.Target))
861
862 if name == "" {
863 ctx.PropertyErrorf("symlinks", "Name can't be empty")
864 continue
865 }
866
867 if target == "" {
868 ctx.PropertyErrorf("symlinks", "Target can't be empty")
869 continue
870 }
871
872 // OutputPath.Join verifies name. don't need to verify target.
873 dst := rootDir.Join(ctx, name)
Cole Faust3b806d32024-03-11 15:15:03 -0700874 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 +0900875 builder.Command().Text("mkdir -p").Text(filepath.Dir(dst.String()))
876 builder.Command().Text("ln -sf").Text(proptools.ShellEscape(target)).Text(dst.String())
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900877 f.appendToEntry(ctx, dst)
Cole Faust19fbb072025-01-30 18:19:29 -0800878 // Only add the fullInstallPath logic for files in the rebased dir. The root dir
879 // is harder to install to.
880 if strings.HasPrefix(name, rebasedPrefix) {
881 *fullInstallPaths = append(*fullInstallPaths, FullInstallPathInfo{
882 FullInstallPath: android.PathForModuleInPartitionInstall(ctx, f.PartitionType(), strings.TrimPrefix(name, rebasedPrefix)),
883 SymlinkTarget: target,
884 })
885 }
Inseob Kim14199b02021-02-09 21:18:31 +0900886 }
Jihoon Kang89e8a692024-12-18 19:28:33 +0000887
888 // https://cs.android.com/android/platform/superproject/main/+/main:build/make/core/Makefile;l=2835;drc=b186569ef00ff2f2a1fab28aedc75ebc32bcd67b
889 if f.partitionName() == "recovery" {
890 builder.Command().Text("mkdir -p").Text(rootDir.Join(ctx, "root/linkerconfig").String())
891 builder.Command().Text("touch").Text(rootDir.Join(ctx, "root/linkerconfig/ld.config.txt").String())
892 }
Inseob Kim2ce1b5d2021-02-15 17:01:04 +0900893}
894
Inseob Kim33f95a92024-07-11 15:44:49 +0900895func (f *filesystem) copyPackagingSpecs(ctx android.ModuleContext, builder *android.RuleBuilder, specs map[string]android.PackagingSpec, rootDir, rebasedDir android.WritablePath) []string {
896 rootDirSpecs := make(map[string]android.PackagingSpec)
897 rebasedDirSpecs := make(map[string]android.PackagingSpec)
898
899 for rel, spec := range specs {
900 if spec.Partition() == "root" {
901 rootDirSpecs[rel] = spec
902 } else {
903 rebasedDirSpecs[rel] = spec
904 }
905 }
906
907 dirsToSpecs := make(map[android.WritablePath]map[string]android.PackagingSpec)
908 dirsToSpecs[rootDir] = rootDirSpecs
909 dirsToSpecs[rebasedDir] = rebasedDirSpecs
910
Cole Fauste3845052025-02-13 12:45:35 -0800911 // Preserve timestamps for adb sync, so that this staging dir file matches the timestamp in the
912 // out/target/product staging directory.
913 return f.CopySpecsToDirs(ctx, builder, dirsToSpecs, true)
Inseob Kim33f95a92024-07-11 15:44:49 +0900914}
915
Spandan Das420e16a2024-12-11 18:10:52 +0000916func (f *filesystem) rootDirString() string {
917 return f.partitionName()
918}
919
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000920type buildImageParams struct {
921 // inputs
922 rootDir android.OutputPath
923 propFile android.Path
924 toolDeps android.Paths
925 // outputs
926 output android.WritablePath
927}
928
Cole Faust62cfaeb2025-01-15 18:06:40 -0800929func (f *filesystem) buildImageUsingBuildImage(
930 ctx android.ModuleContext,
931 builder *android.RuleBuilder,
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000932 params buildImageParams) {
Nikita Ioffe519015f2022-12-23 15:36:29 +0000933 // run host_init_verifier
934 // Ideally we should have a concept of pluggable linters that verify the generated image.
935 // While such concept is not implement this will do.
936 // TODO(b/263574231): substitute with pluggable linter.
937 builder.Command().
938 BuiltTool("host_init_verifier").
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000939 FlagWithArg("--out_system=", params.rootDir.String()+"/system")
Cole Fauste1676122024-12-03 17:32:25 -0800940
941 // Most of the time, if build_image were to call a host tool, it accepts the path to the
942 // host tool in a field in the prop file. However, it doesn't have that option for fec, which
943 // it expects to just be on the PATH. Add fec to the PATH.
944 fec := ctx.Config().HostToolPath(ctx, "fec")
945 pathToolDirs := []string{filepath.Dir(fec.String())}
946
Cole Fauste1676122024-12-03 17:32:25 -0800947 builder.Command().
948 Textf("PATH=%s:$PATH", strings.Join(pathToolDirs, ":")).
949 BuiltTool("build_image").
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000950 Text(params.rootDir.String()). // input directory
951 Input(params.propFile).
952 Implicits(params.toolDeps).
Cole Fauste1676122024-12-03 17:32:25 -0800953 Implicit(fec).
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000954 Implicit(f.fileystemStagingDirTimestamp(ctx)). // assemble the staging directory
955 Output(params.output).
956 Text(params.rootDir.String()) // directory where to find fs_config_files|dirs
Spandan Das1f0a5a12025-01-15 00:53:15 +0000957
Jihoon Kang983dd882025-01-13 23:14:11 +0000958 if f.properties.Partition_size != nil {
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000959 assertMaxImageSize(builder, params.output, *f.properties.Partition_size, false)
Jihoon Kang983dd882025-01-13 23:14:11 +0000960 }
961
Jiyong Park6f0f6882020-11-12 13:14:30 +0900962 // rootDir is not deleted. Might be useful for quick inspection.
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000963 builder.Build("build_"+params.output.String(), fmt.Sprintf("Creating filesystem %s", f.BaseModuleName()))
964}
Jiyong Park65c49f52020-11-24 14:23:26 +0900965
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000966func (f *filesystem) propFileForHermeticImg(ctx android.ModuleContext, builder *android.RuleBuilder, inputPropFile android.Path) android.Path {
967 propFilePinnedTimestamp := android.PathForModuleOut(ctx, "for_target_files", "prop")
968 builder.Command().Textf("cat").Input(inputPropFile).Flag(">").Output(propFilePinnedTimestamp).
969 Textf(" && echo use_fixed_timestamp=true >> %s", propFilePinnedTimestamp).
970 Textf(" && echo block_list=%s >> %s", f.getMapFile(ctx).String(), propFilePinnedTimestamp) // mapfile will be an implicit output
971 builder.Command().Text("touch").Output(f.getMapFile(ctx))
972 return propFilePinnedTimestamp
Jiyong Park65c49f52020-11-24 14:23:26 +0900973}
974
Cole Faust4e9f5922024-11-13 16:09:23 -0800975func (f *filesystem) buildFileContexts(ctx android.ModuleContext) android.Path {
Inseob Kimcc8e5362021-02-03 14:05:24 +0900976 builder := android.NewRuleBuilder(pctx, ctx)
977 fcBin := android.PathForModuleOut(ctx, "file_contexts.bin")
978 builder.Command().BuiltTool("sefcontext_compile").
979 FlagWithOutput("-o ", fcBin).
980 Input(android.PathForModuleSrc(ctx, proptools.String(f.properties.File_contexts)))
981 builder.Build("build_filesystem_file_contexts", fmt.Sprintf("Creating filesystem file contexts for %s", f.BaseModuleName()))
Cole Faust4e9f5922024-11-13 16:09:23 -0800982 return fcBin
Inseob Kimcc8e5362021-02-03 14:05:24 +0900983}
984
Cole Faust4e9f5922024-11-13 16:09:23 -0800985func (f *filesystem) buildPropFile(ctx android.ModuleContext) (android.Path, android.Paths) {
Jiyong Park72678312021-01-18 17:29:49 +0900986 var deps android.Paths
Cole Fauste03ab892025-01-17 13:55:04 -0800987 var lines []string
Jiyong Park72678312021-01-18 17:29:49 +0900988 addStr := func(name string, value string) {
Cole Fauste03ab892025-01-17 13:55:04 -0800989 lines = append(lines, fmt.Sprintf("%s=%s", name, value))
Jiyong Park72678312021-01-18 17:29:49 +0900990 }
991 addPath := func(name string, path android.Path) {
Cole Faustcec230a2024-03-07 15:51:12 -0800992 addStr(name, path.String())
Jiyong Park72678312021-01-18 17:29:49 +0900993 deps = append(deps, path)
994 }
995
Jiyong Park11a65972021-02-01 21:09:38 +0900996 // Type string that build_image.py accepts.
997 fsTypeStr := func(t fsType) string {
998 switch t {
Spandan Das94668822024-10-09 20:51:33 +0000999 // TODO(372522486): add more types like f2fs, erofs, etc.
Jiyong Park11a65972021-02-01 21:09:38 +09001000 case ext4Type:
1001 return "ext4"
Spandan Dasc35d6fb2024-10-10 17:51:14 +00001002 case erofsType:
1003 return "erofs"
mrziwang1a6291f2024-11-07 14:29:25 -08001004 case f2fsType:
1005 return "f2fs"
Jiyong Park11a65972021-02-01 21:09:38 +09001006 }
1007 panic(fmt.Errorf("unsupported fs type %v", t))
1008 }
1009
1010 addStr("fs_type", fsTypeStr(f.fsType(ctx)))
Inseob Kim376d72f2023-11-01 15:40:25 +09001011 addStr("mount_point", proptools.StringDefault(f.properties.Mount_point, "/"))
Jiyong Park72678312021-01-18 17:29:49 +09001012 addStr("use_dynamic_partition_size", "true")
1013 addPath("ext_mkuserimg", ctx.Config().HostToolPath(ctx, "mkuserimg_mke2fs"))
1014 // b/177813163 deps of the host tools have to be added. Remove this.
1015 for _, t := range []string{"mke2fs", "e2fsdroid", "tune2fs"} {
1016 deps = append(deps, ctx.Config().HostToolPath(ctx, t))
1017 }
1018
Jiyong Park71baa762021-01-18 21:11:03 +09001019 if proptools.Bool(f.properties.Use_avb) {
1020 addStr("avb_hashtree_enable", "true")
1021 addPath("avb_avbtool", ctx.Config().HostToolPath(ctx, "avbtool"))
1022 algorithm := proptools.StringDefault(f.properties.Avb_algorithm, "SHA256_RSA4096")
1023 addStr("avb_algorithm", algorithm)
Cole Fauste1676122024-12-03 17:32:25 -08001024 if f.properties.Avb_private_key != nil {
1025 key := android.PathForModuleSrc(ctx, *f.properties.Avb_private_key)
1026 addPath("avb_key_path", key)
1027 }
Inseob Kim53391842024-03-29 17:44:07 +09001028 addStr("partition_name", f.partitionName())
Cole Fauste1676122024-12-03 17:32:25 -08001029 avb_add_hashtree_footer_args := ""
1030 if !proptools.BoolDefault(f.properties.Use_fec, true) {
1031 avb_add_hashtree_footer_args += " --do_not_generate_fec"
1032 }
Nikita Ioffe50fb49c2025-01-24 13:49:00 +00001033 hashAlgorithm := proptools.StringDefault(f.properties.Avb_hash_algorithm, "sha256")
1034 avb_add_hashtree_footer_args += " --hash_algorithm " + hashAlgorithm
Nikita Ioffe2c8cdc62024-03-27 22:19:30 +00001035 if f.properties.Rollback_index != nil {
1036 rollbackIndex := proptools.Int(f.properties.Rollback_index)
1037 if rollbackIndex < 0 {
1038 ctx.PropertyErrorf("rollback_index", "Rollback index must be non-negative")
1039 }
1040 avb_add_hashtree_footer_args += " --rollback_index " + strconv.Itoa(rollbackIndex)
1041 }
Cole Fauste1676122024-12-03 17:32:25 -08001042 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 -08001043 // We're not going to add BuildFingerPrintFile as a dep. If it changed, it's likely because
1044 // the build number changed, and we don't want to trigger rebuilds solely based on the build
1045 // number.
Cole Fauste1676122024-12-03 17:32:25 -08001046 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 +00001047 if f.properties.Security_patch != nil && proptools.String(f.properties.Security_patch) != "" {
1048 avb_add_hashtree_footer_args += fmt.Sprintf(" --prop com.android.build.%s.security_patch:%s", f.partitionName(), proptools.String(f.properties.Security_patch))
1049 }
Shikha Panware6f30632022-12-21 12:54:45 +00001050 addStr("avb_add_hashtree_footer_args", avb_add_hashtree_footer_args)
Jiyong Park71baa762021-01-18 21:11:03 +09001051 }
1052
Cole Faust0d467052024-12-04 17:19:19 -08001053 if f.properties.File_contexts != nil && f.properties.Precompiled_file_contexts != nil {
1054 ctx.ModuleErrorf("file_contexts and precompiled_file_contexts cannot both be set")
1055 } else if f.properties.File_contexts != nil {
Spandan Dasf12ff9b2025-02-12 22:27:43 +00001056 f.selinuxFc = f.buildFileContexts(ctx)
Cole Faust0d467052024-12-04 17:19:19 -08001057 } else if f.properties.Precompiled_file_contexts != nil {
Spandan Dasf12ff9b2025-02-12 22:27:43 +00001058 f.selinuxFc = android.PathForModuleSrc(ctx, *f.properties.Precompiled_file_contexts)
1059 }
1060 if f.selinuxFc != nil {
1061 addPath("selinux_fc", f.selinuxFc)
Inseob Kimcc8e5362021-02-03 14:05:24 +09001062 }
Jooyung Han65f402b2022-04-21 14:24:04 +09001063 if timestamp := proptools.String(f.properties.Fake_timestamp); timestamp != "" {
1064 addStr("timestamp", timestamp)
Spandan Dasa0ddc512025-01-06 20:23:55 +00001065 } else if ctx.Config().Getenv("USE_FIXED_TIMESTAMP_IMG_FILES") == "true" {
1066 addStr("use_fixed_timestamp", "true")
Jooyung Han65f402b2022-04-21 14:24:04 +09001067 }
Spandan Dasa0ddc512025-01-06 20:23:55 +00001068
Jooyung Han65f402b2022-04-21 14:24:04 +09001069 if uuid := proptools.String(f.properties.Uuid); uuid != "" {
1070 addStr("uuid", uuid)
1071 addStr("hash_seed", uuid)
1072 }
mrziwang1a6291f2024-11-07 14:29:25 -08001073
Jihoon Kang40551e62025-01-14 21:55:08 +00001074 // Disable sparse only when partition size is not defined. disable_sparse has the same
1075 // effect as <partition name>_disable_sparse.
1076 if f.properties.Partition_size == nil {
1077 addStr("disable_sparse", "true")
1078 }
Cole Faust43a52c72024-11-26 12:46:08 -08001079
mrziwang1a6291f2024-11-07 14:29:25 -08001080 fst := f.fsType(ctx)
1081 switch fst {
1082 case erofsType:
1083 // Add erofs properties
Cole Faust3e730972024-12-03 13:12:08 -08001084 addStr("erofs_default_compressor", proptools.StringDefault(f.properties.Erofs.Compressor, "lz4hc,9"))
1085 if f.properties.Erofs.Compress_hints != nil {
1086 src := android.PathForModuleSrc(ctx, *f.properties.Erofs.Compress_hints)
1087 addPath("erofs_default_compress_hints", src)
Spandan Dasc35d6fb2024-10-10 17:51:14 +00001088 }
1089 if proptools.BoolDefault(f.properties.Erofs.Sparse, true) {
1090 // https://source.corp.google.com/h/googleplex-android/platform/build/+/88b1c67239ca545b11580237242774b411f2fed9:core/Makefile;l=2292;bpv=1;bpt=0;drc=ea8f34bc1d6e63656b4ec32f2391e9d54b3ebb6b
1091 addStr("erofs_sparse_flag", "-s")
1092 }
mrziwang1a6291f2024-11-07 14:29:25 -08001093 case f2fsType:
1094 if proptools.BoolDefault(f.properties.F2fs.Sparse, true) {
1095 // https://source.corp.google.com/h/googleplex-android/platform/build/+/88b1c67239ca545b11580237242774b411f2fed9:core/Makefile;l=2294;drc=ea8f34bc1d6e63656b4ec32f2391e9d54b3ebb6b;bpv=1;bpt=0
1096 addStr("f2fs_sparse_flag", "-S")
1097 }
Spandan Dasc35d6fb2024-10-10 17:51:14 +00001098 }
mrziwang1a6291f2024-11-07 14:29:25 -08001099 f.checkFsTypePropertyError(ctx, fst, fsTypeStr(fst))
Spandan Dasc35d6fb2024-10-10 17:51:14 +00001100
Jihoon Kang983dd882025-01-13 23:14:11 +00001101 if f.properties.Partition_size != nil {
1102 addStr("partition_size", strconv.FormatInt(*f.properties.Partition_size, 10))
1103 }
1104
Jihoon Kang6d08d922025-01-14 18:31:57 +00001105 if proptools.BoolDefault(f.properties.Support_casefolding, false) {
1106 addStr("needs_casefold", "1")
1107 }
1108
1109 if proptools.BoolDefault(f.properties.Support_project_quota, false) {
1110 addStr("needs_projid", "1")
1111 }
1112
1113 if proptools.BoolDefault(f.properties.Enable_compression, false) {
1114 addStr("needs_compress", "1")
1115 }
1116
Cole Fauste03ab892025-01-17 13:55:04 -08001117 sort.Strings(lines)
1118
Cole Fauste1676122024-12-03 17:32:25 -08001119 propFilePreProcessing := android.PathForModuleOut(ctx, "prop_pre_processing")
Cole Fauste03ab892025-01-17 13:55:04 -08001120 android.WriteFileRule(ctx, propFilePreProcessing, strings.Join(lines, "\n"))
Cole Faust4e9f5922024-11-13 16:09:23 -08001121 propFile := android.PathForModuleOut(ctx, "prop")
Cole Fauste1676122024-12-03 17:32:25 -08001122 ctx.Build(pctx, android.BuildParams{
Cole Faustefeb5c42024-12-16 10:47:26 -08001123 Rule: textFileProcessorRule,
1124 Input: propFilePreProcessing,
1125 Output: propFile,
Cole Fauste1676122024-12-03 17:32:25 -08001126 })
Jiyong Park72678312021-01-18 17:29:49 +09001127 return propFile, deps
1128}
1129
mrziwang1a6291f2024-11-07 14:29:25 -08001130// This method checks if there is any property set for the fstype(s) other than
1131// the current fstype.
1132func (f *filesystem) checkFsTypePropertyError(ctx android.ModuleContext, t fsType, fs string) {
1133 raiseError := func(otherFsType, currentFsType string) {
1134 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)
1135 ctx.PropertyErrorf(otherFsType, errMsg)
1136 }
1137
1138 if t != erofsType {
1139 if f.properties.Erofs.Compressor != nil || f.properties.Erofs.Compress_hints != nil || f.properties.Erofs.Sparse != nil {
1140 raiseError("erofs", fs)
1141 }
1142 }
1143 if t != f2fsType {
1144 if f.properties.F2fs.Sparse != nil {
1145 raiseError("f2fs", fs)
1146 }
1147 }
1148}
1149
Jihoon Kang6da80752024-12-23 18:53:32 +00001150func includeFilesRootDir(ctx android.ModuleContext) (rootDirs android.Paths, partitions android.Paths) {
1151 ctx.VisitDirectDepsWithTag(interPartitionInstallDependencyTag, func(m android.Module) {
1152 if fsProvider, ok := android.OtherModuleProvider(ctx, m, FilesystemProvider); ok {
1153 rootDirs = append(rootDirs, fsProvider.RootDir)
1154 partitions = append(partitions, fsProvider.Output)
1155 } else {
1156 ctx.PropertyErrorf("include_files_of", "only filesystem modules can be listed in "+
1157 "include_files_of but %s is not a filesystem module", m.Name())
1158 }
1159 })
1160 return rootDirs, partitions
1161}
1162
Cole Faust62cfaeb2025-01-15 18:06:40 -08001163func (f *filesystem) buildCpioImage(
1164 ctx android.ModuleContext,
1165 builder *android.RuleBuilder,
1166 rootDir android.OutputPath,
1167 compressed bool,
1168) android.Path {
Jiyong Park11a65972021-02-01 21:09:38 +09001169 if proptools.Bool(f.properties.Use_avb) {
1170 ctx.PropertyErrorf("use_avb", "signing compresed cpio image using avbtool is not supported."+
1171 "Consider adding this to bootimg module and signing the entire boot image.")
1172 }
1173
Inseob Kimcc8e5362021-02-03 14:05:24 +09001174 if proptools.String(f.properties.File_contexts) != "" {
1175 ctx.PropertyErrorf("file_contexts", "file_contexts is not supported for compressed cpio image.")
1176 }
1177
Jihoon Kang6da80752024-12-23 18:53:32 +00001178 rootDirs, partitions := includeFilesRootDir(ctx)
1179
Cole Faust4e9f5922024-11-13 16:09:23 -08001180 output := android.PathForModuleOut(ctx, f.installFileName())
Jiyong Park837cdb22021-02-05 00:17:14 +09001181 cmd := builder.Command().
Jiyong Park11a65972021-02-01 21:09:38 +09001182 BuiltTool("mkbootfs").
Spandan Das5ef1a9c2025-02-11 18:50:17 +00001183 Implicit(f.fileystemStagingDirTimestamp(ctx)).
Jiyong Park837cdb22021-02-05 00:17:14 +09001184 Text(rootDir.String()) // input directory
Jihoon Kang6da80752024-12-23 18:53:32 +00001185
1186 for i := range len(rootDirs) {
1187 cmd.Text(rootDirs[i].String())
1188 }
1189 cmd.Implicits(partitions)
1190
Jihoon Kang6c03c8e2024-11-18 21:30:22 +00001191 if nodeList := f.properties.Dev_nodes_description_file; nodeList != nil {
1192 cmd.FlagWithInput("-n ", android.PathForModuleSrc(ctx, proptools.String(nodeList)))
1193 }
Jiyong Park837cdb22021-02-05 00:17:14 +09001194 if compressed {
1195 cmd.Text("|").
1196 BuiltTool("lz4").
1197 Flag("--favor-decSpeed"). // for faster boot
1198 Flag("-12"). // maximum compression level
1199 Flag("-l"). // legacy format for kernel
1200 Text(">").Output(output)
1201 } else {
1202 cmd.Text(">").Output(output)
1203 }
Jiyong Park11a65972021-02-01 21:09:38 +09001204
1205 // rootDir is not deleted. Might be useful for quick inspection.
Jiyong Park837cdb22021-02-05 00:17:14 +09001206 builder.Build("build_cpio_image", fmt.Sprintf("Creating filesystem %s", f.BaseModuleName()))
Jiyong Park11a65972021-02-01 21:09:38 +09001207
Cole Faust62cfaeb2025-01-15 18:06:40 -08001208 return output
Jiyong Park11a65972021-02-01 21:09:38 +09001209}
1210
Cole Faust4a2a7c92024-03-12 12:44:40 -07001211var validPartitions = []string{
1212 "system",
1213 "userdata",
1214 "cache",
1215 "system_other",
1216 "vendor",
1217 "product",
1218 "system_ext",
1219 "odm",
1220 "vendor_dlkm",
1221 "odm_dlkm",
1222 "system_dlkm",
Cole Faust76a6e952024-11-07 16:56:45 -08001223 "ramdisk",
Cole Faust24938e22024-11-18 14:01:58 -08001224 "vendor_ramdisk",
Jihoon Kang3216c982024-12-02 19:42:20 +00001225 "recovery",
Cole Faust4a2a7c92024-03-12 12:44:40 -07001226}
1227
Cole Faust19fbb072025-01-30 18:19:29 -08001228func (f *filesystem) buildEventLogtagsFile(
1229 ctx android.ModuleContext,
1230 builder *android.RuleBuilder,
1231 rebasedDir android.OutputPath,
1232 fullInstallPaths *[]FullInstallPathInfo,
1233) {
Inseob Kimb7b84572024-04-30 10:51:47 +09001234 if !proptools.Bool(f.properties.Build_logtags) {
1235 return
1236 }
1237
Inseob Kimb7b84572024-04-30 10:51:47 +09001238 etcPath := rebasedDir.Join(ctx, "etc")
1239 eventLogtagsPath := etcPath.Join(ctx, "event-log-tags")
1240 builder.Command().Text("mkdir").Flag("-p").Text(etcPath.String())
Cole Fauste4506af2024-12-11 14:14:50 -08001241 builder.Command().Text("cp").Input(android.MergedLogtagsPath(ctx)).Text(eventLogtagsPath.String())
Kiyoung Kim99a954d2024-06-21 14:22:20 +09001242
Cole Faust19fbb072025-01-30 18:19:29 -08001243 *fullInstallPaths = append(*fullInstallPaths, FullInstallPathInfo{
1244 FullInstallPath: android.PathForModuleInPartitionInstall(ctx, f.PartitionType(), "etc", "event-log-tags"),
1245 SourcePath: android.MergedLogtagsPath(ctx),
1246 })
1247
Kiyoung Kim99a954d2024-06-21 14:22:20 +09001248 f.appendToEntry(ctx, eventLogtagsPath)
Inseob Kimb7b84572024-04-30 10:51:47 +09001249}
1250
Cole Faust19fbb072025-01-30 18:19:29 -08001251func (f *filesystem) BuildLinkerConfigFile(
1252 ctx android.ModuleContext,
1253 builder *android.RuleBuilder,
1254 rebasedDir android.OutputPath,
1255 fullInstallPaths *[]FullInstallPathInfo,
1256) {
Spandan Das2047a4c2024-11-11 21:24:58 +00001257 if !proptools.Bool(f.properties.Linker_config.Gen_linker_config) {
Spandan Das92631882024-10-28 22:49:38 +00001258 return
1259 }
1260
Spandan Das918191e2024-10-31 18:27:23 +00001261 provideModules, _ := f.getLibsForLinkerConfig(ctx)
Cole Faustfee27012024-12-13 14:10:31 -08001262 intermediateOutput := android.PathForModuleOut(ctx, "linker.config.pb")
1263 linkerconfig.BuildLinkerConfig(ctx, android.PathsForModuleSrc(ctx, f.properties.Linker_config.Linker_config_srcs), provideModules, nil, intermediateOutput)
Spandan Das92631882024-10-28 22:49:38 +00001264 output := rebasedDir.Join(ctx, "etc", "linker.config.pb")
Cole Faustfee27012024-12-13 14:10:31 -08001265 builder.Command().Text("cp").Input(intermediateOutput).Output(output)
Spandan Das92631882024-10-28 22:49:38 +00001266
Cole Faust19fbb072025-01-30 18:19:29 -08001267 *fullInstallPaths = append(*fullInstallPaths, FullInstallPathInfo{
1268 FullInstallPath: android.PathForModuleInPartitionInstall(ctx, f.PartitionType(), "etc", "linker.config.pb"),
1269 SourcePath: intermediateOutput,
1270 })
1271
Spandan Das92631882024-10-28 22:49:38 +00001272 f.appendToEntry(ctx, output)
1273}
1274
Kiyoung Kim23be5bb2024-11-27 00:50:30 +00001275func (f *filesystem) ShouldUseVintfFragmentModuleOnly() bool {
1276 return false
1277}
1278
Jiyong Parkf46b1af2024-04-05 18:13:33 +09001279type partition interface {
1280 PartitionType() string
1281}
1282
Cole Faust9a24d902024-03-18 15:38:12 -07001283func (f *filesystem) PartitionType() string {
1284 return proptools.StringDefault(f.properties.Partition_type, "system")
1285}
1286
Jiyong Parkf46b1af2024-04-05 18:13:33 +09001287var _ partition = (*filesystem)(nil)
1288
Jiyong Park65c49f52020-11-24 14:23:26 +09001289var _ android.AndroidMkEntriesProvider = (*filesystem)(nil)
1290
1291// Implements android.AndroidMkEntriesProvider
1292func (f *filesystem) AndroidMkEntries() []android.AndroidMkEntries {
1293 return []android.AndroidMkEntries{android.AndroidMkEntries{
1294 Class: "ETC",
1295 OutputFile: android.OptionalPathForPath(f.output),
1296 ExtraEntries: []android.AndroidMkExtraEntriesFunc{
Colin Crossaa255532020-07-03 13:18:24 -07001297 func(ctx android.AndroidMkExtraEntriesContext, entries *android.AndroidMkEntries) {
Colin Crossc68db4b2021-11-11 18:59:15 -08001298 entries.SetString("LOCAL_MODULE_PATH", f.installDir.String())
Jiyong Park65c49f52020-11-24 14:23:26 +09001299 entries.SetString("LOCAL_INSTALLED_MODULE_STEM", f.installFileName())
Kiyoung Kim99a954d2024-06-21 14:22:20 +09001300 entries.SetString("LOCAL_FILESYSTEM_FILELIST", f.fileListFile.String())
Jiyong Park65c49f52020-11-24 14:23:26 +09001301 },
1302 },
1303 }}
Jiyong Park6f0f6882020-11-12 13:14:30 +09001304}
Jiyong Park12a719c2021-01-07 15:31:24 +09001305
1306// Filesystem is the public interface for the filesystem struct. Currently, it's only for the apex
1307// package to have access to the output file.
1308type Filesystem interface {
1309 android.Module
1310 OutputPath() android.Path
Jiyong Park972e06c2021-03-15 23:32:49 +09001311
1312 // Returns the output file that is signed by avbtool. If this module is not signed, returns
1313 // nil.
1314 SignedOutputPath() android.Path
Jiyong Park12a719c2021-01-07 15:31:24 +09001315}
1316
1317var _ Filesystem = (*filesystem)(nil)
1318
1319func (f *filesystem) OutputPath() android.Path {
1320 return f.output
1321}
Jiyong Park972e06c2021-03-15 23:32:49 +09001322
1323func (f *filesystem) SignedOutputPath() android.Path {
1324 if proptools.Bool(f.properties.Use_avb) {
1325 return f.OutputPath()
1326 }
1327 return nil
1328}
Jooyung Han0fbbc2b2022-03-25 12:35:46 +09001329
1330// Filter the result of GatherPackagingSpecs to discard items targeting outside "system" partition.
1331// Note that "apex" module installs its contents to "apex"(fake partition) as well
1332// for symbol lookup by imitating "activated" paths.
1333func (f *filesystem) gatherFilteredPackagingSpecs(ctx android.ModuleContext) map[string]android.PackagingSpec {
Cole Faustb8e280f2025-01-16 16:33:26 -08001334 return f.PackagingBase.GatherPackagingSpecsWithFilterAndModifier(ctx, f.filesystemBuilder.FilterPackagingSpec, f.filesystemBuilder.ModifyPackagingSpec)
1335}
1336
Jihoon Kangabec3ec2025-02-19 00:55:10 +00001337func (f *filesystem) gatherOwners(specs map[string]android.PackagingSpec) []InstalledModuleInfo {
1338 var owners []InstalledModuleInfo
1339 for _, p := range android.SortedKeys(specs) {
1340 spec := specs[p]
1341 owners = append(owners, InstalledModuleInfo{
1342 Name: spec.Owner(),
1343 Variation: spec.Variation(),
1344 })
1345 }
1346 return owners
1347}
1348
Cole Faustb8e280f2025-01-16 16:33:26 -08001349// Dexpreopt files are installed to system_other. Collect the packaingSpecs for the dexpreopt files
1350// from this partition to export to the system_other partition later.
1351func (f *filesystem) systemOtherFiles(ctx android.ModuleContext) map[string]android.PackagingSpec {
1352 filter := func(spec android.PackagingSpec) bool {
1353 // For some reason system_other packaging specs don't set the partition field.
1354 return strings.HasPrefix(spec.RelPathInPackage(), "system_other/")
1355 }
1356 modifier := func(spec *android.PackagingSpec) {
1357 spec.SetRelPathInPackage(strings.TrimPrefix(spec.RelPathInPackage(), "system_other/"))
1358 spec.SetPartition("system_other")
1359 }
1360 return f.PackagingBase.GatherPackagingSpecsWithFilterAndModifier(ctx, filter, modifier)
Jooyung Han0fbbc2b2022-03-25 12:35:46 +09001361}
Jooyung Han65f402b2022-04-21 14:24:04 +09001362
1363func sha1sum(values []string) string {
1364 h := sha256.New()
1365 for _, value := range values {
1366 io.WriteString(h, value)
1367 }
1368 return fmt.Sprintf("%x", h.Sum(nil))
1369}
Jooyung Hane6067592023-03-16 13:11:17 +09001370
1371// Base cc.UseCoverage
1372
1373var _ cc.UseCoverage = (*filesystem)(nil)
1374
Colin Crosse1a85552024-06-14 12:17:37 -07001375func (*filesystem) IsNativeCoverageNeeded(ctx cc.IsNativeCoverageNeededContext) bool {
Jooyung Hane6067592023-03-16 13:11:17 +09001376 return ctx.Device() && ctx.DeviceConfig().NativeCoverageEnabled()
1377}
Jiyong Parkf46b1af2024-04-05 18:13:33 +09001378
1379// android_filesystem_defaults
1380
1381type filesystemDefaults struct {
1382 android.ModuleBase
1383 android.DefaultsModuleBase
1384
Inseob Kim3c0a0422024-11-05 17:21:37 +09001385 properties FilesystemProperties
Jiyong Parkf46b1af2024-04-05 18:13:33 +09001386}
1387
1388// android_filesystem_defaults is a default module for android_filesystem and android_system_image
1389func filesystemDefaultsFactory() android.Module {
1390 module := &filesystemDefaults{}
1391 module.AddProperties(&module.properties)
1392 module.AddProperties(&android.PackagingProperties{})
1393 android.InitDefaultsModule(module)
1394 return module
1395}
1396
1397func (f *filesystemDefaults) PartitionType() string {
1398 return proptools.StringDefault(f.properties.Partition_type, "system")
1399}
1400
1401var _ partition = (*filesystemDefaults)(nil)
1402
1403func (f *filesystemDefaults) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1404 validatePartitionType(ctx, f)
Yu Liufc8d5c12025-01-09 00:19:06 +00001405 android.SetProvider(ctx, FilesystemDefaultsInfoProvider, FilesystemDefaultsInfo{
1406 PartitionType: f.PartitionType(),
1407 })
Jiyong Parkf46b1af2024-04-05 18:13:33 +09001408}
Spandan Das918191e2024-10-31 18:27:23 +00001409
1410// getLibsForLinkerConfig returns
1411// 1. A list of libraries installed in this filesystem
1412// 2. A list of dep libraries _not_ installed in this filesystem
1413//
1414// `linkerconfig.BuildLinkerConfig` will convert these two to a linker.config.pb for the filesystem
1415// (1) will be added to --provideLibs if they are C libraries with a stable interface (has stubs)
1416// (2) will be added to --requireLibs if they are C libraries with a stable interface (has stubs)
Yu Liu68a70b72025-01-08 22:54:44 +00001417func (f *filesystem) getLibsForLinkerConfig(ctx android.ModuleContext) ([]android.ModuleProxy, []android.ModuleProxy) {
Spandan Das918191e2024-10-31 18:27:23 +00001418 // we need "Module"s for packaging items
Yu Liu68a70b72025-01-08 22:54:44 +00001419 modulesInPackageByModule := make(map[android.ModuleProxy]bool)
Spandan Das918191e2024-10-31 18:27:23 +00001420 modulesInPackageByName := make(map[string]bool)
1421
1422 deps := f.gatherFilteredPackagingSpecs(ctx)
Yu Liu68a70b72025-01-08 22:54:44 +00001423 ctx.WalkDepsProxy(func(child, parent android.ModuleProxy) bool {
1424 if !android.OtherModuleProviderOrDefault(ctx, child, android.CommonModuleInfoKey).Enabled {
Yu Liu9c6b6762025-01-08 22:04:35 +00001425 return false
1426 }
Spandan Das918191e2024-10-31 18:27:23 +00001427 for _, ps := range android.OtherModuleProviderOrDefault(
1428 ctx, child, android.InstallFilesProvider).PackagingSpecs {
Spandan Dasecf667f2024-12-05 00:58:56 +00001429 if _, ok := deps[ps.RelPathInPackage()]; ok && ps.Partition() == f.PartitionType() {
Spandan Das918191e2024-10-31 18:27:23 +00001430 modulesInPackageByModule[child] = true
1431 modulesInPackageByName[child.Name()] = true
1432 return true
1433 }
1434 }
1435 return true
1436 })
1437
Yu Liu68a70b72025-01-08 22:54:44 +00001438 provideModules := make([]android.ModuleProxy, 0, len(modulesInPackageByModule))
Spandan Das918191e2024-10-31 18:27:23 +00001439 for mod := range modulesInPackageByModule {
1440 provideModules = append(provideModules, mod)
1441 }
1442
Yu Liu68a70b72025-01-08 22:54:44 +00001443 var requireModules []android.ModuleProxy
1444 ctx.WalkDepsProxy(func(child, parent android.ModuleProxy) bool {
1445 if !android.OtherModuleProviderOrDefault(ctx, child, android.CommonModuleInfoKey).Enabled {
Yu Liu9c6b6762025-01-08 22:04:35 +00001446 return false
1447 }
Spandan Das918191e2024-10-31 18:27:23 +00001448 _, parentInPackage := modulesInPackageByModule[parent]
1449 _, childInPackageName := modulesInPackageByName[child.Name()]
1450
1451 // When parent is in the package, and child (or its variant) is not, this can be from an interface.
1452 if parentInPackage && !childInPackageName {
1453 requireModules = append(requireModules, child)
1454 }
1455 return true
1456 })
1457
1458 return provideModules, requireModules
1459}
Cole Faust26bdac52024-11-19 13:37:53 -08001460
1461// Checks that the given file doesn't exceed the given size, and will also print a warning
1462// if it's nearing the maximum size. Equivalent to assert-max-image-size in make:
1463// https://cs.android.com/android/platform/superproject/main/+/main:build/make/core/definitions.mk;l=3455;drc=993c4de29a02a6accd60ceaaee153307e1a18d10
1464func assertMaxImageSize(builder *android.RuleBuilder, image android.Path, maxSize int64, addAvbLater bool) {
1465 if addAvbLater {
1466 // The value 69632 is derived from MAX_VBMETA_SIZE + MAX_FOOTER_SIZE in avbtool.
1467 // Logic copied from make:
1468 // https://cs.android.com/android/platform/superproject/main/+/main:build/make/core/Makefile;l=228;drc=a6a0007ef24e16c0b79f439beac4a118416717e6
1469 maxSize -= 69632
1470 }
1471 cmd := builder.Command()
1472 cmd.Textf(`file="%s"; maxsize="%d";`+
1473 `total=$(stat -c "%%s" "$file" | tr -d '\n');`+
1474 `if [ "$total" -gt "$maxsize" ]; then `+
1475 ` echo "error: $file too large ($total > $maxsize)";`+
1476 ` false;`+
1477 `elif [ "$total" -gt $((maxsize - 32768)) ]; then `+
1478 ` echo "WARNING: $file approaching size limit ($total now; limit $maxsize)";`+
1479 `fi`,
1480 image, maxSize)
1481 cmd.Implicit(image)
1482}
Spandan Das71be42d2024-11-20 18:34:16 +00001483
1484// addAutogeneratedRroDeps walks the transitive closure of vendor and product partitions.
1485// It visits apps installed in system and system_ext partitions, and adds the autogenerated
1486// RRO modules to its own deps.
1487func addAutogeneratedRroDeps(ctx android.BottomUpMutatorContext) {
1488 f, ok := ctx.Module().(*filesystem)
1489 if !ok {
1490 return
1491 }
1492 thisPartition := f.PartitionType()
1493 if thisPartition != "vendor" && thisPartition != "product" {
Cole Faust34592c02024-12-13 11:20:24 -08001494 if f.properties.Android_filesystem_deps.System != nil {
1495 ctx.PropertyErrorf("android_filesystem_deps.system", "only vendor or product partitions can use android_filesystem_deps")
1496 }
1497 if f.properties.Android_filesystem_deps.System_ext != nil {
1498 ctx.PropertyErrorf("android_filesystem_deps.system_ext", "only vendor or product partitions can use android_filesystem_deps")
1499 }
Spandan Das71be42d2024-11-20 18:34:16 +00001500 return
1501 }
1502 ctx.WalkDeps(func(child, parent android.Module) bool {
1503 depTag := ctx.OtherModuleDependencyTag(child)
1504 if parent.Name() == f.Name() && depTag != interPartitionDependencyTag {
1505 return false // This is a module listed in deps of vendor/product filesystem
1506 }
1507 if vendorOverlay := java.AutogeneratedRroModuleName(ctx, child.Name(), "vendor"); ctx.OtherModuleExists(vendorOverlay) && thisPartition == "vendor" {
1508 ctx.AddFarVariationDependencies(nil, dependencyTagWithVisibilityEnforcementBypass, vendorOverlay)
1509 }
1510 if productOverlay := java.AutogeneratedRroModuleName(ctx, child.Name(), "product"); ctx.OtherModuleExists(productOverlay) && thisPartition == "product" {
1511 ctx.AddFarVariationDependencies(nil, dependencyTagWithVisibilityEnforcementBypass, productOverlay)
1512 }
1513 return true
1514 })
1515}
Spandan Das6ec1fcf2025-02-11 22:51:51 +00001516
1517func (f *filesystem) MakeVars(ctx android.MakeVarsModuleContext) {
1518 if f.Name() == ctx.Config().SoongDefinedSystemImage() {
1519 ctx.StrictRaw("SOONG_DEFINED_SYSTEM_IMAGE_PATH", f.output.String())
1520 }
1521}