blob: 3f774331d76e3565bb260fe6133ad0fd130084a8 [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)
Jooyung Han9706cbc2021-04-15 22:43:48 +090039}
40
41func registerBuildComponents(ctx android.RegistrationContext) {
Cole Faust92ccbe22024-10-03 14:38:37 -070042 ctx.RegisterModuleType("android_filesystem", FilesystemFactory)
Jiyong Parkf46b1af2024-04-05 18:13:33 +090043 ctx.RegisterModuleType("android_filesystem_defaults", filesystemDefaultsFactory)
Jihoon Kang98047cf2024-10-02 17:13:54 +000044 ctx.RegisterModuleType("android_system_image", SystemImageFactory)
Jiyong Parkbc485482022-11-15 22:31:49 +090045 ctx.RegisterModuleType("avb_add_hash_footer", avbAddHashFooterFactory)
Inseob Kim87230e62023-11-22 18:55:07 +090046 ctx.RegisterModuleType("avb_add_hash_footer_defaults", avbAddHashFooterDefaultsFactory)
Alice Wang000e3a32023-01-03 16:11:20 +000047 ctx.RegisterModuleType("avb_gen_vbmeta_image", avbGenVbmetaImageFactory)
Inseob Kim87230e62023-11-22 18:55:07 +090048 ctx.RegisterModuleType("avb_gen_vbmeta_image_defaults", avbGenVbmetaImageDefaultsFactory)
Jiyong Park6f0f6882020-11-12 13:14:30 +090049}
50
Spandan Das71be42d2024-11-20 18:34:16 +000051func registerMutators(ctx android.RegistrationContext) {
52 ctx.PostDepsMutators(func(ctx android.RegisterMutatorsContext) {
53 ctx.BottomUp("add_autogenerated_rro_deps", addAutogeneratedRroDeps)
54 })
55}
56
Cole Fauste1676122024-12-03 17:32:25 -080057// Remember to add referenced files to implicits!
58var textFileProcessorRule = pctx.AndroidStaticRule("text_file_processing", blueprint.RuleParams{
59 Command: "build/soong/scripts/text_file_processor.py $in $out",
60 CommandDeps: []string{"build/soong/scripts/text_file_processor.py"},
61})
62
Jiyong Park6f0f6882020-11-12 13:14:30 +090063type filesystem struct {
64 android.ModuleBase
65 android.PackagingBase
Jiyong Parkf46b1af2024-04-05 18:13:33 +090066 android.DefaultableModuleBase
Jiyong Park65c49f52020-11-24 14:23:26 +090067
Jihoon Kang98047cf2024-10-02 17:13:54 +000068 properties FilesystemProperties
Jiyong Park71baa762021-01-18 21:11:03 +090069
Cole Faust4e9f5922024-11-13 16:09:23 -080070 output android.Path
Jiyong Park65c49f52020-11-24 14:23:26 +090071 installDir android.InstallPath
Jooyung Han0fbbc2b2022-03-25 12:35:46 +090072
Cole Faust4e9f5922024-11-13 16:09:23 -080073 fileListFile android.Path
Kiyoung Kim99a954d2024-06-21 14:22:20 +090074
75 // Keeps the entries installed from this filesystem
Jooyung Han0fbbc2b2022-03-25 12:35:46 +090076 entries []string
Kiyoung Kim67118212024-11-07 13:23:44 +090077
78 filesystemBuilder filesystemBuilder
Jiyong Park6f0f6882020-11-12 13:14:30 +090079}
80
Kiyoung Kim67118212024-11-07 13:23:44 +090081type filesystemBuilder interface {
Cole Faust19fbb072025-01-30 18:19:29 -080082 BuildLinkerConfigFile(ctx android.ModuleContext, builder *android.RuleBuilder, rebasedDir android.OutputPath, fullInstallPaths *[]FullInstallPathInfo)
Kiyoung Kim67118212024-11-07 13:23:44 +090083 // Function that filters PackagingSpec in PackagingBase.GatherPackagingSpecs()
84 FilterPackagingSpec(spec android.PackagingSpec) bool
Inseob Kim3c0a0422024-11-05 17:21:37 +090085 // Function that modifies PackagingSpec in PackagingBase.GatherPackagingSpecs() to customize.
86 // For example, GSI system.img contains system_ext and product artifacts and their
87 // relPathInPackage need to be rebased to system/system_ext and system/system_product.
88 ModifyPackagingSpec(spec *android.PackagingSpec)
Kiyoung Kim23be5bb2024-11-27 00:50:30 +000089
90 // Function to check if the filesystem should not use `vintf_fragments` property,
91 // but use `vintf_fragment` module type instead
92 ShouldUseVintfFragmentModuleOnly() bool
Kiyoung Kim67118212024-11-07 13:23:44 +090093}
94
95var _ filesystemBuilder = (*filesystem)(nil)
96
Spandan Das69464c32024-10-25 20:08:06 +000097type SymlinkDefinition struct {
Inseob Kim14199b02021-02-09 21:18:31 +090098 Target *string
99 Name *string
100}
101
Jihoon Kang0a453892024-12-09 22:16:26 +0000102// CopyWithNamePrefix returns a new [SymlinkDefinition] with prefix added to Name.
103func (s *SymlinkDefinition) CopyWithNamePrefix(prefix string) SymlinkDefinition {
104 return SymlinkDefinition{
105 Target: s.Target,
106 Name: proptools.StringPtr(filepath.Join(prefix, proptools.String(s.Name))),
107 }
108}
109
Jihoon Kang98047cf2024-10-02 17:13:54 +0000110type FilesystemProperties struct {
Jiyong Park71baa762021-01-18 21:11:03 +0900111 // When set to true, sign the image with avbtool. Default is false.
112 Use_avb *bool
113
114 // Path to the private key that avbtool will use to sign this filesystem image.
115 // TODO(jiyong): allow apex_key to be specified here
116 Avb_private_key *string `android:"path"`
117
Shikha Panwar01403bb2022-12-22 12:22:57 +0000118 // Signing algorithm for avbtool. Default is SHA256_RSA4096.
Jiyong Park71baa762021-01-18 21:11:03 +0900119 Avb_algorithm *string
Jiyong Park11a65972021-02-01 21:09:38 +0900120
Shikha Panwar01403bb2022-12-22 12:22:57 +0000121 // Hash algorithm used for avbtool (for descriptors). This is passed as hash_algorithm to
Nikita Ioffe50fb49c2025-01-24 13:49:00 +0000122 // avbtool. Default is sha256.
Shikha Panware6f30632022-12-21 12:54:45 +0000123 Avb_hash_algorithm *string
124
Spandan Dase5c393c2024-12-12 19:25:07 +0000125 // The security patch passed to as the com.android.build.<type>.security_patch avb property.
126 Security_patch *string
127
Cole Fauste1676122024-12-03 17:32:25 -0800128 // Whether or not to use forward-error-correction codes when signing with AVB. Defaults to true.
129 Use_fec *bool
130
Nikita Ioffe2c8cdc62024-03-27 22:19:30 +0000131 // The index used to prevent rollback of the image. Only used if use_avb is true.
132 Rollback_index *int64
133
Luca Stefani9235f4c2025-02-08 12:09:34 +0100134 // Rollback index location of this image. Must be 1, 2, 3, etc.
Jihoon Kang2f0d1932025-01-17 19:22:44 +0000135 Rollback_index_location *int64
136
Jiyong Parkac4076d2021-03-15 23:21:30 +0900137 // Name of the partition stored in vbmeta desc. Defaults to the name of this module.
138 Partition_name *string
139
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000140 // Type of the filesystem. Currently, ext4, erofs, cpio, and compressed_cpio are supported. Default
Jiyong Park837cdb22021-02-05 00:17:14 +0900141 // is ext4.
Jiyong Park11a65972021-02-01 21:09:38 +0900142 Type *string
Inseob Kimcc8e5362021-02-03 14:05:24 +0900143
Cole Faust9a24d902024-03-18 15:38:12 -0700144 // Identifies which partition this is for //visibility:any_system_image (and others) visibility
145 // checks, and will be used in the future for API surface checks.
146 Partition_type *string
147
Cole Faust0d467052024-12-04 17:19:19 -0800148 // file_contexts file to make image. Currently, only ext4 is supported. These file contexts
149 // will be compiled with sefcontext_compile
Inseob Kimcc8e5362021-02-03 14:05:24 +0900150 File_contexts *string `android:"path"`
Inseob Kim2ce1b5d2021-02-15 17:01:04 +0900151
Cole Faust0d467052024-12-04 17:19:19 -0800152 // The selinux file contexts, after having already run them through sefcontext_compile
153 Precompiled_file_contexts *string `android:"path"`
154
Inseob Kim2ce1b5d2021-02-15 17:01:04 +0900155 // Base directory relative to root, to which deps are installed, e.g. "system". Default is "."
156 // (root).
157 Base_dir *string
Inseob Kim14199b02021-02-09 21:18:31 +0900158
159 // Directories to be created under root. e.g. /dev, /proc, etc.
Cole Faustd9c6a5b2024-05-21 14:54:00 -0700160 Dirs proptools.Configurable[[]string]
Inseob Kim14199b02021-02-09 21:18:31 +0900161
Jihoon Kang6da80752024-12-23 18:53:32 +0000162 // List of filesystem modules to include in creating the partition. The root directory of
163 // the provided filesystem modules are included in creating the partition.
164 // This is only supported for cpio and compressed cpio filesystem types.
165 Include_files_of []string
166
Inseob Kim14199b02021-02-09 21:18:31 +0900167 // Symbolic links to be created under root with "ln -sf <target> <name>".
Spandan Das69464c32024-10-25 20:08:06 +0000168 Symlinks []SymlinkDefinition
Jooyung Han65f402b2022-04-21 14:24:04 +0900169
170 // Seconds since unix epoch to override timestamps of file entries
171 Fake_timestamp *string
172
173 // When set, passed to mkuserimg_mke2fs --mke2fs_uuid & --mke2fs_hash_seed.
174 // Otherwise, they'll be set as random which might cause indeterministic build output.
175 Uuid *string
Inseob Kim376d72f2023-11-01 15:40:25 +0900176
177 // Mount point for this image. Default is "/"
178 Mount_point *string
Cole Faust4a2a7c92024-03-12 12:44:40 -0700179
Inseob Kimb7b84572024-04-30 10:51:47 +0900180 // When set, builds etc/event-log-tags file by merging logtags from all dependencies.
181 // Default is false
182 Build_logtags *bool
183
Justin Yun74f3f302024-05-07 14:32:14 +0900184 // Install aconfig_flags.pb file for the modules installed in this partition.
185 Gen_aconfig_flags_pb *bool
186
Cole Faust34592c02024-12-13 11:20:24 -0800187 // List of names of other filesystem partitions to import their aconfig flags from.
188 // This is used for the system partition to import system_ext's aconfig flags, as currently
189 // those are considered one "container": aosp/3261300
190 Import_aconfig_flags_from []string
191
Inseob Kim53391842024-03-29 17:44:07 +0900192 Fsverity fsverityProperties
Cole Faust92ccbe22024-10-03 14:38:37 -0700193
194 // If this property is set to true, the filesystem will call ctx.UncheckedModule(), causing
195 // it to not be built on checkbuilds. Used for the automatic migration from make to soong
196 // build modules, where we want to emit some not-yet-working filesystems and we don't want them
197 // to be built.
198 Unchecked_module *bool `blueprint:"mutated"`
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000199
200 Erofs ErofsProperties
Jihoon Kang0d545b82024-10-11 00:21:57 +0000201
mrziwang1a6291f2024-11-07 14:29:25 -0800202 F2fs F2fsProperties
203
Spandan Das2047a4c2024-11-11 21:24:58 +0000204 Linker_config LinkerConfigProperties
Spandan Das92631882024-10-28 22:49:38 +0000205
Jihoon Kang0d545b82024-10-11 00:21:57 +0000206 // Determines if the module is auto-generated from Soong or not. If the module is
207 // auto-generated, its deps are exempted from visibility enforcement.
208 Is_auto_generated *bool
Jihoon Kang6c03c8e2024-11-18 21:30:22 +0000209
210 // Path to the dev nodes description file. This is only needed for building the ramdisk
211 // partition and should not be explicitly specified.
212 Dev_nodes_description_file *string `android:"path" blueprint:"mutated"`
Spandan Das71be42d2024-11-20 18:34:16 +0000213
214 // Additional dependencies used for building android products
215 Android_filesystem_deps AndroidFilesystemDeps
Spandan Dasc49b85e2025-01-10 00:51:25 +0000216
217 // Name of the output. Default is $(module_name).img
218 Stem *string
Jihoon Kang983dd882025-01-13 23:14:11 +0000219
220 // The size of the partition on the device. It will be a build error if this built partition
221 // image exceeds this size.
222 Partition_size *int64
Jihoon Kang6d08d922025-01-14 18:31:57 +0000223
224 // Whether to format f2fs and ext4 in a way that supports casefolding
225 Support_casefolding *bool
226
227 // Whether to format f2fs and ext4 in a way that supports project quotas
228 Support_project_quota *bool
229
230 // Whether to enable per-file compression in f2fs
231 Enable_compression *bool
Spandan Das71be42d2024-11-20 18:34:16 +0000232}
233
234type AndroidFilesystemDeps struct {
235 System *string
236 System_ext *string
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000237}
238
239// Additional properties required to generate erofs FS partitions.
240type ErofsProperties struct {
241 // Compressor and Compression level passed to mkfs.erofs. e.g. (lz4hc,9)
242 // Please see external/erofs-utils/README for complete documentation.
243 Compressor *string
244
245 // Used as --compress-hints for mkfs.erofs
246 Compress_hints *string `android:"path"`
247
248 Sparse *bool
Jiyong Park71baa762021-01-18 21:11:03 +0900249}
250
mrziwang1a6291f2024-11-07 14:29:25 -0800251// Additional properties required to generate f2fs FS partitions.
252type F2fsProperties struct {
253 Sparse *bool
254}
255
Spandan Das173256b2024-10-31 19:59:30 +0000256type LinkerConfigProperties struct {
257
258 // Build a linker.config.pb file
259 Gen_linker_config *bool
260
261 // List of files (in .json format) that will be converted to a linker config file (in .pb format).
262 // The linker config file be installed in the filesystem at /etc/linker.config.pb
263 Linker_config_srcs []string `android:"path"`
264}
265
Jiyong Park65c49f52020-11-24 14:23:26 +0900266// android_filesystem packages a set of modules and their transitive dependencies into a filesystem
267// image. The filesystem images are expected to be mounted in the target device, which means the
268// modules in the filesystem image are built for the target device (i.e. Android, not Linux host).
269// The modules are placed in the filesystem image just like they are installed to the ordinary
270// partitions like system.img. For example, cc_library modules are placed under ./lib[64] directory.
Cole Faust92ccbe22024-10-03 14:38:37 -0700271func FilesystemFactory() android.Module {
Jiyong Park6f0f6882020-11-12 13:14:30 +0900272 module := &filesystem{}
Kiyoung Kim67118212024-11-07 13:23:44 +0900273 module.filesystemBuilder = module
Cole Faust2cfe6962024-09-17 11:31:14 -0700274 initFilesystemModule(module, module)
Jiyong Parkfa616132021-04-20 11:36:40 +0900275 return module
276}
277
Cole Faust2cfe6962024-09-17 11:31:14 -0700278func initFilesystemModule(module android.DefaultableModule, filesystemModule *filesystem) {
279 module.AddProperties(&filesystemModule.properties)
280 android.InitPackageModule(filesystemModule)
281 filesystemModule.PackagingBase.DepsCollectFirstTargetOnly = true
Jihoon Kang79196c52024-10-30 18:49:47 +0000282 filesystemModule.PackagingBase.AllowHighPriorityDeps = true
Jiyong Park6f0f6882020-11-12 13:14:30 +0900283 android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900284 android.InitDefaultableModule(module)
Jihoon Kang6c03c8e2024-11-18 21:30:22 +0000285
286 android.AddLoadHook(module, func(ctx android.LoadHookContext) {
287 filesystemModule.setDevNodesDescriptionProp()
288 })
Jiyong Park6f0f6882020-11-12 13:14:30 +0900289}
290
Jihoon Kang0d545b82024-10-11 00:21:57 +0000291type depTag struct {
Jiyong Park12a719c2021-01-07 15:31:24 +0900292 blueprint.BaseDependencyTag
Jooyung Han092ef812021-03-10 15:40:34 +0900293 android.PackagingItemAlwaysDepTag
Jihoon Kang0d545b82024-10-11 00:21:57 +0000294}
295
296var dependencyTag = depTag{}
297
298type depTagWithVisibilityEnforcementBypass struct {
299 depTag
300}
301
Spandan Das71be42d2024-11-20 18:34:16 +0000302type interPartitionDepTag struct {
303 blueprint.BaseDependencyTag
304}
305
306var interPartitionDependencyTag = interPartitionDepTag{}
307
Jihoon Kang6da80752024-12-23 18:53:32 +0000308var interPartitionInstallDependencyTag = interPartitionDepTag{}
309
Jihoon Kang0d545b82024-10-11 00:21:57 +0000310var _ android.ExcludeFromVisibilityEnforcementTag = (*depTagWithVisibilityEnforcementBypass)(nil)
311
312func (t depTagWithVisibilityEnforcementBypass) ExcludeFromVisibilityEnforcement() {}
313
314var dependencyTagWithVisibilityEnforcementBypass = depTagWithVisibilityEnforcementBypass{}
Jiyong Park65b62242020-11-25 12:44:59 +0900315
Jihoon Kang6c03c8e2024-11-18 21:30:22 +0000316// ramdiskDevNodesDescription is the name of the filegroup module that provides the file that
317// contains the description of dev nodes added to the CPIO archive for the ramdisk partition.
318const ramdiskDevNodesDescription = "ramdisk_node_list"
319
320func (f *filesystem) setDevNodesDescriptionProp() {
321 if proptools.String(f.properties.Partition_name) == "ramdisk" {
322 f.properties.Dev_nodes_description_file = proptools.StringPtr(":" + ramdiskDevNodesDescription)
323 }
324}
325
Jiyong Park6f0f6882020-11-12 13:14:30 +0900326func (f *filesystem) DepsMutator(ctx android.BottomUpMutatorContext) {
Jihoon Kang0d545b82024-10-11 00:21:57 +0000327 if proptools.Bool(f.properties.Is_auto_generated) {
328 f.AddDeps(ctx, dependencyTagWithVisibilityEnforcementBypass)
329 } else {
330 f.AddDeps(ctx, dependencyTag)
331 }
Spandan Das71be42d2024-11-20 18:34:16 +0000332 if f.properties.Android_filesystem_deps.System != nil {
333 ctx.AddDependency(ctx.Module(), interPartitionDependencyTag, proptools.String(f.properties.Android_filesystem_deps.System))
334 }
335 if f.properties.Android_filesystem_deps.System_ext != nil {
336 ctx.AddDependency(ctx.Module(), interPartitionDependencyTag, proptools.String(f.properties.Android_filesystem_deps.System_ext))
337 }
Cole Faust34592c02024-12-13 11:20:24 -0800338 for _, partition := range f.properties.Import_aconfig_flags_from {
339 ctx.AddDependency(ctx.Module(), importAconfigDependencyTag, partition)
340 }
Jihoon Kang6da80752024-12-23 18:53:32 +0000341 for _, partition := range f.properties.Include_files_of {
342 ctx.AddDependency(ctx.Module(), interPartitionInstallDependencyTag, partition)
343 }
Jiyong Park6f0f6882020-11-12 13:14:30 +0900344}
345
Jiyong Park11a65972021-02-01 21:09:38 +0900346type fsType int
347
348const (
349 ext4Type fsType = iota
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000350 erofsType
mrziwang1a6291f2024-11-07 14:29:25 -0800351 f2fsType
Jiyong Park11a65972021-02-01 21:09:38 +0900352 compressedCpioType
Jiyong Park837cdb22021-02-05 00:17:14 +0900353 cpioType // uncompressed
Jiyong Park11a65972021-02-01 21:09:38 +0900354 unknown
355)
356
Spandan Das7a46f6c2024-10-14 18:41:18 +0000357func (fs fsType) IsUnknown() bool {
358 return fs == unknown
359}
360
Cole Faust92ccbe22024-10-03 14:38:37 -0700361type FilesystemInfo struct {
Cole Faust44080412024-12-20 14:17:07 -0800362 // The built filesystem image
363 Output android.Path
Spandan Das1f0a5a12025-01-15 00:53:15 +0000364 // An additional hermetic filesystem image.
365 // e.g. this will contain inodes with pinned timestamps.
366 // This will be copied to target_files.zip
367 OutputHermetic android.Path
Cole Faust92ccbe22024-10-03 14:38:37 -0700368 // A text file containing the list of paths installed on the partition.
369 FileListFile android.Path
Cole Faust44080412024-12-20 14:17:07 -0800370 // The root staging directory used to build the output filesystem. If consuming this, make sure
371 // to add a dependency on the Output file, as you cannot add dependencies on directories
372 // in ninja.
373 RootDir android.Path
Cole Faust11fda332025-01-14 16:47:19 -0800374 // The rebased staging directory used to build the output filesystem. If consuming this, make
375 // sure to add a dependency on the Output file, as you cannot add dependencies on directories
376 // in ninja. In many cases this is the same as RootDir, only in the system partition is it
377 // different. There, it points to the "system" sub-directory of RootDir.
378 RebasedDir android.Path
Spandan Das33c9c472025-01-14 19:26:23 +0000379 // A text file with block data of the .img file
380 // This is an implicit output of `build_image`
381 MapFile android.Path
Cole Faust11fda332025-01-14 16:47:19 -0800382 // Name of the module that produced this FilesystemInfo origionally. (though it may be
383 // re-exported by super images or boot images)
384 ModuleName string
Cole Faust74ee4e02025-01-16 14:55:35 -0800385 // The property file generated by this module and passed to build_image.
386 // It's exported here so that system_other can reuse system's property file.
387 BuildImagePropFile android.Path
388 // Paths to all the tools referenced inside of the build image property file.
389 BuildImagePropFileDeps android.Paths
Cole Faustb8e280f2025-01-16 16:33:26 -0800390 // Packaging specs to be installed on the system_other image, for the initial boot's dexpreopt.
391 SpecsForSystemOther map[string]android.PackagingSpec
Cole Faust19fbb072025-01-30 18:19:29 -0800392
393 FullInstallPaths []FullInstallPathInfo
394}
395
396// FullInstallPathInfo contains information about the "full install" paths of all the files
397// inside this partition. The full install paths are the files installed in
398// out/target/product/<device>/<partition>. This is essentially legacy behavior, maintained for
399// tools like adb sync and adevice, but we should update them to query the build system for the
400// installed files no matter where they are.
401type FullInstallPathInfo struct {
402 // RequiresFullInstall tells us if the origional module did the install to FullInstallPath
403 // already. If it's false, the android_device module needs to emit the install rule.
404 RequiresFullInstall bool
405 // The "full install" paths for the files in this filesystem. This is the paths in the
406 // out/target/product/<device>/<partition> folder. They're not used by this filesystem,
407 // but can be depended on by the top-level android_device module to cause the staging
408 // directories to be built.
409 FullInstallPath android.InstallPath
410
411 // The file that's copied to FullInstallPath. May be nil if SymlinkTarget is set or IsDir is
412 // true.
413 SourcePath android.Path
414
415 // The target of the symlink, if this file is a symlink.
416 SymlinkTarget string
417
418 // If this file is a directory. Only used for empty directories, which are mostly mount points.
419 IsDir bool
Cole Faust92ccbe22024-10-03 14:38:37 -0700420}
421
422var FilesystemProvider = blueprint.NewProvider[FilesystemInfo]()
423
Yu Liufc8d5c12025-01-09 00:19:06 +0000424type FilesystemDefaultsInfo struct {
425 // Identifies which partition this is for //visibility:any_system_image (and others) visibility
426 // checks, and will be used in the future for API surface checks.
427 PartitionType string
428}
429
430var FilesystemDefaultsInfoProvider = blueprint.NewProvider[FilesystemDefaultsInfo]()
431
Spandan Das7a46f6c2024-10-14 18:41:18 +0000432func GetFsTypeFromString(ctx android.EarlyModuleContext, typeStr string) fsType {
Jiyong Park11a65972021-02-01 21:09:38 +0900433 switch typeStr {
434 case "ext4":
435 return ext4Type
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000436 case "erofs":
437 return erofsType
mrziwang1a6291f2024-11-07 14:29:25 -0800438 case "f2fs":
439 return f2fsType
Jiyong Park11a65972021-02-01 21:09:38 +0900440 case "compressed_cpio":
441 return compressedCpioType
Jiyong Park837cdb22021-02-05 00:17:14 +0900442 case "cpio":
443 return cpioType
Jiyong Park11a65972021-02-01 21:09:38 +0900444 default:
Jiyong Park11a65972021-02-01 21:09:38 +0900445 return unknown
446 }
447}
448
Spandan Das7a46f6c2024-10-14 18:41:18 +0000449func (f *filesystem) fsType(ctx android.ModuleContext) fsType {
450 typeStr := proptools.StringDefault(f.properties.Type, "ext4")
451 fsType := GetFsTypeFromString(ctx, typeStr)
452 if fsType == unknown {
453 ctx.PropertyErrorf("type", "%q not supported", typeStr)
454 }
455 return fsType
456}
457
Jiyong Park65c49f52020-11-24 14:23:26 +0900458func (f *filesystem) installFileName() string {
Spandan Dasc49b85e2025-01-10 00:51:25 +0000459 return proptools.StringDefault(f.properties.Stem, f.BaseModuleName()+".img")
Jiyong Park65c49f52020-11-24 14:23:26 +0900460}
461
Inseob Kim53391842024-03-29 17:44:07 +0900462func (f *filesystem) partitionName() string {
463 return proptools.StringDefault(f.properties.Partition_name, f.Name())
464}
465
Kiyoung Kim67118212024-11-07 13:23:44 +0900466func (f *filesystem) FilterPackagingSpec(ps android.PackagingSpec) bool {
Jiyong Park7e7d4af2024-05-01 12:36:10 +0000467 // Filesystem module respects the installation semantic. A PackagingSpec from a module with
468 // IsSkipInstall() is skipped.
Cole Faust76a6e952024-11-07 16:56:45 -0800469 if ps.SkipInstall() {
470 return false
Spandan Das6d056502024-10-21 15:40:32 +0000471 }
Cole Faust0d3fd562025-01-31 13:17:58 -0800472 // "apex" is a fake partition used to install files in out/target/product/<device>/apex/.
473 // Don't include these files in the partition. We should also look into removing the following
474 // TODO to check the PackagingSpec's partition against this filesystem's partition for all
475 // modules, not just autogenerated ones, which will fix this as well.
476 if ps.Partition() == "apex" {
477 return false
478 }
Cole Faust76a6e952024-11-07 16:56:45 -0800479 if proptools.Bool(f.properties.Is_auto_generated) { // TODO (spandandas): Remove this.
480 pt := f.PartitionType()
Cole Faustc88cff12024-11-12 13:24:05 -0800481 return ps.Partition() == pt || strings.HasPrefix(ps.Partition(), pt+"/")
Cole Faust76a6e952024-11-07 16:56:45 -0800482 }
483 return true
Jiyong Park7e7d4af2024-05-01 12:36:10 +0000484}
485
Inseob Kim3c0a0422024-11-05 17:21:37 +0900486func (f *filesystem) ModifyPackagingSpec(ps *android.PackagingSpec) {
Cole Faustc88cff12024-11-12 13:24:05 -0800487 // Sometimes, android.modulePartition() returns a path with >1 path components.
488 // This makes the partition field of packagingSpecs have multiple components, like
489 // "system/product". Right now, the filesystem module doesn't look at the partition field
490 // when deciding what path to install the file under, only the RelPathInPackage field, so
491 // we move the later path components from partition to relPathInPackage. This should probably
492 // be revisited in the future.
493 prefix := f.PartitionType() + "/"
494 if strings.HasPrefix(ps.Partition(), prefix) {
495 subPartition := strings.TrimPrefix(ps.Partition(), prefix)
496 ps.SetPartition(f.PartitionType())
497 ps.SetRelPathInPackage(filepath.Join(subPartition, ps.RelPathInPackage()))
498 }
Inseob Kim3c0a0422024-11-05 17:21:37 +0900499}
500
Jiyong Park6f0f6882020-11-12 13:14:30 +0900501var pctx = android.NewPackageContext("android/soong/filesystem")
502
503func (f *filesystem) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900504 validatePartitionType(ctx, f)
Kiyoung Kim23be5bb2024-11-27 00:50:30 +0000505 if f.filesystemBuilder.ShouldUseVintfFragmentModuleOnly() {
506 f.validateVintfFragments(ctx)
507 }
Jihoon Kang6da80752024-12-23 18:53:32 +0000508
509 if len(f.properties.Include_files_of) > 0 && !android.InList(f.fsType(ctx), []fsType{compressedCpioType, cpioType}) {
510 ctx.PropertyErrorf("include_files_of", "include_files_of is only supported for cpio and compressed cpio filesystem types.")
511 }
512
Cole Faust62cfaeb2025-01-15 18:06:40 -0800513 rootDir := android.PathForModuleOut(ctx, f.rootDirString()).OutputPath
514 rebasedDir := rootDir
515 if f.properties.Base_dir != nil {
516 rebasedDir = rootDir.Join(ctx, *f.properties.Base_dir)
517 }
518 builder := android.NewRuleBuilder(pctx, ctx)
519
520 // Wipe the root dir to get rid of leftover files from prior builds
521 builder.Command().Textf("rm -rf %s && mkdir -p %s", rootDir, rootDir)
522 specs := f.gatherFilteredPackagingSpecs(ctx)
Cole Faust62cfaeb2025-01-15 18:06:40 -0800523
Cole Faust19fbb072025-01-30 18:19:29 -0800524 var fullInstallPaths []FullInstallPathInfo
525 for _, spec := range specs {
526 fullInstallPaths = append(fullInstallPaths, FullInstallPathInfo{
527 FullInstallPath: spec.FullInstallPath(),
528 RequiresFullInstall: spec.RequiresFullInstall(),
529 SourcePath: spec.SrcPath(),
530 SymlinkTarget: spec.ToGob().SymlinkTarget,
531 })
532 }
533
534 f.entries = f.copyPackagingSpecs(ctx, builder, specs, rootDir, rebasedDir)
535 f.buildNonDepsFiles(ctx, builder, rootDir, rebasedDir, &fullInstallPaths)
536 f.buildFsverityMetadataFiles(ctx, builder, specs, rootDir, rebasedDir, &fullInstallPaths)
537 f.buildEventLogtagsFile(ctx, builder, rebasedDir, &fullInstallPaths)
538 f.buildAconfigFlagsFiles(ctx, builder, specs, rebasedDir, &fullInstallPaths)
539 f.filesystemBuilder.BuildLinkerConfigFile(ctx, builder, rebasedDir, &fullInstallPaths)
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000540 // Assemeble the staging dir and output a timestamp
541 builder.Command().Text("touch").Output(f.fileystemStagingDirTimestamp(ctx))
542 builder.Build("assemble_filesystem_staging_dir", fmt.Sprintf("Assemble filesystem staging dir %s", f.BaseModuleName()))
Cole Faust62cfaeb2025-01-15 18:06:40 -0800543
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000544 // Create a new rule builder for build_image
545 builder = android.NewRuleBuilder(pctx, ctx)
Spandan Das33c9c472025-01-14 19:26:23 +0000546 var mapFile android.Path
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000547 var outputHermetic android.WritablePath
Cole Faust74ee4e02025-01-16 14:55:35 -0800548 var buildImagePropFile android.Path
549 var buildImagePropFileDeps android.Paths
Jiyong Park11a65972021-02-01 21:09:38 +0900550 switch f.fsType(ctx) {
mrziwang1a6291f2024-11-07 14:29:25 -0800551 case ext4Type, erofsType, f2fsType:
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000552 buildImagePropFile, buildImagePropFileDeps = f.buildPropFile(ctx)
553 output := android.PathForModuleOut(ctx, f.installFileName())
554 f.buildImageUsingBuildImage(ctx, builder, buildImageParams{rootDir, buildImagePropFile, buildImagePropFileDeps, output})
555 f.output = output
556 // Create the hermetic img file using a separate rule builder so that it can be built independently
557 hermeticBuilder := android.NewRuleBuilder(pctx, ctx)
558 outputHermetic = android.PathForModuleOut(ctx, "for_target_files", f.installFileName())
559 propFileHermetic := f.propFileForHermeticImg(ctx, hermeticBuilder, buildImagePropFile)
560 f.buildImageUsingBuildImage(ctx, hermeticBuilder, buildImageParams{rootDir, propFileHermetic, buildImagePropFileDeps, outputHermetic})
Spandan Das33c9c472025-01-14 19:26:23 +0000561 mapFile = f.getMapFile(ctx)
Jiyong Park11a65972021-02-01 21:09:38 +0900562 case compressedCpioType:
Cole Faust62cfaeb2025-01-15 18:06:40 -0800563 f.output = f.buildCpioImage(ctx, builder, rootDir, true)
Jiyong Park837cdb22021-02-05 00:17:14 +0900564 case cpioType:
Cole Faust62cfaeb2025-01-15 18:06:40 -0800565 f.output = f.buildCpioImage(ctx, builder, rootDir, false)
Jiyong Park11a65972021-02-01 21:09:38 +0900566 default:
567 return
568 }
569
570 f.installDir = android.PathForModuleInstall(ctx, "etc")
571 ctx.InstallFile(f.installDir, f.installFileName(), f.output)
mrziwang555d1332024-06-07 11:15:33 -0700572 ctx.SetOutputFiles([]android.Path{f.output}, "")
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900573
Jihoon Kang6da80752024-12-23 18:53:32 +0000574 if f.partitionName() == "recovery" {
575 rootDir = rootDir.Join(ctx, "root")
576 }
577
Cole Faust4e9f5922024-11-13 16:09:23 -0800578 fileListFile := android.PathForModuleOut(ctx, "fileList")
579 android.WriteFileRule(ctx, fileListFile, f.installedFilesList())
Cole Faust92ccbe22024-10-03 14:38:37 -0700580
Spandan Das33c9c472025-01-14 19:26:23 +0000581 fsInfo := FilesystemInfo{
Cole Faust74ee4e02025-01-16 14:55:35 -0800582 Output: f.output,
583 OutputHermetic: outputHermetic,
584 FileListFile: fileListFile,
585 RootDir: rootDir,
586 RebasedDir: rebasedDir,
587 MapFile: mapFile,
588 ModuleName: ctx.ModuleName(),
589 BuildImagePropFile: buildImagePropFile,
590 BuildImagePropFileDeps: buildImagePropFileDeps,
Cole Faustb8e280f2025-01-16 16:33:26 -0800591 SpecsForSystemOther: f.systemOtherFiles(ctx),
Cole Faust19fbb072025-01-30 18:19:29 -0800592 FullInstallPaths: fullInstallPaths,
Spandan Das1f0a5a12025-01-15 00:53:15 +0000593 }
Spandan Das33c9c472025-01-14 19:26:23 +0000594
595 android.SetProvider(ctx, FilesystemProvider, fsInfo)
Spandan Das3ec6d062025-01-09 19:37:47 +0000596
Cole Faust4e9f5922024-11-13 16:09:23 -0800597 f.fileListFile = fileListFile
Cole Faust92ccbe22024-10-03 14:38:37 -0700598
599 if proptools.Bool(f.properties.Unchecked_module) {
600 ctx.UncheckedModule()
601 }
Jihoon Kang2f0d1932025-01-17 19:22:44 +0000602
603 f.setVbmetaPartitionProvider(ctx)
604}
605
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000606func (f *filesystem) fileystemStagingDirTimestamp(ctx android.ModuleContext) android.WritablePath {
607 return android.PathForModuleOut(ctx, "staging_dir.timestamp")
608}
609
Jihoon Kang2f0d1932025-01-17 19:22:44 +0000610func (f *filesystem) setVbmetaPartitionProvider(ctx android.ModuleContext) {
611 var extractedPublicKey android.ModuleOutPath
612 if f.properties.Avb_private_key != nil {
613 key := android.PathForModuleSrc(ctx, proptools.String(f.properties.Avb_private_key))
614 extractedPublicKey = android.PathForModuleOut(ctx, f.partitionName()+".avbpubkey")
615 ctx.Build(pctx, android.BuildParams{
616 Rule: extractPublicKeyRule,
617 Input: key,
618 Output: extractedPublicKey,
619 })
620 }
621
622 var ril int
623 if f.properties.Rollback_index_location != nil {
624 ril = proptools.Int(f.properties.Rollback_index_location)
625 }
626
627 android.SetProvider(ctx, vbmetaPartitionProvider, vbmetaPartitionInfo{
628 Name: f.partitionName(),
629 RollbackIndexLocation: ril,
630 PublicKey: extractedPublicKey,
631 Output: f.output,
632 })
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900633}
634
Spandan Das33c9c472025-01-14 19:26:23 +0000635func (f *filesystem) getMapFile(ctx android.ModuleContext) android.WritablePath {
636 // create the filepath by replacing the extension of the corresponding img file
637 return android.PathForModuleOut(ctx, f.installFileName()).ReplaceExtension(ctx, "map")
638}
639
Kiyoung Kim23be5bb2024-11-27 00:50:30 +0000640func (f *filesystem) validateVintfFragments(ctx android.ModuleContext) {
641 visitedModule := map[string]bool{}
642 packagingSpecs := f.gatherFilteredPackagingSpecs(ctx)
643
644 moduleInFileSystem := func(mod android.Module) bool {
645 for _, ps := range android.OtherModuleProviderOrDefault(
646 ctx, mod, android.InstallFilesProvider).PackagingSpecs {
647 if _, ok := packagingSpecs[ps.RelPathInPackage()]; ok {
648 return true
649 }
650 }
651 return false
652 }
653
654 ctx.WalkDeps(func(child, parent android.Module) bool {
655 if visitedModule[child.Name()] {
656 return false
657 }
658 if !moduleInFileSystem(child) {
659 visitedModule[child.Name()] = true
660 return true
661 }
662 if vintfFragments := child.VintfFragments(ctx); vintfFragments != nil {
663 ctx.PropertyErrorf(
664 "vintf_fragments",
665 "Module %s is referenced by soong-defined filesystem %s with property vintf_fragments(%s) in use."+
666 " Use vintf_fragment_modules property instead.",
667 child.Name(),
668 f.BaseModuleName(),
669 strings.Join(vintfFragments, ", "),
670 )
671 }
672 visitedModule[child.Name()] = true
673 return true
674 })
675}
676
Cole Faust4e9f5922024-11-13 16:09:23 -0800677func (f *filesystem) appendToEntry(ctx android.ModuleContext, installedFile android.Path) {
Spandan Das420e16a2024-12-11 18:10:52 +0000678 partitionBaseDir := android.PathForModuleOut(ctx, f.rootDirString(), proptools.String(f.properties.Base_dir)).String() + "/"
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900679
680 relPath, inTargetPartition := strings.CutPrefix(installedFile.String(), partitionBaseDir)
681 if inTargetPartition {
682 f.entries = append(f.entries, relPath)
683 }
684}
685
686func (f *filesystem) installedFilesList() string {
687 installedFilePaths := android.FirstUniqueStrings(f.entries)
688 slices.Sort(installedFilePaths)
689
690 return strings.Join(installedFilePaths, "\n")
Jiyong Park11a65972021-02-01 21:09:38 +0900691}
692
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900693func validatePartitionType(ctx android.ModuleContext, p partition) {
694 if !android.InList(p.PartitionType(), validPartitions) {
695 ctx.PropertyErrorf("partition_type", "partition_type must be one of %s, found: %s", validPartitions, p.PartitionType())
696 }
697
Yu Liufc8d5c12025-01-09 00:19:06 +0000698 ctx.VisitDirectDepsProxyWithTag(android.DefaultsDepTag, func(m android.ModuleProxy) {
699 if fdm, ok := android.OtherModuleProvider(ctx, m, FilesystemDefaultsInfoProvider); ok {
700 if p.PartitionType() != fdm.PartitionType {
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900701 ctx.PropertyErrorf("partition_type",
702 "%s doesn't match with the partition type %s of the filesystem default module %s",
Yu Liufc8d5c12025-01-09 00:19:06 +0000703 p.PartitionType(), fdm.PartitionType, m.Name())
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900704 }
705 }
706 })
707}
708
Cole Faust3b806d32024-03-11 15:15:03 -0700709// Copy extra files/dirs that are not from the `deps` property to `rootDir`, checking for conflicts with files
710// already in `rootDir`.
Cole Faust19fbb072025-01-30 18:19:29 -0800711func (f *filesystem) buildNonDepsFiles(
712 ctx android.ModuleContext,
713 builder *android.RuleBuilder,
714 rootDir android.OutputPath,
715 rebasedDir android.OutputPath,
716 fullInstallPaths *[]FullInstallPathInfo,
717) {
718 rebasedPrefix, err := filepath.Rel(rootDir.String(), rebasedDir.String())
719 if err != nil || strings.HasPrefix(rebasedPrefix, "../") {
720 panic("rebasedDir could not be made relative to rootDir")
721 }
722 if !strings.HasSuffix(rebasedPrefix, "/") {
723 rebasedPrefix += "/"
724 }
725 if rebasedPrefix == "./" {
726 rebasedPrefix = ""
727 }
728
Inseob Kim14199b02021-02-09 21:18:31 +0900729 // create dirs and symlinks
Cole Faustd9c6a5b2024-05-21 14:54:00 -0700730 for _, dir := range f.properties.Dirs.GetOrDefault(ctx, nil) {
Inseob Kim14199b02021-02-09 21:18:31 +0900731 // OutputPath.Join verifies dir
732 builder.Command().Text("mkdir -p").Text(rootDir.Join(ctx, dir).String())
Cole Faust19fbb072025-01-30 18:19:29 -0800733 // Only add the fullInstallPath logic for files in the rebased dir. The root dir
734 // is harder to install to.
735 if strings.HasPrefix(dir, rebasedPrefix) {
736 *fullInstallPaths = append(*fullInstallPaths, FullInstallPathInfo{
737 FullInstallPath: android.PathForModuleInPartitionInstall(ctx, f.PartitionType(), strings.TrimPrefix(dir, rebasedPrefix)),
738 IsDir: true,
739 })
740 }
Inseob Kim14199b02021-02-09 21:18:31 +0900741 }
742
743 for _, symlink := range f.properties.Symlinks {
744 name := strings.TrimSpace(proptools.String(symlink.Name))
745 target := strings.TrimSpace(proptools.String(symlink.Target))
746
747 if name == "" {
748 ctx.PropertyErrorf("symlinks", "Name can't be empty")
749 continue
750 }
751
752 if target == "" {
753 ctx.PropertyErrorf("symlinks", "Target can't be empty")
754 continue
755 }
756
757 // OutputPath.Join verifies name. don't need to verify target.
758 dst := rootDir.Join(ctx, name)
Cole Faust3b806d32024-03-11 15:15:03 -0700759 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 +0900760 builder.Command().Text("mkdir -p").Text(filepath.Dir(dst.String()))
761 builder.Command().Text("ln -sf").Text(proptools.ShellEscape(target)).Text(dst.String())
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900762 f.appendToEntry(ctx, dst)
Cole Faust19fbb072025-01-30 18:19:29 -0800763 // Only add the fullInstallPath logic for files in the rebased dir. The root dir
764 // is harder to install to.
765 if strings.HasPrefix(name, rebasedPrefix) {
766 *fullInstallPaths = append(*fullInstallPaths, FullInstallPathInfo{
767 FullInstallPath: android.PathForModuleInPartitionInstall(ctx, f.PartitionType(), strings.TrimPrefix(name, rebasedPrefix)),
768 SymlinkTarget: target,
769 })
770 }
Inseob Kim14199b02021-02-09 21:18:31 +0900771 }
Jihoon Kang89e8a692024-12-18 19:28:33 +0000772
773 // https://cs.android.com/android/platform/superproject/main/+/main:build/make/core/Makefile;l=2835;drc=b186569ef00ff2f2a1fab28aedc75ebc32bcd67b
774 if f.partitionName() == "recovery" {
775 builder.Command().Text("mkdir -p").Text(rootDir.Join(ctx, "root/linkerconfig").String())
776 builder.Command().Text("touch").Text(rootDir.Join(ctx, "root/linkerconfig/ld.config.txt").String())
777 }
Inseob Kim2ce1b5d2021-02-15 17:01:04 +0900778}
779
Inseob Kim33f95a92024-07-11 15:44:49 +0900780func (f *filesystem) copyPackagingSpecs(ctx android.ModuleContext, builder *android.RuleBuilder, specs map[string]android.PackagingSpec, rootDir, rebasedDir android.WritablePath) []string {
781 rootDirSpecs := make(map[string]android.PackagingSpec)
782 rebasedDirSpecs := make(map[string]android.PackagingSpec)
783
784 for rel, spec := range specs {
785 if spec.Partition() == "root" {
786 rootDirSpecs[rel] = spec
787 } else {
788 rebasedDirSpecs[rel] = spec
789 }
790 }
791
792 dirsToSpecs := make(map[android.WritablePath]map[string]android.PackagingSpec)
793 dirsToSpecs[rootDir] = rootDirSpecs
794 dirsToSpecs[rebasedDir] = rebasedDirSpecs
795
796 return f.CopySpecsToDirs(ctx, builder, dirsToSpecs)
797}
798
Spandan Das420e16a2024-12-11 18:10:52 +0000799func (f *filesystem) rootDirString() string {
800 return f.partitionName()
801}
802
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000803type buildImageParams struct {
804 // inputs
805 rootDir android.OutputPath
806 propFile android.Path
807 toolDeps android.Paths
808 // outputs
809 output android.WritablePath
810}
811
Cole Faust62cfaeb2025-01-15 18:06:40 -0800812func (f *filesystem) buildImageUsingBuildImage(
813 ctx android.ModuleContext,
814 builder *android.RuleBuilder,
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000815 params buildImageParams) {
Nikita Ioffe519015f2022-12-23 15:36:29 +0000816 // run host_init_verifier
817 // Ideally we should have a concept of pluggable linters that verify the generated image.
818 // While such concept is not implement this will do.
819 // TODO(b/263574231): substitute with pluggable linter.
820 builder.Command().
821 BuiltTool("host_init_verifier").
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000822 FlagWithArg("--out_system=", params.rootDir.String()+"/system")
Cole Fauste1676122024-12-03 17:32:25 -0800823
824 // Most of the time, if build_image were to call a host tool, it accepts the path to the
825 // host tool in a field in the prop file. However, it doesn't have that option for fec, which
826 // it expects to just be on the PATH. Add fec to the PATH.
827 fec := ctx.Config().HostToolPath(ctx, "fec")
828 pathToolDirs := []string{filepath.Dir(fec.String())}
829
Cole Fauste1676122024-12-03 17:32:25 -0800830 builder.Command().
831 Textf("PATH=%s:$PATH", strings.Join(pathToolDirs, ":")).
832 BuiltTool("build_image").
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000833 Text(params.rootDir.String()). // input directory
834 Input(params.propFile).
835 Implicits(params.toolDeps).
Cole Fauste1676122024-12-03 17:32:25 -0800836 Implicit(fec).
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000837 Implicit(f.fileystemStagingDirTimestamp(ctx)). // assemble the staging directory
838 Output(params.output).
839 Text(params.rootDir.String()) // directory where to find fs_config_files|dirs
Spandan Das1f0a5a12025-01-15 00:53:15 +0000840
Jihoon Kang983dd882025-01-13 23:14:11 +0000841 if f.properties.Partition_size != nil {
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000842 assertMaxImageSize(builder, params.output, *f.properties.Partition_size, false)
Jihoon Kang983dd882025-01-13 23:14:11 +0000843 }
844
Jiyong Park6f0f6882020-11-12 13:14:30 +0900845 // rootDir is not deleted. Might be useful for quick inspection.
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000846 builder.Build("build_"+params.output.String(), fmt.Sprintf("Creating filesystem %s", f.BaseModuleName()))
847}
Jiyong Park65c49f52020-11-24 14:23:26 +0900848
Spandan Das5ef1a9c2025-02-11 18:50:17 +0000849func (f *filesystem) propFileForHermeticImg(ctx android.ModuleContext, builder *android.RuleBuilder, inputPropFile android.Path) android.Path {
850 propFilePinnedTimestamp := android.PathForModuleOut(ctx, "for_target_files", "prop")
851 builder.Command().Textf("cat").Input(inputPropFile).Flag(">").Output(propFilePinnedTimestamp).
852 Textf(" && echo use_fixed_timestamp=true >> %s", propFilePinnedTimestamp).
853 Textf(" && echo block_list=%s >> %s", f.getMapFile(ctx).String(), propFilePinnedTimestamp) // mapfile will be an implicit output
854 builder.Command().Text("touch").Output(f.getMapFile(ctx))
855 return propFilePinnedTimestamp
Jiyong Park65c49f52020-11-24 14:23:26 +0900856}
857
Cole Faust4e9f5922024-11-13 16:09:23 -0800858func (f *filesystem) buildFileContexts(ctx android.ModuleContext) android.Path {
Inseob Kimcc8e5362021-02-03 14:05:24 +0900859 builder := android.NewRuleBuilder(pctx, ctx)
860 fcBin := android.PathForModuleOut(ctx, "file_contexts.bin")
861 builder.Command().BuiltTool("sefcontext_compile").
862 FlagWithOutput("-o ", fcBin).
863 Input(android.PathForModuleSrc(ctx, proptools.String(f.properties.File_contexts)))
864 builder.Build("build_filesystem_file_contexts", fmt.Sprintf("Creating filesystem file contexts for %s", f.BaseModuleName()))
Cole Faust4e9f5922024-11-13 16:09:23 -0800865 return fcBin
Inseob Kimcc8e5362021-02-03 14:05:24 +0900866}
867
Cole Faust4e9f5922024-11-13 16:09:23 -0800868func (f *filesystem) buildPropFile(ctx android.ModuleContext) (android.Path, android.Paths) {
Jiyong Park72678312021-01-18 17:29:49 +0900869 var deps android.Paths
Cole Fauste03ab892025-01-17 13:55:04 -0800870 var lines []string
Jiyong Park72678312021-01-18 17:29:49 +0900871 addStr := func(name string, value string) {
Cole Fauste03ab892025-01-17 13:55:04 -0800872 lines = append(lines, fmt.Sprintf("%s=%s", name, value))
Jiyong Park72678312021-01-18 17:29:49 +0900873 }
874 addPath := func(name string, path android.Path) {
Cole Faustcec230a2024-03-07 15:51:12 -0800875 addStr(name, path.String())
Jiyong Park72678312021-01-18 17:29:49 +0900876 deps = append(deps, path)
877 }
878
Jiyong Park11a65972021-02-01 21:09:38 +0900879 // Type string that build_image.py accepts.
880 fsTypeStr := func(t fsType) string {
881 switch t {
Spandan Das94668822024-10-09 20:51:33 +0000882 // TODO(372522486): add more types like f2fs, erofs, etc.
Jiyong Park11a65972021-02-01 21:09:38 +0900883 case ext4Type:
884 return "ext4"
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000885 case erofsType:
886 return "erofs"
mrziwang1a6291f2024-11-07 14:29:25 -0800887 case f2fsType:
888 return "f2fs"
Jiyong Park11a65972021-02-01 21:09:38 +0900889 }
890 panic(fmt.Errorf("unsupported fs type %v", t))
891 }
892
893 addStr("fs_type", fsTypeStr(f.fsType(ctx)))
Inseob Kim376d72f2023-11-01 15:40:25 +0900894 addStr("mount_point", proptools.StringDefault(f.properties.Mount_point, "/"))
Jiyong Park72678312021-01-18 17:29:49 +0900895 addStr("use_dynamic_partition_size", "true")
896 addPath("ext_mkuserimg", ctx.Config().HostToolPath(ctx, "mkuserimg_mke2fs"))
897 // b/177813163 deps of the host tools have to be added. Remove this.
898 for _, t := range []string{"mke2fs", "e2fsdroid", "tune2fs"} {
899 deps = append(deps, ctx.Config().HostToolPath(ctx, t))
900 }
901
Jiyong Park71baa762021-01-18 21:11:03 +0900902 if proptools.Bool(f.properties.Use_avb) {
903 addStr("avb_hashtree_enable", "true")
904 addPath("avb_avbtool", ctx.Config().HostToolPath(ctx, "avbtool"))
905 algorithm := proptools.StringDefault(f.properties.Avb_algorithm, "SHA256_RSA4096")
906 addStr("avb_algorithm", algorithm)
Cole Fauste1676122024-12-03 17:32:25 -0800907 if f.properties.Avb_private_key != nil {
908 key := android.PathForModuleSrc(ctx, *f.properties.Avb_private_key)
909 addPath("avb_key_path", key)
910 }
Inseob Kim53391842024-03-29 17:44:07 +0900911 addStr("partition_name", f.partitionName())
Cole Fauste1676122024-12-03 17:32:25 -0800912 avb_add_hashtree_footer_args := ""
913 if !proptools.BoolDefault(f.properties.Use_fec, true) {
914 avb_add_hashtree_footer_args += " --do_not_generate_fec"
915 }
Nikita Ioffe50fb49c2025-01-24 13:49:00 +0000916 hashAlgorithm := proptools.StringDefault(f.properties.Avb_hash_algorithm, "sha256")
917 avb_add_hashtree_footer_args += " --hash_algorithm " + hashAlgorithm
Nikita Ioffe2c8cdc62024-03-27 22:19:30 +0000918 if f.properties.Rollback_index != nil {
919 rollbackIndex := proptools.Int(f.properties.Rollback_index)
920 if rollbackIndex < 0 {
921 ctx.PropertyErrorf("rollback_index", "Rollback index must be non-negative")
922 }
923 avb_add_hashtree_footer_args += " --rollback_index " + strconv.Itoa(rollbackIndex)
924 }
Cole Fauste1676122024-12-03 17:32:25 -0800925 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 -0800926 // We're not going to add BuildFingerPrintFile as a dep. If it changed, it's likely because
927 // the build number changed, and we don't want to trigger rebuilds solely based on the build
928 // number.
Cole Fauste1676122024-12-03 17:32:25 -0800929 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 +0000930 if f.properties.Security_patch != nil && proptools.String(f.properties.Security_patch) != "" {
931 avb_add_hashtree_footer_args += fmt.Sprintf(" --prop com.android.build.%s.security_patch:%s", f.partitionName(), proptools.String(f.properties.Security_patch))
932 }
Shikha Panware6f30632022-12-21 12:54:45 +0000933 addStr("avb_add_hashtree_footer_args", avb_add_hashtree_footer_args)
Jiyong Park71baa762021-01-18 21:11:03 +0900934 }
935
Cole Faust0d467052024-12-04 17:19:19 -0800936 if f.properties.File_contexts != nil && f.properties.Precompiled_file_contexts != nil {
937 ctx.ModuleErrorf("file_contexts and precompiled_file_contexts cannot both be set")
938 } else if f.properties.File_contexts != nil {
Inseob Kimcc8e5362021-02-03 14:05:24 +0900939 addPath("selinux_fc", f.buildFileContexts(ctx))
Cole Faust0d467052024-12-04 17:19:19 -0800940 } else if f.properties.Precompiled_file_contexts != nil {
941 src := android.PathForModuleSrc(ctx, *f.properties.Precompiled_file_contexts)
942 if src != nil {
943 addPath("selinux_fc", src)
944 }
Inseob Kimcc8e5362021-02-03 14:05:24 +0900945 }
Jooyung Han65f402b2022-04-21 14:24:04 +0900946 if timestamp := proptools.String(f.properties.Fake_timestamp); timestamp != "" {
947 addStr("timestamp", timestamp)
Spandan Dasa0ddc512025-01-06 20:23:55 +0000948 } else if ctx.Config().Getenv("USE_FIXED_TIMESTAMP_IMG_FILES") == "true" {
949 addStr("use_fixed_timestamp", "true")
Jooyung Han65f402b2022-04-21 14:24:04 +0900950 }
Spandan Dasa0ddc512025-01-06 20:23:55 +0000951
Jooyung Han65f402b2022-04-21 14:24:04 +0900952 if uuid := proptools.String(f.properties.Uuid); uuid != "" {
953 addStr("uuid", uuid)
954 addStr("hash_seed", uuid)
955 }
mrziwang1a6291f2024-11-07 14:29:25 -0800956
Jihoon Kang40551e62025-01-14 21:55:08 +0000957 // Disable sparse only when partition size is not defined. disable_sparse has the same
958 // effect as <partition name>_disable_sparse.
959 if f.properties.Partition_size == nil {
960 addStr("disable_sparse", "true")
961 }
Cole Faust43a52c72024-11-26 12:46:08 -0800962
mrziwang1a6291f2024-11-07 14:29:25 -0800963 fst := f.fsType(ctx)
964 switch fst {
965 case erofsType:
966 // Add erofs properties
Cole Faust3e730972024-12-03 13:12:08 -0800967 addStr("erofs_default_compressor", proptools.StringDefault(f.properties.Erofs.Compressor, "lz4hc,9"))
968 if f.properties.Erofs.Compress_hints != nil {
969 src := android.PathForModuleSrc(ctx, *f.properties.Erofs.Compress_hints)
970 addPath("erofs_default_compress_hints", src)
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000971 }
972 if proptools.BoolDefault(f.properties.Erofs.Sparse, true) {
973 // https://source.corp.google.com/h/googleplex-android/platform/build/+/88b1c67239ca545b11580237242774b411f2fed9:core/Makefile;l=2292;bpv=1;bpt=0;drc=ea8f34bc1d6e63656b4ec32f2391e9d54b3ebb6b
974 addStr("erofs_sparse_flag", "-s")
975 }
mrziwang1a6291f2024-11-07 14:29:25 -0800976 case f2fsType:
977 if proptools.BoolDefault(f.properties.F2fs.Sparse, true) {
978 // https://source.corp.google.com/h/googleplex-android/platform/build/+/88b1c67239ca545b11580237242774b411f2fed9:core/Makefile;l=2294;drc=ea8f34bc1d6e63656b4ec32f2391e9d54b3ebb6b;bpv=1;bpt=0
979 addStr("f2fs_sparse_flag", "-S")
980 }
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000981 }
mrziwang1a6291f2024-11-07 14:29:25 -0800982 f.checkFsTypePropertyError(ctx, fst, fsTypeStr(fst))
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000983
Jihoon Kang983dd882025-01-13 23:14:11 +0000984 if f.properties.Partition_size != nil {
985 addStr("partition_size", strconv.FormatInt(*f.properties.Partition_size, 10))
986 }
987
Jihoon Kang6d08d922025-01-14 18:31:57 +0000988 if proptools.BoolDefault(f.properties.Support_casefolding, false) {
989 addStr("needs_casefold", "1")
990 }
991
992 if proptools.BoolDefault(f.properties.Support_project_quota, false) {
993 addStr("needs_projid", "1")
994 }
995
996 if proptools.BoolDefault(f.properties.Enable_compression, false) {
997 addStr("needs_compress", "1")
998 }
999
Cole Fauste03ab892025-01-17 13:55:04 -08001000 sort.Strings(lines)
1001
Cole Fauste1676122024-12-03 17:32:25 -08001002 propFilePreProcessing := android.PathForModuleOut(ctx, "prop_pre_processing")
Cole Fauste03ab892025-01-17 13:55:04 -08001003 android.WriteFileRule(ctx, propFilePreProcessing, strings.Join(lines, "\n"))
Cole Faust4e9f5922024-11-13 16:09:23 -08001004 propFile := android.PathForModuleOut(ctx, "prop")
Cole Fauste1676122024-12-03 17:32:25 -08001005 ctx.Build(pctx, android.BuildParams{
Cole Faustefeb5c42024-12-16 10:47:26 -08001006 Rule: textFileProcessorRule,
1007 Input: propFilePreProcessing,
1008 Output: propFile,
Cole Fauste1676122024-12-03 17:32:25 -08001009 })
Jiyong Park72678312021-01-18 17:29:49 +09001010 return propFile, deps
1011}
1012
mrziwang1a6291f2024-11-07 14:29:25 -08001013// This method checks if there is any property set for the fstype(s) other than
1014// the current fstype.
1015func (f *filesystem) checkFsTypePropertyError(ctx android.ModuleContext, t fsType, fs string) {
1016 raiseError := func(otherFsType, currentFsType string) {
1017 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)
1018 ctx.PropertyErrorf(otherFsType, errMsg)
1019 }
1020
1021 if t != erofsType {
1022 if f.properties.Erofs.Compressor != nil || f.properties.Erofs.Compress_hints != nil || f.properties.Erofs.Sparse != nil {
1023 raiseError("erofs", fs)
1024 }
1025 }
1026 if t != f2fsType {
1027 if f.properties.F2fs.Sparse != nil {
1028 raiseError("f2fs", fs)
1029 }
1030 }
1031}
1032
Jihoon Kang6da80752024-12-23 18:53:32 +00001033func includeFilesRootDir(ctx android.ModuleContext) (rootDirs android.Paths, partitions android.Paths) {
1034 ctx.VisitDirectDepsWithTag(interPartitionInstallDependencyTag, func(m android.Module) {
1035 if fsProvider, ok := android.OtherModuleProvider(ctx, m, FilesystemProvider); ok {
1036 rootDirs = append(rootDirs, fsProvider.RootDir)
1037 partitions = append(partitions, fsProvider.Output)
1038 } else {
1039 ctx.PropertyErrorf("include_files_of", "only filesystem modules can be listed in "+
1040 "include_files_of but %s is not a filesystem module", m.Name())
1041 }
1042 })
1043 return rootDirs, partitions
1044}
1045
Cole Faust62cfaeb2025-01-15 18:06:40 -08001046func (f *filesystem) buildCpioImage(
1047 ctx android.ModuleContext,
1048 builder *android.RuleBuilder,
1049 rootDir android.OutputPath,
1050 compressed bool,
1051) android.Path {
Jiyong Park11a65972021-02-01 21:09:38 +09001052 if proptools.Bool(f.properties.Use_avb) {
1053 ctx.PropertyErrorf("use_avb", "signing compresed cpio image using avbtool is not supported."+
1054 "Consider adding this to bootimg module and signing the entire boot image.")
1055 }
1056
Inseob Kimcc8e5362021-02-03 14:05:24 +09001057 if proptools.String(f.properties.File_contexts) != "" {
1058 ctx.PropertyErrorf("file_contexts", "file_contexts is not supported for compressed cpio image.")
1059 }
1060
Jihoon Kang6da80752024-12-23 18:53:32 +00001061 rootDirs, partitions := includeFilesRootDir(ctx)
1062
Cole Faust4e9f5922024-11-13 16:09:23 -08001063 output := android.PathForModuleOut(ctx, f.installFileName())
Jiyong Park837cdb22021-02-05 00:17:14 +09001064 cmd := builder.Command().
Jiyong Park11a65972021-02-01 21:09:38 +09001065 BuiltTool("mkbootfs").
Spandan Das5ef1a9c2025-02-11 18:50:17 +00001066 Implicit(f.fileystemStagingDirTimestamp(ctx)).
Jiyong Park837cdb22021-02-05 00:17:14 +09001067 Text(rootDir.String()) // input directory
Jihoon Kang6da80752024-12-23 18:53:32 +00001068
1069 for i := range len(rootDirs) {
1070 cmd.Text(rootDirs[i].String())
1071 }
1072 cmd.Implicits(partitions)
1073
Jihoon Kang6c03c8e2024-11-18 21:30:22 +00001074 if nodeList := f.properties.Dev_nodes_description_file; nodeList != nil {
1075 cmd.FlagWithInput("-n ", android.PathForModuleSrc(ctx, proptools.String(nodeList)))
1076 }
Jiyong Park837cdb22021-02-05 00:17:14 +09001077 if compressed {
1078 cmd.Text("|").
1079 BuiltTool("lz4").
1080 Flag("--favor-decSpeed"). // for faster boot
1081 Flag("-12"). // maximum compression level
1082 Flag("-l"). // legacy format for kernel
1083 Text(">").Output(output)
1084 } else {
1085 cmd.Text(">").Output(output)
1086 }
Jiyong Park11a65972021-02-01 21:09:38 +09001087
1088 // rootDir is not deleted. Might be useful for quick inspection.
Jiyong Park837cdb22021-02-05 00:17:14 +09001089 builder.Build("build_cpio_image", fmt.Sprintf("Creating filesystem %s", f.BaseModuleName()))
Jiyong Park11a65972021-02-01 21:09:38 +09001090
Cole Faust62cfaeb2025-01-15 18:06:40 -08001091 return output
Jiyong Park11a65972021-02-01 21:09:38 +09001092}
1093
Cole Faust4a2a7c92024-03-12 12:44:40 -07001094var validPartitions = []string{
1095 "system",
1096 "userdata",
1097 "cache",
1098 "system_other",
1099 "vendor",
1100 "product",
1101 "system_ext",
1102 "odm",
1103 "vendor_dlkm",
1104 "odm_dlkm",
1105 "system_dlkm",
Cole Faust76a6e952024-11-07 16:56:45 -08001106 "ramdisk",
Cole Faust24938e22024-11-18 14:01:58 -08001107 "vendor_ramdisk",
Jihoon Kang3216c982024-12-02 19:42:20 +00001108 "recovery",
Cole Faust4a2a7c92024-03-12 12:44:40 -07001109}
1110
Cole Faust19fbb072025-01-30 18:19:29 -08001111func (f *filesystem) buildEventLogtagsFile(
1112 ctx android.ModuleContext,
1113 builder *android.RuleBuilder,
1114 rebasedDir android.OutputPath,
1115 fullInstallPaths *[]FullInstallPathInfo,
1116) {
Inseob Kimb7b84572024-04-30 10:51:47 +09001117 if !proptools.Bool(f.properties.Build_logtags) {
1118 return
1119 }
1120
Inseob Kimb7b84572024-04-30 10:51:47 +09001121 etcPath := rebasedDir.Join(ctx, "etc")
1122 eventLogtagsPath := etcPath.Join(ctx, "event-log-tags")
1123 builder.Command().Text("mkdir").Flag("-p").Text(etcPath.String())
Cole Fauste4506af2024-12-11 14:14:50 -08001124 builder.Command().Text("cp").Input(android.MergedLogtagsPath(ctx)).Text(eventLogtagsPath.String())
Kiyoung Kim99a954d2024-06-21 14:22:20 +09001125
Cole Faust19fbb072025-01-30 18:19:29 -08001126 *fullInstallPaths = append(*fullInstallPaths, FullInstallPathInfo{
1127 FullInstallPath: android.PathForModuleInPartitionInstall(ctx, f.PartitionType(), "etc", "event-log-tags"),
1128 SourcePath: android.MergedLogtagsPath(ctx),
1129 })
1130
Kiyoung Kim99a954d2024-06-21 14:22:20 +09001131 f.appendToEntry(ctx, eventLogtagsPath)
Inseob Kimb7b84572024-04-30 10:51:47 +09001132}
1133
Cole Faust19fbb072025-01-30 18:19:29 -08001134func (f *filesystem) BuildLinkerConfigFile(
1135 ctx android.ModuleContext,
1136 builder *android.RuleBuilder,
1137 rebasedDir android.OutputPath,
1138 fullInstallPaths *[]FullInstallPathInfo,
1139) {
Spandan Das2047a4c2024-11-11 21:24:58 +00001140 if !proptools.Bool(f.properties.Linker_config.Gen_linker_config) {
Spandan Das92631882024-10-28 22:49:38 +00001141 return
1142 }
1143
Spandan Das918191e2024-10-31 18:27:23 +00001144 provideModules, _ := f.getLibsForLinkerConfig(ctx)
Cole Faustfee27012024-12-13 14:10:31 -08001145 intermediateOutput := android.PathForModuleOut(ctx, "linker.config.pb")
1146 linkerconfig.BuildLinkerConfig(ctx, android.PathsForModuleSrc(ctx, f.properties.Linker_config.Linker_config_srcs), provideModules, nil, intermediateOutput)
Spandan Das92631882024-10-28 22:49:38 +00001147 output := rebasedDir.Join(ctx, "etc", "linker.config.pb")
Cole Faustfee27012024-12-13 14:10:31 -08001148 builder.Command().Text("cp").Input(intermediateOutput).Output(output)
Spandan Das92631882024-10-28 22:49:38 +00001149
Cole Faust19fbb072025-01-30 18:19:29 -08001150 *fullInstallPaths = append(*fullInstallPaths, FullInstallPathInfo{
1151 FullInstallPath: android.PathForModuleInPartitionInstall(ctx, f.PartitionType(), "etc", "linker.config.pb"),
1152 SourcePath: intermediateOutput,
1153 })
1154
Spandan Das92631882024-10-28 22:49:38 +00001155 f.appendToEntry(ctx, output)
1156}
1157
Kiyoung Kim23be5bb2024-11-27 00:50:30 +00001158func (f *filesystem) ShouldUseVintfFragmentModuleOnly() bool {
1159 return false
1160}
1161
Jiyong Parkf46b1af2024-04-05 18:13:33 +09001162type partition interface {
1163 PartitionType() string
1164}
1165
Cole Faust9a24d902024-03-18 15:38:12 -07001166func (f *filesystem) PartitionType() string {
1167 return proptools.StringDefault(f.properties.Partition_type, "system")
1168}
1169
Jiyong Parkf46b1af2024-04-05 18:13:33 +09001170var _ partition = (*filesystem)(nil)
1171
Jiyong Park65c49f52020-11-24 14:23:26 +09001172var _ android.AndroidMkEntriesProvider = (*filesystem)(nil)
1173
1174// Implements android.AndroidMkEntriesProvider
1175func (f *filesystem) AndroidMkEntries() []android.AndroidMkEntries {
1176 return []android.AndroidMkEntries{android.AndroidMkEntries{
1177 Class: "ETC",
1178 OutputFile: android.OptionalPathForPath(f.output),
1179 ExtraEntries: []android.AndroidMkExtraEntriesFunc{
Colin Crossaa255532020-07-03 13:18:24 -07001180 func(ctx android.AndroidMkExtraEntriesContext, entries *android.AndroidMkEntries) {
Colin Crossc68db4b2021-11-11 18:59:15 -08001181 entries.SetString("LOCAL_MODULE_PATH", f.installDir.String())
Jiyong Park65c49f52020-11-24 14:23:26 +09001182 entries.SetString("LOCAL_INSTALLED_MODULE_STEM", f.installFileName())
Kiyoung Kim99a954d2024-06-21 14:22:20 +09001183 entries.SetString("LOCAL_FILESYSTEM_FILELIST", f.fileListFile.String())
Jiyong Park65c49f52020-11-24 14:23:26 +09001184 },
1185 },
1186 }}
Jiyong Park6f0f6882020-11-12 13:14:30 +09001187}
Jiyong Park12a719c2021-01-07 15:31:24 +09001188
1189// Filesystem is the public interface for the filesystem struct. Currently, it's only for the apex
1190// package to have access to the output file.
1191type Filesystem interface {
1192 android.Module
1193 OutputPath() android.Path
Jiyong Park972e06c2021-03-15 23:32:49 +09001194
1195 // Returns the output file that is signed by avbtool. If this module is not signed, returns
1196 // nil.
1197 SignedOutputPath() android.Path
Jiyong Park12a719c2021-01-07 15:31:24 +09001198}
1199
1200var _ Filesystem = (*filesystem)(nil)
1201
1202func (f *filesystem) OutputPath() android.Path {
1203 return f.output
1204}
Jiyong Park972e06c2021-03-15 23:32:49 +09001205
1206func (f *filesystem) SignedOutputPath() android.Path {
1207 if proptools.Bool(f.properties.Use_avb) {
1208 return f.OutputPath()
1209 }
1210 return nil
1211}
Jooyung Han0fbbc2b2022-03-25 12:35:46 +09001212
1213// Filter the result of GatherPackagingSpecs to discard items targeting outside "system" partition.
1214// Note that "apex" module installs its contents to "apex"(fake partition) as well
1215// for symbol lookup by imitating "activated" paths.
1216func (f *filesystem) gatherFilteredPackagingSpecs(ctx android.ModuleContext) map[string]android.PackagingSpec {
Cole Faustb8e280f2025-01-16 16:33:26 -08001217 return f.PackagingBase.GatherPackagingSpecsWithFilterAndModifier(ctx, f.filesystemBuilder.FilterPackagingSpec, f.filesystemBuilder.ModifyPackagingSpec)
1218}
1219
1220// Dexpreopt files are installed to system_other. Collect the packaingSpecs for the dexpreopt files
1221// from this partition to export to the system_other partition later.
1222func (f *filesystem) systemOtherFiles(ctx android.ModuleContext) map[string]android.PackagingSpec {
1223 filter := func(spec android.PackagingSpec) bool {
1224 // For some reason system_other packaging specs don't set the partition field.
1225 return strings.HasPrefix(spec.RelPathInPackage(), "system_other/")
1226 }
1227 modifier := func(spec *android.PackagingSpec) {
1228 spec.SetRelPathInPackage(strings.TrimPrefix(spec.RelPathInPackage(), "system_other/"))
1229 spec.SetPartition("system_other")
1230 }
1231 return f.PackagingBase.GatherPackagingSpecsWithFilterAndModifier(ctx, filter, modifier)
Jooyung Han0fbbc2b2022-03-25 12:35:46 +09001232}
Jooyung Han65f402b2022-04-21 14:24:04 +09001233
1234func sha1sum(values []string) string {
1235 h := sha256.New()
1236 for _, value := range values {
1237 io.WriteString(h, value)
1238 }
1239 return fmt.Sprintf("%x", h.Sum(nil))
1240}
Jooyung Hane6067592023-03-16 13:11:17 +09001241
1242// Base cc.UseCoverage
1243
1244var _ cc.UseCoverage = (*filesystem)(nil)
1245
Colin Crosse1a85552024-06-14 12:17:37 -07001246func (*filesystem) IsNativeCoverageNeeded(ctx cc.IsNativeCoverageNeededContext) bool {
Jooyung Hane6067592023-03-16 13:11:17 +09001247 return ctx.Device() && ctx.DeviceConfig().NativeCoverageEnabled()
1248}
Jiyong Parkf46b1af2024-04-05 18:13:33 +09001249
1250// android_filesystem_defaults
1251
1252type filesystemDefaults struct {
1253 android.ModuleBase
1254 android.DefaultsModuleBase
1255
Inseob Kim3c0a0422024-11-05 17:21:37 +09001256 properties FilesystemProperties
Jiyong Parkf46b1af2024-04-05 18:13:33 +09001257}
1258
1259// android_filesystem_defaults is a default module for android_filesystem and android_system_image
1260func filesystemDefaultsFactory() android.Module {
1261 module := &filesystemDefaults{}
1262 module.AddProperties(&module.properties)
1263 module.AddProperties(&android.PackagingProperties{})
1264 android.InitDefaultsModule(module)
1265 return module
1266}
1267
1268func (f *filesystemDefaults) PartitionType() string {
1269 return proptools.StringDefault(f.properties.Partition_type, "system")
1270}
1271
1272var _ partition = (*filesystemDefaults)(nil)
1273
1274func (f *filesystemDefaults) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1275 validatePartitionType(ctx, f)
Yu Liufc8d5c12025-01-09 00:19:06 +00001276 android.SetProvider(ctx, FilesystemDefaultsInfoProvider, FilesystemDefaultsInfo{
1277 PartitionType: f.PartitionType(),
1278 })
Jiyong Parkf46b1af2024-04-05 18:13:33 +09001279}
Spandan Das918191e2024-10-31 18:27:23 +00001280
1281// getLibsForLinkerConfig returns
1282// 1. A list of libraries installed in this filesystem
1283// 2. A list of dep libraries _not_ installed in this filesystem
1284//
1285// `linkerconfig.BuildLinkerConfig` will convert these two to a linker.config.pb for the filesystem
1286// (1) will be added to --provideLibs if they are C libraries with a stable interface (has stubs)
1287// (2) will be added to --requireLibs if they are C libraries with a stable interface (has stubs)
Yu Liu68a70b72025-01-08 22:54:44 +00001288func (f *filesystem) getLibsForLinkerConfig(ctx android.ModuleContext) ([]android.ModuleProxy, []android.ModuleProxy) {
Spandan Das918191e2024-10-31 18:27:23 +00001289 // we need "Module"s for packaging items
Yu Liu68a70b72025-01-08 22:54:44 +00001290 modulesInPackageByModule := make(map[android.ModuleProxy]bool)
Spandan Das918191e2024-10-31 18:27:23 +00001291 modulesInPackageByName := make(map[string]bool)
1292
1293 deps := f.gatherFilteredPackagingSpecs(ctx)
Yu Liu68a70b72025-01-08 22:54:44 +00001294 ctx.WalkDepsProxy(func(child, parent android.ModuleProxy) bool {
1295 if !android.OtherModuleProviderOrDefault(ctx, child, android.CommonModuleInfoKey).Enabled {
Yu Liu9c6b6762025-01-08 22:04:35 +00001296 return false
1297 }
Spandan Das918191e2024-10-31 18:27:23 +00001298 for _, ps := range android.OtherModuleProviderOrDefault(
1299 ctx, child, android.InstallFilesProvider).PackagingSpecs {
Spandan Dasecf667f2024-12-05 00:58:56 +00001300 if _, ok := deps[ps.RelPathInPackage()]; ok && ps.Partition() == f.PartitionType() {
Spandan Das918191e2024-10-31 18:27:23 +00001301 modulesInPackageByModule[child] = true
1302 modulesInPackageByName[child.Name()] = true
1303 return true
1304 }
1305 }
1306 return true
1307 })
1308
Yu Liu68a70b72025-01-08 22:54:44 +00001309 provideModules := make([]android.ModuleProxy, 0, len(modulesInPackageByModule))
Spandan Das918191e2024-10-31 18:27:23 +00001310 for mod := range modulesInPackageByModule {
1311 provideModules = append(provideModules, mod)
1312 }
1313
Yu Liu68a70b72025-01-08 22:54:44 +00001314 var requireModules []android.ModuleProxy
1315 ctx.WalkDepsProxy(func(child, parent android.ModuleProxy) bool {
1316 if !android.OtherModuleProviderOrDefault(ctx, child, android.CommonModuleInfoKey).Enabled {
Yu Liu9c6b6762025-01-08 22:04:35 +00001317 return false
1318 }
Spandan Das918191e2024-10-31 18:27:23 +00001319 _, parentInPackage := modulesInPackageByModule[parent]
1320 _, childInPackageName := modulesInPackageByName[child.Name()]
1321
1322 // When parent is in the package, and child (or its variant) is not, this can be from an interface.
1323 if parentInPackage && !childInPackageName {
1324 requireModules = append(requireModules, child)
1325 }
1326 return true
1327 })
1328
1329 return provideModules, requireModules
1330}
Cole Faust26bdac52024-11-19 13:37:53 -08001331
1332// Checks that the given file doesn't exceed the given size, and will also print a warning
1333// if it's nearing the maximum size. Equivalent to assert-max-image-size in make:
1334// https://cs.android.com/android/platform/superproject/main/+/main:build/make/core/definitions.mk;l=3455;drc=993c4de29a02a6accd60ceaaee153307e1a18d10
1335func assertMaxImageSize(builder *android.RuleBuilder, image android.Path, maxSize int64, addAvbLater bool) {
1336 if addAvbLater {
1337 // The value 69632 is derived from MAX_VBMETA_SIZE + MAX_FOOTER_SIZE in avbtool.
1338 // Logic copied from make:
1339 // https://cs.android.com/android/platform/superproject/main/+/main:build/make/core/Makefile;l=228;drc=a6a0007ef24e16c0b79f439beac4a118416717e6
1340 maxSize -= 69632
1341 }
1342 cmd := builder.Command()
1343 cmd.Textf(`file="%s"; maxsize="%d";`+
1344 `total=$(stat -c "%%s" "$file" | tr -d '\n');`+
1345 `if [ "$total" -gt "$maxsize" ]; then `+
1346 ` echo "error: $file too large ($total > $maxsize)";`+
1347 ` false;`+
1348 `elif [ "$total" -gt $((maxsize - 32768)) ]; then `+
1349 ` echo "WARNING: $file approaching size limit ($total now; limit $maxsize)";`+
1350 `fi`,
1351 image, maxSize)
1352 cmd.Implicit(image)
1353}
Spandan Das71be42d2024-11-20 18:34:16 +00001354
1355// addAutogeneratedRroDeps walks the transitive closure of vendor and product partitions.
1356// It visits apps installed in system and system_ext partitions, and adds the autogenerated
1357// RRO modules to its own deps.
1358func addAutogeneratedRroDeps(ctx android.BottomUpMutatorContext) {
1359 f, ok := ctx.Module().(*filesystem)
1360 if !ok {
1361 return
1362 }
1363 thisPartition := f.PartitionType()
1364 if thisPartition != "vendor" && thisPartition != "product" {
Cole Faust34592c02024-12-13 11:20:24 -08001365 if f.properties.Android_filesystem_deps.System != nil {
1366 ctx.PropertyErrorf("android_filesystem_deps.system", "only vendor or product partitions can use android_filesystem_deps")
1367 }
1368 if f.properties.Android_filesystem_deps.System_ext != nil {
1369 ctx.PropertyErrorf("android_filesystem_deps.system_ext", "only vendor or product partitions can use android_filesystem_deps")
1370 }
Spandan Das71be42d2024-11-20 18:34:16 +00001371 return
1372 }
1373 ctx.WalkDeps(func(child, parent android.Module) bool {
1374 depTag := ctx.OtherModuleDependencyTag(child)
1375 if parent.Name() == f.Name() && depTag != interPartitionDependencyTag {
1376 return false // This is a module listed in deps of vendor/product filesystem
1377 }
1378 if vendorOverlay := java.AutogeneratedRroModuleName(ctx, child.Name(), "vendor"); ctx.OtherModuleExists(vendorOverlay) && thisPartition == "vendor" {
1379 ctx.AddFarVariationDependencies(nil, dependencyTagWithVisibilityEnforcementBypass, vendorOverlay)
1380 }
1381 if productOverlay := java.AutogeneratedRroModuleName(ctx, child.Name(), "product"); ctx.OtherModuleExists(productOverlay) && thisPartition == "product" {
1382 ctx.AddFarVariationDependencies(nil, dependencyTagWithVisibilityEnforcementBypass, productOverlay)
1383 }
1384 return true
1385 })
1386}
Spandan Das6ec1fcf2025-02-11 22:51:51 +00001387
1388func (f *filesystem) MakeVars(ctx android.MakeVarsModuleContext) {
1389 if f.Name() == ctx.Config().SoongDefinedSystemImage() {
1390 ctx.StrictRaw("SOONG_DEFINED_SYSTEM_IMAGE_PATH", f.output.String())
1391 }
1392}