variable.go 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216
  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. package android
  15. import (
  16. "fmt"
  17. "reflect"
  18. "runtime"
  19. "strings"
  20. "android/soong/android/soongconfig"
  21. "android/soong/bazel"
  22. "github.com/google/blueprint/proptools"
  23. )
  24. func init() {
  25. registerVariableBuildComponents(InitRegistrationContext)
  26. }
  27. func registerVariableBuildComponents(ctx RegistrationContext) {
  28. ctx.PreDepsMutators(func(ctx RegisterMutatorsContext) {
  29. ctx.BottomUp("variable", VariableMutator).Parallel()
  30. })
  31. }
  32. var PrepareForTestWithVariables = FixtureRegisterWithContext(registerVariableBuildComponents)
  33. type variableProperties struct {
  34. Product_variables struct {
  35. Platform_sdk_version struct {
  36. Asflags []string
  37. Cflags []string
  38. Cmd *string
  39. }
  40. Platform_sdk_version_or_codename struct {
  41. Java_resource_dirs []string
  42. }
  43. Platform_sdk_extension_version struct {
  44. Cmd *string
  45. }
  46. Platform_version_name struct {
  47. Base_dir *string
  48. }
  49. // unbundled_build is a catch-all property to annotate modules that don't build in one or
  50. // more unbundled branches, usually due to dependencies missing from the manifest.
  51. Unbundled_build struct {
  52. Enabled *bool `android:"arch_variant"`
  53. } `android:"arch_variant"`
  54. // similar to `Unbundled_build`, but `Always_use_prebuilt_sdks` means that it uses prebuilt
  55. // sdk specifically.
  56. Always_use_prebuilt_sdks struct {
  57. Enabled *bool `android:"arch_variant"`
  58. } `android:"arch_variant"`
  59. Malloc_not_svelte struct {
  60. Cflags []string `android:"arch_variant"`
  61. Shared_libs []string `android:"arch_variant"`
  62. Whole_static_libs []string `android:"arch_variant"`
  63. Exclude_static_libs []string `android:"arch_variant"`
  64. Srcs []string `android:"arch_variant"`
  65. Header_libs []string `android:"arch_variant"`
  66. } `android:"arch_variant"`
  67. Malloc_zero_contents struct {
  68. Cflags []string `android:"arch_variant"`
  69. } `android:"arch_variant"`
  70. Malloc_pattern_fill_contents struct {
  71. Cflags []string `android:"arch_variant"`
  72. } `android:"arch_variant"`
  73. Safestack struct {
  74. Cflags []string `android:"arch_variant"`
  75. } `android:"arch_variant"`
  76. Binder32bit struct {
  77. Cflags []string
  78. }
  79. Override_rs_driver struct {
  80. Cflags []string
  81. }
  82. // treble_linker_namespaces is true when the system/vendor linker namespace separation is
  83. // enabled.
  84. Treble_linker_namespaces struct {
  85. Cflags []string
  86. }
  87. // enforce_vintf_manifest is true when a device is required to have a vintf manifest.
  88. Enforce_vintf_manifest struct {
  89. Cflags []string
  90. }
  91. Build_from_text_stub struct {
  92. Static_libs []string
  93. Exclude_static_libs []string
  94. }
  95. // debuggable is true for eng and userdebug builds, and can be used to turn on additional
  96. // debugging features that don't significantly impact runtime behavior. userdebug builds
  97. // are used for dogfooding and performance testing, and should be as similar to user builds
  98. // as possible.
  99. Debuggable struct {
  100. Cflags []string
  101. Cppflags []string
  102. Init_rc []string
  103. Required []string
  104. Host_required []string
  105. Target_required []string
  106. Strip struct {
  107. All *bool
  108. Keep_symbols *bool
  109. Keep_symbols_and_debug_frame *bool
  110. }
  111. Static_libs []string
  112. Whole_static_libs []string
  113. Shared_libs []string
  114. Cmdline []string
  115. Srcs []string
  116. Exclude_srcs []string
  117. }
  118. // eng is true for -eng builds, and can be used to turn on additional heavyweight debugging
  119. // features.
  120. Eng struct {
  121. Cflags []string
  122. Cppflags []string
  123. Lto struct {
  124. Never *bool
  125. }
  126. Sanitize struct {
  127. Address *bool
  128. }
  129. Optimize struct {
  130. Enabled *bool
  131. }
  132. }
  133. Pdk struct {
  134. Enabled *bool `android:"arch_variant"`
  135. } `android:"arch_variant"`
  136. Uml struct {
  137. Cppflags []string
  138. }
  139. Arc struct {
  140. Cflags []string `android:"arch_variant"`
  141. Exclude_srcs []string `android:"arch_variant"`
  142. Header_libs []string `android:"arch_variant"`
  143. Include_dirs []string `android:"arch_variant"`
  144. Shared_libs []string `android:"arch_variant"`
  145. Static_libs []string `android:"arch_variant"`
  146. Srcs []string `android:"arch_variant"`
  147. Whole_static_libs []string `android:"arch_variant"`
  148. } `android:"arch_variant"`
  149. Flatten_apex struct {
  150. Enabled *bool
  151. }
  152. Native_coverage struct {
  153. Src *string `android:"arch_variant"`
  154. Srcs []string `android:"arch_variant"`
  155. Exclude_srcs []string `android:"arch_variant"`
  156. } `android:"arch_variant"`
  157. } `android:"arch_variant"`
  158. }
  159. var defaultProductVariables interface{} = variableProperties{}
  160. type productVariables struct {
  161. // Suffix to add to generated Makefiles
  162. Make_suffix *string `json:",omitempty"`
  163. BuildId *string `json:",omitempty"`
  164. BuildNumberFile *string `json:",omitempty"`
  165. Platform_version_name *string `json:",omitempty"`
  166. Platform_sdk_version *int `json:",omitempty"`
  167. Platform_sdk_codename *string `json:",omitempty"`
  168. Platform_sdk_version_or_codename *string `json:",omitempty"`
  169. Platform_sdk_final *bool `json:",omitempty"`
  170. Platform_sdk_extension_version *int `json:",omitempty"`
  171. Platform_base_sdk_extension_version *int `json:",omitempty"`
  172. Platform_version_active_codenames []string `json:",omitempty"`
  173. Platform_version_all_preview_codenames []string `json:",omitempty"`
  174. Platform_vndk_version *string `json:",omitempty"`
  175. Platform_systemsdk_versions []string `json:",omitempty"`
  176. Platform_security_patch *string `json:",omitempty"`
  177. Platform_preview_sdk_version *string `json:",omitempty"`
  178. Platform_min_supported_target_sdk_version *string `json:",omitempty"`
  179. Platform_base_os *string `json:",omitempty"`
  180. Platform_version_last_stable *string `json:",omitempty"`
  181. Platform_version_known_codenames *string `json:",omitempty"`
  182. DeviceName *string `json:",omitempty"`
  183. DeviceProduct *string `json:",omitempty"`
  184. DeviceArch *string `json:",omitempty"`
  185. DeviceArchVariant *string `json:",omitempty"`
  186. DeviceCpuVariant *string `json:",omitempty"`
  187. DeviceAbi []string `json:",omitempty"`
  188. DeviceVndkVersion *string `json:",omitempty"`
  189. DeviceCurrentApiLevelForVendorModules *string `json:",omitempty"`
  190. DeviceSystemSdkVersions []string `json:",omitempty"`
  191. DeviceMaxPageSizeSupported *string `json:",omitempty"`
  192. RecoverySnapshotVersion *string `json:",omitempty"`
  193. DeviceSecondaryArch *string `json:",omitempty"`
  194. DeviceSecondaryArchVariant *string `json:",omitempty"`
  195. DeviceSecondaryCpuVariant *string `json:",omitempty"`
  196. DeviceSecondaryAbi []string `json:",omitempty"`
  197. NativeBridgeArch *string `json:",omitempty"`
  198. NativeBridgeArchVariant *string `json:",omitempty"`
  199. NativeBridgeCpuVariant *string `json:",omitempty"`
  200. NativeBridgeAbi []string `json:",omitempty"`
  201. NativeBridgeRelativePath *string `json:",omitempty"`
  202. NativeBridgeSecondaryArch *string `json:",omitempty"`
  203. NativeBridgeSecondaryArchVariant *string `json:",omitempty"`
  204. NativeBridgeSecondaryCpuVariant *string `json:",omitempty"`
  205. NativeBridgeSecondaryAbi []string `json:",omitempty"`
  206. NativeBridgeSecondaryRelativePath *string `json:",omitempty"`
  207. HostArch *string `json:",omitempty"`
  208. HostSecondaryArch *string `json:",omitempty"`
  209. HostMusl *bool `json:",omitempty"`
  210. CrossHost *string `json:",omitempty"`
  211. CrossHostArch *string `json:",omitempty"`
  212. CrossHostSecondaryArch *string `json:",omitempty"`
  213. DeviceResourceOverlays []string `json:",omitempty"`
  214. ProductResourceOverlays []string `json:",omitempty"`
  215. EnforceRROTargets []string `json:",omitempty"`
  216. EnforceRROExcludedOverlays []string `json:",omitempty"`
  217. AAPTCharacteristics *string `json:",omitempty"`
  218. AAPTConfig []string `json:",omitempty"`
  219. AAPTPreferredConfig *string `json:",omitempty"`
  220. AAPTPrebuiltDPI []string `json:",omitempty"`
  221. DefaultAppCertificate *string `json:",omitempty"`
  222. MainlineSepolicyDevCertificates *string `json:",omitempty"`
  223. AppsDefaultVersionName *string `json:",omitempty"`
  224. Allow_missing_dependencies *bool `json:",omitempty"`
  225. Unbundled_build *bool `json:",omitempty"`
  226. Unbundled_build_apps []string `json:",omitempty"`
  227. Unbundled_build_image *bool `json:",omitempty"`
  228. Always_use_prebuilt_sdks *bool `json:",omitempty"`
  229. Skip_boot_jars_check *bool `json:",omitempty"`
  230. Malloc_not_svelte *bool `json:",omitempty"`
  231. Malloc_zero_contents *bool `json:",omitempty"`
  232. Malloc_pattern_fill_contents *bool `json:",omitempty"`
  233. Safestack *bool `json:",omitempty"`
  234. HostStaticBinaries *bool `json:",omitempty"`
  235. Binder32bit *bool `json:",omitempty"`
  236. UseGoma *bool `json:",omitempty"`
  237. UseRBE *bool `json:",omitempty"`
  238. UseRBEJAVAC *bool `json:",omitempty"`
  239. UseRBER8 *bool `json:",omitempty"`
  240. UseRBED8 *bool `json:",omitempty"`
  241. Debuggable *bool `json:",omitempty"`
  242. Eng *bool `json:",omitempty"`
  243. Treble_linker_namespaces *bool `json:",omitempty"`
  244. Enforce_vintf_manifest *bool `json:",omitempty"`
  245. Uml *bool `json:",omitempty"`
  246. Arc *bool `json:",omitempty"`
  247. MinimizeJavaDebugInfo *bool `json:",omitempty"`
  248. Build_from_text_stub *bool `json:",omitempty"`
  249. Check_elf_files *bool `json:",omitempty"`
  250. UncompressPrivAppDex *bool `json:",omitempty"`
  251. ModulesLoadedByPrivilegedModules []string `json:",omitempty"`
  252. BootJars ConfiguredJarList `json:",omitempty"`
  253. ApexBootJars ConfiguredJarList `json:",omitempty"`
  254. IntegerOverflowExcludePaths []string `json:",omitempty"`
  255. EnableCFI *bool `json:",omitempty"`
  256. CFIExcludePaths []string `json:",omitempty"`
  257. CFIIncludePaths []string `json:",omitempty"`
  258. DisableScudo *bool `json:",omitempty"`
  259. MemtagHeapExcludePaths []string `json:",omitempty"`
  260. MemtagHeapAsyncIncludePaths []string `json:",omitempty"`
  261. MemtagHeapSyncIncludePaths []string `json:",omitempty"`
  262. HWASanIncludePaths []string `json:",omitempty"`
  263. VendorPath *string `json:",omitempty"`
  264. OdmPath *string `json:",omitempty"`
  265. ProductPath *string `json:",omitempty"`
  266. SystemExtPath *string `json:",omitempty"`
  267. ClangTidy *bool `json:",omitempty"`
  268. TidyChecks *string `json:",omitempty"`
  269. JavaCoveragePaths []string `json:",omitempty"`
  270. JavaCoverageExcludePaths []string `json:",omitempty"`
  271. GcovCoverage *bool `json:",omitempty"`
  272. ClangCoverage *bool `json:",omitempty"`
  273. NativeCoveragePaths []string `json:",omitempty"`
  274. NativeCoverageExcludePaths []string `json:",omitempty"`
  275. ClangCoverageContinuousMode *bool `json:",omitempty"`
  276. // Set by NewConfig
  277. Native_coverage *bool `json:",omitempty"`
  278. SanitizeHost []string `json:",omitempty"`
  279. SanitizeDevice []string `json:",omitempty"`
  280. SanitizeDeviceDiag []string `json:",omitempty"`
  281. SanitizeDeviceArch []string `json:",omitempty"`
  282. ArtUseReadBarrier *bool `json:",omitempty"`
  283. BtConfigIncludeDir *string `json:",omitempty"`
  284. Override_rs_driver *string `json:",omitempty"`
  285. DeviceKernelHeaders []string `json:",omitempty"`
  286. ExtraVndkVersions []string `json:",omitempty"`
  287. NamespacesToExport []string `json:",omitempty"`
  288. PgoAdditionalProfileDirs []string `json:",omitempty"`
  289. VndkUseCoreVariant *bool `json:",omitempty"`
  290. VndkSnapshotBuildArtifacts *bool `json:",omitempty"`
  291. DirectedVendorSnapshot bool `json:",omitempty"`
  292. VendorSnapshotModules map[string]bool `json:",omitempty"`
  293. DirectedRecoverySnapshot bool `json:",omitempty"`
  294. RecoverySnapshotModules map[string]bool `json:",omitempty"`
  295. VendorSnapshotDirsIncluded []string `json:",omitempty"`
  296. VendorSnapshotDirsExcluded []string `json:",omitempty"`
  297. RecoverySnapshotDirsExcluded []string `json:",omitempty"`
  298. RecoverySnapshotDirsIncluded []string `json:",omitempty"`
  299. HostFakeSnapshotEnabled bool `json:",omitempty"`
  300. MultitreeUpdateMeta bool `json:",omitempty"`
  301. BoardVendorSepolicyDirs []string `json:",omitempty"`
  302. BoardOdmSepolicyDirs []string `json:",omitempty"`
  303. BoardReqdMaskPolicy []string `json:",omitempty"`
  304. BoardPlatVendorPolicy []string `json:",omitempty"`
  305. BoardSystemExtPublicPrebuiltDirs []string `json:",omitempty"`
  306. BoardSystemExtPrivatePrebuiltDirs []string `json:",omitempty"`
  307. BoardProductPublicPrebuiltDirs []string `json:",omitempty"`
  308. BoardProductPrivatePrebuiltDirs []string `json:",omitempty"`
  309. SystemExtPublicSepolicyDirs []string `json:",omitempty"`
  310. SystemExtPrivateSepolicyDirs []string `json:",omitempty"`
  311. BoardSepolicyM4Defs []string `json:",omitempty"`
  312. BoardSepolicyVers *string `json:",omitempty"`
  313. PlatformSepolicyVersion *string `json:",omitempty"`
  314. TotSepolicyVersion *string `json:",omitempty"`
  315. SystemExtSepolicyPrebuiltApiDir *string `json:",omitempty"`
  316. ProductSepolicyPrebuiltApiDir *string `json:",omitempty"`
  317. PlatformSepolicyCompatVersions []string `json:",omitempty"`
  318. VendorVars map[string]map[string]string `json:",omitempty"`
  319. Ndk_abis *bool `json:",omitempty"`
  320. TrimmedApex *bool `json:",omitempty"`
  321. Flatten_apex *bool `json:",omitempty"`
  322. ForceApexSymlinkOptimization *bool `json:",omitempty"`
  323. CompressedApex *bool `json:",omitempty"`
  324. Aml_abis *bool `json:",omitempty"`
  325. DexpreoptGlobalConfig *string `json:",omitempty"`
  326. WithDexpreopt bool `json:",omitempty"`
  327. ManifestPackageNameOverrides []string `json:",omitempty"`
  328. CertificateOverrides []string `json:",omitempty"`
  329. PackageNameOverrides []string `json:",omitempty"`
  330. ApexGlobalMinSdkVersionOverride *string `json:",omitempty"`
  331. EnforceSystemCertificate *bool `json:",omitempty"`
  332. EnforceSystemCertificateAllowList []string `json:",omitempty"`
  333. ProductHiddenAPIStubs []string `json:",omitempty"`
  334. ProductHiddenAPIStubsSystem []string `json:",omitempty"`
  335. ProductHiddenAPIStubsTest []string `json:",omitempty"`
  336. ProductPublicSepolicyDirs []string `json:",omitempty"`
  337. ProductPrivateSepolicyDirs []string `json:",omitempty"`
  338. ProductVndkVersion *string `json:",omitempty"`
  339. TargetFSConfigGen []string `json:",omitempty"`
  340. EnforceProductPartitionInterface *bool `json:",omitempty"`
  341. EnforceInterPartitionJavaSdkLibrary *bool `json:",omitempty"`
  342. InterPartitionJavaLibraryAllowList []string `json:",omitempty"`
  343. BoardUsesRecoveryAsBoot *bool `json:",omitempty"`
  344. BoardKernelBinaries []string `json:",omitempty"`
  345. BoardKernelModuleInterfaceVersions []string `json:",omitempty"`
  346. BoardMoveRecoveryResourcesToVendorBoot *bool `json:",omitempty"`
  347. PrebuiltHiddenApiDir *string `json:",omitempty"`
  348. ShippingApiLevel *string `json:",omitempty"`
  349. BuildBrokenPluginValidation []string `json:",omitempty"`
  350. BuildBrokenClangAsFlags bool `json:",omitempty"`
  351. BuildBrokenClangCFlags bool `json:",omitempty"`
  352. BuildBrokenClangProperty bool `json:",omitempty"`
  353. GenruleSandboxing *bool `json:",omitempty"`
  354. BuildBrokenEnforceSyspropOwner bool `json:",omitempty"`
  355. BuildBrokenTrebleSyspropNeverallow bool `json:",omitempty"`
  356. BuildBrokenUsesSoongPython2Modules bool `json:",omitempty"`
  357. BuildBrokenVendorPropertyNamespace bool `json:",omitempty"`
  358. BuildBrokenInputDirModules []string `json:",omitempty"`
  359. BuildWarningBadOptionalUsesLibsAllowlist []string `json:",omitempty"`
  360. BuildDebugfsRestrictionsEnabled bool `json:",omitempty"`
  361. RequiresInsecureExecmemForSwiftshader bool `json:",omitempty"`
  362. SelinuxIgnoreNeverallows bool `json:",omitempty"`
  363. SepolicyFreezeTestExtraDirs []string `json:",omitempty"`
  364. SepolicyFreezeTestExtraPrebuiltDirs []string `json:",omitempty"`
  365. GenerateAidlNdkPlatformBackend bool `json:",omitempty"`
  366. IgnorePrefer32OnDevice bool `json:",omitempty"`
  367. IncludeTags []string `json:",omitempty"`
  368. SourceRootDirs []string `json:",omitempty"`
  369. AfdoProfiles []string `json:",omitempty"`
  370. ProductManufacturer string `json:",omitempty"`
  371. ProductBrand string `json:",omitempty"`
  372. BuildVersionTags []string `json:",omitempty"`
  373. ReleaseVersion string `json:",omitempty"`
  374. ReleaseAconfigValueSets []string `json:",omitempty"`
  375. }
  376. func boolPtr(v bool) *bool {
  377. return &v
  378. }
  379. func intPtr(v int) *int {
  380. return &v
  381. }
  382. func stringPtr(v string) *string {
  383. return &v
  384. }
  385. func (v *productVariables) SetDefaultConfig() {
  386. *v = productVariables{
  387. BuildNumberFile: stringPtr("build_number.txt"),
  388. Platform_version_name: stringPtr("S"),
  389. Platform_base_sdk_extension_version: intPtr(30),
  390. Platform_sdk_version: intPtr(30),
  391. Platform_sdk_codename: stringPtr("S"),
  392. Platform_sdk_final: boolPtr(false),
  393. Platform_version_active_codenames: []string{"S"},
  394. Platform_version_all_preview_codenames: []string{"S"},
  395. Platform_vndk_version: stringPtr("S"),
  396. HostArch: stringPtr("x86_64"),
  397. HostSecondaryArch: stringPtr("x86"),
  398. DeviceName: stringPtr("generic_arm64"),
  399. DeviceProduct: stringPtr("aosp_arm-eng"),
  400. DeviceArch: stringPtr("arm64"),
  401. DeviceArchVariant: stringPtr("armv8-a"),
  402. DeviceCpuVariant: stringPtr("generic"),
  403. DeviceAbi: []string{"arm64-v8a"},
  404. DeviceSecondaryArch: stringPtr("arm"),
  405. DeviceSecondaryArchVariant: stringPtr("armv8-a"),
  406. DeviceSecondaryCpuVariant: stringPtr("generic"),
  407. DeviceSecondaryAbi: []string{"armeabi-v7a", "armeabi"},
  408. DeviceMaxPageSizeSupported: stringPtr("4096"),
  409. AAPTConfig: []string{"normal", "large", "xlarge", "hdpi", "xhdpi", "xxhdpi"},
  410. AAPTPreferredConfig: stringPtr("xhdpi"),
  411. AAPTCharacteristics: stringPtr("nosdcard"),
  412. AAPTPrebuiltDPI: []string{"xhdpi", "xxhdpi"},
  413. Malloc_not_svelte: boolPtr(true),
  414. Malloc_zero_contents: boolPtr(true),
  415. Malloc_pattern_fill_contents: boolPtr(false),
  416. Safestack: boolPtr(false),
  417. TrimmedApex: boolPtr(false),
  418. Build_from_text_stub: boolPtr(false),
  419. BootJars: ConfiguredJarList{apexes: []string{}, jars: []string{}},
  420. ApexBootJars: ConfiguredJarList{apexes: []string{}, jars: []string{}},
  421. }
  422. if runtime.GOOS == "linux" {
  423. v.CrossHost = stringPtr("windows")
  424. v.CrossHostArch = stringPtr("x86")
  425. v.CrossHostSecondaryArch = stringPtr("x86_64")
  426. }
  427. }
  428. // ProductConfigContext requires the access to the Module to get product config properties.
  429. type ProductConfigContext interface {
  430. Module() Module
  431. }
  432. // ProductConfigOrSoongConfigProperty represents either a soong config variable + its value
  433. // or a product config variable. You can get both a ConfigurationAxis and a SelectKey from it
  434. // for use in bazel attributes. ProductVariableProperties() will return a map from properties ->
  435. // this interface -> property structs for use in bp2build converters
  436. type ProductConfigOrSoongConfigProperty interface {
  437. // Name of the product variable or soong config variable
  438. Name() string
  439. // AlwaysEmit returns true for soong config variables but false for product variables. This
  440. // is intended to indicate if we need to always emit empty lists in the select statements.
  441. AlwaysEmit() bool
  442. // ConfigurationAxis returns the bazel.ConfigurationAxis that represents this variable. The
  443. // configuration axis will change depending on the variable and whether it's arch/os variant
  444. // as well.
  445. ConfigurationAxis() bazel.ConfigurationAxis
  446. // SelectKey returns a string that represents the key of a select branch, however, it is not
  447. // actually the real label written out to the build file.
  448. // this.ConfigurationAxis().SelectKey(this.SelectKey()) will give the actual label.
  449. SelectKey() string
  450. }
  451. // ProductConfigProperty represents a product config variable, and if it is arch-variant or not.
  452. type ProductConfigProperty struct {
  453. // The name of the product variable, e.g. "safestack", "malloc_not_svelte",
  454. // "board"
  455. name string
  456. arch string
  457. }
  458. func (p ProductConfigProperty) Name() string {
  459. return p.name
  460. }
  461. func (p ProductConfigProperty) AlwaysEmit() bool {
  462. return false
  463. }
  464. func (p ProductConfigProperty) ConfigurationAxis() bazel.ConfigurationAxis {
  465. return bazel.ProductVariableConfigurationAxis(p.arch != "", p.name+"__"+p.arch)
  466. }
  467. func (p ProductConfigProperty) SelectKey() string {
  468. if p.arch == "" {
  469. return strings.ToLower(p.name)
  470. } else {
  471. return strings.ToLower(p.name + "-" + p.arch)
  472. }
  473. }
  474. // SoongConfigProperty represents a soong config variable, its value if it's a string variable,
  475. // and if it's dependent on the OS or not
  476. type SoongConfigProperty struct {
  477. name string
  478. namespace string
  479. // Can be an empty string for bool/value soong config variables
  480. value string
  481. // If there is a target: field inside a soong config property struct, the os that it selects
  482. // on will be represented here.
  483. os string
  484. }
  485. func (p SoongConfigProperty) Name() string {
  486. return p.name
  487. }
  488. func (p SoongConfigProperty) AlwaysEmit() bool {
  489. return true
  490. }
  491. func (p SoongConfigProperty) ConfigurationAxis() bazel.ConfigurationAxis {
  492. return bazel.ProductVariableConfigurationAxis(false, p.namespace+"__"+p.name+"__"+p.os)
  493. }
  494. // SelectKey returns the literal string that represents this variable in a BUILD
  495. // select statement.
  496. func (p SoongConfigProperty) SelectKey() string {
  497. // p.value being conditions_default can happen with or without a desired os. When not using
  498. // an os, we want to emit literally just //conditions:default in the select statement, but
  499. // when using an os, we want to emit namespace__name__conditions_default__os, so that
  500. // the branch is only taken if the variable is not set, and we're on the desired os.
  501. // ConfigurationAxis#SelectKey will map the conditions_default result of this function to
  502. // //conditions:default.
  503. if p.value == bazel.ConditionsDefaultConfigKey && p.os == "" {
  504. return bazel.ConditionsDefaultConfigKey
  505. }
  506. parts := []string{p.namespace, p.name}
  507. if p.value != "" && p.value != bazel.ConditionsDefaultSelectKey {
  508. parts = append(parts, p.value)
  509. }
  510. if p.os != "" {
  511. parts = append(parts, p.os)
  512. }
  513. // e.g. acme__feature1, android__board__soc_a, my_namespace__my_variables__my_value__my_os
  514. return strings.ToLower(strings.Join(parts, "__"))
  515. }
  516. // ProductConfigProperties is a map of maps to group property values according
  517. // their property name and the product config variable they're set under.
  518. //
  519. // The outer map key is the name of the property, like "cflags".
  520. //
  521. // The inner map key is a ProductConfigProperty, which is a struct of product
  522. // variable name, namespace, and the "full configuration" of the product
  523. // variable.
  524. //
  525. // e.g. product variable name: board, namespace: acme, full config: vendor_chip_foo
  526. //
  527. // The value of the map is the interface{} representing the value of the
  528. // property, like ["-DDEFINES"] for cflags.
  529. type ProductConfigProperties map[string]map[ProductConfigOrSoongConfigProperty]interface{}
  530. // ProductVariableProperties returns a ProductConfigProperties containing only the properties which
  531. // have been set for the given module.
  532. func ProductVariableProperties(ctx ArchVariantContext, module Module) ProductConfigProperties {
  533. moduleBase := module.base()
  534. productConfigProperties := ProductConfigProperties{}
  535. if moduleBase.variableProperties != nil {
  536. productVariablesProperty := proptools.FieldNameForProperty("product_variables")
  537. for /* axis */ _, configToProps := range moduleBase.GetArchVariantProperties(ctx, moduleBase.variableProperties) {
  538. for config, props := range configToProps {
  539. variableValues := reflect.ValueOf(props).Elem().FieldByName(productVariablesProperty)
  540. productConfigProperties.AddProductConfigProperties(variableValues, config)
  541. }
  542. }
  543. }
  544. if m, ok := module.(Bazelable); ok && m.namespacedVariableProps() != nil {
  545. for namespace, namespacedVariableProps := range m.namespacedVariableProps() {
  546. for _, namespacedVariableProp := range namespacedVariableProps {
  547. variableValues := reflect.ValueOf(namespacedVariableProp).Elem().FieldByName(soongconfig.SoongConfigProperty)
  548. productConfigProperties.AddSoongConfigProperties(namespace, variableValues)
  549. }
  550. }
  551. }
  552. return productConfigProperties
  553. }
  554. func (p *ProductConfigProperties) AddProductConfigProperty(
  555. propertyName, productVariableName, arch string, propertyValue interface{}) {
  556. productConfigProp := ProductConfigProperty{
  557. name: productVariableName, // e.g. size, feature1, feature2, FEATURE3, board
  558. arch: arch, // e.g. "", x86, arm64
  559. }
  560. p.AddEitherProperty(propertyName, productConfigProp, propertyValue)
  561. }
  562. func (p *ProductConfigProperties) AddSoongConfigProperty(
  563. propertyName, namespace, variableName, value, os string, propertyValue interface{}) {
  564. soongConfigProp := SoongConfigProperty{
  565. namespace: namespace,
  566. name: variableName, // e.g. size, feature1, feature2, FEATURE3, board
  567. value: value,
  568. os: os, // e.g. android, linux_x86
  569. }
  570. p.AddEitherProperty(propertyName, soongConfigProp, propertyValue)
  571. }
  572. func (p *ProductConfigProperties) AddEitherProperty(
  573. propertyName string, key ProductConfigOrSoongConfigProperty, propertyValue interface{}) {
  574. if (*p)[propertyName] == nil {
  575. (*p)[propertyName] = make(map[ProductConfigOrSoongConfigProperty]interface{})
  576. }
  577. if existing, ok := (*p)[propertyName][key]; ok {
  578. switch dst := existing.(type) {
  579. case []string:
  580. src, ok := propertyValue.([]string)
  581. if !ok {
  582. panic("Conflicting types")
  583. }
  584. dst = append(dst, src...)
  585. (*p)[propertyName][key] = dst
  586. default:
  587. panic(fmt.Errorf("TODO: handle merging value %#v", existing))
  588. }
  589. } else {
  590. (*p)[propertyName][key] = propertyValue
  591. }
  592. }
  593. var (
  594. conditionsDefaultField string = proptools.FieldNameForProperty(bazel.ConditionsDefaultConfigKey)
  595. )
  596. // maybeExtractConfigVarProp attempts to read this value as a config var struct
  597. // wrapped by interfaces and ptrs. If it's not the right type, the second return
  598. // value is false.
  599. func maybeExtractConfigVarProp(v reflect.Value) (reflect.Value, bool) {
  600. if v.Kind() == reflect.Interface {
  601. // The conditions_default value can be either
  602. // 1) an ptr to an interface of a struct (bool config variables and product variables)
  603. // 2) an interface of 1) (config variables with nested structs, like string vars)
  604. v = v.Elem()
  605. }
  606. if v.Kind() != reflect.Ptr {
  607. return v, false
  608. }
  609. v = reflect.Indirect(v)
  610. if v.Kind() == reflect.Interface {
  611. // Extract the struct from the interface
  612. v = v.Elem()
  613. }
  614. if !v.IsValid() {
  615. return v, false
  616. }
  617. if v.Kind() != reflect.Struct {
  618. return v, false
  619. }
  620. return v, true
  621. }
  622. func (productConfigProperties *ProductConfigProperties) AddProductConfigProperties(variableValues reflect.Value, arch string) {
  623. // Example of product_variables:
  624. //
  625. // product_variables: {
  626. // malloc_not_svelte: {
  627. // shared_libs: ["malloc_not_svelte_shared_lib"],
  628. // whole_static_libs: ["malloc_not_svelte_whole_static_lib"],
  629. // exclude_static_libs: [
  630. // "malloc_not_svelte_static_lib_excludes",
  631. // "malloc_not_svelte_whole_static_lib_excludes",
  632. // ],
  633. // },
  634. // },
  635. for i := 0; i < variableValues.NumField(); i++ {
  636. // e.g. Platform_sdk_version, Unbundled_build, Malloc_not_svelte, etc.
  637. productVariableName := variableValues.Type().Field(i).Name
  638. variableValue := variableValues.Field(i)
  639. // Check if any properties were set for the module
  640. if variableValue.IsZero() {
  641. // e.g. feature1: {}, malloc_not_svelte: {}
  642. continue
  643. }
  644. for j := 0; j < variableValue.NumField(); j++ {
  645. property := variableValue.Field(j)
  646. // e.g. Asflags, Cflags, Enabled, etc.
  647. propertyName := variableValue.Type().Field(j).Name
  648. if property.Kind() != reflect.Interface {
  649. productConfigProperties.AddProductConfigProperty(propertyName, productVariableName, arch, property.Interface())
  650. }
  651. }
  652. }
  653. }
  654. func (productConfigProperties *ProductConfigProperties) AddSoongConfigProperties(namespace string, soongConfigVariablesStruct reflect.Value) {
  655. //
  656. // Example of soong_config_variables:
  657. //
  658. // soong_config_variables: {
  659. // feature1: {
  660. // conditions_default: {
  661. // ...
  662. // },
  663. // cflags: ...
  664. // },
  665. // feature2: {
  666. // cflags: ...
  667. // conditions_default: {
  668. // ...
  669. // },
  670. // },
  671. // board: {
  672. // soc_a: {
  673. // ...
  674. // },
  675. // soc_b: {
  676. // ...
  677. // },
  678. // soc_c: {},
  679. // conditions_default: {
  680. // ...
  681. // },
  682. // },
  683. // }
  684. for i := 0; i < soongConfigVariablesStruct.NumField(); i++ {
  685. // e.g. feature1, feature2, board
  686. variableName := soongConfigVariablesStruct.Type().Field(i).Name
  687. variableStruct := soongConfigVariablesStruct.Field(i)
  688. // Check if any properties were set for the module
  689. if variableStruct.IsZero() {
  690. // e.g. feature1: {}
  691. continue
  692. }
  693. // Unlike product variables, config variables require a few more
  694. // indirections to extract the struct from the reflect.Value.
  695. if v, ok := maybeExtractConfigVarProp(variableStruct); ok {
  696. variableStruct = v
  697. } else if !v.IsValid() {
  698. // Skip invalid variables which may not used, else leads to panic
  699. continue
  700. }
  701. for j := 0; j < variableStruct.NumField(); j++ {
  702. propertyOrStruct := variableStruct.Field(j)
  703. // propertyOrValueName can either be:
  704. // - A property, like: Asflags, Cflags, Enabled, etc.
  705. // - A soong config string variable's value, like soc_a, soc_b, soc_c in the example above
  706. // - "conditions_default"
  707. propertyOrValueName := variableStruct.Type().Field(j).Name
  708. // If the property wasn't set, no need to pass it along
  709. if propertyOrStruct.IsZero() {
  710. continue
  711. }
  712. if v, ok := maybeExtractConfigVarProp(propertyOrStruct); ok {
  713. // The field is a struct, which is used by:
  714. // 1) soong_config_string_variables
  715. //
  716. // soc_a: {
  717. // cflags: ...,
  718. // }
  719. //
  720. // soc_b: {
  721. // cflags: ...,
  722. // }
  723. //
  724. // 2) conditions_default structs for all soong config variable types.
  725. //
  726. // conditions_default: {
  727. // cflags: ...,
  728. // static_libs: ...
  729. // }
  730. //
  731. // This means that propertyOrValueName is either conditions_default, or a soong
  732. // config string variable's value.
  733. field := v
  734. // Iterate over fields of this struct prop.
  735. for k := 0; k < field.NumField(); k++ {
  736. // For product variables, zero values are irrelevant; however, for soong config variables,
  737. // empty values are relevant because there can also be a conditions default which is not
  738. // applied for empty variables.
  739. if field.Field(k).IsZero() && namespace == "" {
  740. continue
  741. }
  742. propertyName := field.Type().Field(k).Name
  743. if propertyName == "Target" {
  744. productConfigProperties.AddSoongConfigPropertiesFromTargetStruct(namespace, variableName, proptools.PropertyNameForField(propertyOrValueName), field.Field(k))
  745. } else if propertyName == "Arch" || propertyName == "Multilib" {
  746. panic("Arch/Multilib are not currently supported in soong config variable structs")
  747. } else {
  748. productConfigProperties.AddSoongConfigProperty(propertyName, namespace, variableName, proptools.PropertyNameForField(propertyOrValueName), "", field.Field(k).Interface())
  749. }
  750. }
  751. } else if propertyOrStruct.Kind() != reflect.Interface {
  752. // If not an interface, then this is not a conditions_default or
  753. // a struct prop. That is, this is a bool/value config variable.
  754. if propertyOrValueName == "Target" {
  755. productConfigProperties.AddSoongConfigPropertiesFromTargetStruct(namespace, variableName, "", propertyOrStruct)
  756. } else if propertyOrValueName == "Arch" || propertyOrValueName == "Multilib" {
  757. panic("Arch/Multilib are not currently supported in soong config variable structs")
  758. } else {
  759. productConfigProperties.AddSoongConfigProperty(propertyOrValueName, namespace, variableName, "", "", propertyOrStruct.Interface())
  760. }
  761. }
  762. }
  763. }
  764. }
  765. func (productConfigProperties *ProductConfigProperties) AddSoongConfigPropertiesFromTargetStruct(namespace, soongConfigVariableName string, soongConfigVariableValue string, targetStruct reflect.Value) {
  766. // targetStruct will be a struct with fields like "android", "host", "arm", "x86",
  767. // "android_arm", etc. The values of each of those fields will be a regular property struct.
  768. for i := 0; i < targetStruct.NumField(); i++ {
  769. targetFieldName := targetStruct.Type().Field(i).Name
  770. archOrOsSpecificStruct := targetStruct.Field(i)
  771. for j := 0; j < archOrOsSpecificStruct.NumField(); j++ {
  772. property := archOrOsSpecificStruct.Field(j)
  773. // e.g. Asflags, Cflags, Enabled, etc.
  774. propertyName := archOrOsSpecificStruct.Type().Field(j).Name
  775. if targetFieldName == "Android" {
  776. productConfigProperties.AddSoongConfigProperty(propertyName, namespace, soongConfigVariableName, soongConfigVariableValue, "android", property.Interface())
  777. } else if targetFieldName == "Host" {
  778. for _, os := range osTypeList {
  779. if os.Class == Host {
  780. productConfigProperties.AddSoongConfigProperty(propertyName, namespace, soongConfigVariableName, soongConfigVariableValue, os.Name, property.Interface())
  781. }
  782. }
  783. } else {
  784. // One problem with supporting additional fields is that if multiple branches of
  785. // "target" overlap, we don't want them to be in the same select statement (aka
  786. // configuration axis). "android" and "host" are disjoint, so it's ok that we only
  787. // have 2 axes right now. (soongConfigVariables and soongConfigVariablesPlusOs)
  788. panic("TODO: support other target types in soong config variable structs: " + targetFieldName)
  789. }
  790. }
  791. }
  792. }
  793. func VariableMutator(mctx BottomUpMutatorContext) {
  794. var module Module
  795. var ok bool
  796. if module, ok = mctx.Module().(Module); !ok {
  797. return
  798. }
  799. // TODO: depend on config variable, create variants, propagate variants up tree
  800. a := module.base()
  801. if a.variableProperties == nil {
  802. return
  803. }
  804. variableValues := reflect.ValueOf(a.variableProperties).Elem().FieldByName("Product_variables")
  805. productVariables := reflect.ValueOf(mctx.Config().productVariables)
  806. for i := 0; i < variableValues.NumField(); i++ {
  807. variableValue := variableValues.Field(i)
  808. name := variableValues.Type().Field(i).Name
  809. property := "product_variables." + proptools.PropertyNameForField(name)
  810. // Check that the variable was set for the product
  811. val := productVariables.FieldByName(name)
  812. if !val.IsValid() || val.Kind() != reflect.Ptr || val.IsNil() {
  813. continue
  814. }
  815. val = val.Elem()
  816. // For bools, check that the value is true
  817. if val.Kind() == reflect.Bool && val.Bool() == false {
  818. continue
  819. }
  820. // Check if any properties were set for the module
  821. if variableValue.IsZero() {
  822. continue
  823. }
  824. a.setVariableProperties(mctx, property, variableValue, val.Interface())
  825. }
  826. }
  827. func (m *ModuleBase) setVariableProperties(ctx BottomUpMutatorContext,
  828. prefix string, productVariablePropertyValue reflect.Value, variableValue interface{}) {
  829. printfIntoProperties(ctx, prefix, productVariablePropertyValue, variableValue)
  830. err := proptools.AppendMatchingProperties(m.GetProperties(),
  831. productVariablePropertyValue.Addr().Interface(), nil)
  832. if err != nil {
  833. if propertyErr, ok := err.(*proptools.ExtendPropertyError); ok {
  834. ctx.PropertyErrorf(propertyErr.Property, "%s", propertyErr.Err.Error())
  835. } else {
  836. panic(err)
  837. }
  838. }
  839. }
  840. func printfIntoPropertiesError(ctx BottomUpMutatorContext, prefix string,
  841. productVariablePropertyValue reflect.Value, i int, err error) {
  842. field := productVariablePropertyValue.Type().Field(i).Name
  843. property := prefix + "." + proptools.PropertyNameForField(field)
  844. ctx.PropertyErrorf(property, "%s", err)
  845. }
  846. func printfIntoProperties(ctx BottomUpMutatorContext, prefix string,
  847. productVariablePropertyValue reflect.Value, variableValue interface{}) {
  848. for i := 0; i < productVariablePropertyValue.NumField(); i++ {
  849. propertyValue := productVariablePropertyValue.Field(i)
  850. kind := propertyValue.Kind()
  851. if kind == reflect.Ptr {
  852. if propertyValue.IsNil() {
  853. continue
  854. }
  855. propertyValue = propertyValue.Elem()
  856. }
  857. switch propertyValue.Kind() {
  858. case reflect.String:
  859. err := printfIntoProperty(propertyValue, variableValue)
  860. if err != nil {
  861. printfIntoPropertiesError(ctx, prefix, productVariablePropertyValue, i, err)
  862. }
  863. case reflect.Slice:
  864. for j := 0; j < propertyValue.Len(); j++ {
  865. err := printfIntoProperty(propertyValue.Index(j), variableValue)
  866. if err != nil {
  867. printfIntoPropertiesError(ctx, prefix, productVariablePropertyValue, i, err)
  868. }
  869. }
  870. case reflect.Bool:
  871. // Nothing
  872. case reflect.Struct:
  873. printfIntoProperties(ctx, prefix, propertyValue, variableValue)
  874. default:
  875. panic(fmt.Errorf("unsupported field kind %q", propertyValue.Kind()))
  876. }
  877. }
  878. }
  879. func printfIntoProperty(propertyValue reflect.Value, variableValue interface{}) error {
  880. s := propertyValue.String()
  881. count := strings.Count(s, "%")
  882. if count == 0 {
  883. return nil
  884. }
  885. if count > 1 {
  886. return fmt.Errorf("product variable properties only support a single '%%'")
  887. }
  888. if strings.Contains(s, "%d") {
  889. switch v := variableValue.(type) {
  890. case int:
  891. // Nothing
  892. case bool:
  893. if v {
  894. variableValue = 1
  895. } else {
  896. variableValue = 0
  897. }
  898. default:
  899. return fmt.Errorf("unsupported type %T for %%d", variableValue)
  900. }
  901. } else if strings.Contains(s, "%s") {
  902. switch variableValue.(type) {
  903. case string:
  904. // Nothing
  905. default:
  906. return fmt.Errorf("unsupported type %T for %%s", variableValue)
  907. }
  908. } else {
  909. return fmt.Errorf("unsupported %% in product variable property")
  910. }
  911. propertyValue.Set(reflect.ValueOf(fmt.Sprintf(s, variableValue)))
  912. return nil
  913. }
  914. var variablePropTypeMap OncePer
  915. // sliceToTypeArray takes a slice of property structs and returns a reflection created array containing the
  916. // reflect.Types of each property struct. The result can be used as a key in a map.
  917. func sliceToTypeArray(s []interface{}) interface{} {
  918. // Create an array using reflection whose length is the length of the input slice
  919. ret := reflect.New(reflect.ArrayOf(len(s), reflect.TypeOf(reflect.TypeOf(0)))).Elem()
  920. for i, e := range s {
  921. ret.Index(i).Set(reflect.ValueOf(reflect.TypeOf(e)))
  922. }
  923. return ret.Interface()
  924. }
  925. func initProductVariableModule(m Module) {
  926. base := m.base()
  927. // Allow tests to override the default product variables
  928. if base.variableProperties == nil {
  929. base.variableProperties = defaultProductVariables
  930. }
  931. // Filter the product variables properties to the ones that exist on this module
  932. base.variableProperties = createVariableProperties(m.GetProperties(), base.variableProperties)
  933. if base.variableProperties != nil {
  934. m.AddProperties(base.variableProperties)
  935. }
  936. }
  937. // createVariableProperties takes the list of property structs for a module and returns a property struct that
  938. // contains the product variable properties that exist in the property structs, or nil if there are none. It
  939. // caches the result.
  940. func createVariableProperties(moduleTypeProps []interface{}, productVariables interface{}) interface{} {
  941. // Convert the moduleTypeProps to an array of reflect.Types that can be used as a key in the OncePer.
  942. key := sliceToTypeArray(moduleTypeProps)
  943. // Use the variablePropTypeMap OncePer to cache the result for each set of property struct types.
  944. typ, _ := variablePropTypeMap.Once(NewCustomOnceKey(key), func() interface{} {
  945. // Compute the filtered property struct type.
  946. return createVariablePropertiesType(moduleTypeProps, productVariables)
  947. }).(reflect.Type)
  948. if typ == nil {
  949. return nil
  950. }
  951. // Create a new pointer to a filtered property struct.
  952. return reflect.New(typ).Interface()
  953. }
  954. // createVariablePropertiesType creates a new type that contains only the product variable properties that exist in
  955. // a list of property structs.
  956. func createVariablePropertiesType(moduleTypeProps []interface{}, productVariables interface{}) reflect.Type {
  957. typ, _ := proptools.FilterPropertyStruct(reflect.TypeOf(productVariables),
  958. func(field reflect.StructField, prefix string) (bool, reflect.StructField) {
  959. // Filter function, returns true if the field should be in the resulting struct
  960. if prefix == "" {
  961. // Keep the top level Product_variables field
  962. return true, field
  963. }
  964. _, rest := splitPrefix(prefix)
  965. if rest == "" {
  966. // Keep the 2nd level field (i.e. Product_variables.Eng)
  967. return true, field
  968. }
  969. // Strip off the first 2 levels of the prefix
  970. _, prefix = splitPrefix(rest)
  971. for _, p := range moduleTypeProps {
  972. if fieldExistsByNameRecursive(reflect.TypeOf(p).Elem(), prefix, field.Name) {
  973. // Keep any fields that exist in one of the property structs
  974. return true, field
  975. }
  976. }
  977. return false, field
  978. })
  979. return typ
  980. }
  981. func splitPrefix(prefix string) (first, rest string) {
  982. index := strings.IndexByte(prefix, '.')
  983. if index == -1 {
  984. return prefix, ""
  985. }
  986. return prefix[:index], prefix[index+1:]
  987. }
  988. func fieldExistsByNameRecursive(t reflect.Type, prefix, name string) bool {
  989. if t.Kind() != reflect.Struct {
  990. panic(fmt.Errorf("fieldExistsByNameRecursive can only be called on a reflect.Struct"))
  991. }
  992. if prefix != "" {
  993. split := strings.SplitN(prefix, ".", 2)
  994. firstPrefix := split[0]
  995. rest := ""
  996. if len(split) > 1 {
  997. rest = split[1]
  998. }
  999. f, exists := t.FieldByName(firstPrefix)
  1000. if !exists {
  1001. return false
  1002. }
  1003. ft := f.Type
  1004. if ft.Kind() == reflect.Ptr {
  1005. ft = ft.Elem()
  1006. }
  1007. if ft.Kind() != reflect.Struct {
  1008. panic(fmt.Errorf("field %q in %q is not a struct", firstPrefix, t))
  1009. }
  1010. return fieldExistsByNameRecursive(ft, rest, name)
  1011. } else {
  1012. _, exists := t.FieldByName(name)
  1013. return exists
  1014. }
  1015. }