blob: 468794fabf78167690a697e4dd89be34965ca08f [file] [log] [blame]
Jihoon Kang98047cf2024-10-02 17:13:54 +00001// Copyright (C) 2024 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 fsgen
16
17import (
Cole Faust92ccbe22024-10-03 14:38:37 -070018 "crypto/sha256"
Jihoon Kang98047cf2024-10-02 17:13:54 +000019 "fmt"
mrziwang8f86c882024-10-03 12:34:33 -070020 "slices"
Jihoon Kang98047cf2024-10-02 17:13:54 +000021 "strconv"
mrziwang8f86c882024-10-03 12:34:33 -070022 "strings"
23 "sync"
24
25 "android/soong/android"
26 "android/soong/filesystem"
Jihoon Kang98047cf2024-10-02 17:13:54 +000027
Cole Faust92ccbe22024-10-03 14:38:37 -070028 "github.com/google/blueprint"
mrziwang8f86c882024-10-03 12:34:33 -070029 "github.com/google/blueprint/parser"
Jihoon Kang98047cf2024-10-02 17:13:54 +000030 "github.com/google/blueprint/proptools"
31)
32
Cole Faust92ccbe22024-10-03 14:38:37 -070033var pctx = android.NewPackageContext("android/soong/fsgen")
34
Jihoon Kang98047cf2024-10-02 17:13:54 +000035func init() {
36 registerBuildComponents(android.InitRegistrationContext)
37}
38
39func registerBuildComponents(ctx android.RegistrationContext) {
40 ctx.RegisterModuleType("soong_filesystem_creator", filesystemCreatorFactory)
mrziwang8f86c882024-10-03 12:34:33 -070041 ctx.PreDepsMutators(RegisterCollectFileSystemDepsMutators)
42}
43
44func RegisterCollectFileSystemDepsMutators(ctx android.RegisterMutatorsContext) {
45 ctx.BottomUp("fs_collect_deps", collectDepsMutator).MutatesGlobalState()
Jihoon Kang0d545b82024-10-11 00:21:57 +000046 ctx.BottomUp("fs_set_deps", setDepsMutator)
mrziwang8f86c882024-10-03 12:34:33 -070047}
48
Jihoon Kang0d545b82024-10-11 00:21:57 +000049var fsGenStateOnceKey = android.NewOnceKey("FsGenState")
Spandan Dase1860e42024-10-24 22:29:50 +000050var fsGenRemoveOverridesOnceKey = android.NewOnceKey("FsGenRemoveOverrides")
Jihoon Kang0d545b82024-10-11 00:21:57 +000051
52// Map of partition module name to its partition that may be generated by Soong.
53// Note that it is not guaranteed that all modules returned by this function are successfully
54// created.
55func getAllSoongGeneratedPartitionNames(config android.Config, partitions []string) map[string]string {
56 ret := map[string]string{}
57 for _, partition := range partitions {
58 ret[generatedModuleNameForPartition(config, partition)] = partition
59 }
60 return ret
61}
62
63type depCandidateProps struct {
64 Namespace string
65 Multilib string
66 Arch []android.ArchType
67}
68
69// Map of module name to depCandidateProps
70type multilibDeps *map[string]*depCandidateProps
71
72// Information necessary to generate the filesystem modules, including details about their
73// dependencies
74type FsGenState struct {
75 // List of modules in `PRODUCT_PACKAGES` and `PRODUCT_PACKAGES_DEBUG`
76 depCandidates []string
77 // Map of names of partition to the information of modules to be added as deps
78 fsDeps map[string]multilibDeps
79 // List of name of partitions to be generated by the filesystem_creator module
80 soongGeneratedPartitions []string
81 // Mutex to protect the fsDeps
82 fsDepsMutex sync.Mutex
Spandan Dase1860e42024-10-24 22:29:50 +000083 // Map of _all_ soong module names to their corresponding installation properties
84 moduleToInstallationProps map[string]installationProperties
85}
86
87type installationProperties struct {
88 Required []string
89 Overrides []string
Jihoon Kang0d545b82024-10-11 00:21:57 +000090}
91
92func newMultilibDeps() multilibDeps {
93 return &map[string]*depCandidateProps{}
94}
95
96func defaultDepCandidateProps(config android.Config) *depCandidateProps {
97 return &depCandidateProps{
98 Namespace: ".",
99 Arch: []android.ArchType{config.BuildArch},
100 }
101}
102
103func createFsGenState(ctx android.LoadHookContext) *FsGenState {
104 return ctx.Config().Once(fsGenStateOnceKey, func() interface{} {
105 partitionVars := ctx.Config().ProductVariables().PartitionVarsForSoongMigrationOnlyDoNotUse
106 candidates := android.FirstUniqueStrings(android.Concat(partitionVars.ProductPackages, partitionVars.ProductPackagesDebug))
107
108 generatedPartitions := []string{"system"}
109 if ctx.DeviceConfig().SystemExtPath() == "system_ext" {
110 generatedPartitions = append(generatedPartitions, "system_ext")
111 }
Spandan Dase3b65312024-10-22 00:27:27 +0000112 if ctx.DeviceConfig().BuildingVendorImage() && ctx.DeviceConfig().VendorPath() == "vendor" {
113 generatedPartitions = append(generatedPartitions, "vendor")
114 }
Jihoon Kang6dd13b62024-10-22 23:21:02 +0000115 if ctx.DeviceConfig().BuildingProductImage() && ctx.DeviceConfig().ProductPath() == "product" {
116 generatedPartitions = append(generatedPartitions, "product")
117 }
Jihoon Kang0d545b82024-10-11 00:21:57 +0000118
119 return &FsGenState{
120 depCandidates: candidates,
121 fsDeps: map[string]multilibDeps{
122 // These additional deps are added according to the cuttlefish system image bp.
123 "system": &map[string]*depCandidateProps{
124 "com.android.apex.cts.shim.v1_prebuilt": defaultDepCandidateProps(ctx.Config()),
125 "dex_bootjars": defaultDepCandidateProps(ctx.Config()),
126 "framework_compatibility_matrix.device.xml": defaultDepCandidateProps(ctx.Config()),
127 "idc_data": defaultDepCandidateProps(ctx.Config()),
128 "init.environ.rc-soong": defaultDepCandidateProps(ctx.Config()),
129 "keychars_data": defaultDepCandidateProps(ctx.Config()),
130 "keylayout_data": defaultDepCandidateProps(ctx.Config()),
131 "libclang_rt.asan": defaultDepCandidateProps(ctx.Config()),
132 "libcompiler_rt": defaultDepCandidateProps(ctx.Config()),
133 "libdmabufheap": defaultDepCandidateProps(ctx.Config()),
134 "libgsi": defaultDepCandidateProps(ctx.Config()),
135 "llndk.libraries.txt": defaultDepCandidateProps(ctx.Config()),
136 "logpersist.start": defaultDepCandidateProps(ctx.Config()),
137 "preloaded-classes": defaultDepCandidateProps(ctx.Config()),
138 "public.libraries.android.txt": defaultDepCandidateProps(ctx.Config()),
139 "update_engine_sideload": defaultDepCandidateProps(ctx.Config()),
140 },
Spandan Das49cc3e82024-10-23 20:54:01 +0000141 "vendor": &map[string]*depCandidateProps{
142 "fs_config_files_vendor": defaultDepCandidateProps(ctx.Config()),
143 "fs_config_dirs_vendor": defaultDepCandidateProps(ctx.Config()),
144 },
Spandan Dasd9875bc2024-10-17 21:36:17 +0000145 "odm": newMultilibDeps(),
146 "product": newMultilibDeps(),
147 "system_ext": &map[string]*depCandidateProps{
148 // VNDK apexes are automatically included.
149 // This hardcoded list will need to be updated if `PRODUCT_EXTRA_VNDK_VERSIONS` is updated.
150 // https://cs.android.com/android/_/android/platform/build/+/adba533072b00c53ac0f198c550a3cbd7a00e4cd:core/main.mk;l=984;bpv=1;bpt=0;drc=174db7b179592cf07cbfd2adb0119486fda911e7
151 "com.android.vndk.v30": defaultDepCandidateProps(ctx.Config()),
152 "com.android.vndk.v31": defaultDepCandidateProps(ctx.Config()),
153 "com.android.vndk.v32": defaultDepCandidateProps(ctx.Config()),
154 "com.android.vndk.v33": defaultDepCandidateProps(ctx.Config()),
155 "com.android.vndk.v34": defaultDepCandidateProps(ctx.Config()),
156 },
Jihoon Kang0d545b82024-10-11 00:21:57 +0000157 },
Spandan Dase1860e42024-10-24 22:29:50 +0000158 soongGeneratedPartitions: generatedPartitions,
159 fsDepsMutex: sync.Mutex{},
160 moduleToInstallationProps: map[string]installationProperties{},
Jihoon Kang0d545b82024-10-11 00:21:57 +0000161 }
162 }).(*FsGenState)
163}
164
165func checkDepModuleInMultipleNamespaces(mctx android.BottomUpMutatorContext, foundDeps map[string]*depCandidateProps, module string, partitionName string) {
166 otherNamespace := mctx.Namespace().Path
167 if val, found := foundDeps[module]; found && otherNamespace != "." && !android.InList(val.Namespace, []string{".", otherNamespace}) {
168 mctx.ModuleErrorf("found in multiple namespaces(%s and %s) when including in %s partition", val.Namespace, otherNamespace, partitionName)
169 }
170}
171
172func appendDepIfAppropriate(mctx android.BottomUpMutatorContext, deps *map[string]*depCandidateProps, installPartition string) {
173 checkDepModuleInMultipleNamespaces(mctx, *deps, mctx.Module().Name(), installPartition)
174 if _, ok := (*deps)[mctx.Module().Name()]; ok {
175 // Prefer the namespace-specific module over the platform module
176 if mctx.Namespace().Path != "." {
177 (*deps)[mctx.Module().Name()].Namespace = mctx.Namespace().Path
178 }
179 (*deps)[mctx.Module().Name()].Arch = append((*deps)[mctx.Module().Name()].Arch, mctx.Module().Target().Arch.ArchType)
180 } else {
181 multilib, _ := mctx.Module().DecodeMultilib(mctx)
182 (*deps)[mctx.Module().Name()] = &depCandidateProps{
183 Namespace: mctx.Namespace().Path,
184 Multilib: multilib,
185 Arch: []android.ArchType{mctx.Module().Target().Arch.ArchType},
186 }
187 }
188}
mrziwang8f86c882024-10-03 12:34:33 -0700189
190func collectDepsMutator(mctx android.BottomUpMutatorContext) {
Jihoon Kang0d545b82024-10-11 00:21:57 +0000191 fsGenState := mctx.Config().Get(fsGenStateOnceKey).(*FsGenState)
mrziwang8f86c882024-10-03 12:34:33 -0700192
193 m := mctx.Module()
Spandan Dasfcc07c02024-10-21 23:33:43 +0000194 if m.Target().Os.Class == android.Device && slices.Contains(fsGenState.depCandidates, m.Name()) {
Jihoon Kang0d545b82024-10-11 00:21:57 +0000195 installPartition := m.PartitionTag(mctx.DeviceConfig())
196 fsGenState.fsDepsMutex.Lock()
197 // Only add the module as dependency when:
198 // - its enabled
199 // - its namespace is included in PRODUCT_SOONG_NAMESPACES
200 if m.Enabled(mctx) && m.ExportedToMake() {
201 appendDepIfAppropriate(mctx, fsGenState.fsDeps[installPartition], installPartition)
202 }
203 fsGenState.fsDepsMutex.Unlock()
204 }
Spandan Dase1860e42024-10-24 22:29:50 +0000205 // store the map of module to (required,overrides) even if the module is not in PRODUCT_PACKAGES.
206 // the module might be installed transitively.
207 if m.Target().Os.Class == android.Device && m.Enabled(mctx) && m.ExportedToMake() {
208 fsGenState.fsDepsMutex.Lock()
209 fsGenState.moduleToInstallationProps[m.Name()] = installationProperties{
210 Required: m.RequiredModuleNames(mctx),
211 Overrides: m.Overrides(),
212 }
213 fsGenState.fsDepsMutex.Unlock()
214 }
Jihoon Kang0d545b82024-10-11 00:21:57 +0000215}
216
217type depsStruct struct {
218 Deps []string
219}
220
221type multilibDepsStruct struct {
222 Common depsStruct
223 Lib32 depsStruct
224 Lib64 depsStruct
225 Both depsStruct
226 Prefer32 depsStruct
227}
228
229type packagingPropsStruct struct {
230 Deps []string
231 Multilib multilibDepsStruct
232}
233
234func fullyQualifiedModuleName(moduleName, namespace string) string {
235 if namespace == "." {
236 return moduleName
237 }
238 return fmt.Sprintf("//%s:%s", namespace, moduleName)
239}
240
Jihoon Kang0d545b82024-10-11 00:21:57 +0000241func getBitness(archTypes []android.ArchType) (ret []string) {
242 for _, archType := range archTypes {
243 if archType.Multilib == "" {
244 ret = append(ret, android.COMMON_VARIANT)
245 } else {
246 ret = append(ret, archType.Bitness())
247 }
248 }
249 return ret
250}
251
252func setDepsMutator(mctx android.BottomUpMutatorContext) {
Spandan Dase1860e42024-10-24 22:29:50 +0000253 removeOverriddenDeps(mctx)
Jihoon Kang0d545b82024-10-11 00:21:57 +0000254 fsGenState := mctx.Config().Get(fsGenStateOnceKey).(*FsGenState)
255 fsDeps := fsGenState.fsDeps
256 soongGeneratedPartitionMap := getAllSoongGeneratedPartitionNames(mctx.Config(), fsGenState.soongGeneratedPartitions)
257 m := mctx.Module()
258 if partition, ok := soongGeneratedPartitionMap[m.Name()]; ok {
mrziwang2a506cf2024-10-17 15:38:37 -0700259 depsStruct := generateDepStruct(*fsDeps[partition])
260 if err := proptools.AppendMatchingProperties(m.GetProperties(), depsStruct, nil); err != nil {
Jihoon Kang0d545b82024-10-11 00:21:57 +0000261 mctx.ModuleErrorf(err.Error())
mrziwang8f86c882024-10-03 12:34:33 -0700262 }
263 }
Jihoon Kang98047cf2024-10-02 17:13:54 +0000264}
265
Spandan Dase1860e42024-10-24 22:29:50 +0000266// removeOverriddenDeps collects PRODUCT_PACKAGES and (transitive) required deps.
267// it then removes any modules which appear in `overrides` of the above list.
268func removeOverriddenDeps(mctx android.BottomUpMutatorContext) {
269 mctx.Config().Once(fsGenRemoveOverridesOnceKey, func() interface{} {
270 fsGenState := mctx.Config().Get(fsGenStateOnceKey).(*FsGenState)
271 fsDeps := fsGenState.fsDeps
272 overridden := map[string]bool{}
273 allDeps := []string{}
274
275 // Step 1: Initialization: Append PRODUCT_PACKAGES to the queue
276 for _, fsDep := range fsDeps {
277 for depName, _ := range *fsDep {
278 allDeps = append(allDeps, depName)
279 }
280 }
281
282 // Step 2: Process the queue, and add required modules to the queue.
283 i := 0
284 for {
285 if i == len(allDeps) {
286 break
287 }
288 depName := allDeps[i]
289 for _, overrides := range fsGenState.moduleToInstallationProps[depName].Overrides {
290 overridden[overrides] = true
291 }
292 // add required dep to the queue.
293 allDeps = append(allDeps, fsGenState.moduleToInstallationProps[depName].Required...)
294 i += 1
295 }
296
297 // Step 3: Delete all the overridden modules.
298 for overridden, _ := range overridden {
299 for partition, _ := range fsDeps {
300 delete(*fsDeps[partition], overridden)
301 }
302 }
303 return nil
304 })
305}
306
mrziwang2a506cf2024-10-17 15:38:37 -0700307func generateDepStruct(deps map[string]*depCandidateProps) *packagingPropsStruct {
308 depsStruct := packagingPropsStruct{}
309 for depName, depProps := range deps {
310 bitness := getBitness(depProps.Arch)
311 fullyQualifiedDepName := fullyQualifiedModuleName(depName, depProps.Namespace)
312 if android.InList("32", bitness) && android.InList("64", bitness) {
313 // If both 32 and 64 bit variants are enabled for this module
314 switch depProps.Multilib {
315 case string(android.MultilibBoth):
316 depsStruct.Multilib.Both.Deps = append(depsStruct.Multilib.Both.Deps, fullyQualifiedDepName)
317 case string(android.MultilibCommon), string(android.MultilibFirst):
318 depsStruct.Deps = append(depsStruct.Deps, fullyQualifiedDepName)
319 case "32":
320 depsStruct.Multilib.Lib32.Deps = append(depsStruct.Multilib.Lib32.Deps, fullyQualifiedDepName)
321 case "64", "darwin_universal":
322 depsStruct.Multilib.Lib64.Deps = append(depsStruct.Multilib.Lib64.Deps, fullyQualifiedDepName)
323 case "prefer32", "first_prefer32":
324 depsStruct.Multilib.Prefer32.Deps = append(depsStruct.Multilib.Prefer32.Deps, fullyQualifiedDepName)
325 default:
326 depsStruct.Multilib.Both.Deps = append(depsStruct.Multilib.Both.Deps, fullyQualifiedDepName)
327 }
328 } else if android.InList("64", bitness) {
329 // If only 64 bit variant is enabled
330 depsStruct.Multilib.Lib64.Deps = append(depsStruct.Multilib.Lib64.Deps, fullyQualifiedDepName)
331 } else if android.InList("32", bitness) {
332 // If only 32 bit variant is enabled
333 depsStruct.Multilib.Lib32.Deps = append(depsStruct.Multilib.Lib32.Deps, fullyQualifiedDepName)
334 } else {
335 // If only common variant is enabled
336 depsStruct.Multilib.Common.Deps = append(depsStruct.Multilib.Common.Deps, fullyQualifiedDepName)
337 }
338 }
Jihoon Kang4e5d8de2024-10-19 01:59:58 +0000339 depsStruct.Deps = android.SortedUniqueStrings(depsStruct.Deps)
340 depsStruct.Multilib.Lib32.Deps = android.SortedUniqueStrings(depsStruct.Multilib.Lib32.Deps)
341 depsStruct.Multilib.Lib64.Deps = android.SortedUniqueStrings(depsStruct.Multilib.Lib64.Deps)
342 depsStruct.Multilib.Prefer32.Deps = android.SortedUniqueStrings(depsStruct.Multilib.Prefer32.Deps)
343 depsStruct.Multilib.Both.Deps = android.SortedUniqueStrings(depsStruct.Multilib.Both.Deps)
344 depsStruct.Multilib.Common.Deps = android.SortedUniqueStrings(depsStruct.Multilib.Common.Deps)
345
mrziwang2a506cf2024-10-17 15:38:37 -0700346 return &depsStruct
347}
348
Cole Faust92ccbe22024-10-03 14:38:37 -0700349type filesystemCreatorProps struct {
350 Generated_partition_types []string `blueprint:"mutated"`
351 Unsupported_partition_types []string `blueprint:"mutated"`
352}
353
Jihoon Kang98047cf2024-10-02 17:13:54 +0000354type filesystemCreator struct {
355 android.ModuleBase
Cole Faust92ccbe22024-10-03 14:38:37 -0700356
357 properties filesystemCreatorProps
Jihoon Kang98047cf2024-10-02 17:13:54 +0000358}
359
360func filesystemCreatorFactory() android.Module {
361 module := &filesystemCreator{}
362
Cole Faust69788792024-10-10 11:00:36 -0700363 android.InitAndroidArchModule(module, android.DeviceSupported, android.MultilibCommon)
Cole Faust92ccbe22024-10-03 14:38:37 -0700364 module.AddProperties(&module.properties)
Jihoon Kang98047cf2024-10-02 17:13:54 +0000365 android.AddLoadHook(module, func(ctx android.LoadHookContext) {
Jihoon Kang0d545b82024-10-11 00:21:57 +0000366 createFsGenState(ctx)
Jihoon Kang98047cf2024-10-02 17:13:54 +0000367 module.createInternalModules(ctx)
368 })
369
370 return module
371}
372
373func (f *filesystemCreator) createInternalModules(ctx android.LoadHookContext) {
Jihoon Kang0d545b82024-10-11 00:21:57 +0000374 soongGeneratedPartitions := &ctx.Config().Get(fsGenStateOnceKey).(*FsGenState).soongGeneratedPartitions
375 for _, partitionType := range *soongGeneratedPartitions {
Cole Faust92ccbe22024-10-03 14:38:37 -0700376 if f.createPartition(ctx, partitionType) {
377 f.properties.Generated_partition_types = append(f.properties.Generated_partition_types, partitionType)
378 } else {
379 f.properties.Unsupported_partition_types = append(f.properties.Unsupported_partition_types, partitionType)
Jihoon Kang0d545b82024-10-11 00:21:57 +0000380 _, *soongGeneratedPartitions = android.RemoveFromList(partitionType, *soongGeneratedPartitions)
Cole Faust92ccbe22024-10-03 14:38:37 -0700381 }
382 }
Jihoon Kangf1c79ca2024-10-09 20:18:38 +0000383 f.createDeviceModule(ctx)
Jihoon Kang98047cf2024-10-02 17:13:54 +0000384}
385
Jihoon Kang0d545b82024-10-11 00:21:57 +0000386func generatedModuleName(cfg android.Config, suffix string) string {
Cole Faust92ccbe22024-10-03 14:38:37 -0700387 prefix := "soong"
388 if cfg.HasDeviceProduct() {
389 prefix = cfg.DeviceProduct()
390 }
Jihoon Kangf1c79ca2024-10-09 20:18:38 +0000391 return fmt.Sprintf("%s_generated_%s", prefix, suffix)
392}
393
Jihoon Kang0d545b82024-10-11 00:21:57 +0000394func generatedModuleNameForPartition(cfg android.Config, partitionType string) string {
395 return generatedModuleName(cfg, fmt.Sprintf("%s_image", partitionType))
Jihoon Kangf1c79ca2024-10-09 20:18:38 +0000396}
397
398func (f *filesystemCreator) createDeviceModule(ctx android.LoadHookContext) {
399 baseProps := &struct {
400 Name *string
401 }{
Jihoon Kang0d545b82024-10-11 00:21:57 +0000402 Name: proptools.StringPtr(generatedModuleName(ctx.Config(), "device")),
Jihoon Kangf1c79ca2024-10-09 20:18:38 +0000403 }
404
Priyanka Advani (xWF)dafaa7f2024-10-21 22:55:13 +0000405 // Currently, only the system and system_ext partition module is created.
Jihoon Kangf1c79ca2024-10-09 20:18:38 +0000406 partitionProps := &filesystem.PartitionNameProperties{}
407 if android.InList("system", f.properties.Generated_partition_types) {
Jihoon Kang0d545b82024-10-11 00:21:57 +0000408 partitionProps.System_partition_name = proptools.StringPtr(generatedModuleNameForPartition(ctx.Config(), "system"))
Jihoon Kangf1c79ca2024-10-09 20:18:38 +0000409 }
Spandan Das7a46f6c2024-10-14 18:41:18 +0000410 if android.InList("system_ext", f.properties.Generated_partition_types) {
Jihoon Kang0d545b82024-10-11 00:21:57 +0000411 partitionProps.System_ext_partition_name = proptools.StringPtr(generatedModuleNameForPartition(ctx.Config(), "system_ext"))
Spandan Das7a46f6c2024-10-14 18:41:18 +0000412 }
Spandan Dase3b65312024-10-22 00:27:27 +0000413 if android.InList("vendor", f.properties.Generated_partition_types) {
414 partitionProps.Vendor_partition_name = proptools.StringPtr(generatedModuleNameForPartition(ctx.Config(), "vendor"))
415 }
Jihoon Kang6dd13b62024-10-22 23:21:02 +0000416 if android.InList("product", f.properties.Generated_partition_types) {
417 partitionProps.Product_partition_name = proptools.StringPtr(generatedModuleNameForPartition(ctx.Config(), "product"))
418 }
Jihoon Kangf1c79ca2024-10-09 20:18:38 +0000419
420 ctx.CreateModule(filesystem.AndroidDeviceFactory, baseProps, partitionProps)
Cole Faust92ccbe22024-10-03 14:38:37 -0700421}
422
Jihoon Kang6850d8f2024-10-17 20:45:58 +0000423func partitionSpecificFsProps(fsProps *filesystem.FilesystemProperties, partitionType string) {
424 switch partitionType {
425 case "system":
426 fsProps.Build_logtags = proptools.BoolPtr(true)
427 // https://source.corp.google.com/h/googleplex-android/platform/build//639d79f5012a6542ab1f733b0697db45761ab0f3:core/packaging/flags.mk;l=21;drc=5ba8a8b77507f93aa48cc61c5ba3f31a4d0cbf37;bpv=1;bpt=0
428 fsProps.Gen_aconfig_flags_pb = proptools.BoolPtr(true)
Spandan Dasa8fa6b42024-10-23 00:45:29 +0000429 // Identical to that of the generic_system_image
430 fsProps.Fsverity.Inputs = []string{
431 "etc/boot-image.prof",
432 "etc/dirty-image-objects",
433 "etc/preloaded-classes",
434 "etc/classpaths/*.pb",
435 "framework/*",
436 "framework/*/*", // framework/{arch}
437 "framework/oat/*/*", // framework/oat/{arch}
438 }
439 fsProps.Fsverity.Libs = []string{":framework-res{.export-package.apk}"}
440 case "system_ext":
441 fsProps.Fsverity.Inputs = []string{
442 "framework/*",
443 "framework/*/*", // framework/{arch}
444 "framework/oat/*/*", // framework/oat/{arch}
445 }
446 fsProps.Fsverity.Libs = []string{":framework-res{.export-package.apk}"}
Jihoon Kang6850d8f2024-10-17 20:45:58 +0000447 case "product":
448 fsProps.Gen_aconfig_flags_pb = proptools.BoolPtr(true)
449 case "vendor":
450 fsProps.Gen_aconfig_flags_pb = proptools.BoolPtr(true)
451 }
452}
Spandan Dascbe641a2024-10-14 21:07:34 +0000453
Cole Faust92ccbe22024-10-03 14:38:37 -0700454// Creates a soong module to build the given partition. Returns false if we can't support building
455// it.
456func (f *filesystemCreator) createPartition(ctx android.LoadHookContext, partitionType string) bool {
mrziwang4b0ca972024-10-17 14:56:19 -0700457 baseProps := generateBaseProps(proptools.StringPtr(generatedModuleNameForPartition(ctx.Config(), partitionType)))
458
459 fsProps, supported := generateFsProps(ctx, partitionType)
460 if !supported {
461 return false
mrziwanga077b942024-10-16 16:00:06 -0700462 }
mrziwanga077b942024-10-16 16:00:06 -0700463
mrziwang4b0ca972024-10-17 14:56:19 -0700464 var module android.Module
465 if partitionType == "system" {
466 module = ctx.CreateModule(filesystem.SystemImageFactory, baseProps, fsProps)
467 } else {
468 // Explicitly set the partition.
469 fsProps.Partition_type = proptools.StringPtr(partitionType)
470 module = ctx.CreateModule(filesystem.FilesystemFactory, baseProps, fsProps)
471 }
472 module.HideFromMake()
473 return true
474}
475
476type filesystemBaseProperty struct {
477 Name *string
478 Compile_multilib *string
479}
480
481func generateBaseProps(namePtr *string) *filesystemBaseProperty {
482 return &filesystemBaseProperty{
483 Name: namePtr,
484 Compile_multilib: proptools.StringPtr("both"),
485 }
486}
487
488func generateFsProps(ctx android.EarlyModuleContext, partitionType string) (*filesystem.FilesystemProperties, bool) {
Cole Faust92ccbe22024-10-03 14:38:37 -0700489 fsProps := &filesystem.FilesystemProperties{}
490
mrziwang4b0ca972024-10-17 14:56:19 -0700491 partitionVars := ctx.Config().ProductVariables().PartitionVarsForSoongMigrationOnlyDoNotUse
492 specificPartitionVars := partitionVars.PartitionQualifiedVariables[partitionType]
493
494 // BOARD_SYSTEMIMAGE_FILE_SYSTEM_TYPE
495 fsType := specificPartitionVars.BoardFileSystemType
496 if fsType == "" {
497 fsType = "ext4" //default
498 }
499 fsProps.Type = proptools.StringPtr(fsType)
500 if filesystem.GetFsTypeFromString(ctx, *fsProps.Type).IsUnknown() {
501 // Currently the android_filesystem module type only supports a handful of FS types like ext4, erofs
502 return nil, false
503 }
504
Cole Faust92ccbe22024-10-03 14:38:37 -0700505 // Don't build this module on checkbuilds, the soong-built partitions are still in-progress
506 // and sometimes don't build.
507 fsProps.Unchecked_module = proptools.BoolPtr(true)
508
Jihoon Kang98047cf2024-10-02 17:13:54 +0000509 // BOARD_AVB_ENABLE
510 fsProps.Use_avb = proptools.BoolPtr(partitionVars.BoardAvbEnable)
511 // BOARD_AVB_KEY_PATH
Cole Faust92ccbe22024-10-03 14:38:37 -0700512 fsProps.Avb_private_key = proptools.StringPtr(specificPartitionVars.BoardAvbKeyPath)
Jihoon Kang98047cf2024-10-02 17:13:54 +0000513 // BOARD_AVB_ALGORITHM
Cole Faust92ccbe22024-10-03 14:38:37 -0700514 fsProps.Avb_algorithm = proptools.StringPtr(specificPartitionVars.BoardAvbAlgorithm)
Jihoon Kang98047cf2024-10-02 17:13:54 +0000515 // BOARD_AVB_SYSTEM_ROLLBACK_INDEX
Cole Faust92ccbe22024-10-03 14:38:37 -0700516 if rollbackIndex, err := strconv.ParseInt(specificPartitionVars.BoardAvbRollbackIndex, 10, 64); err == nil {
Jihoon Kang98047cf2024-10-02 17:13:54 +0000517 fsProps.Rollback_index = proptools.Int64Ptr(rollbackIndex)
518 }
519
Cole Faust92ccbe22024-10-03 14:38:37 -0700520 fsProps.Partition_name = proptools.StringPtr(partitionType)
Jihoon Kang98047cf2024-10-02 17:13:54 +0000521
Cole Faust92ccbe22024-10-03 14:38:37 -0700522 fsProps.Base_dir = proptools.StringPtr(partitionType)
Jihoon Kang98047cf2024-10-02 17:13:54 +0000523
Jihoon Kang0d545b82024-10-11 00:21:57 +0000524 fsProps.Is_auto_generated = proptools.BoolPtr(true)
525
Jihoon Kang6850d8f2024-10-17 20:45:58 +0000526 partitionSpecificFsProps(fsProps, partitionType)
527
Jihoon Kang98047cf2024-10-02 17:13:54 +0000528 // system_image properties that are not set:
529 // - filesystemProperties.Avb_hash_algorithm
530 // - filesystemProperties.File_contexts
531 // - filesystemProperties.Dirs
532 // - filesystemProperties.Symlinks
533 // - filesystemProperties.Fake_timestamp
534 // - filesystemProperties.Uuid
535 // - filesystemProperties.Mount_point
536 // - filesystemProperties.Include_make_built_files
537 // - filesystemProperties.Build_logtags
Jihoon Kang98047cf2024-10-02 17:13:54 +0000538 // - systemImageProperties.Linker_config_src
mrziwang4b0ca972024-10-17 14:56:19 -0700539
540 return fsProps, true
Cole Faust92ccbe22024-10-03 14:38:37 -0700541}
542
543func (f *filesystemCreator) createDiffTest(ctx android.ModuleContext, partitionType string) android.Path {
Jihoon Kang0d545b82024-10-11 00:21:57 +0000544 partitionModuleName := generatedModuleNameForPartition(ctx.Config(), partitionType)
Cole Faust92ccbe22024-10-03 14:38:37 -0700545 systemImage := ctx.GetDirectDepWithTag(partitionModuleName, generatedFilesystemDepTag)
546 filesystemInfo, ok := android.OtherModuleProvider(ctx, systemImage, filesystem.FilesystemProvider)
547 if !ok {
548 ctx.ModuleErrorf("Expected module %s to provide FileysystemInfo", partitionModuleName)
549 }
550 makeFileList := android.PathForArbitraryOutput(ctx, fmt.Sprintf("target/product/%s/obj/PACKAGING/%s_intermediates/file_list.txt", ctx.Config().DeviceName(), partitionType))
551 // For now, don't allowlist anything. The test will fail, but that's fine in the current
552 // early stages where we're just figuring out what we need
Jihoon Kang9e866c82024-10-07 22:39:18 +0000553 emptyAllowlistFile := android.PathForModuleOut(ctx, fmt.Sprintf("allowlist_%s.txt", partitionModuleName))
Cole Faust92ccbe22024-10-03 14:38:37 -0700554 android.WriteFileRule(ctx, emptyAllowlistFile, "")
Jihoon Kang9e866c82024-10-07 22:39:18 +0000555 diffTestResultFile := android.PathForModuleOut(ctx, fmt.Sprintf("diff_test_%s.txt", partitionModuleName))
Cole Faust92ccbe22024-10-03 14:38:37 -0700556
557 builder := android.NewRuleBuilder(pctx, ctx)
558 builder.Command().BuiltTool("file_list_diff").
559 Input(makeFileList).
560 Input(filesystemInfo.FileListFile).
Jihoon Kang9e866c82024-10-07 22:39:18 +0000561 Text(partitionModuleName).
562 FlagWithInput("--allowlists ", emptyAllowlistFile)
Cole Faust92ccbe22024-10-03 14:38:37 -0700563 builder.Command().Text("touch").Output(diffTestResultFile)
564 builder.Build(partitionModuleName+" diff test", partitionModuleName+" diff test")
565 return diffTestResultFile
566}
567
568func createFailingCommand(ctx android.ModuleContext, message string) android.Path {
569 hasher := sha256.New()
570 hasher.Write([]byte(message))
571 filename := fmt.Sprintf("failing_command_%x.txt", hasher.Sum(nil))
572 file := android.PathForModuleOut(ctx, filename)
573 builder := android.NewRuleBuilder(pctx, ctx)
574 builder.Command().Textf("echo %s", proptools.NinjaAndShellEscape(message))
575 builder.Command().Text("exit 1 #").Output(file)
576 builder.Build("failing command "+filename, "failing command "+filename)
577 return file
578}
579
580type systemImageDepTagType struct {
581 blueprint.BaseDependencyTag
582}
583
584var generatedFilesystemDepTag systemImageDepTagType
585
586func (f *filesystemCreator) DepsMutator(ctx android.BottomUpMutatorContext) {
587 for _, partitionType := range f.properties.Generated_partition_types {
Jihoon Kang0d545b82024-10-11 00:21:57 +0000588 ctx.AddDependency(ctx.Module(), generatedFilesystemDepTag, generatedModuleNameForPartition(ctx.Config(), partitionType))
Cole Faust92ccbe22024-10-03 14:38:37 -0700589 }
Jihoon Kang98047cf2024-10-02 17:13:54 +0000590}
591
592func (f *filesystemCreator) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Cole Faust92ccbe22024-10-03 14:38:37 -0700593 if ctx.ModuleDir() != "build/soong/fsgen" {
594 ctx.ModuleErrorf("There can only be one soong_filesystem_creator in build/soong/fsgen")
595 }
596 f.HideFromMake()
Jihoon Kang98047cf2024-10-02 17:13:54 +0000597
Jihoon Kang4e5d8de2024-10-19 01:59:58 +0000598 var content strings.Builder
599 generatedBp := android.PathForModuleOut(ctx, "soong_generated_product_config.bp")
600 for _, partition := range ctx.Config().Get(fsGenStateOnceKey).(*FsGenState).soongGeneratedPartitions {
601 content.WriteString(generateBpContent(ctx, partition))
602 content.WriteString("\n")
603 }
604 android.WriteFileRule(ctx, generatedBp, content.String())
605
mrziwang8f86c882024-10-03 12:34:33 -0700606 ctx.Phony("product_config_to_bp", generatedBp)
607
Cole Faust92ccbe22024-10-03 14:38:37 -0700608 var diffTestFiles []android.Path
609 for _, partitionType := range f.properties.Generated_partition_types {
Jihoon Kang72f812f2024-10-17 18:46:24 +0000610 diffTestFile := f.createDiffTest(ctx, partitionType)
611 diffTestFiles = append(diffTestFiles, diffTestFile)
612 ctx.Phony(fmt.Sprintf("soong_generated_%s_filesystem_test", partitionType), diffTestFile)
Cole Faust92ccbe22024-10-03 14:38:37 -0700613 }
614 for _, partitionType := range f.properties.Unsupported_partition_types {
Jihoon Kang72f812f2024-10-17 18:46:24 +0000615 diffTestFile := createFailingCommand(ctx, fmt.Sprintf("Couldn't build %s partition", partitionType))
616 diffTestFiles = append(diffTestFiles, diffTestFile)
617 ctx.Phony(fmt.Sprintf("soong_generated_%s_filesystem_test", partitionType), diffTestFile)
Cole Faust92ccbe22024-10-03 14:38:37 -0700618 }
619 ctx.Phony("soong_generated_filesystem_tests", diffTestFiles...)
Jihoon Kang98047cf2024-10-02 17:13:54 +0000620}
mrziwang8f86c882024-10-03 12:34:33 -0700621
mrziwang8f86c882024-10-03 12:34:33 -0700622func generateBpContent(ctx android.EarlyModuleContext, partitionType string) string {
mrziwang4b0ca972024-10-17 14:56:19 -0700623 fsProps, fsTypeSupported := generateFsProps(ctx, partitionType)
624 if !fsTypeSupported {
625 return ""
mrziwang8f86c882024-10-03 12:34:33 -0700626 }
627
mrziwang4b0ca972024-10-17 14:56:19 -0700628 baseProps := generateBaseProps(proptools.StringPtr(generatedModuleNameForPartition(ctx.Config(), partitionType)))
mrziwang2a506cf2024-10-17 15:38:37 -0700629 deps := ctx.Config().Get(fsGenStateOnceKey).(*FsGenState).fsDeps[partitionType]
630 depProps := generateDepStruct(*deps)
mrziwang8f86c882024-10-03 12:34:33 -0700631
mrziwang4b0ca972024-10-17 14:56:19 -0700632 result, err := proptools.RepackProperties([]interface{}{baseProps, fsProps, depProps})
mrziwang8f86c882024-10-03 12:34:33 -0700633 if err != nil {
634 ctx.ModuleErrorf(err.Error())
635 }
636
Jihoon Kang4e5d8de2024-10-19 01:59:58 +0000637 moduleType := "android_filesystem"
638 if partitionType == "system" {
639 moduleType = "android_system_image"
640 }
641
mrziwang8f86c882024-10-03 12:34:33 -0700642 file := &parser.File{
643 Defs: []parser.Definition{
644 &parser.Module{
Jihoon Kang4e5d8de2024-10-19 01:59:58 +0000645 Type: moduleType,
mrziwang8f86c882024-10-03 12:34:33 -0700646 Map: *result,
647 },
648 },
649 }
650 bytes, err := parser.Print(file)
651 if err != nil {
652 ctx.ModuleErrorf(err.Error())
653 }
654 return strings.TrimSpace(string(bytes))
655}