variable.go 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264
  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. MultitreeUpdateMeta bool `json:",omitempty"`
  287. BoardVendorSepolicyDirs []string `json:",omitempty"`
  288. BoardOdmSepolicyDirs []string `json:",omitempty"`
  289. BoardReqdMaskPolicy []string `json:",omitempty"`
  290. BoardPlatVendorPolicy []string `json:",omitempty"`
  291. BoardSystemExtPublicPrebuiltDirs []string `json:",omitempty"`
  292. BoardSystemExtPrivatePrebuiltDirs []string `json:",omitempty"`
  293. BoardProductPublicPrebuiltDirs []string `json:",omitempty"`
  294. BoardProductPrivatePrebuiltDirs []string `json:",omitempty"`
  295. SystemExtPublicSepolicyDirs []string `json:",omitempty"`
  296. SystemExtPrivateSepolicyDirs []string `json:",omitempty"`
  297. BoardSepolicyM4Defs []string `json:",omitempty"`
  298. BoardSepolicyVers *string `json:",omitempty"`
  299. PlatformSepolicyVersion *string `json:",omitempty"`
  300. TotSepolicyVersion *string `json:",omitempty"`
  301. SystemExtSepolicyPrebuiltApiDir *string `json:",omitempty"`
  302. ProductSepolicyPrebuiltApiDir *string `json:",omitempty"`
  303. PlatformSepolicyCompatVersions []string `json:",omitempty"`
  304. VendorVars map[string]map[string]string `json:",omitempty"`
  305. Ndk_abis *bool `json:",omitempty"`
  306. Flatten_apex *bool `json:",omitempty"`
  307. ForceApexSymlinkOptimization *bool `json:",omitempty"`
  308. CompressedApex *bool `json:",omitempty"`
  309. Aml_abis *bool `json:",omitempty"`
  310. DexpreoptGlobalConfig *string `json:",omitempty"`
  311. WithDexpreopt bool `json:",omitempty"`
  312. ManifestPackageNameOverrides []string `json:",omitempty"`
  313. CertificateOverrides []string `json:",omitempty"`
  314. PackageNameOverrides []string `json:",omitempty"`
  315. ApexGlobalMinSdkVersionOverride *string `json:",omitempty"`
  316. EnforceSystemCertificate *bool `json:",omitempty"`
  317. EnforceSystemCertificateAllowList []string `json:",omitempty"`
  318. ProductHiddenAPIStubs []string `json:",omitempty"`
  319. ProductHiddenAPIStubsSystem []string `json:",omitempty"`
  320. ProductHiddenAPIStubsTest []string `json:",omitempty"`
  321. ProductPublicSepolicyDirs []string `json:",omitempty"`
  322. ProductPrivateSepolicyDirs []string `json:",omitempty"`
  323. ProductVndkVersion *string `json:",omitempty"`
  324. TargetFSConfigGen []string `json:",omitempty"`
  325. MissingUsesLibraries []string `json:",omitempty"`
  326. EnforceProductPartitionInterface *bool `json:",omitempty"`
  327. EnforceInterPartitionJavaSdkLibrary *bool `json:",omitempty"`
  328. InterPartitionJavaLibraryAllowList []string `json:",omitempty"`
  329. InstallExtraFlattenedApexes *bool `json:",omitempty"`
  330. BoardUsesRecoveryAsBoot *bool `json:",omitempty"`
  331. BoardKernelBinaries []string `json:",omitempty"`
  332. BoardKernelModuleInterfaceVersions []string `json:",omitempty"`
  333. BoardMoveRecoveryResourcesToVendorBoot *bool `json:",omitempty"`
  334. PrebuiltHiddenApiDir *string `json:",omitempty"`
  335. ShippingApiLevel *string `json:",omitempty"`
  336. BuildBrokenEnforceSyspropOwner bool `json:",omitempty"`
  337. BuildBrokenTrebleSyspropNeverallow bool `json:",omitempty"`
  338. BuildBrokenVendorPropertyNamespace bool `json:",omitempty"`
  339. BuildBrokenInputDirModules []string `json:",omitempty"`
  340. BuildDebugfsRestrictionsEnabled bool `json:",omitempty"`
  341. RequiresInsecureExecmemForSwiftshader bool `json:",omitempty"`
  342. SelinuxIgnoreNeverallows bool `json:",omitempty"`
  343. SepolicySplit bool `json:",omitempty"`
  344. SepolicyFreezeTestExtraDirs []string `json:",omitempty"`
  345. SepolicyFreezeTestExtraPrebuiltDirs []string `json:",omitempty"`
  346. GenerateAidlNdkPlatformBackend bool `json:",omitempty"`
  347. }
  348. func boolPtr(v bool) *bool {
  349. return &v
  350. }
  351. func intPtr(v int) *int {
  352. return &v
  353. }
  354. func stringPtr(v string) *string {
  355. return &v
  356. }
  357. func (v *productVariables) SetDefaultConfig() {
  358. *v = productVariables{
  359. BuildNumberFile: stringPtr("build_number.txt"),
  360. Platform_version_name: stringPtr("S"),
  361. Platform_base_sdk_extension_version: intPtr(30),
  362. Platform_sdk_version: intPtr(30),
  363. Platform_sdk_codename: stringPtr("S"),
  364. Platform_sdk_final: boolPtr(false),
  365. Platform_version_active_codenames: []string{"S"},
  366. Platform_vndk_version: stringPtr("S"),
  367. HostArch: stringPtr("x86_64"),
  368. HostSecondaryArch: stringPtr("x86"),
  369. DeviceName: stringPtr("generic_arm64"),
  370. DeviceProduct: stringPtr("aosp_arm-eng"),
  371. DeviceArch: stringPtr("arm64"),
  372. DeviceArchVariant: stringPtr("armv8-a"),
  373. DeviceCpuVariant: stringPtr("generic"),
  374. DeviceAbi: []string{"arm64-v8a"},
  375. DeviceSecondaryArch: stringPtr("arm"),
  376. DeviceSecondaryArchVariant: stringPtr("armv8-a"),
  377. DeviceSecondaryCpuVariant: stringPtr("generic"),
  378. DeviceSecondaryAbi: []string{"armeabi-v7a", "armeabi"},
  379. AAPTConfig: []string{"normal", "large", "xlarge", "hdpi", "xhdpi", "xxhdpi"},
  380. AAPTPreferredConfig: stringPtr("xhdpi"),
  381. AAPTCharacteristics: stringPtr("nosdcard"),
  382. AAPTPrebuiltDPI: []string{"xhdpi", "xxhdpi"},
  383. Malloc_not_svelte: boolPtr(true),
  384. Malloc_zero_contents: boolPtr(true),
  385. Malloc_pattern_fill_contents: boolPtr(false),
  386. Safestack: boolPtr(false),
  387. BootJars: ConfiguredJarList{apexes: []string{}, jars: []string{}},
  388. ApexBootJars: ConfiguredJarList{apexes: []string{}, jars: []string{}},
  389. }
  390. if runtime.GOOS == "linux" {
  391. v.CrossHost = stringPtr("windows")
  392. v.CrossHostArch = stringPtr("x86")
  393. v.CrossHostSecondaryArch = stringPtr("x86_64")
  394. }
  395. }
  396. // ProductConfigContext requires the access to the Module to get product config properties.
  397. type ProductConfigContext interface {
  398. Module() Module
  399. }
  400. // ProductConfigProperty contains the information for a single property (may be a struct) paired
  401. // with the appropriate ProductConfigVariable.
  402. type ProductConfigProperty struct {
  403. // The name of the product variable, e.g. "safestack", "malloc_not_svelte",
  404. // "board"
  405. Name string
  406. // Namespace of the variable, if this is a soong_config_module_type variable
  407. // e.g. "acme", "ANDROID", "vendor_name"
  408. Namespace string
  409. // Unique configuration to identify this product config property (i.e. a
  410. // primary key), as just using the product variable name is not sufficient.
  411. //
  412. // For product variables, this is the product variable name + optional
  413. // archvariant information. e.g.
  414. //
  415. // product_variables: {
  416. // foo: {
  417. // cflags: ["-Dfoo"],
  418. // },
  419. // },
  420. //
  421. // FullConfig would be "foo".
  422. //
  423. // target: {
  424. // android: {
  425. // product_variables: {
  426. // foo: {
  427. // cflags: ["-Dfoo-android"],
  428. // },
  429. // },
  430. // },
  431. // },
  432. //
  433. // FullConfig would be "foo-android".
  434. //
  435. // For soong config variables, this is the namespace + product variable name
  436. // + value of the variable, if applicable. The value can also be
  437. // conditions_default.
  438. //
  439. // e.g.
  440. //
  441. // soong_config_variables: {
  442. // feature1: {
  443. // conditions_default: {
  444. // cflags: ["-DDEFAULT1"],
  445. // },
  446. // cflags: ["-DFEATURE1"],
  447. // },
  448. // }
  449. //
  450. // where feature1 is created in the "acme" namespace, so FullConfig would be
  451. // "acme__feature1" and "acme__feature1__conditions_default".
  452. //
  453. // e.g.
  454. //
  455. // soong_config_variables: {
  456. // board: {
  457. // soc_a: {
  458. // cflags: ["-DSOC_A"],
  459. // },
  460. // soc_b: {
  461. // cflags: ["-DSOC_B"],
  462. // },
  463. // soc_c: {},
  464. // conditions_default: {
  465. // cflags: ["-DSOC_DEFAULT"]
  466. // },
  467. // },
  468. // }
  469. //
  470. // where board is created in the "acme" namespace, so FullConfig would be
  471. // "acme__board__soc_a", "acme__board__soc_b", and
  472. // "acme__board__conditions_default"
  473. FullConfig string
  474. }
  475. func (p *ProductConfigProperty) AlwaysEmit() bool {
  476. return p.Namespace != ""
  477. }
  478. func (p *ProductConfigProperty) ConfigurationAxis() bazel.ConfigurationAxis {
  479. if p.Namespace == "" {
  480. return bazel.ProductVariableConfigurationAxis(p.FullConfig)
  481. } else {
  482. // Soong config variables can be uniquely identified by the namespace
  483. // (e.g. acme, android) and the product variable name (e.g. board, size)
  484. return bazel.ProductVariableConfigurationAxis(p.Namespace + "__" + p.Name)
  485. }
  486. }
  487. // SelectKey returns the literal string that represents this variable in a BUILD
  488. // select statement.
  489. func (p *ProductConfigProperty) SelectKey() string {
  490. if p.Namespace == "" {
  491. return strings.ToLower(p.FullConfig)
  492. }
  493. if p.FullConfig == bazel.ConditionsDefaultConfigKey {
  494. return bazel.ConditionsDefaultConfigKey
  495. }
  496. value := p.FullConfig
  497. if value == p.Name {
  498. value = ""
  499. }
  500. // e.g. acme__feature1, android__board__soc_a
  501. selectKey := strings.ToLower(strings.Join([]string{p.Namespace, p.Name}, "__"))
  502. if value != "" {
  503. selectKey = strings.ToLower(strings.Join([]string{selectKey, value}, "__"))
  504. }
  505. return selectKey
  506. }
  507. // ProductConfigProperties is a map of maps to group property values according
  508. // their property name and the product config variable they're set under.
  509. //
  510. // The outer map key is the name of the property, like "cflags".
  511. //
  512. // The inner map key is a ProductConfigProperty, which is a struct of product
  513. // variable name, namespace, and the "full configuration" of the product
  514. // variable.
  515. //
  516. // e.g. product variable name: board, namespace: acme, full config: vendor_chip_foo
  517. //
  518. // The value of the map is the interface{} representing the value of the
  519. // property, like ["-DDEFINES"] for cflags.
  520. type ProductConfigProperties map[string]map[ProductConfigProperty]interface{}
  521. // ProductVariableProperties returns a ProductConfigProperties containing only the properties which
  522. // have been set for the module in the given context.
  523. func ProductVariableProperties(ctx BazelConversionPathContext) ProductConfigProperties {
  524. module := ctx.Module()
  525. moduleBase := module.base()
  526. productConfigProperties := ProductConfigProperties{}
  527. if moduleBase.variableProperties != nil {
  528. productVariablesProperty := proptools.FieldNameForProperty("product_variables")
  529. productVariableValues(
  530. productVariablesProperty,
  531. moduleBase.variableProperties,
  532. "",
  533. "",
  534. &productConfigProperties)
  535. for _, configToProps := range moduleBase.GetArchVariantProperties(ctx, moduleBase.variableProperties) {
  536. for config, props := range configToProps {
  537. // GetArchVariantProperties is creating an instance of the requested type
  538. // and productVariablesValues expects an interface, so no need to cast
  539. productVariableValues(
  540. productVariablesProperty,
  541. props,
  542. "",
  543. config,
  544. &productConfigProperties)
  545. }
  546. }
  547. }
  548. if m, ok := module.(Bazelable); ok && m.namespacedVariableProps() != nil {
  549. for namespace, namespacedVariableProps := range m.namespacedVariableProps() {
  550. for _, namespacedVariableProp := range namespacedVariableProps {
  551. productVariableValues(
  552. soongconfig.SoongConfigProperty,
  553. namespacedVariableProp,
  554. namespace,
  555. "",
  556. &productConfigProperties)
  557. }
  558. }
  559. }
  560. productConfigProperties.zeroValuesForNamespacedVariables()
  561. return productConfigProperties
  562. }
  563. // zeroValuesForNamespacedVariables ensures that selects that contain __only__
  564. // conditions default values have zero values set for the other non-default
  565. // values for that select statement.
  566. //
  567. // If the ProductConfigProperties map contains these items, as parsed from the .bp file:
  568. //
  569. // library_linking_strategy: {
  570. // prefer_static: {
  571. // static_libs: [
  572. // "lib_a",
  573. // "lib_b",
  574. // ],
  575. // },
  576. // conditions_default: {
  577. // shared_libs: [
  578. // "lib_a",
  579. // "lib_b",
  580. // ],
  581. // },
  582. // },
  583. //
  584. // Static_libs {Library_linking_strategy ANDROID prefer_static} [lib_a lib_b]
  585. // Shared_libs {Library_linking_strategy ANDROID conditions_default} [lib_a lib_b]
  586. //
  587. // We need to add this:
  588. //
  589. // Shared_libs {Library_linking_strategy ANDROID prefer_static} []
  590. //
  591. // so that the following gets generated for the "dynamic_deps" attribute,
  592. // instead of putting lib_a and lib_b directly into dynamic_deps without a
  593. // select:
  594. //
  595. // dynamic_deps = select({
  596. // "//build/bazel/product_variables:android__library_linking_strategy__prefer_static": [],
  597. // "//conditions:default": [
  598. // "//foo/bar:lib_a",
  599. // "//foo/bar:lib_b",
  600. // ],
  601. // }),
  602. func (props *ProductConfigProperties) zeroValuesForNamespacedVariables() {
  603. // A map of product config properties to the zero values of their respective
  604. // property value.
  605. zeroValues := make(map[ProductConfigProperty]interface{})
  606. // A map of prop names (e.g. cflags) to product config properties where the
  607. // (prop name, ProductConfigProperty) tuple contains a non-conditions_default key.
  608. //
  609. // e.g.
  610. //
  611. // prefer_static: {
  612. // static_libs: [
  613. // "lib_a",
  614. // "lib_b",
  615. // ],
  616. // },
  617. // conditions_default: {
  618. // shared_libs: [
  619. // "lib_a",
  620. // "lib_b",
  621. // ],
  622. // },
  623. //
  624. // The tuple of ("static_libs", prefer_static) would be in this map.
  625. hasNonDefaultValue := make(map[string]map[ProductConfigProperty]bool)
  626. // Iterate over all added soong config variables.
  627. for propName, v := range *props {
  628. for p, intf := range v {
  629. if p.Namespace == "" {
  630. // If there's no namespace, this isn't a soong config variable,
  631. // i.e. this is a product variable. product variables have no
  632. // conditions_defaults, so skip them.
  633. continue
  634. }
  635. if p.FullConfig == bazel.ConditionsDefaultConfigKey {
  636. // Skip conditions_defaults.
  637. continue
  638. }
  639. if hasNonDefaultValue[propName] == nil {
  640. hasNonDefaultValue[propName] = make(map[ProductConfigProperty]bool)
  641. hasNonDefaultValue[propName][p] = false
  642. }
  643. // Create the zero value of the variable.
  644. if _, exists := zeroValues[p]; !exists {
  645. zeroValue := reflect.Zero(reflect.ValueOf(intf).Type()).Interface()
  646. if zeroValue == nil {
  647. panic(fmt.Errorf("Expected non-nil zero value for product/config variable %+v\n", intf))
  648. }
  649. zeroValues[p] = zeroValue
  650. }
  651. hasNonDefaultValue[propName][p] = true
  652. }
  653. }
  654. for propName := range *props {
  655. for p, zeroValue := range zeroValues {
  656. // Ignore variables that already have a non-default value for that axis
  657. if exists, _ := hasNonDefaultValue[propName][p]; !exists {
  658. // fmt.Println(propName, p.Namespace, p.Name, p.FullConfig, zeroValue)
  659. // Insert the zero value for this propname + product config value.
  660. props.AddProductConfigProperty(
  661. propName,
  662. p.Namespace,
  663. p.Name,
  664. p.FullConfig,
  665. zeroValue,
  666. )
  667. }
  668. }
  669. }
  670. }
  671. func (p *ProductConfigProperties) AddProductConfigProperty(
  672. propertyName, namespace, productVariableName, config string, property interface{}) {
  673. if (*p)[propertyName] == nil {
  674. (*p)[propertyName] = make(map[ProductConfigProperty]interface{})
  675. }
  676. productConfigProp := ProductConfigProperty{
  677. Namespace: namespace, // e.g. acme, android
  678. Name: productVariableName, // e.g. size, feature1, feature2, FEATURE3, board
  679. FullConfig: config, // e.g. size, feature1-x86, size__conditions_default
  680. }
  681. if existing, ok := (*p)[propertyName][productConfigProp]; ok && namespace != "" {
  682. switch dst := existing.(type) {
  683. case []string:
  684. if src, ok := property.([]string); ok {
  685. dst = append(dst, src...)
  686. (*p)[propertyName][productConfigProp] = dst
  687. }
  688. default:
  689. panic(fmt.Errorf("TODO: handle merging value %s", existing))
  690. }
  691. } else {
  692. (*p)[propertyName][productConfigProp] = property
  693. }
  694. }
  695. var (
  696. conditionsDefaultField string = proptools.FieldNameForProperty(bazel.ConditionsDefaultConfigKey)
  697. )
  698. // maybeExtractConfigVarProp attempts to read this value as a config var struct
  699. // wrapped by interfaces and ptrs. If it's not the right type, the second return
  700. // value is false.
  701. func maybeExtractConfigVarProp(v reflect.Value) (reflect.Value, bool) {
  702. if v.Kind() == reflect.Interface {
  703. // The conditions_default value can be either
  704. // 1) an ptr to an interface of a struct (bool config variables and product variables)
  705. // 2) an interface of 1) (config variables with nested structs, like string vars)
  706. v = v.Elem()
  707. }
  708. if v.Kind() != reflect.Ptr {
  709. return v, false
  710. }
  711. v = reflect.Indirect(v)
  712. if v.Kind() == reflect.Interface {
  713. // Extract the struct from the interface
  714. v = v.Elem()
  715. }
  716. if !v.IsValid() {
  717. return v, false
  718. }
  719. if v.Kind() != reflect.Struct {
  720. return v, false
  721. }
  722. return v, true
  723. }
  724. func (productConfigProperties *ProductConfigProperties) AddProductConfigProperties(namespace, suffix string, variableValues reflect.Value) {
  725. // variableValues can either be a product_variables or
  726. // soong_config_variables struct.
  727. //
  728. // Example of product_variables:
  729. //
  730. // product_variables: {
  731. // malloc_not_svelte: {
  732. // shared_libs: ["malloc_not_svelte_shared_lib"],
  733. // whole_static_libs: ["malloc_not_svelte_whole_static_lib"],
  734. // exclude_static_libs: [
  735. // "malloc_not_svelte_static_lib_excludes",
  736. // "malloc_not_svelte_whole_static_lib_excludes",
  737. // ],
  738. // },
  739. // },
  740. //
  741. // Example of soong_config_variables:
  742. //
  743. // soong_config_variables: {
  744. // feature1: {
  745. // conditions_default: {
  746. // ...
  747. // },
  748. // cflags: ...
  749. // },
  750. // feature2: {
  751. // cflags: ...
  752. // conditions_default: {
  753. // ...
  754. // },
  755. // },
  756. // board: {
  757. // soc_a: {
  758. // ...
  759. // },
  760. // soc_a: {
  761. // ...
  762. // },
  763. // soc_c: {},
  764. // conditions_default: {
  765. // ...
  766. // },
  767. // },
  768. // }
  769. for i := 0; i < variableValues.NumField(); i++ {
  770. // e.g. Platform_sdk_version, Unbundled_build, Malloc_not_svelte, etc.
  771. productVariableName := variableValues.Type().Field(i).Name
  772. variableValue := variableValues.Field(i)
  773. // Check if any properties were set for the module
  774. if variableValue.IsZero() {
  775. // e.g. feature1: {}, malloc_not_svelte: {}
  776. continue
  777. }
  778. // Unlike product variables, config variables require a few more
  779. // indirections to extract the struct from the reflect.Value.
  780. if v, ok := maybeExtractConfigVarProp(variableValue); ok {
  781. variableValue = v
  782. }
  783. for j := 0; j < variableValue.NumField(); j++ {
  784. property := variableValue.Field(j)
  785. // If the property wasn't set, no need to pass it along
  786. if property.IsZero() {
  787. continue
  788. }
  789. // e.g. Asflags, Cflags, Enabled, etc.
  790. propertyName := variableValue.Type().Field(j).Name
  791. if v, ok := maybeExtractConfigVarProp(property); ok {
  792. // The field is a struct, which is used by:
  793. // 1) soong_config_string_variables
  794. //
  795. // soc_a: {
  796. // cflags: ...,
  797. // }
  798. //
  799. // soc_b: {
  800. // cflags: ...,
  801. // }
  802. //
  803. // 2) conditions_default structs for all soong config variable types.
  804. //
  805. // conditions_default: {
  806. // cflags: ...,
  807. // static_libs: ...
  808. // }
  809. field := v
  810. for k := 0; k < field.NumField(); k++ {
  811. // Iterate over fields of this struct prop.
  812. if field.Field(k).IsZero() {
  813. continue
  814. }
  815. // config can also be "conditions_default".
  816. config := proptools.PropertyNameForField(propertyName)
  817. actualPropertyName := field.Type().Field(k).Name
  818. productConfigProperties.AddProductConfigProperty(
  819. actualPropertyName, // e.g. cflags, static_libs
  820. namespace, // e.g. acme, android
  821. productVariableName, // e.g. size, feature1, FEATURE2, board
  822. config,
  823. field.Field(k).Interface(), // e.g. ["-DDEFAULT"], ["foo", "bar"]
  824. )
  825. }
  826. } else if property.Kind() != reflect.Interface {
  827. // If not an interface, then this is not a conditions_default or
  828. // a struct prop. That is, this is a regular product variable,
  829. // or a bool/value config variable.
  830. config := productVariableName + suffix
  831. productConfigProperties.AddProductConfigProperty(
  832. propertyName,
  833. namespace,
  834. productVariableName,
  835. config,
  836. property.Interface(),
  837. )
  838. }
  839. }
  840. }
  841. }
  842. // productVariableValues uses reflection to convert a property struct for
  843. // product_variables and soong_config_variables to structs that can be generated
  844. // as select statements.
  845. func productVariableValues(
  846. fieldName string, variableProps interface{}, namespace, suffix string, productConfigProperties *ProductConfigProperties) {
  847. if suffix != "" {
  848. suffix = "-" + suffix
  849. }
  850. // variableValues represent the product_variables or soong_config_variables struct.
  851. variableValues := reflect.ValueOf(variableProps).Elem().FieldByName(fieldName)
  852. productConfigProperties.AddProductConfigProperties(namespace, suffix, variableValues)
  853. }
  854. func VariableMutator(mctx BottomUpMutatorContext) {
  855. var module Module
  856. var ok bool
  857. if module, ok = mctx.Module().(Module); !ok {
  858. return
  859. }
  860. // TODO: depend on config variable, create variants, propagate variants up tree
  861. a := module.base()
  862. if a.variableProperties == nil {
  863. return
  864. }
  865. variableValues := reflect.ValueOf(a.variableProperties).Elem().FieldByName("Product_variables")
  866. productVariables := reflect.ValueOf(mctx.Config().productVariables)
  867. for i := 0; i < variableValues.NumField(); i++ {
  868. variableValue := variableValues.Field(i)
  869. name := variableValues.Type().Field(i).Name
  870. property := "product_variables." + proptools.PropertyNameForField(name)
  871. // Check that the variable was set for the product
  872. val := productVariables.FieldByName(name)
  873. if !val.IsValid() || val.Kind() != reflect.Ptr || val.IsNil() {
  874. continue
  875. }
  876. val = val.Elem()
  877. // For bools, check that the value is true
  878. if val.Kind() == reflect.Bool && val.Bool() == false {
  879. continue
  880. }
  881. // Check if any properties were set for the module
  882. if variableValue.IsZero() {
  883. continue
  884. }
  885. a.setVariableProperties(mctx, property, variableValue, val.Interface())
  886. }
  887. }
  888. func (m *ModuleBase) setVariableProperties(ctx BottomUpMutatorContext,
  889. prefix string, productVariablePropertyValue reflect.Value, variableValue interface{}) {
  890. printfIntoProperties(ctx, prefix, productVariablePropertyValue, variableValue)
  891. err := proptools.AppendMatchingProperties(m.GetProperties(),
  892. productVariablePropertyValue.Addr().Interface(), nil)
  893. if err != nil {
  894. if propertyErr, ok := err.(*proptools.ExtendPropertyError); ok {
  895. ctx.PropertyErrorf(propertyErr.Property, "%s", propertyErr.Err.Error())
  896. } else {
  897. panic(err)
  898. }
  899. }
  900. }
  901. func printfIntoPropertiesError(ctx BottomUpMutatorContext, prefix string,
  902. productVariablePropertyValue reflect.Value, i int, err error) {
  903. field := productVariablePropertyValue.Type().Field(i).Name
  904. property := prefix + "." + proptools.PropertyNameForField(field)
  905. ctx.PropertyErrorf(property, "%s", err)
  906. }
  907. func printfIntoProperties(ctx BottomUpMutatorContext, prefix string,
  908. productVariablePropertyValue reflect.Value, variableValue interface{}) {
  909. for i := 0; i < productVariablePropertyValue.NumField(); i++ {
  910. propertyValue := productVariablePropertyValue.Field(i)
  911. kind := propertyValue.Kind()
  912. if kind == reflect.Ptr {
  913. if propertyValue.IsNil() {
  914. continue
  915. }
  916. propertyValue = propertyValue.Elem()
  917. }
  918. switch propertyValue.Kind() {
  919. case reflect.String:
  920. err := printfIntoProperty(propertyValue, variableValue)
  921. if err != nil {
  922. printfIntoPropertiesError(ctx, prefix, productVariablePropertyValue, i, err)
  923. }
  924. case reflect.Slice:
  925. for j := 0; j < propertyValue.Len(); j++ {
  926. err := printfIntoProperty(propertyValue.Index(j), variableValue)
  927. if err != nil {
  928. printfIntoPropertiesError(ctx, prefix, productVariablePropertyValue, i, err)
  929. }
  930. }
  931. case reflect.Bool:
  932. // Nothing
  933. case reflect.Struct:
  934. printfIntoProperties(ctx, prefix, propertyValue, variableValue)
  935. default:
  936. panic(fmt.Errorf("unsupported field kind %q", propertyValue.Kind()))
  937. }
  938. }
  939. }
  940. func printfIntoProperty(propertyValue reflect.Value, variableValue interface{}) error {
  941. s := propertyValue.String()
  942. count := strings.Count(s, "%")
  943. if count == 0 {
  944. return nil
  945. }
  946. if count > 1 {
  947. return fmt.Errorf("product variable properties only support a single '%%'")
  948. }
  949. if strings.Contains(s, "%d") {
  950. switch v := variableValue.(type) {
  951. case int:
  952. // Nothing
  953. case bool:
  954. if v {
  955. variableValue = 1
  956. } else {
  957. variableValue = 0
  958. }
  959. default:
  960. return fmt.Errorf("unsupported type %T for %%d", variableValue)
  961. }
  962. } else if strings.Contains(s, "%s") {
  963. switch variableValue.(type) {
  964. case string:
  965. // Nothing
  966. default:
  967. return fmt.Errorf("unsupported type %T for %%s", variableValue)
  968. }
  969. } else {
  970. return fmt.Errorf("unsupported %% in product variable property")
  971. }
  972. propertyValue.Set(reflect.ValueOf(fmt.Sprintf(s, variableValue)))
  973. return nil
  974. }
  975. var variablePropTypeMap OncePer
  976. // sliceToTypeArray takes a slice of property structs and returns a reflection created array containing the
  977. // reflect.Types of each property struct. The result can be used as a key in a map.
  978. func sliceToTypeArray(s []interface{}) interface{} {
  979. // Create an array using reflection whose length is the length of the input slice
  980. ret := reflect.New(reflect.ArrayOf(len(s), reflect.TypeOf(reflect.TypeOf(0)))).Elem()
  981. for i, e := range s {
  982. ret.Index(i).Set(reflect.ValueOf(reflect.TypeOf(e)))
  983. }
  984. return ret.Interface()
  985. }
  986. func initProductVariableModule(m Module) {
  987. base := m.base()
  988. // Allow tests to override the default product variables
  989. if base.variableProperties == nil {
  990. base.variableProperties = defaultProductVariables
  991. }
  992. // Filter the product variables properties to the ones that exist on this module
  993. base.variableProperties = createVariableProperties(m.GetProperties(), base.variableProperties)
  994. if base.variableProperties != nil {
  995. m.AddProperties(base.variableProperties)
  996. }
  997. }
  998. // createVariableProperties takes the list of property structs for a module and returns a property struct that
  999. // contains the product variable properties that exist in the property structs, or nil if there are none. It
  1000. // caches the result.
  1001. func createVariableProperties(moduleTypeProps []interface{}, productVariables interface{}) interface{} {
  1002. // Convert the moduleTypeProps to an array of reflect.Types that can be used as a key in the OncePer.
  1003. key := sliceToTypeArray(moduleTypeProps)
  1004. // Use the variablePropTypeMap OncePer to cache the result for each set of property struct types.
  1005. typ, _ := variablePropTypeMap.Once(NewCustomOnceKey(key), func() interface{} {
  1006. // Compute the filtered property struct type.
  1007. return createVariablePropertiesType(moduleTypeProps, productVariables)
  1008. }).(reflect.Type)
  1009. if typ == nil {
  1010. return nil
  1011. }
  1012. // Create a new pointer to a filtered property struct.
  1013. return reflect.New(typ).Interface()
  1014. }
  1015. // createVariablePropertiesType creates a new type that contains only the product variable properties that exist in
  1016. // a list of property structs.
  1017. func createVariablePropertiesType(moduleTypeProps []interface{}, productVariables interface{}) reflect.Type {
  1018. typ, _ := proptools.FilterPropertyStruct(reflect.TypeOf(productVariables),
  1019. func(field reflect.StructField, prefix string) (bool, reflect.StructField) {
  1020. // Filter function, returns true if the field should be in the resulting struct
  1021. if prefix == "" {
  1022. // Keep the top level Product_variables field
  1023. return true, field
  1024. }
  1025. _, rest := splitPrefix(prefix)
  1026. if rest == "" {
  1027. // Keep the 2nd level field (i.e. Product_variables.Eng)
  1028. return true, field
  1029. }
  1030. // Strip off the first 2 levels of the prefix
  1031. _, prefix = splitPrefix(rest)
  1032. for _, p := range moduleTypeProps {
  1033. if fieldExistsByNameRecursive(reflect.TypeOf(p).Elem(), prefix, field.Name) {
  1034. // Keep any fields that exist in one of the property structs
  1035. return true, field
  1036. }
  1037. }
  1038. return false, field
  1039. })
  1040. return typ
  1041. }
  1042. func splitPrefix(prefix string) (first, rest string) {
  1043. index := strings.IndexByte(prefix, '.')
  1044. if index == -1 {
  1045. return prefix, ""
  1046. }
  1047. return prefix[:index], prefix[index+1:]
  1048. }
  1049. func fieldExistsByNameRecursive(t reflect.Type, prefix, name string) bool {
  1050. if t.Kind() != reflect.Struct {
  1051. panic(fmt.Errorf("fieldExistsByNameRecursive can only be called on a reflect.Struct"))
  1052. }
  1053. if prefix != "" {
  1054. split := strings.SplitN(prefix, ".", 2)
  1055. firstPrefix := split[0]
  1056. rest := ""
  1057. if len(split) > 1 {
  1058. rest = split[1]
  1059. }
  1060. f, exists := t.FieldByName(firstPrefix)
  1061. if !exists {
  1062. return false
  1063. }
  1064. ft := f.Type
  1065. if ft.Kind() == reflect.Ptr {
  1066. ft = ft.Elem()
  1067. }
  1068. if ft.Kind() != reflect.Struct {
  1069. panic(fmt.Errorf("field %q in %q is not a struct", firstPrefix, t))
  1070. }
  1071. return fieldExistsByNameRecursive(ft, rest, name)
  1072. } else {
  1073. _, exists := t.FieldByName(name)
  1074. return exists
  1075. }
  1076. }