blob: b7a3adc8bfaa076fc4369a5b9423f8d7ddee685e [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
Cole Fauste1676122024-12-03 17:32:25 -0800124 // Whether or not to use forward-error-correction codes when signing with AVB. Defaults to true.
125 Use_fec *bool
126
Nikita Ioffe2c8cdc62024-03-27 22:19:30 +0000127 // The index used to prevent rollback of the image. Only used if use_avb is true.
128 Rollback_index *int64
129
Jiyong Parkac4076d2021-03-15 23:21:30 +0900130 // Name of the partition stored in vbmeta desc. Defaults to the name of this module.
131 Partition_name *string
132
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000133 // Type of the filesystem. Currently, ext4, erofs, cpio, and compressed_cpio are supported. Default
Jiyong Park837cdb22021-02-05 00:17:14 +0900134 // is ext4.
Jiyong Park11a65972021-02-01 21:09:38 +0900135 Type *string
Inseob Kimcc8e5362021-02-03 14:05:24 +0900136
Cole Faust9a24d902024-03-18 15:38:12 -0700137 // Identifies which partition this is for //visibility:any_system_image (and others) visibility
138 // checks, and will be used in the future for API surface checks.
139 Partition_type *string
140
Cole Faust0d467052024-12-04 17:19:19 -0800141 // file_contexts file to make image. Currently, only ext4 is supported. These file contexts
142 // will be compiled with sefcontext_compile
Inseob Kimcc8e5362021-02-03 14:05:24 +0900143 File_contexts *string `android:"path"`
Inseob Kim2ce1b5d2021-02-15 17:01:04 +0900144
Cole Faust0d467052024-12-04 17:19:19 -0800145 // The selinux file contexts, after having already run them through sefcontext_compile
146 Precompiled_file_contexts *string `android:"path"`
147
Inseob Kim2ce1b5d2021-02-15 17:01:04 +0900148 // Base directory relative to root, to which deps are installed, e.g. "system". Default is "."
149 // (root).
150 Base_dir *string
Inseob Kim14199b02021-02-09 21:18:31 +0900151
152 // Directories to be created under root. e.g. /dev, /proc, etc.
Cole Faustd9c6a5b2024-05-21 14:54:00 -0700153 Dirs proptools.Configurable[[]string]
Inseob Kim14199b02021-02-09 21:18:31 +0900154
155 // Symbolic links to be created under root with "ln -sf <target> <name>".
Spandan Das69464c32024-10-25 20:08:06 +0000156 Symlinks []SymlinkDefinition
Jooyung Han65f402b2022-04-21 14:24:04 +0900157
158 // Seconds since unix epoch to override timestamps of file entries
159 Fake_timestamp *string
160
161 // When set, passed to mkuserimg_mke2fs --mke2fs_uuid & --mke2fs_hash_seed.
162 // Otherwise, they'll be set as random which might cause indeterministic build output.
163 Uuid *string
Inseob Kim376d72f2023-11-01 15:40:25 +0900164
165 // Mount point for this image. Default is "/"
166 Mount_point *string
Cole Faust4a2a7c92024-03-12 12:44:40 -0700167
168 // If set to the name of a partition ("system", "vendor", etc), this filesystem module
169 // will also include the contents of the make-built staging directories. If any soong
170 // modules would be installed to the same location as a make module, they will overwrite
171 // the make version.
172 Include_make_built_files string
Inseob Kim53391842024-03-29 17:44:07 +0900173
Inseob Kimb7b84572024-04-30 10:51:47 +0900174 // When set, builds etc/event-log-tags file by merging logtags from all dependencies.
175 // Default is false
176 Build_logtags *bool
177
Justin Yun74f3f302024-05-07 14:32:14 +0900178 // Install aconfig_flags.pb file for the modules installed in this partition.
179 Gen_aconfig_flags_pb *bool
180
Inseob Kim53391842024-03-29 17:44:07 +0900181 Fsverity fsverityProperties
Cole Faust92ccbe22024-10-03 14:38:37 -0700182
183 // If this property is set to true, the filesystem will call ctx.UncheckedModule(), causing
184 // it to not be built on checkbuilds. Used for the automatic migration from make to soong
185 // build modules, where we want to emit some not-yet-working filesystems and we don't want them
186 // to be built.
187 Unchecked_module *bool `blueprint:"mutated"`
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000188
189 Erofs ErofsProperties
Jihoon Kang0d545b82024-10-11 00:21:57 +0000190
mrziwang1a6291f2024-11-07 14:29:25 -0800191 F2fs F2fsProperties
192
Spandan Das2047a4c2024-11-11 21:24:58 +0000193 Linker_config LinkerConfigProperties
Spandan Das92631882024-10-28 22:49:38 +0000194
Jihoon Kang0d545b82024-10-11 00:21:57 +0000195 // Determines if the module is auto-generated from Soong or not. If the module is
196 // auto-generated, its deps are exempted from visibility enforcement.
197 Is_auto_generated *bool
Jihoon Kang6c03c8e2024-11-18 21:30:22 +0000198
199 // Path to the dev nodes description file. This is only needed for building the ramdisk
200 // partition and should not be explicitly specified.
201 Dev_nodes_description_file *string `android:"path" blueprint:"mutated"`
Spandan Das71be42d2024-11-20 18:34:16 +0000202
203 // Additional dependencies used for building android products
204 Android_filesystem_deps AndroidFilesystemDeps
205}
206
207type AndroidFilesystemDeps struct {
208 System *string
209 System_ext *string
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000210}
211
212// Additional properties required to generate erofs FS partitions.
213type ErofsProperties struct {
214 // Compressor and Compression level passed to mkfs.erofs. e.g. (lz4hc,9)
215 // Please see external/erofs-utils/README for complete documentation.
216 Compressor *string
217
218 // Used as --compress-hints for mkfs.erofs
219 Compress_hints *string `android:"path"`
220
221 Sparse *bool
Jiyong Park71baa762021-01-18 21:11:03 +0900222}
223
mrziwang1a6291f2024-11-07 14:29:25 -0800224// Additional properties required to generate f2fs FS partitions.
225type F2fsProperties struct {
226 Sparse *bool
227}
228
Spandan Das173256b2024-10-31 19:59:30 +0000229type LinkerConfigProperties struct {
230
231 // Build a linker.config.pb file
232 Gen_linker_config *bool
233
234 // List of files (in .json format) that will be converted to a linker config file (in .pb format).
235 // The linker config file be installed in the filesystem at /etc/linker.config.pb
236 Linker_config_srcs []string `android:"path"`
237}
238
Jiyong Park65c49f52020-11-24 14:23:26 +0900239// android_filesystem packages a set of modules and their transitive dependencies into a filesystem
240// image. The filesystem images are expected to be mounted in the target device, which means the
241// modules in the filesystem image are built for the target device (i.e. Android, not Linux host).
242// The modules are placed in the filesystem image just like they are installed to the ordinary
243// partitions like system.img. For example, cc_library modules are placed under ./lib[64] directory.
Cole Faust92ccbe22024-10-03 14:38:37 -0700244func FilesystemFactory() android.Module {
Jiyong Park6f0f6882020-11-12 13:14:30 +0900245 module := &filesystem{}
Kiyoung Kim67118212024-11-07 13:23:44 +0900246 module.filesystemBuilder = module
Cole Faust2cfe6962024-09-17 11:31:14 -0700247 initFilesystemModule(module, module)
Jiyong Parkfa616132021-04-20 11:36:40 +0900248 return module
249}
250
Cole Faust2cfe6962024-09-17 11:31:14 -0700251func initFilesystemModule(module android.DefaultableModule, filesystemModule *filesystem) {
252 module.AddProperties(&filesystemModule.properties)
253 android.InitPackageModule(filesystemModule)
254 filesystemModule.PackagingBase.DepsCollectFirstTargetOnly = true
Jihoon Kang79196c52024-10-30 18:49:47 +0000255 filesystemModule.PackagingBase.AllowHighPriorityDeps = true
Jiyong Park6f0f6882020-11-12 13:14:30 +0900256 android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900257 android.InitDefaultableModule(module)
Jihoon Kang6c03c8e2024-11-18 21:30:22 +0000258
259 android.AddLoadHook(module, func(ctx android.LoadHookContext) {
260 filesystemModule.setDevNodesDescriptionProp()
261 })
Jiyong Park6f0f6882020-11-12 13:14:30 +0900262}
263
Jihoon Kang0d545b82024-10-11 00:21:57 +0000264type depTag struct {
Jiyong Park12a719c2021-01-07 15:31:24 +0900265 blueprint.BaseDependencyTag
Jooyung Han092ef812021-03-10 15:40:34 +0900266 android.PackagingItemAlwaysDepTag
Jihoon Kang0d545b82024-10-11 00:21:57 +0000267}
268
269var dependencyTag = depTag{}
270
271type depTagWithVisibilityEnforcementBypass struct {
272 depTag
273}
274
Spandan Das71be42d2024-11-20 18:34:16 +0000275type interPartitionDepTag struct {
276 blueprint.BaseDependencyTag
277}
278
279var interPartitionDependencyTag = interPartitionDepTag{}
280
Jihoon Kang0d545b82024-10-11 00:21:57 +0000281var _ android.ExcludeFromVisibilityEnforcementTag = (*depTagWithVisibilityEnforcementBypass)(nil)
282
283func (t depTagWithVisibilityEnforcementBypass) ExcludeFromVisibilityEnforcement() {}
284
285var dependencyTagWithVisibilityEnforcementBypass = depTagWithVisibilityEnforcementBypass{}
Jiyong Park65b62242020-11-25 12:44:59 +0900286
Jihoon Kang6c03c8e2024-11-18 21:30:22 +0000287// ramdiskDevNodesDescription is the name of the filegroup module that provides the file that
288// contains the description of dev nodes added to the CPIO archive for the ramdisk partition.
289const ramdiskDevNodesDescription = "ramdisk_node_list"
290
291func (f *filesystem) setDevNodesDescriptionProp() {
292 if proptools.String(f.properties.Partition_name) == "ramdisk" {
293 f.properties.Dev_nodes_description_file = proptools.StringPtr(":" + ramdiskDevNodesDescription)
294 }
295}
296
Jiyong Park6f0f6882020-11-12 13:14:30 +0900297func (f *filesystem) DepsMutator(ctx android.BottomUpMutatorContext) {
Jihoon Kang0d545b82024-10-11 00:21:57 +0000298 if proptools.Bool(f.properties.Is_auto_generated) {
299 f.AddDeps(ctx, dependencyTagWithVisibilityEnforcementBypass)
300 } else {
301 f.AddDeps(ctx, dependencyTag)
302 }
Spandan Das71be42d2024-11-20 18:34:16 +0000303 if f.properties.Android_filesystem_deps.System != nil {
304 ctx.AddDependency(ctx.Module(), interPartitionDependencyTag, proptools.String(f.properties.Android_filesystem_deps.System))
305 }
306 if f.properties.Android_filesystem_deps.System_ext != nil {
307 ctx.AddDependency(ctx.Module(), interPartitionDependencyTag, proptools.String(f.properties.Android_filesystem_deps.System_ext))
308 }
Jiyong Park6f0f6882020-11-12 13:14:30 +0900309}
310
Jiyong Park11a65972021-02-01 21:09:38 +0900311type fsType int
312
313const (
314 ext4Type fsType = iota
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000315 erofsType
mrziwang1a6291f2024-11-07 14:29:25 -0800316 f2fsType
Jiyong Park11a65972021-02-01 21:09:38 +0900317 compressedCpioType
Jiyong Park837cdb22021-02-05 00:17:14 +0900318 cpioType // uncompressed
Jiyong Park11a65972021-02-01 21:09:38 +0900319 unknown
320)
321
Spandan Das7a46f6c2024-10-14 18:41:18 +0000322func (fs fsType) IsUnknown() bool {
323 return fs == unknown
324}
325
Cole Faust92ccbe22024-10-03 14:38:37 -0700326type FilesystemInfo struct {
327 // A text file containing the list of paths installed on the partition.
328 FileListFile android.Path
329}
330
331var FilesystemProvider = blueprint.NewProvider[FilesystemInfo]()
332
Spandan Das7a46f6c2024-10-14 18:41:18 +0000333func GetFsTypeFromString(ctx android.EarlyModuleContext, typeStr string) fsType {
Jiyong Park11a65972021-02-01 21:09:38 +0900334 switch typeStr {
335 case "ext4":
336 return ext4Type
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000337 case "erofs":
338 return erofsType
mrziwang1a6291f2024-11-07 14:29:25 -0800339 case "f2fs":
340 return f2fsType
Jiyong Park11a65972021-02-01 21:09:38 +0900341 case "compressed_cpio":
342 return compressedCpioType
Jiyong Park837cdb22021-02-05 00:17:14 +0900343 case "cpio":
344 return cpioType
Jiyong Park11a65972021-02-01 21:09:38 +0900345 default:
Jiyong Park11a65972021-02-01 21:09:38 +0900346 return unknown
347 }
348}
349
Spandan Das7a46f6c2024-10-14 18:41:18 +0000350func (f *filesystem) fsType(ctx android.ModuleContext) fsType {
351 typeStr := proptools.StringDefault(f.properties.Type, "ext4")
352 fsType := GetFsTypeFromString(ctx, typeStr)
353 if fsType == unknown {
354 ctx.PropertyErrorf("type", "%q not supported", typeStr)
355 }
356 return fsType
357}
358
Jiyong Park65c49f52020-11-24 14:23:26 +0900359func (f *filesystem) installFileName() string {
360 return f.BaseModuleName() + ".img"
361}
362
Inseob Kim53391842024-03-29 17:44:07 +0900363func (f *filesystem) partitionName() string {
364 return proptools.StringDefault(f.properties.Partition_name, f.Name())
365}
366
Kiyoung Kim67118212024-11-07 13:23:44 +0900367func (f *filesystem) FilterPackagingSpec(ps android.PackagingSpec) bool {
Jiyong Park7e7d4af2024-05-01 12:36:10 +0000368 // Filesystem module respects the installation semantic. A PackagingSpec from a module with
369 // IsSkipInstall() is skipped.
Cole Faust76a6e952024-11-07 16:56:45 -0800370 if ps.SkipInstall() {
371 return false
Spandan Das6d056502024-10-21 15:40:32 +0000372 }
Cole Faust76a6e952024-11-07 16:56:45 -0800373 if proptools.Bool(f.properties.Is_auto_generated) { // TODO (spandandas): Remove this.
374 pt := f.PartitionType()
Cole Faustc88cff12024-11-12 13:24:05 -0800375 return ps.Partition() == pt || strings.HasPrefix(ps.Partition(), pt+"/")
Cole Faust76a6e952024-11-07 16:56:45 -0800376 }
377 return true
Jiyong Park7e7d4af2024-05-01 12:36:10 +0000378}
379
Inseob Kim3c0a0422024-11-05 17:21:37 +0900380func (f *filesystem) ModifyPackagingSpec(ps *android.PackagingSpec) {
Cole Faustc88cff12024-11-12 13:24:05 -0800381 // Sometimes, android.modulePartition() returns a path with >1 path components.
382 // This makes the partition field of packagingSpecs have multiple components, like
383 // "system/product". Right now, the filesystem module doesn't look at the partition field
384 // when deciding what path to install the file under, only the RelPathInPackage field, so
385 // we move the later path components from partition to relPathInPackage. This should probably
386 // be revisited in the future.
387 prefix := f.PartitionType() + "/"
388 if strings.HasPrefix(ps.Partition(), prefix) {
389 subPartition := strings.TrimPrefix(ps.Partition(), prefix)
390 ps.SetPartition(f.PartitionType())
391 ps.SetRelPathInPackage(filepath.Join(subPartition, ps.RelPathInPackage()))
392 }
Inseob Kim3c0a0422024-11-05 17:21:37 +0900393}
394
Jiyong Park6f0f6882020-11-12 13:14:30 +0900395var pctx = android.NewPackageContext("android/soong/filesystem")
396
397func (f *filesystem) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900398 validatePartitionType(ctx, f)
Kiyoung Kim23be5bb2024-11-27 00:50:30 +0000399 if f.filesystemBuilder.ShouldUseVintfFragmentModuleOnly() {
400 f.validateVintfFragments(ctx)
401 }
Jiyong Park11a65972021-02-01 21:09:38 +0900402 switch f.fsType(ctx) {
mrziwang1a6291f2024-11-07 14:29:25 -0800403 case ext4Type, erofsType, f2fsType:
Jiyong Park11a65972021-02-01 21:09:38 +0900404 f.output = f.buildImageUsingBuildImage(ctx)
405 case compressedCpioType:
Jiyong Park837cdb22021-02-05 00:17:14 +0900406 f.output = f.buildCpioImage(ctx, true)
407 case cpioType:
408 f.output = f.buildCpioImage(ctx, false)
Jiyong Park11a65972021-02-01 21:09:38 +0900409 default:
410 return
411 }
412
413 f.installDir = android.PathForModuleInstall(ctx, "etc")
414 ctx.InstallFile(f.installDir, f.installFileName(), f.output)
mrziwang555d1332024-06-07 11:15:33 -0700415 ctx.SetOutputFiles([]android.Path{f.output}, "")
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900416
Cole Faust4e9f5922024-11-13 16:09:23 -0800417 fileListFile := android.PathForModuleOut(ctx, "fileList")
418 android.WriteFileRule(ctx, fileListFile, f.installedFilesList())
Cole Faust92ccbe22024-10-03 14:38:37 -0700419
420 android.SetProvider(ctx, FilesystemProvider, FilesystemInfo{
Cole Faust4e9f5922024-11-13 16:09:23 -0800421 FileListFile: fileListFile,
Cole Faust92ccbe22024-10-03 14:38:37 -0700422 })
Cole Faust4e9f5922024-11-13 16:09:23 -0800423 f.fileListFile = fileListFile
Cole Faust92ccbe22024-10-03 14:38:37 -0700424
425 if proptools.Bool(f.properties.Unchecked_module) {
426 ctx.UncheckedModule()
427 }
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900428}
429
Kiyoung Kim23be5bb2024-11-27 00:50:30 +0000430func (f *filesystem) validateVintfFragments(ctx android.ModuleContext) {
431 visitedModule := map[string]bool{}
432 packagingSpecs := f.gatherFilteredPackagingSpecs(ctx)
433
434 moduleInFileSystem := func(mod android.Module) bool {
435 for _, ps := range android.OtherModuleProviderOrDefault(
436 ctx, mod, android.InstallFilesProvider).PackagingSpecs {
437 if _, ok := packagingSpecs[ps.RelPathInPackage()]; ok {
438 return true
439 }
440 }
441 return false
442 }
443
444 ctx.WalkDeps(func(child, parent android.Module) bool {
445 if visitedModule[child.Name()] {
446 return false
447 }
448 if !moduleInFileSystem(child) {
449 visitedModule[child.Name()] = true
450 return true
451 }
452 if vintfFragments := child.VintfFragments(ctx); vintfFragments != nil {
453 ctx.PropertyErrorf(
454 "vintf_fragments",
455 "Module %s is referenced by soong-defined filesystem %s with property vintf_fragments(%s) in use."+
456 " Use vintf_fragment_modules property instead.",
457 child.Name(),
458 f.BaseModuleName(),
459 strings.Join(vintfFragments, ", "),
460 )
461 }
462 visitedModule[child.Name()] = true
463 return true
464 })
465}
466
Cole Faust4e9f5922024-11-13 16:09:23 -0800467func (f *filesystem) appendToEntry(ctx android.ModuleContext, installedFile android.Path) {
Spandan Das420e16a2024-12-11 18:10:52 +0000468 partitionBaseDir := android.PathForModuleOut(ctx, f.rootDirString(), proptools.String(f.properties.Base_dir)).String() + "/"
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900469
470 relPath, inTargetPartition := strings.CutPrefix(installedFile.String(), partitionBaseDir)
471 if inTargetPartition {
472 f.entries = append(f.entries, relPath)
473 }
474}
475
476func (f *filesystem) installedFilesList() string {
477 installedFilePaths := android.FirstUniqueStrings(f.entries)
478 slices.Sort(installedFilePaths)
479
480 return strings.Join(installedFilePaths, "\n")
Jiyong Park11a65972021-02-01 21:09:38 +0900481}
482
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900483func validatePartitionType(ctx android.ModuleContext, p partition) {
484 if !android.InList(p.PartitionType(), validPartitions) {
485 ctx.PropertyErrorf("partition_type", "partition_type must be one of %s, found: %s", validPartitions, p.PartitionType())
486 }
487
488 ctx.VisitDirectDepsWithTag(android.DefaultsDepTag, func(m android.Module) {
489 if fdm, ok := m.(*filesystemDefaults); ok {
490 if p.PartitionType() != fdm.PartitionType() {
491 ctx.PropertyErrorf("partition_type",
492 "%s doesn't match with the partition type %s of the filesystem default module %s",
493 p.PartitionType(), fdm.PartitionType(), m.Name())
494 }
495 }
496 })
497}
498
Cole Faust3b806d32024-03-11 15:15:03 -0700499// Copy extra files/dirs that are not from the `deps` property to `rootDir`, checking for conflicts with files
500// already in `rootDir`.
501func (f *filesystem) buildNonDepsFiles(ctx android.ModuleContext, builder *android.RuleBuilder, rootDir android.OutputPath) {
Inseob Kim14199b02021-02-09 21:18:31 +0900502 // create dirs and symlinks
Cole Faustd9c6a5b2024-05-21 14:54:00 -0700503 for _, dir := range f.properties.Dirs.GetOrDefault(ctx, nil) {
Inseob Kim14199b02021-02-09 21:18:31 +0900504 // OutputPath.Join verifies dir
505 builder.Command().Text("mkdir -p").Text(rootDir.Join(ctx, dir).String())
506 }
507
508 for _, symlink := range f.properties.Symlinks {
509 name := strings.TrimSpace(proptools.String(symlink.Name))
510 target := strings.TrimSpace(proptools.String(symlink.Target))
511
512 if name == "" {
513 ctx.PropertyErrorf("symlinks", "Name can't be empty")
514 continue
515 }
516
517 if target == "" {
518 ctx.PropertyErrorf("symlinks", "Target can't be empty")
519 continue
520 }
521
522 // OutputPath.Join verifies name. don't need to verify target.
523 dst := rootDir.Join(ctx, name)
Cole Faust3b806d32024-03-11 15:15:03 -0700524 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 +0900525 builder.Command().Text("mkdir -p").Text(filepath.Dir(dst.String()))
526 builder.Command().Text("ln -sf").Text(proptools.ShellEscape(target)).Text(dst.String())
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900527 f.appendToEntry(ctx, dst)
Inseob Kim14199b02021-02-09 21:18:31 +0900528 }
Inseob Kim2ce1b5d2021-02-15 17:01:04 +0900529}
530
Inseob Kim33f95a92024-07-11 15:44:49 +0900531func (f *filesystem) copyPackagingSpecs(ctx android.ModuleContext, builder *android.RuleBuilder, specs map[string]android.PackagingSpec, rootDir, rebasedDir android.WritablePath) []string {
532 rootDirSpecs := make(map[string]android.PackagingSpec)
533 rebasedDirSpecs := make(map[string]android.PackagingSpec)
534
535 for rel, spec := range specs {
536 if spec.Partition() == "root" {
537 rootDirSpecs[rel] = spec
538 } else {
539 rebasedDirSpecs[rel] = spec
540 }
541 }
542
543 dirsToSpecs := make(map[android.WritablePath]map[string]android.PackagingSpec)
544 dirsToSpecs[rootDir] = rootDirSpecs
545 dirsToSpecs[rebasedDir] = rebasedDirSpecs
546
547 return f.CopySpecsToDirs(ctx, builder, dirsToSpecs)
548}
549
Justin Yun34baa2e2024-08-30 21:11:33 +0900550func (f *filesystem) copyFilesToProductOut(ctx android.ModuleContext, builder *android.RuleBuilder, rebasedDir android.OutputPath) {
Justin Yun2cc42502024-09-11 14:10:20 +0900551 if f.Name() != ctx.Config().SoongDefinedSystemImage() {
Justin Yun34baa2e2024-08-30 21:11:33 +0900552 return
553 }
554 installPath := android.PathForModuleInPartitionInstall(ctx, f.partitionName())
555 builder.Command().Textf("cp -prf %s/* %s", rebasedDir, installPath)
556}
557
Spandan Das420e16a2024-12-11 18:10:52 +0000558func (f *filesystem) rootDirString() string {
559 return f.partitionName()
560}
561
Cole Faust4e9f5922024-11-13 16:09:23 -0800562func (f *filesystem) buildImageUsingBuildImage(ctx android.ModuleContext) android.Path {
Spandan Das420e16a2024-12-11 18:10:52 +0000563 rootDir := android.PathForModuleOut(ctx, f.rootDirString()).OutputPath
Cole Faust3b806d32024-03-11 15:15:03 -0700564 rebasedDir := rootDir
565 if f.properties.Base_dir != nil {
566 rebasedDir = rootDir.Join(ctx, *f.properties.Base_dir)
567 }
568 builder := android.NewRuleBuilder(pctx, ctx)
569 // Wipe the root dir to get rid of leftover files from prior builds
570 builder.Command().Textf("rm -rf %s && mkdir -p %s", rootDir, rootDir)
Inseob Kim53391842024-03-29 17:44:07 +0900571 specs := f.gatherFilteredPackagingSpecs(ctx)
Inseob Kim33f95a92024-07-11 15:44:49 +0900572 f.entries = f.copyPackagingSpecs(ctx, builder, specs, rootDir, rebasedDir)
Cole Faust3b806d32024-03-11 15:15:03 -0700573
574 f.buildNonDepsFiles(ctx, builder, rootDir)
Cole Faust4a2a7c92024-03-12 12:44:40 -0700575 f.addMakeBuiltFiles(ctx, builder, rootDir)
Inseob Kim53391842024-03-29 17:44:07 +0900576 f.buildFsverityMetadataFiles(ctx, builder, specs, rootDir, rebasedDir)
Inseob Kimb7b84572024-04-30 10:51:47 +0900577 f.buildEventLogtagsFile(ctx, builder, rebasedDir)
Justin Yun74f3f302024-05-07 14:32:14 +0900578 f.buildAconfigFlagsFiles(ctx, builder, specs, rebasedDir)
Kiyoung Kim67118212024-11-07 13:23:44 +0900579 f.filesystemBuilder.BuildLinkerConfigFile(ctx, builder, rebasedDir)
Justin Yun34baa2e2024-08-30 21:11:33 +0900580 f.copyFilesToProductOut(ctx, builder, rebasedDir)
Jiyong Park6f0f6882020-11-12 13:14:30 +0900581
Nikita Ioffe519015f2022-12-23 15:36:29 +0000582 // run host_init_verifier
583 // Ideally we should have a concept of pluggable linters that verify the generated image.
584 // While such concept is not implement this will do.
585 // TODO(b/263574231): substitute with pluggable linter.
586 builder.Command().
587 BuiltTool("host_init_verifier").
588 FlagWithArg("--out_system=", rootDir.String()+"/system")
589
Jiyong Park72678312021-01-18 17:29:49 +0900590 propFile, toolDeps := f.buildPropFile(ctx)
Cole Fauste1676122024-12-03 17:32:25 -0800591
592 // Most of the time, if build_image were to call a host tool, it accepts the path to the
593 // host tool in a field in the prop file. However, it doesn't have that option for fec, which
594 // it expects to just be on the PATH. Add fec to the PATH.
595 fec := ctx.Config().HostToolPath(ctx, "fec")
596 pathToolDirs := []string{filepath.Dir(fec.String())}
597
Cole Faust4e9f5922024-11-13 16:09:23 -0800598 output := android.PathForModuleOut(ctx, f.installFileName())
Cole Fauste1676122024-12-03 17:32:25 -0800599 builder.Command().
600 Textf("PATH=%s:$PATH", strings.Join(pathToolDirs, ":")).
601 BuiltTool("build_image").
Jiyong Park6f0f6882020-11-12 13:14:30 +0900602 Text(rootDir.String()). // input directory
603 Input(propFile).
Jiyong Park72678312021-01-18 17:29:49 +0900604 Implicits(toolDeps).
Cole Fauste1676122024-12-03 17:32:25 -0800605 Implicit(fec).
Jiyong Park11a65972021-02-01 21:09:38 +0900606 Output(output).
Jiyong Park6f0f6882020-11-12 13:14:30 +0900607 Text(rootDir.String()) // directory where to find fs_config_files|dirs
608
609 // rootDir is not deleted. Might be useful for quick inspection.
Colin Crossf1a035e2020-11-16 17:32:30 -0800610 builder.Build("build_filesystem_image", fmt.Sprintf("Creating filesystem %s", f.BaseModuleName()))
Jiyong Park65c49f52020-11-24 14:23:26 +0900611
Jiyong Park11a65972021-02-01 21:09:38 +0900612 return output
Jiyong Park65c49f52020-11-24 14:23:26 +0900613}
614
Cole Faust4e9f5922024-11-13 16:09:23 -0800615func (f *filesystem) buildFileContexts(ctx android.ModuleContext) android.Path {
Inseob Kimcc8e5362021-02-03 14:05:24 +0900616 builder := android.NewRuleBuilder(pctx, ctx)
617 fcBin := android.PathForModuleOut(ctx, "file_contexts.bin")
618 builder.Command().BuiltTool("sefcontext_compile").
619 FlagWithOutput("-o ", fcBin).
620 Input(android.PathForModuleSrc(ctx, proptools.String(f.properties.File_contexts)))
621 builder.Build("build_filesystem_file_contexts", fmt.Sprintf("Creating filesystem file contexts for %s", f.BaseModuleName()))
Cole Faust4e9f5922024-11-13 16:09:23 -0800622 return fcBin
Inseob Kimcc8e5362021-02-03 14:05:24 +0900623}
624
Jooyung Han65f402b2022-04-21 14:24:04 +0900625// Calculates avb_salt from entry list (sorted) for deterministic output.
626func (f *filesystem) salt() string {
627 return sha1sum(f.entries)
628}
629
Cole Faust4e9f5922024-11-13 16:09:23 -0800630func (f *filesystem) buildPropFile(ctx android.ModuleContext) (android.Path, android.Paths) {
Jiyong Park72678312021-01-18 17:29:49 +0900631 var deps android.Paths
Cole Faustcec230a2024-03-07 15:51:12 -0800632 var propFileString strings.Builder
Jiyong Park72678312021-01-18 17:29:49 +0900633 addStr := func(name string, value string) {
Cole Faustcec230a2024-03-07 15:51:12 -0800634 propFileString.WriteString(name)
635 propFileString.WriteRune('=')
636 propFileString.WriteString(value)
637 propFileString.WriteRune('\n')
Jiyong Park72678312021-01-18 17:29:49 +0900638 }
639 addPath := func(name string, path android.Path) {
Cole Faustcec230a2024-03-07 15:51:12 -0800640 addStr(name, path.String())
Jiyong Park72678312021-01-18 17:29:49 +0900641 deps = append(deps, path)
642 }
643
Jiyong Park11a65972021-02-01 21:09:38 +0900644 // Type string that build_image.py accepts.
645 fsTypeStr := func(t fsType) string {
646 switch t {
Spandan Das94668822024-10-09 20:51:33 +0000647 // TODO(372522486): add more types like f2fs, erofs, etc.
Jiyong Park11a65972021-02-01 21:09:38 +0900648 case ext4Type:
649 return "ext4"
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000650 case erofsType:
651 return "erofs"
mrziwang1a6291f2024-11-07 14:29:25 -0800652 case f2fsType:
653 return "f2fs"
Jiyong Park11a65972021-02-01 21:09:38 +0900654 }
655 panic(fmt.Errorf("unsupported fs type %v", t))
656 }
657
658 addStr("fs_type", fsTypeStr(f.fsType(ctx)))
Inseob Kim376d72f2023-11-01 15:40:25 +0900659 addStr("mount_point", proptools.StringDefault(f.properties.Mount_point, "/"))
Jiyong Park72678312021-01-18 17:29:49 +0900660 addStr("use_dynamic_partition_size", "true")
661 addPath("ext_mkuserimg", ctx.Config().HostToolPath(ctx, "mkuserimg_mke2fs"))
662 // b/177813163 deps of the host tools have to be added. Remove this.
663 for _, t := range []string{"mke2fs", "e2fsdroid", "tune2fs"} {
664 deps = append(deps, ctx.Config().HostToolPath(ctx, t))
665 }
666
Jiyong Park71baa762021-01-18 21:11:03 +0900667 if proptools.Bool(f.properties.Use_avb) {
668 addStr("avb_hashtree_enable", "true")
669 addPath("avb_avbtool", ctx.Config().HostToolPath(ctx, "avbtool"))
670 algorithm := proptools.StringDefault(f.properties.Avb_algorithm, "SHA256_RSA4096")
671 addStr("avb_algorithm", algorithm)
Cole Fauste1676122024-12-03 17:32:25 -0800672 if f.properties.Avb_private_key != nil {
673 key := android.PathForModuleSrc(ctx, *f.properties.Avb_private_key)
674 addPath("avb_key_path", key)
675 }
Inseob Kim53391842024-03-29 17:44:07 +0900676 addStr("partition_name", f.partitionName())
Cole Fauste1676122024-12-03 17:32:25 -0800677 avb_add_hashtree_footer_args := ""
678 if !proptools.BoolDefault(f.properties.Use_fec, true) {
679 avb_add_hashtree_footer_args += " --do_not_generate_fec"
680 }
Shikha Panware6f30632022-12-21 12:54:45 +0000681 if hashAlgorithm := proptools.String(f.properties.Avb_hash_algorithm); hashAlgorithm != "" {
682 avb_add_hashtree_footer_args += " --hash_algorithm " + hashAlgorithm
683 }
Nikita Ioffe2c8cdc62024-03-27 22:19:30 +0000684 if f.properties.Rollback_index != nil {
685 rollbackIndex := proptools.Int(f.properties.Rollback_index)
686 if rollbackIndex < 0 {
687 ctx.PropertyErrorf("rollback_index", "Rollback index must be non-negative")
688 }
689 avb_add_hashtree_footer_args += " --rollback_index " + strconv.Itoa(rollbackIndex)
690 }
Cole Fauste1676122024-12-03 17:32:25 -0800691 avb_add_hashtree_footer_args += fmt.Sprintf(" --prop com.android.build.%s.os_version:%s", f.partitionName(), ctx.Config().PlatformVersionLastStable())
692 avb_add_hashtree_footer_args += fmt.Sprintf(" --prop com.android.build.%s.fingerprint:{CONTENTS_OF:%s}", f.partitionName(), ctx.Config().BuildFingerprintFile(ctx))
693 avb_add_hashtree_footer_args += fmt.Sprintf(" --prop com.android.build.%s.security_patch:%s", f.partitionName(), ctx.Config().PlatformSecurityPatch())
Shikha Panware6f30632022-12-21 12:54:45 +0000694 addStr("avb_add_hashtree_footer_args", avb_add_hashtree_footer_args)
Jooyung Han65f402b2022-04-21 14:24:04 +0900695 addStr("avb_salt", f.salt())
Jiyong Park71baa762021-01-18 21:11:03 +0900696 }
697
Cole Faust0d467052024-12-04 17:19:19 -0800698 if f.properties.File_contexts != nil && f.properties.Precompiled_file_contexts != nil {
699 ctx.ModuleErrorf("file_contexts and precompiled_file_contexts cannot both be set")
700 } else if f.properties.File_contexts != nil {
Inseob Kimcc8e5362021-02-03 14:05:24 +0900701 addPath("selinux_fc", f.buildFileContexts(ctx))
Cole Faust0d467052024-12-04 17:19:19 -0800702 } else if f.properties.Precompiled_file_contexts != nil {
703 src := android.PathForModuleSrc(ctx, *f.properties.Precompiled_file_contexts)
704 if src != nil {
705 addPath("selinux_fc", src)
706 }
Inseob Kimcc8e5362021-02-03 14:05:24 +0900707 }
Jooyung Han65f402b2022-04-21 14:24:04 +0900708 if timestamp := proptools.String(f.properties.Fake_timestamp); timestamp != "" {
709 addStr("timestamp", timestamp)
710 }
711 if uuid := proptools.String(f.properties.Uuid); uuid != "" {
712 addStr("uuid", uuid)
713 addStr("hash_seed", uuid)
714 }
mrziwang1a6291f2024-11-07 14:29:25 -0800715
Cole Faust43a52c72024-11-26 12:46:08 -0800716 // TODO(b/381120092): This should only be added if none of the size-related properties are set,
717 // but currently soong built partitions don't have size properties. Make code:
718 // https://cs.android.com/android/platform/superproject/main/+/main:build/make/core/Makefile;l=2262;drc=39cd33701c9278db0e7e481a090605f428d5b12d
719 // Make uses system_disable_sparse but disable_sparse has the same effect, and we shouldn't need
720 // to qualify it because each partition gets its own property file built.
721 addStr("disable_sparse", "true")
722
mrziwang1a6291f2024-11-07 14:29:25 -0800723 fst := f.fsType(ctx)
724 switch fst {
725 case erofsType:
726 // Add erofs properties
Cole Faust3e730972024-12-03 13:12:08 -0800727 addStr("erofs_default_compressor", proptools.StringDefault(f.properties.Erofs.Compressor, "lz4hc,9"))
728 if f.properties.Erofs.Compress_hints != nil {
729 src := android.PathForModuleSrc(ctx, *f.properties.Erofs.Compress_hints)
730 addPath("erofs_default_compress_hints", src)
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000731 }
732 if proptools.BoolDefault(f.properties.Erofs.Sparse, true) {
733 // https://source.corp.google.com/h/googleplex-android/platform/build/+/88b1c67239ca545b11580237242774b411f2fed9:core/Makefile;l=2292;bpv=1;bpt=0;drc=ea8f34bc1d6e63656b4ec32f2391e9d54b3ebb6b
734 addStr("erofs_sparse_flag", "-s")
735 }
mrziwang1a6291f2024-11-07 14:29:25 -0800736 case f2fsType:
737 if proptools.BoolDefault(f.properties.F2fs.Sparse, true) {
738 // https://source.corp.google.com/h/googleplex-android/platform/build/+/88b1c67239ca545b11580237242774b411f2fed9:core/Makefile;l=2294;drc=ea8f34bc1d6e63656b4ec32f2391e9d54b3ebb6b;bpv=1;bpt=0
739 addStr("f2fs_sparse_flag", "-S")
740 }
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000741 }
mrziwang1a6291f2024-11-07 14:29:25 -0800742 f.checkFsTypePropertyError(ctx, fst, fsTypeStr(fst))
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000743
Cole Fauste1676122024-12-03 17:32:25 -0800744 propFilePreProcessing := android.PathForModuleOut(ctx, "prop_pre_processing")
745 android.WriteFileRuleVerbatim(ctx, propFilePreProcessing, propFileString.String())
Cole Faust4e9f5922024-11-13 16:09:23 -0800746 propFile := android.PathForModuleOut(ctx, "prop")
Cole Fauste1676122024-12-03 17:32:25 -0800747 ctx.Build(pctx, android.BuildParams{
748 Rule: textFileProcessorRule,
749 Input: propFilePreProcessing,
750 Output: propFile,
751 Implicit: ctx.Config().BuildFingerprintFile(ctx),
752 })
Jiyong Park72678312021-01-18 17:29:49 +0900753 return propFile, deps
754}
755
mrziwang1a6291f2024-11-07 14:29:25 -0800756// This method checks if there is any property set for the fstype(s) other than
757// the current fstype.
758func (f *filesystem) checkFsTypePropertyError(ctx android.ModuleContext, t fsType, fs string) {
759 raiseError := func(otherFsType, currentFsType string) {
760 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)
761 ctx.PropertyErrorf(otherFsType, errMsg)
762 }
763
764 if t != erofsType {
765 if f.properties.Erofs.Compressor != nil || f.properties.Erofs.Compress_hints != nil || f.properties.Erofs.Sparse != nil {
766 raiseError("erofs", fs)
767 }
768 }
769 if t != f2fsType {
770 if f.properties.F2fs.Sparse != nil {
771 raiseError("f2fs", fs)
772 }
773 }
774}
775
Cole Faust4e9f5922024-11-13 16:09:23 -0800776func (f *filesystem) buildCpioImage(ctx android.ModuleContext, compressed bool) android.Path {
Jiyong Park11a65972021-02-01 21:09:38 +0900777 if proptools.Bool(f.properties.Use_avb) {
778 ctx.PropertyErrorf("use_avb", "signing compresed cpio image using avbtool is not supported."+
779 "Consider adding this to bootimg module and signing the entire boot image.")
780 }
781
Inseob Kimcc8e5362021-02-03 14:05:24 +0900782 if proptools.String(f.properties.File_contexts) != "" {
783 ctx.PropertyErrorf("file_contexts", "file_contexts is not supported for compressed cpio image.")
784 }
785
Cole Faust4a2a7c92024-03-12 12:44:40 -0700786 if f.properties.Include_make_built_files != "" {
787 ctx.PropertyErrorf("include_make_built_files", "include_make_built_files is not supported for compressed cpio image.")
788 }
789
Spandan Das420e16a2024-12-11 18:10:52 +0000790 rootDir := android.PathForModuleOut(ctx, f.rootDirString()).OutputPath
Cole Faust3b806d32024-03-11 15:15:03 -0700791 rebasedDir := rootDir
792 if f.properties.Base_dir != nil {
793 rebasedDir = rootDir.Join(ctx, *f.properties.Base_dir)
794 }
795 builder := android.NewRuleBuilder(pctx, ctx)
796 // Wipe the root dir to get rid of leftover files from prior builds
797 builder.Command().Textf("rm -rf %s && mkdir -p %s", rootDir, rootDir)
Inseob Kim53391842024-03-29 17:44:07 +0900798 specs := f.gatherFilteredPackagingSpecs(ctx)
Inseob Kim33f95a92024-07-11 15:44:49 +0900799 f.entries = f.copyPackagingSpecs(ctx, builder, specs, rootDir, rebasedDir)
Cole Faust3b806d32024-03-11 15:15:03 -0700800
801 f.buildNonDepsFiles(ctx, builder, rootDir)
Inseob Kim53391842024-03-29 17:44:07 +0900802 f.buildFsverityMetadataFiles(ctx, builder, specs, rootDir, rebasedDir)
Inseob Kimb7b84572024-04-30 10:51:47 +0900803 f.buildEventLogtagsFile(ctx, builder, rebasedDir)
Justin Yun74f3f302024-05-07 14:32:14 +0900804 f.buildAconfigFlagsFiles(ctx, builder, specs, rebasedDir)
Kiyoung Kim67118212024-11-07 13:23:44 +0900805 f.filesystemBuilder.BuildLinkerConfigFile(ctx, builder, rebasedDir)
Justin Yun34baa2e2024-08-30 21:11:33 +0900806 f.copyFilesToProductOut(ctx, builder, rebasedDir)
Jiyong Park11a65972021-02-01 21:09:38 +0900807
Cole Faust4e9f5922024-11-13 16:09:23 -0800808 output := android.PathForModuleOut(ctx, f.installFileName())
Jiyong Park837cdb22021-02-05 00:17:14 +0900809 cmd := builder.Command().
Jiyong Park11a65972021-02-01 21:09:38 +0900810 BuiltTool("mkbootfs").
Jiyong Park837cdb22021-02-05 00:17:14 +0900811 Text(rootDir.String()) // input directory
Jihoon Kang6c03c8e2024-11-18 21:30:22 +0000812 if nodeList := f.properties.Dev_nodes_description_file; nodeList != nil {
813 cmd.FlagWithInput("-n ", android.PathForModuleSrc(ctx, proptools.String(nodeList)))
814 }
Jiyong Park837cdb22021-02-05 00:17:14 +0900815 if compressed {
816 cmd.Text("|").
817 BuiltTool("lz4").
818 Flag("--favor-decSpeed"). // for faster boot
819 Flag("-12"). // maximum compression level
820 Flag("-l"). // legacy format for kernel
821 Text(">").Output(output)
822 } else {
823 cmd.Text(">").Output(output)
824 }
Jiyong Park11a65972021-02-01 21:09:38 +0900825
826 // rootDir is not deleted. Might be useful for quick inspection.
Jiyong Park837cdb22021-02-05 00:17:14 +0900827 builder.Build("build_cpio_image", fmt.Sprintf("Creating filesystem %s", f.BaseModuleName()))
Jiyong Park11a65972021-02-01 21:09:38 +0900828
829 return output
830}
831
Cole Faust4a2a7c92024-03-12 12:44:40 -0700832var validPartitions = []string{
833 "system",
834 "userdata",
835 "cache",
836 "system_other",
837 "vendor",
838 "product",
839 "system_ext",
840 "odm",
841 "vendor_dlkm",
842 "odm_dlkm",
843 "system_dlkm",
Cole Faust76a6e952024-11-07 16:56:45 -0800844 "ramdisk",
Cole Faust24938e22024-11-18 14:01:58 -0800845 "vendor_ramdisk",
Jihoon Kang3216c982024-12-02 19:42:20 +0000846 "recovery",
Cole Faust4a2a7c92024-03-12 12:44:40 -0700847}
848
849func (f *filesystem) addMakeBuiltFiles(ctx android.ModuleContext, builder *android.RuleBuilder, rootDir android.Path) {
850 partition := f.properties.Include_make_built_files
851 if partition == "" {
852 return
853 }
854 if !slices.Contains(validPartitions, partition) {
855 ctx.PropertyErrorf("include_make_built_files", "Expected one of %#v, found %q", validPartitions, partition)
856 return
857 }
858 stampFile := fmt.Sprintf("target/product/%s/obj/PACKAGING/%s_intermediates/staging_dir.stamp", ctx.Config().DeviceName(), partition)
859 fileListFile := fmt.Sprintf("target/product/%s/obj/PACKAGING/%s_intermediates/file_list.txt", ctx.Config().DeviceName(), partition)
860 stagingDir := fmt.Sprintf("target/product/%s/%s", ctx.Config().DeviceName(), partition)
861
862 builder.Command().BuiltTool("merge_directories").
863 Implicit(android.PathForArbitraryOutput(ctx, stampFile)).
864 Text("--ignore-duplicates").
865 FlagWithInput("--file-list", android.PathForArbitraryOutput(ctx, fileListFile)).
866 Text(rootDir.String()).
867 Text(android.PathForArbitraryOutput(ctx, stagingDir).String())
868}
869
Inseob Kimb7b84572024-04-30 10:51:47 +0900870func (f *filesystem) buildEventLogtagsFile(ctx android.ModuleContext, builder *android.RuleBuilder, rebasedDir android.OutputPath) {
871 if !proptools.Bool(f.properties.Build_logtags) {
872 return
873 }
874
875 logtagsFilePaths := make(map[string]bool)
876 ctx.WalkDeps(func(child, parent android.Module) bool {
877 if logtagsInfo, ok := android.OtherModuleProvider(ctx, child, android.LogtagsProviderKey); ok {
878 for _, path := range logtagsInfo.Logtags {
879 logtagsFilePaths[path.String()] = true
880 }
881 }
882 return true
883 })
884
885 if len(logtagsFilePaths) == 0 {
886 return
887 }
888
889 etcPath := rebasedDir.Join(ctx, "etc")
890 eventLogtagsPath := etcPath.Join(ctx, "event-log-tags")
891 builder.Command().Text("mkdir").Flag("-p").Text(etcPath.String())
892 cmd := builder.Command().BuiltTool("merge-event-log-tags").
Cole Faustbd20ac12024-12-10 12:30:44 -0800893 FlagWithArg("-o ", eventLogtagsPath.String())
Inseob Kimb7b84572024-04-30 10:51:47 +0900894
895 for _, path := range android.SortedKeys(logtagsFilePaths) {
896 cmd.Text(path)
897 }
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900898
899 f.appendToEntry(ctx, eventLogtagsPath)
Inseob Kimb7b84572024-04-30 10:51:47 +0900900}
901
Kiyoung Kim67118212024-11-07 13:23:44 +0900902func (f *filesystem) BuildLinkerConfigFile(ctx android.ModuleContext, builder *android.RuleBuilder, rebasedDir android.OutputPath) {
Spandan Das2047a4c2024-11-11 21:24:58 +0000903 if !proptools.Bool(f.properties.Linker_config.Gen_linker_config) {
Spandan Das92631882024-10-28 22:49:38 +0000904 return
905 }
906
Spandan Das918191e2024-10-31 18:27:23 +0000907 provideModules, _ := f.getLibsForLinkerConfig(ctx)
Spandan Das92631882024-10-28 22:49:38 +0000908 output := rebasedDir.Join(ctx, "etc", "linker.config.pb")
Spandan Das2047a4c2024-11-11 21:24:58 +0000909 linkerconfig.BuildLinkerConfig(ctx, builder, android.PathsForModuleSrc(ctx, f.properties.Linker_config.Linker_config_srcs), provideModules, nil, output)
Spandan Das92631882024-10-28 22:49:38 +0000910
911 f.appendToEntry(ctx, output)
912}
913
Kiyoung Kim23be5bb2024-11-27 00:50:30 +0000914func (f *filesystem) ShouldUseVintfFragmentModuleOnly() bool {
915 return false
916}
917
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900918type partition interface {
919 PartitionType() string
920}
921
Cole Faust9a24d902024-03-18 15:38:12 -0700922func (f *filesystem) PartitionType() string {
923 return proptools.StringDefault(f.properties.Partition_type, "system")
924}
925
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900926var _ partition = (*filesystem)(nil)
927
Jiyong Park65c49f52020-11-24 14:23:26 +0900928var _ android.AndroidMkEntriesProvider = (*filesystem)(nil)
929
930// Implements android.AndroidMkEntriesProvider
931func (f *filesystem) AndroidMkEntries() []android.AndroidMkEntries {
932 return []android.AndroidMkEntries{android.AndroidMkEntries{
933 Class: "ETC",
934 OutputFile: android.OptionalPathForPath(f.output),
935 ExtraEntries: []android.AndroidMkExtraEntriesFunc{
Colin Crossaa255532020-07-03 13:18:24 -0700936 func(ctx android.AndroidMkExtraEntriesContext, entries *android.AndroidMkEntries) {
Colin Crossc68db4b2021-11-11 18:59:15 -0800937 entries.SetString("LOCAL_MODULE_PATH", f.installDir.String())
Jiyong Park65c49f52020-11-24 14:23:26 +0900938 entries.SetString("LOCAL_INSTALLED_MODULE_STEM", f.installFileName())
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900939 entries.SetString("LOCAL_FILESYSTEM_FILELIST", f.fileListFile.String())
Jiyong Park65c49f52020-11-24 14:23:26 +0900940 },
941 },
942 }}
Jiyong Park6f0f6882020-11-12 13:14:30 +0900943}
Jiyong Park12a719c2021-01-07 15:31:24 +0900944
945// Filesystem is the public interface for the filesystem struct. Currently, it's only for the apex
946// package to have access to the output file.
947type Filesystem interface {
948 android.Module
949 OutputPath() android.Path
Jiyong Park972e06c2021-03-15 23:32:49 +0900950
951 // Returns the output file that is signed by avbtool. If this module is not signed, returns
952 // nil.
953 SignedOutputPath() android.Path
Jiyong Park12a719c2021-01-07 15:31:24 +0900954}
955
956var _ Filesystem = (*filesystem)(nil)
957
958func (f *filesystem) OutputPath() android.Path {
959 return f.output
960}
Jiyong Park972e06c2021-03-15 23:32:49 +0900961
962func (f *filesystem) SignedOutputPath() android.Path {
963 if proptools.Bool(f.properties.Use_avb) {
964 return f.OutputPath()
965 }
966 return nil
967}
Jooyung Han0fbbc2b2022-03-25 12:35:46 +0900968
969// Filter the result of GatherPackagingSpecs to discard items targeting outside "system" partition.
970// Note that "apex" module installs its contents to "apex"(fake partition) as well
971// for symbol lookup by imitating "activated" paths.
972func (f *filesystem) gatherFilteredPackagingSpecs(ctx android.ModuleContext) map[string]android.PackagingSpec {
Inseob Kim3c0a0422024-11-05 17:21:37 +0900973 specs := f.PackagingBase.GatherPackagingSpecsWithFilterAndModifier(ctx, f.filesystemBuilder.FilterPackagingSpec, f.filesystemBuilder.ModifyPackagingSpec)
Jooyung Han0fbbc2b2022-03-25 12:35:46 +0900974 return specs
975}
Jooyung Han65f402b2022-04-21 14:24:04 +0900976
977func sha1sum(values []string) string {
978 h := sha256.New()
979 for _, value := range values {
980 io.WriteString(h, value)
981 }
982 return fmt.Sprintf("%x", h.Sum(nil))
983}
Jooyung Hane6067592023-03-16 13:11:17 +0900984
985// Base cc.UseCoverage
986
987var _ cc.UseCoverage = (*filesystem)(nil)
988
Colin Crosse1a85552024-06-14 12:17:37 -0700989func (*filesystem) IsNativeCoverageNeeded(ctx cc.IsNativeCoverageNeededContext) bool {
Jooyung Hane6067592023-03-16 13:11:17 +0900990 return ctx.Device() && ctx.DeviceConfig().NativeCoverageEnabled()
991}
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900992
993// android_filesystem_defaults
994
995type filesystemDefaults struct {
996 android.ModuleBase
997 android.DefaultsModuleBase
998
Inseob Kim3c0a0422024-11-05 17:21:37 +0900999 properties FilesystemProperties
Jiyong Parkf46b1af2024-04-05 18:13:33 +09001000}
1001
1002// android_filesystem_defaults is a default module for android_filesystem and android_system_image
1003func filesystemDefaultsFactory() android.Module {
1004 module := &filesystemDefaults{}
1005 module.AddProperties(&module.properties)
1006 module.AddProperties(&android.PackagingProperties{})
1007 android.InitDefaultsModule(module)
1008 return module
1009}
1010
1011func (f *filesystemDefaults) PartitionType() string {
1012 return proptools.StringDefault(f.properties.Partition_type, "system")
1013}
1014
1015var _ partition = (*filesystemDefaults)(nil)
1016
1017func (f *filesystemDefaults) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1018 validatePartitionType(ctx, f)
1019}
Spandan Das918191e2024-10-31 18:27:23 +00001020
1021// getLibsForLinkerConfig returns
1022// 1. A list of libraries installed in this filesystem
1023// 2. A list of dep libraries _not_ installed in this filesystem
1024//
1025// `linkerconfig.BuildLinkerConfig` will convert these two to a linker.config.pb for the filesystem
1026// (1) will be added to --provideLibs if they are C libraries with a stable interface (has stubs)
1027// (2) will be added to --requireLibs if they are C libraries with a stable interface (has stubs)
1028func (f *filesystem) getLibsForLinkerConfig(ctx android.ModuleContext) ([]android.Module, []android.Module) {
1029 // we need "Module"s for packaging items
1030 modulesInPackageByModule := make(map[android.Module]bool)
1031 modulesInPackageByName := make(map[string]bool)
1032
1033 deps := f.gatherFilteredPackagingSpecs(ctx)
1034 ctx.WalkDeps(func(child, parent android.Module) bool {
1035 for _, ps := range android.OtherModuleProviderOrDefault(
1036 ctx, child, android.InstallFilesProvider).PackagingSpecs {
Spandan Dasecf667f2024-12-05 00:58:56 +00001037 if _, ok := deps[ps.RelPathInPackage()]; ok && ps.Partition() == f.PartitionType() {
Spandan Das918191e2024-10-31 18:27:23 +00001038 modulesInPackageByModule[child] = true
1039 modulesInPackageByName[child.Name()] = true
1040 return true
1041 }
1042 }
1043 return true
1044 })
1045
1046 provideModules := make([]android.Module, 0, len(modulesInPackageByModule))
1047 for mod := range modulesInPackageByModule {
1048 provideModules = append(provideModules, mod)
1049 }
1050
1051 var requireModules []android.Module
1052 ctx.WalkDeps(func(child, parent android.Module) bool {
1053 _, parentInPackage := modulesInPackageByModule[parent]
1054 _, childInPackageName := modulesInPackageByName[child.Name()]
1055
1056 // When parent is in the package, and child (or its variant) is not, this can be from an interface.
1057 if parentInPackage && !childInPackageName {
1058 requireModules = append(requireModules, child)
1059 }
1060 return true
1061 })
1062
1063 return provideModules, requireModules
1064}
Cole Faust26bdac52024-11-19 13:37:53 -08001065
1066// Checks that the given file doesn't exceed the given size, and will also print a warning
1067// if it's nearing the maximum size. Equivalent to assert-max-image-size in make:
1068// https://cs.android.com/android/platform/superproject/main/+/main:build/make/core/definitions.mk;l=3455;drc=993c4de29a02a6accd60ceaaee153307e1a18d10
1069func assertMaxImageSize(builder *android.RuleBuilder, image android.Path, maxSize int64, addAvbLater bool) {
1070 if addAvbLater {
1071 // The value 69632 is derived from MAX_VBMETA_SIZE + MAX_FOOTER_SIZE in avbtool.
1072 // Logic copied from make:
1073 // https://cs.android.com/android/platform/superproject/main/+/main:build/make/core/Makefile;l=228;drc=a6a0007ef24e16c0b79f439beac4a118416717e6
1074 maxSize -= 69632
1075 }
1076 cmd := builder.Command()
1077 cmd.Textf(`file="%s"; maxsize="%d";`+
1078 `total=$(stat -c "%%s" "$file" | tr -d '\n');`+
1079 `if [ "$total" -gt "$maxsize" ]; then `+
1080 ` echo "error: $file too large ($total > $maxsize)";`+
1081 ` false;`+
1082 `elif [ "$total" -gt $((maxsize - 32768)) ]; then `+
1083 ` echo "WARNING: $file approaching size limit ($total now; limit $maxsize)";`+
1084 `fi`,
1085 image, maxSize)
1086 cmd.Implicit(image)
1087}
Spandan Das71be42d2024-11-20 18:34:16 +00001088
1089// addAutogeneratedRroDeps walks the transitive closure of vendor and product partitions.
1090// It visits apps installed in system and system_ext partitions, and adds the autogenerated
1091// RRO modules to its own deps.
1092func addAutogeneratedRroDeps(ctx android.BottomUpMutatorContext) {
1093 f, ok := ctx.Module().(*filesystem)
1094 if !ok {
1095 return
1096 }
1097 thisPartition := f.PartitionType()
1098 if thisPartition != "vendor" && thisPartition != "product" {
1099 return
1100 }
1101 ctx.WalkDeps(func(child, parent android.Module) bool {
1102 depTag := ctx.OtherModuleDependencyTag(child)
1103 if parent.Name() == f.Name() && depTag != interPartitionDependencyTag {
1104 return false // This is a module listed in deps of vendor/product filesystem
1105 }
1106 if vendorOverlay := java.AutogeneratedRroModuleName(ctx, child.Name(), "vendor"); ctx.OtherModuleExists(vendorOverlay) && thisPartition == "vendor" {
1107 ctx.AddFarVariationDependencies(nil, dependencyTagWithVisibilityEnforcementBypass, vendorOverlay)
1108 }
1109 if productOverlay := java.AutogeneratedRroModuleName(ctx, child.Name(), "product"); ctx.OtherModuleExists(productOverlay) && thisPartition == "product" {
1110 ctx.AddFarVariationDependencies(nil, dependencyTagWithVisibilityEnforcementBypass, productOverlay)
1111 }
1112 return true
1113 })
1114}