variable.go 40 KB

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