blob: 21c0689a24ea15dbc594e14eae9afcd559122da7 [file] [log] [blame]
Jiyong Park6f0f6882020-11-12 13:14:30 +09001// Copyright (C) 2020 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package filesystem
16
17import (
Jooyung Han65f402b2022-04-21 14:24:04 +090018 "crypto/sha256"
Jiyong Park6f0f6882020-11-12 13:14:30 +090019 "fmt"
Jooyung Han65f402b2022-04-21 14:24:04 +090020 "io"
Inseob Kim14199b02021-02-09 21:18:31 +090021 "path/filepath"
Cole Faust4a2a7c92024-03-12 12:44:40 -070022 "slices"
Cole Fauste03ab892025-01-17 13:55:04 -080023 "sort"
Nikita Ioffe2c8cdc62024-03-27 22:19:30 +000024 "strconv"
Inseob Kim14199b02021-02-09 21:18:31 +090025 "strings"
Jiyong Park6f0f6882020-11-12 13:14:30 +090026
27 "android/soong/android"
Jooyung Hane6067592023-03-16 13:11:17 +090028 "android/soong/cc"
Spandan Das71be42d2024-11-20 18:34:16 +000029 "android/soong/java"
Spandan Das92631882024-10-28 22:49:38 +000030 "android/soong/linkerconfig"
Jiyong Park65b62242020-11-25 12:44:59 +090031
32 "github.com/google/blueprint"
Jiyong Park71baa762021-01-18 21:11:03 +090033 "github.com/google/blueprint/proptools"
Jiyong Park6f0f6882020-11-12 13:14:30 +090034)
35
36func init() {
Jooyung Han9706cbc2021-04-15 22:43:48 +090037 registerBuildComponents(android.InitRegistrationContext)
Spandan Das71be42d2024-11-20 18:34:16 +000038 registerMutators(android.InitRegistrationContext)
Jihoon Kangf67b7de2025-02-12 01:01:09 +000039 pctx.HostBinToolVariable("fileslist", "fileslist")
Jooyung Han9706cbc2021-04-15 22:43:48 +090040}
41
42func registerBuildComponents(ctx android.RegistrationContext) {
Cole Faust92ccbe22024-10-03 14:38:37 -070043 ctx.RegisterModuleType("android_filesystem", FilesystemFactory)
Jiyong Parkf46b1af2024-04-05 18:13:33 +090044 ctx.RegisterModuleType("android_filesystem_defaults", filesystemDefaultsFactory)
Jihoon Kang98047cf2024-10-02 17:13:54 +000045 ctx.RegisterModuleType("android_system_image", SystemImageFactory)
Jiyong Parkbc485482022-11-15 22:31:49 +090046 ctx.RegisterModuleType("avb_add_hash_footer", avbAddHashFooterFactory)
Inseob Kim87230e62023-11-22 18:55:07 +090047 ctx.RegisterModuleType("avb_add_hash_footer_defaults", avbAddHashFooterDefaultsFactory)
Alice Wang000e3a32023-01-03 16:11:20 +000048 ctx.RegisterModuleType("avb_gen_vbmeta_image", avbGenVbmetaImageFactory)
Inseob Kim87230e62023-11-22 18:55:07 +090049 ctx.RegisterModuleType("avb_gen_vbmeta_image_defaults", avbGenVbmetaImageDefaultsFactory)
Jiyong Park6f0f6882020-11-12 13:14:30 +090050}
51
Spandan Das71be42d2024-11-20 18:34:16 +000052func registerMutators(ctx android.RegistrationContext) {
53 ctx.PostDepsMutators(func(ctx android.RegisterMutatorsContext) {
54 ctx.BottomUp("add_autogenerated_rro_deps", addAutogeneratedRroDeps)
55 })
56}
57
Jihoon Kangf67b7de2025-02-12 01:01:09 +000058var (
59 // Remember to add referenced files to implicits!
60 textFileProcessorRule = pctx.AndroidStaticRule("text_file_processing", blueprint.RuleParams{
61 Command: "build/soong/scripts/text_file_processor.py $in $out",
62 CommandDeps: []string{"build/soong/scripts/text_file_processor.py"},
63 })
64
65 // Remember to add the output image file as an implicit dependency!
66 installedFilesJsonRule = pctx.AndroidStaticRule("installed_files_json", blueprint.RuleParams{
67 Command: `${fileslist} ${rootDir} > ${out}`,
68 CommandDeps: []string{"${fileslist}"},
69 }, "rootDir")
70
71 installedFilesTxtRule = pctx.AndroidStaticRule("installed_files_txt", blueprint.RuleParams{
72 Command: `build/make/tools/fileslist_util.py -c ${in} > ${out}`,
73 CommandDeps: []string{"build/make/tools/fileslist_util.py"},
74 })
75)
Cole Fauste1676122024-12-03 17:32:25 -080076
Jiyong Park6f0f6882020-11-12 13:14:30 +090077type filesystem struct {
78 android.ModuleBase
79 android.PackagingBase
Jiyong Parkf46b1af2024-04-05 18:13:33 +090080 android.DefaultableModuleBase
Jiyong Park65c49f52020-11-24 14:23:26 +090081
Jihoon Kang98047cf2024-10-02 17:13:54 +000082 properties FilesystemProperties
Jiyong Park71baa762021-01-18 21:11:03 +090083
Cole Faust4e9f5922024-11-13 16:09:23 -080084 output android.Path
Jiyong Park65c49f52020-11-24 14:23:26 +090085 installDir android.InstallPath
Jooyung Han0fbbc2b2022-03-25 12:35:46 +090086
Cole Faust4e9f5922024-11-13 16:09:23 -080087 fileListFile android.Path
Kiyoung Kim99a954d2024-06-21 14:22:20 +090088
89 // Keeps the entries installed from this filesystem
Jooyung Han0fbbc2b2022-03-25 12:35:46 +090090 entries []string
Kiyoung Kim67118212024-11-07 13:23:44 +090091
92 filesystemBuilder filesystemBuilder
Jiyong Park6f0f6882020-11-12 13:14:30 +090093}
94
Kiyoung Kim67118212024-11-07 13:23:44 +090095type filesystemBuilder interface {
Cole Faust19fbb072025-01-30 18:19:29 -080096 BuildLinkerConfigFile(ctx android.ModuleContext, builder *android.RuleBuilder, rebasedDir android.OutputPath, fullInstallPaths *[]FullInstallPathInfo)
Kiyoung Kim67118212024-11-07 13:23:44 +090097 // Function that filters PackagingSpec in PackagingBase.GatherPackagingSpecs()
98 FilterPackagingSpec(spec android.PackagingSpec) bool
Inseob Kim3c0a0422024-11-05 17:21:37 +090099 // Function that modifies PackagingSpec in PackagingBase.GatherPackagingSpecs() to customize.
100 // For example, GSI system.img contains system_ext and product artifacts and their
101 // relPathInPackage need to be rebased to system/system_ext and system/system_product.
102 ModifyPackagingSpec(spec *android.PackagingSpec)
Kiyoung Kim23be5bb2024-11-27 00:50:30 +0000103
104 // Function to check if the filesystem should not use `vintf_fragments` property,
105 // but use `vintf_fragment` module type instead
106 ShouldUseVintfFragmentModuleOnly() bool
Kiyoung Kim67118212024-11-07 13:23:44 +0900107}
108
109var _ filesystemBuilder = (*filesystem)(nil)
110
Spandan Das69464c32024-10-25 20:08:06 +0000111type SymlinkDefinition struct {
Inseob Kim14199b02021-02-09 21:18:31 +0900112 Target *string
113 Name *string
114}
115
Jihoon Kang0a453892024-12-09 22:16:26 +0000116// CopyWithNamePrefix returns a new [SymlinkDefinition] with prefix added to Name.
117func (s *SymlinkDefinition) CopyWithNamePrefix(prefix string) SymlinkDefinition {
118 return SymlinkDefinition{
119 Target: s.Target,
120 Name: proptools.StringPtr(filepath.Join(prefix, proptools.String(s.Name))),
121 }
122}
123
Jihoon Kang98047cf2024-10-02 17:13:54 +0000124type FilesystemProperties struct {
Jiyong Park71baa762021-01-18 21:11:03 +0900125 // When set to true, sign the image with avbtool. Default is false.
126 Use_avb *bool
127
128 // Path to the private key that avbtool will use to sign this filesystem image.
129 // TODO(jiyong): allow apex_key to be specified here
130 Avb_private_key *string `android:"path"`
131
Shikha Panwar01403bb2022-12-22 12:22:57 +0000132 // Signing algorithm for avbtool. Default is SHA256_RSA4096.
Jiyong Park71baa762021-01-18 21:11:03 +0900133 Avb_algorithm *string
Jiyong Park11a65972021-02-01 21:09:38 +0900134
Shikha Panwar01403bb2022-12-22 12:22:57 +0000135 // Hash algorithm used for avbtool (for descriptors). This is passed as hash_algorithm to
Nikita Ioffe50fb49c2025-01-24 13:49:00 +0000136 // avbtool. Default is sha256.
Shikha Panware6f30632022-12-21 12:54:45 +0000137 Avb_hash_algorithm *string
138
Spandan Dase5c393c2024-12-12 19:25:07 +0000139 // The security patch passed to as the com.android.build.<type>.security_patch avb property.
140 Security_patch *string
141
Cole Fauste1676122024-12-03 17:32:25 -0800142 // Whether or not to use forward-error-correction codes when signing with AVB. Defaults to true.
143 Use_fec *bool
144
Nikita Ioffe2c8cdc62024-03-27 22:19:30 +0000145 // The index used to prevent rollback of the image. Only used if use_avb is true.
146 Rollback_index *int64
147
Jihoon Kang2f0d1932025-01-17 19:22:44 +0000148 // Rollback index location of this image. Must be 0, 1, 2, etc.
149 Rollback_index_location *int64
150
Jiyong Parkac4076d2021-03-15 23:21:30 +0900151 // Name of the partition stored in vbmeta desc. Defaults to the name of this module.
152 Partition_name *string
153
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000154 // Type of the filesystem. Currently, ext4, erofs, cpio, and compressed_cpio are supported. Default
Jiyong Park837cdb22021-02-05 00:17:14 +0900155 // is ext4.
Jiyong Park11a65972021-02-01 21:09:38 +0900156 Type *string
Inseob Kimcc8e5362021-02-03 14:05:24 +0900157
Cole Faust9a24d902024-03-18 15:38:12 -0700158 // Identifies which partition this is for //visibility:any_system_image (and others) visibility
159 // checks, and will be used in the future for API surface checks.
160 Partition_type *string
161
Cole Faust0d467052024-12-04 17:19:19 -0800162 // file_contexts file to make image. Currently, only ext4 is supported. These file contexts
163 // will be compiled with sefcontext_compile
Inseob Kimcc8e5362021-02-03 14:05:24 +0900164 File_contexts *string `android:"path"`
Inseob Kim2ce1b5d2021-02-15 17:01:04 +0900165
Cole Faust0d467052024-12-04 17:19:19 -0800166 // The selinux file contexts, after having already run them through sefcontext_compile
167 Precompiled_file_contexts *string `android:"path"`
168
Inseob Kim2ce1b5d2021-02-15 17:01:04 +0900169 // Base directory relative to root, to which deps are installed, e.g. "system". Default is "."
170 // (root).
171 Base_dir *string
Inseob Kim14199b02021-02-09 21:18:31 +0900172
173 // Directories to be created under root. e.g. /dev, /proc, etc.
Cole Faustd9c6a5b2024-05-21 14:54:00 -0700174 Dirs proptools.Configurable[[]string]
Inseob Kim14199b02021-02-09 21:18:31 +0900175
Jihoon Kang6da80752024-12-23 18:53:32 +0000176 // List of filesystem modules to include in creating the partition. The root directory of
177 // the provided filesystem modules are included in creating the partition.
178 // This is only supported for cpio and compressed cpio filesystem types.
179 Include_files_of []string
180
Inseob Kim14199b02021-02-09 21:18:31 +0900181 // Symbolic links to be created under root with "ln -sf <target> <name>".
Spandan Das69464c32024-10-25 20:08:06 +0000182 Symlinks []SymlinkDefinition
Jooyung Han65f402b2022-04-21 14:24:04 +0900183
184 // Seconds since unix epoch to override timestamps of file entries
185 Fake_timestamp *string
186
187 // When set, passed to mkuserimg_mke2fs --mke2fs_uuid & --mke2fs_hash_seed.
188 // Otherwise, they'll be set as random which might cause indeterministic build output.
189 Uuid *string
Inseob Kim376d72f2023-11-01 15:40:25 +0900190
191 // Mount point for this image. Default is "/"
192 Mount_point *string
Cole Faust4a2a7c92024-03-12 12:44:40 -0700193
Inseob Kimb7b84572024-04-30 10:51:47 +0900194 // When set, builds etc/event-log-tags file by merging logtags from all dependencies.
195 // Default is false
196 Build_logtags *bool
197
Justin Yun74f3f302024-05-07 14:32:14 +0900198 // Install aconfig_flags.pb file for the modules installed in this partition.
199 Gen_aconfig_flags_pb *bool
200
Cole Faust34592c02024-12-13 11:20:24 -0800201 // List of names of other filesystem partitions to import their aconfig flags from.
202 // This is used for the system partition to import system_ext's aconfig flags, as currently
203 // those are considered one "container": aosp/3261300
204 Import_aconfig_flags_from []string
205
Inseob Kim53391842024-03-29 17:44:07 +0900206 Fsverity fsverityProperties
Cole Faust92ccbe22024-10-03 14:38:37 -0700207
208 // If this property is set to true, the filesystem will call ctx.UncheckedModule(), causing
209 // it to not be built on checkbuilds. Used for the automatic migration from make to soong
210 // build modules, where we want to emit some not-yet-working filesystems and we don't want them
211 // to be built.
212 Unchecked_module *bool `blueprint:"mutated"`
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000213
214 Erofs ErofsProperties
Jihoon Kang0d545b82024-10-11 00:21:57 +0000215
mrziwang1a6291f2024-11-07 14:29:25 -0800216 F2fs F2fsProperties
217
Spandan Das2047a4c2024-11-11 21:24:58 +0000218 Linker_config LinkerConfigProperties
Spandan Das92631882024-10-28 22:49:38 +0000219
Jihoon Kang0d545b82024-10-11 00:21:57 +0000220 // Determines if the module is auto-generated from Soong or not. If the module is
221 // auto-generated, its deps are exempted from visibility enforcement.
222 Is_auto_generated *bool
Jihoon Kang6c03c8e2024-11-18 21:30:22 +0000223
224 // Path to the dev nodes description file. This is only needed for building the ramdisk
225 // partition and should not be explicitly specified.
226 Dev_nodes_description_file *string `android:"path" blueprint:"mutated"`
Spandan Das71be42d2024-11-20 18:34:16 +0000227
228 // Additional dependencies used for building android products
229 Android_filesystem_deps AndroidFilesystemDeps
Spandan Dasc49b85e2025-01-10 00:51:25 +0000230
231 // Name of the output. Default is $(module_name).img
232 Stem *string
Jihoon Kang983dd882025-01-13 23:14:11 +0000233
234 // The size of the partition on the device. It will be a build error if this built partition
235 // image exceeds this size.
236 Partition_size *int64
Jihoon Kang6d08d922025-01-14 18:31:57 +0000237
238 // Whether to format f2fs and ext4 in a way that supports casefolding
239 Support_casefolding *bool
240
241 // Whether to format f2fs and ext4 in a way that supports project quotas
242 Support_project_quota *bool
243
244 // Whether to enable per-file compression in f2fs
245 Enable_compression *bool
Spandan Das71be42d2024-11-20 18:34:16 +0000246}
247
248type AndroidFilesystemDeps struct {
249 System *string
250 System_ext *string
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000251}
252
253// Additional properties required to generate erofs FS partitions.
254type ErofsProperties struct {
255 // Compressor and Compression level passed to mkfs.erofs. e.g. (lz4hc,9)
256 // Please see external/erofs-utils/README for complete documentation.
257 Compressor *string
258
259 // Used as --compress-hints for mkfs.erofs
260 Compress_hints *string `android:"path"`
261
262 Sparse *bool
Jiyong Park71baa762021-01-18 21:11:03 +0900263}
264
mrziwang1a6291f2024-11-07 14:29:25 -0800265// Additional properties required to generate f2fs FS partitions.
266type F2fsProperties struct {
267 Sparse *bool
268}
269
Spandan Das173256b2024-10-31 19:59:30 +0000270type LinkerConfigProperties struct {
271
272 // Build a linker.config.pb file
273 Gen_linker_config *bool
274
275 // List of files (in .json format) that will be converted to a linker config file (in .pb format).
276 // The linker config file be installed in the filesystem at /etc/linker.config.pb
277 Linker_config_srcs []string `android:"path"`
278}
279
Jiyong Park65c49f52020-11-24 14:23:26 +0900280// android_filesystem packages a set of modules and their transitive dependencies into a filesystem
281// image. The filesystem images are expected to be mounted in the target device, which means the
282// modules in the filesystem image are built for the target device (i.e. Android, not Linux host).
283// The modules are placed in the filesystem image just like they are installed to the ordinary
284// partitions like system.img. For example, cc_library modules are placed under ./lib[64] directory.
Cole Faust92ccbe22024-10-03 14:38:37 -0700285func FilesystemFactory() android.Module {
Jiyong Park6f0f6882020-11-12 13:14:30 +0900286 module := &filesystem{}
Kiyoung Kim67118212024-11-07 13:23:44 +0900287 module.filesystemBuilder = module
Cole Faust2cfe6962024-09-17 11:31:14 -0700288 initFilesystemModule(module, module)
Jiyong Parkfa616132021-04-20 11:36:40 +0900289 return module
290}
291
Cole Faust2cfe6962024-09-17 11:31:14 -0700292func initFilesystemModule(module android.DefaultableModule, filesystemModule *filesystem) {
293 module.AddProperties(&filesystemModule.properties)
294 android.InitPackageModule(filesystemModule)
295 filesystemModule.PackagingBase.DepsCollectFirstTargetOnly = true
Jihoon Kang79196c52024-10-30 18:49:47 +0000296 filesystemModule.PackagingBase.AllowHighPriorityDeps = true
Jiyong Park6f0f6882020-11-12 13:14:30 +0900297 android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900298 android.InitDefaultableModule(module)
Jihoon Kang6c03c8e2024-11-18 21:30:22 +0000299
300 android.AddLoadHook(module, func(ctx android.LoadHookContext) {
301 filesystemModule.setDevNodesDescriptionProp()
302 })
Jiyong Park6f0f6882020-11-12 13:14:30 +0900303}
304
Jihoon Kang0d545b82024-10-11 00:21:57 +0000305type depTag struct {
Jiyong Park12a719c2021-01-07 15:31:24 +0900306 blueprint.BaseDependencyTag
Jooyung Han092ef812021-03-10 15:40:34 +0900307 android.PackagingItemAlwaysDepTag
Jihoon Kang0d545b82024-10-11 00:21:57 +0000308}
309
310var dependencyTag = depTag{}
311
312type depTagWithVisibilityEnforcementBypass struct {
313 depTag
314}
315
Spandan Das71be42d2024-11-20 18:34:16 +0000316type interPartitionDepTag struct {
317 blueprint.BaseDependencyTag
318}
319
320var interPartitionDependencyTag = interPartitionDepTag{}
321
Jihoon Kang6da80752024-12-23 18:53:32 +0000322var interPartitionInstallDependencyTag = interPartitionDepTag{}
323
Jihoon Kang0d545b82024-10-11 00:21:57 +0000324var _ android.ExcludeFromVisibilityEnforcementTag = (*depTagWithVisibilityEnforcementBypass)(nil)
325
326func (t depTagWithVisibilityEnforcementBypass) ExcludeFromVisibilityEnforcement() {}
327
328var dependencyTagWithVisibilityEnforcementBypass = depTagWithVisibilityEnforcementBypass{}
Jiyong Park65b62242020-11-25 12:44:59 +0900329
Jihoon Kang6c03c8e2024-11-18 21:30:22 +0000330// ramdiskDevNodesDescription is the name of the filegroup module that provides the file that
331// contains the description of dev nodes added to the CPIO archive for the ramdisk partition.
332const ramdiskDevNodesDescription = "ramdisk_node_list"
333
334func (f *filesystem) setDevNodesDescriptionProp() {
335 if proptools.String(f.properties.Partition_name) == "ramdisk" {
336 f.properties.Dev_nodes_description_file = proptools.StringPtr(":" + ramdiskDevNodesDescription)
337 }
338}
339
Jiyong Park6f0f6882020-11-12 13:14:30 +0900340func (f *filesystem) DepsMutator(ctx android.BottomUpMutatorContext) {
Jihoon Kang0d545b82024-10-11 00:21:57 +0000341 if proptools.Bool(f.properties.Is_auto_generated) {
342 f.AddDeps(ctx, dependencyTagWithVisibilityEnforcementBypass)
343 } else {
344 f.AddDeps(ctx, dependencyTag)
345 }
Spandan Das71be42d2024-11-20 18:34:16 +0000346 if f.properties.Android_filesystem_deps.System != nil {
347 ctx.AddDependency(ctx.Module(), interPartitionDependencyTag, proptools.String(f.properties.Android_filesystem_deps.System))
348 }
349 if f.properties.Android_filesystem_deps.System_ext != nil {
350 ctx.AddDependency(ctx.Module(), interPartitionDependencyTag, proptools.String(f.properties.Android_filesystem_deps.System_ext))
351 }
Cole Faust34592c02024-12-13 11:20:24 -0800352 for _, partition := range f.properties.Import_aconfig_flags_from {
353 ctx.AddDependency(ctx.Module(), importAconfigDependencyTag, partition)
354 }
Jihoon Kang6da80752024-12-23 18:53:32 +0000355 for _, partition := range f.properties.Include_files_of {
356 ctx.AddDependency(ctx.Module(), interPartitionInstallDependencyTag, partition)
357 }
Jiyong Park6f0f6882020-11-12 13:14:30 +0900358}
359
Jiyong Park11a65972021-02-01 21:09:38 +0900360type fsType int
361
362const (
363 ext4Type fsType = iota
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000364 erofsType
mrziwang1a6291f2024-11-07 14:29:25 -0800365 f2fsType
Jiyong Park11a65972021-02-01 21:09:38 +0900366 compressedCpioType
Jiyong Park837cdb22021-02-05 00:17:14 +0900367 cpioType // uncompressed
Jiyong Park11a65972021-02-01 21:09:38 +0900368 unknown
369)
370
Spandan Das7a46f6c2024-10-14 18:41:18 +0000371func (fs fsType) IsUnknown() bool {
372 return fs == unknown
373}
374
Jihoon Kangf67b7de2025-02-12 01:01:09 +0000375type InstalledFilesStruct struct {
376 Txt android.Path
377 Json android.Path
378}
379
Cole Faust92ccbe22024-10-03 14:38:37 -0700380type FilesystemInfo struct {
Cole Faust44080412024-12-20 14:17:07 -0800381 // The built filesystem image
382 Output android.Path
Spandan Das1f0a5a12025-01-15 00:53:15 +0000383 // An additional hermetic filesystem image.
384 // e.g. this will contain inodes with pinned timestamps.
385 // This will be copied to target_files.zip
386 OutputHermetic android.Path
Cole Faust92ccbe22024-10-03 14:38:37 -0700387 // A text file containing the list of paths installed on the partition.
388 FileListFile android.Path
Cole Faust44080412024-12-20 14:17:07 -0800389 // The root staging directory used to build the output filesystem. If consuming this, make sure
390 // to add a dependency on the Output file, as you cannot add dependencies on directories
391 // in ninja.
392 RootDir android.Path
Cole Faust11fda332025-01-14 16:47:19 -0800393 // The rebased staging directory used to build the output filesystem. If consuming this, make
394 // sure to add a dependency on the Output file, as you cannot add dependencies on directories
395 // in ninja. In many cases this is the same as RootDir, only in the system partition is it
396 // different. There, it points to the "system" sub-directory of RootDir.
397 RebasedDir android.Path
Spandan Das33c9c472025-01-14 19:26:23 +0000398 // A text file with block data of the .img file
399 // This is an implicit output of `build_image`
400 MapFile android.Path
Cole Faust11fda332025-01-14 16:47:19 -0800401 // Name of the module that produced this FilesystemInfo origionally. (though it may be
402 // re-exported by super images or boot images)
403 ModuleName string
Cole Faust74ee4e02025-01-16 14:55:35 -0800404 // The property file generated by this module and passed to build_image.
405 // It's exported here so that system_other can reuse system's property file.
406 BuildImagePropFile android.Path
407 // Paths to all the tools referenced inside of the build image property file.
408 BuildImagePropFileDeps android.Paths
Cole Faustb8e280f2025-01-16 16:33:26 -0800409 // Packaging specs to be installed on the system_other image, for the initial boot's dexpreopt.
410 SpecsForSystemOther map[string]android.PackagingSpec
Cole Faust19fbb072025-01-30 18:19:29 -0800411
412 FullInstallPaths []FullInstallPathInfo
Jihoon Kangf67b7de2025-02-12 01:01:09 +0000413
414 // Installed files list
415 InstalledFiles InstalledFilesStruct
Cole Faust19fbb072025-01-30 18:19:29 -0800416}
417
418// FullInstallPathInfo contains information about the "full install" paths of all the files
419// inside this partition. The full install paths are the files installed in
420// out/target/product/<device>/<partition>. This is essentially legacy behavior, maintained for
421// tools like adb sync and adevice, but we should update them to query the build system for the
422// installed files no matter where they are.
423type FullInstallPathInfo struct {
424 // RequiresFullInstall tells us if the origional module did the install to FullInstallPath
425 // already. If it's false, the android_device module needs to emit the install rule.
426 RequiresFullInstall bool
427 // The "full install" paths for the files in this filesystem. This is the paths in the
428 // out/target/product/<device>/<partition> folder. They're not used by this filesystem,
429 // but can be depended on by the top-level android_device module to cause the staging
430 // directories to be built.
431 FullInstallPath android.InstallPath
432
433 // The file that's copied to FullInstallPath. May be nil if SymlinkTarget is set or IsDir is
434 // true.
435 SourcePath android.Path
436
437 // The target of the symlink, if this file is a symlink.
438 SymlinkTarget string
439
440 // If this file is a directory. Only used for empty directories, which are mostly mount points.
441 IsDir bool
Cole Faust92ccbe22024-10-03 14:38:37 -0700442}
443
444var FilesystemProvider = blueprint.NewProvider[FilesystemInfo]()
445
Yu Liufc8d5c12025-01-09 00:19:06 +0000446type FilesystemDefaultsInfo struct {
447 // Identifies which partition this is for //visibility:any_system_image (and others) visibility
448 // checks, and will be used in the future for API surface checks.
449 PartitionType string
450}
451
452var FilesystemDefaultsInfoProvider = blueprint.NewProvider[FilesystemDefaultsInfo]()
453
Spandan Das7a46f6c2024-10-14 18:41:18 +0000454func GetFsTypeFromString(ctx android.EarlyModuleContext, typeStr string) fsType {
Jiyong Park11a65972021-02-01 21:09:38 +0900455 switch typeStr {
456 case "ext4":
457 return ext4Type
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000458 case "erofs":
459 return erofsType
mrziwang1a6291f2024-11-07 14:29:25 -0800460 case "f2fs":
461 return f2fsType
Jiyong Park11a65972021-02-01 21:09:38 +0900462 case "compressed_cpio":
463 return compressedCpioType
Jiyong Park837cdb22021-02-05 00:17:14 +0900464 case "cpio":
465 return cpioType
Jiyong Park11a65972021-02-01 21:09:38 +0900466 default:
Jiyong Park11a65972021-02-01 21:09:38 +0900467 return unknown
468 }
469}
470
Spandan Das7a46f6c2024-10-14 18:41:18 +0000471func (f *filesystem) fsType(ctx android.ModuleContext) fsType {
472 typeStr := proptools.StringDefault(f.properties.Type, "ext4")
473 fsType := GetFsTypeFromString(ctx, typeStr)
474 if fsType == unknown {
475 ctx.PropertyErrorf("type", "%q not supported", typeStr)
476 }
477 return fsType
478}
479
Jiyong Park65c49f52020-11-24 14:23:26 +0900480func (f *filesystem) installFileName() string {
Spandan Dasc49b85e2025-01-10 00:51:25 +0000481 return proptools.StringDefault(f.properties.Stem, f.BaseModuleName()+".img")
Jiyong Park65c49f52020-11-24 14:23:26 +0900482}
483
Inseob Kim53391842024-03-29 17:44:07 +0900484func (f *filesystem) partitionName() string {
485 return proptools.StringDefault(f.properties.Partition_name, f.Name())
486}
487
Kiyoung Kim67118212024-11-07 13:23:44 +0900488func (f *filesystem) FilterPackagingSpec(ps android.PackagingSpec) bool {
Jiyong Park7e7d4af2024-05-01 12:36:10 +0000489 // Filesystem module respects the installation semantic. A PackagingSpec from a module with
490 // IsSkipInstall() is skipped.
Cole Faust76a6e952024-11-07 16:56:45 -0800491 if ps.SkipInstall() {
492 return false
Spandan Das6d056502024-10-21 15:40:32 +0000493 }
Cole Faust0d3fd562025-01-31 13:17:58 -0800494 // "apex" is a fake partition used to install files in out/target/product/<device>/apex/.
495 // Don't include these files in the partition. We should also look into removing the following
496 // TODO to check the PackagingSpec's partition against this filesystem's partition for all
497 // modules, not just autogenerated ones, which will fix this as well.
498 if ps.Partition() == "apex" {
499 return false
500 }
Cole Faust76a6e952024-11-07 16:56:45 -0800501 if proptools.Bool(f.properties.Is_auto_generated) { // TODO (spandandas): Remove this.
502 pt := f.PartitionType()
Cole Faustc88cff12024-11-12 13:24:05 -0800503 return ps.Partition() == pt || strings.HasPrefix(ps.Partition(), pt+"/")
Cole Faust76a6e952024-11-07 16:56:45 -0800504 }
505 return true
Jiyong Park7e7d4af2024-05-01 12:36:10 +0000506}
507
Inseob Kim3c0a0422024-11-05 17:21:37 +0900508func (f *filesystem) ModifyPackagingSpec(ps *android.PackagingSpec) {
Cole Faustc88cff12024-11-12 13:24:05 -0800509 // Sometimes, android.modulePartition() returns a path with >1 path components.
510 // This makes the partition field of packagingSpecs have multiple components, like
511 // "system/product". Right now, the filesystem module doesn't look at the partition field
512 // when deciding what path to install the file under, only the RelPathInPackage field, so
513 // we move the later path components from partition to relPathInPackage. This should probably
514 // be revisited in the future.
515 prefix := f.PartitionType() + "/"
516 if strings.HasPrefix(ps.Partition(), prefix) {
517 subPartition := strings.TrimPrefix(ps.Partition(), prefix)
518 ps.SetPartition(f.PartitionType())
519 ps.SetRelPathInPackage(filepath.Join(subPartition, ps.RelPathInPackage()))
520 }
Inseob Kim3c0a0422024-11-05 17:21:37 +0900521}
522
Jihoon Kangf67b7de2025-02-12 01:01:09 +0000523func buildInstalledFiles(ctx android.ModuleContext, partition string, rootDir android.Path, image android.Path) (txt android.ModuleOutPath, json android.ModuleOutPath) {
524 fileName := "installed-files"
525 if len(partition) > 0 {
526 fileName += fmt.Sprintf("-%s", partition)
527 }
528 txt = android.PathForModuleOut(ctx, fmt.Sprintf("%s.txt", fileName))
529 json = android.PathForModuleOut(ctx, fmt.Sprintf("%s.json", fileName))
530
531 ctx.Build(pctx, android.BuildParams{
532 Rule: installedFilesJsonRule,
533 Implicit: image,
534 Output: json,
535 Description: "Installed file list json",
536 Args: map[string]string{
537 "rootDir": rootDir.String(),
538 },
539 })
540
541 ctx.Build(pctx, android.BuildParams{
542 Rule: installedFilesTxtRule,
543 Input: json,
544 Output: txt,
545 Description: "Installed file list txt",
546 })
547
548 return txt, json
549}
550
Jiyong Park6f0f6882020-11-12 13:14:30 +0900551var pctx = android.NewPackageContext("android/soong/filesystem")
552
553func (f *filesystem) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900554 validatePartitionType(ctx, f)
Kiyoung Kim23be5bb2024-11-27 00:50:30 +0000555 if f.filesystemBuilder.ShouldUseVintfFragmentModuleOnly() {
556 f.validateVintfFragments(ctx)
557 }
Jihoon Kang6da80752024-12-23 18:53:32 +0000558
559 if len(f.properties.Include_files_of) > 0 && !android.InList(f.fsType(ctx), []fsType{compressedCpioType, cpioType}) {
560 ctx.PropertyErrorf("include_files_of", "include_files_of is only supported for cpio and compressed cpio filesystem types.")
561 }
562
Cole Faust62cfaeb2025-01-15 18:06:40 -0800563 rootDir := android.PathForModuleOut(ctx, f.rootDirString()).OutputPath
564 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
570 // Wipe the root dir to get rid of leftover files from prior builds
571 builder.Command().Textf("rm -rf %s && mkdir -p %s", rootDir, rootDir)
572 specs := f.gatherFilteredPackagingSpecs(ctx)
Cole Faust62cfaeb2025-01-15 18:06:40 -0800573
Cole Faust19fbb072025-01-30 18:19:29 -0800574 var fullInstallPaths []FullInstallPathInfo
575 for _, spec := range specs {
576 fullInstallPaths = append(fullInstallPaths, FullInstallPathInfo{
577 FullInstallPath: spec.FullInstallPath(),
578 RequiresFullInstall: spec.RequiresFullInstall(),
579 SourcePath: spec.SrcPath(),
580 SymlinkTarget: spec.ToGob().SymlinkTarget,
581 })
582 }
583
584 f.entries = f.copyPackagingSpecs(ctx, builder, specs, rootDir, rebasedDir)
585 f.buildNonDepsFiles(ctx, builder, rootDir, rebasedDir, &fullInstallPaths)
586 f.buildFsverityMetadataFiles(ctx, builder, specs, rootDir, rebasedDir, &fullInstallPaths)
587 f.buildEventLogtagsFile(ctx, builder, rebasedDir, &fullInstallPaths)
588 f.buildAconfigFlagsFiles(ctx, builder, specs, rebasedDir, &fullInstallPaths)
589 f.filesystemBuilder.BuildLinkerConfigFile(ctx, builder, rebasedDir, &fullInstallPaths)
Cole Faust62cfaeb2025-01-15 18:06:40 -0800590
Spandan Das33c9c472025-01-14 19:26:23 +0000591 var mapFile android.Path
Spandan Das1f0a5a12025-01-15 00:53:15 +0000592 var outputHermetic android.Path
Cole Faust74ee4e02025-01-16 14:55:35 -0800593 var buildImagePropFile android.Path
594 var buildImagePropFileDeps android.Paths
Jiyong Park11a65972021-02-01 21:09:38 +0900595 switch f.fsType(ctx) {
mrziwang1a6291f2024-11-07 14:29:25 -0800596 case ext4Type, erofsType, f2fsType:
Cole Faust74ee4e02025-01-16 14:55:35 -0800597 f.output, outputHermetic, buildImagePropFile, buildImagePropFileDeps = f.buildImageUsingBuildImage(ctx, builder, rootDir, rebasedDir)
Spandan Das33c9c472025-01-14 19:26:23 +0000598 mapFile = f.getMapFile(ctx)
Jiyong Park11a65972021-02-01 21:09:38 +0900599 case compressedCpioType:
Cole Faust62cfaeb2025-01-15 18:06:40 -0800600 f.output = f.buildCpioImage(ctx, builder, rootDir, true)
Jiyong Park837cdb22021-02-05 00:17:14 +0900601 case cpioType:
Cole Faust62cfaeb2025-01-15 18:06:40 -0800602 f.output = f.buildCpioImage(ctx, builder, rootDir, false)
Jiyong Park11a65972021-02-01 21:09:38 +0900603 default:
604 return
605 }
606
607 f.installDir = android.PathForModuleInstall(ctx, "etc")
608 ctx.InstallFile(f.installDir, f.installFileName(), f.output)
mrziwang555d1332024-06-07 11:15:33 -0700609 ctx.SetOutputFiles([]android.Path{f.output}, "")
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900610
Jihoon Kang6da80752024-12-23 18:53:32 +0000611 if f.partitionName() == "recovery" {
612 rootDir = rootDir.Join(ctx, "root")
613 }
614
Cole Faust4e9f5922024-11-13 16:09:23 -0800615 fileListFile := android.PathForModuleOut(ctx, "fileList")
616 android.WriteFileRule(ctx, fileListFile, f.installedFilesList())
Cole Faust92ccbe22024-10-03 14:38:37 -0700617
Jihoon Kangf67b7de2025-02-12 01:01:09 +0000618 partitionName := f.partitionName()
619 if partitionName == "system" {
620 partitionName = ""
621 }
622 installedFileTxt, installedFileJson := buildInstalledFiles(ctx, partitionName, rootDir, f.output)
623
Spandan Das33c9c472025-01-14 19:26:23 +0000624 fsInfo := FilesystemInfo{
Cole Faust74ee4e02025-01-16 14:55:35 -0800625 Output: f.output,
626 OutputHermetic: outputHermetic,
627 FileListFile: fileListFile,
628 RootDir: rootDir,
629 RebasedDir: rebasedDir,
630 MapFile: mapFile,
631 ModuleName: ctx.ModuleName(),
632 BuildImagePropFile: buildImagePropFile,
633 BuildImagePropFileDeps: buildImagePropFileDeps,
Cole Faustb8e280f2025-01-16 16:33:26 -0800634 SpecsForSystemOther: f.systemOtherFiles(ctx),
Cole Faust19fbb072025-01-30 18:19:29 -0800635 FullInstallPaths: fullInstallPaths,
Jihoon Kangf67b7de2025-02-12 01:01:09 +0000636 InstalledFiles: InstalledFilesStruct{
637 Txt: installedFileTxt,
638 Json: installedFileJson,
639 },
Spandan Das1f0a5a12025-01-15 00:53:15 +0000640 }
Spandan Das33c9c472025-01-14 19:26:23 +0000641
642 android.SetProvider(ctx, FilesystemProvider, fsInfo)
Spandan Das3ec6d062025-01-09 19:37:47 +0000643
Cole Faust4e9f5922024-11-13 16:09:23 -0800644 f.fileListFile = fileListFile
Cole Faust92ccbe22024-10-03 14:38:37 -0700645
646 if proptools.Bool(f.properties.Unchecked_module) {
647 ctx.UncheckedModule()
648 }
Jihoon Kang2f0d1932025-01-17 19:22:44 +0000649
650 f.setVbmetaPartitionProvider(ctx)
651}
652
653func (f *filesystem) setVbmetaPartitionProvider(ctx android.ModuleContext) {
654 var extractedPublicKey android.ModuleOutPath
655 if f.properties.Avb_private_key != nil {
656 key := android.PathForModuleSrc(ctx, proptools.String(f.properties.Avb_private_key))
657 extractedPublicKey = android.PathForModuleOut(ctx, f.partitionName()+".avbpubkey")
658 ctx.Build(pctx, android.BuildParams{
659 Rule: extractPublicKeyRule,
660 Input: key,
661 Output: extractedPublicKey,
662 })
663 }
664
665 var ril int
666 if f.properties.Rollback_index_location != nil {
667 ril = proptools.Int(f.properties.Rollback_index_location)
668 }
669
670 android.SetProvider(ctx, vbmetaPartitionProvider, vbmetaPartitionInfo{
671 Name: f.partitionName(),
672 RollbackIndexLocation: ril,
673 PublicKey: extractedPublicKey,
674 Output: f.output,
675 })
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900676}
677
Spandan Das33c9c472025-01-14 19:26:23 +0000678func (f *filesystem) getMapFile(ctx android.ModuleContext) android.WritablePath {
679 // create the filepath by replacing the extension of the corresponding img file
680 return android.PathForModuleOut(ctx, f.installFileName()).ReplaceExtension(ctx, "map")
681}
682
Kiyoung Kim23be5bb2024-11-27 00:50:30 +0000683func (f *filesystem) validateVintfFragments(ctx android.ModuleContext) {
684 visitedModule := map[string]bool{}
685 packagingSpecs := f.gatherFilteredPackagingSpecs(ctx)
686
687 moduleInFileSystem := func(mod android.Module) bool {
688 for _, ps := range android.OtherModuleProviderOrDefault(
689 ctx, mod, android.InstallFilesProvider).PackagingSpecs {
690 if _, ok := packagingSpecs[ps.RelPathInPackage()]; ok {
691 return true
692 }
693 }
694 return false
695 }
696
697 ctx.WalkDeps(func(child, parent android.Module) bool {
698 if visitedModule[child.Name()] {
699 return false
700 }
701 if !moduleInFileSystem(child) {
702 visitedModule[child.Name()] = true
703 return true
704 }
705 if vintfFragments := child.VintfFragments(ctx); vintfFragments != nil {
706 ctx.PropertyErrorf(
707 "vintf_fragments",
708 "Module %s is referenced by soong-defined filesystem %s with property vintf_fragments(%s) in use."+
709 " Use vintf_fragment_modules property instead.",
710 child.Name(),
711 f.BaseModuleName(),
712 strings.Join(vintfFragments, ", "),
713 )
714 }
715 visitedModule[child.Name()] = true
716 return true
717 })
718}
719
Cole Faust4e9f5922024-11-13 16:09:23 -0800720func (f *filesystem) appendToEntry(ctx android.ModuleContext, installedFile android.Path) {
Spandan Das420e16a2024-12-11 18:10:52 +0000721 partitionBaseDir := android.PathForModuleOut(ctx, f.rootDirString(), proptools.String(f.properties.Base_dir)).String() + "/"
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900722
723 relPath, inTargetPartition := strings.CutPrefix(installedFile.String(), partitionBaseDir)
724 if inTargetPartition {
725 f.entries = append(f.entries, relPath)
726 }
727}
728
729func (f *filesystem) installedFilesList() string {
730 installedFilePaths := android.FirstUniqueStrings(f.entries)
731 slices.Sort(installedFilePaths)
732
733 return strings.Join(installedFilePaths, "\n")
Jiyong Park11a65972021-02-01 21:09:38 +0900734}
735
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900736func validatePartitionType(ctx android.ModuleContext, p partition) {
737 if !android.InList(p.PartitionType(), validPartitions) {
738 ctx.PropertyErrorf("partition_type", "partition_type must be one of %s, found: %s", validPartitions, p.PartitionType())
739 }
740
Yu Liufc8d5c12025-01-09 00:19:06 +0000741 ctx.VisitDirectDepsProxyWithTag(android.DefaultsDepTag, func(m android.ModuleProxy) {
742 if fdm, ok := android.OtherModuleProvider(ctx, m, FilesystemDefaultsInfoProvider); ok {
743 if p.PartitionType() != fdm.PartitionType {
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900744 ctx.PropertyErrorf("partition_type",
745 "%s doesn't match with the partition type %s of the filesystem default module %s",
Yu Liufc8d5c12025-01-09 00:19:06 +0000746 p.PartitionType(), fdm.PartitionType, m.Name())
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900747 }
748 }
749 })
750}
751
Cole Faust3b806d32024-03-11 15:15:03 -0700752// Copy extra files/dirs that are not from the `deps` property to `rootDir`, checking for conflicts with files
753// already in `rootDir`.
Cole Faust19fbb072025-01-30 18:19:29 -0800754func (f *filesystem) buildNonDepsFiles(
755 ctx android.ModuleContext,
756 builder *android.RuleBuilder,
757 rootDir android.OutputPath,
758 rebasedDir android.OutputPath,
759 fullInstallPaths *[]FullInstallPathInfo,
760) {
761 rebasedPrefix, err := filepath.Rel(rootDir.String(), rebasedDir.String())
762 if err != nil || strings.HasPrefix(rebasedPrefix, "../") {
763 panic("rebasedDir could not be made relative to rootDir")
764 }
765 if !strings.HasSuffix(rebasedPrefix, "/") {
766 rebasedPrefix += "/"
767 }
768 if rebasedPrefix == "./" {
769 rebasedPrefix = ""
770 }
771
Inseob Kim14199b02021-02-09 21:18:31 +0900772 // create dirs and symlinks
Cole Faustd9c6a5b2024-05-21 14:54:00 -0700773 for _, dir := range f.properties.Dirs.GetOrDefault(ctx, nil) {
Inseob Kim14199b02021-02-09 21:18:31 +0900774 // OutputPath.Join verifies dir
775 builder.Command().Text("mkdir -p").Text(rootDir.Join(ctx, dir).String())
Cole Faust19fbb072025-01-30 18:19:29 -0800776 // Only add the fullInstallPath logic for files in the rebased dir. The root dir
777 // is harder to install to.
778 if strings.HasPrefix(dir, rebasedPrefix) {
779 *fullInstallPaths = append(*fullInstallPaths, FullInstallPathInfo{
780 FullInstallPath: android.PathForModuleInPartitionInstall(ctx, f.PartitionType(), strings.TrimPrefix(dir, rebasedPrefix)),
781 IsDir: true,
782 })
783 }
Inseob Kim14199b02021-02-09 21:18:31 +0900784 }
785
786 for _, symlink := range f.properties.Symlinks {
787 name := strings.TrimSpace(proptools.String(symlink.Name))
788 target := strings.TrimSpace(proptools.String(symlink.Target))
789
790 if name == "" {
791 ctx.PropertyErrorf("symlinks", "Name can't be empty")
792 continue
793 }
794
795 if target == "" {
796 ctx.PropertyErrorf("symlinks", "Target can't be empty")
797 continue
798 }
799
800 // OutputPath.Join verifies name. don't need to verify target.
801 dst := rootDir.Join(ctx, name)
Cole Faust3b806d32024-03-11 15:15:03 -0700802 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 +0900803 builder.Command().Text("mkdir -p").Text(filepath.Dir(dst.String()))
804 builder.Command().Text("ln -sf").Text(proptools.ShellEscape(target)).Text(dst.String())
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900805 f.appendToEntry(ctx, dst)
Cole Faust19fbb072025-01-30 18:19:29 -0800806 // Only add the fullInstallPath logic for files in the rebased dir. The root dir
807 // is harder to install to.
808 if strings.HasPrefix(name, rebasedPrefix) {
809 *fullInstallPaths = append(*fullInstallPaths, FullInstallPathInfo{
810 FullInstallPath: android.PathForModuleInPartitionInstall(ctx, f.PartitionType(), strings.TrimPrefix(name, rebasedPrefix)),
811 SymlinkTarget: target,
812 })
813 }
Inseob Kim14199b02021-02-09 21:18:31 +0900814 }
Jihoon Kang89e8a692024-12-18 19:28:33 +0000815
816 // https://cs.android.com/android/platform/superproject/main/+/main:build/make/core/Makefile;l=2835;drc=b186569ef00ff2f2a1fab28aedc75ebc32bcd67b
817 if f.partitionName() == "recovery" {
818 builder.Command().Text("mkdir -p").Text(rootDir.Join(ctx, "root/linkerconfig").String())
819 builder.Command().Text("touch").Text(rootDir.Join(ctx, "root/linkerconfig/ld.config.txt").String())
820 }
Inseob Kim2ce1b5d2021-02-15 17:01:04 +0900821}
822
Inseob Kim33f95a92024-07-11 15:44:49 +0900823func (f *filesystem) copyPackagingSpecs(ctx android.ModuleContext, builder *android.RuleBuilder, specs map[string]android.PackagingSpec, rootDir, rebasedDir android.WritablePath) []string {
824 rootDirSpecs := make(map[string]android.PackagingSpec)
825 rebasedDirSpecs := make(map[string]android.PackagingSpec)
826
827 for rel, spec := range specs {
828 if spec.Partition() == "root" {
829 rootDirSpecs[rel] = spec
830 } else {
831 rebasedDirSpecs[rel] = spec
832 }
833 }
834
835 dirsToSpecs := make(map[android.WritablePath]map[string]android.PackagingSpec)
836 dirsToSpecs[rootDir] = rootDirSpecs
837 dirsToSpecs[rebasedDir] = rebasedDirSpecs
838
839 return f.CopySpecsToDirs(ctx, builder, dirsToSpecs)
840}
841
Spandan Das420e16a2024-12-11 18:10:52 +0000842func (f *filesystem) rootDirString() string {
843 return f.partitionName()
844}
845
Cole Faust62cfaeb2025-01-15 18:06:40 -0800846func (f *filesystem) buildImageUsingBuildImage(
847 ctx android.ModuleContext,
848 builder *android.RuleBuilder,
849 rootDir android.OutputPath,
850 rebasedDir android.OutputPath,
Cole Faust74ee4e02025-01-16 14:55:35 -0800851) (android.Path, android.Path, android.Path, android.Paths) {
Nikita Ioffe519015f2022-12-23 15:36:29 +0000852 // run host_init_verifier
853 // Ideally we should have a concept of pluggable linters that verify the generated image.
854 // While such concept is not implement this will do.
855 // TODO(b/263574231): substitute with pluggable linter.
856 builder.Command().
857 BuiltTool("host_init_verifier").
858 FlagWithArg("--out_system=", rootDir.String()+"/system")
859
Jiyong Park72678312021-01-18 17:29:49 +0900860 propFile, toolDeps := f.buildPropFile(ctx)
Cole Fauste1676122024-12-03 17:32:25 -0800861
862 // Most of the time, if build_image were to call a host tool, it accepts the path to the
863 // host tool in a field in the prop file. However, it doesn't have that option for fec, which
864 // it expects to just be on the PATH. Add fec to the PATH.
865 fec := ctx.Config().HostToolPath(ctx, "fec")
866 pathToolDirs := []string{filepath.Dir(fec.String())}
867
Cole Faust4e9f5922024-11-13 16:09:23 -0800868 output := android.PathForModuleOut(ctx, f.installFileName())
Spandan Das33c9c472025-01-14 19:26:23 +0000869 builder.Command().Text("touch").Output(f.getMapFile(ctx))
Cole Fauste1676122024-12-03 17:32:25 -0800870 builder.Command().
871 Textf("PATH=%s:$PATH", strings.Join(pathToolDirs, ":")).
872 BuiltTool("build_image").
Jiyong Park6f0f6882020-11-12 13:14:30 +0900873 Text(rootDir.String()). // input directory
874 Input(propFile).
Jiyong Park72678312021-01-18 17:29:49 +0900875 Implicits(toolDeps).
Cole Fauste1676122024-12-03 17:32:25 -0800876 Implicit(fec).
Jiyong Park11a65972021-02-01 21:09:38 +0900877 Output(output).
Jiyong Park6f0f6882020-11-12 13:14:30 +0900878 Text(rootDir.String()) // directory where to find fs_config_files|dirs
879
Spandan Das3ccda6e2025-01-30 00:22:05 +0000880 // TODO (b/393203512): Re-enable hermetic img file creation for target_files.zip
Spandan Das1f0a5a12025-01-15 00:53:15 +0000881 // Add an additional cmd to create a hermetic img file. This will contain pinned timestamps e.g.
Spandan Das3ccda6e2025-01-30 00:22:05 +0000882 //propFilePinnedTimestamp := android.PathForModuleOut(ctx, "for_target_files", "prop")
883 //builder.Command().Textf("cat").Input(propFile).Flag(">").Output(propFilePinnedTimestamp).
884 // Textf(" && echo use_fixed_timestamp=true >> %s", propFilePinnedTimestamp).
885 // Textf(" && echo block_list=%s >> %s", f.getMapFile(ctx).String(), propFilePinnedTimestamp) // mapfile will be an implicit output
Spandan Das1f0a5a12025-01-15 00:53:15 +0000886
Spandan Das3ccda6e2025-01-30 00:22:05 +0000887 //outputHermetic := android.PathForModuleOut(ctx, "for_target_files", f.installFileName())
888 //builder.Command().
889 // Textf("PATH=%s:$PATH", strings.Join(pathToolDirs, ":")).
890 // BuiltTool("build_image").
891 // Text(rootDir.String()). // input directory
892 // Flag(propFilePinnedTimestamp.String()).
893 // Implicits(toolDeps).
894 // Implicit(fec).
895 // Output(outputHermetic).
896 // Text(rootDir.String()) // directory where to find fs_config_files|dirs
Spandan Das1f0a5a12025-01-15 00:53:15 +0000897
Jihoon Kang983dd882025-01-13 23:14:11 +0000898 if f.properties.Partition_size != nil {
899 assertMaxImageSize(builder, output, *f.properties.Partition_size, false)
900 }
901
Jiyong Park6f0f6882020-11-12 13:14:30 +0900902 // rootDir is not deleted. Might be useful for quick inspection.
Colin Crossf1a035e2020-11-16 17:32:30 -0800903 builder.Build("build_filesystem_image", fmt.Sprintf("Creating filesystem %s", f.BaseModuleName()))
Jiyong Park65c49f52020-11-24 14:23:26 +0900904
Spandan Das3ccda6e2025-01-30 00:22:05 +0000905 return output, nil, propFile, toolDeps
Jiyong Park65c49f52020-11-24 14:23:26 +0900906}
907
Cole Faust4e9f5922024-11-13 16:09:23 -0800908func (f *filesystem) buildFileContexts(ctx android.ModuleContext) android.Path {
Inseob Kimcc8e5362021-02-03 14:05:24 +0900909 builder := android.NewRuleBuilder(pctx, ctx)
910 fcBin := android.PathForModuleOut(ctx, "file_contexts.bin")
911 builder.Command().BuiltTool("sefcontext_compile").
912 FlagWithOutput("-o ", fcBin).
913 Input(android.PathForModuleSrc(ctx, proptools.String(f.properties.File_contexts)))
914 builder.Build("build_filesystem_file_contexts", fmt.Sprintf("Creating filesystem file contexts for %s", f.BaseModuleName()))
Cole Faust4e9f5922024-11-13 16:09:23 -0800915 return fcBin
Inseob Kimcc8e5362021-02-03 14:05:24 +0900916}
917
Cole Faust4e9f5922024-11-13 16:09:23 -0800918func (f *filesystem) buildPropFile(ctx android.ModuleContext) (android.Path, android.Paths) {
Jiyong Park72678312021-01-18 17:29:49 +0900919 var deps android.Paths
Cole Fauste03ab892025-01-17 13:55:04 -0800920 var lines []string
Jiyong Park72678312021-01-18 17:29:49 +0900921 addStr := func(name string, value string) {
Cole Fauste03ab892025-01-17 13:55:04 -0800922 lines = append(lines, fmt.Sprintf("%s=%s", name, value))
Jiyong Park72678312021-01-18 17:29:49 +0900923 }
924 addPath := func(name string, path android.Path) {
Cole Faustcec230a2024-03-07 15:51:12 -0800925 addStr(name, path.String())
Jiyong Park72678312021-01-18 17:29:49 +0900926 deps = append(deps, path)
927 }
928
Jiyong Park11a65972021-02-01 21:09:38 +0900929 // Type string that build_image.py accepts.
930 fsTypeStr := func(t fsType) string {
931 switch t {
Spandan Das94668822024-10-09 20:51:33 +0000932 // TODO(372522486): add more types like f2fs, erofs, etc.
Jiyong Park11a65972021-02-01 21:09:38 +0900933 case ext4Type:
934 return "ext4"
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000935 case erofsType:
936 return "erofs"
mrziwang1a6291f2024-11-07 14:29:25 -0800937 case f2fsType:
938 return "f2fs"
Jiyong Park11a65972021-02-01 21:09:38 +0900939 }
940 panic(fmt.Errorf("unsupported fs type %v", t))
941 }
942
943 addStr("fs_type", fsTypeStr(f.fsType(ctx)))
Inseob Kim376d72f2023-11-01 15:40:25 +0900944 addStr("mount_point", proptools.StringDefault(f.properties.Mount_point, "/"))
Jiyong Park72678312021-01-18 17:29:49 +0900945 addStr("use_dynamic_partition_size", "true")
946 addPath("ext_mkuserimg", ctx.Config().HostToolPath(ctx, "mkuserimg_mke2fs"))
947 // b/177813163 deps of the host tools have to be added. Remove this.
948 for _, t := range []string{"mke2fs", "e2fsdroid", "tune2fs"} {
949 deps = append(deps, ctx.Config().HostToolPath(ctx, t))
950 }
951
Jiyong Park71baa762021-01-18 21:11:03 +0900952 if proptools.Bool(f.properties.Use_avb) {
953 addStr("avb_hashtree_enable", "true")
954 addPath("avb_avbtool", ctx.Config().HostToolPath(ctx, "avbtool"))
955 algorithm := proptools.StringDefault(f.properties.Avb_algorithm, "SHA256_RSA4096")
956 addStr("avb_algorithm", algorithm)
Cole Fauste1676122024-12-03 17:32:25 -0800957 if f.properties.Avb_private_key != nil {
958 key := android.PathForModuleSrc(ctx, *f.properties.Avb_private_key)
959 addPath("avb_key_path", key)
960 }
Inseob Kim53391842024-03-29 17:44:07 +0900961 addStr("partition_name", f.partitionName())
Cole Fauste1676122024-12-03 17:32:25 -0800962 avb_add_hashtree_footer_args := ""
963 if !proptools.BoolDefault(f.properties.Use_fec, true) {
964 avb_add_hashtree_footer_args += " --do_not_generate_fec"
965 }
Nikita Ioffe50fb49c2025-01-24 13:49:00 +0000966 hashAlgorithm := proptools.StringDefault(f.properties.Avb_hash_algorithm, "sha256")
967 avb_add_hashtree_footer_args += " --hash_algorithm " + hashAlgorithm
Nikita Ioffe2c8cdc62024-03-27 22:19:30 +0000968 if f.properties.Rollback_index != nil {
969 rollbackIndex := proptools.Int(f.properties.Rollback_index)
970 if rollbackIndex < 0 {
971 ctx.PropertyErrorf("rollback_index", "Rollback index must be non-negative")
972 }
973 avb_add_hashtree_footer_args += " --rollback_index " + strconv.Itoa(rollbackIndex)
974 }
Cole Fauste1676122024-12-03 17:32:25 -0800975 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 -0800976 // We're not going to add BuildFingerPrintFile as a dep. If it changed, it's likely because
977 // the build number changed, and we don't want to trigger rebuilds solely based on the build
978 // number.
Cole Fauste1676122024-12-03 17:32:25 -0800979 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 +0000980 if f.properties.Security_patch != nil && proptools.String(f.properties.Security_patch) != "" {
981 avb_add_hashtree_footer_args += fmt.Sprintf(" --prop com.android.build.%s.security_patch:%s", f.partitionName(), proptools.String(f.properties.Security_patch))
982 }
Shikha Panware6f30632022-12-21 12:54:45 +0000983 addStr("avb_add_hashtree_footer_args", avb_add_hashtree_footer_args)
Jiyong Park71baa762021-01-18 21:11:03 +0900984 }
985
Cole Faust0d467052024-12-04 17:19:19 -0800986 if f.properties.File_contexts != nil && f.properties.Precompiled_file_contexts != nil {
987 ctx.ModuleErrorf("file_contexts and precompiled_file_contexts cannot both be set")
988 } else if f.properties.File_contexts != nil {
Inseob Kimcc8e5362021-02-03 14:05:24 +0900989 addPath("selinux_fc", f.buildFileContexts(ctx))
Cole Faust0d467052024-12-04 17:19:19 -0800990 } else if f.properties.Precompiled_file_contexts != nil {
991 src := android.PathForModuleSrc(ctx, *f.properties.Precompiled_file_contexts)
992 if src != nil {
993 addPath("selinux_fc", src)
994 }
Inseob Kimcc8e5362021-02-03 14:05:24 +0900995 }
Jooyung Han65f402b2022-04-21 14:24:04 +0900996 if timestamp := proptools.String(f.properties.Fake_timestamp); timestamp != "" {
997 addStr("timestamp", timestamp)
Spandan Dasa0ddc512025-01-06 20:23:55 +0000998 } else if ctx.Config().Getenv("USE_FIXED_TIMESTAMP_IMG_FILES") == "true" {
999 addStr("use_fixed_timestamp", "true")
Jooyung Han65f402b2022-04-21 14:24:04 +09001000 }
Spandan Dasa0ddc512025-01-06 20:23:55 +00001001
Jooyung Han65f402b2022-04-21 14:24:04 +09001002 if uuid := proptools.String(f.properties.Uuid); uuid != "" {
1003 addStr("uuid", uuid)
1004 addStr("hash_seed", uuid)
1005 }
mrziwang1a6291f2024-11-07 14:29:25 -08001006
Jihoon Kang40551e62025-01-14 21:55:08 +00001007 // Disable sparse only when partition size is not defined. disable_sparse has the same
1008 // effect as <partition name>_disable_sparse.
1009 if f.properties.Partition_size == nil {
1010 addStr("disable_sparse", "true")
1011 }
Cole Faust43a52c72024-11-26 12:46:08 -08001012
mrziwang1a6291f2024-11-07 14:29:25 -08001013 fst := f.fsType(ctx)
1014 switch fst {
1015 case erofsType:
1016 // Add erofs properties
Cole Faust3e730972024-12-03 13:12:08 -08001017 addStr("erofs_default_compressor", proptools.StringDefault(f.properties.Erofs.Compressor, "lz4hc,9"))
1018 if f.properties.Erofs.Compress_hints != nil {
1019 src := android.PathForModuleSrc(ctx, *f.properties.Erofs.Compress_hints)
1020 addPath("erofs_default_compress_hints", src)
Spandan Dasc35d6fb2024-10-10 17:51:14 +00001021 }
1022 if proptools.BoolDefault(f.properties.Erofs.Sparse, true) {
1023 // https://source.corp.google.com/h/googleplex-android/platform/build/+/88b1c67239ca545b11580237242774b411f2fed9:core/Makefile;l=2292;bpv=1;bpt=0;drc=ea8f34bc1d6e63656b4ec32f2391e9d54b3ebb6b
1024 addStr("erofs_sparse_flag", "-s")
1025 }
mrziwang1a6291f2024-11-07 14:29:25 -08001026 case f2fsType:
1027 if proptools.BoolDefault(f.properties.F2fs.Sparse, true) {
1028 // https://source.corp.google.com/h/googleplex-android/platform/build/+/88b1c67239ca545b11580237242774b411f2fed9:core/Makefile;l=2294;drc=ea8f34bc1d6e63656b4ec32f2391e9d54b3ebb6b;bpv=1;bpt=0
1029 addStr("f2fs_sparse_flag", "-S")
1030 }
Spandan Dasc35d6fb2024-10-10 17:51:14 +00001031 }
mrziwang1a6291f2024-11-07 14:29:25 -08001032 f.checkFsTypePropertyError(ctx, fst, fsTypeStr(fst))
Spandan Dasc35d6fb2024-10-10 17:51:14 +00001033
Jihoon Kang983dd882025-01-13 23:14:11 +00001034 if f.properties.Partition_size != nil {
1035 addStr("partition_size", strconv.FormatInt(*f.properties.Partition_size, 10))
1036 }
1037
Jihoon Kang6d08d922025-01-14 18:31:57 +00001038 if proptools.BoolDefault(f.properties.Support_casefolding, false) {
1039 addStr("needs_casefold", "1")
1040 }
1041
1042 if proptools.BoolDefault(f.properties.Support_project_quota, false) {
1043 addStr("needs_projid", "1")
1044 }
1045
1046 if proptools.BoolDefault(f.properties.Enable_compression, false) {
1047 addStr("needs_compress", "1")
1048 }
1049
Cole Fauste03ab892025-01-17 13:55:04 -08001050 sort.Strings(lines)
1051
Cole Fauste1676122024-12-03 17:32:25 -08001052 propFilePreProcessing := android.PathForModuleOut(ctx, "prop_pre_processing")
Cole Fauste03ab892025-01-17 13:55:04 -08001053 android.WriteFileRule(ctx, propFilePreProcessing, strings.Join(lines, "\n"))
Cole Faust4e9f5922024-11-13 16:09:23 -08001054 propFile := android.PathForModuleOut(ctx, "prop")
Cole Fauste1676122024-12-03 17:32:25 -08001055 ctx.Build(pctx, android.BuildParams{
Cole Faustefeb5c42024-12-16 10:47:26 -08001056 Rule: textFileProcessorRule,
1057 Input: propFilePreProcessing,
1058 Output: propFile,
Cole Fauste1676122024-12-03 17:32:25 -08001059 })
Jiyong Park72678312021-01-18 17:29:49 +09001060 return propFile, deps
1061}
1062
mrziwang1a6291f2024-11-07 14:29:25 -08001063// This method checks if there is any property set for the fstype(s) other than
1064// the current fstype.
1065func (f *filesystem) checkFsTypePropertyError(ctx android.ModuleContext, t fsType, fs string) {
1066 raiseError := func(otherFsType, currentFsType string) {
1067 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)
1068 ctx.PropertyErrorf(otherFsType, errMsg)
1069 }
1070
1071 if t != erofsType {
1072 if f.properties.Erofs.Compressor != nil || f.properties.Erofs.Compress_hints != nil || f.properties.Erofs.Sparse != nil {
1073 raiseError("erofs", fs)
1074 }
1075 }
1076 if t != f2fsType {
1077 if f.properties.F2fs.Sparse != nil {
1078 raiseError("f2fs", fs)
1079 }
1080 }
1081}
1082
Jihoon Kang6da80752024-12-23 18:53:32 +00001083func includeFilesRootDir(ctx android.ModuleContext) (rootDirs android.Paths, partitions android.Paths) {
1084 ctx.VisitDirectDepsWithTag(interPartitionInstallDependencyTag, func(m android.Module) {
1085 if fsProvider, ok := android.OtherModuleProvider(ctx, m, FilesystemProvider); ok {
1086 rootDirs = append(rootDirs, fsProvider.RootDir)
1087 partitions = append(partitions, fsProvider.Output)
1088 } else {
1089 ctx.PropertyErrorf("include_files_of", "only filesystem modules can be listed in "+
1090 "include_files_of but %s is not a filesystem module", m.Name())
1091 }
1092 })
1093 return rootDirs, partitions
1094}
1095
Cole Faust62cfaeb2025-01-15 18:06:40 -08001096func (f *filesystem) buildCpioImage(
1097 ctx android.ModuleContext,
1098 builder *android.RuleBuilder,
1099 rootDir android.OutputPath,
1100 compressed bool,
1101) android.Path {
Jiyong Park11a65972021-02-01 21:09:38 +09001102 if proptools.Bool(f.properties.Use_avb) {
1103 ctx.PropertyErrorf("use_avb", "signing compresed cpio image using avbtool is not supported."+
1104 "Consider adding this to bootimg module and signing the entire boot image.")
1105 }
1106
Inseob Kimcc8e5362021-02-03 14:05:24 +09001107 if proptools.String(f.properties.File_contexts) != "" {
1108 ctx.PropertyErrorf("file_contexts", "file_contexts is not supported for compressed cpio image.")
1109 }
1110
Jihoon Kang6da80752024-12-23 18:53:32 +00001111 rootDirs, partitions := includeFilesRootDir(ctx)
1112
Cole Faust4e9f5922024-11-13 16:09:23 -08001113 output := android.PathForModuleOut(ctx, f.installFileName())
Jiyong Park837cdb22021-02-05 00:17:14 +09001114 cmd := builder.Command().
Jiyong Park11a65972021-02-01 21:09:38 +09001115 BuiltTool("mkbootfs").
Jiyong Park837cdb22021-02-05 00:17:14 +09001116 Text(rootDir.String()) // input directory
Jihoon Kang6da80752024-12-23 18:53:32 +00001117
1118 for i := range len(rootDirs) {
1119 cmd.Text(rootDirs[i].String())
1120 }
1121 cmd.Implicits(partitions)
1122
Jihoon Kang6c03c8e2024-11-18 21:30:22 +00001123 if nodeList := f.properties.Dev_nodes_description_file; nodeList != nil {
1124 cmd.FlagWithInput("-n ", android.PathForModuleSrc(ctx, proptools.String(nodeList)))
1125 }
Jiyong Park837cdb22021-02-05 00:17:14 +09001126 if compressed {
1127 cmd.Text("|").
1128 BuiltTool("lz4").
1129 Flag("--favor-decSpeed"). // for faster boot
1130 Flag("-12"). // maximum compression level
1131 Flag("-l"). // legacy format for kernel
1132 Text(">").Output(output)
1133 } else {
1134 cmd.Text(">").Output(output)
1135 }
Jiyong Park11a65972021-02-01 21:09:38 +09001136
1137 // rootDir is not deleted. Might be useful for quick inspection.
Jiyong Park837cdb22021-02-05 00:17:14 +09001138 builder.Build("build_cpio_image", fmt.Sprintf("Creating filesystem %s", f.BaseModuleName()))
Jiyong Park11a65972021-02-01 21:09:38 +09001139
Cole Faust62cfaeb2025-01-15 18:06:40 -08001140 return output
Jiyong Park11a65972021-02-01 21:09:38 +09001141}
1142
Cole Faust4a2a7c92024-03-12 12:44:40 -07001143var validPartitions = []string{
1144 "system",
1145 "userdata",
1146 "cache",
1147 "system_other",
1148 "vendor",
1149 "product",
1150 "system_ext",
1151 "odm",
1152 "vendor_dlkm",
1153 "odm_dlkm",
1154 "system_dlkm",
Cole Faust76a6e952024-11-07 16:56:45 -08001155 "ramdisk",
Cole Faust24938e22024-11-18 14:01:58 -08001156 "vendor_ramdisk",
Jihoon Kang3216c982024-12-02 19:42:20 +00001157 "recovery",
Cole Faust4a2a7c92024-03-12 12:44:40 -07001158}
1159
Cole Faust19fbb072025-01-30 18:19:29 -08001160func (f *filesystem) buildEventLogtagsFile(
1161 ctx android.ModuleContext,
1162 builder *android.RuleBuilder,
1163 rebasedDir android.OutputPath,
1164 fullInstallPaths *[]FullInstallPathInfo,
1165) {
Inseob Kimb7b84572024-04-30 10:51:47 +09001166 if !proptools.Bool(f.properties.Build_logtags) {
1167 return
1168 }
1169
Inseob Kimb7b84572024-04-30 10:51:47 +09001170 etcPath := rebasedDir.Join(ctx, "etc")
1171 eventLogtagsPath := etcPath.Join(ctx, "event-log-tags")
1172 builder.Command().Text("mkdir").Flag("-p").Text(etcPath.String())
Cole Fauste4506af2024-12-11 14:14:50 -08001173 builder.Command().Text("cp").Input(android.MergedLogtagsPath(ctx)).Text(eventLogtagsPath.String())
Kiyoung Kim99a954d2024-06-21 14:22:20 +09001174
Cole Faust19fbb072025-01-30 18:19:29 -08001175 *fullInstallPaths = append(*fullInstallPaths, FullInstallPathInfo{
1176 FullInstallPath: android.PathForModuleInPartitionInstall(ctx, f.PartitionType(), "etc", "event-log-tags"),
1177 SourcePath: android.MergedLogtagsPath(ctx),
1178 })
1179
Kiyoung Kim99a954d2024-06-21 14:22:20 +09001180 f.appendToEntry(ctx, eventLogtagsPath)
Inseob Kimb7b84572024-04-30 10:51:47 +09001181}
1182
Cole Faust19fbb072025-01-30 18:19:29 -08001183func (f *filesystem) BuildLinkerConfigFile(
1184 ctx android.ModuleContext,
1185 builder *android.RuleBuilder,
1186 rebasedDir android.OutputPath,
1187 fullInstallPaths *[]FullInstallPathInfo,
1188) {
Spandan Das2047a4c2024-11-11 21:24:58 +00001189 if !proptools.Bool(f.properties.Linker_config.Gen_linker_config) {
Spandan Das92631882024-10-28 22:49:38 +00001190 return
1191 }
1192
Spandan Das918191e2024-10-31 18:27:23 +00001193 provideModules, _ := f.getLibsForLinkerConfig(ctx)
Cole Faustfee27012024-12-13 14:10:31 -08001194 intermediateOutput := android.PathForModuleOut(ctx, "linker.config.pb")
1195 linkerconfig.BuildLinkerConfig(ctx, android.PathsForModuleSrc(ctx, f.properties.Linker_config.Linker_config_srcs), provideModules, nil, intermediateOutput)
Spandan Das92631882024-10-28 22:49:38 +00001196 output := rebasedDir.Join(ctx, "etc", "linker.config.pb")
Cole Faustfee27012024-12-13 14:10:31 -08001197 builder.Command().Text("cp").Input(intermediateOutput).Output(output)
Spandan Das92631882024-10-28 22:49:38 +00001198
Cole Faust19fbb072025-01-30 18:19:29 -08001199 *fullInstallPaths = append(*fullInstallPaths, FullInstallPathInfo{
1200 FullInstallPath: android.PathForModuleInPartitionInstall(ctx, f.PartitionType(), "etc", "linker.config.pb"),
1201 SourcePath: intermediateOutput,
1202 })
1203
Spandan Das92631882024-10-28 22:49:38 +00001204 f.appendToEntry(ctx, output)
1205}
1206
Kiyoung Kim23be5bb2024-11-27 00:50:30 +00001207func (f *filesystem) ShouldUseVintfFragmentModuleOnly() bool {
1208 return false
1209}
1210
Jiyong Parkf46b1af2024-04-05 18:13:33 +09001211type partition interface {
1212 PartitionType() string
1213}
1214
Cole Faust9a24d902024-03-18 15:38:12 -07001215func (f *filesystem) PartitionType() string {
1216 return proptools.StringDefault(f.properties.Partition_type, "system")
1217}
1218
Jiyong Parkf46b1af2024-04-05 18:13:33 +09001219var _ partition = (*filesystem)(nil)
1220
Jiyong Park65c49f52020-11-24 14:23:26 +09001221var _ android.AndroidMkEntriesProvider = (*filesystem)(nil)
1222
1223// Implements android.AndroidMkEntriesProvider
1224func (f *filesystem) AndroidMkEntries() []android.AndroidMkEntries {
1225 return []android.AndroidMkEntries{android.AndroidMkEntries{
1226 Class: "ETC",
1227 OutputFile: android.OptionalPathForPath(f.output),
1228 ExtraEntries: []android.AndroidMkExtraEntriesFunc{
Colin Crossaa255532020-07-03 13:18:24 -07001229 func(ctx android.AndroidMkExtraEntriesContext, entries *android.AndroidMkEntries) {
Colin Crossc68db4b2021-11-11 18:59:15 -08001230 entries.SetString("LOCAL_MODULE_PATH", f.installDir.String())
Jiyong Park65c49f52020-11-24 14:23:26 +09001231 entries.SetString("LOCAL_INSTALLED_MODULE_STEM", f.installFileName())
Kiyoung Kim99a954d2024-06-21 14:22:20 +09001232 entries.SetString("LOCAL_FILESYSTEM_FILELIST", f.fileListFile.String())
Jiyong Park65c49f52020-11-24 14:23:26 +09001233 },
1234 },
1235 }}
Jiyong Park6f0f6882020-11-12 13:14:30 +09001236}
Jiyong Park12a719c2021-01-07 15:31:24 +09001237
1238// Filesystem is the public interface for the filesystem struct. Currently, it's only for the apex
1239// package to have access to the output file.
1240type Filesystem interface {
1241 android.Module
1242 OutputPath() android.Path
Jiyong Park972e06c2021-03-15 23:32:49 +09001243
1244 // Returns the output file that is signed by avbtool. If this module is not signed, returns
1245 // nil.
1246 SignedOutputPath() android.Path
Jiyong Park12a719c2021-01-07 15:31:24 +09001247}
1248
1249var _ Filesystem = (*filesystem)(nil)
1250
1251func (f *filesystem) OutputPath() android.Path {
1252 return f.output
1253}
Jiyong Park972e06c2021-03-15 23:32:49 +09001254
1255func (f *filesystem) SignedOutputPath() android.Path {
1256 if proptools.Bool(f.properties.Use_avb) {
1257 return f.OutputPath()
1258 }
1259 return nil
1260}
Jooyung Han0fbbc2b2022-03-25 12:35:46 +09001261
1262// Filter the result of GatherPackagingSpecs to discard items targeting outside "system" partition.
1263// Note that "apex" module installs its contents to "apex"(fake partition) as well
1264// for symbol lookup by imitating "activated" paths.
1265func (f *filesystem) gatherFilteredPackagingSpecs(ctx android.ModuleContext) map[string]android.PackagingSpec {
Cole Faustb8e280f2025-01-16 16:33:26 -08001266 return f.PackagingBase.GatherPackagingSpecsWithFilterAndModifier(ctx, f.filesystemBuilder.FilterPackagingSpec, f.filesystemBuilder.ModifyPackagingSpec)
1267}
1268
1269// Dexpreopt files are installed to system_other. Collect the packaingSpecs for the dexpreopt files
1270// from this partition to export to the system_other partition later.
1271func (f *filesystem) systemOtherFiles(ctx android.ModuleContext) map[string]android.PackagingSpec {
1272 filter := func(spec android.PackagingSpec) bool {
1273 // For some reason system_other packaging specs don't set the partition field.
1274 return strings.HasPrefix(spec.RelPathInPackage(), "system_other/")
1275 }
1276 modifier := func(spec *android.PackagingSpec) {
1277 spec.SetRelPathInPackage(strings.TrimPrefix(spec.RelPathInPackage(), "system_other/"))
1278 spec.SetPartition("system_other")
1279 }
1280 return f.PackagingBase.GatherPackagingSpecsWithFilterAndModifier(ctx, filter, modifier)
Jooyung Han0fbbc2b2022-03-25 12:35:46 +09001281}
Jooyung Han65f402b2022-04-21 14:24:04 +09001282
1283func sha1sum(values []string) string {
1284 h := sha256.New()
1285 for _, value := range values {
1286 io.WriteString(h, value)
1287 }
1288 return fmt.Sprintf("%x", h.Sum(nil))
1289}
Jooyung Hane6067592023-03-16 13:11:17 +09001290
1291// Base cc.UseCoverage
1292
1293var _ cc.UseCoverage = (*filesystem)(nil)
1294
Colin Crosse1a85552024-06-14 12:17:37 -07001295func (*filesystem) IsNativeCoverageNeeded(ctx cc.IsNativeCoverageNeededContext) bool {
Jooyung Hane6067592023-03-16 13:11:17 +09001296 return ctx.Device() && ctx.DeviceConfig().NativeCoverageEnabled()
1297}
Jiyong Parkf46b1af2024-04-05 18:13:33 +09001298
1299// android_filesystem_defaults
1300
1301type filesystemDefaults struct {
1302 android.ModuleBase
1303 android.DefaultsModuleBase
1304
Inseob Kim3c0a0422024-11-05 17:21:37 +09001305 properties FilesystemProperties
Jiyong Parkf46b1af2024-04-05 18:13:33 +09001306}
1307
1308// android_filesystem_defaults is a default module for android_filesystem and android_system_image
1309func filesystemDefaultsFactory() android.Module {
1310 module := &filesystemDefaults{}
1311 module.AddProperties(&module.properties)
1312 module.AddProperties(&android.PackagingProperties{})
1313 android.InitDefaultsModule(module)
1314 return module
1315}
1316
1317func (f *filesystemDefaults) PartitionType() string {
1318 return proptools.StringDefault(f.properties.Partition_type, "system")
1319}
1320
1321var _ partition = (*filesystemDefaults)(nil)
1322
1323func (f *filesystemDefaults) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1324 validatePartitionType(ctx, f)
Yu Liufc8d5c12025-01-09 00:19:06 +00001325 android.SetProvider(ctx, FilesystemDefaultsInfoProvider, FilesystemDefaultsInfo{
1326 PartitionType: f.PartitionType(),
1327 })
Jiyong Parkf46b1af2024-04-05 18:13:33 +09001328}
Spandan Das918191e2024-10-31 18:27:23 +00001329
1330// getLibsForLinkerConfig returns
1331// 1. A list of libraries installed in this filesystem
1332// 2. A list of dep libraries _not_ installed in this filesystem
1333//
1334// `linkerconfig.BuildLinkerConfig` will convert these two to a linker.config.pb for the filesystem
1335// (1) will be added to --provideLibs if they are C libraries with a stable interface (has stubs)
1336// (2) will be added to --requireLibs if they are C libraries with a stable interface (has stubs)
Yu Liu68a70b72025-01-08 22:54:44 +00001337func (f *filesystem) getLibsForLinkerConfig(ctx android.ModuleContext) ([]android.ModuleProxy, []android.ModuleProxy) {
Spandan Das918191e2024-10-31 18:27:23 +00001338 // we need "Module"s for packaging items
Yu Liu68a70b72025-01-08 22:54:44 +00001339 modulesInPackageByModule := make(map[android.ModuleProxy]bool)
Spandan Das918191e2024-10-31 18:27:23 +00001340 modulesInPackageByName := make(map[string]bool)
1341
1342 deps := f.gatherFilteredPackagingSpecs(ctx)
Yu Liu68a70b72025-01-08 22:54:44 +00001343 ctx.WalkDepsProxy(func(child, parent android.ModuleProxy) bool {
1344 if !android.OtherModuleProviderOrDefault(ctx, child, android.CommonModuleInfoKey).Enabled {
Yu Liu9c6b6762025-01-08 22:04:35 +00001345 return false
1346 }
Spandan Das918191e2024-10-31 18:27:23 +00001347 for _, ps := range android.OtherModuleProviderOrDefault(
1348 ctx, child, android.InstallFilesProvider).PackagingSpecs {
Spandan Dasecf667f2024-12-05 00:58:56 +00001349 if _, ok := deps[ps.RelPathInPackage()]; ok && ps.Partition() == f.PartitionType() {
Spandan Das918191e2024-10-31 18:27:23 +00001350 modulesInPackageByModule[child] = true
1351 modulesInPackageByName[child.Name()] = true
1352 return true
1353 }
1354 }
1355 return true
1356 })
1357
Yu Liu68a70b72025-01-08 22:54:44 +00001358 provideModules := make([]android.ModuleProxy, 0, len(modulesInPackageByModule))
Spandan Das918191e2024-10-31 18:27:23 +00001359 for mod := range modulesInPackageByModule {
1360 provideModules = append(provideModules, mod)
1361 }
1362
Yu Liu68a70b72025-01-08 22:54:44 +00001363 var requireModules []android.ModuleProxy
1364 ctx.WalkDepsProxy(func(child, parent android.ModuleProxy) bool {
1365 if !android.OtherModuleProviderOrDefault(ctx, child, android.CommonModuleInfoKey).Enabled {
Yu Liu9c6b6762025-01-08 22:04:35 +00001366 return false
1367 }
Spandan Das918191e2024-10-31 18:27:23 +00001368 _, parentInPackage := modulesInPackageByModule[parent]
1369 _, childInPackageName := modulesInPackageByName[child.Name()]
1370
1371 // When parent is in the package, and child (or its variant) is not, this can be from an interface.
1372 if parentInPackage && !childInPackageName {
1373 requireModules = append(requireModules, child)
1374 }
1375 return true
1376 })
1377
1378 return provideModules, requireModules
1379}
Cole Faust26bdac52024-11-19 13:37:53 -08001380
1381// Checks that the given file doesn't exceed the given size, and will also print a warning
1382// if it's nearing the maximum size. Equivalent to assert-max-image-size in make:
1383// https://cs.android.com/android/platform/superproject/main/+/main:build/make/core/definitions.mk;l=3455;drc=993c4de29a02a6accd60ceaaee153307e1a18d10
1384func assertMaxImageSize(builder *android.RuleBuilder, image android.Path, maxSize int64, addAvbLater bool) {
1385 if addAvbLater {
1386 // The value 69632 is derived from MAX_VBMETA_SIZE + MAX_FOOTER_SIZE in avbtool.
1387 // Logic copied from make:
1388 // https://cs.android.com/android/platform/superproject/main/+/main:build/make/core/Makefile;l=228;drc=a6a0007ef24e16c0b79f439beac4a118416717e6
1389 maxSize -= 69632
1390 }
1391 cmd := builder.Command()
1392 cmd.Textf(`file="%s"; maxsize="%d";`+
1393 `total=$(stat -c "%%s" "$file" | tr -d '\n');`+
1394 `if [ "$total" -gt "$maxsize" ]; then `+
1395 ` echo "error: $file too large ($total > $maxsize)";`+
1396 ` false;`+
1397 `elif [ "$total" -gt $((maxsize - 32768)) ]; then `+
1398 ` echo "WARNING: $file approaching size limit ($total now; limit $maxsize)";`+
1399 `fi`,
1400 image, maxSize)
1401 cmd.Implicit(image)
1402}
Spandan Das71be42d2024-11-20 18:34:16 +00001403
1404// addAutogeneratedRroDeps walks the transitive closure of vendor and product partitions.
1405// It visits apps installed in system and system_ext partitions, and adds the autogenerated
1406// RRO modules to its own deps.
1407func addAutogeneratedRroDeps(ctx android.BottomUpMutatorContext) {
1408 f, ok := ctx.Module().(*filesystem)
1409 if !ok {
1410 return
1411 }
1412 thisPartition := f.PartitionType()
1413 if thisPartition != "vendor" && thisPartition != "product" {
Cole Faust34592c02024-12-13 11:20:24 -08001414 if f.properties.Android_filesystem_deps.System != nil {
1415 ctx.PropertyErrorf("android_filesystem_deps.system", "only vendor or product partitions can use android_filesystem_deps")
1416 }
1417 if f.properties.Android_filesystem_deps.System_ext != nil {
1418 ctx.PropertyErrorf("android_filesystem_deps.system_ext", "only vendor or product partitions can use android_filesystem_deps")
1419 }
Spandan Das71be42d2024-11-20 18:34:16 +00001420 return
1421 }
1422 ctx.WalkDeps(func(child, parent android.Module) bool {
1423 depTag := ctx.OtherModuleDependencyTag(child)
1424 if parent.Name() == f.Name() && depTag != interPartitionDependencyTag {
1425 return false // This is a module listed in deps of vendor/product filesystem
1426 }
1427 if vendorOverlay := java.AutogeneratedRroModuleName(ctx, child.Name(), "vendor"); ctx.OtherModuleExists(vendorOverlay) && thisPartition == "vendor" {
1428 ctx.AddFarVariationDependencies(nil, dependencyTagWithVisibilityEnforcementBypass, vendorOverlay)
1429 }
1430 if productOverlay := java.AutogeneratedRroModuleName(ctx, child.Name(), "product"); ctx.OtherModuleExists(productOverlay) && thisPartition == "product" {
1431 ctx.AddFarVariationDependencies(nil, dependencyTagWithVisibilityEnforcementBypass, productOverlay)
1432 }
1433 return true
1434 })
1435}