• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright 2015 Google Inc. All rights reserved.
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 android
16
17import (
18	"fmt"
19	"reflect"
20	"runtime"
21	"strings"
22
23	"github.com/google/blueprint/proptools"
24)
25
26func init() {
27	registerVariableBuildComponents(InitRegistrationContext)
28}
29
30func registerVariableBuildComponents(ctx RegistrationContext) {
31	ctx.PreDepsMutators(func(ctx RegisterMutatorsContext) {
32		ctx.BottomUp("variable", VariableMutator)
33	})
34}
35
36var PrepareForTestWithVariables = FixtureRegisterWithContext(registerVariableBuildComponents)
37
38type variableProperties struct {
39	Product_variables struct {
40		Platform_sdk_version struct {
41			Asflags []string
42			Cflags  []string
43			Cmd     *string
44		}
45
46		Platform_sdk_version_or_codename struct {
47			Java_resource_dirs []string
48		}
49
50		Platform_sdk_extension_version struct {
51			Cmd *string
52		}
53
54		Platform_version_name struct {
55			Base_dir *string
56		}
57
58		Shipping_api_level struct {
59			Cflags []string
60		}
61
62		// unbundled_build is a catch-all property to annotate modules that don't build in one or
63		// more unbundled branches, usually due to dependencies missing from the manifest.
64		Unbundled_build struct {
65			Enabled proptools.Configurable[bool] `android:"arch_variant,replace_instead_of_append"`
66		} `android:"arch_variant"`
67
68		Malloc_low_memory struct {
69			Cflags              []string `android:"arch_variant"`
70			Shared_libs         []string `android:"arch_variant"`
71			Whole_static_libs   []string `android:"arch_variant"`
72			Static_libs         []string `android:"arch_variant"`
73			Exclude_static_libs []string `android:"arch_variant"`
74			Srcs                []string `android:"arch_variant"`
75			Header_libs         []string `android:"arch_variant"`
76		} `android:"arch_variant"`
77
78		Malloc_zero_contents struct {
79			Cflags []string `android:"arch_variant"`
80		} `android:"arch_variant"`
81
82		Malloc_pattern_fill_contents struct {
83			Cflags []string `android:"arch_variant"`
84		} `android:"arch_variant"`
85
86		Safestack struct {
87			Cflags []string `android:"arch_variant"`
88		} `android:"arch_variant"`
89
90		Binder32bit struct {
91			Cflags []string
92		}
93
94		Override_rs_driver struct {
95			Cflags []string
96		}
97
98		// treble_linker_namespaces is true when the system/vendor linker namespace separation is
99		// enabled.
100		Treble_linker_namespaces struct {
101			Cflags []string
102		}
103		// enforce_vintf_manifest is true when a device is required to have a vintf manifest.
104		Enforce_vintf_manifest struct {
105			Cflags []string
106		}
107
108		Build_from_text_stub struct {
109			Static_libs         []string
110			Exclude_static_libs []string
111		}
112
113		// debuggable is true for eng and userdebug builds, and can be used to turn on additional
114		// debugging features that don't significantly impact runtime behavior.  userdebug builds
115		// are used for dogfooding and performance testing, and should be as similar to user builds
116		// as possible.
117		Debuggable struct {
118			Apk             *string
119			Cflags          []string
120			Cppflags        []string
121			Init_rc         []string
122			Required        []string
123			Host_required   []string
124			Target_required []string
125			Strip           struct {
126				All                          *bool
127				Keep_symbols                 *bool
128				Keep_symbols_and_debug_frame *bool
129			}
130			Static_libs         []string
131			Exclude_static_libs []string
132			Whole_static_libs   []string
133			Shared_libs         []string
134			Jni_libs            []string
135
136			Cmdline []string
137
138			Srcs         []string
139			Exclude_srcs []string
140			Cmd          *string
141
142			Deps []string
143		}
144
145		// eng is true for -eng builds, and can be used to turn on additional heavyweight debugging
146		// features.
147		Eng struct {
148			Cflags   []string
149			Cppflags []string
150			Lto      struct {
151				Never *bool
152			}
153			Sanitize struct {
154				Address *bool
155			}
156			Optimize struct {
157				Enabled *bool
158			}
159			Aaptflags []string
160		}
161
162		Uml struct {
163			Cppflags []string
164		}
165
166		Arc struct {
167			Cflags            []string `android:"arch_variant"`
168			Exclude_srcs      []string `android:"arch_variant"`
169			Header_libs       []string `android:"arch_variant"`
170			Include_dirs      []string `android:"arch_variant"`
171			Shared_libs       []string `android:"arch_variant"`
172			Static_libs       []string `android:"arch_variant"`
173			Srcs              []string `android:"arch_variant"`
174			Whole_static_libs []string `android:"arch_variant"`
175		} `android:"arch_variant"`
176
177		Native_coverage struct {
178			Src          *string  `android:"arch_variant"`
179			Srcs         []string `android:"arch_variant"`
180			Exclude_srcs []string `android:"arch_variant"`
181		} `android:"arch_variant"`
182
183		// release_aidl_use_unfrozen is "true" when a device can
184		// use the unfrozen versions of AIDL interfaces.
185		Release_aidl_use_unfrozen struct {
186			Cflags                 []string
187			Cmd                    *string
188			Required               []string
189			Vintf_fragment_modules []string
190		}
191		SelinuxIgnoreNeverallows struct {
192			Required []string
193		}
194	} `android:"arch_variant"`
195}
196
197var defaultProductVariables interface{} = variableProperties{}
198
199type ProductVariables struct {
200	// Suffix to add to generated Makefiles
201	Make_suffix *string `json:",omitempty"`
202
203	BuildId              *string `json:",omitempty"`
204	BuildFingerprintFile *string `json:",omitempty"`
205	BuildNumberFile      *string `json:",omitempty"`
206	BuildHostnameFile    *string `json:",omitempty"`
207	BuildThumbprintFile  *string `json:",omitempty"`
208	DisplayBuildNumber   *bool   `json:",omitempty"`
209
210	Platform_display_version_name          *string  `json:",omitempty"`
211	Platform_version_name                  *string  `json:",omitempty"`
212	Platform_sdk_version                   *int     `json:",omitempty"`
213	Platform_sdk_version_full              *string  `json:",omitempty"`
214	Platform_sdk_codename                  *string  `json:",omitempty"`
215	Platform_sdk_version_or_codename       *string  `json:",omitempty"`
216	Platform_sdk_final                     *bool    `json:",omitempty"`
217	Platform_sdk_extension_version         *int     `json:",omitempty"`
218	Platform_base_sdk_extension_version    *int     `json:",omitempty"`
219	Platform_version_active_codenames      []string `json:",omitempty"`
220	Platform_version_all_preview_codenames []string `json:",omitempty"`
221	Platform_systemsdk_versions            []string `json:",omitempty"`
222	Platform_security_patch                *string  `json:",omitempty"`
223	Platform_preview_sdk_version           *string  `json:",omitempty"`
224	Platform_base_os                       *string  `json:",omitempty"`
225	Platform_version_last_stable           *string  `json:",omitempty"`
226	Platform_version_known_codenames       *string  `json:",omitempty"`
227
228	DeviceName                            *string  `json:",omitempty" generic:"generic"`
229	DeviceProduct                         *string  `json:",omitempty" generic:"generic"`
230	DeviceArch                            *string  `json:",omitempty"`
231	DeviceArchVariant                     *string  `json:",omitempty"`
232	DeviceCpuVariant                      *string  `json:",omitempty"`
233	DeviceAbi                             []string `json:",omitempty"`
234	DeviceVndkVersion                     *string  `json:",omitempty"`
235	DeviceCurrentApiLevelForVendorModules *string  `json:",omitempty"`
236	DeviceSystemSdkVersions               []string `json:",omitempty"`
237	DeviceMaxPageSizeSupported            *string  `json:",omitempty"`
238	DeviceNoBionicPageSizeMacro           *bool    `json:",omitempty"`
239
240	VendorApiLevel             *string `json:",omitempty"`
241	VendorApiLevelPropOverride *string `json:",omitempty"`
242
243	DeviceSecondaryArch        *string  `json:",omitempty"`
244	DeviceSecondaryArchVariant *string  `json:",omitempty"`
245	DeviceSecondaryCpuVariant  *string  `json:",omitempty"`
246	DeviceSecondaryAbi         []string `json:",omitempty"`
247
248	NativeBridgeArch         *string  `json:",omitempty"`
249	NativeBridgeArchVariant  *string  `json:",omitempty"`
250	NativeBridgeCpuVariant   *string  `json:",omitempty"`
251	NativeBridgeAbi          []string `json:",omitempty"`
252	NativeBridgeRelativePath *string  `json:",omitempty"`
253
254	NativeBridgeSecondaryArch         *string  `json:",omitempty"`
255	NativeBridgeSecondaryArchVariant  *string  `json:",omitempty"`
256	NativeBridgeSecondaryCpuVariant   *string  `json:",omitempty"`
257	NativeBridgeSecondaryAbi          []string `json:",omitempty"`
258	NativeBridgeSecondaryRelativePath *string  `json:",omitempty"`
259
260	HostArch          *string `json:",omitempty"`
261	HostSecondaryArch *string `json:",omitempty"`
262	HostMusl          *bool   `json:",omitempty"`
263
264	CrossHost              *string `json:",omitempty"`
265	CrossHostArch          *string `json:",omitempty"`
266	CrossHostSecondaryArch *string `json:",omitempty"`
267
268	DeviceResourceOverlays     []string `json:",omitempty"`
269	ProductResourceOverlays    []string `json:",omitempty"`
270	EnforceRROTargets          []string `json:",omitempty"`
271	EnforceRROExcludedOverlays []string `json:",omitempty"`
272
273	AAPTCharacteristics *string  `json:",omitempty"`
274	AAPTConfig          []string `json:",omitempty"`
275	AAPTPreferredConfig *string  `json:",omitempty"`
276	AAPTPrebuiltDPI     []string `json:",omitempty"`
277
278	DefaultAppCertificate           *string  `json:",omitempty"`
279	ExtraOtaKeys                    []string `json:",omitempty"`
280	ExtraOtaRecoveryKeys            []string `json:",omitempty"`
281	MainlineSepolicyDevCertificates *string  `json:",omitempty"`
282
283	AppsDefaultVersionName *string `json:",omitempty"`
284
285	Allow_missing_dependencies   *bool    `json:",omitempty"`
286	Unbundled_build              *bool    `json:",omitempty"`
287	Unbundled_build_apps         []string `json:",omitempty"`
288	Unbundled_build_image        *bool    `json:",omitempty"`
289	Always_use_prebuilt_sdks     *bool    `json:",omitempty"`
290	Skip_boot_jars_check         *bool    `json:",omitempty"`
291	Malloc_low_memory            *bool    `json:",omitempty"`
292	Malloc_zero_contents         *bool    `json:",omitempty"`
293	Malloc_pattern_fill_contents *bool    `json:",omitempty"`
294	Safestack                    *bool    `json:",omitempty"`
295	HostStaticBinaries           *bool    `json:",omitempty"`
296	Binder32bit                  *bool    `json:",omitempty"`
297	UseGoma                      *bool    `json:",omitempty"`
298	UseABFS                      *bool    `json:",omitempty"`
299	UseRBE                       *bool    `json:",omitempty"`
300	UseRBEJAVAC                  *bool    `json:",omitempty"`
301	UseRBER8                     *bool    `json:",omitempty"`
302	UseRBED8                     *bool    `json:",omitempty"`
303	Debuggable                   *bool    `json:",omitempty"`
304	Eng                          *bool    `json:",omitempty"`
305	Treble_linker_namespaces     *bool    `json:",omitempty"`
306	Enforce_vintf_manifest       *bool    `json:",omitempty"`
307	Uml                          *bool    `json:",omitempty"`
308	Arc                          *bool    `json:",omitempty"`
309	MinimizeJavaDebugInfo        *bool    `json:",omitempty"`
310	Build_from_text_stub         *bool    `json:",omitempty"`
311
312	BuildType *string `json:",omitempty"`
313
314	Check_elf_files *bool `json:",omitempty"`
315
316	UncompressPrivAppDex             *bool    `json:",omitempty"`
317	ModulesLoadedByPrivilegedModules []string `json:",omitempty"`
318
319	BootJars     ConfiguredJarList `json:",omitempty"`
320	ApexBootJars ConfiguredJarList `json:",omitempty"`
321
322	IntegerOverflowExcludePaths []string `json:",omitempty"`
323
324	EnableCFI       *bool    `json:",omitempty"`
325	CFIExcludePaths []string `json:",omitempty"`
326	CFIIncludePaths []string `json:",omitempty"`
327
328	DisableScudo *bool `json:",omitempty"`
329
330	MemtagHeapExcludePaths      []string `json:",omitempty"`
331	MemtagHeapAsyncIncludePaths []string `json:",omitempty"`
332	MemtagHeapSyncIncludePaths  []string `json:",omitempty"`
333
334	HWASanIncludePaths []string `json:",omitempty"`
335	HWASanExcludePaths []string `json:",omitempty"`
336
337	VendorPath            *string `json:",omitempty"`
338	VendorDlkmPath        *string `json:",omitempty"`
339	BuildingVendorImage   *bool   `json:",omitempty"`
340	OdmPath               *string `json:",omitempty"`
341	BuildingOdmImage      *bool   `json:",omitempty"`
342	OdmDlkmPath           *string `json:",omitempty"`
343	ProductPath           *string `json:",omitempty"`
344	BuildingProductImage  *bool   `json:",omitempty"`
345	SystemExtPath         *string `json:",omitempty"`
346	SystemDlkmPath        *string `json:",omitempty"`
347	OemPath               *string `json:",omitempty"`
348	UserdataPath          *string `json:",omitempty"`
349	BuildingUserdataImage *bool   `json:",omitempty"`
350	RecoveryPath          *string `json:",omitempty"`
351	BuildingRecoveryImage *bool   `json:",omitempty"`
352
353	ClangTidy  *bool   `json:",omitempty"`
354	TidyChecks *string `json:",omitempty"`
355
356	JavaCoveragePaths        []string `json:",omitempty"`
357	JavaCoverageExcludePaths []string `json:",omitempty"`
358
359	GcovCoverage                *bool    `json:",omitempty"`
360	ClangCoverage               *bool    `json:",omitempty"`
361	NativeCoveragePaths         []string `json:",omitempty"`
362	NativeCoverageExcludePaths  []string `json:",omitempty"`
363	ClangCoverageContinuousMode *bool    `json:",omitempty"`
364
365	// Set by NewConfig
366	Native_coverage *bool `json:",omitempty"`
367
368	SanitizeHost       []string `json:",omitempty"`
369	SanitizeDevice     []string `json:",omitempty"`
370	SanitizeDeviceDiag []string `json:",omitempty"`
371	SanitizeDeviceArch []string `json:",omitempty"`
372
373	ArtUseReadBarrier *bool `json:",omitempty"`
374
375	BtConfigIncludeDir *string `json:",omitempty"`
376
377	Override_rs_driver *string `json:",omitempty"`
378
379	DeviceKernelHeaders []string `json:",omitempty"`
380
381	ExtraVndkVersions []string `json:",omitempty"`
382
383	NamespacesToExport []string `json:",omitempty"`
384
385	PgoAdditionalProfileDirs []string `json:",omitempty"`
386
387	MultitreeUpdateMeta bool `json:",omitempty"`
388
389	BoardVendorSepolicyDirs      []string `json:",omitempty"`
390	BoardOdmSepolicyDirs         []string `json:",omitempty"`
391	SystemExtPublicSepolicyDirs  []string `json:",omitempty"`
392	SystemExtPrivateSepolicyDirs []string `json:",omitempty"`
393	BoardSepolicyM4Defs          []string `json:",omitempty"`
394
395	BoardPlatform           *string `json:",omitempty"`
396	BoardSepolicyVers       *string `json:",omitempty"`
397	PlatformSepolicyVersion *string `json:",omitempty"`
398
399	SystemExtSepolicyPrebuiltApiDir *string `json:",omitempty"`
400	ProductSepolicyPrebuiltApiDir   *string `json:",omitempty"`
401
402	PlatformSepolicyCompatVersions []string `json:",omitempty"`
403
404	VendorVars     map[string]map[string]string `json:",omitempty"`
405	VendorVarTypes map[string]map[string]string `json:",omitempty"`
406
407	Ndk_abis *bool `json:",omitempty"`
408
409	ForceApexSymlinkOptimization *bool   `json:",omitempty"`
410	CompressedApex               *bool   `json:",omitempty"`
411	DefaultApexPayloadType       *string `json:",omitempty"`
412	Aml_abis                     *bool   `json:",omitempty"`
413
414	DexpreoptGlobalConfig *string `json:",omitempty"`
415
416	WithDexpreopt bool `json:",omitempty"`
417
418	ManifestPackageNameOverrides   []string `json:",omitempty"`
419	CertificateOverrides           []string `json:",omitempty"`
420	PackageNameOverrides           []string `json:",omitempty"`
421	ConfiguredJarLocationOverrides []string `json:",omitempty"`
422
423	ApexGlobalMinSdkVersionOverride *string `json:",omitempty"`
424
425	EnforceSystemCertificate          *bool    `json:",omitempty"`
426	EnforceSystemCertificateAllowList []string `json:",omitempty"`
427
428	ProductHiddenAPIStubs       []string `json:",omitempty"`
429	ProductHiddenAPIStubsSystem []string `json:",omitempty"`
430	ProductHiddenAPIStubsTest   []string `json:",omitempty"`
431
432	ProductPublicSepolicyDirs  []string `json:",omitempty"`
433	ProductPrivateSepolicyDirs []string `json:",omitempty"`
434
435	TargetFSConfigGen []string `json:",omitempty"`
436
437	UseSoongSystemImage            *bool   `json:",omitempty"`
438	ProductSoongDefinedSystemImage *string `json:",omitempty"`
439
440	EnforceProductPartitionInterface *bool `json:",omitempty"`
441
442	BoardUsesRecoveryAsBoot *bool `json:",omitempty"`
443
444	BoardKernelBinaries                []string `json:",omitempty"`
445	BoardKernelModuleInterfaceVersions []string `json:",omitempty"`
446
447	BoardMoveRecoveryResourcesToVendorBoot *bool `json:",omitempty"`
448
449	PrebuiltHiddenApiDir *string `json:",omitempty"`
450
451	Shipping_api_level *string `json:",omitempty"`
452
453	BuildBrokenPluginValidation         []string `json:",omitempty"`
454	BuildBrokenClangAsFlags             bool     `json:",omitempty"`
455	BuildBrokenClangCFlags              bool     `json:",omitempty"`
456	BuildBrokenClangProperty            bool     `json:",omitempty"`
457	GenruleSandboxing                   *bool    `json:",omitempty"`
458	BuildBrokenEnforceSyspropOwner      bool     `json:",omitempty"`
459	BuildBrokenTrebleSyspropNeverallow  bool     `json:",omitempty"`
460	BuildBrokenVendorPropertyNamespace  bool     `json:",omitempty"`
461	BuildBrokenIncorrectPartitionImages bool     `json:",omitempty"`
462	BuildBrokenInputDirModules          []string `json:",omitempty"`
463	BuildBrokenDontCheckSystemSdk       bool     `json:",omitempty"`
464	BuildBrokenDupSysprop               bool     `json:",omitempty"`
465
466	BuildWarningBadOptionalUsesLibsAllowlist []string `json:",omitempty"`
467
468	BuildDebugfsRestrictionsEnabled bool `json:",omitempty"`
469
470	RequiresInsecureExecmemForSwiftshader bool `json:",omitempty"`
471
472	SelinuxIgnoreNeverallows bool `json:",omitempty"`
473
474	Release_aidl_use_unfrozen *bool `json:",omitempty"`
475
476	SepolicyFreezeTestExtraDirs         []string `json:",omitempty"`
477	SepolicyFreezeTestExtraPrebuiltDirs []string `json:",omitempty"`
478
479	GenerateAidlNdkPlatformBackend bool `json:",omitempty"`
480
481	IgnorePrefer32OnDevice bool `json:",omitempty"`
482
483	SourceRootDirs []string `json:",omitempty"`
484
485	AfdoProfiles []string `json:",omitempty"`
486
487	ProductManufacturer string `json:",omitempty"`
488	ProductBrand        string `json:",omitempty"`
489	ProductDevice       string `json:",omitempty"`
490	ProductModel        string `json:",omitempty"`
491
492	ReleaseVersion          string   `json:",omitempty"`
493	ReleaseAconfigValueSets []string `json:",omitempty"`
494
495	ReleaseAconfigFlagDefaultPermission string `json:",omitempty"`
496
497	ReleaseDefaultModuleBuildFromSource *bool `json:",omitempty"`
498
499	CheckVendorSeappViolations *bool `json:",omitempty"`
500
501	BuildFlags map[string]string `json:",omitempty"`
502
503	BuildFlagTypes map[string]string `json:",omitempty"`
504
505	BuildFromSourceStub *bool `json:",omitempty"`
506
507	BuildIgnoreApexContributionContents *bool `json:",omitempty"`
508
509	HiddenapiExportableStubs *bool `json:",omitempty"`
510
511	ExportRuntimeApis *bool `json:",omitempty"`
512
513	AconfigContainerValidation string `json:",omitempty"`
514
515	ProductLocales []string `json:",omitempty"`
516
517	ProductDefaultWifiChannels []string `json:",omitempty"`
518
519	BoardUseVbmetaDigestInFingerprint *bool `json:",omitempty"`
520
521	OemProperties []string `json:",omitempty"`
522
523	ArtTargetIncludeDebugBuild *bool `json:",omitempty"`
524
525	SystemPropFiles    []string `json:",omitempty"`
526	SystemExtPropFiles []string `json:",omitempty"`
527	ProductPropFiles   []string `json:",omitempty"`
528	OdmPropFiles       []string `json:",omitempty"`
529	VendorPropFiles    []string `json:",omitempty"`
530
531	EnableUffdGc       *string `json:",omitempty"`
532	BoardKernelVersion *string `json:",omitempty"`
533
534	BoardAvbEnable                         *bool    `json:",omitempty"`
535	BoardAvbSystemAddHashtreeFooterArgs    []string `json:",omitempty"`
536	DeviceFrameworkCompatibilityMatrixFile []string `json:",omitempty"`
537	DeviceProductCompatibilityMatrixFile   []string `json:",omitempty"`
538
539	PartitionVarsForSoongMigrationOnlyDoNotUse PartitionVariables
540
541	AdbKeys *string `json:",omitempty"`
542
543	DeviceMatrixFile       []string `json:",omitempty"`
544	ProductManifestFiles   []string `json:",omitempty"`
545	SystemManifestFile     []string `json:",omitempty"`
546	SystemExtManifestFiles []string `json:",omitempty"`
547	DeviceManifestFiles    []string `json:",omitempty"`
548	OdmManifestFiles       []string `json:",omitempty"`
549
550	UseSoongNoticeXML *bool `json:",omitempty"`
551
552	StripByDefault *bool `json:",omitempty"`
553}
554
555type PartitionQualifiedVariablesType struct {
556	BuildingImage               bool   `json:",omitempty"`
557	PrebuiltImage               bool   `json:",omitempty"`
558	BoardErofsCompressor        string `json:",omitempty"`
559	BoardErofsCompressHints     string `json:",omitempty"`
560	BoardErofsPclusterSize      string `json:",omitempty"`
561	BoardExtfsInodeCount        string `json:",omitempty"`
562	BoardExtfsRsvPct            string `json:",omitempty"`
563	BoardF2fsSloadCompressFlags string `json:",omitempty"`
564	BoardFileSystemCompress     string `json:",omitempty"`
565	BoardFileSystemType         string `json:",omitempty"`
566	BoardJournalSize            string `json:",omitempty"`
567	BoardPartitionReservedSize  string `json:",omitempty"`
568	BoardPartitionSize          string `json:",omitempty"`
569	BoardSquashfsBlockSize      string `json:",omitempty"`
570	BoardSquashfsCompressor     string `json:",omitempty"`
571	BoardSquashfsCompressorOpt  string `json:",omitempty"`
572	BoardSquashfsDisable4kAlign string `json:",omitempty"`
573	ProductBaseFsPath           string `json:",omitempty"`
574	ProductHeadroom             string `json:",omitempty"`
575	ProductVerityPartition      string `json:",omitempty"`
576
577	BoardAvbAddHashtreeFooterArgs string `json:",omitempty"`
578	BoardAvbKeyPath               string `json:",omitempty"`
579	BoardAvbAlgorithm             string `json:",omitempty"`
580	BoardAvbRollbackIndex         string `json:",omitempty"`
581	BoardAvbRollbackIndexLocation string `json:",omitempty"`
582}
583
584type BoardSuperPartitionGroupProps struct {
585	GroupSize     string   `json:",omitempty"`
586	PartitionList []string `json:",omitempty"`
587}
588
589type ChainedAvbPartitionProps struct {
590	Partitions            []string `json:",omitempty"`
591	Key                   string   `json:",omitempty"`
592	Algorithm             string   `json:",omitempty"`
593	RollbackIndex         string   `json:",omitempty"`
594	RollbackIndexLocation string   `json:",omitempty"`
595}
596
597type PartitionVariables struct {
598	ProductDirectory            string `json:",omitempty"`
599	PartitionQualifiedVariables map[string]PartitionQualifiedVariablesType
600	TargetUserimagesUseExt2     bool `json:",omitempty"`
601	TargetUserimagesUseExt3     bool `json:",omitempty"`
602	TargetUserimagesUseExt4     bool `json:",omitempty"`
603
604	TargetUserimagesSparseExtDisabled      bool `json:",omitempty"`
605	TargetUserimagesSparseErofsDisabled    bool `json:",omitempty"`
606	TargetUserimagesSparseSquashfsDisabled bool `json:",omitempty"`
607	TargetUserimagesSparseF2fsDisabled     bool `json:",omitempty"`
608
609	BoardErofsCompressor           string `json:",omitempty"`
610	BoardErofsCompressorHints      string `json:",omitempty"`
611	BoardErofsPclusterSize         string `json:",omitempty"`
612	BoardErofsShareDupBlocks       string `json:",omitempty"`
613	BoardErofsUseLegacyCompression string `json:",omitempty"`
614	BoardExt4ShareDupBlocks        string `json:",omitempty"`
615	BoardFlashLogicalBlockSize     string `json:",omitempty"`
616	BoardFlashEraseBlockSize       string `json:",omitempty"`
617	ProductUseDynamicPartitionSize bool   `json:",omitempty"`
618	CopyImagesForTargetFilesZip    bool   `json:",omitempty"`
619
620	VendorSecurityPatch     string `json:",omitempty"`
621	OdmSecurityPatch        string `json:",omitempty"`
622	SystemDlkmSecurityPatch string `json:",omitempty"`
623	VendorDlkmSecurityPatch string `json:",omitempty"`
624	OdmDlkmSecurityPatch    string `json:",omitempty"`
625
626	BuildingSystemOtherImage bool `json:",omitempty"`
627
628	// Boot image stuff
629	BuildingRamdiskImage              bool     `json:",omitempty"`
630	ProductBuildBootImage             bool     `json:",omitempty"`
631	ProductBuildVendorBootImage       string   `json:",omitempty"`
632	ProductBuildInitBootImage         bool     `json:",omitempty"`
633	BoardUsesRecoveryAsBoot           bool     `json:",omitempty"`
634	BoardPrebuiltBootimage            string   `json:",omitempty"`
635	BoardPrebuiltInitBootimage        string   `json:",omitempty"`
636	BoardBootimagePartitionSize       string   `json:",omitempty"`
637	BoardVendorBootimagePartitionSize string   `json:",omitempty"`
638	BoardInitBootimagePartitionSize   string   `json:",omitempty"`
639	BoardBootHeaderVersion            string   `json:",omitempty"`
640	TargetKernelPath                  string   `json:",omitempty"`
641	BoardUsesGenericKernelImage       bool     `json:",omitempty"`
642	BootSecurityPatch                 string   `json:",omitempty"`
643	InitBootSecurityPatch             string   `json:",omitempty"`
644	BoardIncludeDtbInBootimg          bool     `json:",omitempty"`
645	InternalKernelCmdline             []string `json:",omitempty"`
646	InternalBootconfig                []string `json:",omitempty"`
647	InternalBootconfigFile            string   `json:",omitempty"`
648
649	// Super image stuff
650	ProductUseDynamicPartitions       bool                                     `json:",omitempty"`
651	ProductRetrofitDynamicPartitions  bool                                     `json:",omitempty"`
652	ProductBuildSuperPartition        bool                                     `json:",omitempty"`
653	BuildingSuperEmptyImage           bool                                     `json:",omitempty"`
654	BoardSuperPartitionSize           string                                   `json:",omitempty"`
655	BoardSuperPartitionMetadataDevice string                                   `json:",omitempty"`
656	BoardSuperPartitionBlockDevices   []string                                 `json:",omitempty"`
657	BoardSuperPartitionGroups         map[string]BoardSuperPartitionGroupProps `json:",omitempty"`
658	ProductVirtualAbOta               bool                                     `json:",omitempty"`
659	ProductVirtualAbOtaRetrofit       bool                                     `json:",omitempty"`
660	ProductVirtualAbCompression       bool                                     `json:",omitempty"`
661	ProductVirtualAbCompressionMethod string                                   `json:",omitempty"`
662	ProductVirtualAbCompressionFactor string                                   `json:",omitempty"`
663	ProductVirtualAbCowVersion        string                                   `json:",omitempty"`
664	AbOtaUpdater                      bool                                     `json:",omitempty"`
665	AbOtaPartitions                   []string                                 `json:",omitempty"`
666	AbOtaKeys                         []string                                 `json:",omitempty"`
667	AbOtaPostInstallConfig            []string                                 `json:",omitempty"`
668	BoardSuperImageInUpdatePackage    bool                                     `json:",omitempty"`
669
670	// Avb (android verified boot) stuff
671	BoardAvbEnable          bool                                `json:",omitempty"`
672	BoardAvbAlgorithm       string                              `json:",omitempty"`
673	BoardAvbKeyPath         string                              `json:",omitempty"`
674	BoardAvbRollbackIndex   string                              `json:",omitempty"`
675	BuildingVbmetaImage     bool                                `json:",omitempty"`
676	ChainedVbmetaPartitions map[string]ChainedAvbPartitionProps `json:",omitempty"`
677
678	ProductPackages         []string `json:",omitempty"`
679	ProductPackagesDebug    []string `json:",omitempty"`
680	VendorLinkerConfigSrcs  []string `json:",omitempty"`
681	ProductLinkerConfigSrcs []string `json:",omitempty"`
682
683	BoardInfoFiles      []string `json:",omitempty"`
684	BootLoaderBoardName string   `json:",omitempty"`
685
686	ProductCopyFiles []string `json:",omitempty"`
687
688	BuildingSystemDlkmImage   bool     `json:",omitempty"`
689	SystemKernelModules       []string `json:",omitempty"`
690	SystemKernelBlocklistFile string   `json:",omitempty"`
691	SystemKernelLoadModules   []string `json:",omitempty"`
692	BuildingVendorDlkmImage   bool     `json:",omitempty"`
693	VendorKernelModules       []string `json:",omitempty"`
694	VendorKernelBlocklistFile string   `json:",omitempty"`
695	BuildingOdmDlkmImage      bool     `json:",omitempty"`
696	OdmKernelModules          []string `json:",omitempty"`
697	OdmKernelBlocklistFile    string   `json:",omitempty"`
698
699	VendorRamdiskKernelModules       []string `json:",omitempty"`
700	VendorRamdiskKernelBlocklistFile string   `json:",omitempty"`
701	VendorRamdiskKernelLoadModules   []string `json:",omitempty"`
702	VendorRamdiskKernelOptionsFile   string   `json:",omitempty"`
703
704	ProductFsverityGenerateMetadata bool `json:",omitempty"`
705
706	TargetScreenDensity string `json:",omitempty"`
707
708	PrivateRecoveryUiProperties map[string]string `json:",omitempty"`
709
710	PrebuiltBootloader string `json:",omitempty"`
711
712	ProductFsCasefold    string `json:",omitempty"`
713	ProductQuotaProjid   string `json:",omitempty"`
714	ProductFsCompression string `json:",omitempty"`
715
716	ReleaseToolsExtensionDir string `json:",omitempty"`
717
718	BoardPartialOtaUpdatePartitionsList []string `json:",omitempty"`
719	BoardFlashBlockSize                 string   `json:",omitempty"`
720	BootloaderInUpdatePackage           bool     `json:",omitempty"`
721
722	BoardFastbootInfoFile string `json:",omitempty"`
723}
724
725func boolPtr(v bool) *bool {
726	return &v
727}
728
729func intPtr(v int) *int {
730	return &v
731}
732
733func stringPtr(v string) *string {
734	return &v
735}
736
737func (v *ProductVariables) SetDefaultConfig() {
738	*v = ProductVariables{
739		BuildNumberFile: stringPtr("build_number.txt"),
740
741		Platform_version_name:                  stringPtr("S"),
742		Platform_base_sdk_extension_version:    intPtr(30),
743		Platform_sdk_version:                   intPtr(30),
744		Platform_sdk_codename:                  stringPtr("S"),
745		Platform_sdk_final:                     boolPtr(false),
746		Platform_version_active_codenames:      []string{"S"},
747		Platform_version_all_preview_codenames: []string{"S"},
748
749		HostArch:                    stringPtr("x86_64"),
750		HostSecondaryArch:           stringPtr("x86"),
751		DeviceName:                  stringPtr("generic_arm64"),
752		DeviceProduct:               stringPtr("aosp_arm-eng"),
753		DeviceArch:                  stringPtr("arm64"),
754		DeviceArchVariant:           stringPtr("armv8-a"),
755		DeviceCpuVariant:            stringPtr("generic"),
756		DeviceAbi:                   []string{"arm64-v8a"},
757		DeviceSecondaryArch:         stringPtr("arm"),
758		DeviceSecondaryArchVariant:  stringPtr("armv8-a"),
759		DeviceSecondaryCpuVariant:   stringPtr("generic"),
760		DeviceSecondaryAbi:          []string{"armeabi-v7a", "armeabi"},
761		DeviceMaxPageSizeSupported:  stringPtr("4096"),
762		DeviceNoBionicPageSizeMacro: boolPtr(false),
763
764		AAPTConfig:          []string{"normal", "large", "xlarge", "hdpi", "xhdpi", "xxhdpi"},
765		AAPTPreferredConfig: stringPtr("xhdpi"),
766		AAPTCharacteristics: stringPtr("nosdcard"),
767		AAPTPrebuiltDPI:     []string{"xhdpi", "xxhdpi"},
768
769		Malloc_low_memory:            boolPtr(false),
770		Malloc_zero_contents:         boolPtr(true),
771		Malloc_pattern_fill_contents: boolPtr(false),
772		Safestack:                    boolPtr(false),
773		Build_from_text_stub:         boolPtr(false),
774
775		BootJars:     ConfiguredJarList{apexes: []string{}, jars: []string{}},
776		ApexBootJars: ConfiguredJarList{apexes: []string{}, jars: []string{}},
777	}
778
779	if runtime.GOOS == "linux" {
780		v.CrossHost = stringPtr("windows")
781		v.CrossHostArch = stringPtr("x86")
782		v.CrossHostSecondaryArch = stringPtr("x86_64")
783	}
784}
785
786func (this *ProductVariables) GetBuildFlagBool(flag string) bool {
787	val, ok := this.BuildFlags[flag]
788	if !ok {
789		return false
790	}
791	return val == "true"
792}
793
794func VariableMutator(mctx BottomUpMutatorContext) {
795	var module Module
796	var ok bool
797	if module, ok = mctx.Module().(Module); !ok {
798		return
799	}
800
801	// TODO: depend on config variable, create variants, propagate variants up tree
802	a := module.base()
803
804	if a.variableProperties == nil {
805		return
806	}
807
808	variableValues := reflect.ValueOf(a.variableProperties).Elem().FieldByName("Product_variables")
809
810	productVariables := reflect.ValueOf(mctx.Config().productVariables)
811
812	for i := 0; i < variableValues.NumField(); i++ {
813		variableValue := variableValues.Field(i)
814		name := variableValues.Type().Field(i).Name
815		property := "product_variables." + proptools.PropertyNameForField(name)
816
817		// Check that the variable was set for the product
818		val := productVariables.FieldByName(name)
819		if !val.IsValid() || val.Kind() != reflect.Ptr || val.IsNil() {
820			continue
821		}
822
823		val = val.Elem()
824
825		// For bools, check that the value is true
826		if val.Kind() == reflect.Bool && val.Bool() == false {
827			continue
828		}
829
830		// Check if any properties were set for the module
831		if variableValue.IsZero() {
832			continue
833		}
834		a.setVariableProperties(mctx, property, variableValue, val.Interface())
835	}
836}
837
838func (m *ModuleBase) setVariableProperties(ctx BottomUpMutatorContext,
839	prefix string, productVariablePropertyValue reflect.Value, variableValue interface{}) {
840
841	printfIntoProperties(ctx, prefix, productVariablePropertyValue, variableValue)
842
843	err := proptools.AppendMatchingProperties(m.GetProperties(),
844		productVariablePropertyValue.Addr().Interface(), nil)
845	if err != nil {
846		if propertyErr, ok := err.(*proptools.ExtendPropertyError); ok {
847			ctx.PropertyErrorf(propertyErr.Property, "%s", propertyErr.Err.Error())
848		} else {
849			panic(err)
850		}
851	}
852}
853
854func printfIntoPropertiesError(ctx BottomUpMutatorContext, prefix string,
855	productVariablePropertyValue reflect.Value, i int, err error) {
856
857	field := productVariablePropertyValue.Type().Field(i).Name
858	property := prefix + "." + proptools.PropertyNameForField(field)
859	ctx.PropertyErrorf(property, "%s", err)
860}
861
862func printfIntoProperties(ctx BottomUpMutatorContext, prefix string,
863	productVariablePropertyValue reflect.Value, variableValue interface{}) {
864
865	for i := 0; i < productVariablePropertyValue.NumField(); i++ {
866		propertyValue := productVariablePropertyValue.Field(i)
867		kind := propertyValue.Kind()
868		if kind == reflect.Ptr {
869			if propertyValue.IsNil() {
870				continue
871			}
872			propertyValue = propertyValue.Elem()
873		}
874		switch propertyValue.Kind() {
875		case reflect.String:
876			err := printfIntoProperty(propertyValue, variableValue)
877			if err != nil {
878				printfIntoPropertiesError(ctx, prefix, productVariablePropertyValue, i, err)
879			}
880		case reflect.Slice:
881			for j := 0; j < propertyValue.Len(); j++ {
882				err := printfIntoProperty(propertyValue.Index(j), variableValue)
883				if err != nil {
884					printfIntoPropertiesError(ctx, prefix, productVariablePropertyValue, i, err)
885				}
886			}
887		case reflect.Bool:
888			// Nothing
889		case reflect.Struct:
890			printfIntoProperties(ctx, prefix, propertyValue, variableValue)
891		default:
892			panic(fmt.Errorf("unsupported field kind %q", propertyValue.Kind()))
893		}
894	}
895}
896
897func printfIntoProperty(propertyValue reflect.Value, variableValue interface{}) error {
898	s := propertyValue.String()
899
900	count := strings.Count(s, "%")
901	if count == 0 {
902		return nil
903	}
904
905	if count > 1 {
906		return fmt.Errorf("product variable properties only support a single '%%'")
907	}
908
909	if strings.Contains(s, "%d") {
910		switch v := variableValue.(type) {
911		case int:
912			// Nothing
913		case bool:
914			if v {
915				variableValue = 1
916			} else {
917				variableValue = 0
918			}
919		default:
920			return fmt.Errorf("unsupported type %T for %%d", variableValue)
921		}
922	} else if strings.Contains(s, "%s") {
923		switch variableValue.(type) {
924		case string:
925			// Nothing
926		default:
927			return fmt.Errorf("unsupported type %T for %%s", variableValue)
928		}
929	} else {
930		return fmt.Errorf("unsupported %% in product variable property")
931	}
932
933	propertyValue.Set(reflect.ValueOf(fmt.Sprintf(s, variableValue)))
934
935	return nil
936}
937
938var variablePropTypeMap OncePer
939
940// sliceToTypeArray takes a slice of property structs and returns a reflection created array containing the
941// reflect.Types of each property struct.  The result can be used as a key in a map.
942func sliceToTypeArray(s []interface{}) interface{} {
943	// Create an array using reflection whose length is the length of the input slice
944	ret := reflect.New(reflect.ArrayOf(len(s), reflect.TypeOf(reflect.TypeOf(0)))).Elem()
945	for i, e := range s {
946		ret.Index(i).Set(reflect.ValueOf(reflect.TypeOf(e)))
947	}
948	return ret.Interface()
949}
950
951func initProductVariableModule(m Module) {
952	base := m.base()
953
954	// Allow tests to override the default product variables
955	if base.variableProperties == nil {
956		base.variableProperties = defaultProductVariables
957	}
958	// Filter the product variables properties to the ones that exist on this module
959	base.variableProperties = createVariableProperties(m.GetProperties(), base.variableProperties)
960	if base.variableProperties != nil {
961		m.AddProperties(base.variableProperties)
962	}
963}
964
965// createVariableProperties takes the list of property structs for a module and returns a property struct that
966// contains the product variable properties that exist in the property structs, or nil if there are none.  It
967// caches the result.
968func createVariableProperties(moduleTypeProps []interface{}, productVariables interface{}) interface{} {
969	// Convert the moduleTypeProps to an array of reflect.Types that can be used as a key in the OncePer.
970	key := sliceToTypeArray(moduleTypeProps)
971
972	// Use the variablePropTypeMap OncePer to cache the result for each set of property struct types.
973	typ, _ := variablePropTypeMap.Once(NewCustomOnceKey(key), func() interface{} {
974		// Compute the filtered property struct type.
975		return createVariablePropertiesType(moduleTypeProps, productVariables)
976	}).(reflect.Type)
977
978	if typ == nil {
979		return nil
980	}
981
982	// Create a new pointer to a filtered property struct.
983	return reflect.New(typ).Interface()
984}
985
986// createVariablePropertiesType creates a new type that contains only the product variable properties that exist in
987// a list of property structs.
988func createVariablePropertiesType(moduleTypeProps []interface{}, productVariables interface{}) reflect.Type {
989	typ, _ := proptools.FilterPropertyStruct(reflect.TypeOf(productVariables),
990		func(field reflect.StructField, prefix string) (bool, reflect.StructField) {
991			// Filter function, returns true if the field should be in the resulting struct
992			if prefix == "" {
993				// Keep the top level Product_variables field
994				return true, field
995			}
996			_, rest := splitPrefix(prefix)
997			if rest == "" {
998				// Keep the 2nd level field (i.e. Product_variables.Eng)
999				return true, field
1000			}
1001
1002			// Strip off the first 2 levels of the prefix
1003			_, prefix = splitPrefix(rest)
1004
1005			for _, p := range moduleTypeProps {
1006				if fieldExistsByNameRecursive(reflect.TypeOf(p).Elem(), prefix, field.Name) {
1007					// Keep any fields that exist in one of the property structs
1008					return true, field
1009				}
1010			}
1011
1012			return false, field
1013		})
1014	return typ
1015}
1016
1017func splitPrefix(prefix string) (first, rest string) {
1018	index := strings.IndexByte(prefix, '.')
1019	if index == -1 {
1020		return prefix, ""
1021	}
1022	return prefix[:index], prefix[index+1:]
1023}
1024
1025func fieldExistsByNameRecursive(t reflect.Type, prefix, name string) bool {
1026	if t.Kind() != reflect.Struct {
1027		panic(fmt.Errorf("fieldExistsByNameRecursive can only be called on a reflect.Struct"))
1028	}
1029
1030	if prefix != "" {
1031		split := strings.SplitN(prefix, ".", 2)
1032		firstPrefix := split[0]
1033		rest := ""
1034		if len(split) > 1 {
1035			rest = split[1]
1036		}
1037		f, exists := t.FieldByName(firstPrefix)
1038		if !exists {
1039			return false
1040		}
1041		ft := f.Type
1042		if ft.Kind() == reflect.Ptr {
1043			ft = ft.Elem()
1044		}
1045		if ft.Kind() != reflect.Struct {
1046			panic(fmt.Errorf("field %q in %q is not a struct", firstPrefix, t))
1047		}
1048		return fieldExistsByNameRecursive(ft, rest, name)
1049	} else {
1050		_, exists := t.FieldByName(name)
1051		return exists
1052	}
1053}
1054