blob: 5b217aeec0b6bd490afb74c20b69dd3b36a5d15f [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 Das92631882024-10-28 22:49:38 +000028 "android/soong/linkerconfig"
Jiyong Park65b62242020-11-25 12:44:59 +090029
30 "github.com/google/blueprint"
Jiyong Park71baa762021-01-18 21:11:03 +090031 "github.com/google/blueprint/proptools"
Jiyong Park6f0f6882020-11-12 13:14:30 +090032)
33
34func init() {
Jooyung Han9706cbc2021-04-15 22:43:48 +090035 registerBuildComponents(android.InitRegistrationContext)
36}
37
38func registerBuildComponents(ctx android.RegistrationContext) {
Cole Faust92ccbe22024-10-03 14:38:37 -070039 ctx.RegisterModuleType("android_filesystem", FilesystemFactory)
Jiyong Parkf46b1af2024-04-05 18:13:33 +090040 ctx.RegisterModuleType("android_filesystem_defaults", filesystemDefaultsFactory)
Jihoon Kang98047cf2024-10-02 17:13:54 +000041 ctx.RegisterModuleType("android_system_image", SystemImageFactory)
Jiyong Parkbc485482022-11-15 22:31:49 +090042 ctx.RegisterModuleType("avb_add_hash_footer", avbAddHashFooterFactory)
Inseob Kim87230e62023-11-22 18:55:07 +090043 ctx.RegisterModuleType("avb_add_hash_footer_defaults", avbAddHashFooterDefaultsFactory)
Alice Wang000e3a32023-01-03 16:11:20 +000044 ctx.RegisterModuleType("avb_gen_vbmeta_image", avbGenVbmetaImageFactory)
Inseob Kim87230e62023-11-22 18:55:07 +090045 ctx.RegisterModuleType("avb_gen_vbmeta_image_defaults", avbGenVbmetaImageDefaultsFactory)
Jiyong Park6f0f6882020-11-12 13:14:30 +090046}
47
48type filesystem struct {
49 android.ModuleBase
50 android.PackagingBase
Jiyong Parkf46b1af2024-04-05 18:13:33 +090051 android.DefaultableModuleBase
Jiyong Park65c49f52020-11-24 14:23:26 +090052
Jihoon Kang98047cf2024-10-02 17:13:54 +000053 properties FilesystemProperties
Jiyong Park71baa762021-01-18 21:11:03 +090054
Cole Faust4e9f5922024-11-13 16:09:23 -080055 output android.Path
Jiyong Park65c49f52020-11-24 14:23:26 +090056 installDir android.InstallPath
Jooyung Han0fbbc2b2022-03-25 12:35:46 +090057
Cole Faust4e9f5922024-11-13 16:09:23 -080058 fileListFile android.Path
Kiyoung Kim99a954d2024-06-21 14:22:20 +090059
60 // Keeps the entries installed from this filesystem
Jooyung Han0fbbc2b2022-03-25 12:35:46 +090061 entries []string
Kiyoung Kim67118212024-11-07 13:23:44 +090062
63 filesystemBuilder filesystemBuilder
Jiyong Park6f0f6882020-11-12 13:14:30 +090064}
65
Kiyoung Kim67118212024-11-07 13:23:44 +090066type filesystemBuilder interface {
67 BuildLinkerConfigFile(ctx android.ModuleContext, builder *android.RuleBuilder, rebasedDir android.OutputPath)
68 // Function that filters PackagingSpec in PackagingBase.GatherPackagingSpecs()
69 FilterPackagingSpec(spec android.PackagingSpec) bool
Inseob Kim3c0a0422024-11-05 17:21:37 +090070 // Function that modifies PackagingSpec in PackagingBase.GatherPackagingSpecs() to customize.
71 // For example, GSI system.img contains system_ext and product artifacts and their
72 // relPathInPackage need to be rebased to system/system_ext and system/system_product.
73 ModifyPackagingSpec(spec *android.PackagingSpec)
Kiyoung Kim23be5bb2024-11-27 00:50:30 +000074
75 // Function to check if the filesystem should not use `vintf_fragments` property,
76 // but use `vintf_fragment` module type instead
77 ShouldUseVintfFragmentModuleOnly() bool
Kiyoung Kim67118212024-11-07 13:23:44 +090078}
79
80var _ filesystemBuilder = (*filesystem)(nil)
81
Spandan Das69464c32024-10-25 20:08:06 +000082type SymlinkDefinition struct {
Inseob Kim14199b02021-02-09 21:18:31 +090083 Target *string
84 Name *string
85}
86
Jihoon Kang98047cf2024-10-02 17:13:54 +000087type FilesystemProperties struct {
Jiyong Park71baa762021-01-18 21:11:03 +090088 // When set to true, sign the image with avbtool. Default is false.
89 Use_avb *bool
90
91 // Path to the private key that avbtool will use to sign this filesystem image.
92 // TODO(jiyong): allow apex_key to be specified here
93 Avb_private_key *string `android:"path"`
94
Shikha Panwar01403bb2022-12-22 12:22:57 +000095 // Signing algorithm for avbtool. Default is SHA256_RSA4096.
Jiyong Park71baa762021-01-18 21:11:03 +090096 Avb_algorithm *string
Jiyong Park11a65972021-02-01 21:09:38 +090097
Shikha Panwar01403bb2022-12-22 12:22:57 +000098 // Hash algorithm used for avbtool (for descriptors). This is passed as hash_algorithm to
99 // avbtool. Default used by avbtool is sha1.
Shikha Panware6f30632022-12-21 12:54:45 +0000100 Avb_hash_algorithm *string
101
Nikita Ioffe2c8cdc62024-03-27 22:19:30 +0000102 // The index used to prevent rollback of the image. Only used if use_avb is true.
103 Rollback_index *int64
104
Jiyong Parkac4076d2021-03-15 23:21:30 +0900105 // Name of the partition stored in vbmeta desc. Defaults to the name of this module.
106 Partition_name *string
107
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000108 // Type of the filesystem. Currently, ext4, erofs, cpio, and compressed_cpio are supported. Default
Jiyong Park837cdb22021-02-05 00:17:14 +0900109 // is ext4.
Jiyong Park11a65972021-02-01 21:09:38 +0900110 Type *string
Inseob Kimcc8e5362021-02-03 14:05:24 +0900111
Cole Faust9a24d902024-03-18 15:38:12 -0700112 // Identifies which partition this is for //visibility:any_system_image (and others) visibility
113 // checks, and will be used in the future for API surface checks.
114 Partition_type *string
115
Inseob Kimcc8e5362021-02-03 14:05:24 +0900116 // file_contexts file to make image. Currently, only ext4 is supported.
117 File_contexts *string `android:"path"`
Inseob Kim2ce1b5d2021-02-15 17:01:04 +0900118
119 // Base directory relative to root, to which deps are installed, e.g. "system". Default is "."
120 // (root).
121 Base_dir *string
Inseob Kim14199b02021-02-09 21:18:31 +0900122
123 // Directories to be created under root. e.g. /dev, /proc, etc.
Cole Faustd9c6a5b2024-05-21 14:54:00 -0700124 Dirs proptools.Configurable[[]string]
Inseob Kim14199b02021-02-09 21:18:31 +0900125
126 // Symbolic links to be created under root with "ln -sf <target> <name>".
Spandan Das69464c32024-10-25 20:08:06 +0000127 Symlinks []SymlinkDefinition
Jooyung Han65f402b2022-04-21 14:24:04 +0900128
129 // Seconds since unix epoch to override timestamps of file entries
130 Fake_timestamp *string
131
132 // When set, passed to mkuserimg_mke2fs --mke2fs_uuid & --mke2fs_hash_seed.
133 // Otherwise, they'll be set as random which might cause indeterministic build output.
134 Uuid *string
Inseob Kim376d72f2023-11-01 15:40:25 +0900135
136 // Mount point for this image. Default is "/"
137 Mount_point *string
Cole Faust4a2a7c92024-03-12 12:44:40 -0700138
139 // If set to the name of a partition ("system", "vendor", etc), this filesystem module
140 // will also include the contents of the make-built staging directories. If any soong
141 // modules would be installed to the same location as a make module, they will overwrite
142 // the make version.
143 Include_make_built_files string
Inseob Kim53391842024-03-29 17:44:07 +0900144
Inseob Kimb7b84572024-04-30 10:51:47 +0900145 // When set, builds etc/event-log-tags file by merging logtags from all dependencies.
146 // Default is false
147 Build_logtags *bool
148
Justin Yun74f3f302024-05-07 14:32:14 +0900149 // Install aconfig_flags.pb file for the modules installed in this partition.
150 Gen_aconfig_flags_pb *bool
151
Inseob Kim53391842024-03-29 17:44:07 +0900152 Fsverity fsverityProperties
Cole Faust92ccbe22024-10-03 14:38:37 -0700153
154 // If this property is set to true, the filesystem will call ctx.UncheckedModule(), causing
155 // it to not be built on checkbuilds. Used for the automatic migration from make to soong
156 // build modules, where we want to emit some not-yet-working filesystems and we don't want them
157 // to be built.
158 Unchecked_module *bool `blueprint:"mutated"`
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000159
160 Erofs ErofsProperties
Jihoon Kang0d545b82024-10-11 00:21:57 +0000161
mrziwang1a6291f2024-11-07 14:29:25 -0800162 F2fs F2fsProperties
163
Spandan Das2047a4c2024-11-11 21:24:58 +0000164 Linker_config LinkerConfigProperties
Spandan Das92631882024-10-28 22:49:38 +0000165
Jihoon Kang0d545b82024-10-11 00:21:57 +0000166 // Determines if the module is auto-generated from Soong or not. If the module is
167 // auto-generated, its deps are exempted from visibility enforcement.
168 Is_auto_generated *bool
Jihoon Kang6c03c8e2024-11-18 21:30:22 +0000169
170 // Path to the dev nodes description file. This is only needed for building the ramdisk
171 // partition and should not be explicitly specified.
172 Dev_nodes_description_file *string `android:"path" blueprint:"mutated"`
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000173}
174
175// Additional properties required to generate erofs FS partitions.
176type ErofsProperties struct {
177 // Compressor and Compression level passed to mkfs.erofs. e.g. (lz4hc,9)
178 // Please see external/erofs-utils/README for complete documentation.
179 Compressor *string
180
181 // Used as --compress-hints for mkfs.erofs
182 Compress_hints *string `android:"path"`
183
184 Sparse *bool
Jiyong Park71baa762021-01-18 21:11:03 +0900185}
186
mrziwang1a6291f2024-11-07 14:29:25 -0800187// Additional properties required to generate f2fs FS partitions.
188type F2fsProperties struct {
189 Sparse *bool
190}
191
Spandan Das173256b2024-10-31 19:59:30 +0000192type LinkerConfigProperties struct {
193
194 // Build a linker.config.pb file
195 Gen_linker_config *bool
196
197 // List of files (in .json format) that will be converted to a linker config file (in .pb format).
198 // The linker config file be installed in the filesystem at /etc/linker.config.pb
199 Linker_config_srcs []string `android:"path"`
200}
201
Jiyong Park65c49f52020-11-24 14:23:26 +0900202// android_filesystem packages a set of modules and their transitive dependencies into a filesystem
203// image. The filesystem images are expected to be mounted in the target device, which means the
204// modules in the filesystem image are built for the target device (i.e. Android, not Linux host).
205// The modules are placed in the filesystem image just like they are installed to the ordinary
206// partitions like system.img. For example, cc_library modules are placed under ./lib[64] directory.
Cole Faust92ccbe22024-10-03 14:38:37 -0700207func FilesystemFactory() android.Module {
Jiyong Park6f0f6882020-11-12 13:14:30 +0900208 module := &filesystem{}
Kiyoung Kim67118212024-11-07 13:23:44 +0900209 module.filesystemBuilder = module
Cole Faust2cfe6962024-09-17 11:31:14 -0700210 initFilesystemModule(module, module)
Jiyong Parkfa616132021-04-20 11:36:40 +0900211 return module
212}
213
Cole Faust2cfe6962024-09-17 11:31:14 -0700214func initFilesystemModule(module android.DefaultableModule, filesystemModule *filesystem) {
215 module.AddProperties(&filesystemModule.properties)
216 android.InitPackageModule(filesystemModule)
217 filesystemModule.PackagingBase.DepsCollectFirstTargetOnly = true
Jihoon Kang79196c52024-10-30 18:49:47 +0000218 filesystemModule.PackagingBase.AllowHighPriorityDeps = true
Jiyong Park6f0f6882020-11-12 13:14:30 +0900219 android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900220 android.InitDefaultableModule(module)
Jihoon Kang6c03c8e2024-11-18 21:30:22 +0000221
222 android.AddLoadHook(module, func(ctx android.LoadHookContext) {
223 filesystemModule.setDevNodesDescriptionProp()
224 })
Jiyong Park6f0f6882020-11-12 13:14:30 +0900225}
226
Jihoon Kang0d545b82024-10-11 00:21:57 +0000227type depTag struct {
Jiyong Park12a719c2021-01-07 15:31:24 +0900228 blueprint.BaseDependencyTag
Jooyung Han092ef812021-03-10 15:40:34 +0900229 android.PackagingItemAlwaysDepTag
Jihoon Kang0d545b82024-10-11 00:21:57 +0000230}
231
232var dependencyTag = depTag{}
233
234type depTagWithVisibilityEnforcementBypass struct {
235 depTag
236}
237
238var _ android.ExcludeFromVisibilityEnforcementTag = (*depTagWithVisibilityEnforcementBypass)(nil)
239
240func (t depTagWithVisibilityEnforcementBypass) ExcludeFromVisibilityEnforcement() {}
241
242var dependencyTagWithVisibilityEnforcementBypass = depTagWithVisibilityEnforcementBypass{}
Jiyong Park65b62242020-11-25 12:44:59 +0900243
Jihoon Kang6c03c8e2024-11-18 21:30:22 +0000244// ramdiskDevNodesDescription is the name of the filegroup module that provides the file that
245// contains the description of dev nodes added to the CPIO archive for the ramdisk partition.
246const ramdiskDevNodesDescription = "ramdisk_node_list"
247
248func (f *filesystem) setDevNodesDescriptionProp() {
249 if proptools.String(f.properties.Partition_name) == "ramdisk" {
250 f.properties.Dev_nodes_description_file = proptools.StringPtr(":" + ramdiskDevNodesDescription)
251 }
252}
253
Jiyong Park6f0f6882020-11-12 13:14:30 +0900254func (f *filesystem) DepsMutator(ctx android.BottomUpMutatorContext) {
Jihoon Kang0d545b82024-10-11 00:21:57 +0000255 if proptools.Bool(f.properties.Is_auto_generated) {
256 f.AddDeps(ctx, dependencyTagWithVisibilityEnforcementBypass)
257 } else {
258 f.AddDeps(ctx, dependencyTag)
259 }
Jiyong Park6f0f6882020-11-12 13:14:30 +0900260}
261
Jiyong Park11a65972021-02-01 21:09:38 +0900262type fsType int
263
264const (
265 ext4Type fsType = iota
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000266 erofsType
mrziwang1a6291f2024-11-07 14:29:25 -0800267 f2fsType
Jiyong Park11a65972021-02-01 21:09:38 +0900268 compressedCpioType
Jiyong Park837cdb22021-02-05 00:17:14 +0900269 cpioType // uncompressed
Jiyong Park11a65972021-02-01 21:09:38 +0900270 unknown
271)
272
Spandan Das7a46f6c2024-10-14 18:41:18 +0000273func (fs fsType) IsUnknown() bool {
274 return fs == unknown
275}
276
Cole Faust92ccbe22024-10-03 14:38:37 -0700277type FilesystemInfo struct {
278 // A text file containing the list of paths installed on the partition.
279 FileListFile android.Path
280}
281
282var FilesystemProvider = blueprint.NewProvider[FilesystemInfo]()
283
Spandan Das7a46f6c2024-10-14 18:41:18 +0000284func GetFsTypeFromString(ctx android.EarlyModuleContext, typeStr string) fsType {
Jiyong Park11a65972021-02-01 21:09:38 +0900285 switch typeStr {
286 case "ext4":
287 return ext4Type
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000288 case "erofs":
289 return erofsType
mrziwang1a6291f2024-11-07 14:29:25 -0800290 case "f2fs":
291 return f2fsType
Jiyong Park11a65972021-02-01 21:09:38 +0900292 case "compressed_cpio":
293 return compressedCpioType
Jiyong Park837cdb22021-02-05 00:17:14 +0900294 case "cpio":
295 return cpioType
Jiyong Park11a65972021-02-01 21:09:38 +0900296 default:
Jiyong Park11a65972021-02-01 21:09:38 +0900297 return unknown
298 }
299}
300
Spandan Das7a46f6c2024-10-14 18:41:18 +0000301func (f *filesystem) fsType(ctx android.ModuleContext) fsType {
302 typeStr := proptools.StringDefault(f.properties.Type, "ext4")
303 fsType := GetFsTypeFromString(ctx, typeStr)
304 if fsType == unknown {
305 ctx.PropertyErrorf("type", "%q not supported", typeStr)
306 }
307 return fsType
308}
309
Jiyong Park65c49f52020-11-24 14:23:26 +0900310func (f *filesystem) installFileName() string {
311 return f.BaseModuleName() + ".img"
312}
313
Inseob Kim53391842024-03-29 17:44:07 +0900314func (f *filesystem) partitionName() string {
315 return proptools.StringDefault(f.properties.Partition_name, f.Name())
316}
317
Kiyoung Kim67118212024-11-07 13:23:44 +0900318func (f *filesystem) FilterPackagingSpec(ps android.PackagingSpec) bool {
Jiyong Park7e7d4af2024-05-01 12:36:10 +0000319 // Filesystem module respects the installation semantic. A PackagingSpec from a module with
320 // IsSkipInstall() is skipped.
Cole Faust76a6e952024-11-07 16:56:45 -0800321 if ps.SkipInstall() {
322 return false
Spandan Das6d056502024-10-21 15:40:32 +0000323 }
Cole Faust76a6e952024-11-07 16:56:45 -0800324 if proptools.Bool(f.properties.Is_auto_generated) { // TODO (spandandas): Remove this.
325 pt := f.PartitionType()
Cole Faustc88cff12024-11-12 13:24:05 -0800326 return ps.Partition() == pt || strings.HasPrefix(ps.Partition(), pt+"/")
Cole Faust76a6e952024-11-07 16:56:45 -0800327 }
328 return true
Jiyong Park7e7d4af2024-05-01 12:36:10 +0000329}
330
Inseob Kim3c0a0422024-11-05 17:21:37 +0900331func (f *filesystem) ModifyPackagingSpec(ps *android.PackagingSpec) {
Cole Faustc88cff12024-11-12 13:24:05 -0800332 // Sometimes, android.modulePartition() returns a path with >1 path components.
333 // This makes the partition field of packagingSpecs have multiple components, like
334 // "system/product". Right now, the filesystem module doesn't look at the partition field
335 // when deciding what path to install the file under, only the RelPathInPackage field, so
336 // we move the later path components from partition to relPathInPackage. This should probably
337 // be revisited in the future.
338 prefix := f.PartitionType() + "/"
339 if strings.HasPrefix(ps.Partition(), prefix) {
340 subPartition := strings.TrimPrefix(ps.Partition(), prefix)
341 ps.SetPartition(f.PartitionType())
342 ps.SetRelPathInPackage(filepath.Join(subPartition, ps.RelPathInPackage()))
343 }
Inseob Kim3c0a0422024-11-05 17:21:37 +0900344}
345
Jiyong Park6f0f6882020-11-12 13:14:30 +0900346var pctx = android.NewPackageContext("android/soong/filesystem")
347
348func (f *filesystem) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900349 validatePartitionType(ctx, f)
Kiyoung Kim23be5bb2024-11-27 00:50:30 +0000350 if f.filesystemBuilder.ShouldUseVintfFragmentModuleOnly() {
351 f.validateVintfFragments(ctx)
352 }
Jiyong Park11a65972021-02-01 21:09:38 +0900353 switch f.fsType(ctx) {
mrziwang1a6291f2024-11-07 14:29:25 -0800354 case ext4Type, erofsType, f2fsType:
Jiyong Park11a65972021-02-01 21:09:38 +0900355 f.output = f.buildImageUsingBuildImage(ctx)
356 case compressedCpioType:
Jiyong Park837cdb22021-02-05 00:17:14 +0900357 f.output = f.buildCpioImage(ctx, true)
358 case cpioType:
359 f.output = f.buildCpioImage(ctx, false)
Jiyong Park11a65972021-02-01 21:09:38 +0900360 default:
361 return
362 }
363
364 f.installDir = android.PathForModuleInstall(ctx, "etc")
365 ctx.InstallFile(f.installDir, f.installFileName(), f.output)
mrziwang555d1332024-06-07 11:15:33 -0700366 ctx.SetOutputFiles([]android.Path{f.output}, "")
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900367
Cole Faust4e9f5922024-11-13 16:09:23 -0800368 fileListFile := android.PathForModuleOut(ctx, "fileList")
369 android.WriteFileRule(ctx, fileListFile, f.installedFilesList())
Cole Faust92ccbe22024-10-03 14:38:37 -0700370
371 android.SetProvider(ctx, FilesystemProvider, FilesystemInfo{
Cole Faust4e9f5922024-11-13 16:09:23 -0800372 FileListFile: fileListFile,
Cole Faust92ccbe22024-10-03 14:38:37 -0700373 })
Cole Faust4e9f5922024-11-13 16:09:23 -0800374 f.fileListFile = fileListFile
Cole Faust92ccbe22024-10-03 14:38:37 -0700375
376 if proptools.Bool(f.properties.Unchecked_module) {
377 ctx.UncheckedModule()
378 }
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900379}
380
Kiyoung Kim23be5bb2024-11-27 00:50:30 +0000381func (f *filesystem) validateVintfFragments(ctx android.ModuleContext) {
382 visitedModule := map[string]bool{}
383 packagingSpecs := f.gatherFilteredPackagingSpecs(ctx)
384
385 moduleInFileSystem := func(mod android.Module) bool {
386 for _, ps := range android.OtherModuleProviderOrDefault(
387 ctx, mod, android.InstallFilesProvider).PackagingSpecs {
388 if _, ok := packagingSpecs[ps.RelPathInPackage()]; ok {
389 return true
390 }
391 }
392 return false
393 }
394
395 ctx.WalkDeps(func(child, parent android.Module) bool {
396 if visitedModule[child.Name()] {
397 return false
398 }
399 if !moduleInFileSystem(child) {
400 visitedModule[child.Name()] = true
401 return true
402 }
403 if vintfFragments := child.VintfFragments(ctx); vintfFragments != nil {
404 ctx.PropertyErrorf(
405 "vintf_fragments",
406 "Module %s is referenced by soong-defined filesystem %s with property vintf_fragments(%s) in use."+
407 " Use vintf_fragment_modules property instead.",
408 child.Name(),
409 f.BaseModuleName(),
410 strings.Join(vintfFragments, ", "),
411 )
412 }
413 visitedModule[child.Name()] = true
414 return true
415 })
416}
417
Cole Faust4e9f5922024-11-13 16:09:23 -0800418func (f *filesystem) appendToEntry(ctx android.ModuleContext, installedFile android.Path) {
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900419 partitionBaseDir := android.PathForModuleOut(ctx, "root", f.partitionName()).String() + "/"
420
421 relPath, inTargetPartition := strings.CutPrefix(installedFile.String(), partitionBaseDir)
422 if inTargetPartition {
423 f.entries = append(f.entries, relPath)
424 }
425}
426
427func (f *filesystem) installedFilesList() string {
428 installedFilePaths := android.FirstUniqueStrings(f.entries)
429 slices.Sort(installedFilePaths)
430
431 return strings.Join(installedFilePaths, "\n")
Jiyong Park11a65972021-02-01 21:09:38 +0900432}
433
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900434func validatePartitionType(ctx android.ModuleContext, p partition) {
435 if !android.InList(p.PartitionType(), validPartitions) {
436 ctx.PropertyErrorf("partition_type", "partition_type must be one of %s, found: %s", validPartitions, p.PartitionType())
437 }
438
439 ctx.VisitDirectDepsWithTag(android.DefaultsDepTag, func(m android.Module) {
440 if fdm, ok := m.(*filesystemDefaults); ok {
441 if p.PartitionType() != fdm.PartitionType() {
442 ctx.PropertyErrorf("partition_type",
443 "%s doesn't match with the partition type %s of the filesystem default module %s",
444 p.PartitionType(), fdm.PartitionType(), m.Name())
445 }
446 }
447 })
448}
449
Cole Faust3b806d32024-03-11 15:15:03 -0700450// Copy extra files/dirs that are not from the `deps` property to `rootDir`, checking for conflicts with files
451// already in `rootDir`.
452func (f *filesystem) buildNonDepsFiles(ctx android.ModuleContext, builder *android.RuleBuilder, rootDir android.OutputPath) {
Inseob Kim14199b02021-02-09 21:18:31 +0900453 // create dirs and symlinks
Cole Faustd9c6a5b2024-05-21 14:54:00 -0700454 for _, dir := range f.properties.Dirs.GetOrDefault(ctx, nil) {
Inseob Kim14199b02021-02-09 21:18:31 +0900455 // OutputPath.Join verifies dir
456 builder.Command().Text("mkdir -p").Text(rootDir.Join(ctx, dir).String())
457 }
458
459 for _, symlink := range f.properties.Symlinks {
460 name := strings.TrimSpace(proptools.String(symlink.Name))
461 target := strings.TrimSpace(proptools.String(symlink.Target))
462
463 if name == "" {
464 ctx.PropertyErrorf("symlinks", "Name can't be empty")
465 continue
466 }
467
468 if target == "" {
469 ctx.PropertyErrorf("symlinks", "Target can't be empty")
470 continue
471 }
472
473 // OutputPath.Join verifies name. don't need to verify target.
474 dst := rootDir.Join(ctx, name)
Cole Faust3b806d32024-03-11 15:15:03 -0700475 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 +0900476 builder.Command().Text("mkdir -p").Text(filepath.Dir(dst.String()))
477 builder.Command().Text("ln -sf").Text(proptools.ShellEscape(target)).Text(dst.String())
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900478 f.appendToEntry(ctx, dst)
Inseob Kim14199b02021-02-09 21:18:31 +0900479 }
Inseob Kim2ce1b5d2021-02-15 17:01:04 +0900480}
481
Inseob Kim33f95a92024-07-11 15:44:49 +0900482func (f *filesystem) copyPackagingSpecs(ctx android.ModuleContext, builder *android.RuleBuilder, specs map[string]android.PackagingSpec, rootDir, rebasedDir android.WritablePath) []string {
483 rootDirSpecs := make(map[string]android.PackagingSpec)
484 rebasedDirSpecs := make(map[string]android.PackagingSpec)
485
486 for rel, spec := range specs {
487 if spec.Partition() == "root" {
488 rootDirSpecs[rel] = spec
489 } else {
490 rebasedDirSpecs[rel] = spec
491 }
492 }
493
494 dirsToSpecs := make(map[android.WritablePath]map[string]android.PackagingSpec)
495 dirsToSpecs[rootDir] = rootDirSpecs
496 dirsToSpecs[rebasedDir] = rebasedDirSpecs
497
498 return f.CopySpecsToDirs(ctx, builder, dirsToSpecs)
499}
500
Justin Yun34baa2e2024-08-30 21:11:33 +0900501func (f *filesystem) copyFilesToProductOut(ctx android.ModuleContext, builder *android.RuleBuilder, rebasedDir android.OutputPath) {
Justin Yun2cc42502024-09-11 14:10:20 +0900502 if f.Name() != ctx.Config().SoongDefinedSystemImage() {
Justin Yun34baa2e2024-08-30 21:11:33 +0900503 return
504 }
505 installPath := android.PathForModuleInPartitionInstall(ctx, f.partitionName())
506 builder.Command().Textf("cp -prf %s/* %s", rebasedDir, installPath)
507}
508
Cole Faust4e9f5922024-11-13 16:09:23 -0800509func (f *filesystem) buildImageUsingBuildImage(ctx android.ModuleContext) android.Path {
Jiyong Park6f0f6882020-11-12 13:14:30 +0900510 rootDir := android.PathForModuleOut(ctx, "root").OutputPath
Cole Faust3b806d32024-03-11 15:15:03 -0700511 rebasedDir := rootDir
512 if f.properties.Base_dir != nil {
513 rebasedDir = rootDir.Join(ctx, *f.properties.Base_dir)
514 }
515 builder := android.NewRuleBuilder(pctx, ctx)
516 // Wipe the root dir to get rid of leftover files from prior builds
517 builder.Command().Textf("rm -rf %s && mkdir -p %s", rootDir, rootDir)
Inseob Kim53391842024-03-29 17:44:07 +0900518 specs := f.gatherFilteredPackagingSpecs(ctx)
Inseob Kim33f95a92024-07-11 15:44:49 +0900519 f.entries = f.copyPackagingSpecs(ctx, builder, specs, rootDir, rebasedDir)
Cole Faust3b806d32024-03-11 15:15:03 -0700520
521 f.buildNonDepsFiles(ctx, builder, rootDir)
Cole Faust4a2a7c92024-03-12 12:44:40 -0700522 f.addMakeBuiltFiles(ctx, builder, rootDir)
Inseob Kim53391842024-03-29 17:44:07 +0900523 f.buildFsverityMetadataFiles(ctx, builder, specs, rootDir, rebasedDir)
Inseob Kimb7b84572024-04-30 10:51:47 +0900524 f.buildEventLogtagsFile(ctx, builder, rebasedDir)
Justin Yun74f3f302024-05-07 14:32:14 +0900525 f.buildAconfigFlagsFiles(ctx, builder, specs, rebasedDir)
Kiyoung Kim67118212024-11-07 13:23:44 +0900526 f.filesystemBuilder.BuildLinkerConfigFile(ctx, builder, rebasedDir)
Justin Yun34baa2e2024-08-30 21:11:33 +0900527 f.copyFilesToProductOut(ctx, builder, rebasedDir)
Jiyong Park6f0f6882020-11-12 13:14:30 +0900528
Nikita Ioffe519015f2022-12-23 15:36:29 +0000529 // run host_init_verifier
530 // Ideally we should have a concept of pluggable linters that verify the generated image.
531 // While such concept is not implement this will do.
532 // TODO(b/263574231): substitute with pluggable linter.
533 builder.Command().
534 BuiltTool("host_init_verifier").
535 FlagWithArg("--out_system=", rootDir.String()+"/system")
536
Jiyong Park72678312021-01-18 17:29:49 +0900537 propFile, toolDeps := f.buildPropFile(ctx)
Cole Faust4e9f5922024-11-13 16:09:23 -0800538 output := android.PathForModuleOut(ctx, f.installFileName())
Colin Crossf1a035e2020-11-16 17:32:30 -0800539 builder.Command().BuiltTool("build_image").
Jiyong Park6f0f6882020-11-12 13:14:30 +0900540 Text(rootDir.String()). // input directory
541 Input(propFile).
Jiyong Park72678312021-01-18 17:29:49 +0900542 Implicits(toolDeps).
Jiyong Park11a65972021-02-01 21:09:38 +0900543 Output(output).
Jiyong Park6f0f6882020-11-12 13:14:30 +0900544 Text(rootDir.String()) // directory where to find fs_config_files|dirs
545
546 // rootDir is not deleted. Might be useful for quick inspection.
Colin Crossf1a035e2020-11-16 17:32:30 -0800547 builder.Build("build_filesystem_image", fmt.Sprintf("Creating filesystem %s", f.BaseModuleName()))
Jiyong Park65c49f52020-11-24 14:23:26 +0900548
Jiyong Park11a65972021-02-01 21:09:38 +0900549 return output
Jiyong Park65c49f52020-11-24 14:23:26 +0900550}
551
Cole Faust4e9f5922024-11-13 16:09:23 -0800552func (f *filesystem) buildFileContexts(ctx android.ModuleContext) android.Path {
Inseob Kimcc8e5362021-02-03 14:05:24 +0900553 builder := android.NewRuleBuilder(pctx, ctx)
554 fcBin := android.PathForModuleOut(ctx, "file_contexts.bin")
555 builder.Command().BuiltTool("sefcontext_compile").
556 FlagWithOutput("-o ", fcBin).
557 Input(android.PathForModuleSrc(ctx, proptools.String(f.properties.File_contexts)))
558 builder.Build("build_filesystem_file_contexts", fmt.Sprintf("Creating filesystem file contexts for %s", f.BaseModuleName()))
Cole Faust4e9f5922024-11-13 16:09:23 -0800559 return fcBin
Inseob Kimcc8e5362021-02-03 14:05:24 +0900560}
561
Jooyung Han65f402b2022-04-21 14:24:04 +0900562// Calculates avb_salt from entry list (sorted) for deterministic output.
563func (f *filesystem) salt() string {
564 return sha1sum(f.entries)
565}
566
Cole Faust4e9f5922024-11-13 16:09:23 -0800567func (f *filesystem) buildPropFile(ctx android.ModuleContext) (android.Path, android.Paths) {
Jiyong Park72678312021-01-18 17:29:49 +0900568 var deps android.Paths
Cole Faustcec230a2024-03-07 15:51:12 -0800569 var propFileString strings.Builder
Jiyong Park72678312021-01-18 17:29:49 +0900570 addStr := func(name string, value string) {
Cole Faustcec230a2024-03-07 15:51:12 -0800571 propFileString.WriteString(name)
572 propFileString.WriteRune('=')
573 propFileString.WriteString(value)
574 propFileString.WriteRune('\n')
Jiyong Park72678312021-01-18 17:29:49 +0900575 }
576 addPath := func(name string, path android.Path) {
Cole Faustcec230a2024-03-07 15:51:12 -0800577 addStr(name, path.String())
Jiyong Park72678312021-01-18 17:29:49 +0900578 deps = append(deps, path)
579 }
580
Jiyong Park11a65972021-02-01 21:09:38 +0900581 // Type string that build_image.py accepts.
582 fsTypeStr := func(t fsType) string {
583 switch t {
Spandan Das94668822024-10-09 20:51:33 +0000584 // TODO(372522486): add more types like f2fs, erofs, etc.
Jiyong Park11a65972021-02-01 21:09:38 +0900585 case ext4Type:
586 return "ext4"
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000587 case erofsType:
588 return "erofs"
mrziwang1a6291f2024-11-07 14:29:25 -0800589 case f2fsType:
590 return "f2fs"
Jiyong Park11a65972021-02-01 21:09:38 +0900591 }
592 panic(fmt.Errorf("unsupported fs type %v", t))
593 }
594
595 addStr("fs_type", fsTypeStr(f.fsType(ctx)))
Inseob Kim376d72f2023-11-01 15:40:25 +0900596 addStr("mount_point", proptools.StringDefault(f.properties.Mount_point, "/"))
Jiyong Park72678312021-01-18 17:29:49 +0900597 addStr("use_dynamic_partition_size", "true")
598 addPath("ext_mkuserimg", ctx.Config().HostToolPath(ctx, "mkuserimg_mke2fs"))
599 // b/177813163 deps of the host tools have to be added. Remove this.
600 for _, t := range []string{"mke2fs", "e2fsdroid", "tune2fs"} {
601 deps = append(deps, ctx.Config().HostToolPath(ctx, t))
602 }
603
Jiyong Park71baa762021-01-18 21:11:03 +0900604 if proptools.Bool(f.properties.Use_avb) {
605 addStr("avb_hashtree_enable", "true")
606 addPath("avb_avbtool", ctx.Config().HostToolPath(ctx, "avbtool"))
607 algorithm := proptools.StringDefault(f.properties.Avb_algorithm, "SHA256_RSA4096")
608 addStr("avb_algorithm", algorithm)
609 key := android.PathForModuleSrc(ctx, proptools.String(f.properties.Avb_private_key))
610 addPath("avb_key_path", key)
Inseob Kim53391842024-03-29 17:44:07 +0900611 addStr("partition_name", f.partitionName())
Shikha Panware6f30632022-12-21 12:54:45 +0000612 avb_add_hashtree_footer_args := "--do_not_generate_fec"
613 if hashAlgorithm := proptools.String(f.properties.Avb_hash_algorithm); hashAlgorithm != "" {
614 avb_add_hashtree_footer_args += " --hash_algorithm " + hashAlgorithm
615 }
Nikita Ioffe2c8cdc62024-03-27 22:19:30 +0000616 if f.properties.Rollback_index != nil {
617 rollbackIndex := proptools.Int(f.properties.Rollback_index)
618 if rollbackIndex < 0 {
619 ctx.PropertyErrorf("rollback_index", "Rollback index must be non-negative")
620 }
621 avb_add_hashtree_footer_args += " --rollback_index " + strconv.Itoa(rollbackIndex)
622 }
Inseob Kim53391842024-03-29 17:44:07 +0900623 securityPatchKey := "com.android.build." + f.partitionName() + ".security_patch"
Seungjae Yooa30e4502023-11-09 14:55:44 +0900624 securityPatchValue := ctx.Config().PlatformSecurityPatch()
625 avb_add_hashtree_footer_args += " --prop " + securityPatchKey + ":" + securityPatchValue
Shikha Panware6f30632022-12-21 12:54:45 +0000626 addStr("avb_add_hashtree_footer_args", avb_add_hashtree_footer_args)
Jooyung Han65f402b2022-04-21 14:24:04 +0900627 addStr("avb_salt", f.salt())
Jiyong Park71baa762021-01-18 21:11:03 +0900628 }
629
Inseob Kimcc8e5362021-02-03 14:05:24 +0900630 if proptools.String(f.properties.File_contexts) != "" {
631 addPath("selinux_fc", f.buildFileContexts(ctx))
632 }
Jooyung Han65f402b2022-04-21 14:24:04 +0900633 if timestamp := proptools.String(f.properties.Fake_timestamp); timestamp != "" {
634 addStr("timestamp", timestamp)
635 }
636 if uuid := proptools.String(f.properties.Uuid); uuid != "" {
637 addStr("uuid", uuid)
638 addStr("hash_seed", uuid)
639 }
mrziwang1a6291f2024-11-07 14:29:25 -0800640
Cole Faust43a52c72024-11-26 12:46:08 -0800641 // TODO(b/381120092): This should only be added if none of the size-related properties are set,
642 // but currently soong built partitions don't have size properties. Make code:
643 // https://cs.android.com/android/platform/superproject/main/+/main:build/make/core/Makefile;l=2262;drc=39cd33701c9278db0e7e481a090605f428d5b12d
644 // Make uses system_disable_sparse but disable_sparse has the same effect, and we shouldn't need
645 // to qualify it because each partition gets its own property file built.
646 addStr("disable_sparse", "true")
647
mrziwang1a6291f2024-11-07 14:29:25 -0800648 fst := f.fsType(ctx)
649 switch fst {
650 case erofsType:
651 // Add erofs properties
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000652 if compressor := f.properties.Erofs.Compressor; compressor != nil {
653 addStr("erofs_default_compressor", proptools.String(compressor))
654 }
655 if compressHints := f.properties.Erofs.Compress_hints; compressHints != nil {
Cole Faust7cd4bad2024-10-11 10:31:12 -0700656 addPath("erofs_default_compress_hints", android.PathForModuleSrc(ctx, *compressHints))
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000657 }
658 if proptools.BoolDefault(f.properties.Erofs.Sparse, true) {
659 // https://source.corp.google.com/h/googleplex-android/platform/build/+/88b1c67239ca545b11580237242774b411f2fed9:core/Makefile;l=2292;bpv=1;bpt=0;drc=ea8f34bc1d6e63656b4ec32f2391e9d54b3ebb6b
660 addStr("erofs_sparse_flag", "-s")
661 }
mrziwang1a6291f2024-11-07 14:29:25 -0800662 case f2fsType:
663 if proptools.BoolDefault(f.properties.F2fs.Sparse, true) {
664 // https://source.corp.google.com/h/googleplex-android/platform/build/+/88b1c67239ca545b11580237242774b411f2fed9:core/Makefile;l=2294;drc=ea8f34bc1d6e63656b4ec32f2391e9d54b3ebb6b;bpv=1;bpt=0
665 addStr("f2fs_sparse_flag", "-S")
666 }
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000667 }
mrziwang1a6291f2024-11-07 14:29:25 -0800668 f.checkFsTypePropertyError(ctx, fst, fsTypeStr(fst))
Spandan Dasc35d6fb2024-10-10 17:51:14 +0000669
Cole Faust4e9f5922024-11-13 16:09:23 -0800670 propFile := android.PathForModuleOut(ctx, "prop")
Cole Faustcec230a2024-03-07 15:51:12 -0800671 android.WriteFileRuleVerbatim(ctx, propFile, propFileString.String())
Jiyong Park72678312021-01-18 17:29:49 +0900672 return propFile, deps
673}
674
mrziwang1a6291f2024-11-07 14:29:25 -0800675// This method checks if there is any property set for the fstype(s) other than
676// the current fstype.
677func (f *filesystem) checkFsTypePropertyError(ctx android.ModuleContext, t fsType, fs string) {
678 raiseError := func(otherFsType, currentFsType string) {
679 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)
680 ctx.PropertyErrorf(otherFsType, errMsg)
681 }
682
683 if t != erofsType {
684 if f.properties.Erofs.Compressor != nil || f.properties.Erofs.Compress_hints != nil || f.properties.Erofs.Sparse != nil {
685 raiseError("erofs", fs)
686 }
687 }
688 if t != f2fsType {
689 if f.properties.F2fs.Sparse != nil {
690 raiseError("f2fs", fs)
691 }
692 }
693}
694
Cole Faust4e9f5922024-11-13 16:09:23 -0800695func (f *filesystem) buildCpioImage(ctx android.ModuleContext, compressed bool) android.Path {
Jiyong Park11a65972021-02-01 21:09:38 +0900696 if proptools.Bool(f.properties.Use_avb) {
697 ctx.PropertyErrorf("use_avb", "signing compresed cpio image using avbtool is not supported."+
698 "Consider adding this to bootimg module and signing the entire boot image.")
699 }
700
Inseob Kimcc8e5362021-02-03 14:05:24 +0900701 if proptools.String(f.properties.File_contexts) != "" {
702 ctx.PropertyErrorf("file_contexts", "file_contexts is not supported for compressed cpio image.")
703 }
704
Cole Faust4a2a7c92024-03-12 12:44:40 -0700705 if f.properties.Include_make_built_files != "" {
706 ctx.PropertyErrorf("include_make_built_files", "include_make_built_files is not supported for compressed cpio image.")
707 }
708
Jiyong Park11a65972021-02-01 21:09:38 +0900709 rootDir := android.PathForModuleOut(ctx, "root").OutputPath
Cole Faust3b806d32024-03-11 15:15:03 -0700710 rebasedDir := rootDir
711 if f.properties.Base_dir != nil {
712 rebasedDir = rootDir.Join(ctx, *f.properties.Base_dir)
713 }
714 builder := android.NewRuleBuilder(pctx, ctx)
715 // Wipe the root dir to get rid of leftover files from prior builds
716 builder.Command().Textf("rm -rf %s && mkdir -p %s", rootDir, rootDir)
Inseob Kim53391842024-03-29 17:44:07 +0900717 specs := f.gatherFilteredPackagingSpecs(ctx)
Inseob Kim33f95a92024-07-11 15:44:49 +0900718 f.entries = f.copyPackagingSpecs(ctx, builder, specs, rootDir, rebasedDir)
Cole Faust3b806d32024-03-11 15:15:03 -0700719
720 f.buildNonDepsFiles(ctx, builder, rootDir)
Inseob Kim53391842024-03-29 17:44:07 +0900721 f.buildFsverityMetadataFiles(ctx, builder, specs, rootDir, rebasedDir)
Inseob Kimb7b84572024-04-30 10:51:47 +0900722 f.buildEventLogtagsFile(ctx, builder, rebasedDir)
Justin Yun74f3f302024-05-07 14:32:14 +0900723 f.buildAconfigFlagsFiles(ctx, builder, specs, rebasedDir)
Kiyoung Kim67118212024-11-07 13:23:44 +0900724 f.filesystemBuilder.BuildLinkerConfigFile(ctx, builder, rebasedDir)
Justin Yun34baa2e2024-08-30 21:11:33 +0900725 f.copyFilesToProductOut(ctx, builder, rebasedDir)
Jiyong Park11a65972021-02-01 21:09:38 +0900726
Cole Faust4e9f5922024-11-13 16:09:23 -0800727 output := android.PathForModuleOut(ctx, f.installFileName())
Jiyong Park837cdb22021-02-05 00:17:14 +0900728 cmd := builder.Command().
Jiyong Park11a65972021-02-01 21:09:38 +0900729 BuiltTool("mkbootfs").
Jiyong Park837cdb22021-02-05 00:17:14 +0900730 Text(rootDir.String()) // input directory
Jihoon Kang6c03c8e2024-11-18 21:30:22 +0000731 if nodeList := f.properties.Dev_nodes_description_file; nodeList != nil {
732 cmd.FlagWithInput("-n ", android.PathForModuleSrc(ctx, proptools.String(nodeList)))
733 }
Jiyong Park837cdb22021-02-05 00:17:14 +0900734 if compressed {
735 cmd.Text("|").
736 BuiltTool("lz4").
737 Flag("--favor-decSpeed"). // for faster boot
738 Flag("-12"). // maximum compression level
739 Flag("-l"). // legacy format for kernel
740 Text(">").Output(output)
741 } else {
742 cmd.Text(">").Output(output)
743 }
Jiyong Park11a65972021-02-01 21:09:38 +0900744
745 // rootDir is not deleted. Might be useful for quick inspection.
Jiyong Park837cdb22021-02-05 00:17:14 +0900746 builder.Build("build_cpio_image", fmt.Sprintf("Creating filesystem %s", f.BaseModuleName()))
Jiyong Park11a65972021-02-01 21:09:38 +0900747
748 return output
749}
750
Cole Faust4a2a7c92024-03-12 12:44:40 -0700751var validPartitions = []string{
752 "system",
753 "userdata",
754 "cache",
755 "system_other",
756 "vendor",
757 "product",
758 "system_ext",
759 "odm",
760 "vendor_dlkm",
761 "odm_dlkm",
762 "system_dlkm",
Cole Faust76a6e952024-11-07 16:56:45 -0800763 "ramdisk",
Cole Faust24938e22024-11-18 14:01:58 -0800764 "vendor_ramdisk",
Cole Faust4a2a7c92024-03-12 12:44:40 -0700765}
766
767func (f *filesystem) addMakeBuiltFiles(ctx android.ModuleContext, builder *android.RuleBuilder, rootDir android.Path) {
768 partition := f.properties.Include_make_built_files
769 if partition == "" {
770 return
771 }
772 if !slices.Contains(validPartitions, partition) {
773 ctx.PropertyErrorf("include_make_built_files", "Expected one of %#v, found %q", validPartitions, partition)
774 return
775 }
776 stampFile := fmt.Sprintf("target/product/%s/obj/PACKAGING/%s_intermediates/staging_dir.stamp", ctx.Config().DeviceName(), partition)
777 fileListFile := fmt.Sprintf("target/product/%s/obj/PACKAGING/%s_intermediates/file_list.txt", ctx.Config().DeviceName(), partition)
778 stagingDir := fmt.Sprintf("target/product/%s/%s", ctx.Config().DeviceName(), partition)
779
780 builder.Command().BuiltTool("merge_directories").
781 Implicit(android.PathForArbitraryOutput(ctx, stampFile)).
782 Text("--ignore-duplicates").
783 FlagWithInput("--file-list", android.PathForArbitraryOutput(ctx, fileListFile)).
784 Text(rootDir.String()).
785 Text(android.PathForArbitraryOutput(ctx, stagingDir).String())
786}
787
Inseob Kimb7b84572024-04-30 10:51:47 +0900788func (f *filesystem) buildEventLogtagsFile(ctx android.ModuleContext, builder *android.RuleBuilder, rebasedDir android.OutputPath) {
789 if !proptools.Bool(f.properties.Build_logtags) {
790 return
791 }
792
793 logtagsFilePaths := make(map[string]bool)
794 ctx.WalkDeps(func(child, parent android.Module) bool {
795 if logtagsInfo, ok := android.OtherModuleProvider(ctx, child, android.LogtagsProviderKey); ok {
796 for _, path := range logtagsInfo.Logtags {
797 logtagsFilePaths[path.String()] = true
798 }
799 }
800 return true
801 })
802
803 if len(logtagsFilePaths) == 0 {
804 return
805 }
806
807 etcPath := rebasedDir.Join(ctx, "etc")
808 eventLogtagsPath := etcPath.Join(ctx, "event-log-tags")
809 builder.Command().Text("mkdir").Flag("-p").Text(etcPath.String())
810 cmd := builder.Command().BuiltTool("merge-event-log-tags").
811 FlagWithArg("-o ", eventLogtagsPath.String()).
812 FlagWithInput("-m ", android.MergedLogtagsPath(ctx))
813
814 for _, path := range android.SortedKeys(logtagsFilePaths) {
815 cmd.Text(path)
816 }
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900817
818 f.appendToEntry(ctx, eventLogtagsPath)
Inseob Kimb7b84572024-04-30 10:51:47 +0900819}
820
Kiyoung Kim67118212024-11-07 13:23:44 +0900821func (f *filesystem) BuildLinkerConfigFile(ctx android.ModuleContext, builder *android.RuleBuilder, rebasedDir android.OutputPath) {
Spandan Das2047a4c2024-11-11 21:24:58 +0000822 if !proptools.Bool(f.properties.Linker_config.Gen_linker_config) {
Spandan Das92631882024-10-28 22:49:38 +0000823 return
824 }
825
Spandan Das918191e2024-10-31 18:27:23 +0000826 provideModules, _ := f.getLibsForLinkerConfig(ctx)
Spandan Das92631882024-10-28 22:49:38 +0000827 output := rebasedDir.Join(ctx, "etc", "linker.config.pb")
Spandan Das2047a4c2024-11-11 21:24:58 +0000828 linkerconfig.BuildLinkerConfig(ctx, builder, android.PathsForModuleSrc(ctx, f.properties.Linker_config.Linker_config_srcs), provideModules, nil, output)
Spandan Das92631882024-10-28 22:49:38 +0000829
830 f.appendToEntry(ctx, output)
831}
832
Kiyoung Kim23be5bb2024-11-27 00:50:30 +0000833func (f *filesystem) ShouldUseVintfFragmentModuleOnly() bool {
834 return false
835}
836
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900837type partition interface {
838 PartitionType() string
839}
840
Cole Faust9a24d902024-03-18 15:38:12 -0700841func (f *filesystem) PartitionType() string {
842 return proptools.StringDefault(f.properties.Partition_type, "system")
843}
844
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900845var _ partition = (*filesystem)(nil)
846
Jiyong Park65c49f52020-11-24 14:23:26 +0900847var _ android.AndroidMkEntriesProvider = (*filesystem)(nil)
848
849// Implements android.AndroidMkEntriesProvider
850func (f *filesystem) AndroidMkEntries() []android.AndroidMkEntries {
851 return []android.AndroidMkEntries{android.AndroidMkEntries{
852 Class: "ETC",
853 OutputFile: android.OptionalPathForPath(f.output),
854 ExtraEntries: []android.AndroidMkExtraEntriesFunc{
Colin Crossaa255532020-07-03 13:18:24 -0700855 func(ctx android.AndroidMkExtraEntriesContext, entries *android.AndroidMkEntries) {
Colin Crossc68db4b2021-11-11 18:59:15 -0800856 entries.SetString("LOCAL_MODULE_PATH", f.installDir.String())
Jiyong Park65c49f52020-11-24 14:23:26 +0900857 entries.SetString("LOCAL_INSTALLED_MODULE_STEM", f.installFileName())
Kiyoung Kim99a954d2024-06-21 14:22:20 +0900858 entries.SetString("LOCAL_FILESYSTEM_FILELIST", f.fileListFile.String())
Jiyong Park65c49f52020-11-24 14:23:26 +0900859 },
860 },
861 }}
Jiyong Park6f0f6882020-11-12 13:14:30 +0900862}
Jiyong Park12a719c2021-01-07 15:31:24 +0900863
864// Filesystem is the public interface for the filesystem struct. Currently, it's only for the apex
865// package to have access to the output file.
866type Filesystem interface {
867 android.Module
868 OutputPath() android.Path
Jiyong Park972e06c2021-03-15 23:32:49 +0900869
870 // Returns the output file that is signed by avbtool. If this module is not signed, returns
871 // nil.
872 SignedOutputPath() android.Path
Jiyong Park12a719c2021-01-07 15:31:24 +0900873}
874
875var _ Filesystem = (*filesystem)(nil)
876
877func (f *filesystem) OutputPath() android.Path {
878 return f.output
879}
Jiyong Park972e06c2021-03-15 23:32:49 +0900880
881func (f *filesystem) SignedOutputPath() android.Path {
882 if proptools.Bool(f.properties.Use_avb) {
883 return f.OutputPath()
884 }
885 return nil
886}
Jooyung Han0fbbc2b2022-03-25 12:35:46 +0900887
888// Filter the result of GatherPackagingSpecs to discard items targeting outside "system" partition.
889// Note that "apex" module installs its contents to "apex"(fake partition) as well
890// for symbol lookup by imitating "activated" paths.
891func (f *filesystem) gatherFilteredPackagingSpecs(ctx android.ModuleContext) map[string]android.PackagingSpec {
Inseob Kim3c0a0422024-11-05 17:21:37 +0900892 specs := f.PackagingBase.GatherPackagingSpecsWithFilterAndModifier(ctx, f.filesystemBuilder.FilterPackagingSpec, f.filesystemBuilder.ModifyPackagingSpec)
Jooyung Han0fbbc2b2022-03-25 12:35:46 +0900893 return specs
894}
Jooyung Han65f402b2022-04-21 14:24:04 +0900895
896func sha1sum(values []string) string {
897 h := sha256.New()
898 for _, value := range values {
899 io.WriteString(h, value)
900 }
901 return fmt.Sprintf("%x", h.Sum(nil))
902}
Jooyung Hane6067592023-03-16 13:11:17 +0900903
904// Base cc.UseCoverage
905
906var _ cc.UseCoverage = (*filesystem)(nil)
907
Colin Crosse1a85552024-06-14 12:17:37 -0700908func (*filesystem) IsNativeCoverageNeeded(ctx cc.IsNativeCoverageNeededContext) bool {
Jooyung Hane6067592023-03-16 13:11:17 +0900909 return ctx.Device() && ctx.DeviceConfig().NativeCoverageEnabled()
910}
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900911
912// android_filesystem_defaults
913
914type filesystemDefaults struct {
915 android.ModuleBase
916 android.DefaultsModuleBase
917
Inseob Kim3c0a0422024-11-05 17:21:37 +0900918 properties FilesystemProperties
Jiyong Parkf46b1af2024-04-05 18:13:33 +0900919}
920
921// android_filesystem_defaults is a default module for android_filesystem and android_system_image
922func filesystemDefaultsFactory() android.Module {
923 module := &filesystemDefaults{}
924 module.AddProperties(&module.properties)
925 module.AddProperties(&android.PackagingProperties{})
926 android.InitDefaultsModule(module)
927 return module
928}
929
930func (f *filesystemDefaults) PartitionType() string {
931 return proptools.StringDefault(f.properties.Partition_type, "system")
932}
933
934var _ partition = (*filesystemDefaults)(nil)
935
936func (f *filesystemDefaults) GenerateAndroidBuildActions(ctx android.ModuleContext) {
937 validatePartitionType(ctx, f)
938}
Spandan Das918191e2024-10-31 18:27:23 +0000939
940// getLibsForLinkerConfig returns
941// 1. A list of libraries installed in this filesystem
942// 2. A list of dep libraries _not_ installed in this filesystem
943//
944// `linkerconfig.BuildLinkerConfig` will convert these two to a linker.config.pb for the filesystem
945// (1) will be added to --provideLibs if they are C libraries with a stable interface (has stubs)
946// (2) will be added to --requireLibs if they are C libraries with a stable interface (has stubs)
947func (f *filesystem) getLibsForLinkerConfig(ctx android.ModuleContext) ([]android.Module, []android.Module) {
948 // we need "Module"s for packaging items
949 modulesInPackageByModule := make(map[android.Module]bool)
950 modulesInPackageByName := make(map[string]bool)
951
952 deps := f.gatherFilteredPackagingSpecs(ctx)
953 ctx.WalkDeps(func(child, parent android.Module) bool {
954 for _, ps := range android.OtherModuleProviderOrDefault(
955 ctx, child, android.InstallFilesProvider).PackagingSpecs {
956 if _, ok := deps[ps.RelPathInPackage()]; ok {
957 modulesInPackageByModule[child] = true
958 modulesInPackageByName[child.Name()] = true
959 return true
960 }
961 }
962 return true
963 })
964
965 provideModules := make([]android.Module, 0, len(modulesInPackageByModule))
966 for mod := range modulesInPackageByModule {
967 provideModules = append(provideModules, mod)
968 }
969
970 var requireModules []android.Module
971 ctx.WalkDeps(func(child, parent android.Module) bool {
972 _, parentInPackage := modulesInPackageByModule[parent]
973 _, childInPackageName := modulesInPackageByName[child.Name()]
974
975 // When parent is in the package, and child (or its variant) is not, this can be from an interface.
976 if parentInPackage && !childInPackageName {
977 requireModules = append(requireModules, child)
978 }
979 return true
980 })
981
982 return provideModules, requireModules
983}
Cole Faust26bdac52024-11-19 13:37:53 -0800984
985// Checks that the given file doesn't exceed the given size, and will also print a warning
986// if it's nearing the maximum size. Equivalent to assert-max-image-size in make:
987// https://cs.android.com/android/platform/superproject/main/+/main:build/make/core/definitions.mk;l=3455;drc=993c4de29a02a6accd60ceaaee153307e1a18d10
988func assertMaxImageSize(builder *android.RuleBuilder, image android.Path, maxSize int64, addAvbLater bool) {
989 if addAvbLater {
990 // The value 69632 is derived from MAX_VBMETA_SIZE + MAX_FOOTER_SIZE in avbtool.
991 // Logic copied from make:
992 // https://cs.android.com/android/platform/superproject/main/+/main:build/make/core/Makefile;l=228;drc=a6a0007ef24e16c0b79f439beac4a118416717e6
993 maxSize -= 69632
994 }
995 cmd := builder.Command()
996 cmd.Textf(`file="%s"; maxsize="%d";`+
997 `total=$(stat -c "%%s" "$file" | tr -d '\n');`+
998 `if [ "$total" -gt "$maxsize" ]; then `+
999 ` echo "error: $file too large ($total > $maxsize)";`+
1000 ` false;`+
1001 `elif [ "$total" -gt $((maxsize - 32768)) ]; then `+
1002 ` echo "WARNING: $file approaching size limit ($total now; limit $maxsize)";`+
1003 `fi`,
1004 image, maxSize)
1005 cmd.Implicit(image)
1006}