blob: 57b361b27f9b157f3b0cb8ed1eb3a90a4972377d [file] [log] [blame]
Jiyong Park6f0f6882020-11-12 13:14:30 +09001// Copyright (C) 2020 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package filesystem
16
17import (
Jooyung Han65f402b2022-04-21 14:24:04 +090018 "crypto/sha256"
Jiyong Park6f0f6882020-11-12 13:14:30 +090019 "fmt"
Jooyung Han65f402b2022-04-21 14:24:04 +090020 "io"
Inseob Kim14199b02021-02-09 21:18:31 +090021 "path/filepath"
Cole Faust4a2a7c92024-03-12 12:44:40 -070022 "slices"
Nikita Ioffe2c8cdc62024-03-27 22:19:30 +000023 "strconv"
Inseob Kim14199b02021-02-09 21:18:31 +090024 "strings"
Jiyong Park6f0f6882020-11-12 13:14:30 +090025
26 "android/soong/android"
Jooyung Hane6067592023-03-16 13:11:17 +090027 "android/soong/cc"
Spandan Das71be42d2024-11-20 18:34:16 +000028 "android/soong/java"
Spandan Das92631882024-10-28 22:49:38 +000029 "android/soong/linkerconfig"
Jiyong Park65b62242020-11-25 12:44:59 +090030
31 "github.com/google/blueprint"
Jiyong Park71baa762021-01-18 21:11:03 +090032 "github.com/google/blueprint/proptools"
Jiyong Park6f0f6882020-11-12 13:14:30 +090033)
34
35func init() {
Jooyung Han9706cbc2021-04-15 22:43:48 +090036 registerBuildComponents(android.InitRegistrationContext)
Spandan Das71be42d2024-11-20 18:34:16 +000037 registerMutators(android.InitRegistrationContext)
Jooyung Han9706cbc2021-04-15 22:43:48 +090038}
39
40func registerBuildComponents(ctx android.RegistrationContext) {
Cole Faust92ccbe22024-10-03 14:38:37 -070041 ctx.RegisterModuleType("android_filesystem", FilesystemFactory)
Jiyong Parkf46b1af2024-04-05 18:13:33 +090042 ctx.RegisterModuleType("android_filesystem_defaults", filesystemDefaultsFactory)
Jihoon Kang98047cf2024-10-02 17:13:54 +000043 ctx.RegisterModuleType("android_system_image", SystemImageFactory)
Jiyong Parkbc485482022-11-15 22:31:49 +090044 ctx.RegisterModuleType("avb_add_hash_footer", avbAddHashFooterFactory)
Inseob Kim87230e62023-11-22 18:55:07 +090045 ctx.RegisterModuleType("avb_add_hash_footer_defaults", avbAddHashFooterDefaultsFactory)
Alice Wang000e3a32023-01-03 16:11:20 +000046 ctx.RegisterModuleType("avb_gen_vbmeta_image", avbGenVbmetaImageFactory)
Inseob Kim87230e62023-11-22 18:55:07 +090047 ctx.RegisterModuleType("avb_gen_vbmeta_image_defaults", avbGenVbmetaImageDefaultsFactory)
Jiyong Park6f0f6882020-11-12 13:14:30 +090048}
49
Spandan Das71be42d2024-11-20 18:34:16 +000050func registerMutators(ctx android.RegistrationContext) {
51 ctx.PostDepsMutators(func(ctx android.RegisterMutatorsContext) {
52 ctx.BottomUp("add_autogenerated_rro_deps", addAutogeneratedRroDeps)
53 })
54}
55
Cole Fauste1676122024-12-03 17:32:25 -080056// Remember to add referenced files to implicits!
57var textFileProcessorRule = pctx.AndroidStaticRule("text_file_processing", blueprint.RuleParams{
58 Command: "build/soong/scripts/text_file_processor.py $in $out",
59 CommandDeps: []string{"build/soong/scripts/text_file_processor.py"},
60})
61
Jiyong Park6f0f6882020-11-12 13:14:30 +090062type filesystem struct {
63 android.ModuleBase
64 android.PackagingBase
Jiyong Parkf46b1af2024-04-05 18:13:33 +090065 android.DefaultableModuleBase
Jiyong Park65c49f52020-11-24 14:23:26 +090066
Jihoon Kang98047cf2024-10-02 17:13:54 +000067 properties FilesystemProperties
Jiyong Park71baa762021-01-18 21:11:03 +090068
Cole Faust4e9f5922024-11-13 16:09:23 -080069 output android.Path
Jiyong Park65c49f52020-11-24 14:23:26 +090070 installDir android.InstallPath
Jooyung Han0fbbc2b2022-03-25 12:35:46 +090071
Cole Faust4e9f5922024-11-13 16:09:23 -080072 fileListFile android.Path
Kiyoung Kim99a954d2024-06-21 14:22:20 +090073
74 // Keeps the entries installed from this filesystem
Jooyung Han0fbbc2b2022-03-25 12:35:46 +090075 entries []string
Kiyoung Kim67118212024-11-07 13:23:44 +090076
77 filesystemBuilder filesystemBuilder
Jiyong Park6f0f6882020-11-12 13:14:30 +090078}
79
Kiyoung Kim67118212024-11-07 13:23:44 +090080type filesystemBuilder interface {
81 BuildLinkerConfigFile(ctx android.ModuleContext, builder *android.RuleBuilder, rebasedDir android.OutputPath)
82 // Function that filters PackagingSpec in PackagingBase.GatherPackagingSpecs()
83 FilterPackagingSpec(spec android.PackagingSpec) bool
Inseob Kim3c0a0422024-11-05 17:21:37 +090084 // Function that modifies PackagingSpec in PackagingBase.GatherPackagingSpecs() to customize.
85 // For example, GSI system.img contains system_ext and product artifacts and their
86 // relPathInPackage need to be rebased to system/system_ext and system/system_product.
87 ModifyPackagingSpec(spec *android.PackagingSpec)
Kiyoung Kim23be5bb2024-11-27 00:50:30 +000088
89 // Function to check if the filesystem should not use `vintf_fragments` property,
90 // but use `vintf_fragment` module type instead
91 ShouldUseVintfFragmentModuleOnly() bool
Kiyoung Kim67118212024-11-07 13:23:44 +090092}
93
94var _ filesystemBuilder = (*filesystem)(nil)
95
Spandan Das69464c32024-10-25 20:08:06 +000096type SymlinkDefinition struct {
Inseob Kim14199b02021-02-09 21:18:31 +090097 Target *string
98 Name *string
99}
100
Jihoon Kang0a453892024-12-09 22:16:26 +0000101// CopyWithNamePrefix returns a new [SymlinkDefinition] with prefix added to Name.
102func (s *SymlinkDefinition) CopyWithNamePrefix(prefix string) SymlinkDefinition {
103 return SymlinkDefinition{
104 Target: s.Target,
105 Name: proptools.StringPtr(filepath.Join(prefix, proptools.String(s.Name))),
106 }
107}
108
Jihoon Kang98047cf2024-10-02 17:13:54 +0000109type FilesystemProperties struct {
Jiyong Park71baa762021-01-18 21:11:03 +0900110 // When set to true, sign the image with avbtool. Default is false.
111 Use_avb *bool
112
113 // Path to the private key that avbtool will use to sign this filesystem image.
114 // TODO(jiyong): allow apex_key to be specified here
115 Avb_private_key *string `android:"path"`
116
Shikha Panwar01403bb2022-12-22 12:22:57 +0000117 // Signing algorithm for avbtool. Default is SHA256_RSA4096.
Jiyong Park71baa762021-01-18 21:11:03 +0900118 Avb_algorithm *string
Jiyong Park11a65972021-02-01 21:09:38 +0900119
Shikha Panwar01403bb2022-12-22 12:22:57 +0000120 // Hash algorithm used for avbtool (for descriptors). This is passed as hash_algorithm to
121 // avbtool. Default used by avbtool is sha1.
Shikha Panware6f30632022-12-21 12:54:45 +0000122 Avb_hash_algorithm *string
123
Spandan Dase5c393c2024-12-12 19:25:07 +0000124 // The security patch passed to as the com.android.build.<type>.security_patch avb property.
125 Security_patch *string
126
Cole Fauste1676122024-12-03 17:32:25 -0800127 // Whether or not to use forward-error-correction codes when signing with AVB. Defaults to true.
128 Use_fec *bool
129
Nikita Ioffe2c8cdc62024-03-27 22:19:30 +0000130 // The index used to prevent rollback of the image. Only used if use_avb is true.
131 Rollback_index *int64
132
Jiyong Parkac4076d2021-03-15 23:21:30 +0900133 // Name of the partition stored in vbmeta desc. Defaults to the name of this module.
134 Partition_name *string
135
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000136 // Type of the filesystem. Currently, ext4, erofs, cpio, and compressed_cpio are supported. Default
Jiyong Park837cdb22021-02-05 00:17:14 +0900137 // is ext4.
Jiyong Park11a65972021-02-01 21:09:38 +0900138 Type *string
Inseob Kimcc8e5362021-02-03 14:05:24 +0900139
Cole Faust9a24d902024-03-18 15:38:12 -0700140 // Identifies which partition this is for //visibility:any_system_image (and others) visibility
141 // checks, and will be used in the future for API surface checks.
142 Partition_type *string
143
Cole Faust0d467052024-12-04 17:19:19 -0800144 // file_contexts file to make image. Currently, only ext4 is supported. These file contexts
145 // will be compiled with sefcontext_compile
Inseob Kimcc8e5362021-02-03 14:05:24 +0900146 File_contexts *string `android:"path"`
Inseob Kim2ce1b5d2021-02-15 17:01:04 +0900147
Cole Faust0d467052024-12-04 17:19:19 -0800148 // The selinux file contexts, after having already run them through sefcontext_compile
149 Precompiled_file_contexts *string `android:"path"`
150
Inseob Kim2ce1b5d2021-02-15 17:01:04 +0900151 // Base directory relative to root, to which deps are installed, e.g. "system". Default is "."
152 // (root).
153 Base_dir *string
Inseob Kim14199b02021-02-09 21:18:31 +0900154
155 // Directories to be created under root. e.g. /dev, /proc, etc.
Cole Faustd9c6a5b2024-05-21 14:54:00 -0700156 Dirs proptools.Configurable[[]string]
Inseob Kim14199b02021-02-09 21:18:31 +0900157
158 // Symbolic links to be created under root with "ln -sf <target> <name>".
Spandan Das69464c32024-10-25 20:08:06 +0000159 Symlinks []SymlinkDefinition
Jooyung Han65f402b2022-04-21 14:24:04 +0900160
161 // Seconds since unix epoch to override timestamps of file entries
162 Fake_timestamp *string
163
164 // When set, passed to mkuserimg_mke2fs --mke2fs_uuid & --mke2fs_hash_seed.
165 // Otherwise, they'll be set as random which might cause indeterministic build output.
166 Uuid *string
Inseob Kim376d72f2023-11-01 15:40:25 +0900167
168 // Mount point for this image. Default is "/"
169 Mount_point *string
Cole Faust4a2a7c92024-03-12 12:44:40 -0700170
171 // If set to the name of a partition ("system", "vendor", etc), this filesystem module
172 // will also include the contents of the make-built staging directories. If any soong
173 // modules would be installed to the same location as a make module, they will overwrite
174 // the make version.
175 Include_make_built_files string
Inseob Kim53391842024-03-29 17:44:07 +0900176
Inseob Kimb7b84572024-04-30 10:51:47 +0900177 // When set, builds etc/event-log-tags file by merging logtags from all dependencies.
178 // Default is false
179 Build_logtags *bool
180
Justin Yun74f3f302024-05-07 14:32:14 +0900181 // Install aconfig_flags.pb file for the modules installed in this partition.
182 Gen_aconfig_flags_pb *bool
183
Cole Faust34592c02024-12-13 11:20:24 -0800184 // List of names of other filesystem partitions to import their aconfig flags from.
185 // This is used for the system partition to import system_ext's aconfig flags, as currently
186 // those are considered one "container": aosp/3261300
187 Import_aconfig_flags_from []string
188
Inseob Kim53391842024-03-29 17:44:07 +0900189 Fsverity fsverityProperties
Cole Faust92ccbe22024-10-03 14:38:37 -0700190
191 // If this property is set to true, the filesystem will call ctx.UncheckedModule(), causing
192 // it to not be built on checkbuilds. Used for the automatic migration from make to soong
193 // build modules, where we want to emit some not-yet-working filesystems and we don't want them
194 // to be built.
195 Unchecked_module *bool `blueprint:"mutated"`
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000196
197 Erofs ErofsProperties
Jihoon Kang0d545b82024-10-11 00:21:57 +0000198
mrziwang1a6291f2024-11-07 14:29:25 -0800199 F2fs F2fsProperties
200
Spandan Das2047a4c2024-11-11 21:24:58 +0000201 Linker_config LinkerConfigProperties
Spandan Das92631882024-10-28 22:49:38 +0000202
Jihoon Kang0d545b82024-10-11 00:21:57 +0000203 // Determines if the module is auto-generated from Soong or not. If the module is
204 // auto-generated, its deps are exempted from visibility enforcement.
205 Is_auto_generated *bool
Jihoon Kang6c03c8e2024-11-18 21:30:22 +0000206
207 // Path to the dev nodes description file. This is only needed for building the ramdisk
208 // partition and should not be explicitly specified.
209 Dev_nodes_description_file *string `android:"path" blueprint:"mutated"`
Spandan Das71be42d2024-11-20 18:34:16 +0000210
211 // Additional dependencies used for building android products
212 Android_filesystem_deps AndroidFilesystemDeps
213}
214
215type AndroidFilesystemDeps struct {
216 System *string
217 System_ext *string
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000218}
219
220// Additional properties required to generate erofs FS partitions.
221type ErofsProperties struct {
222 // Compressor and Compression level passed to mkfs.erofs. e.g. (lz4hc,9)
223 // Please see external/erofs-utils/README for complete documentation.
224 Compressor *string
225
226 // Used as --compress-hints for mkfs.erofs
227 Compress_hints *string `android:"path"`
228
229 Sparse *bool
Jiyong Park71baa762021-01-18 21:11:03 +0900230}
231
mrziwang1a6291f2024-11-07 14:29:25 -0800232// Additional properties required to generate f2fs FS partitions.
233type F2fsProperties struct {
234 Sparse *bool
235}
236
Spandan Das173256b2024-10-31 19:59:30 +0000237type LinkerConfigProperties struct {
238
239 // Build a linker.config.pb file
240 Gen_linker_config *bool
241
242 // List of files (in .json format) that will be converted to a linker config file (in .pb format).
243 // The linker config file be installed in the filesystem at /etc/linker.config.pb
244 Linker_config_srcs []string `android:"path"`
245}
246
Jiyong Park65c49f52020-11-24 14:23:26 +0900247// android_filesystem packages a set of modules and their transitive dependencies into a filesystem
248// image. The filesystem images are expected to be mounted in the target device, which means the
249// modules in the filesystem image are built for the target device (i.e. Android, not Linux host).
250// The modules are placed in the filesystem image just like they are installed to the ordinary
251// partitions like system.img. For example, cc_library modules are placed under ./lib[64] directory.
Cole Faust92ccbe22024-10-03 14:38:37 -0700252func FilesystemFactory() android.Module {
Jiyong Park6f0f6882020-11-12 13:14:30 +0900253 module := &filesystem{}
Kiyoung Kim67118212024-11-07 13:23:44 +0900254 module.filesystemBuilder = module
Cole Faust2cfe6962024-09-17 11:31:14 -0700255 initFilesystemModule(module, module)
Jiyong Parkfa616132021-04-20 11:36:40 +0900256 return module
257}
258
Cole Faust2cfe6962024-09-17 11:31:14 -0700259func initFilesystemModule(module android.DefaultableModule, filesystemModule *filesystem) {
260 module.AddProperties(&filesystemModule.properties)
261 android.InitPackageModule(filesystemModule)
262 filesystemModule.PackagingBase.DepsCollectFirstTargetOnly = true
Jihoon Kang79196c52024-10-30 18:49:47 +0000263 filesystemModule.PackagingBase.AllowHighPriorityDeps = true
Jiyong Park6f0f6882020-11-12 13:14:30 +0900264 android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900265 android.InitDefaultableModule(module)
Jihoon Kang6c03c8e2024-11-18 21:30:22 +0000266
267 android.AddLoadHook(module, func(ctx android.LoadHookContext) {
268 filesystemModule.setDevNodesDescriptionProp()
269 })
Jiyong Park6f0f6882020-11-12 13:14:30 +0900270}
271
Jihoon Kang0d545b82024-10-11 00:21:57 +0000272type depTag struct {
Jiyong Park12a719c2021-01-07 15:31:24 +0900273 blueprint.BaseDependencyTag
Jooyung Han092ef812021-03-10 15:40:34 +0900274 android.PackagingItemAlwaysDepTag
Jihoon Kang0d545b82024-10-11 00:21:57 +0000275}
276
277var dependencyTag = depTag{}
278
279type depTagWithVisibilityEnforcementBypass struct {
280 depTag
281}
282
Spandan Das71be42d2024-11-20 18:34:16 +0000283type interPartitionDepTag struct {
284 blueprint.BaseDependencyTag
285}
286
287var interPartitionDependencyTag = interPartitionDepTag{}
288
Jihoon Kang0d545b82024-10-11 00:21:57 +0000289var _ android.ExcludeFromVisibilityEnforcementTag = (*depTagWithVisibilityEnforcementBypass)(nil)
290
291func (t depTagWithVisibilityEnforcementBypass) ExcludeFromVisibilityEnforcement() {}
292
293var dependencyTagWithVisibilityEnforcementBypass = depTagWithVisibilityEnforcementBypass{}
Jiyong Park65b62242020-11-25 12:44:59 +0900294
Jihoon Kang6c03c8e2024-11-18 21:30:22 +0000295// ramdiskDevNodesDescription is the name of the filegroup module that provides the file that
296// contains the description of dev nodes added to the CPIO archive for the ramdisk partition.
297const ramdiskDevNodesDescription = "ramdisk_node_list"
298
299func (f *filesystem) setDevNodesDescriptionProp() {
300 if proptools.String(f.properties.Partition_name) == "ramdisk" {
301 f.properties.Dev_nodes_description_file = proptools.StringPtr(":" + ramdiskDevNodesDescription)
302 }
303}
304
Jiyong Park6f0f6882020-11-12 13:14:30 +0900305func (f *filesystem) DepsMutator(ctx android.BottomUpMutatorContext) {
Jihoon Kang0d545b82024-10-11 00:21:57 +0000306 if proptools.Bool(f.properties.Is_auto_generated) {
307 f.AddDeps(ctx, dependencyTagWithVisibilityEnforcementBypass)
308 } else {
309 f.AddDeps(ctx, dependencyTag)
310 }
Spandan Das71be42d2024-11-20 18:34:16 +0000311 if f.properties.Android_filesystem_deps.System != nil {
312 ctx.AddDependency(ctx.Module(), interPartitionDependencyTag, proptools.String(f.properties.Android_filesystem_deps.System))
313 }
314 if f.properties.Android_filesystem_deps.System_ext != nil {
315 ctx.AddDependency(ctx.Module(), interPartitionDependencyTag, proptools.String(f.properties.Android_filesystem_deps.System_ext))
316 }
Cole Faust34592c02024-12-13 11:20:24 -0800317 for _, partition := range f.properties.Import_aconfig_flags_from {
318 ctx.AddDependency(ctx.Module(), importAconfigDependencyTag, partition)
319 }
Jiyong Park6f0f6882020-11-12 13:14:30 +0900320}
321
Jiyong Park11a65972021-02-01 21:09:38 +0900322type fsType int
323
324const (
325 ext4Type fsType = iota
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000326 erofsType
mrziwang1a6291f2024-11-07 14:29:25 -0800327 f2fsType
Jiyong Park11a65972021-02-01 21:09:38 +0900328 compressedCpioType
Jiyong Park837cdb22021-02-05 00:17:14 +0900329 cpioType // uncompressed
Jiyong Park11a65972021-02-01 21:09:38 +0900330 unknown
331)
332
Spandan Das7a46f6c2024-10-14 18:41:18 +0000333func (fs fsType) IsUnknown() bool {
334 return fs == unknown
335}
336
Cole Faust92ccbe22024-10-03 14:38:37 -0700337type FilesystemInfo struct {
Cole Faust44080412024-12-20 14:17:07 -0800338 // The built filesystem image
339 Output android.Path
Cole Faust92ccbe22024-10-03 14:38:37 -0700340 // A text file containing the list of paths installed on the partition.
341 FileListFile android.Path
Cole Faust44080412024-12-20 14:17:07 -0800342 // The root staging directory used to build the output filesystem. If consuming this, make sure
343 // to add a dependency on the Output file, as you cannot add dependencies on directories
344 // in ninja.
345 RootDir android.Path
Cole Faust92ccbe22024-10-03 14:38:37 -0700346}
347
348var FilesystemProvider = blueprint.NewProvider[FilesystemInfo]()
349
Spandan Das7a46f6c2024-10-14 18:41:18 +0000350func GetFsTypeFromString(ctx android.EarlyModuleContext, typeStr string) fsType {
Jiyong Park11a65972021-02-01 21:09:38 +0900351 switch typeStr {
352 case "ext4":
353 return ext4Type
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000354 case "erofs":
355 return erofsType
mrziwang1a6291f2024-11-07 14:29:25 -0800356 case "f2fs":
357 return f2fsType
Jiyong Park11a65972021-02-01 21:09:38 +0900358 case "compressed_cpio":
359 return compressedCpioType
Jiyong Park837cdb22021-02-05 00:17:14 +0900360 case "cpio":
361 return cpioType
Jiyong Park11a65972021-02-01 21:09:38 +0900362 default:
Jiyong Park11a65972021-02-01 21:09:38 +0900363 return unknown
364 }
365}
366
Spandan Das7a46f6c2024-10-14 18:41:18 +0000367func (f *filesystem) fsType(ctx android.ModuleContext) fsType {
368 typeStr := proptools.StringDefault(f.properties.Type, "ext4")
369 fsType := GetFsTypeFromString(ctx, typeStr)
370 if fsType == unknown {
371 ctx.PropertyErrorf("type", "%q not supported", typeStr)
372 }
373 return fsType
374}
375
Jiyong Park65c49f52020-11-24 14:23:26 +0900376func (f *filesystem) installFileName() string {
377 return f.BaseModuleName() + ".img"
378}
379
Inseob Kim53391842024-03-29 17:44:07 +0900380func (f *filesystem) partitionName() string {
381 return proptools.StringDefault(f.properties.Partition_name, f.Name())
382}
383
Kiyoung Kim67118212024-11-07 13:23:44 +0900384func (f *filesystem) FilterPackagingSpec(ps android.PackagingSpec) bool {
Jiyong Park7e7d4af2024-05-01 12:36:10 +0000385 // Filesystem module respects the installation semantic. A PackagingSpec from a module with
386 // IsSkipInstall() is skipped.
Cole Faust76a6e952024-11-07 16:56:45 -0800387 if ps.SkipInstall() {
388 return false
Spandan Das6d056502024-10-21 15:40:32 +0000389 }
Cole Faust76a6e952024-11-07 16:56:45 -0800390 if proptools.Bool(f.properties.Is_auto_generated) { // TODO (spandandas): Remove this.
391 pt := f.PartitionType()
Cole Faustc88cff12024-11-12 13:24:05 -0800392 return ps.Partition() == pt || strings.HasPrefix(ps.Partition(), pt+"/")
Cole Faust76a6e952024-11-07 16:56:45 -0800393 }
394 return true
Jiyong Park7e7d4af2024-05-01 12:36:10 +0000395}
396
Inseob Kim3c0a0422024-11-05 17:21:37 +0900397func (f *filesystem) ModifyPackagingSpec(ps *android.PackagingSpec) {
Cole Faustc88cff12024-11-12 13:24:05 -0800398 // Sometimes, android.modulePartition() returns a path with >1 path components.
399 // This makes the partition field of packagingSpecs have multiple components, like
400 // "system/product". Right now, the filesystem module doesn't look at the partition field
401 // when deciding what path to install the file under, only the RelPathInPackage field, so
402 // we move the later path components from partition to relPathInPackage. This should probably
403 // be revisited in the future.
404 prefix := f.PartitionType() + "/"
405 if strings.HasPrefix(ps.Partition(), prefix) {
406 subPartition := strings.TrimPrefix(ps.Partition(), prefix)
407 ps.SetPartition(f.PartitionType())
408 ps.SetRelPathInPackage(filepath.Join(subPartition, ps.RelPathInPackage()))
409 }
Inseob Kim3c0a0422024-11-05 17:21:37 +0900410}
411
Jiyong Park6f0f6882020-11-12 13:14:30 +0900412var pctx = android.NewPackageContext("android/soong/filesystem")
413
414func (f *filesystem) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900415 validatePartitionType(ctx, f)
Kiyoung Kim23be5bb2024-11-27 00:50:30 +0000416 if f.filesystemBuilder.ShouldUseVintfFragmentModuleOnly() {
417 f.validateVintfFragments(ctx)
418 }
Cole Faust44080412024-12-20 14:17:07 -0800419 var rootDir android.Path
Jiyong Park11a65972021-02-01 21:09:38 +0900420 switch f.fsType(ctx) {
mrziwang1a6291f2024-11-07 14:29:25 -0800421 case ext4Type, erofsType, f2fsType:
Cole Faust44080412024-12-20 14:17:07 -0800422 f.output, rootDir = f.buildImageUsingBuildImage(ctx)
Jiyong Park11a65972021-02-01 21:09:38 +0900423 case compressedCpioType:
Cole Faust44080412024-12-20 14:17:07 -0800424 f.output, rootDir = f.buildCpioImage(ctx, true)
Jiyong Park837cdb22021-02-05 00:17:14 +0900425 case cpioType:
Cole Faust44080412024-12-20 14:17:07 -0800426 f.output, rootDir = f.buildCpioImage(ctx, false)
Jiyong Park11a65972021-02-01 21:09:38 +0900427 default:
428 return
429 }
430
431 f.installDir = android.PathForModuleInstall(ctx, "etc")
432 ctx.InstallFile(f.installDir, f.installFileName(), f.output)
mrziwang555d1332024-06-07 11:15:33 -0700433 ctx.SetOutputFiles([]android.Path{f.output}, "")
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900434
Cole Faust4e9f5922024-11-13 16:09:23 -0800435 fileListFile := android.PathForModuleOut(ctx, "fileList")
436 android.WriteFileRule(ctx, fileListFile, f.installedFilesList())
Cole Faust92ccbe22024-10-03 14:38:37 -0700437
438 android.SetProvider(ctx, FilesystemProvider, FilesystemInfo{
Cole Faust44080412024-12-20 14:17:07 -0800439 Output: f.output,
Naresh Kumar Podishetty (xWF)7d89e662024-12-19 23:40:02 -0800440 FileListFile: fileListFile,
Cole Faust44080412024-12-20 14:17:07 -0800441 RootDir: rootDir,
Cole Faust92ccbe22024-10-03 14:38:37 -0700442 })
Cole Faust4e9f5922024-11-13 16:09:23 -0800443 f.fileListFile = fileListFile
Cole Faust92ccbe22024-10-03 14:38:37 -0700444
445 if proptools.Bool(f.properties.Unchecked_module) {
446 ctx.UncheckedModule()
447 }
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900448}
449
Kiyoung Kim23be5bb2024-11-27 00:50:30 +0000450func (f *filesystem) validateVintfFragments(ctx android.ModuleContext) {
451 visitedModule := map[string]bool{}
452 packagingSpecs := f.gatherFilteredPackagingSpecs(ctx)
453
454 moduleInFileSystem := func(mod android.Module) bool {
455 for _, ps := range android.OtherModuleProviderOrDefault(
456 ctx, mod, android.InstallFilesProvider).PackagingSpecs {
457 if _, ok := packagingSpecs[ps.RelPathInPackage()]; ok {
458 return true
459 }
460 }
461 return false
462 }
463
464 ctx.WalkDeps(func(child, parent android.Module) bool {
465 if visitedModule[child.Name()] {
466 return false
467 }
468 if !moduleInFileSystem(child) {
469 visitedModule[child.Name()] = true
470 return true
471 }
472 if vintfFragments := child.VintfFragments(ctx); vintfFragments != nil {
473 ctx.PropertyErrorf(
474 "vintf_fragments",
475 "Module %s is referenced by soong-defined filesystem %s with property vintf_fragments(%s) in use."+
476 " Use vintf_fragment_modules property instead.",
477 child.Name(),
478 f.BaseModuleName(),
479 strings.Join(vintfFragments, ", "),
480 )
481 }
482 visitedModule[child.Name()] = true
483 return true
484 })
485}
486
Cole Faust4e9f5922024-11-13 16:09:23 -0800487func (f *filesystem) appendToEntry(ctx android.ModuleContext, installedFile android.Path) {
Spandan Das420e16a2024-12-11 18:10:52 +0000488 partitionBaseDir := android.PathForModuleOut(ctx, f.rootDirString(), proptools.String(f.properties.Base_dir)).String() + "/"
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900489
490 relPath, inTargetPartition := strings.CutPrefix(installedFile.String(), partitionBaseDir)
491 if inTargetPartition {
492 f.entries = append(f.entries, relPath)
493 }
494}
495
496func (f *filesystem) installedFilesList() string {
497 installedFilePaths := android.FirstUniqueStrings(f.entries)
498 slices.Sort(installedFilePaths)
499
500 return strings.Join(installedFilePaths, "\n")
Jiyong Park11a65972021-02-01 21:09:38 +0900501}
502
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900503func validatePartitionType(ctx android.ModuleContext, p partition) {
504 if !android.InList(p.PartitionType(), validPartitions) {
505 ctx.PropertyErrorf("partition_type", "partition_type must be one of %s, found: %s", validPartitions, p.PartitionType())
506 }
507
508 ctx.VisitDirectDepsWithTag(android.DefaultsDepTag, func(m android.Module) {
509 if fdm, ok := m.(*filesystemDefaults); ok {
510 if p.PartitionType() != fdm.PartitionType() {
511 ctx.PropertyErrorf("partition_type",
512 "%s doesn't match with the partition type %s of the filesystem default module %s",
513 p.PartitionType(), fdm.PartitionType(), m.Name())
514 }
515 }
516 })
517}
518
Cole Faust3b806d32024-03-11 15:15:03 -0700519// Copy extra files/dirs that are not from the `deps` property to `rootDir`, checking for conflicts with files
520// already in `rootDir`.
521func (f *filesystem) buildNonDepsFiles(ctx android.ModuleContext, builder *android.RuleBuilder, rootDir android.OutputPath) {
Inseob Kim14199b02021-02-09 21:18:31 +0900522 // create dirs and symlinks
Cole Faustd9c6a5b2024-05-21 14:54:00 -0700523 for _, dir := range f.properties.Dirs.GetOrDefault(ctx, nil) {
Inseob Kim14199b02021-02-09 21:18:31 +0900524 // OutputPath.Join verifies dir
525 builder.Command().Text("mkdir -p").Text(rootDir.Join(ctx, dir).String())
526 }
527
528 for _, symlink := range f.properties.Symlinks {
529 name := strings.TrimSpace(proptools.String(symlink.Name))
530 target := strings.TrimSpace(proptools.String(symlink.Target))
531
532 if name == "" {
533 ctx.PropertyErrorf("symlinks", "Name can't be empty")
534 continue
535 }
536
537 if target == "" {
538 ctx.PropertyErrorf("symlinks", "Target can't be empty")
539 continue
540 }
541
542 // OutputPath.Join verifies name. don't need to verify target.
543 dst := rootDir.Join(ctx, name)
Cole Faust3b806d32024-03-11 15:15:03 -0700544 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 +0900545 builder.Command().Text("mkdir -p").Text(filepath.Dir(dst.String()))
546 builder.Command().Text("ln -sf").Text(proptools.ShellEscape(target)).Text(dst.String())
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900547 f.appendToEntry(ctx, dst)
Inseob Kim14199b02021-02-09 21:18:31 +0900548 }
Jihoon Kang89e8a692024-12-18 19:28:33 +0000549
550 // https://cs.android.com/android/platform/superproject/main/+/main:build/make/core/Makefile;l=2835;drc=b186569ef00ff2f2a1fab28aedc75ebc32bcd67b
551 if f.partitionName() == "recovery" {
552 builder.Command().Text("mkdir -p").Text(rootDir.Join(ctx, "root/linkerconfig").String())
553 builder.Command().Text("touch").Text(rootDir.Join(ctx, "root/linkerconfig/ld.config.txt").String())
554 }
Inseob Kim2ce1b5d2021-02-15 17:01:04 +0900555}
556
Inseob Kim33f95a92024-07-11 15:44:49 +0900557func (f *filesystem) copyPackagingSpecs(ctx android.ModuleContext, builder *android.RuleBuilder, specs map[string]android.PackagingSpec, rootDir, rebasedDir android.WritablePath) []string {
558 rootDirSpecs := make(map[string]android.PackagingSpec)
559 rebasedDirSpecs := make(map[string]android.PackagingSpec)
560
561 for rel, spec := range specs {
562 if spec.Partition() == "root" {
563 rootDirSpecs[rel] = spec
564 } else {
565 rebasedDirSpecs[rel] = spec
566 }
567 }
568
569 dirsToSpecs := make(map[android.WritablePath]map[string]android.PackagingSpec)
570 dirsToSpecs[rootDir] = rootDirSpecs
571 dirsToSpecs[rebasedDir] = rebasedDirSpecs
572
573 return f.CopySpecsToDirs(ctx, builder, dirsToSpecs)
574}
575
Justin Yun34baa2e2024-08-30 21:11:33 +0900576func (f *filesystem) copyFilesToProductOut(ctx android.ModuleContext, builder *android.RuleBuilder, rebasedDir android.OutputPath) {
Justin Yun2cc42502024-09-11 14:10:20 +0900577 if f.Name() != ctx.Config().SoongDefinedSystemImage() {
Justin Yun34baa2e2024-08-30 21:11:33 +0900578 return
579 }
580 installPath := android.PathForModuleInPartitionInstall(ctx, f.partitionName())
581 builder.Command().Textf("cp -prf %s/* %s", rebasedDir, installPath)
582}
583
Spandan Das420e16a2024-12-11 18:10:52 +0000584func (f *filesystem) rootDirString() string {
585 return f.partitionName()
586}
587
Cole Faust44080412024-12-20 14:17:07 -0800588func (f *filesystem) buildImageUsingBuildImage(ctx android.ModuleContext) (android.Path, android.Path) {
Spandan Das420e16a2024-12-11 18:10:52 +0000589 rootDir := android.PathForModuleOut(ctx, f.rootDirString()).OutputPath
Cole Faust3b806d32024-03-11 15:15:03 -0700590 rebasedDir := rootDir
591 if f.properties.Base_dir != nil {
592 rebasedDir = rootDir.Join(ctx, *f.properties.Base_dir)
593 }
594 builder := android.NewRuleBuilder(pctx, ctx)
595 // Wipe the root dir to get rid of leftover files from prior builds
596 builder.Command().Textf("rm -rf %s && mkdir -p %s", rootDir, rootDir)
Inseob Kim53391842024-03-29 17:44:07 +0900597 specs := f.gatherFilteredPackagingSpecs(ctx)
Inseob Kim33f95a92024-07-11 15:44:49 +0900598 f.entries = f.copyPackagingSpecs(ctx, builder, specs, rootDir, rebasedDir)
Cole Faust3b806d32024-03-11 15:15:03 -0700599
600 f.buildNonDepsFiles(ctx, builder, rootDir)
Cole Faust4a2a7c92024-03-12 12:44:40 -0700601 f.addMakeBuiltFiles(ctx, builder, rootDir)
Inseob Kim53391842024-03-29 17:44:07 +0900602 f.buildFsverityMetadataFiles(ctx, builder, specs, rootDir, rebasedDir)
Inseob Kimb7b84572024-04-30 10:51:47 +0900603 f.buildEventLogtagsFile(ctx, builder, rebasedDir)
Justin Yun74f3f302024-05-07 14:32:14 +0900604 f.buildAconfigFlagsFiles(ctx, builder, specs, rebasedDir)
Kiyoung Kim67118212024-11-07 13:23:44 +0900605 f.filesystemBuilder.BuildLinkerConfigFile(ctx, builder, rebasedDir)
Justin Yun34baa2e2024-08-30 21:11:33 +0900606 f.copyFilesToProductOut(ctx, builder, rebasedDir)
Jiyong Park6f0f6882020-11-12 13:14:30 +0900607
Nikita Ioffe519015f2022-12-23 15:36:29 +0000608 // run host_init_verifier
609 // Ideally we should have a concept of pluggable linters that verify the generated image.
610 // While such concept is not implement this will do.
611 // TODO(b/263574231): substitute with pluggable linter.
612 builder.Command().
613 BuiltTool("host_init_verifier").
614 FlagWithArg("--out_system=", rootDir.String()+"/system")
615
Jiyong Park72678312021-01-18 17:29:49 +0900616 propFile, toolDeps := f.buildPropFile(ctx)
Cole Fauste1676122024-12-03 17:32:25 -0800617
618 // Most of the time, if build_image were to call a host tool, it accepts the path to the
619 // host tool in a field in the prop file. However, it doesn't have that option for fec, which
620 // it expects to just be on the PATH. Add fec to the PATH.
621 fec := ctx.Config().HostToolPath(ctx, "fec")
622 pathToolDirs := []string{filepath.Dir(fec.String())}
623
Cole Faust4e9f5922024-11-13 16:09:23 -0800624 output := android.PathForModuleOut(ctx, f.installFileName())
Cole Fauste1676122024-12-03 17:32:25 -0800625 builder.Command().
626 Textf("PATH=%s:$PATH", strings.Join(pathToolDirs, ":")).
627 BuiltTool("build_image").
Jiyong Park6f0f6882020-11-12 13:14:30 +0900628 Text(rootDir.String()). // input directory
629 Input(propFile).
Jiyong Park72678312021-01-18 17:29:49 +0900630 Implicits(toolDeps).
Cole Fauste1676122024-12-03 17:32:25 -0800631 Implicit(fec).
Spandan Dasba273222024-12-12 19:25:07 +0000632 FlagWithArg("--build_datetime_file ", ctx.Config().Getenv("BUILD_DATETIME_FILE")).
Jiyong Park11a65972021-02-01 21:09:38 +0900633 Output(output).
Jiyong Park6f0f6882020-11-12 13:14:30 +0900634 Text(rootDir.String()) // directory where to find fs_config_files|dirs
635
636 // rootDir is not deleted. Might be useful for quick inspection.
Colin Crossf1a035e2020-11-16 17:32:30 -0800637 builder.Build("build_filesystem_image", fmt.Sprintf("Creating filesystem %s", f.BaseModuleName()))
Jiyong Park65c49f52020-11-24 14:23:26 +0900638
Cole Faust44080412024-12-20 14:17:07 -0800639 return output, rootDir
Jiyong Park65c49f52020-11-24 14:23:26 +0900640}
641
Cole Faust4e9f5922024-11-13 16:09:23 -0800642func (f *filesystem) buildFileContexts(ctx android.ModuleContext) android.Path {
Inseob Kimcc8e5362021-02-03 14:05:24 +0900643 builder := android.NewRuleBuilder(pctx, ctx)
644 fcBin := android.PathForModuleOut(ctx, "file_contexts.bin")
645 builder.Command().BuiltTool("sefcontext_compile").
646 FlagWithOutput("-o ", fcBin).
647 Input(android.PathForModuleSrc(ctx, proptools.String(f.properties.File_contexts)))
648 builder.Build("build_filesystem_file_contexts", fmt.Sprintf("Creating filesystem file contexts for %s", f.BaseModuleName()))
Cole Faust4e9f5922024-11-13 16:09:23 -0800649 return fcBin
Inseob Kimcc8e5362021-02-03 14:05:24 +0900650}
651
Cole Faust4e9f5922024-11-13 16:09:23 -0800652func (f *filesystem) buildPropFile(ctx android.ModuleContext) (android.Path, android.Paths) {
Jiyong Park72678312021-01-18 17:29:49 +0900653 var deps android.Paths
Cole Faustcec230a2024-03-07 15:51:12 -0800654 var propFileString strings.Builder
Jiyong Park72678312021-01-18 17:29:49 +0900655 addStr := func(name string, value string) {
Cole Faustcec230a2024-03-07 15:51:12 -0800656 propFileString.WriteString(name)
657 propFileString.WriteRune('=')
658 propFileString.WriteString(value)
659 propFileString.WriteRune('\n')
Jiyong Park72678312021-01-18 17:29:49 +0900660 }
661 addPath := func(name string, path android.Path) {
Cole Faustcec230a2024-03-07 15:51:12 -0800662 addStr(name, path.String())
Jiyong Park72678312021-01-18 17:29:49 +0900663 deps = append(deps, path)
664 }
665
Jiyong Park11a65972021-02-01 21:09:38 +0900666 // Type string that build_image.py accepts.
667 fsTypeStr := func(t fsType) string {
668 switch t {
Spandan Das94668822024-10-09 20:51:33 +0000669 // TODO(372522486): add more types like f2fs, erofs, etc.
Jiyong Park11a65972021-02-01 21:09:38 +0900670 case ext4Type:
671 return "ext4"
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000672 case erofsType:
673 return "erofs"
mrziwang1a6291f2024-11-07 14:29:25 -0800674 case f2fsType:
675 return "f2fs"
Jiyong Park11a65972021-02-01 21:09:38 +0900676 }
677 panic(fmt.Errorf("unsupported fs type %v", t))
678 }
679
680 addStr("fs_type", fsTypeStr(f.fsType(ctx)))
Inseob Kim376d72f2023-11-01 15:40:25 +0900681 addStr("mount_point", proptools.StringDefault(f.properties.Mount_point, "/"))
Jiyong Park72678312021-01-18 17:29:49 +0900682 addStr("use_dynamic_partition_size", "true")
683 addPath("ext_mkuserimg", ctx.Config().HostToolPath(ctx, "mkuserimg_mke2fs"))
684 // b/177813163 deps of the host tools have to be added. Remove this.
685 for _, t := range []string{"mke2fs", "e2fsdroid", "tune2fs"} {
686 deps = append(deps, ctx.Config().HostToolPath(ctx, t))
687 }
688
Jiyong Park71baa762021-01-18 21:11:03 +0900689 if proptools.Bool(f.properties.Use_avb) {
690 addStr("avb_hashtree_enable", "true")
691 addPath("avb_avbtool", ctx.Config().HostToolPath(ctx, "avbtool"))
692 algorithm := proptools.StringDefault(f.properties.Avb_algorithm, "SHA256_RSA4096")
693 addStr("avb_algorithm", algorithm)
Cole Fauste1676122024-12-03 17:32:25 -0800694 if f.properties.Avb_private_key != nil {
695 key := android.PathForModuleSrc(ctx, *f.properties.Avb_private_key)
696 addPath("avb_key_path", key)
697 }
Inseob Kim53391842024-03-29 17:44:07 +0900698 addStr("partition_name", f.partitionName())
Cole Fauste1676122024-12-03 17:32:25 -0800699 avb_add_hashtree_footer_args := ""
700 if !proptools.BoolDefault(f.properties.Use_fec, true) {
701 avb_add_hashtree_footer_args += " --do_not_generate_fec"
702 }
Shikha Panware6f30632022-12-21 12:54:45 +0000703 if hashAlgorithm := proptools.String(f.properties.Avb_hash_algorithm); hashAlgorithm != "" {
704 avb_add_hashtree_footer_args += " --hash_algorithm " + hashAlgorithm
705 }
Nikita Ioffe2c8cdc62024-03-27 22:19:30 +0000706 if f.properties.Rollback_index != nil {
707 rollbackIndex := proptools.Int(f.properties.Rollback_index)
708 if rollbackIndex < 0 {
709 ctx.PropertyErrorf("rollback_index", "Rollback index must be non-negative")
710 }
711 avb_add_hashtree_footer_args += " --rollback_index " + strconv.Itoa(rollbackIndex)
712 }
Cole Fauste1676122024-12-03 17:32:25 -0800713 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 -0800714 // We're not going to add BuildFingerPrintFile as a dep. If it changed, it's likely because
715 // the build number changed, and we don't want to trigger rebuilds solely based on the build
716 // number.
Cole Fauste1676122024-12-03 17:32:25 -0800717 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 +0000718 if f.properties.Security_patch != nil && proptools.String(f.properties.Security_patch) != "" {
719 avb_add_hashtree_footer_args += fmt.Sprintf(" --prop com.android.build.%s.security_patch:%s", f.partitionName(), proptools.String(f.properties.Security_patch))
720 }
Shikha Panware6f30632022-12-21 12:54:45 +0000721 addStr("avb_add_hashtree_footer_args", avb_add_hashtree_footer_args)
Jiyong Park71baa762021-01-18 21:11:03 +0900722 }
723
Cole Faust0d467052024-12-04 17:19:19 -0800724 if f.properties.File_contexts != nil && f.properties.Precompiled_file_contexts != nil {
725 ctx.ModuleErrorf("file_contexts and precompiled_file_contexts cannot both be set")
726 } else if f.properties.File_contexts != nil {
Inseob Kimcc8e5362021-02-03 14:05:24 +0900727 addPath("selinux_fc", f.buildFileContexts(ctx))
Cole Faust0d467052024-12-04 17:19:19 -0800728 } else if f.properties.Precompiled_file_contexts != nil {
729 src := android.PathForModuleSrc(ctx, *f.properties.Precompiled_file_contexts)
730 if src != nil {
731 addPath("selinux_fc", src)
732 }
Inseob Kimcc8e5362021-02-03 14:05:24 +0900733 }
Jooyung Han65f402b2022-04-21 14:24:04 +0900734 if timestamp := proptools.String(f.properties.Fake_timestamp); timestamp != "" {
735 addStr("timestamp", timestamp)
736 }
737 if uuid := proptools.String(f.properties.Uuid); uuid != "" {
738 addStr("uuid", uuid)
739 addStr("hash_seed", uuid)
740 }
mrziwang1a6291f2024-11-07 14:29:25 -0800741
Cole Faust43a52c72024-11-26 12:46:08 -0800742 // TODO(b/381120092): This should only be added if none of the size-related properties are set,
743 // but currently soong built partitions don't have size properties. Make code:
744 // https://cs.android.com/android/platform/superproject/main/+/main:build/make/core/Makefile;l=2262;drc=39cd33701c9278db0e7e481a090605f428d5b12d
745 // Make uses system_disable_sparse but disable_sparse has the same effect, and we shouldn't need
746 // to qualify it because each partition gets its own property file built.
747 addStr("disable_sparse", "true")
748
mrziwang1a6291f2024-11-07 14:29:25 -0800749 fst := f.fsType(ctx)
750 switch fst {
751 case erofsType:
752 // Add erofs properties
Cole Faust3e730972024-12-03 13:12:08 -0800753 addStr("erofs_default_compressor", proptools.StringDefault(f.properties.Erofs.Compressor, "lz4hc,9"))
754 if f.properties.Erofs.Compress_hints != nil {
755 src := android.PathForModuleSrc(ctx, *f.properties.Erofs.Compress_hints)
756 addPath("erofs_default_compress_hints", src)
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000757 }
758 if proptools.BoolDefault(f.properties.Erofs.Sparse, true) {
759 // https://source.corp.google.com/h/googleplex-android/platform/build/+/88b1c67239ca545b11580237242774b411f2fed9:core/Makefile;l=2292;bpv=1;bpt=0;drc=ea8f34bc1d6e63656b4ec32f2391e9d54b3ebb6b
760 addStr("erofs_sparse_flag", "-s")
761 }
mrziwang1a6291f2024-11-07 14:29:25 -0800762 case f2fsType:
763 if proptools.BoolDefault(f.properties.F2fs.Sparse, true) {
764 // https://source.corp.google.com/h/googleplex-android/platform/build/+/88b1c67239ca545b11580237242774b411f2fed9:core/Makefile;l=2294;drc=ea8f34bc1d6e63656b4ec32f2391e9d54b3ebb6b;bpv=1;bpt=0
765 addStr("f2fs_sparse_flag", "-S")
766 }
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000767 }
mrziwang1a6291f2024-11-07 14:29:25 -0800768 f.checkFsTypePropertyError(ctx, fst, fsTypeStr(fst))
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000769
Cole Fauste1676122024-12-03 17:32:25 -0800770 propFilePreProcessing := android.PathForModuleOut(ctx, "prop_pre_processing")
771 android.WriteFileRuleVerbatim(ctx, propFilePreProcessing, propFileString.String())
Cole Faust4e9f5922024-11-13 16:09:23 -0800772 propFile := android.PathForModuleOut(ctx, "prop")
Cole Fauste1676122024-12-03 17:32:25 -0800773 ctx.Build(pctx, android.BuildParams{
Cole Faustefeb5c42024-12-16 10:47:26 -0800774 Rule: textFileProcessorRule,
775 Input: propFilePreProcessing,
776 Output: propFile,
Cole Fauste1676122024-12-03 17:32:25 -0800777 })
Jiyong Park72678312021-01-18 17:29:49 +0900778 return propFile, deps
779}
780
mrziwang1a6291f2024-11-07 14:29:25 -0800781// This method checks if there is any property set for the fstype(s) other than
782// the current fstype.
783func (f *filesystem) checkFsTypePropertyError(ctx android.ModuleContext, t fsType, fs string) {
784 raiseError := func(otherFsType, currentFsType string) {
785 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)
786 ctx.PropertyErrorf(otherFsType, errMsg)
787 }
788
789 if t != erofsType {
790 if f.properties.Erofs.Compressor != nil || f.properties.Erofs.Compress_hints != nil || f.properties.Erofs.Sparse != nil {
791 raiseError("erofs", fs)
792 }
793 }
794 if t != f2fsType {
795 if f.properties.F2fs.Sparse != nil {
796 raiseError("f2fs", fs)
797 }
798 }
799}
800
Cole Faust44080412024-12-20 14:17:07 -0800801func (f *filesystem) buildCpioImage(ctx android.ModuleContext, compressed bool) (android.Path, android.Path) {
Jiyong Park11a65972021-02-01 21:09:38 +0900802 if proptools.Bool(f.properties.Use_avb) {
803 ctx.PropertyErrorf("use_avb", "signing compresed cpio image using avbtool is not supported."+
804 "Consider adding this to bootimg module and signing the entire boot image.")
805 }
806
Inseob Kimcc8e5362021-02-03 14:05:24 +0900807 if proptools.String(f.properties.File_contexts) != "" {
808 ctx.PropertyErrorf("file_contexts", "file_contexts is not supported for compressed cpio image.")
809 }
810
Cole Faust4a2a7c92024-03-12 12:44:40 -0700811 if f.properties.Include_make_built_files != "" {
812 ctx.PropertyErrorf("include_make_built_files", "include_make_built_files is not supported for compressed cpio image.")
813 }
814
Spandan Das420e16a2024-12-11 18:10:52 +0000815 rootDir := android.PathForModuleOut(ctx, f.rootDirString()).OutputPath
Cole Faust3b806d32024-03-11 15:15:03 -0700816 rebasedDir := rootDir
817 if f.properties.Base_dir != nil {
818 rebasedDir = rootDir.Join(ctx, *f.properties.Base_dir)
819 }
820 builder := android.NewRuleBuilder(pctx, ctx)
821 // Wipe the root dir to get rid of leftover files from prior builds
822 builder.Command().Textf("rm -rf %s && mkdir -p %s", rootDir, rootDir)
Inseob Kim53391842024-03-29 17:44:07 +0900823 specs := f.gatherFilteredPackagingSpecs(ctx)
Inseob Kim33f95a92024-07-11 15:44:49 +0900824 f.entries = f.copyPackagingSpecs(ctx, builder, specs, rootDir, rebasedDir)
Cole Faust3b806d32024-03-11 15:15:03 -0700825
826 f.buildNonDepsFiles(ctx, builder, rootDir)
Inseob Kim53391842024-03-29 17:44:07 +0900827 f.buildFsverityMetadataFiles(ctx, builder, specs, rootDir, rebasedDir)
Inseob Kimb7b84572024-04-30 10:51:47 +0900828 f.buildEventLogtagsFile(ctx, builder, rebasedDir)
Justin Yun74f3f302024-05-07 14:32:14 +0900829 f.buildAconfigFlagsFiles(ctx, builder, specs, rebasedDir)
Kiyoung Kim67118212024-11-07 13:23:44 +0900830 f.filesystemBuilder.BuildLinkerConfigFile(ctx, builder, rebasedDir)
Justin Yun34baa2e2024-08-30 21:11:33 +0900831 f.copyFilesToProductOut(ctx, builder, rebasedDir)
Jiyong Park11a65972021-02-01 21:09:38 +0900832
Cole Faust4e9f5922024-11-13 16:09:23 -0800833 output := android.PathForModuleOut(ctx, f.installFileName())
Jiyong Park837cdb22021-02-05 00:17:14 +0900834 cmd := builder.Command().
Jiyong Park11a65972021-02-01 21:09:38 +0900835 BuiltTool("mkbootfs").
Jiyong Park837cdb22021-02-05 00:17:14 +0900836 Text(rootDir.String()) // input directory
Jihoon Kang6c03c8e2024-11-18 21:30:22 +0000837 if nodeList := f.properties.Dev_nodes_description_file; nodeList != nil {
838 cmd.FlagWithInput("-n ", android.PathForModuleSrc(ctx, proptools.String(nodeList)))
839 }
Jiyong Park837cdb22021-02-05 00:17:14 +0900840 if compressed {
841 cmd.Text("|").
842 BuiltTool("lz4").
843 Flag("--favor-decSpeed"). // for faster boot
844 Flag("-12"). // maximum compression level
845 Flag("-l"). // legacy format for kernel
846 Text(">").Output(output)
847 } else {
848 cmd.Text(">").Output(output)
849 }
Jiyong Park11a65972021-02-01 21:09:38 +0900850
851 // rootDir is not deleted. Might be useful for quick inspection.
Jiyong Park837cdb22021-02-05 00:17:14 +0900852 builder.Build("build_cpio_image", fmt.Sprintf("Creating filesystem %s", f.BaseModuleName()))
Jiyong Park11a65972021-02-01 21:09:38 +0900853
Cole Faust44080412024-12-20 14:17:07 -0800854 return output, rootDir
Jiyong Park11a65972021-02-01 21:09:38 +0900855}
856
Cole Faust4a2a7c92024-03-12 12:44:40 -0700857var validPartitions = []string{
858 "system",
859 "userdata",
860 "cache",
861 "system_other",
862 "vendor",
863 "product",
864 "system_ext",
865 "odm",
866 "vendor_dlkm",
867 "odm_dlkm",
868 "system_dlkm",
Cole Faust76a6e952024-11-07 16:56:45 -0800869 "ramdisk",
Cole Faust24938e22024-11-18 14:01:58 -0800870 "vendor_ramdisk",
Jihoon Kang3216c982024-12-02 19:42:20 +0000871 "recovery",
Cole Faust4a2a7c92024-03-12 12:44:40 -0700872}
873
874func (f *filesystem) addMakeBuiltFiles(ctx android.ModuleContext, builder *android.RuleBuilder, rootDir android.Path) {
875 partition := f.properties.Include_make_built_files
876 if partition == "" {
877 return
878 }
879 if !slices.Contains(validPartitions, partition) {
880 ctx.PropertyErrorf("include_make_built_files", "Expected one of %#v, found %q", validPartitions, partition)
881 return
882 }
883 stampFile := fmt.Sprintf("target/product/%s/obj/PACKAGING/%s_intermediates/staging_dir.stamp", ctx.Config().DeviceName(), partition)
884 fileListFile := fmt.Sprintf("target/product/%s/obj/PACKAGING/%s_intermediates/file_list.txt", ctx.Config().DeviceName(), partition)
885 stagingDir := fmt.Sprintf("target/product/%s/%s", ctx.Config().DeviceName(), partition)
886
887 builder.Command().BuiltTool("merge_directories").
888 Implicit(android.PathForArbitraryOutput(ctx, stampFile)).
889 Text("--ignore-duplicates").
890 FlagWithInput("--file-list", android.PathForArbitraryOutput(ctx, fileListFile)).
891 Text(rootDir.String()).
892 Text(android.PathForArbitraryOutput(ctx, stagingDir).String())
893}
894
Inseob Kimb7b84572024-04-30 10:51:47 +0900895func (f *filesystem) buildEventLogtagsFile(ctx android.ModuleContext, builder *android.RuleBuilder, rebasedDir android.OutputPath) {
896 if !proptools.Bool(f.properties.Build_logtags) {
897 return
898 }
899
Inseob Kimb7b84572024-04-30 10:51:47 +0900900 etcPath := rebasedDir.Join(ctx, "etc")
901 eventLogtagsPath := etcPath.Join(ctx, "event-log-tags")
902 builder.Command().Text("mkdir").Flag("-p").Text(etcPath.String())
Cole Fauste4506af2024-12-11 14:14:50 -0800903 builder.Command().Text("cp").Input(android.MergedLogtagsPath(ctx)).Text(eventLogtagsPath.String())
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900904
905 f.appendToEntry(ctx, eventLogtagsPath)
Inseob Kimb7b84572024-04-30 10:51:47 +0900906}
907
Kiyoung Kim67118212024-11-07 13:23:44 +0900908func (f *filesystem) BuildLinkerConfigFile(ctx android.ModuleContext, builder *android.RuleBuilder, rebasedDir android.OutputPath) {
Spandan Das2047a4c2024-11-11 21:24:58 +0000909 if !proptools.Bool(f.properties.Linker_config.Gen_linker_config) {
Spandan Das92631882024-10-28 22:49:38 +0000910 return
911 }
912
Spandan Das918191e2024-10-31 18:27:23 +0000913 provideModules, _ := f.getLibsForLinkerConfig(ctx)
Cole Faustfee27012024-12-13 14:10:31 -0800914 intermediateOutput := android.PathForModuleOut(ctx, "linker.config.pb")
915 linkerconfig.BuildLinkerConfig(ctx, android.PathsForModuleSrc(ctx, f.properties.Linker_config.Linker_config_srcs), provideModules, nil, intermediateOutput)
Spandan Das92631882024-10-28 22:49:38 +0000916 output := rebasedDir.Join(ctx, "etc", "linker.config.pb")
Cole Faustfee27012024-12-13 14:10:31 -0800917 builder.Command().Text("cp").Input(intermediateOutput).Output(output)
Spandan Das92631882024-10-28 22:49:38 +0000918
919 f.appendToEntry(ctx, output)
920}
921
Kiyoung Kim23be5bb2024-11-27 00:50:30 +0000922func (f *filesystem) ShouldUseVintfFragmentModuleOnly() bool {
923 return false
924}
925
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900926type partition interface {
927 PartitionType() string
928}
929
Cole Faust9a24d902024-03-18 15:38:12 -0700930func (f *filesystem) PartitionType() string {
931 return proptools.StringDefault(f.properties.Partition_type, "system")
932}
933
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900934var _ partition = (*filesystem)(nil)
935
Jiyong Park65c49f52020-11-24 14:23:26 +0900936var _ android.AndroidMkEntriesProvider = (*filesystem)(nil)
937
938// Implements android.AndroidMkEntriesProvider
939func (f *filesystem) AndroidMkEntries() []android.AndroidMkEntries {
940 return []android.AndroidMkEntries{android.AndroidMkEntries{
941 Class: "ETC",
942 OutputFile: android.OptionalPathForPath(f.output),
943 ExtraEntries: []android.AndroidMkExtraEntriesFunc{
Colin Crossaa255532020-07-03 13:18:24 -0700944 func(ctx android.AndroidMkExtraEntriesContext, entries *android.AndroidMkEntries) {
Colin Crossc68db4b2021-11-11 18:59:15 -0800945 entries.SetString("LOCAL_MODULE_PATH", f.installDir.String())
Jiyong Park65c49f52020-11-24 14:23:26 +0900946 entries.SetString("LOCAL_INSTALLED_MODULE_STEM", f.installFileName())
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900947 entries.SetString("LOCAL_FILESYSTEM_FILELIST", f.fileListFile.String())
Jiyong Park65c49f52020-11-24 14:23:26 +0900948 },
949 },
950 }}
Jiyong Park6f0f6882020-11-12 13:14:30 +0900951}
Jiyong Park12a719c2021-01-07 15:31:24 +0900952
953// Filesystem is the public interface for the filesystem struct. Currently, it's only for the apex
954// package to have access to the output file.
955type Filesystem interface {
956 android.Module
957 OutputPath() android.Path
Jiyong Park972e06c2021-03-15 23:32:49 +0900958
959 // Returns the output file that is signed by avbtool. If this module is not signed, returns
960 // nil.
961 SignedOutputPath() android.Path
Jiyong Park12a719c2021-01-07 15:31:24 +0900962}
963
964var _ Filesystem = (*filesystem)(nil)
965
966func (f *filesystem) OutputPath() android.Path {
967 return f.output
968}
Jiyong Park972e06c2021-03-15 23:32:49 +0900969
970func (f *filesystem) SignedOutputPath() android.Path {
971 if proptools.Bool(f.properties.Use_avb) {
972 return f.OutputPath()
973 }
974 return nil
975}
Jooyung Han0fbbc2b2022-03-25 12:35:46 +0900976
977// Filter the result of GatherPackagingSpecs to discard items targeting outside "system" partition.
978// Note that "apex" module installs its contents to "apex"(fake partition) as well
979// for symbol lookup by imitating "activated" paths.
980func (f *filesystem) gatherFilteredPackagingSpecs(ctx android.ModuleContext) map[string]android.PackagingSpec {
Inseob Kim3c0a0422024-11-05 17:21:37 +0900981 specs := f.PackagingBase.GatherPackagingSpecsWithFilterAndModifier(ctx, f.filesystemBuilder.FilterPackagingSpec, f.filesystemBuilder.ModifyPackagingSpec)
Jooyung Han0fbbc2b2022-03-25 12:35:46 +0900982 return specs
983}
Jooyung Han65f402b2022-04-21 14:24:04 +0900984
985func sha1sum(values []string) string {
986 h := sha256.New()
987 for _, value := range values {
988 io.WriteString(h, value)
989 }
990 return fmt.Sprintf("%x", h.Sum(nil))
991}
Jooyung Hane6067592023-03-16 13:11:17 +0900992
993// Base cc.UseCoverage
994
995var _ cc.UseCoverage = (*filesystem)(nil)
996
Colin Crosse1a85552024-06-14 12:17:37 -0700997func (*filesystem) IsNativeCoverageNeeded(ctx cc.IsNativeCoverageNeededContext) bool {
Jooyung Hane6067592023-03-16 13:11:17 +0900998 return ctx.Device() && ctx.DeviceConfig().NativeCoverageEnabled()
999}
Jiyong Parkf46b1af2024-04-05 18:13:33 +09001000
1001// android_filesystem_defaults
1002
1003type filesystemDefaults struct {
1004 android.ModuleBase
1005 android.DefaultsModuleBase
1006
Inseob Kim3c0a0422024-11-05 17:21:37 +09001007 properties FilesystemProperties
Jiyong Parkf46b1af2024-04-05 18:13:33 +09001008}
1009
1010// android_filesystem_defaults is a default module for android_filesystem and android_system_image
1011func filesystemDefaultsFactory() android.Module {
1012 module := &filesystemDefaults{}
1013 module.AddProperties(&module.properties)
1014 module.AddProperties(&android.PackagingProperties{})
1015 android.InitDefaultsModule(module)
1016 return module
1017}
1018
1019func (f *filesystemDefaults) PartitionType() string {
1020 return proptools.StringDefault(f.properties.Partition_type, "system")
1021}
1022
1023var _ partition = (*filesystemDefaults)(nil)
1024
1025func (f *filesystemDefaults) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1026 validatePartitionType(ctx, f)
1027}
Spandan Das918191e2024-10-31 18:27:23 +00001028
1029// getLibsForLinkerConfig returns
1030// 1. A list of libraries installed in this filesystem
1031// 2. A list of dep libraries _not_ installed in this filesystem
1032//
1033// `linkerconfig.BuildLinkerConfig` will convert these two to a linker.config.pb for the filesystem
1034// (1) will be added to --provideLibs if they are C libraries with a stable interface (has stubs)
1035// (2) will be added to --requireLibs if they are C libraries with a stable interface (has stubs)
1036func (f *filesystem) getLibsForLinkerConfig(ctx android.ModuleContext) ([]android.Module, []android.Module) {
1037 // we need "Module"s for packaging items
1038 modulesInPackageByModule := make(map[android.Module]bool)
1039 modulesInPackageByName := make(map[string]bool)
1040
1041 deps := f.gatherFilteredPackagingSpecs(ctx)
1042 ctx.WalkDeps(func(child, parent android.Module) bool {
1043 for _, ps := range android.OtherModuleProviderOrDefault(
1044 ctx, child, android.InstallFilesProvider).PackagingSpecs {
Spandan Dasecf667f2024-12-05 00:58:56 +00001045 if _, ok := deps[ps.RelPathInPackage()]; ok && ps.Partition() == f.PartitionType() {
Spandan Das918191e2024-10-31 18:27:23 +00001046 modulesInPackageByModule[child] = true
1047 modulesInPackageByName[child.Name()] = true
1048 return true
1049 }
1050 }
1051 return true
1052 })
1053
1054 provideModules := make([]android.Module, 0, len(modulesInPackageByModule))
1055 for mod := range modulesInPackageByModule {
1056 provideModules = append(provideModules, mod)
1057 }
1058
1059 var requireModules []android.Module
1060 ctx.WalkDeps(func(child, parent android.Module) bool {
1061 _, parentInPackage := modulesInPackageByModule[parent]
1062 _, childInPackageName := modulesInPackageByName[child.Name()]
1063
1064 // When parent is in the package, and child (or its variant) is not, this can be from an interface.
1065 if parentInPackage && !childInPackageName {
1066 requireModules = append(requireModules, child)
1067 }
1068 return true
1069 })
1070
1071 return provideModules, requireModules
1072}
Cole Faust26bdac52024-11-19 13:37:53 -08001073
1074// Checks that the given file doesn't exceed the given size, and will also print a warning
1075// if it's nearing the maximum size. Equivalent to assert-max-image-size in make:
1076// https://cs.android.com/android/platform/superproject/main/+/main:build/make/core/definitions.mk;l=3455;drc=993c4de29a02a6accd60ceaaee153307e1a18d10
1077func assertMaxImageSize(builder *android.RuleBuilder, image android.Path, maxSize int64, addAvbLater bool) {
1078 if addAvbLater {
1079 // The value 69632 is derived from MAX_VBMETA_SIZE + MAX_FOOTER_SIZE in avbtool.
1080 // Logic copied from make:
1081 // https://cs.android.com/android/platform/superproject/main/+/main:build/make/core/Makefile;l=228;drc=a6a0007ef24e16c0b79f439beac4a118416717e6
1082 maxSize -= 69632
1083 }
1084 cmd := builder.Command()
1085 cmd.Textf(`file="%s"; maxsize="%d";`+
1086 `total=$(stat -c "%%s" "$file" | tr -d '\n');`+
1087 `if [ "$total" -gt "$maxsize" ]; then `+
1088 ` echo "error: $file too large ($total > $maxsize)";`+
1089 ` false;`+
1090 `elif [ "$total" -gt $((maxsize - 32768)) ]; then `+
1091 ` echo "WARNING: $file approaching size limit ($total now; limit $maxsize)";`+
1092 `fi`,
1093 image, maxSize)
1094 cmd.Implicit(image)
1095}
Spandan Das71be42d2024-11-20 18:34:16 +00001096
1097// addAutogeneratedRroDeps walks the transitive closure of vendor and product partitions.
1098// It visits apps installed in system and system_ext partitions, and adds the autogenerated
1099// RRO modules to its own deps.
1100func addAutogeneratedRroDeps(ctx android.BottomUpMutatorContext) {
1101 f, ok := ctx.Module().(*filesystem)
1102 if !ok {
1103 return
1104 }
1105 thisPartition := f.PartitionType()
1106 if thisPartition != "vendor" && thisPartition != "product" {
Cole Faust34592c02024-12-13 11:20:24 -08001107 if f.properties.Android_filesystem_deps.System != nil {
1108 ctx.PropertyErrorf("android_filesystem_deps.system", "only vendor or product partitions can use android_filesystem_deps")
1109 }
1110 if f.properties.Android_filesystem_deps.System_ext != nil {
1111 ctx.PropertyErrorf("android_filesystem_deps.system_ext", "only vendor or product partitions can use android_filesystem_deps")
1112 }
Spandan Das71be42d2024-11-20 18:34:16 +00001113 return
1114 }
1115 ctx.WalkDeps(func(child, parent android.Module) bool {
1116 depTag := ctx.OtherModuleDependencyTag(child)
1117 if parent.Name() == f.Name() && depTag != interPartitionDependencyTag {
1118 return false // This is a module listed in deps of vendor/product filesystem
1119 }
1120 if vendorOverlay := java.AutogeneratedRroModuleName(ctx, child.Name(), "vendor"); ctx.OtherModuleExists(vendorOverlay) && thisPartition == "vendor" {
1121 ctx.AddFarVariationDependencies(nil, dependencyTagWithVisibilityEnforcementBypass, vendorOverlay)
1122 }
1123 if productOverlay := java.AutogeneratedRroModuleName(ctx, child.Name(), "product"); ctx.OtherModuleExists(productOverlay) && thisPartition == "product" {
1124 ctx.AddFarVariationDependencies(nil, dependencyTagWithVisibilityEnforcementBypass, productOverlay)
1125 }
1126 return true
1127 })
1128}